diff --git a/node_modules/@jridgewell/sourcemap-codec/types/strings.d.mts b/node_modules/@jridgewell/sourcemap-codec/types/strings.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..62faceb3de9c90532158206c1ab55ee35ac24a89 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/strings.d.mts @@ -0,0 +1,16 @@ +export declare class StringWriter { + pos: number; + private out; + private buffer; + write(v: number): void; + flush(): string; +} +export declare class StringReader { + pos: number; + private buffer; + constructor(buffer: string); + next(): number; + peek(): number; + indexOf(char: string): number; +} +//# sourceMappingURL=strings.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/strings.d.mts.map b/node_modules/@jridgewell/sourcemap-codec/types/strings.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..d3602da4257449b6145da1bcaf14314073d6f31a --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/strings.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"strings.d.ts","sourceRoot":"","sources":["../src/strings.ts"],"names":[],"mappings":"AAuBA,qBAAa,YAAY;IACvB,GAAG,SAAK;IACR,OAAO,CAAC,GAAG,CAAM;IACjB,OAAO,CAAC,MAAM,CAA6B;IAE3C,KAAK,CAAC,CAAC,EAAE,MAAM,GAAG,IAAI;IAStB,KAAK,IAAI,MAAM;CAIhB;AAED,qBAAa,YAAY;IACvB,GAAG,SAAK;IACR,QAAgB,MAAM,CAAS;gBAEnB,MAAM,EAAE,MAAM;IAI1B,IAAI,IAAI,MAAM;IAId,IAAI,IAAI,MAAM;IAId,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;CAK9B"} \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.cts b/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..dbd6602d1876df8089ce52b3309b340d1a088555 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.cts @@ -0,0 +1,7 @@ +import type { StringReader, StringWriter } from './strings.cts'; +export declare const comma: number; +export declare const semicolon: number; +export declare function decodeInteger(reader: StringReader, relative: number): number; +export declare function encodeInteger(builder: StringWriter, num: number, relative: number): number; +export declare function hasMoreVlq(reader: StringReader, max: number): boolean; +//# sourceMappingURL=vlq.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.cts.map b/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.cts.map new file mode 100644 index 0000000000000000000000000000000000000000..6fdc356977cc89df14692e21863ed6724b63a0fc --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"vlq.d.ts","sourceRoot":"","sources":["../src/vlq.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAE5D,eAAO,MAAM,KAAK,QAAoB,CAAC;AACvC,eAAO,MAAM,SAAS,QAAoB,CAAC;AAY3C,wBAAgB,aAAa,CAAC,MAAM,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAoB5E;AAED,wBAAgB,aAAa,CAAC,OAAO,EAAE,YAAY,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAY1F;AAED,wBAAgB,UAAU,CAAC,MAAM,EAAE,YAAY,EAAE,GAAG,EAAE,MAAM,WAG3D"} \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.mts b/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..2c739bc9fedb038a659a85726a98af7c5f32c5da --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.mts @@ -0,0 +1,7 @@ +import type { StringReader, StringWriter } from './strings.mts'; +export declare const comma: number; +export declare const semicolon: number; +export declare function decodeInteger(reader: StringReader, relative: number): number; +export declare function encodeInteger(builder: StringWriter, num: number, relative: number): number; +export declare function hasMoreVlq(reader: StringReader, max: number): boolean; +//# sourceMappingURL=vlq.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.mts.map b/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..6fdc356977cc89df14692e21863ed6724b63a0fc --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"vlq.d.ts","sourceRoot":"","sources":["../src/vlq.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAE5D,eAAO,MAAM,KAAK,QAAoB,CAAC;AACvC,eAAO,MAAM,SAAS,QAAoB,CAAC;AAY3C,wBAAgB,aAAa,CAAC,MAAM,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAoB5E;AAED,wBAAgB,aAAa,CAAC,OAAO,EAAE,YAAY,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAY1F;AAED,wBAAgB,UAAU,CAAC,MAAM,EAAE,YAAY,EAAE,GAAG,EAAE,MAAM,WAG3D"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/LICENSE b/node_modules/@jridgewell/trace-mapping/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1f6ce94c11912496b96298630d84753dbf593a7d --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/LICENSE @@ -0,0 +1,19 @@ +Copyright 2024 Justin Ridgewell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@jridgewell/trace-mapping/README.md b/node_modules/@jridgewell/trace-mapping/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9fc0ed09cedeb0eea388b5d2b891b87886830776 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/README.md @@ -0,0 +1,348 @@ +# @jridgewell/trace-mapping + +> Trace the original position through a source map + +`trace-mapping` allows you to take the line and column of an output file and trace it to the +original location in the source file through a source map. + +You may already be familiar with the [`source-map`][source-map] package's `SourceMapConsumer`. This +provides the same `originalPositionFor` and `generatedPositionFor` API, without requiring WASM. + +## Installation + +```sh +npm install @jridgewell/trace-mapping +``` + +## Usage + +```typescript +import { + TraceMap, + originalPositionFor, + generatedPositionFor, + sourceContentFor, + isIgnored, +} from '@jridgewell/trace-mapping'; + +const tracer = new TraceMap({ + version: 3, + sources: ['input.js'], + sourcesContent: ['content of input.js'], + names: ['foo'], + mappings: 'KAyCIA', + ignoreList: [], +}); + +// Lines start at line 1, columns at column 0. +const traced = originalPositionFor(tracer, { line: 1, column: 5 }); +assert.deepEqual(traced, { + source: 'input.js', + line: 42, + column: 4, + name: 'foo', +}); + +const content = sourceContentFor(tracer, traced.source); +assert.strictEqual(content, 'content for input.js'); + +const generated = generatedPositionFor(tracer, { + source: 'input.js', + line: 42, + column: 4, +}); +assert.deepEqual(generated, { + line: 1, + column: 5, +}); + +const ignored = isIgnored(tracer, 'input.js'); +assert.equal(ignored, false); +``` + +We also provide a lower level API to get the actual segment that matches our line and column. Unlike +`originalPositionFor`, `traceSegment` uses a 0-base for `line`: + +```typescript +import { traceSegment } from '@jridgewell/trace-mapping'; + +// line is 0-base. +const traced = traceSegment(tracer, /* line */ 0, /* column */ 5); + +// Segments are [outputColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex] +// Again, line is 0-base and so is sourceLine +assert.deepEqual(traced, [5, 0, 41, 4, 0]); +``` + +### SectionedSourceMaps + +The sourcemap spec defines a special `sections` field that's designed to handle concatenation of +output code with associated sourcemaps. This type of sourcemap is rarely used (no major build tool +produces it), but if you are hand coding a concatenation you may need it. We provide an `AnyMap` +helper that can receive either a regular sourcemap or a `SectionedSourceMap` and returns a +`TraceMap` instance: + +```typescript +import { AnyMap } from '@jridgewell/trace-mapping'; +const fooOutput = 'foo'; +const barOutput = 'bar'; +const output = [fooOutput, barOutput].join('\n'); + +const sectioned = new AnyMap({ + version: 3, + sections: [ + { + // 0-base line and column + offset: { line: 0, column: 0 }, + // fooOutput's sourcemap + map: { + version: 3, + sources: ['foo.js'], + names: ['foo'], + mappings: 'AAAAA', + }, + }, + { + // barOutput's sourcemap will not affect the first line, only the second + offset: { line: 1, column: 0 }, + map: { + version: 3, + sources: ['bar.js'], + names: ['bar'], + mappings: 'AAAAA', + }, + }, + ], +}); + +const traced = originalPositionFor(sectioned, { + line: 2, + column: 0, +}); + +assert.deepEqual(traced, { + source: 'bar.js', + line: 1, + column: 0, + name: 'bar', +}); +``` + +## Benchmarks + +``` +node v20.10.0 + +amp.js.map - 45120 segments + +Memory Usage: +trace-mapping decoded 414164 bytes +trace-mapping encoded 6274352 bytes +source-map-js 10968904 bytes +source-map-0.6.1 17587160 bytes +source-map-0.8.0 8812155 bytes +Chrome dev tools 8672912 bytes +Smallest memory usage is trace-mapping decoded + +Init speed: +trace-mapping: decoded JSON input x 205 ops/sec ±0.19% (88 runs sampled) +trace-mapping: encoded JSON input x 405 ops/sec ±1.47% (88 runs sampled) +trace-mapping: decoded Object input x 4,645 ops/sec ±0.15% (98 runs sampled) +trace-mapping: encoded Object input x 458 ops/sec ±1.63% (91 runs sampled) +source-map-js: encoded Object input x 75.48 ops/sec ±1.64% (67 runs sampled) +source-map-0.6.1: encoded Object input x 39.37 ops/sec ±1.44% (53 runs sampled) +Chrome dev tools: encoded Object input x 150 ops/sec ±1.76% (79 runs sampled) +Fastest is trace-mapping: decoded Object input + +Trace speed (random): +trace-mapping: decoded originalPositionFor x 44,946 ops/sec ±0.16% (99 runs sampled) +trace-mapping: encoded originalPositionFor x 37,995 ops/sec ±1.81% (89 runs sampled) +source-map-js: encoded originalPositionFor x 9,230 ops/sec ±1.36% (93 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 8,057 ops/sec ±0.84% (96 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 28,198 ops/sec ±1.12% (91 runs sampled) +Chrome dev tools: encoded originalPositionFor x 46,276 ops/sec ±1.35% (95 runs sampled) +Fastest is Chrome dev tools: encoded originalPositionFor + +Trace speed (ascending): +trace-mapping: decoded originalPositionFor x 204,406 ops/sec ±0.19% (97 runs sampled) +trace-mapping: encoded originalPositionFor x 196,695 ops/sec ±0.24% (99 runs sampled) +source-map-js: encoded originalPositionFor x 11,948 ops/sec ±0.94% (99 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 10,730 ops/sec ±0.36% (100 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 51,427 ops/sec ±0.21% (98 runs sampled) +Chrome dev tools: encoded originalPositionFor x 162,615 ops/sec ±0.18% (98 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor + + +*** + + +babel.min.js.map - 347793 segments + +Memory Usage: +trace-mapping decoded 18504 bytes +trace-mapping encoded 35428008 bytes +source-map-js 51676808 bytes +source-map-0.6.1 63367136 bytes +source-map-0.8.0 43158400 bytes +Chrome dev tools 50721552 bytes +Smallest memory usage is trace-mapping decoded + +Init speed: +trace-mapping: decoded JSON input x 17.82 ops/sec ±6.35% (35 runs sampled) +trace-mapping: encoded JSON input x 31.57 ops/sec ±7.50% (43 runs sampled) +trace-mapping: decoded Object input x 867 ops/sec ±0.74% (94 runs sampled) +trace-mapping: encoded Object input x 33.83 ops/sec ±7.66% (46 runs sampled) +source-map-js: encoded Object input x 6.58 ops/sec ±3.31% (20 runs sampled) +source-map-0.6.1: encoded Object input x 4.23 ops/sec ±3.43% (15 runs sampled) +Chrome dev tools: encoded Object input x 22.14 ops/sec ±3.79% (41 runs sampled) +Fastest is trace-mapping: decoded Object input + +Trace speed (random): +trace-mapping: decoded originalPositionFor x 78,234 ops/sec ±1.48% (29 runs sampled) +trace-mapping: encoded originalPositionFor x 60,761 ops/sec ±1.35% (21 runs sampled) +source-map-js: encoded originalPositionFor x 51,448 ops/sec ±2.17% (89 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 47,221 ops/sec ±1.99% (15 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 84,002 ops/sec ±1.45% (27 runs sampled) +Chrome dev tools: encoded originalPositionFor x 106,457 ops/sec ±1.38% (37 runs sampled) +Fastest is Chrome dev tools: encoded originalPositionFor + +Trace speed (ascending): +trace-mapping: decoded originalPositionFor x 930,943 ops/sec ±0.25% (99 runs sampled) +trace-mapping: encoded originalPositionFor x 843,545 ops/sec ±0.34% (97 runs sampled) +source-map-js: encoded originalPositionFor x 114,510 ops/sec ±1.37% (36 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 87,412 ops/sec ±0.72% (92 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 197,709 ops/sec ±0.89% (59 runs sampled) +Chrome dev tools: encoded originalPositionFor x 688,983 ops/sec ±0.33% (98 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor + + +*** + + +preact.js.map - 1992 segments + +Memory Usage: +trace-mapping decoded 33136 bytes +trace-mapping encoded 254240 bytes +source-map-js 837488 bytes +source-map-0.6.1 961928 bytes +source-map-0.8.0 54384 bytes +Chrome dev tools 709680 bytes +Smallest memory usage is trace-mapping decoded + +Init speed: +trace-mapping: decoded JSON input x 3,709 ops/sec ±0.13% (99 runs sampled) +trace-mapping: encoded JSON input x 6,447 ops/sec ±0.22% (101 runs sampled) +trace-mapping: decoded Object input x 83,062 ops/sec ±0.23% (100 runs sampled) +trace-mapping: encoded Object input x 14,980 ops/sec ±0.28% (100 runs sampled) +source-map-js: encoded Object input x 2,544 ops/sec ±0.16% (99 runs sampled) +source-map-0.6.1: encoded Object input x 1,221 ops/sec ±0.37% (97 runs sampled) +Chrome dev tools: encoded Object input x 4,241 ops/sec ±0.39% (93 runs sampled) +Fastest is trace-mapping: decoded Object input + +Trace speed (random): +trace-mapping: decoded originalPositionFor x 91,028 ops/sec ±0.14% (94 runs sampled) +trace-mapping: encoded originalPositionFor x 84,348 ops/sec ±0.26% (98 runs sampled) +source-map-js: encoded originalPositionFor x 26,998 ops/sec ±0.23% (98 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 18,049 ops/sec ±0.26% (100 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 41,916 ops/sec ±0.28% (98 runs sampled) +Chrome dev tools: encoded originalPositionFor x 88,616 ops/sec ±0.14% (98 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor + +Trace speed (ascending): +trace-mapping: decoded originalPositionFor x 319,960 ops/sec ±0.16% (100 runs sampled) +trace-mapping: encoded originalPositionFor x 302,153 ops/sec ±0.18% (100 runs sampled) +source-map-js: encoded originalPositionFor x 35,574 ops/sec ±0.19% (100 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 19,943 ops/sec ±0.12% (101 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 54,648 ops/sec ±0.20% (99 runs sampled) +Chrome dev tools: encoded originalPositionFor x 278,319 ops/sec ±0.17% (102 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor + + +*** + + +react.js.map - 5726 segments + +Memory Usage: +trace-mapping decoded 10872 bytes +trace-mapping encoded 681512 bytes +source-map-js 2563944 bytes +source-map-0.6.1 2150864 bytes +source-map-0.8.0 88680 bytes +Chrome dev tools 1149576 bytes +Smallest memory usage is trace-mapping decoded + +Init speed: +trace-mapping: decoded JSON input x 1,887 ops/sec ±0.28% (99 runs sampled) +trace-mapping: encoded JSON input x 4,749 ops/sec ±0.48% (97 runs sampled) +trace-mapping: decoded Object input x 74,236 ops/sec ±0.11% (99 runs sampled) +trace-mapping: encoded Object input x 5,752 ops/sec ±0.38% (100 runs sampled) +source-map-js: encoded Object input x 806 ops/sec ±0.19% (97 runs sampled) +source-map-0.6.1: encoded Object input x 418 ops/sec ±0.33% (94 runs sampled) +Chrome dev tools: encoded Object input x 1,524 ops/sec ±0.57% (92 runs sampled) +Fastest is trace-mapping: decoded Object input + +Trace speed (random): +trace-mapping: decoded originalPositionFor x 620,201 ops/sec ±0.33% (96 runs sampled) +trace-mapping: encoded originalPositionFor x 579,548 ops/sec ±0.35% (97 runs sampled) +source-map-js: encoded originalPositionFor x 230,983 ops/sec ±0.62% (54 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 158,145 ops/sec ±0.80% (46 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 343,801 ops/sec ±0.55% (96 runs sampled) +Chrome dev tools: encoded originalPositionFor x 659,649 ops/sec ±0.49% (98 runs sampled) +Fastest is Chrome dev tools: encoded originalPositionFor + +Trace speed (ascending): +trace-mapping: decoded originalPositionFor x 2,368,079 ops/sec ±0.32% (98 runs sampled) +trace-mapping: encoded originalPositionFor x 2,134,039 ops/sec ±2.72% (87 runs sampled) +source-map-js: encoded originalPositionFor x 290,120 ops/sec ±2.49% (82 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 187,613 ops/sec ±0.86% (49 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 479,569 ops/sec ±0.65% (96 runs sampled) +Chrome dev tools: encoded originalPositionFor x 2,048,414 ops/sec ±0.24% (98 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor + + +*** + + +vscode.map - 2141001 segments + +Memory Usage: +trace-mapping decoded 5206584 bytes +trace-mapping encoded 208370336 bytes +source-map-js 278493008 bytes +source-map-0.6.1 391564048 bytes +source-map-0.8.0 257508787 bytes +Chrome dev tools 291053000 bytes +Smallest memory usage is trace-mapping decoded + +Init speed: +trace-mapping: decoded JSON input x 1.63 ops/sec ±33.88% (9 runs sampled) +trace-mapping: encoded JSON input x 3.29 ops/sec ±36.13% (13 runs sampled) +trace-mapping: decoded Object input x 103 ops/sec ±0.93% (77 runs sampled) +trace-mapping: encoded Object input x 5.42 ops/sec ±28.54% (19 runs sampled) +source-map-js: encoded Object input x 1.07 ops/sec ±13.84% (7 runs sampled) +source-map-0.6.1: encoded Object input x 0.60 ops/sec ±2.43% (6 runs sampled) +Chrome dev tools: encoded Object input x 2.61 ops/sec ±22.00% (11 runs sampled) +Fastest is trace-mapping: decoded Object input + +Trace speed (random): +trace-mapping: decoded originalPositionFor x 257,019 ops/sec ±0.97% (93 runs sampled) +trace-mapping: encoded originalPositionFor x 179,163 ops/sec ±0.83% (92 runs sampled) +source-map-js: encoded originalPositionFor x 73,337 ops/sec ±1.35% (87 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 38,797 ops/sec ±1.66% (88 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 107,758 ops/sec ±1.94% (45 runs sampled) +Chrome dev tools: encoded originalPositionFor x 188,550 ops/sec ±1.85% (79 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor + +Trace speed (ascending): +trace-mapping: decoded originalPositionFor x 447,621 ops/sec ±3.64% (94 runs sampled) +trace-mapping: encoded originalPositionFor x 323,698 ops/sec ±5.20% (88 runs sampled) +source-map-js: encoded originalPositionFor x 78,387 ops/sec ±1.69% (89 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 41,016 ops/sec ±3.01% (25 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 124,204 ops/sec ±0.90% (92 runs sampled) +Chrome dev tools: encoded originalPositionFor x 230,087 ops/sec ±2.61% (93 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor +``` + +[source-map]: https://www.npmjs.com/package/source-map diff --git a/node_modules/@jridgewell/trace-mapping/package.json b/node_modules/@jridgewell/trace-mapping/package.json new file mode 100644 index 0000000000000000000000000000000000000000..9d3a1c08e5d4c0316371ed16f966c353ab34e790 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/package.json @@ -0,0 +1,67 @@ +{ + "name": "@jridgewell/trace-mapping", + "version": "0.3.31", + "description": "Trace the original position through a source map", + "keywords": [ + "source", + "map" + ], + "main": "dist/trace-mapping.umd.js", + "module": "dist/trace-mapping.mjs", + "types": "types/trace-mapping.d.cts", + "files": [ + "dist", + "src", + "types" + ], + "exports": { + ".": [ + { + "import": { + "types": "./types/trace-mapping.d.mts", + "default": "./dist/trace-mapping.mjs" + }, + "default": { + "types": "./types/trace-mapping.d.cts", + "default": "./dist/trace-mapping.umd.js" + } + }, + "./dist/trace-mapping.umd.js" + ], + "./package.json": "./package.json" + }, + "scripts": { + "benchmark": "run-s build:code benchmark:*", + "benchmark:install": "cd benchmark && npm install", + "benchmark:only": "node --expose-gc benchmark/index.mjs", + "build": "run-s -n build:code build:types", + "build:code": "node ../../esbuild.mjs trace-mapping.ts", + "build:types": "run-s build:types:force build:types:emit build:types:mts", + "build:types:force": "rimraf tsconfig.build.tsbuildinfo", + "build:types:emit": "tsc --project tsconfig.build.json", + "build:types:mts": "node ../../mts-types.mjs", + "clean": "run-s -n clean:code clean:types", + "clean:code": "tsc --build --clean tsconfig.build.json", + "clean:types": "rimraf dist types", + "test": "run-s -n test:types test:only test:format", + "test:format": "prettier --check '{src,test}/**/*.ts'", + "test:only": "mocha", + "test:types": "eslint '{src,test}/**/*.ts'", + "lint": "run-s -n lint:types lint:format", + "lint:format": "npm run test:format -- --write", + "lint:types": "npm run test:types -- --fix", + "prepublishOnly": "npm run-s -n build test" + }, + "homepage": "https://github.com/jridgewell/sourcemaps/tree/main/packages/trace-mapping", + "repository": { + "type": "git", + "url": "git+https://github.com/jridgewell/sourcemaps.git", + "directory": "packages/trace-mapping" + }, + "author": "Justin Ridgewell ", + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } +} diff --git a/node_modules/@jridgewell/trace-mapping/src/binary-search.ts b/node_modules/@jridgewell/trace-mapping/src/binary-search.ts new file mode 100644 index 0000000000000000000000000000000000000000..c1144ad1cdcdf6dcdfbfe3fed3f4daeeb2b1bd8d --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/src/binary-search.ts @@ -0,0 +1,115 @@ +import type { SourceMapSegment, ReverseSegment } from './sourcemap-segment'; +import { COLUMN } from './sourcemap-segment'; + +export type MemoState = { + lastKey: number; + lastNeedle: number; + lastIndex: number; +}; + +export let found = false; + +/** + * A binary search implementation that returns the index if a match is found. + * If no match is found, then the left-index (the index associated with the item that comes just + * before the desired index) is returned. To maintain proper sort order, a splice would happen at + * the next index: + * + * ```js + * const array = [1, 3]; + * const needle = 2; + * const index = binarySearch(array, needle, (item, needle) => item - needle); + * + * assert.equal(index, 0); + * array.splice(index + 1, 0, needle); + * assert.deepEqual(array, [1, 2, 3]); + * ``` + */ +export function binarySearch( + haystack: SourceMapSegment[] | ReverseSegment[], + needle: number, + low: number, + high: number, +): number { + while (low <= high) { + const mid = low + ((high - low) >> 1); + const cmp = haystack[mid][COLUMN] - needle; + + if (cmp === 0) { + found = true; + return mid; + } + + if (cmp < 0) { + low = mid + 1; + } else { + high = mid - 1; + } + } + + found = false; + return low - 1; +} + +export function upperBound( + haystack: SourceMapSegment[] | ReverseSegment[], + needle: number, + index: number, +): number { + for (let i = index + 1; i < haystack.length; index = i++) { + if (haystack[i][COLUMN] !== needle) break; + } + return index; +} + +export function lowerBound( + haystack: SourceMapSegment[] | ReverseSegment[], + needle: number, + index: number, +): number { + for (let i = index - 1; i >= 0; index = i--) { + if (haystack[i][COLUMN] !== needle) break; + } + return index; +} + +export function memoizedState(): MemoState { + return { + lastKey: -1, + lastNeedle: -1, + lastIndex: -1, + }; +} + +/** + * This overly complicated beast is just to record the last tested line/column and the resulting + * index, allowing us to skip a few tests if mappings are monotonically increasing. + */ +export function memoizedBinarySearch( + haystack: SourceMapSegment[] | ReverseSegment[], + needle: number, + state: MemoState, + key: number, +): number { + const { lastKey, lastNeedle, lastIndex } = state; + + let low = 0; + let high = haystack.length - 1; + if (key === lastKey) { + if (needle === lastNeedle) { + found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle; + return lastIndex; + } + + if (needle >= lastNeedle) { + // lastIndex may be -1 if the previous needle was not found. + low = lastIndex === -1 ? 0 : lastIndex; + } else { + high = lastIndex; + } + } + state.lastKey = key; + state.lastNeedle = needle; + + return (state.lastIndex = binarySearch(haystack, needle, low, high)); +} diff --git a/node_modules/@jridgewell/trace-mapping/src/by-source.ts b/node_modules/@jridgewell/trace-mapping/src/by-source.ts new file mode 100644 index 0000000000000000000000000000000000000000..1da6af05cae200e2c4df1322a08910d0c5082e37 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/src/by-source.ts @@ -0,0 +1,41 @@ +import { COLUMN, SOURCES_INDEX, SOURCE_LINE, SOURCE_COLUMN } from './sourcemap-segment'; +import { sortComparator } from './sort'; + +import type { ReverseSegment, SourceMapSegment } from './sourcemap-segment'; + +export type Source = ReverseSegment[][]; + +// Rebuilds the original source files, with mappings that are ordered by source line/column instead +// of generated line/column. +export default function buildBySources( + decoded: readonly SourceMapSegment[][], + memos: unknown[], +): Source[] { + const sources: Source[] = memos.map(() => []); + + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + if (seg.length === 1) continue; + + const sourceIndex = seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + + const source = sources[sourceIndex]; + const segs = (source[sourceLine] ||= []); + segs.push([sourceColumn, i, seg[COLUMN]]); + } + } + + for (let i = 0; i < sources.length; i++) { + const source = sources[i]; + for (let j = 0; j < source.length; j++) { + const line = source[j]; + if (line) line.sort(sortComparator); + } + } + + return sources; +} diff --git a/node_modules/@jridgewell/trace-mapping/src/flatten-map.ts b/node_modules/@jridgewell/trace-mapping/src/flatten-map.ts new file mode 100644 index 0000000000000000000000000000000000000000..61ac40caabeb70e1759bf67e0582d01240120713 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/src/flatten-map.ts @@ -0,0 +1,192 @@ +import { TraceMap, presortedDecodedMap, decodedMappings } from './trace-mapping'; +import { + COLUMN, + SOURCES_INDEX, + SOURCE_LINE, + SOURCE_COLUMN, + NAMES_INDEX, +} from './sourcemap-segment'; +import { parse } from './types'; + +import type { + DecodedSourceMap, + DecodedSourceMapXInput, + EncodedSourceMapXInput, + SectionedSourceMapXInput, + SectionedSourceMapInput, + SectionXInput, + Ro, +} from './types'; +import type { SourceMapSegment } from './sourcemap-segment'; + +type FlattenMap = { + new (map: Ro, mapUrl?: string | null): TraceMap; + (map: Ro, mapUrl?: string | null): TraceMap; +}; + +export const FlattenMap: FlattenMap = function (map, mapUrl) { + const parsed = parse(map as SectionedSourceMapInput); + + if (!('sections' in parsed)) { + return new TraceMap(parsed as DecodedSourceMapXInput | EncodedSourceMapXInput, mapUrl); + } + + const mappings: SourceMapSegment[][] = []; + const sources: string[] = []; + const sourcesContent: (string | null)[] = []; + const names: string[] = []; + const ignoreList: number[] = []; + + recurse( + parsed, + mapUrl, + mappings, + sources, + sourcesContent, + names, + ignoreList, + 0, + 0, + Infinity, + Infinity, + ); + + const joined: DecodedSourceMap = { + version: 3, + file: parsed.file, + names, + sources, + sourcesContent, + mappings, + ignoreList, + }; + + return presortedDecodedMap(joined); +} as FlattenMap; + +function recurse( + input: SectionedSourceMapXInput, + mapUrl: string | null | undefined, + mappings: SourceMapSegment[][], + sources: string[], + sourcesContent: (string | null)[], + names: string[], + ignoreList: number[], + lineOffset: number, + columnOffset: number, + stopLine: number, + stopColumn: number, +) { + const { sections } = input; + for (let i = 0; i < sections.length; i++) { + const { map, offset } = sections[i]; + + let sl = stopLine; + let sc = stopColumn; + if (i + 1 < sections.length) { + const nextOffset = sections[i + 1].offset; + sl = Math.min(stopLine, lineOffset + nextOffset.line); + + if (sl === stopLine) { + sc = Math.min(stopColumn, columnOffset + nextOffset.column); + } else if (sl < stopLine) { + sc = columnOffset + nextOffset.column; + } + } + + addSection( + map, + mapUrl, + mappings, + sources, + sourcesContent, + names, + ignoreList, + lineOffset + offset.line, + columnOffset + offset.column, + sl, + sc, + ); + } +} + +function addSection( + input: SectionXInput['map'], + mapUrl: string | null | undefined, + mappings: SourceMapSegment[][], + sources: string[], + sourcesContent: (string | null)[], + names: string[], + ignoreList: number[], + lineOffset: number, + columnOffset: number, + stopLine: number, + stopColumn: number, +) { + const parsed = parse(input); + if ('sections' in parsed) return recurse(...(arguments as unknown as Parameters)); + + const map = new TraceMap(parsed, mapUrl); + const sourcesOffset = sources.length; + const namesOffset = names.length; + const decoded = decodedMappings(map); + const { resolvedSources, sourcesContent: contents, ignoreList: ignores } = map; + + append(sources, resolvedSources); + append(names, map.names); + + if (contents) append(sourcesContent, contents); + else for (let i = 0; i < resolvedSources.length; i++) sourcesContent.push(null); + + if (ignores) for (let i = 0; i < ignores.length; i++) ignoreList.push(ignores[i] + sourcesOffset); + + for (let i = 0; i < decoded.length; i++) { + const lineI = lineOffset + i; + + // We can only add so many lines before we step into the range that the next section's map + // controls. When we get to the last line, then we'll start checking the segments to see if + // they've crossed into the column range. But it may not have any columns that overstep, so we + // still need to check that we don't overstep lines, too. + if (lineI > stopLine) return; + + // The out line may already exist in mappings (if we're continuing the line started by a + // previous section). Or, we may have jumped ahead several lines to start this section. + const out = getLine(mappings, lineI); + // On the 0th loop, the section's column offset shifts us forward. On all other lines (since the + // map can be multiple lines), it doesn't. + const cOffset = i === 0 ? columnOffset : 0; + + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const column = cOffset + seg[COLUMN]; + + // If this segment steps into the column range that the next section's map controls, we need + // to stop early. + if (lineI === stopLine && column >= stopColumn) return; + + if (seg.length === 1) { + out.push([column]); + continue; + } + + const sourcesIndex = sourcesOffset + seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + out.push( + seg.length === 4 + ? [column, sourcesIndex, sourceLine, sourceColumn] + : [column, sourcesIndex, sourceLine, sourceColumn, namesOffset + seg[NAMES_INDEX]], + ); + } + } +} + +function append(arr: T[], other: T[]) { + for (let i = 0; i < other.length; i++) arr.push(other[i]); +} + +function getLine(arr: T[][], index: number): T[] { + for (let i = arr.length; i <= index; i++) arr[i] = []; + return arr[index]; +} diff --git a/node_modules/@jridgewell/trace-mapping/src/resolve.ts b/node_modules/@jridgewell/trace-mapping/src/resolve.ts new file mode 100644 index 0000000000000000000000000000000000000000..30bfa3b226f8990dc650a372d0fa8300b9521a56 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/src/resolve.ts @@ -0,0 +1,16 @@ +import resolveUri from '@jridgewell/resolve-uri'; +import stripFilename from './strip-filename'; + +type Resolve = (source: string | null) => string; +export default function resolver( + mapUrl: string | null | undefined, + sourceRoot: string | undefined, +): Resolve { + const from = stripFilename(mapUrl); + // The sourceRoot is always treated as a directory, if it's not empty. + // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327 + // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401 + const prefix = sourceRoot ? sourceRoot + '/' : ''; + + return (source) => resolveUri(prefix + (source || ''), from); +} diff --git a/node_modules/@jridgewell/trace-mapping/src/sort.ts b/node_modules/@jridgewell/trace-mapping/src/sort.ts new file mode 100644 index 0000000000000000000000000000000000000000..5d016cb78cfca482b736ec06d25f334d2ab849ff --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/src/sort.ts @@ -0,0 +1,45 @@ +import { COLUMN } from './sourcemap-segment'; + +import type { ReverseSegment, SourceMapSegment } from './sourcemap-segment'; + +export default function maybeSort( + mappings: SourceMapSegment[][], + owned: boolean, +): SourceMapSegment[][] { + const unsortedIndex = nextUnsortedSegmentLine(mappings, 0); + if (unsortedIndex === mappings.length) return mappings; + + // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If + // not, we do not want to modify the consumer's input array. + if (!owned) mappings = mappings.slice(); + + for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) { + mappings[i] = sortSegments(mappings[i], owned); + } + return mappings; +} + +function nextUnsortedSegmentLine(mappings: SourceMapSegment[][], start: number): number { + for (let i = start; i < mappings.length; i++) { + if (!isSorted(mappings[i])) return i; + } + return mappings.length; +} + +function isSorted(line: SourceMapSegment[]): boolean { + for (let j = 1; j < line.length; j++) { + if (line[j][COLUMN] < line[j - 1][COLUMN]) { + return false; + } + } + return true; +} + +function sortSegments(line: SourceMapSegment[], owned: boolean): SourceMapSegment[] { + if (!owned) line = line.slice(); + return line.sort(sortComparator); +} + +export function sortComparator(a: T, b: T): number { + return a[COLUMN] - b[COLUMN]; +} diff --git a/node_modules/@jridgewell/trace-mapping/src/sourcemap-segment.ts b/node_modules/@jridgewell/trace-mapping/src/sourcemap-segment.ts new file mode 100644 index 0000000000000000000000000000000000000000..94f1b6ab0d675ecdf00cd0416bcb228cba1ba604 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/src/sourcemap-segment.ts @@ -0,0 +1,23 @@ +type GeneratedColumn = number; +type SourcesIndex = number; +type SourceLine = number; +type SourceColumn = number; +type NamesIndex = number; + +type GeneratedLine = number; + +export type SourceMapSegment = + | [GeneratedColumn] + | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn] + | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex]; + +export type ReverseSegment = [SourceColumn, GeneratedLine, GeneratedColumn]; + +export const COLUMN = 0; +export const SOURCES_INDEX = 1; +export const SOURCE_LINE = 2; +export const SOURCE_COLUMN = 3; +export const NAMES_INDEX = 4; + +export const REV_GENERATED_LINE = 1; +export const REV_GENERATED_COLUMN = 2; diff --git a/node_modules/@jridgewell/trace-mapping/src/strip-filename.ts b/node_modules/@jridgewell/trace-mapping/src/strip-filename.ts new file mode 100644 index 0000000000000000000000000000000000000000..2c889800e196e1728b8f4e6c50dd686b5f874376 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/src/strip-filename.ts @@ -0,0 +1,8 @@ +/** + * Removes everything after the last "/", but leaves the slash. + */ +export default function stripFilename(path: string | undefined | null): string { + if (!path) return ''; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); +} diff --git a/node_modules/@jridgewell/trace-mapping/src/trace-mapping.ts b/node_modules/@jridgewell/trace-mapping/src/trace-mapping.ts new file mode 100644 index 0000000000000000000000000000000000000000..0b793d5bb342398516285157e8ed5bc09aef306d --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/src/trace-mapping.ts @@ -0,0 +1,502 @@ +import { encode, decode } from '@jridgewell/sourcemap-codec'; + +import resolver from './resolve'; +import maybeSort from './sort'; +import buildBySources from './by-source'; +import { + memoizedState, + memoizedBinarySearch, + upperBound, + lowerBound, + found as bsFound, +} from './binary-search'; +import { + COLUMN, + SOURCES_INDEX, + SOURCE_LINE, + SOURCE_COLUMN, + NAMES_INDEX, + REV_GENERATED_LINE, + REV_GENERATED_COLUMN, +} from './sourcemap-segment'; +import { parse } from './types'; + +import type { SourceMapSegment, ReverseSegment } from './sourcemap-segment'; +import type { + SourceMapV3, + DecodedSourceMap, + EncodedSourceMap, + InvalidOriginalMapping, + OriginalMapping, + InvalidGeneratedMapping, + GeneratedMapping, + SourceMapInput, + Needle, + SourceNeedle, + SourceMap, + EachMapping, + Bias, + XInput, + SectionedSourceMap, + Ro, +} from './types'; +import type { Source } from './by-source'; +import type { MemoState } from './binary-search'; + +export type { SourceMapSegment } from './sourcemap-segment'; +export type { + SourceMap, + DecodedSourceMap, + EncodedSourceMap, + Section, + SectionedSourceMap, + SourceMapV3, + Bias, + EachMapping, + GeneratedMapping, + InvalidGeneratedMapping, + InvalidOriginalMapping, + Needle, + OriginalMapping, + OriginalMapping as Mapping, + SectionedSourceMapInput, + SourceMapInput, + SourceNeedle, + XInput, + EncodedSourceMapXInput, + DecodedSourceMapXInput, + SectionedSourceMapXInput, + SectionXInput, +} from './types'; + +interface PublicMap { + _encoded: TraceMap['_encoded']; + _decoded: TraceMap['_decoded']; + _decodedMemo: TraceMap['_decodedMemo']; + _bySources: TraceMap['_bySources']; + _bySourceMemos: TraceMap['_bySourceMemos']; +} + +const LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)'; +const COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)'; + +export const LEAST_UPPER_BOUND = -1; +export const GREATEST_LOWER_BOUND = 1; + +export { FlattenMap, FlattenMap as AnyMap } from './flatten-map'; + +export class TraceMap implements SourceMap { + declare version: SourceMapV3['version']; + declare file: SourceMapV3['file']; + declare names: SourceMapV3['names']; + declare sourceRoot: SourceMapV3['sourceRoot']; + declare sources: SourceMapV3['sources']; + declare sourcesContent: SourceMapV3['sourcesContent']; + declare ignoreList: SourceMapV3['ignoreList']; + + declare resolvedSources: string[]; + declare private _encoded: string | undefined; + + declare private _decoded: SourceMapSegment[][] | undefined; + declare private _decodedMemo: MemoState; + + declare private _bySources: Source[] | undefined; + declare private _bySourceMemos: MemoState[] | undefined; + + constructor(map: Ro, mapUrl?: string | null) { + const isString = typeof map === 'string'; + if (!isString && (map as unknown as { _decodedMemo: any })._decodedMemo) return map as TraceMap; + + const parsed = parse(map as Exclude); + + const { version, file, names, sourceRoot, sources, sourcesContent } = parsed; + this.version = version; + this.file = file; + this.names = names || []; + this.sourceRoot = sourceRoot; + this.sources = sources; + this.sourcesContent = sourcesContent; + this.ignoreList = parsed.ignoreList || (parsed as XInput).x_google_ignoreList || undefined; + + const resolve = resolver(mapUrl, sourceRoot); + this.resolvedSources = sources.map(resolve); + + const { mappings } = parsed; + if (typeof mappings === 'string') { + this._encoded = mappings; + this._decoded = undefined; + } else if (Array.isArray(mappings)) { + this._encoded = undefined; + this._decoded = maybeSort(mappings, isString); + } else if ((parsed as unknown as SectionedSourceMap).sections) { + throw new Error(`TraceMap passed sectioned source map, please use FlattenMap export instead`); + } else { + throw new Error(`invalid source map: ${JSON.stringify(parsed)}`); + } + + this._decodedMemo = memoizedState(); + this._bySources = undefined; + this._bySourceMemos = undefined; + } +} + +/** + * Typescript doesn't allow friend access to private fields, so this just casts the map into a type + * with public access modifiers. + */ +function cast(map: unknown): PublicMap { + return map as any; +} + +/** + * Returns the encoded (VLQ string) form of the SourceMap's mappings field. + */ +export function encodedMappings(map: TraceMap): EncodedSourceMap['mappings'] { + return (cast(map)._encoded ??= encode(cast(map)._decoded!)); +} + +/** + * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field. + */ +export function decodedMappings(map: TraceMap): Readonly { + return (cast(map)._decoded ||= decode(cast(map)._encoded!)); +} + +/** + * A low-level API to find the segment associated with a generated line/column (think, from a + * stack trace). Line and column here are 0-based, unlike `originalPositionFor`. + */ +export function traceSegment( + map: TraceMap, + line: number, + column: number, +): Readonly | null { + const decoded = decodedMappings(map); + + // It's common for parent source maps to have pointers to lines that have no + // mapping (like a "//# sourceMappingURL=") at the end of the child file. + if (line >= decoded.length) return null; + + const segments = decoded[line]; + const index = traceSegmentInternal( + segments, + cast(map)._decodedMemo, + line, + column, + GREATEST_LOWER_BOUND, + ); + + return index === -1 ? null : segments[index]; +} + +/** + * A higher-level API to find the source/line/column associated with a generated line/column + * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in + * `source-map` library. + */ +export function originalPositionFor( + map: TraceMap, + needle: Needle, +): OriginalMapping | InvalidOriginalMapping { + let { line, column, bias } = needle; + line--; + if (line < 0) throw new Error(LINE_GTR_ZERO); + if (column < 0) throw new Error(COL_GTR_EQ_ZERO); + + const decoded = decodedMappings(map); + + // It's common for parent source maps to have pointers to lines that have no + // mapping (like a "//# sourceMappingURL=") at the end of the child file. + if (line >= decoded.length) return OMapping(null, null, null, null); + + const segments = decoded[line]; + const index = traceSegmentInternal( + segments, + cast(map)._decodedMemo, + line, + column, + bias || GREATEST_LOWER_BOUND, + ); + + if (index === -1) return OMapping(null, null, null, null); + + const segment = segments[index]; + if (segment.length === 1) return OMapping(null, null, null, null); + + const { names, resolvedSources } = map; + return OMapping( + resolvedSources[segment[SOURCES_INDEX]], + segment[SOURCE_LINE] + 1, + segment[SOURCE_COLUMN], + segment.length === 5 ? names[segment[NAMES_INDEX]] : null, + ); +} + +/** + * Finds the generated line/column position of the provided source/line/column source position. + */ +export function generatedPositionFor( + map: TraceMap, + needle: SourceNeedle, +): GeneratedMapping | InvalidGeneratedMapping { + const { source, line, column, bias } = needle; + return generatedPosition(map, source, line, column, bias || GREATEST_LOWER_BOUND, false); +} + +/** + * Finds all generated line/column positions of the provided source/line/column source position. + */ +export function allGeneratedPositionsFor(map: TraceMap, needle: SourceNeedle): GeneratedMapping[] { + const { source, line, column, bias } = needle; + // SourceMapConsumer uses LEAST_UPPER_BOUND for some reason, so we follow suit. + return generatedPosition(map, source, line, column, bias || LEAST_UPPER_BOUND, true); +} + +/** + * Iterates each mapping in generated position order. + */ +export function eachMapping(map: TraceMap, cb: (mapping: EachMapping) => void): void { + const decoded = decodedMappings(map); + const { names, resolvedSources } = map; + + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + + const generatedLine = i + 1; + const generatedColumn = seg[0]; + let source = null; + let originalLine = null; + let originalColumn = null; + let name = null; + if (seg.length !== 1) { + source = resolvedSources[seg[1]]; + originalLine = seg[2] + 1; + originalColumn = seg[3]; + } + if (seg.length === 5) name = names[seg[4]]; + + cb({ + generatedLine, + generatedColumn, + source, + originalLine, + originalColumn, + name, + } as EachMapping); + } + } +} + +function sourceIndex(map: TraceMap, source: string): number { + const { sources, resolvedSources } = map; + let index = sources.indexOf(source); + if (index === -1) index = resolvedSources.indexOf(source); + return index; +} + +/** + * Retrieves the source content for a particular source, if its found. Returns null if not. + */ +export function sourceContentFor(map: TraceMap, source: string): string | null { + const { sourcesContent } = map; + if (sourcesContent == null) return null; + const index = sourceIndex(map, source); + return index === -1 ? null : sourcesContent[index]; +} + +/** + * Determines if the source is marked to ignore by the source map. + */ +export function isIgnored(map: TraceMap, source: string): boolean { + const { ignoreList } = map; + if (ignoreList == null) return false; + const index = sourceIndex(map, source); + return index === -1 ? false : ignoreList.includes(index); +} + +/** + * A helper that skips sorting of the input map's mappings array, which can be expensive for larger + * maps. + */ +export function presortedDecodedMap(map: DecodedSourceMap, mapUrl?: string): TraceMap { + const tracer = new TraceMap(clone(map, []), mapUrl); + cast(tracer)._decoded = map.mappings; + return tracer; +} + +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export function decodedMap( + map: TraceMap, +): Omit & { mappings: readonly SourceMapSegment[][] } { + return clone(map, decodedMappings(map)); +} + +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export function encodedMap(map: TraceMap): EncodedSourceMap { + return clone(map, encodedMappings(map)); +} + +function clone( + map: TraceMap | DecodedSourceMap, + mappings: T, +): T extends string ? EncodedSourceMap : DecodedSourceMap { + return { + version: map.version, + file: map.file, + names: map.names, + sourceRoot: map.sourceRoot, + sources: map.sources, + sourcesContent: map.sourcesContent, + mappings, + ignoreList: map.ignoreList || (map as XInput).x_google_ignoreList, + } as any; +} + +function OMapping(source: null, line: null, column: null, name: null): InvalidOriginalMapping; +function OMapping( + source: string, + line: number, + column: number, + name: string | null, +): OriginalMapping; +function OMapping( + source: string | null, + line: number | null, + column: number | null, + name: string | null, +): OriginalMapping | InvalidOriginalMapping { + return { source, line, column, name } as any; +} + +function GMapping(line: null, column: null): InvalidGeneratedMapping; +function GMapping(line: number, column: number): GeneratedMapping; +function GMapping( + line: number | null, + column: number | null, +): GeneratedMapping | InvalidGeneratedMapping { + return { line, column } as any; +} + +function traceSegmentInternal( + segments: SourceMapSegment[], + memo: MemoState, + line: number, + column: number, + bias: Bias, +): number; +function traceSegmentInternal( + segments: ReverseSegment[], + memo: MemoState, + line: number, + column: number, + bias: Bias, +): number; +function traceSegmentInternal( + segments: SourceMapSegment[] | ReverseSegment[], + memo: MemoState, + line: number, + column: number, + bias: Bias, +): number { + let index = memoizedBinarySearch(segments, column, memo, line); + if (bsFound) { + index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index); + } else if (bias === LEAST_UPPER_BOUND) index++; + + if (index === -1 || index === segments.length) return -1; + return index; +} + +function sliceGeneratedPositions( + segments: ReverseSegment[], + memo: MemoState, + line: number, + column: number, + bias: Bias, +): GeneratedMapping[] { + let min = traceSegmentInternal(segments, memo, line, column, GREATEST_LOWER_BOUND); + + // We ignored the bias when tracing the segment so that we're guarnateed to find the first (in + // insertion order) segment that matched. Even if we did respect the bias when tracing, we would + // still need to call `lowerBound()` to find the first segment, which is slower than just looking + // for the GREATEST_LOWER_BOUND to begin with. The only difference that matters for us is when the + // binary search didn't match, in which case GREATEST_LOWER_BOUND just needs to increment to + // match LEAST_UPPER_BOUND. + if (!bsFound && bias === LEAST_UPPER_BOUND) min++; + + if (min === -1 || min === segments.length) return []; + + // We may have found the segment that started at an earlier column. If this is the case, then we + // need to slice all generated segments that match _that_ column, because all such segments span + // to our desired column. + const matchedColumn = bsFound ? column : segments[min][COLUMN]; + + // The binary search is not guaranteed to find the lower bound when a match wasn't found. + if (!bsFound) min = lowerBound(segments, matchedColumn, min); + const max = upperBound(segments, matchedColumn, min); + + const result = []; + for (; min <= max; min++) { + const segment = segments[min]; + result.push(GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN])); + } + return result; +} + +function generatedPosition( + map: TraceMap, + source: string, + line: number, + column: number, + bias: Bias, + all: false, +): GeneratedMapping | InvalidGeneratedMapping; +function generatedPosition( + map: TraceMap, + source: string, + line: number, + column: number, + bias: Bias, + all: true, +): GeneratedMapping[]; +function generatedPosition( + map: TraceMap, + source: string, + line: number, + column: number, + bias: Bias, + all: boolean, +): GeneratedMapping | InvalidGeneratedMapping | GeneratedMapping[] { + line--; + if (line < 0) throw new Error(LINE_GTR_ZERO); + if (column < 0) throw new Error(COL_GTR_EQ_ZERO); + + const { sources, resolvedSources } = map; + let sourceIndex = sources.indexOf(source); + if (sourceIndex === -1) sourceIndex = resolvedSources.indexOf(source); + if (sourceIndex === -1) return all ? [] : GMapping(null, null); + + const bySourceMemos = (cast(map)._bySourceMemos ||= sources.map(memoizedState)); + const generated = (cast(map)._bySources ||= buildBySources(decodedMappings(map), bySourceMemos)); + + const segments = generated[sourceIndex][line]; + if (segments == null) return all ? [] : GMapping(null, null); + + const memo = bySourceMemos[sourceIndex]; + + if (all) return sliceGeneratedPositions(segments, memo, line, column, bias); + + const index = traceSegmentInternal(segments, memo, line, column, bias); + if (index === -1) return GMapping(null, null); + + const segment = segments[index]; + return GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]); +} diff --git a/node_modules/@jridgewell/trace-mapping/src/types.ts b/node_modules/@jridgewell/trace-mapping/src/types.ts new file mode 100644 index 0000000000000000000000000000000000000000..730a61fb5ca1e2a389b6bff8dc773828a0372421 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/src/types.ts @@ -0,0 +1,114 @@ +import type { SourceMapSegment } from './sourcemap-segment'; +import type { GREATEST_LOWER_BOUND, LEAST_UPPER_BOUND, TraceMap } from './trace-mapping'; + +export interface SourceMapV3 { + file?: string | null; + names: string[]; + sourceRoot?: string; + sources: (string | null)[]; + sourcesContent?: (string | null)[]; + version: 3; + ignoreList?: number[]; +} + +export interface EncodedSourceMap extends SourceMapV3 { + mappings: string; +} + +export interface DecodedSourceMap extends SourceMapV3 { + mappings: SourceMapSegment[][]; +} + +export interface Section { + offset: { line: number; column: number }; + map: EncodedSourceMap | DecodedSourceMap | SectionedSourceMap; +} + +export interface SectionedSourceMap { + file?: string | null; + sections: Section[]; + version: 3; +} + +export type OriginalMapping = { + source: string | null; + line: number; + column: number; + name: string | null; +}; + +export type InvalidOriginalMapping = { + source: null; + line: null; + column: null; + name: null; +}; + +export type GeneratedMapping = { + line: number; + column: number; +}; +export type InvalidGeneratedMapping = { + line: null; + column: null; +}; + +export type Bias = typeof GREATEST_LOWER_BOUND | typeof LEAST_UPPER_BOUND; + +export type XInput = { x_google_ignoreList?: SourceMapV3['ignoreList'] }; +export type EncodedSourceMapXInput = EncodedSourceMap & XInput; +export type DecodedSourceMapXInput = DecodedSourceMap & XInput; +export type SectionedSourceMapXInput = Omit & { + sections: SectionXInput[]; +}; +export type SectionXInput = Omit & { + map: SectionedSourceMapInput; +}; + +export type SourceMapInput = string | EncodedSourceMapXInput | DecodedSourceMapXInput | TraceMap; +export type SectionedSourceMapInput = SourceMapInput | SectionedSourceMapXInput; + +export type Needle = { line: number; column: number; bias?: Bias }; +export type SourceNeedle = { source: string; line: number; column: number; bias?: Bias }; + +export type EachMapping = + | { + generatedLine: number; + generatedColumn: number; + source: null; + originalLine: null; + originalColumn: null; + name: null; + } + | { + generatedLine: number; + generatedColumn: number; + source: string | null; + originalLine: number; + originalColumn: number; + name: string | null; + }; + +export abstract class SourceMap { + declare version: SourceMapV3['version']; + declare file: SourceMapV3['file']; + declare names: SourceMapV3['names']; + declare sourceRoot: SourceMapV3['sourceRoot']; + declare sources: SourceMapV3['sources']; + declare sourcesContent: SourceMapV3['sourcesContent']; + declare resolvedSources: SourceMapV3['sources']; + declare ignoreList: SourceMapV3['ignoreList']; +} + +export type Ro = + T extends Array + ? V[] | Readonly | RoArray | Readonly> + : T extends object + ? T | Readonly | RoObject | Readonly> + : T; +type RoArray = Ro[]; +type RoObject = { [K in keyof T]: T[K] | Ro }; + +export function parse(map: T): Exclude { + return typeof map === 'string' ? JSON.parse(map) : (map as Exclude); +} diff --git a/node_modules/@jridgewell/trace-mapping/types/binary-search.d.cts b/node_modules/@jridgewell/trace-mapping/types/binary-search.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..b7bb85c913b38b846273813e77c3c9aecbcaa3cd --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/binary-search.d.cts @@ -0,0 +1,33 @@ +import type { SourceMapSegment, ReverseSegment } from './sourcemap-segment.cts'; +export type MemoState = { + lastKey: number; + lastNeedle: number; + lastIndex: number; +}; +export declare let found: boolean; +/** + * A binary search implementation that returns the index if a match is found. + * If no match is found, then the left-index (the index associated with the item that comes just + * before the desired index) is returned. To maintain proper sort order, a splice would happen at + * the next index: + * + * ```js + * const array = [1, 3]; + * const needle = 2; + * const index = binarySearch(array, needle, (item, needle) => item - needle); + * + * assert.equal(index, 0); + * array.splice(index + 1, 0, needle); + * assert.deepEqual(array, [1, 2, 3]); + * ``` + */ +export declare function binarySearch(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, low: number, high: number): number; +export declare function upperBound(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, index: number): number; +export declare function lowerBound(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, index: number): number; +export declare function memoizedState(): MemoState; +/** + * This overly complicated beast is just to record the last tested line/column and the resulting + * index, allowing us to skip a few tests if mappings are monotonically increasing. + */ +export declare function memoizedBinarySearch(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, state: MemoState, key: number): number; +//# sourceMappingURL=binary-search.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/binary-search.d.cts.map b/node_modules/@jridgewell/trace-mapping/types/binary-search.d.cts.map new file mode 100644 index 0000000000000000000000000000000000000000..648e84c1e7a5c587e300fe348389c500fa2af2c6 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/binary-search.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"binary-search.d.ts","sourceRoot":"","sources":["../src/binary-search.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAG5E,MAAM,MAAM,SAAS,GAAG;IACtB,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;CACnB,CAAC;AAEF,eAAO,IAAI,KAAK,SAAQ,CAAC;AAEzB;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,YAAY,CAC1B,QAAQ,EAAE,gBAAgB,EAAE,GAAG,cAAc,EAAE,EAC/C,MAAM,EAAE,MAAM,EACd,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,MAAM,GACX,MAAM,CAmBR;AAED,wBAAgB,UAAU,CACxB,QAAQ,EAAE,gBAAgB,EAAE,GAAG,cAAc,EAAE,EAC/C,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,MAAM,GACZ,MAAM,CAKR;AAED,wBAAgB,UAAU,CACxB,QAAQ,EAAE,gBAAgB,EAAE,GAAG,cAAc,EAAE,EAC/C,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,MAAM,GACZ,MAAM,CAKR;AAED,wBAAgB,aAAa,IAAI,SAAS,CAMzC;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAClC,QAAQ,EAAE,gBAAgB,EAAE,GAAG,cAAc,EAAE,EAC/C,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,SAAS,EAChB,GAAG,EAAE,MAAM,GACV,MAAM,CAsBR"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/binary-search.d.mts b/node_modules/@jridgewell/trace-mapping/types/binary-search.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..19e1e6b9eb4e26e90df2e4bc21d1e27ae149d132 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/binary-search.d.mts @@ -0,0 +1,33 @@ +import type { SourceMapSegment, ReverseSegment } from './sourcemap-segment.mts'; +export type MemoState = { + lastKey: number; + lastNeedle: number; + lastIndex: number; +}; +export declare let found: boolean; +/** + * A binary search implementation that returns the index if a match is found. + * If no match is found, then the left-index (the index associated with the item that comes just + * before the desired index) is returned. To maintain proper sort order, a splice would happen at + * the next index: + * + * ```js + * const array = [1, 3]; + * const needle = 2; + * const index = binarySearch(array, needle, (item, needle) => item - needle); + * + * assert.equal(index, 0); + * array.splice(index + 1, 0, needle); + * assert.deepEqual(array, [1, 2, 3]); + * ``` + */ +export declare function binarySearch(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, low: number, high: number): number; +export declare function upperBound(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, index: number): number; +export declare function lowerBound(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, index: number): number; +export declare function memoizedState(): MemoState; +/** + * This overly complicated beast is just to record the last tested line/column and the resulting + * index, allowing us to skip a few tests if mappings are monotonically increasing. + */ +export declare function memoizedBinarySearch(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, state: MemoState, key: number): number; +//# sourceMappingURL=binary-search.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/binary-search.d.mts.map b/node_modules/@jridgewell/trace-mapping/types/binary-search.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..648e84c1e7a5c587e300fe348389c500fa2af2c6 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/binary-search.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"binary-search.d.ts","sourceRoot":"","sources":["../src/binary-search.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAG5E,MAAM,MAAM,SAAS,GAAG;IACtB,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;CACnB,CAAC;AAEF,eAAO,IAAI,KAAK,SAAQ,CAAC;AAEzB;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,YAAY,CAC1B,QAAQ,EAAE,gBAAgB,EAAE,GAAG,cAAc,EAAE,EAC/C,MAAM,EAAE,MAAM,EACd,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,MAAM,GACX,MAAM,CAmBR;AAED,wBAAgB,UAAU,CACxB,QAAQ,EAAE,gBAAgB,EAAE,GAAG,cAAc,EAAE,EAC/C,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,MAAM,GACZ,MAAM,CAKR;AAED,wBAAgB,UAAU,CACxB,QAAQ,EAAE,gBAAgB,EAAE,GAAG,cAAc,EAAE,EAC/C,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,MAAM,GACZ,MAAM,CAKR;AAED,wBAAgB,aAAa,IAAI,SAAS,CAMzC;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAClC,QAAQ,EAAE,gBAAgB,EAAE,GAAG,cAAc,EAAE,EAC/C,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,SAAS,EAChB,GAAG,EAAE,MAAM,GACV,MAAM,CAsBR"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/by-source.d.cts b/node_modules/@jridgewell/trace-mapping/types/by-source.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..da496939c7c9d357a14710fcf16254e54e129c17 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/by-source.d.cts @@ -0,0 +1,4 @@ +import type { ReverseSegment, SourceMapSegment } from './sourcemap-segment.cts'; +export type Source = ReverseSegment[][]; +export = function buildBySources(decoded: readonly SourceMapSegment[][], memos: unknown[]): Source[]; +//# sourceMappingURL=by-source.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/by-source.d.cts.map b/node_modules/@jridgewell/trace-mapping/types/by-source.d.cts.map new file mode 100644 index 0000000000000000000000000000000000000000..32d2a7a1a941010c0b0315b458ba23d53d839b35 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/by-source.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"by-source.d.ts","sourceRoot":"","sources":["../src/by-source.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAE5E,MAAM,MAAM,MAAM,GAAG,cAAc,EAAE,EAAE,CAAC;AAIxC,MAAM,CAAC,OAAO,UAAU,cAAc,CACpC,OAAO,EAAE,SAAS,gBAAgB,EAAE,EAAE,EACtC,KAAK,EAAE,OAAO,EAAE,GACf,MAAM,EAAE,CA4BV"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/by-source.d.mts b/node_modules/@jridgewell/trace-mapping/types/by-source.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..f36104955fbc695200a077cb96bc6019ec73c7c0 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/by-source.d.mts @@ -0,0 +1,4 @@ +import type { ReverseSegment, SourceMapSegment } from './sourcemap-segment.mts'; +export type Source = ReverseSegment[][]; +export default function buildBySources(decoded: readonly SourceMapSegment[][], memos: unknown[]): Source[]; +//# sourceMappingURL=by-source.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/by-source.d.mts.map b/node_modules/@jridgewell/trace-mapping/types/by-source.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..32d2a7a1a941010c0b0315b458ba23d53d839b35 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/by-source.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"by-source.d.ts","sourceRoot":"","sources":["../src/by-source.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAE5E,MAAM,MAAM,MAAM,GAAG,cAAc,EAAE,EAAE,CAAC;AAIxC,MAAM,CAAC,OAAO,UAAU,cAAc,CACpC,OAAO,EAAE,SAAS,gBAAgB,EAAE,EAAE,EACtC,KAAK,EAAE,OAAO,EAAE,GACf,MAAM,EAAE,CA4BV"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/flatten-map.d.cts b/node_modules/@jridgewell/trace-mapping/types/flatten-map.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..433d849b7c4a8cec8c2dc50013b26b2ebd5f61ad --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/flatten-map.d.cts @@ -0,0 +1,9 @@ +import { TraceMap } from './trace-mapping.cts'; +import type { SectionedSourceMapInput, Ro } from './types.cts'; +type FlattenMap = { + new (map: Ro, mapUrl?: string | null): TraceMap; + (map: Ro, mapUrl?: string | null): TraceMap; +}; +export declare const FlattenMap: FlattenMap; +export {}; +//# sourceMappingURL=flatten-map.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/flatten-map.d.cts.map b/node_modules/@jridgewell/trace-mapping/types/flatten-map.d.cts.map new file mode 100644 index 0000000000000000000000000000000000000000..994b208adfdb40a78e7b788b3bb039ca5da41031 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/flatten-map.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"flatten-map.d.ts","sourceRoot":"","sources":["../src/flatten-map.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAwC,MAAM,iBAAiB,CAAC;AAUjF,OAAO,KAAK,EAKV,uBAAuB,EAEvB,EAAE,EACH,MAAM,SAAS,CAAC;AAGjB,KAAK,UAAU,GAAG;IAChB,KAAK,GAAG,EAAE,EAAE,CAAC,uBAAuB,CAAC,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,QAAQ,CAAC;IACzE,CAAC,GAAG,EAAE,EAAE,CAAC,uBAAuB,CAAC,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,QAAQ,CAAC;CACtE,CAAC;AAEF,eAAO,MAAM,UAAU,EAAE,UAsCV,CAAC"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/flatten-map.d.mts b/node_modules/@jridgewell/trace-mapping/types/flatten-map.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..444a1bed55f5210de610d9dd8360ce9c8db37f10 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/flatten-map.d.mts @@ -0,0 +1,9 @@ +import { TraceMap } from './trace-mapping.mts'; +import type { SectionedSourceMapInput, Ro } from './types.mts'; +type FlattenMap = { + new (map: Ro, mapUrl?: string | null): TraceMap; + (map: Ro, mapUrl?: string | null): TraceMap; +}; +export declare const FlattenMap: FlattenMap; +export {}; +//# sourceMappingURL=flatten-map.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/flatten-map.d.mts.map b/node_modules/@jridgewell/trace-mapping/types/flatten-map.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..994b208adfdb40a78e7b788b3bb039ca5da41031 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/flatten-map.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"flatten-map.d.ts","sourceRoot":"","sources":["../src/flatten-map.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAwC,MAAM,iBAAiB,CAAC;AAUjF,OAAO,KAAK,EAKV,uBAAuB,EAEvB,EAAE,EACH,MAAM,SAAS,CAAC;AAGjB,KAAK,UAAU,GAAG;IAChB,KAAK,GAAG,EAAE,EAAE,CAAC,uBAAuB,CAAC,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,QAAQ,CAAC;IACzE,CAAC,GAAG,EAAE,EAAE,CAAC,uBAAuB,CAAC,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,QAAQ,CAAC;CACtE,CAAC;AAEF,eAAO,MAAM,UAAU,EAAE,UAsCV,CAAC"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/resolve.d.cts b/node_modules/@jridgewell/trace-mapping/types/resolve.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..62aeedb5b381de715b75ad8d15553fae994ee079 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/resolve.d.cts @@ -0,0 +1,4 @@ +type Resolve = (source: string | null) => string; +export = function resolver(mapUrl: string | null | undefined, sourceRoot: string | undefined): Resolve; +export {}; +//# sourceMappingURL=resolve.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/resolve.d.cts.map b/node_modules/@jridgewell/trace-mapping/types/resolve.d.cts.map new file mode 100644 index 0000000000000000000000000000000000000000..9f155ace7bab5ceb34974af9ea919c4760c4e9a4 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/resolve.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"resolve.d.ts","sourceRoot":"","sources":["../src/resolve.ts"],"names":[],"mappings":"AAGA,KAAK,OAAO,GAAG,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,KAAK,MAAM,CAAC;AACjD,MAAM,CAAC,OAAO,UAAU,QAAQ,CAC9B,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EACjC,UAAU,EAAE,MAAM,GAAG,SAAS,GAC7B,OAAO,CAQT"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/resolve.d.mts b/node_modules/@jridgewell/trace-mapping/types/resolve.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..e2798a19ccb20ab2d94ffa7a8bd1bab03303fe69 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/resolve.d.mts @@ -0,0 +1,4 @@ +type Resolve = (source: string | null) => string; +export default function resolver(mapUrl: string | null | undefined, sourceRoot: string | undefined): Resolve; +export {}; +//# sourceMappingURL=resolve.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/resolve.d.mts.map b/node_modules/@jridgewell/trace-mapping/types/resolve.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..9f155ace7bab5ceb34974af9ea919c4760c4e9a4 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/resolve.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"resolve.d.ts","sourceRoot":"","sources":["../src/resolve.ts"],"names":[],"mappings":"AAGA,KAAK,OAAO,GAAG,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,KAAK,MAAM,CAAC;AACjD,MAAM,CAAC,OAAO,UAAU,QAAQ,CAC9B,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EACjC,UAAU,EAAE,MAAM,GAAG,SAAS,GAC7B,OAAO,CAQT"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/sort.d.cts b/node_modules/@jridgewell/trace-mapping/types/sort.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..aa14c129008da878cf9443414951b8a9c2d0799f --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/sort.d.cts @@ -0,0 +1,4 @@ +import type { ReverseSegment, SourceMapSegment } from './sourcemap-segment.cts'; +export = function maybeSort(mappings: SourceMapSegment[][], owned: boolean): SourceMapSegment[][]; +export declare function sortComparator(a: T, b: T): number; +//# sourceMappingURL=sort.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/sort.d.cts.map b/node_modules/@jridgewell/trace-mapping/types/sort.d.cts.map new file mode 100644 index 0000000000000000000000000000000000000000..48b8e67418d400b7c68921231f0028b2cee0652a --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/sort.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"sort.d.ts","sourceRoot":"","sources":["../src/sort.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAE5E,MAAM,CAAC,OAAO,UAAU,SAAS,CAC/B,QAAQ,EAAE,gBAAgB,EAAE,EAAE,EAC9B,KAAK,EAAE,OAAO,GACb,gBAAgB,EAAE,EAAE,CAYtB;AAuBD,wBAAgB,cAAc,CAAC,CAAC,SAAS,gBAAgB,GAAG,cAAc,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,GAAG,MAAM,CAE9F"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/sort.d.mts b/node_modules/@jridgewell/trace-mapping/types/sort.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..c5b94e64fd5595680120201212a03e905ebeb4c3 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/sort.d.mts @@ -0,0 +1,4 @@ +import type { ReverseSegment, SourceMapSegment } from './sourcemap-segment.mts'; +export default function maybeSort(mappings: SourceMapSegment[][], owned: boolean): SourceMapSegment[][]; +export declare function sortComparator(a: T, b: T): number; +//# sourceMappingURL=sort.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/sort.d.mts.map b/node_modules/@jridgewell/trace-mapping/types/sort.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..48b8e67418d400b7c68921231f0028b2cee0652a --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/sort.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"sort.d.ts","sourceRoot":"","sources":["../src/sort.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAE5E,MAAM,CAAC,OAAO,UAAU,SAAS,CAC/B,QAAQ,EAAE,gBAAgB,EAAE,EAAE,EAC9B,KAAK,EAAE,OAAO,GACb,gBAAgB,EAAE,EAAE,CAYtB;AAuBD,wBAAgB,cAAc,CAAC,CAAC,SAAS,gBAAgB,GAAG,cAAc,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,GAAG,MAAM,CAE9F"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/sourcemap-segment.d.cts b/node_modules/@jridgewell/trace-mapping/types/sourcemap-segment.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..8d3cabc13032461848e6bcef75d702402517991f --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/sourcemap-segment.d.cts @@ -0,0 +1,17 @@ +type GeneratedColumn = number; +type SourcesIndex = number; +type SourceLine = number; +type SourceColumn = number; +type NamesIndex = number; +type GeneratedLine = number; +export type SourceMapSegment = [GeneratedColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex]; +export type ReverseSegment = [SourceColumn, GeneratedLine, GeneratedColumn]; +export declare const COLUMN = 0; +export declare const SOURCES_INDEX = 1; +export declare const SOURCE_LINE = 2; +export declare const SOURCE_COLUMN = 3; +export declare const NAMES_INDEX = 4; +export declare const REV_GENERATED_LINE = 1; +export declare const REV_GENERATED_COLUMN = 2; +export {}; +//# sourceMappingURL=sourcemap-segment.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/sourcemap-segment.d.cts.map b/node_modules/@jridgewell/trace-mapping/types/sourcemap-segment.d.cts.map new file mode 100644 index 0000000000000000000000000000000000000000..0c94a4610db499464df13dfe8456019983053a56 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/sourcemap-segment.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"sourcemap-segment.d.ts","sourceRoot":"","sources":["../src/sourcemap-segment.ts"],"names":[],"mappings":"AAAA,KAAK,eAAe,GAAG,MAAM,CAAC;AAC9B,KAAK,YAAY,GAAG,MAAM,CAAC;AAC3B,KAAK,UAAU,GAAG,MAAM,CAAC;AACzB,KAAK,YAAY,GAAG,MAAM,CAAC;AAC3B,KAAK,UAAU,GAAG,MAAM,CAAC;AAEzB,KAAK,aAAa,GAAG,MAAM,CAAC;AAE5B,MAAM,MAAM,gBAAgB,GACxB,CAAC,eAAe,CAAC,GACjB,CAAC,eAAe,EAAE,YAAY,EAAE,UAAU,EAAE,YAAY,CAAC,GACzD,CAAC,eAAe,EAAE,YAAY,EAAE,UAAU,EAAE,YAAY,EAAE,UAAU,CAAC,CAAC;AAE1E,MAAM,MAAM,cAAc,GAAG,CAAC,YAAY,EAAE,aAAa,EAAE,eAAe,CAAC,CAAC;AAE5E,eAAO,MAAM,MAAM,IAAI,CAAC;AACxB,eAAO,MAAM,aAAa,IAAI,CAAC;AAC/B,eAAO,MAAM,WAAW,IAAI,CAAC;AAC7B,eAAO,MAAM,aAAa,IAAI,CAAC;AAC/B,eAAO,MAAM,WAAW,IAAI,CAAC;AAE7B,eAAO,MAAM,kBAAkB,IAAI,CAAC;AACpC,eAAO,MAAM,oBAAoB,IAAI,CAAC"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/sourcemap-segment.d.mts b/node_modules/@jridgewell/trace-mapping/types/sourcemap-segment.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..8d3cabc13032461848e6bcef75d702402517991f --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/sourcemap-segment.d.mts @@ -0,0 +1,17 @@ +type GeneratedColumn = number; +type SourcesIndex = number; +type SourceLine = number; +type SourceColumn = number; +type NamesIndex = number; +type GeneratedLine = number; +export type SourceMapSegment = [GeneratedColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex]; +export type ReverseSegment = [SourceColumn, GeneratedLine, GeneratedColumn]; +export declare const COLUMN = 0; +export declare const SOURCES_INDEX = 1; +export declare const SOURCE_LINE = 2; +export declare const SOURCE_COLUMN = 3; +export declare const NAMES_INDEX = 4; +export declare const REV_GENERATED_LINE = 1; +export declare const REV_GENERATED_COLUMN = 2; +export {}; +//# sourceMappingURL=sourcemap-segment.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/sourcemap-segment.d.mts.map b/node_modules/@jridgewell/trace-mapping/types/sourcemap-segment.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..0c94a4610db499464df13dfe8456019983053a56 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/sourcemap-segment.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"sourcemap-segment.d.ts","sourceRoot":"","sources":["../src/sourcemap-segment.ts"],"names":[],"mappings":"AAAA,KAAK,eAAe,GAAG,MAAM,CAAC;AAC9B,KAAK,YAAY,GAAG,MAAM,CAAC;AAC3B,KAAK,UAAU,GAAG,MAAM,CAAC;AACzB,KAAK,YAAY,GAAG,MAAM,CAAC;AAC3B,KAAK,UAAU,GAAG,MAAM,CAAC;AAEzB,KAAK,aAAa,GAAG,MAAM,CAAC;AAE5B,MAAM,MAAM,gBAAgB,GACxB,CAAC,eAAe,CAAC,GACjB,CAAC,eAAe,EAAE,YAAY,EAAE,UAAU,EAAE,YAAY,CAAC,GACzD,CAAC,eAAe,EAAE,YAAY,EAAE,UAAU,EAAE,YAAY,EAAE,UAAU,CAAC,CAAC;AAE1E,MAAM,MAAM,cAAc,GAAG,CAAC,YAAY,EAAE,aAAa,EAAE,eAAe,CAAC,CAAC;AAE5E,eAAO,MAAM,MAAM,IAAI,CAAC;AACxB,eAAO,MAAM,aAAa,IAAI,CAAC;AAC/B,eAAO,MAAM,WAAW,IAAI,CAAC;AAC7B,eAAO,MAAM,aAAa,IAAI,CAAC;AAC/B,eAAO,MAAM,WAAW,IAAI,CAAC;AAE7B,eAAO,MAAM,kBAAkB,IAAI,CAAC;AACpC,eAAO,MAAM,oBAAoB,IAAI,CAAC"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/strip-filename.d.cts b/node_modules/@jridgewell/trace-mapping/types/strip-filename.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..8b3c0e9b9b8b4d94280c825ec48f41b4db0310a2 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/strip-filename.d.cts @@ -0,0 +1,5 @@ +/** + * Removes everything after the last "/", but leaves the slash. + */ +export = function stripFilename(path: string | undefined | null): string; +//# sourceMappingURL=strip-filename.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/strip-filename.d.cts.map b/node_modules/@jridgewell/trace-mapping/types/strip-filename.d.cts.map new file mode 100644 index 0000000000000000000000000000000000000000..17a25da0d4301a031587b6098f8a21f987b909f9 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/strip-filename.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"strip-filename.d.ts","sourceRoot":"","sources":["../src/strip-filename.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,CAAC,OAAO,UAAU,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,GAAG,MAAM,CAI7E"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/strip-filename.d.mts b/node_modules/@jridgewell/trace-mapping/types/strip-filename.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..cbbaee0db3016c0532f2b10e6acc31ee28c8a48f --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/strip-filename.d.mts @@ -0,0 +1,5 @@ +/** + * Removes everything after the last "/", but leaves the slash. + */ +export default function stripFilename(path: string | undefined | null): string; +//# sourceMappingURL=strip-filename.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/strip-filename.d.mts.map b/node_modules/@jridgewell/trace-mapping/types/strip-filename.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..17a25da0d4301a031587b6098f8a21f987b909f9 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/strip-filename.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"strip-filename.d.ts","sourceRoot":"","sources":["../src/strip-filename.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,CAAC,OAAO,UAAU,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,GAAG,MAAM,CAI7E"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/trace-mapping.d.cts b/node_modules/@jridgewell/trace-mapping/types/trace-mapping.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..a40f305476fd50c93d8209b43a09cba84f4bc68d --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/trace-mapping.d.cts @@ -0,0 +1,80 @@ +import type { SourceMapSegment } from './sourcemap-segment.cts'; +import type { SourceMapV3, DecodedSourceMap, EncodedSourceMap, InvalidOriginalMapping, OriginalMapping, InvalidGeneratedMapping, GeneratedMapping, SourceMapInput, Needle, SourceNeedle, SourceMap, EachMapping, Ro } from './types.cts'; +export type { SourceMapSegment } from './sourcemap-segment.cts'; +export type { SourceMap, DecodedSourceMap, EncodedSourceMap, Section, SectionedSourceMap, SourceMapV3, Bias, EachMapping, GeneratedMapping, InvalidGeneratedMapping, InvalidOriginalMapping, Needle, OriginalMapping, OriginalMapping as Mapping, SectionedSourceMapInput, SourceMapInput, SourceNeedle, XInput, EncodedSourceMapXInput, DecodedSourceMapXInput, SectionedSourceMapXInput, SectionXInput, } from './types.cts'; +export declare const LEAST_UPPER_BOUND = -1; +export declare const GREATEST_LOWER_BOUND = 1; +export { FlattenMap, FlattenMap as AnyMap } from './flatten-map.cts'; +export declare class TraceMap implements SourceMap { + version: SourceMapV3['version']; + file: SourceMapV3['file']; + names: SourceMapV3['names']; + sourceRoot: SourceMapV3['sourceRoot']; + sources: SourceMapV3['sources']; + sourcesContent: SourceMapV3['sourcesContent']; + ignoreList: SourceMapV3['ignoreList']; + resolvedSources: string[]; + private _encoded; + private _decoded; + private _decodedMemo; + private _bySources; + private _bySourceMemos; + constructor(map: Ro, mapUrl?: string | null); +} +/** + * Returns the encoded (VLQ string) form of the SourceMap's mappings field. + */ +export declare function encodedMappings(map: TraceMap): EncodedSourceMap['mappings']; +/** + * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field. + */ +export declare function decodedMappings(map: TraceMap): Readonly; +/** + * A low-level API to find the segment associated with a generated line/column (think, from a + * stack trace). Line and column here are 0-based, unlike `originalPositionFor`. + */ +export declare function traceSegment(map: TraceMap, line: number, column: number): Readonly | null; +/** + * A higher-level API to find the source/line/column associated with a generated line/column + * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in + * `source-map` library. + */ +export declare function originalPositionFor(map: TraceMap, needle: Needle): OriginalMapping | InvalidOriginalMapping; +/** + * Finds the generated line/column position of the provided source/line/column source position. + */ +export declare function generatedPositionFor(map: TraceMap, needle: SourceNeedle): GeneratedMapping | InvalidGeneratedMapping; +/** + * Finds all generated line/column positions of the provided source/line/column source position. + */ +export declare function allGeneratedPositionsFor(map: TraceMap, needle: SourceNeedle): GeneratedMapping[]; +/** + * Iterates each mapping in generated position order. + */ +export declare function eachMapping(map: TraceMap, cb: (mapping: EachMapping) => void): void; +/** + * Retrieves the source content for a particular source, if its found. Returns null if not. + */ +export declare function sourceContentFor(map: TraceMap, source: string): string | null; +/** + * Determines if the source is marked to ignore by the source map. + */ +export declare function isIgnored(map: TraceMap, source: string): boolean; +/** + * A helper that skips sorting of the input map's mappings array, which can be expensive for larger + * maps. + */ +export declare function presortedDecodedMap(map: DecodedSourceMap, mapUrl?: string): TraceMap; +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare function decodedMap(map: TraceMap): Omit & { + mappings: readonly SourceMapSegment[][]; +}; +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare function encodedMap(map: TraceMap): EncodedSourceMap; +//# sourceMappingURL=trace-mapping.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/trace-mapping.d.cts.map b/node_modules/@jridgewell/trace-mapping/types/trace-mapping.d.cts.map new file mode 100644 index 0000000000000000000000000000000000000000..b5a874c05a941f0f90a77a747f6ff27bd97200be --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/trace-mapping.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"trace-mapping.d.ts","sourceRoot":"","sources":["../src/trace-mapping.ts"],"names":[],"mappings":"AAuBA,OAAO,KAAK,EAAE,gBAAgB,EAAkB,MAAM,qBAAqB,CAAC;AAC5E,OAAO,KAAK,EACV,WAAW,EACX,gBAAgB,EAChB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M,CAAC,EAAE,MAAM,GAAG,QAAQ,CAIpF;AAED;;;GAGG;AACH,wBAAgB,UAAU,CACxB,GAAG,EAAE,QAAQ,GACZ,IAAI,CAAC,gBAAgB,EAAE,UAAU,CAAC,GAAG;IAAE,QAAQ,EAAE,SAAS,gBAAgB,EAAE,EAAE,CAAA;CAAE,CAElF;AAED;;;GAGG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,QAAQ,GAAG,gBAAgB,CAE1D"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/trace-mapping.d.mts b/node_modules/@jridgewell/trace-mapping/types/trace-mapping.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..bc2ff0f10ada49589f151943d011f212852abd81 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/trace-mapping.d.mts @@ -0,0 +1,80 @@ +import type { SourceMapSegment } from './sourcemap-segment.mts'; +import type { SourceMapV3, DecodedSourceMap, EncodedSourceMap, InvalidOriginalMapping, OriginalMapping, InvalidGeneratedMapping, GeneratedMapping, SourceMapInput, Needle, SourceNeedle, SourceMap, EachMapping, Ro } from './types.mts'; +export type { SourceMapSegment } from './sourcemap-segment.mts'; +export type { SourceMap, DecodedSourceMap, EncodedSourceMap, Section, SectionedSourceMap, SourceMapV3, Bias, EachMapping, GeneratedMapping, InvalidGeneratedMapping, InvalidOriginalMapping, Needle, OriginalMapping, OriginalMapping as Mapping, SectionedSourceMapInput, SourceMapInput, SourceNeedle, XInput, EncodedSourceMapXInput, DecodedSourceMapXInput, SectionedSourceMapXInput, SectionXInput, } from './types.mts'; +export declare const LEAST_UPPER_BOUND = -1; +export declare const GREATEST_LOWER_BOUND = 1; +export { FlattenMap, FlattenMap as AnyMap } from './flatten-map.mts'; +export declare class TraceMap implements SourceMap { + version: SourceMapV3['version']; + file: SourceMapV3['file']; + names: SourceMapV3['names']; + sourceRoot: SourceMapV3['sourceRoot']; + sources: SourceMapV3['sources']; + sourcesContent: SourceMapV3['sourcesContent']; + ignoreList: SourceMapV3['ignoreList']; + resolvedSources: string[]; + private _encoded; + private _decoded; + private _decodedMemo; + private _bySources; + private _bySourceMemos; + constructor(map: Ro, mapUrl?: string | null); +} +/** + * Returns the encoded (VLQ string) form of the SourceMap's mappings field. + */ +export declare function encodedMappings(map: TraceMap): EncodedSourceMap['mappings']; +/** + * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field. + */ +export declare function decodedMappings(map: TraceMap): Readonly; +/** + * A low-level API to find the segment associated with a generated line/column (think, from a + * stack trace). Line and column here are 0-based, unlike `originalPositionFor`. + */ +export declare function traceSegment(map: TraceMap, line: number, column: number): Readonly | null; +/** + * A higher-level API to find the source/line/column associated with a generated line/column + * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in + * `source-map` library. + */ +export declare function originalPositionFor(map: TraceMap, needle: Needle): OriginalMapping | InvalidOriginalMapping; +/** + * Finds the generated line/column position of the provided source/line/column source position. + */ +export declare function generatedPositionFor(map: TraceMap, needle: SourceNeedle): GeneratedMapping | InvalidGeneratedMapping; +/** + * Finds all generated line/column positions of the provided source/line/column source position. + */ +export declare function allGeneratedPositionsFor(map: TraceMap, needle: SourceNeedle): GeneratedMapping[]; +/** + * Iterates each mapping in generated position order. + */ +export declare function eachMapping(map: TraceMap, cb: (mapping: EachMapping) => void): void; +/** + * Retrieves the source content for a particular source, if its found. Returns null if not. + */ +export declare function sourceContentFor(map: TraceMap, source: string): string | null; +/** + * Determines if the source is marked to ignore by the source map. + */ +export declare function isIgnored(map: TraceMap, source: string): boolean; +/** + * A helper that skips sorting of the input map's mappings array, which can be expensive for larger + * maps. + */ +export declare function presortedDecodedMap(map: DecodedSourceMap, mapUrl?: string): TraceMap; +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare function decodedMap(map: TraceMap): Omit & { + mappings: readonly SourceMapSegment[][]; +}; +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare function encodedMap(map: TraceMap): EncodedSourceMap; +//# sourceMappingURL=trace-mapping.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/trace-mapping.d.mts.map b/node_modules/@jridgewell/trace-mapping/types/trace-mapping.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..b5a874c05a941f0f90a77a747f6ff27bd97200be --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/trace-mapping.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"trace-mapping.d.ts","sourceRoot":"","sources":["../src/trace-mapping.ts"],"names":[],"mappings":"AAuBA,OAAO,KAAK,EAAE,gBAAgB,EAAkB,MAAM,qBAAqB,CAAC;AAC5E,OAAO,KAAK,EACV,WAAW,EACX,gBAAgB,EAChB,gBAAgB,EAChB,sBAAsB,EACtB,eAAe,EACf,uBAAuB,EACvB,gBAAgB,EAChB,cAAc,EACd,MAAM,EACN,YAAY,EACZ,SAAS,EACT,WAAW,EAIX,EAAE,EACH,MAAM,SAAS,CAAC;AAIjB,YAAY,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAC5D,YAAY,EACV,SAAS,EACT,gBAAgB,EAChB,gBAAgB,EAChB,OAAO,EACP,kBAAkB,EAClB,WAAW,EACX,IAAI,EACJ,WAAW,EACX,gBAAgB,EAChB,uBAAuB,EACvB,sBAAsB,EACtB,MAAM,EACN,eAAe,EACf,eAAe,IAAI,OAAO,EAC1B,uBAAuB,EACvB,cAAc,EACd,YAAY,EACZ,MAAM,EACN,sBAAsB,EACtB,sBAAsB,EACtB,wBAAwB,EACxB,aAAa,GACd,MAAM,SAAS,CAAC;AAajB,eAAO,MAAM,iBAAiB,KAAK,CAAC;AACpC,eAAO,MAAM,oBAAoB,IAAI,CAAC;AAEtC,OAAO,EAAE,UAAU,EAAE,UAAU,IAAI,MAAM,EAAE,MAAM,eAAe,CAAC;AAEjE,qBAAa,QAAS,YAAW,SAAS;IAChC,OAAO,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BAAwB,CAAC,GAAG,EAAE,QAAQ,EAAE,MAAM,EAAE,YAAY,GAAG,gBAAgB,EAAE,CAIhG;AAED;;GAEG;AACH,wBAAgB,WAAW,CAAC,GAAG,EAAE,QAAQ,EAAE,EAAE,EAAE,CAAC,OAAO,EAAE,WAAW,KAAK,IAAI,GAAG,IAAI,CAgCnF;AASD;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAK7E;AAED;;GAEG;AACH,wBAAgB,SAAS,CAAC,GAAG,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAKhE;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,gBAAgB,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,QAAQ,CAIpF;AAED;;;GAGG;AACH,wBAAgB,UAAU,CACxB,GAAG,EAAE,QAAQ,GACZ,IAAI,CAAC,gBAAgB,EAAE,UAAU,CAAC,GAAG;IAAE,QAAQ,EAAE,SAAS,gBAAgB,EAAE,EAAE,CAAA;CAAE,CAElF;AAED;;;GAGG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,QAAQ,GAAG,gBAAgB,CAE1D"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/types.d.cts b/node_modules/@jridgewell/trace-mapping/types/types.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..729c2c3218138386b9ac9e462ed46b2503c2407d --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/types.d.cts @@ -0,0 +1,107 @@ +import type { SourceMapSegment } from './sourcemap-segment.cts'; +import type { GREATEST_LOWER_BOUND, LEAST_UPPER_BOUND, TraceMap } from './trace-mapping.cts'; +export interface SourceMapV3 { + file?: string | null; + names: string[]; + sourceRoot?: string; + sources: (string | null)[]; + sourcesContent?: (string | null)[]; + version: 3; + ignoreList?: number[]; +} +export interface EncodedSourceMap extends SourceMapV3 { + mappings: string; +} +export interface DecodedSourceMap extends SourceMapV3 { + mappings: SourceMapSegment[][]; +} +export interface Section { + offset: { + line: number; + column: number; + }; + map: EncodedSourceMap | DecodedSourceMap | SectionedSourceMap; +} +export interface SectionedSourceMap { + file?: string | null; + sections: Section[]; + version: 3; +} +export type OriginalMapping = { + source: string | null; + line: number; + column: number; + name: string | null; +}; +export type InvalidOriginalMapping = { + source: null; + line: null; + column: null; + name: null; +}; +export type GeneratedMapping = { + line: number; + column: number; +}; +export type InvalidGeneratedMapping = { + line: null; + column: null; +}; +export type Bias = typeof GREATEST_LOWER_BOUND | typeof LEAST_UPPER_BOUND; +export type XInput = { + x_google_ignoreList?: SourceMapV3['ignoreList']; +}; +export type EncodedSourceMapXInput = EncodedSourceMap & XInput; +export type DecodedSourceMapXInput = DecodedSourceMap & XInput; +export type SectionedSourceMapXInput = Omit & { + sections: SectionXInput[]; +}; +export type SectionXInput = Omit & { + map: SectionedSourceMapInput; +}; +export type SourceMapInput = string | EncodedSourceMapXInput | DecodedSourceMapXInput | TraceMap; +export type SectionedSourceMapInput = SourceMapInput | SectionedSourceMapXInput; +export type Needle = { + line: number; + column: number; + bias?: Bias; +}; +export type SourceNeedle = { + source: string; + line: number; + column: number; + bias?: Bias; +}; +export type EachMapping = { + generatedLine: number; + generatedColumn: number; + source: null; + originalLine: null; + originalColumn: null; + name: null; +} | { + generatedLine: number; + generatedColumn: number; + source: string | null; + originalLine: number; + originalColumn: number; + name: string | null; +}; +export declare abstract class SourceMap { + version: SourceMapV3['version']; + file: SourceMapV3['file']; + names: SourceMapV3['names']; + sourceRoot: SourceMapV3['sourceRoot']; + sources: SourceMapV3['sources']; + sourcesContent: SourceMapV3['sourcesContent']; + resolvedSources: SourceMapV3['sources']; + ignoreList: SourceMapV3['ignoreList']; +} +export type Ro = T extends Array ? V[] | Readonly | RoArray | Readonly> : T extends object ? T | Readonly | RoObject | Readonly> : T; +type RoArray = Ro[]; +type RoObject = { + [K in keyof T]: T[K] | Ro; +}; +export declare function parse(map: T): Exclude; +export {}; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/types.d.cts.map b/node_modules/@jridgewell/trace-mapping/types/types.d.cts.map new file mode 100644 index 0000000000000000000000000000000000000000..922478396d1e658b7b43c40a4e461bf1d3e327fd --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/types.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAC5D,OAAO,KAAK,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAEzF,MAAM,WAAW,WAAW;IAC1B,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE,CAAC,MAAM,GAAG,IAAI,CAAC,EAAE,CAAC;IAC3B,cAAc,CAAC,EAAE,CAAC,MAAM,GAAG,IAAI,CAAC,EAAE,CAAC;IACnC,OAAO,EAAE,CAAC,CAAC;IACX,UAAU,CAAC,EAAE,MAAM,EAAE,CAAC;CACvB;AAED,MAAM,WAAW,gBAAiB,SAAQ,WAAW;IACnD,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,gBAAiB,SAAQ,WAAW;IACnD,QAAQ,EAAE,gBAAgB,EAAE,EAAE,CAAC;CAChC;AAED,MAAM,WAAW,OAAO;IACtB,MAAM,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC;IACzC,GAAG,EAAE,gBAAgB,GAAG,gBAAgB,GAAG,kBAAkB,CAAC;CAC/D;AAED,MAAM,WAAW,kBAAkB;IACjC,IAAI,CAAC,EA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AAC,YAAY,CAAC,CAAC;CAC/C;AAED,MAAM,MAAM,EAAE,CAAC,CAAC,IACd,CAAC,SAAS,KAAK,CAAC,MAAM,CAAC,CAAC,GACpB,CAAC,EAAE,GAAG,QAAQ,CAAC,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,GACvD,CAAC,SAAS,MAAM,GACd,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,GACrD,CAAC,CAAC;AACV,KAAK,OAAO,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;AAC1B,KAAK,QAAQ,CAAC,CAAC,IAAI;KAAG,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;CAAE,CAAC;AAEvD,wBAAgB,KAAK,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,OAAO,CAAC,CAAC,EAAE,MAAM,CAAC,CAEnD"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/types.d.mts b/node_modules/@jridgewell/trace-mapping/types/types.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..a26d1866b4832bbce021f14bdcd28af6eb5db464 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/types.d.mts @@ -0,0 +1,107 @@ +import type { SourceMapSegment } from './sourcemap-segment.mts'; +import type { GREATEST_LOWER_BOUND, LEAST_UPPER_BOUND, TraceMap } from './trace-mapping.mts'; +export interface SourceMapV3 { + file?: string | null; + names: string[]; + sourceRoot?: string; + sources: (string | null)[]; + sourcesContent?: (string | null)[]; + version: 3; + ignoreList?: number[]; +} +export interface EncodedSourceMap extends SourceMapV3 { + mappings: string; +} +export interface DecodedSourceMap extends SourceMapV3 { + mappings: SourceMapSegment[][]; +} +export interface Section { + offset: { + line: number; + column: number; + }; + map: EncodedSourceMap | DecodedSourceMap | SectionedSourceMap; +} +export interface SectionedSourceMap { + file?: string | null; + sections: Section[]; + version: 3; +} +export type OriginalMapping = { + source: string | null; + line: number; + column: number; + name: string | null; +}; +export type InvalidOriginalMapping = { + source: null; + line: null; + column: null; + name: null; +}; +export type GeneratedMapping = { + line: number; + column: number; +}; +export type InvalidGeneratedMapping = { + line: null; + column: null; +}; +export type Bias = typeof GREATEST_LOWER_BOUND | typeof LEAST_UPPER_BOUND; +export type XInput = { + x_google_ignoreList?: SourceMapV3['ignoreList']; +}; +export type EncodedSourceMapXInput = EncodedSourceMap & XInput; +export type DecodedSourceMapXInput = DecodedSourceMap & XInput; +export type SectionedSourceMapXInput = Omit & { + sections: SectionXInput[]; +}; +export type SectionXInput = Omit & { + map: SectionedSourceMapInput; +}; +export type SourceMapInput = string | EncodedSourceMapXInput | DecodedSourceMapXInput | TraceMap; +export type SectionedSourceMapInput = SourceMapInput | SectionedSourceMapXInput; +export type Needle = { + line: number; + column: number; + bias?: Bias; +}; +export type SourceNeedle = { + source: string; + line: number; + column: number; + bias?: Bias; +}; +export type EachMapping = { + generatedLine: number; + generatedColumn: number; + source: null; + originalLine: null; + originalColumn: null; + name: null; +} | { + generatedLine: number; + generatedColumn: number; + source: string | null; + originalLine: number; + originalColumn: number; + name: string | null; +}; +export declare abstract class SourceMap { + version: SourceMapV3['version']; + file: SourceMapV3['file']; + names: SourceMapV3['names']; + sourceRoot: SourceMapV3['sourceRoot']; + sources: SourceMapV3['sources']; + sourcesContent: SourceMapV3['sourcesContent']; + resolvedSources: SourceMapV3['sources']; + ignoreList: SourceMapV3['ignoreList']; +} +export type Ro = T extends Array ? V[] | Readonly | RoArray | Readonly> : T extends object ? T | Readonly | RoObject | Readonly> : T; +type RoArray = Ro[]; +type RoObject = { + [K in keyof T]: T[K] | Ro; +}; +export declare function parse(map: T): Exclude; +export {}; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/types/types.d.mts.map b/node_modules/@jridgewell/trace-mapping/types/types.d.mts.map new file mode 100644 index 0000000000000000000000000000000000000000..922478396d1e658b7b43c40a4e461bf1d3e327fd --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/types/types.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAC5D,OAAO,KAAK,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAEzF,MAAM,WAAW,WAAW;IAC1B,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE,CAAC,MAAM,GAAG,IAAI,CAAC,EAAE,CAAC;IAC3B,cAAc,CAAC,EAAE,CAAC,MAAM,GAAG,IAAI,CAAC,EAAE,CAAC;IACnC,OAAO,EAAE,CAAC,CAAC;IACX,UAAU,CAAC,EAAE,MAAM,EAAE,CAAC;CACvB;AAED,MAAM,WAAW,gBAAiB,SAAQ,WAAW;IACnD,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,gBAAiB,SAAQ,WAAW;IACnD,QAAQ,EAAE,gBAAgB,EAAE,EAAE,CAAC;CAChC;AAED,MAAM,WAAW,OAAO;IACtB,MAAM,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC;IACzC,GAAG,EAAE,gBAAgB,GAAG,gBAAgB,GAAG,kBAAkB,CAAC;CAC/D;AAED,MAAM,WAAW,kBAAkB;IACjC,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,QAAQ,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MAAM,EAAE,CAAC,CAAC,IACd,CAAC,SAAS,KAAK,CAAC,MAAM,CAAC,CAAC,GACpB,CAAC,EAAE,GAAG,QAAQ,CAAC,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,GACvD,CAAC,SAAS,MAAM,GACd,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,GACrD,CAAC,CAAC;AACV,KAAK,OAAO,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;AAC1B,KAAK,QAAQ,CAAC,CAAC,IAAI;KAAG,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;CAAE,CAAC;AAEvD,wBAAgB,KAAK,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,OAAO,CAAC,CAAC,EAAE,MAAM,CAAC,CAEnD"} \ No newline at end of file diff --git a/node_modules/@levischuck/tiny-cbor/LICENSE b/node_modules/@levischuck/tiny-cbor/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..6c1cacac2eebd04903e265ac867a24590e925787 --- /dev/null +++ b/node_modules/@levischuck/tiny-cbor/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Levi + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@levischuck/tiny-cbor/README.md b/node_modules/@levischuck/tiny-cbor/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9687527232c83ca0044b1b17e14ac3567fbde02f --- /dev/null +++ b/node_modules/@levischuck/tiny-cbor/README.md @@ -0,0 +1,81 @@ +# Tiny CBOR + +[![](https://img.shields.io/github/actions/workflow/status/levischuck/tiny-cbor/build.yaml?branch=main&style=flat-square)](https://github.com/LeviSchuck/tiny-cbor/actions) +[![](https://img.shields.io/codecov/c/gh/levischuck/tiny-cbor?style=flat-square)](https://codecov.io/gh/levischuck/tiny-cbor) +[![](https://img.shields.io/github/v/tag/levischuck/tiny-cbor?label=npm&logo=npm&style=flat-square)](https://www.npmjs.com/package/@levischuck/tiny-cbor) +[![](https://img.shields.io/jsr/v/%40levischuck/tiny-cbor?style=flat-square&logo=jsr&label=JSR)](https://jsr.io/@levischuck/tiny-cbor) +[![](https://img.shields.io/github/license/levischuck/tiny-cbor?style=flat-square)](https://github.com/LeviSchuck/tiny-cbor/blob/main/LICENSE.txt) +![](https://img.shields.io/bundlephobia/min/%40levischuck/tiny-cbor?style=flat-square) + +This minimal generic library decodes and encodes most useful CBOR structures +into simple JavaScript structures: + +- Maps with keys as `string`s or `number`s with `CBORType` values as a `Map` +- Arrays of `CBORType` values +- integers as `number`s +- float32 and float64 as `number`s +- float16 `NaN`, `Infinity`, `-Infinity` +- `string`s +- byte strings as `Uint8Array` +- booleans +- `null` and `undefined` +- tags as `CBORTag(tag, value)` + +## Limitations + +This implementation does not support: + +- indefinite length maps, arrays, text strings, or byte strings. +- half precision floating point numbers +- integers outside the range of `[-9007199254740991, 9007199254740991]`, see + [Number.MAX_SAFE_INTEGER](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER) +- native output to JSON +- does not support generic objects, only `Map`s + +This implementation has the following constraints: + +- Map keys may only be strings or numbers +- Tags are not interpreted + +## Behavior + +Maps that have duplicate keys will throw an error during decoding. Decoding data +that is incomplete will throw an error during decoding. + +## Example + +```ts +// NPM +// import { decodeCBOR } from "@levischuck/tiny-cbor"; +// or JSR +// import { decodeCBOR } from "jsr:@levischuck/tiny-cbor"; +import { decodeCBOR } from "./index.ts"; +// Get your bytes somehow, directly or with decodeBase64 / decodeHex (available through @levischuck/tiny-encodings) +const HELLO_WORLD_BYTES = new Uint8Array([ + 107, // String wih length 11 + 104, // h + 101, // e + 108, // l + 108, // l + 111, // o + 32, // Space + 119, // w + 111, // o + 114, // r + 108, // l + 100, // d +]); +const helloWorld = decodeCBOR(HELLO_WORLD_BYTES); +if ("hello world" == helloWorld) { + console.log("Success!"); +} +``` + +## Where to get it + +This library is available on +[NPM](https://www.npmjs.com/package/@levischuck/tiny-cbor) and +[JSR](https://jsr.io/@levischuck/tiny-cbor). + +This library is no longer automatically published to Deno's Third Party Modules. +Newer versions may appear on deno.land/x, but do not work. diff --git a/node_modules/@levischuck/tiny-cbor/esm/cbor/cbor.d.ts b/node_modules/@levischuck/tiny-cbor/esm/cbor/cbor.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ab9189eac4c779cdd5b44f7b0132337989fc9983 --- /dev/null +++ b/node_modules/@levischuck/tiny-cbor/esm/cbor/cbor.d.ts @@ -0,0 +1,101 @@ +/** + * A value which is wrapped with a CBOR Tag. + * Several tags are registered with defined meanings like 0 for a date string. + * These meanings are **not interpreted** when decoded or encoded. + * + * This class is an immutable record. + * If the tag number or value needs to change, then construct a new tag + */ +export declare class CBORTag { + private tagId; + private tagValue; + /** + * Wrap a value with a tag number. + * When encoded, this tag will be attached to the value. + * + * @param tag Tag number + * @param value Wrapped value + */ + constructor(tag: number, value: CBORType); + /** + * Read the tag number + */ + get tag(): number; + /** + * Read the value + */ + get value(): CBORType; +} +/** + * Supported types which are encodable and decodable with tiny CBOR. + * Note that plain javascript objects are omitted. + */ +export type CBORType = number | bigint | string | Uint8Array | boolean | null | undefined | CBORType[] | CBORTag | Map; +/** + * Like {decodeCBOR}, but the length of the data is unknown and there is likely + * more -- possibly unrelated non-CBOR -- data afterwards. + * + * Examples: + * + * ```ts + * import {decodePartialCBOR} from './cbor.ts' + * decodePartialCBOR(new Uint8Array([1, 2, 245, 3, 4]), 2) + * // returns [true, 1] + * // It did not decode the leading [1, 2] or trailing [3, 4] + * ``` + * + * @param data a data stream to read data from + * @param index where to start reading in the data stream + * @returns a tuple of the value followed by bytes read. + * @throws {Error} + * When the data stream ends early or the CBOR data is not well formed + */ +export declare function decodePartialCBOR(data: DataView | Uint8Array | ArrayBuffer, index: number): [CBORType, number]; +/** + * Decode CBOR data from a binary stream + * + * The entire data stream from [0, length) will be consumed. + * If you require a partial decoding, see {decodePartialCBOR}. + * + * Examples: + * + * ```ts + * import {decodeCBOR, CBORTag, CBORType} from './cbor.ts' + * decodeCBOR(new Uint8Array([162, 99, 107, 101, 121, 101, 118, 97, 108, 117, 101, 1, 109, 97, 110, 111, 116, 104, 101, 114, 32, 118, 97, 108, 117, 101])); + * // returns new Map([ + * // ["key", "value"], + * // [1, "another value"] + * // ]); + * + * const taggedItem = new Uint8Array([217, 4, 210, 101, 104, 101, 108, 108, 111]); + * decodeCBOR(new DataView(taggedItem.buffer)) + * // returns new CBORTag(1234, "hello") + * ``` + * + * @param data a data stream, multiple types are supported + * @returns + */ +export declare function decodeCBOR(data: DataView | Uint8Array | ArrayBuffer): CBORType; +/** + * Encode a supported structure to a CBOR byte string. + * + * Example: + * + * ```ts + * import {encodeCBOR, CBORType, CBORTag} from './cbor.ts' + * encodeCBOR(new Map([ + * ["key", "value"], + * [1, "another value"] + * ])); + * // returns new Uint8Array([162, 99, 107, 101, 121, 101, 118, 97, 108, 117, 101, 1, 109, 97, 110, 111, 116, 104, 101, 114, 32 118, 97, 108, 117, 101]) + * + * encodeCBOR(new CBORTag(1234, "hello")) + * // returns new UInt8Array([217, 4, 210, 101, 104, 101, 108, 108, 111]) + * ``` + * + * @param data Data to encode + * @returns A byte string as a Uint8Array + * @throws Error + * if unsupported data is found during encoding + */ +export declare function encodeCBOR(data: CBORType): Uint8Array; diff --git a/node_modules/@levischuck/tiny-cbor/esm/cbor/cbor.js b/node_modules/@levischuck/tiny-cbor/esm/cbor/cbor.js new file mode 100644 index 0000000000000000000000000000000000000000..38b2f22b0f6c9cbbdeb297bd46c09b5b98bc321e --- /dev/null +++ b/node_modules/@levischuck/tiny-cbor/esm/cbor/cbor.js @@ -0,0 +1,440 @@ +import { decodeLength, encodeLength, MAJOR_TYPE_ARRAY, MAJOR_TYPE_BYTE_STRING, MAJOR_TYPE_MAP, MAJOR_TYPE_NEGATIVE_INTEGER, MAJOR_TYPE_SIMPLE_OR_FLOAT, MAJOR_TYPE_TAG, MAJOR_TYPE_TEXT_STRING, MAJOR_TYPE_UNSIGNED_INTEGER, } from "./cbor_internal.js"; +/** + * A value which is wrapped with a CBOR Tag. + * Several tags are registered with defined meanings like 0 for a date string. + * These meanings are **not interpreted** when decoded or encoded. + * + * This class is an immutable record. + * If the tag number or value needs to change, then construct a new tag + */ +export class CBORTag { + /** + * Wrap a value with a tag number. + * When encoded, this tag will be attached to the value. + * + * @param tag Tag number + * @param value Wrapped value + */ + constructor(tag, value) { + Object.defineProperty(this, "tagId", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "tagValue", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.tagId = tag; + this.tagValue = value; + } + /** + * Read the tag number + */ + get tag() { + return this.tagId; + } + /** + * Read the value + */ + get value() { + return this.tagValue; + } +} +function decodeUnsignedInteger(data, argument, index) { + return decodeLength(data, argument, index); +} +function decodeNegativeInteger(data, argument, index) { + const [value, length] = decodeUnsignedInteger(data, argument, index); + return [-value - 1, length]; +} +function decodeByteString(data, argument, index) { + const [lengthValue, lengthConsumed] = decodeLength(data, argument, index); + const dataStartIndex = index + lengthConsumed; + return [ + new Uint8Array(data.buffer.slice(dataStartIndex, dataStartIndex + lengthValue)), + lengthConsumed + lengthValue, + ]; +} +const TEXT_DECODER = new TextDecoder(); +function decodeString(data, argument, index) { + const [value, length] = decodeByteString(data, argument, index); + return [TEXT_DECODER.decode(value), length]; +} +function decodeArray(data, argument, index) { + if (argument === 0) { + return [[], 1]; + } + const [length, lengthConsumed] = decodeLength(data, argument, index); + let consumedLength = lengthConsumed; + const value = []; + for (let i = 0; i < length; i++) { + const remainingDataLength = data.byteLength - index - consumedLength; + if (remainingDataLength <= 0) { + throw new Error("array is not supported or well formed"); + } + const [decodedValue, consumed] = decodeNext(data, index + consumedLength); + value.push(decodedValue); + consumedLength += consumed; + } + return [value, consumedLength]; +} +const MAP_ERROR = "Map is not supported or well formed"; +function decodeMap(data, argument, index) { + if (argument === 0) { + return [new Map(), 1]; + } + const [length, lengthConsumed] = decodeLength(data, argument, index); + let consumedLength = lengthConsumed; + const result = new Map(); + for (let i = 0; i < length; i++) { + let remainingDataLength = data.byteLength - index - consumedLength; + if (remainingDataLength <= 0) { + throw new Error(MAP_ERROR); + } + // Load key + const [key, keyConsumed] = decodeNext(data, index + consumedLength); + consumedLength += keyConsumed; + remainingDataLength -= keyConsumed; + // Check that there's enough to have a value + if (remainingDataLength <= 0) { + throw new Error(MAP_ERROR); + } + // Technically CBOR maps can have any type as the key, and so can JS Maps + // However, JS Maps can only reference such keys as references which would + // require key iteration and pattern matching. + // For simplicity, since such keys are not in use with WebAuthn, this + // capability is not implemented and the types are restricted to strings + // and numbers. + if (typeof key !== "string" && typeof key !== "number") { + throw new Error(MAP_ERROR); + } + // CBOR Maps are not well formed if there are duplicate keys + if (result.has(key)) { + throw new Error(MAP_ERROR); + } + // Load value + const [value, valueConsumed] = decodeNext(data, index + consumedLength); + consumedLength += valueConsumed; + result.set(key, value); + } + return [result, consumedLength]; +} +function decodeFloat16(data, index) { + if (index + 3 > data.byteLength) { + throw new Error("CBOR stream ended before end of Float 16"); + } + // Skip the first byte + const result = data.getUint16(index + 1, false); + // A minimal selection of supported values + if (result == 0x7c00) { + return [Infinity, 3]; + } + else if (result == 0x7e00) { + return [NaN, 3]; + } + else if (result == 0xfc00) { + return [-Infinity, 3]; + } + throw new Error("Float16 data is unsupported"); +} +function decodeFloat32(data, index) { + if (index + 5 > data.byteLength) { + throw new Error("CBOR stream ended before end of Float 32"); + } + // Skip the first byte + const result = data.getFloat32(index + 1, false); + // First byte + 4 byte float + return [result, 5]; +} +function decodeFloat64(data, index) { + if (index + 9 > data.byteLength) { + throw new Error("CBOR stream ended before end of Float 64"); + } + // Skip the first byte + const result = data.getFloat64(index + 1, false); + // First byte + 8 byte float + return [result, 9]; +} +function decodeTag(data, argument, index) { + const [tag, tagBytes] = decodeLength(data, argument, index); + const [value, valueBytes] = decodeNext(data, index + tagBytes); + return [new CBORTag(tag, value), tagBytes + valueBytes]; +} +function decodeNext(data, index) { + if (index >= data.byteLength) { + throw new Error("CBOR stream ended before tag value"); + } + const byte = data.getUint8(index); + const majorType = byte >> 5; + const argument = byte & 0x1f; + switch (majorType) { + case MAJOR_TYPE_UNSIGNED_INTEGER: { + return decodeUnsignedInteger(data, argument, index); + } + case MAJOR_TYPE_NEGATIVE_INTEGER: { + return decodeNegativeInteger(data, argument, index); + } + case MAJOR_TYPE_BYTE_STRING: { + return decodeByteString(data, argument, index); + } + case MAJOR_TYPE_TEXT_STRING: { + return decodeString(data, argument, index); + } + case MAJOR_TYPE_ARRAY: { + return decodeArray(data, argument, index); + } + case MAJOR_TYPE_MAP: { + return decodeMap(data, argument, index); + } + case MAJOR_TYPE_TAG: { + return decodeTag(data, argument, index); + } + case MAJOR_TYPE_SIMPLE_OR_FLOAT: { + switch (argument) { + case 20: + return [false, 1]; + case 21: + return [true, 1]; + case 22: + return [null, 1]; + case 23: + return [undefined, 1]; + // 24: Simple value (value 32..255 in following byte) + case 25: // IEEE 754 Half-Precision Float (16 bits follow) + return decodeFloat16(data, index); + case 26: // IEEE 754 Single-Precision Float (32 bits follow) + return decodeFloat32(data, index); + case 27: // IEEE 754 Double-Precision Float (64 bits follow) + return decodeFloat64(data, index); + // 28-30: Reserved, not well-formed in the present document + // 31: "break" stop code for indefinite-length items + } + } + } + throw new Error(`Unsupported or not well formed at ${index}`); +} +function encodeSimple(data) { + if (data === true) { + return 0xf5; + } + else if (data === false) { + return 0xf4; + } + else if (data === null) { + return 0xf6; + } + // Else undefined + return 0xf7; +} +function encodeFloat(data) { + if (Math.fround(data) == data || !Number.isFinite(data) || Number.isNaN(data)) { + // Float32 + const output = new Uint8Array(5); + output[0] = 0xfa; + const view = new DataView(output.buffer); + view.setFloat32(1, data, false); + return output; + } + else { + // Float64 + const output = new Uint8Array(9); + output[0] = 0xfb; + const view = new DataView(output.buffer); + view.setFloat64(1, data, false); + return output; + } +} +function encodeNumber(data) { + if (typeof data == "number") { + if (Number.isSafeInteger(data)) { + // Encode integer + if (data < 0) { + return encodeLength(MAJOR_TYPE_NEGATIVE_INTEGER, Math.abs(data)); + } + else { + return encodeLength(MAJOR_TYPE_UNSIGNED_INTEGER, data); + } + } + return [encodeFloat(data)]; + } + else { + if (data < 0n) { + return encodeLength(MAJOR_TYPE_NEGATIVE_INTEGER, data * -1n); + } + else { + return encodeLength(MAJOR_TYPE_UNSIGNED_INTEGER, data); + } + } +} +const ENCODER = new TextEncoder(); +function encodeString(data, output) { + output.push(...encodeLength(MAJOR_TYPE_TEXT_STRING, data.length)); + output.push(ENCODER.encode(data)); +} +function encodeBytes(data, output) { + output.push(...encodeLength(MAJOR_TYPE_BYTE_STRING, data.length)); + output.push(data); +} +function encodeArray(data, output) { + output.push(...encodeLength(MAJOR_TYPE_ARRAY, data.length)); + for (const element of data) { + encodePartialCBOR(element, output); + } +} +function encodeMap(data, output) { + output.push(new Uint8Array(encodeLength(MAJOR_TYPE_MAP, data.size))); + for (const [key, value] of data.entries()) { + encodePartialCBOR(key, output); + encodePartialCBOR(value, output); + } +} +function encodeTag(tag, output) { + output.push(...encodeLength(MAJOR_TYPE_TAG, tag.tag)); + encodePartialCBOR(tag.value, output); +} +function encodePartialCBOR(data, output) { + if (typeof data == "boolean" || data === null || data == undefined) { + output.push(encodeSimple(data)); + return; + } + if (typeof data == "number" || typeof data == "bigint") { + output.push(...encodeNumber(data)); + return; + } + if (typeof data == "string") { + encodeString(data, output); + return; + } + if (data instanceof Uint8Array) { + encodeBytes(data, output); + return; + } + if (Array.isArray(data)) { + encodeArray(data, output); + return; + } + if (data instanceof Map) { + encodeMap(data, output); + return; + } + if (data instanceof CBORTag) { + encodeTag(data, output); + return; + } + throw new Error("Not implemented"); +} +/** + * Like {decodeCBOR}, but the length of the data is unknown and there is likely + * more -- possibly unrelated non-CBOR -- data afterwards. + * + * Examples: + * + * ```ts + * import {decodePartialCBOR} from './cbor.ts' + * decodePartialCBOR(new Uint8Array([1, 2, 245, 3, 4]), 2) + * // returns [true, 1] + * // It did not decode the leading [1, 2] or trailing [3, 4] + * ``` + * + * @param data a data stream to read data from + * @param index where to start reading in the data stream + * @returns a tuple of the value followed by bytes read. + * @throws {Error} + * When the data stream ends early or the CBOR data is not well formed + */ +export function decodePartialCBOR(data, index) { + if (data.byteLength === 0 || data.byteLength <= index || index < 0) { + throw new Error("No data"); + } + if (data instanceof Uint8Array) { + return decodeNext(new DataView(data.buffer), index); + } + else if (data instanceof ArrayBuffer) { + return decodeNext(new DataView(data), index); + } + // otherwise, it is a data view + return decodeNext(data, index); +} +/** + * Decode CBOR data from a binary stream + * + * The entire data stream from [0, length) will be consumed. + * If you require a partial decoding, see {decodePartialCBOR}. + * + * Examples: + * + * ```ts + * import {decodeCBOR, CBORTag, CBORType} from './cbor.ts' + * decodeCBOR(new Uint8Array([162, 99, 107, 101, 121, 101, 118, 97, 108, 117, 101, 1, 109, 97, 110, 111, 116, 104, 101, 114, 32, 118, 97, 108, 117, 101])); + * // returns new Map([ + * // ["key", "value"], + * // [1, "another value"] + * // ]); + * + * const taggedItem = new Uint8Array([217, 4, 210, 101, 104, 101, 108, 108, 111]); + * decodeCBOR(new DataView(taggedItem.buffer)) + * // returns new CBORTag(1234, "hello") + * ``` + * + * @param data a data stream, multiple types are supported + * @returns + */ +export function decodeCBOR(data) { + const [value, length] = decodePartialCBOR(data, 0); + if (length !== data.byteLength) { + throw new Error(`Data was decoded, but the whole stream was not processed ${length} != ${data.byteLength}`); + } + return value; +} +/** + * Encode a supported structure to a CBOR byte string. + * + * Example: + * + * ```ts + * import {encodeCBOR, CBORType, CBORTag} from './cbor.ts' + * encodeCBOR(new Map([ + * ["key", "value"], + * [1, "another value"] + * ])); + * // returns new Uint8Array([162, 99, 107, 101, 121, 101, 118, 97, 108, 117, 101, 1, 109, 97, 110, 111, 116, 104, 101, 114, 32 118, 97, 108, 117, 101]) + * + * encodeCBOR(new CBORTag(1234, "hello")) + * // returns new UInt8Array([217, 4, 210, 101, 104, 101, 108, 108, 111]) + * ``` + * + * @param data Data to encode + * @returns A byte string as a Uint8Array + * @throws Error + * if unsupported data is found during encoding + */ +export function encodeCBOR(data) { + const results = []; + encodePartialCBOR(data, results); + let length = 0; + for (const result of results) { + if (typeof result == "number") { + length += 1; + } + else { + length += result.length; + } + } + const output = new Uint8Array(length); + let index = 0; + for (const result of results) { + if (typeof result == "number") { + output[index] = result; + index += 1; + } + else { + output.set(result, index); + index += result.length; + } + } + return output; +} diff --git a/node_modules/@levischuck/tiny-cbor/esm/cbor/cbor_internal.d.ts b/node_modules/@levischuck/tiny-cbor/esm/cbor/cbor_internal.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c726300faa8bea5978d9c33c374fec0664679251 --- /dev/null +++ b/node_modules/@levischuck/tiny-cbor/esm/cbor/cbor_internal.d.ts @@ -0,0 +1,11 @@ +export declare function decodeLength(data: DataView, argument: number, index: number): [number, number]; +export type MajorType = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7; +export declare const MAJOR_TYPE_UNSIGNED_INTEGER: MajorType; +export declare const MAJOR_TYPE_NEGATIVE_INTEGER: MajorType; +export declare const MAJOR_TYPE_BYTE_STRING: MajorType; +export declare const MAJOR_TYPE_TEXT_STRING: MajorType; +export declare const MAJOR_TYPE_ARRAY: MajorType; +export declare const MAJOR_TYPE_MAP: MajorType; +export declare const MAJOR_TYPE_TAG: MajorType; +export declare const MAJOR_TYPE_SIMPLE_OR_FLOAT: MajorType; +export declare function encodeLength(major: MajorType, argument: number | bigint): number[]; diff --git a/node_modules/@levischuck/tiny-cbor/esm/cbor/cbor_internal.js b/node_modules/@levischuck/tiny-cbor/esm/cbor/cbor_internal.js new file mode 100644 index 0000000000000000000000000000000000000000..2ce5b06e40ade053faa0581fbf1663fe1c06476a --- /dev/null +++ b/node_modules/@levischuck/tiny-cbor/esm/cbor/cbor_internal.js @@ -0,0 +1,111 @@ +export function decodeLength(data, argument, index) { + if (argument < 24) { + return [argument, 1]; + } + const remainingDataLength = data.byteLength - index - 1; + const view = new DataView(data.buffer, index + 1); + let output; + let bytes = 0; + switch (argument) { + case 24: { + if (remainingDataLength > 0) { + output = view.getUint8(0); + bytes = 2; + } + break; + } + case 25: { + if (remainingDataLength > 1) { + output = view.getUint16(0, false); + bytes = 3; + } + break; + } + case 26: { + if (remainingDataLength > 3) { + output = view.getUint32(0, false); + bytes = 5; + } + break; + } + case 27: { + if (remainingDataLength > 7) { + const bigOutput = view.getBigUint64(0, false); + // Bound it to [24, MAX_SAFE_INTEGER], where it is safe + // to encode as a javascript number + if (bigOutput >= 24n && bigOutput <= Number.MAX_SAFE_INTEGER) { + return [Number(bigOutput), 9]; + } + } + break; + } + } + if (output && output >= 24) { + return [output, bytes]; + } + throw new Error("Length not supported or not well formed"); +} +export const MAJOR_TYPE_UNSIGNED_INTEGER = 0; +export const MAJOR_TYPE_NEGATIVE_INTEGER = 1; +export const MAJOR_TYPE_BYTE_STRING = 2; +export const MAJOR_TYPE_TEXT_STRING = 3; +export const MAJOR_TYPE_ARRAY = 4; +export const MAJOR_TYPE_MAP = 5; +export const MAJOR_TYPE_TAG = 6; +export const MAJOR_TYPE_SIMPLE_OR_FLOAT = 7; +export function encodeLength(major, argument) { + const majorEncoded = major << 5; + if (argument < 0) { + throw new Error("CBOR Data Item argument must not be negative"); + } + // Convert to bigint first. + // Encode integers around and above 32 bits in big endian / network byte order + // is unreliable in javascript. + // https://tc39.es/ecma262/#sec-bitwise-shift-operators + // Bit shifting operations result in 32 bit signed numbers + let bigintArgument; + if (typeof argument == "number") { + if (!Number.isInteger(argument)) { + throw new Error("CBOR Data Item argument must be an integer"); + } + bigintArgument = BigInt(argument); + } + else { + bigintArgument = argument; + } + // Negative 0 is not a thing + if (major == MAJOR_TYPE_NEGATIVE_INTEGER) { + if (bigintArgument == 0n) { + throw new Error("CBOR Data Item argument cannot be zero when negative"); + } + bigintArgument = bigintArgument - 1n; + } + if (bigintArgument > 18446744073709551615n) { + throw new Error("CBOR number out of range"); + } + // Encode into 64 bits and extract the tail + const buffer = new Uint8Array(8); + const view = new DataView(buffer.buffer); + view.setBigUint64(0, bigintArgument, false); + if (bigintArgument <= 23) { + return [majorEncoded | buffer[7]]; + } + else if (bigintArgument <= 255) { + return [majorEncoded | 24, buffer[7]]; + } + else if (bigintArgument <= 65535) { + return [majorEncoded | 25, ...buffer.slice(6)]; + } + else if (bigintArgument <= 4294967295) { + return [ + majorEncoded | 26, + ...buffer.slice(4), + ]; + } + else { + return [ + majorEncoded | 27, + ...buffer, + ]; + } +} diff --git a/node_modules/@levischuck/tiny-cbor/esm/index.d.ts b/node_modules/@levischuck/tiny-cbor/esm/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c95cd38f9aa7aa262fd194342ea62cdaa38a09dc --- /dev/null +++ b/node_modules/@levischuck/tiny-cbor/esm/index.d.ts @@ -0,0 +1,2 @@ +export { CBORTag, decodeCBOR, decodePartialCBOR, encodeCBOR, } from "./cbor/cbor.js"; +export type { CBORType } from "./cbor/cbor.js"; diff --git a/node_modules/@levischuck/tiny-cbor/esm/index.js b/node_modules/@levischuck/tiny-cbor/esm/index.js new file mode 100644 index 0000000000000000000000000000000000000000..9fcfd93055e8a9a9db9773bc89599018c0517d58 --- /dev/null +++ b/node_modules/@levischuck/tiny-cbor/esm/index.js @@ -0,0 +1 @@ +export { CBORTag, decodeCBOR, decodePartialCBOR, encodeCBOR, } from "./cbor/cbor.js"; diff --git a/node_modules/@levischuck/tiny-cbor/esm/package.json b/node_modules/@levischuck/tiny-cbor/esm/package.json new file mode 100644 index 0000000000000000000000000000000000000000..3dbc1ca591c0557e35b6004aeba250e6a70b56e3 --- /dev/null +++ b/node_modules/@levischuck/tiny-cbor/esm/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/node_modules/@levischuck/tiny-cbor/package.json b/node_modules/@levischuck/tiny-cbor/package.json new file mode 100644 index 0000000000000000000000000000000000000000..e1971c65fe9cc16bfd8ca43cf523bf55f1a56138 --- /dev/null +++ b/node_modules/@levischuck/tiny-cbor/package.json @@ -0,0 +1,25 @@ +{ + "name": "@levischuck/tiny-cbor", + "version": "0.2.11", + "description": "Tiny CBOR library", + "repository": { + "type": "git", + "url": "git+https://github.com/levischuck/tiny-cbor.git" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/levischuck/tiny-cbor/issues" + }, + "main": "./script/index.js", + "module": "./esm/index.js", + "exports": { + ".": { + "import": "./esm/index.js", + "require": "./script/index.js" + } + }, + "devDependencies": { + "@types/node": "^20.9.0" + }, + "_generatedBy": "dnt@0.40.0" +} \ No newline at end of file diff --git a/node_modules/@levischuck/tiny-cbor/script/cbor/cbor.d.ts b/node_modules/@levischuck/tiny-cbor/script/cbor/cbor.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ab9189eac4c779cdd5b44f7b0132337989fc9983 --- /dev/null +++ b/node_modules/@levischuck/tiny-cbor/script/cbor/cbor.d.ts @@ -0,0 +1,101 @@ +/** + * A value which is wrapped with a CBOR Tag. + * Several tags are registered with defined meanings like 0 for a date string. + * These meanings are **not interpreted** when decoded or encoded. + * + * This class is an immutable record. + * If the tag number or value needs to change, then construct a new tag + */ +export declare class CBORTag { + private tagId; + private tagValue; + /** + * Wrap a value with a tag number. + * When encoded, this tag will be attached to the value. + * + * @param tag Tag number + * @param value Wrapped value + */ + constructor(tag: number, value: CBORType); + /** + * Read the tag number + */ + get tag(): number; + /** + * Read the value + */ + get value(): CBORType; +} +/** + * Supported types which are encodable and decodable with tiny CBOR. + * Note that plain javascript objects are omitted. + */ +export type CBORType = number | bigint | string | Uint8Array | boolean | null | undefined | CBORType[] | CBORTag | Map; +/** + * Like {decodeCBOR}, but the length of the data is unknown and there is likely + * more -- possibly unrelated non-CBOR -- data afterwards. + * + * Examples: + * + * ```ts + * import {decodePartialCBOR} from './cbor.ts' + * decodePartialCBOR(new Uint8Array([1, 2, 245, 3, 4]), 2) + * // returns [true, 1] + * // It did not decode the leading [1, 2] or trailing [3, 4] + * ``` + * + * @param data a data stream to read data from + * @param index where to start reading in the data stream + * @returns a tuple of the value followed by bytes read. + * @throws {Error} + * When the data stream ends early or the CBOR data is not well formed + */ +export declare function decodePartialCBOR(data: DataView | Uint8Array | ArrayBuffer, index: number): [CBORType, number]; +/** + * Decode CBOR data from a binary stream + * + * The entire data stream from [0, length) will be consumed. + * If you require a partial decoding, see {decodePartialCBOR}. + * + * Examples: + * + * ```ts + * import {decodeCBOR, CBORTag, CBORType} from './cbor.ts' + * decodeCBOR(new Uint8Array([162, 99, 107, 101, 121, 101, 118, 97, 108, 117, 101, 1, 109, 97, 110, 111, 116, 104, 101, 114, 32, 118, 97, 108, 117, 101])); + * // returns new Map([ + * // ["key", "value"], + * // [1, "another value"] + * // ]); + * + * const taggedItem = new Uint8Array([217, 4, 210, 101, 104, 101, 108, 108, 111]); + * decodeCBOR(new DataView(taggedItem.buffer)) + * // returns new CBORTag(1234, "hello") + * ``` + * + * @param data a data stream, multiple types are supported + * @returns + */ +export declare function decodeCBOR(data: DataView | Uint8Array | ArrayBuffer): CBORType; +/** + * Encode a supported structure to a CBOR byte string. + * + * Example: + * + * ```ts + * import {encodeCBOR, CBORType, CBORTag} from './cbor.ts' + * encodeCBOR(new Map([ + * ["key", "value"], + * [1, "another value"] + * ])); + * // returns new Uint8Array([162, 99, 107, 101, 121, 101, 118, 97, 108, 117, 101, 1, 109, 97, 110, 111, 116, 104, 101, 114, 32 118, 97, 108, 117, 101]) + * + * encodeCBOR(new CBORTag(1234, "hello")) + * // returns new UInt8Array([217, 4, 210, 101, 104, 101, 108, 108, 111]) + * ``` + * + * @param data Data to encode + * @returns A byte string as a Uint8Array + * @throws Error + * if unsupported data is found during encoding + */ +export declare function encodeCBOR(data: CBORType): Uint8Array; diff --git a/node_modules/@levischuck/tiny-cbor/script/cbor/cbor.js b/node_modules/@levischuck/tiny-cbor/script/cbor/cbor.js new file mode 100644 index 0000000000000000000000000000000000000000..40a9941baca2dee9c7f1b1e310d4be4cc5287b59 --- /dev/null +++ b/node_modules/@levischuck/tiny-cbor/script/cbor/cbor.js @@ -0,0 +1,447 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.encodeCBOR = exports.decodeCBOR = exports.decodePartialCBOR = exports.CBORTag = void 0; +const cbor_internal_js_1 = require("./cbor_internal.js"); +/** + * A value which is wrapped with a CBOR Tag. + * Several tags are registered with defined meanings like 0 for a date string. + * These meanings are **not interpreted** when decoded or encoded. + * + * This class is an immutable record. + * If the tag number or value needs to change, then construct a new tag + */ +class CBORTag { + /** + * Wrap a value with a tag number. + * When encoded, this tag will be attached to the value. + * + * @param tag Tag number + * @param value Wrapped value + */ + constructor(tag, value) { + Object.defineProperty(this, "tagId", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "tagValue", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.tagId = tag; + this.tagValue = value; + } + /** + * Read the tag number + */ + get tag() { + return this.tagId; + } + /** + * Read the value + */ + get value() { + return this.tagValue; + } +} +exports.CBORTag = CBORTag; +function decodeUnsignedInteger(data, argument, index) { + return (0, cbor_internal_js_1.decodeLength)(data, argument, index); +} +function decodeNegativeInteger(data, argument, index) { + const [value, length] = decodeUnsignedInteger(data, argument, index); + return [-value - 1, length]; +} +function decodeByteString(data, argument, index) { + const [lengthValue, lengthConsumed] = (0, cbor_internal_js_1.decodeLength)(data, argument, index); + const dataStartIndex = index + lengthConsumed; + return [ + new Uint8Array(data.buffer.slice(dataStartIndex, dataStartIndex + lengthValue)), + lengthConsumed + lengthValue, + ]; +} +const TEXT_DECODER = new TextDecoder(); +function decodeString(data, argument, index) { + const [value, length] = decodeByteString(data, argument, index); + return [TEXT_DECODER.decode(value), length]; +} +function decodeArray(data, argument, index) { + if (argument === 0) { + return [[], 1]; + } + const [length, lengthConsumed] = (0, cbor_internal_js_1.decodeLength)(data, argument, index); + let consumedLength = lengthConsumed; + const value = []; + for (let i = 0; i < length; i++) { + const remainingDataLength = data.byteLength - index - consumedLength; + if (remainingDataLength <= 0) { + throw new Error("array is not supported or well formed"); + } + const [decodedValue, consumed] = decodeNext(data, index + consumedLength); + value.push(decodedValue); + consumedLength += consumed; + } + return [value, consumedLength]; +} +const MAP_ERROR = "Map is not supported or well formed"; +function decodeMap(data, argument, index) { + if (argument === 0) { + return [new Map(), 1]; + } + const [length, lengthConsumed] = (0, cbor_internal_js_1.decodeLength)(data, argument, index); + let consumedLength = lengthConsumed; + const result = new Map(); + for (let i = 0; i < length; i++) { + let remainingDataLength = data.byteLength - index - consumedLength; + if (remainingDataLength <= 0) { + throw new Error(MAP_ERROR); + } + // Load key + const [key, keyConsumed] = decodeNext(data, index + consumedLength); + consumedLength += keyConsumed; + remainingDataLength -= keyConsumed; + // Check that there's enough to have a value + if (remainingDataLength <= 0) { + throw new Error(MAP_ERROR); + } + // Technically CBOR maps can have any type as the key, and so can JS Maps + // However, JS Maps can only reference such keys as references which would + // require key iteration and pattern matching. + // For simplicity, since such keys are not in use with WebAuthn, this + // capability is not implemented and the types are restricted to strings + // and numbers. + if (typeof key !== "string" && typeof key !== "number") { + throw new Error(MAP_ERROR); + } + // CBOR Maps are not well formed if there are duplicate keys + if (result.has(key)) { + throw new Error(MAP_ERROR); + } + // Load value + const [value, valueConsumed] = decodeNext(data, index + consumedLength); + consumedLength += valueConsumed; + result.set(key, value); + } + return [result, consumedLength]; +} +function decodeFloat16(data, index) { + if (index + 3 > data.byteLength) { + throw new Error("CBOR stream ended before end of Float 16"); + } + // Skip the first byte + const result = data.getUint16(index + 1, false); + // A minimal selection of supported values + if (result == 0x7c00) { + return [Infinity, 3]; + } + else if (result == 0x7e00) { + return [NaN, 3]; + } + else if (result == 0xfc00) { + return [-Infinity, 3]; + } + throw new Error("Float16 data is unsupported"); +} +function decodeFloat32(data, index) { + if (index + 5 > data.byteLength) { + throw new Error("CBOR stream ended before end of Float 32"); + } + // Skip the first byte + const result = data.getFloat32(index + 1, false); + // First byte + 4 byte float + return [result, 5]; +} +function decodeFloat64(data, index) { + if (index + 9 > data.byteLength) { + throw new Error("CBOR stream ended before end of Float 64"); + } + // Skip the first byte + const result = data.getFloat64(index + 1, false); + // First byte + 8 byte float + return [result, 9]; +} +function decodeTag(data, argument, index) { + const [tag, tagBytes] = (0, cbor_internal_js_1.decodeLength)(data, argument, index); + const [value, valueBytes] = decodeNext(data, index + tagBytes); + return [new CBORTag(tag, value), tagBytes + valueBytes]; +} +function decodeNext(data, index) { + if (index >= data.byteLength) { + throw new Error("CBOR stream ended before tag value"); + } + const byte = data.getUint8(index); + const majorType = byte >> 5; + const argument = byte & 0x1f; + switch (majorType) { + case cbor_internal_js_1.MAJOR_TYPE_UNSIGNED_INTEGER: { + return decodeUnsignedInteger(data, argument, index); + } + case cbor_internal_js_1.MAJOR_TYPE_NEGATIVE_INTEGER: { + return decodeNegativeInteger(data, argument, index); + } + case cbor_internal_js_1.MAJOR_TYPE_BYTE_STRING: { + return decodeByteString(data, argument, index); + } + case cbor_internal_js_1.MAJOR_TYPE_TEXT_STRING: { + return decodeString(data, argument, index); + } + case cbor_internal_js_1.MAJOR_TYPE_ARRAY: { + return decodeArray(data, argument, index); + } + case cbor_internal_js_1.MAJOR_TYPE_MAP: { + return decodeMap(data, argument, index); + } + case cbor_internal_js_1.MAJOR_TYPE_TAG: { + return decodeTag(data, argument, index); + } + case cbor_internal_js_1.MAJOR_TYPE_SIMPLE_OR_FLOAT: { + switch (argument) { + case 20: + return [false, 1]; + case 21: + return [true, 1]; + case 22: + return [null, 1]; + case 23: + return [undefined, 1]; + // 24: Simple value (value 32..255 in following byte) + case 25: // IEEE 754 Half-Precision Float (16 bits follow) + return decodeFloat16(data, index); + case 26: // IEEE 754 Single-Precision Float (32 bits follow) + return decodeFloat32(data, index); + case 27: // IEEE 754 Double-Precision Float (64 bits follow) + return decodeFloat64(data, index); + // 28-30: Reserved, not well-formed in the present document + // 31: "break" stop code for indefinite-length items + } + } + } + throw new Error(`Unsupported or not well formed at ${index}`); +} +function encodeSimple(data) { + if (data === true) { + return 0xf5; + } + else if (data === false) { + return 0xf4; + } + else if (data === null) { + return 0xf6; + } + // Else undefined + return 0xf7; +} +function encodeFloat(data) { + if (Math.fround(data) == data || !Number.isFinite(data) || Number.isNaN(data)) { + // Float32 + const output = new Uint8Array(5); + output[0] = 0xfa; + const view = new DataView(output.buffer); + view.setFloat32(1, data, false); + return output; + } + else { + // Float64 + const output = new Uint8Array(9); + output[0] = 0xfb; + const view = new DataView(output.buffer); + view.setFloat64(1, data, false); + return output; + } +} +function encodeNumber(data) { + if (typeof data == "number") { + if (Number.isSafeInteger(data)) { + // Encode integer + if (data < 0) { + return (0, cbor_internal_js_1.encodeLength)(cbor_internal_js_1.MAJOR_TYPE_NEGATIVE_INTEGER, Math.abs(data)); + } + else { + return (0, cbor_internal_js_1.encodeLength)(cbor_internal_js_1.MAJOR_TYPE_UNSIGNED_INTEGER, data); + } + } + return [encodeFloat(data)]; + } + else { + if (data < 0n) { + return (0, cbor_internal_js_1.encodeLength)(cbor_internal_js_1.MAJOR_TYPE_NEGATIVE_INTEGER, data * -1n); + } + else { + return (0, cbor_internal_js_1.encodeLength)(cbor_internal_js_1.MAJOR_TYPE_UNSIGNED_INTEGER, data); + } + } +} +const ENCODER = new TextEncoder(); +function encodeString(data, output) { + output.push(...(0, cbor_internal_js_1.encodeLength)(cbor_internal_js_1.MAJOR_TYPE_TEXT_STRING, data.length)); + output.push(ENCODER.encode(data)); +} +function encodeBytes(data, output) { + output.push(...(0, cbor_internal_js_1.encodeLength)(cbor_internal_js_1.MAJOR_TYPE_BYTE_STRING, data.length)); + output.push(data); +} +function encodeArray(data, output) { + output.push(...(0, cbor_internal_js_1.encodeLength)(cbor_internal_js_1.MAJOR_TYPE_ARRAY, data.length)); + for (const element of data) { + encodePartialCBOR(element, output); + } +} +function encodeMap(data, output) { + output.push(new Uint8Array((0, cbor_internal_js_1.encodeLength)(cbor_internal_js_1.MAJOR_TYPE_MAP, data.size))); + for (const [key, value] of data.entries()) { + encodePartialCBOR(key, output); + encodePartialCBOR(value, output); + } +} +function encodeTag(tag, output) { + output.push(...(0, cbor_internal_js_1.encodeLength)(cbor_internal_js_1.MAJOR_TYPE_TAG, tag.tag)); + encodePartialCBOR(tag.value, output); +} +function encodePartialCBOR(data, output) { + if (typeof data == "boolean" || data === null || data == undefined) { + output.push(encodeSimple(data)); + return; + } + if (typeof data == "number" || typeof data == "bigint") { + output.push(...encodeNumber(data)); + return; + } + if (typeof data == "string") { + encodeString(data, output); + return; + } + if (data instanceof Uint8Array) { + encodeBytes(data, output); + return; + } + if (Array.isArray(data)) { + encodeArray(data, output); + return; + } + if (data instanceof Map) { + encodeMap(data, output); + return; + } + if (data instanceof CBORTag) { + encodeTag(data, output); + return; + } + throw new Error("Not implemented"); +} +/** + * Like {decodeCBOR}, but the length of the data is unknown and there is likely + * more -- possibly unrelated non-CBOR -- data afterwards. + * + * Examples: + * + * ```ts + * import {decodePartialCBOR} from './cbor.ts' + * decodePartialCBOR(new Uint8Array([1, 2, 245, 3, 4]), 2) + * // returns [true, 1] + * // It did not decode the leading [1, 2] or trailing [3, 4] + * ``` + * + * @param data a data stream to read data from + * @param index where to start reading in the data stream + * @returns a tuple of the value followed by bytes read. + * @throws {Error} + * When the data stream ends early or the CBOR data is not well formed + */ +function decodePartialCBOR(data, index) { + if (data.byteLength === 0 || data.byteLength <= index || index < 0) { + throw new Error("No data"); + } + if (data instanceof Uint8Array) { + return decodeNext(new DataView(data.buffer), index); + } + else if (data instanceof ArrayBuffer) { + return decodeNext(new DataView(data), index); + } + // otherwise, it is a data view + return decodeNext(data, index); +} +exports.decodePartialCBOR = decodePartialCBOR; +/** + * Decode CBOR data from a binary stream + * + * The entire data stream from [0, length) will be consumed. + * If you require a partial decoding, see {decodePartialCBOR}. + * + * Examples: + * + * ```ts + * import {decodeCBOR, CBORTag, CBORType} from './cbor.ts' + * decodeCBOR(new Uint8Array([162, 99, 107, 101, 121, 101, 118, 97, 108, 117, 101, 1, 109, 97, 110, 111, 116, 104, 101, 114, 32, 118, 97, 108, 117, 101])); + * // returns new Map([ + * // ["key", "value"], + * // [1, "another value"] + * // ]); + * + * const taggedItem = new Uint8Array([217, 4, 210, 101, 104, 101, 108, 108, 111]); + * decodeCBOR(new DataView(taggedItem.buffer)) + * // returns new CBORTag(1234, "hello") + * ``` + * + * @param data a data stream, multiple types are supported + * @returns + */ +function decodeCBOR(data) { + const [value, length] = decodePartialCBOR(data, 0); + if (length !== data.byteLength) { + throw new Error(`Data was decoded, but the whole stream was not processed ${length} != ${data.byteLength}`); + } + return value; +} +exports.decodeCBOR = decodeCBOR; +/** + * Encode a supported structure to a CBOR byte string. + * + * Example: + * + * ```ts + * import {encodeCBOR, CBORType, CBORTag} from './cbor.ts' + * encodeCBOR(new Map([ + * ["key", "value"], + * [1, "another value"] + * ])); + * // returns new Uint8Array([162, 99, 107, 101, 121, 101, 118, 97, 108, 117, 101, 1, 109, 97, 110, 111, 116, 104, 101, 114, 32 118, 97, 108, 117, 101]) + * + * encodeCBOR(new CBORTag(1234, "hello")) + * // returns new UInt8Array([217, 4, 210, 101, 104, 101, 108, 108, 111]) + * ``` + * + * @param data Data to encode + * @returns A byte string as a Uint8Array + * @throws Error + * if unsupported data is found during encoding + */ +function encodeCBOR(data) { + const results = []; + encodePartialCBOR(data, results); + let length = 0; + for (const result of results) { + if (typeof result == "number") { + length += 1; + } + else { + length += result.length; + } + } + const output = new Uint8Array(length); + let index = 0; + for (const result of results) { + if (typeof result == "number") { + output[index] = result; + index += 1; + } + else { + output.set(result, index); + index += result.length; + } + } + return output; +} +exports.encodeCBOR = encodeCBOR; diff --git a/node_modules/@levischuck/tiny-cbor/script/cbor/cbor_internal.d.ts b/node_modules/@levischuck/tiny-cbor/script/cbor/cbor_internal.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c726300faa8bea5978d9c33c374fec0664679251 --- /dev/null +++ b/node_modules/@levischuck/tiny-cbor/script/cbor/cbor_internal.d.ts @@ -0,0 +1,11 @@ +export declare function decodeLength(data: DataView, argument: number, index: number): [number, number]; +export type MajorType = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7; +export declare const MAJOR_TYPE_UNSIGNED_INTEGER: MajorType; +export declare const MAJOR_TYPE_NEGATIVE_INTEGER: MajorType; +export declare const MAJOR_TYPE_BYTE_STRING: MajorType; +export declare const MAJOR_TYPE_TEXT_STRING: MajorType; +export declare const MAJOR_TYPE_ARRAY: MajorType; +export declare const MAJOR_TYPE_MAP: MajorType; +export declare const MAJOR_TYPE_TAG: MajorType; +export declare const MAJOR_TYPE_SIMPLE_OR_FLOAT: MajorType; +export declare function encodeLength(major: MajorType, argument: number | bigint): number[]; diff --git a/node_modules/@levischuck/tiny-cbor/script/cbor/cbor_internal.js b/node_modules/@levischuck/tiny-cbor/script/cbor/cbor_internal.js new file mode 100644 index 0000000000000000000000000000000000000000..5fbc0833eba2f987addc203ae92f3ec260d66faa --- /dev/null +++ b/node_modules/@levischuck/tiny-cbor/script/cbor/cbor_internal.js @@ -0,0 +1,116 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.encodeLength = exports.MAJOR_TYPE_SIMPLE_OR_FLOAT = exports.MAJOR_TYPE_TAG = exports.MAJOR_TYPE_MAP = exports.MAJOR_TYPE_ARRAY = exports.MAJOR_TYPE_TEXT_STRING = exports.MAJOR_TYPE_BYTE_STRING = exports.MAJOR_TYPE_NEGATIVE_INTEGER = exports.MAJOR_TYPE_UNSIGNED_INTEGER = exports.decodeLength = void 0; +function decodeLength(data, argument, index) { + if (argument < 24) { + return [argument, 1]; + } + const remainingDataLength = data.byteLength - index - 1; + const view = new DataView(data.buffer, index + 1); + let output; + let bytes = 0; + switch (argument) { + case 24: { + if (remainingDataLength > 0) { + output = view.getUint8(0); + bytes = 2; + } + break; + } + case 25: { + if (remainingDataLength > 1) { + output = view.getUint16(0, false); + bytes = 3; + } + break; + } + case 26: { + if (remainingDataLength > 3) { + output = view.getUint32(0, false); + bytes = 5; + } + break; + } + case 27: { + if (remainingDataLength > 7) { + const bigOutput = view.getBigUint64(0, false); + // Bound it to [24, MAX_SAFE_INTEGER], where it is safe + // to encode as a javascript number + if (bigOutput >= 24n && bigOutput <= Number.MAX_SAFE_INTEGER) { + return [Number(bigOutput), 9]; + } + } + break; + } + } + if (output && output >= 24) { + return [output, bytes]; + } + throw new Error("Length not supported or not well formed"); +} +exports.decodeLength = decodeLength; +exports.MAJOR_TYPE_UNSIGNED_INTEGER = 0; +exports.MAJOR_TYPE_NEGATIVE_INTEGER = 1; +exports.MAJOR_TYPE_BYTE_STRING = 2; +exports.MAJOR_TYPE_TEXT_STRING = 3; +exports.MAJOR_TYPE_ARRAY = 4; +exports.MAJOR_TYPE_MAP = 5; +exports.MAJOR_TYPE_TAG = 6; +exports.MAJOR_TYPE_SIMPLE_OR_FLOAT = 7; +function encodeLength(major, argument) { + const majorEncoded = major << 5; + if (argument < 0) { + throw new Error("CBOR Data Item argument must not be negative"); + } + // Convert to bigint first. + // Encode integers around and above 32 bits in big endian / network byte order + // is unreliable in javascript. + // https://tc39.es/ecma262/#sec-bitwise-shift-operators + // Bit shifting operations result in 32 bit signed numbers + let bigintArgument; + if (typeof argument == "number") { + if (!Number.isInteger(argument)) { + throw new Error("CBOR Data Item argument must be an integer"); + } + bigintArgument = BigInt(argument); + } + else { + bigintArgument = argument; + } + // Negative 0 is not a thing + if (major == exports.MAJOR_TYPE_NEGATIVE_INTEGER) { + if (bigintArgument == 0n) { + throw new Error("CBOR Data Item argument cannot be zero when negative"); + } + bigintArgument = bigintArgument - 1n; + } + if (bigintArgument > 18446744073709551615n) { + throw new Error("CBOR number out of range"); + } + // Encode into 64 bits and extract the tail + const buffer = new Uint8Array(8); + const view = new DataView(buffer.buffer); + view.setBigUint64(0, bigintArgument, false); + if (bigintArgument <= 23) { + return [majorEncoded | buffer[7]]; + } + else if (bigintArgument <= 255) { + return [majorEncoded | 24, buffer[7]]; + } + else if (bigintArgument <= 65535) { + return [majorEncoded | 25, ...buffer.slice(6)]; + } + else if (bigintArgument <= 4294967295) { + return [ + majorEncoded | 26, + ...buffer.slice(4), + ]; + } + else { + return [ + majorEncoded | 27, + ...buffer, + ]; + } +} +exports.encodeLength = encodeLength; diff --git a/node_modules/@levischuck/tiny-cbor/script/index.d.ts b/node_modules/@levischuck/tiny-cbor/script/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c95cd38f9aa7aa262fd194342ea62cdaa38a09dc --- /dev/null +++ b/node_modules/@levischuck/tiny-cbor/script/index.d.ts @@ -0,0 +1,2 @@ +export { CBORTag, decodeCBOR, decodePartialCBOR, encodeCBOR, } from "./cbor/cbor.js"; +export type { CBORType } from "./cbor/cbor.js"; diff --git a/node_modules/@levischuck/tiny-cbor/script/index.js b/node_modules/@levischuck/tiny-cbor/script/index.js new file mode 100644 index 0000000000000000000000000000000000000000..4063101a784b4d8e8bf420d37d081a720ac6475c --- /dev/null +++ b/node_modules/@levischuck/tiny-cbor/script/index.js @@ -0,0 +1,8 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.encodeCBOR = exports.decodePartialCBOR = exports.decodeCBOR = exports.CBORTag = void 0; +var cbor_js_1 = require("./cbor/cbor.js"); +Object.defineProperty(exports, "CBORTag", { enumerable: true, get: function () { return cbor_js_1.CBORTag; } }); +Object.defineProperty(exports, "decodeCBOR", { enumerable: true, get: function () { return cbor_js_1.decodeCBOR; } }); +Object.defineProperty(exports, "decodePartialCBOR", { enumerable: true, get: function () { return cbor_js_1.decodePartialCBOR; } }); +Object.defineProperty(exports, "encodeCBOR", { enumerable: true, get: function () { return cbor_js_1.encodeCBOR; } }); diff --git a/node_modules/@levischuck/tiny-cbor/script/package.json b/node_modules/@levischuck/tiny-cbor/script/package.json new file mode 100644 index 0000000000000000000000000000000000000000..5bbefffbabee392d1855491b84dc0a716b6a3bf2 --- /dev/null +++ b/node_modules/@levischuck/tiny-cbor/script/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/node_modules/@lukeed/csprng/browser/index.d.ts b/node_modules/@lukeed/csprng/browser/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7e42d843f11bdde1a211207366805d0aa7cc1619 --- /dev/null +++ b/node_modules/@lukeed/csprng/browser/index.d.ts @@ -0,0 +1 @@ +export function random(len: number): T; diff --git a/node_modules/@lukeed/csprng/browser/index.js b/node_modules/@lukeed/csprng/browser/index.js new file mode 100644 index 0000000000000000000000000000000000000000..df8b656c0b8a85d0c9eae3fef7c2752d53ca7df8 --- /dev/null +++ b/node_modules/@lukeed/csprng/browser/index.js @@ -0,0 +1,5 @@ +function random(len) { + return crypto.getRandomValues(new Uint8Array(len)); +} + +exports.random = random; \ No newline at end of file diff --git a/node_modules/@lukeed/csprng/browser/index.min.js b/node_modules/@lukeed/csprng/browser/index.min.js new file mode 100644 index 0000000000000000000000000000000000000000..d3be73f9b887010d457cc1439095a7ba3f74323b --- /dev/null +++ b/node_modules/@lukeed/csprng/browser/index.min.js @@ -0,0 +1 @@ +!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n(e["@lukeed/csprng"]={})}(this,(function(e){e.random=function(e){return crypto.getRandomValues(new Uint8Array(e))}})); \ No newline at end of file diff --git a/node_modules/@lukeed/csprng/browser/index.mjs b/node_modules/@lukeed/csprng/browser/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b65d84980c9e3a84568fdcb78f11871386921087 --- /dev/null +++ b/node_modules/@lukeed/csprng/browser/index.mjs @@ -0,0 +1,3 @@ +export function random(len) { + return crypto.getRandomValues(new Uint8Array(len)); +} diff --git a/node_modules/@lukeed/csprng/index.d.ts b/node_modules/@lukeed/csprng/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e1f3795274918f278cce3cef8632ebf92ac436a6 --- /dev/null +++ b/node_modules/@lukeed/csprng/index.d.ts @@ -0,0 +1 @@ +export function random(len: number): T; diff --git a/node_modules/@lukeed/csprng/license b/node_modules/@lukeed/csprng/license new file mode 100644 index 0000000000000000000000000000000000000000..fa6089faba3cf381229744c9f21ed3ae9ed5014a --- /dev/null +++ b/node_modules/@lukeed/csprng/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Luke Edwards (lukeed.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@lukeed/csprng/node/index.d.ts b/node_modules/@lukeed/csprng/node/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..92f07de3160e89c0db7340de3dc5615478789ed3 --- /dev/null +++ b/node_modules/@lukeed/csprng/node/index.d.ts @@ -0,0 +1 @@ +export function random(len: number): T; diff --git a/node_modules/@lukeed/csprng/node/index.js b/node_modules/@lukeed/csprng/node/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c3128a0824120e9889efb87577d34a3de8493c81 --- /dev/null +++ b/node_modules/@lukeed/csprng/node/index.js @@ -0,0 +1,7 @@ +const { randomBytes } = require('crypto'); + +function random(len) { + return randomBytes(len); +} + +exports.random = random; \ No newline at end of file diff --git a/node_modules/@lukeed/csprng/node/index.min.js b/node_modules/@lukeed/csprng/node/index.min.js new file mode 100644 index 0000000000000000000000000000000000000000..af3a99e1c6ece4ef9ff821cdef769c8ce9317e11 --- /dev/null +++ b/node_modules/@lukeed/csprng/node/index.min.js @@ -0,0 +1 @@ +!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n(e["@lukeed/csprng"]={})}(this,(function(e){const{randomBytes:n}=require("crypto");e.random=function(e){return n(e)}})); \ No newline at end of file diff --git a/node_modules/@lukeed/csprng/node/index.mjs b/node_modules/@lukeed/csprng/node/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..9b76787f044cdd3dfd8e8fc84b807b32b52953ef --- /dev/null +++ b/node_modules/@lukeed/csprng/node/index.mjs @@ -0,0 +1,5 @@ +import { randomBytes } from 'crypto'; + +export function random(len) { + return randomBytes(len); +} diff --git a/node_modules/@lukeed/csprng/package.json b/node_modules/@lukeed/csprng/package.json new file mode 100644 index 0000000000000000000000000000000000000000..844b9c8553f2c00ae3d2fed74b4dba5c0064ae73 --- /dev/null +++ b/node_modules/@lukeed/csprng/package.json @@ -0,0 +1,73 @@ +{ + "version": "1.1.0", + "name": "@lukeed/csprng", + "repository": "lukeed/csprng", + "description": "An alias package for `crypto.randomBytes` in Node.js and/or browsers", + "unpkg": "browser/index.min.js", + "browser": "browser/index.mjs", + "module": "node/index.mjs", + "main": "node/index.js", + "types": "index.d.ts", + "license": "MIT", + "author": { + "name": "Luke Edwards", + "email": "luke.edwards05@gmail.com", + "url": "https://lukeed.com" + }, + "exports": { + ".": { + "browser": { + "types": "./browser/index.d.ts", + "import": "./browser/index.mjs", + "require": "./browser/index.js" + }, + "types": "./node/index.d.ts", + "import": "./node/index.mjs", + "require": "./node/index.js" + }, + "./node": { + "types": "./node/index.d.ts", + "import": "./node/index.mjs", + "require": "./node/index.js" + }, + "./browser": { + "types": "./browser/index.d.ts", + "import": "./browser/index.mjs", + "require": "./browser/index.js" + }, + "./package.json": "./package.json" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "build": "bundt", + "test": "uvu -r esm test" + }, + "files": [ + "*.d.ts", + "browser", + "node" + ], + "modes": { + "browser": "src/browser.js", + "node": "src/node.js" + }, + "keywords": [ + "crypto", + "browser", + "isomorphic", + "getRandomValues", + "randomFill", + "random", + "csprng" + ], + "devDependencies": { + "bundt": "1.1.1", + "esm": "3.2.25", + "uvu": "0.5.2" + }, + "publishConfig": { + "access": "public" + } +} diff --git a/node_modules/@lukeed/csprng/readme.md b/node_modules/@lukeed/csprng/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..cee48c63ea08256bb14a014918247d2475323305 --- /dev/null +++ b/node_modules/@lukeed/csprng/readme.md @@ -0,0 +1,76 @@ +# @lukeed/csprng ![CI](https://github.com/lukeed/csprng/workflows/CI/badge.svg) [![codecov](https://badgen.now.sh/codecov/c/github/lukeed/csprng)](https://codecov.io/gh/lukeed/csprng) + +> A tiny (~90B) isomorphic wrapper for `crypto.randomBytes` in Node.js and browsers. + +***Why?*** + +This package allows you/dependents to import a cryptographically secure generator (CSPRNG) _without_ worrying about (aka, checking the runtime environment for) the different `crypto` implementations. Instead, by extracting a `random` function into a third-party/external package, one can rely on bundlers and/or module resolution to load the correct implementation for the desired environment. + +In other words, one can include the browser-specific implementation when bundling for the browser, completely ignoring the Node.js code – or vice versa. + +By default, this module is set up to work with Rollup, webpack, and Node's native ESM _and_ CommonJS path resolutions. + +## Install + +``` +$ npm install --save @lukeed/csprng +``` + + +## Usage + +***General Usage*** + +```js +// Rely on bundlers/environment detection +import { random } from '@lukeed/csprng'; + +const array = random(12); +// browser => Uint8Array(12) [...] +// Node.js => +``` + +***Specific Environment*** + +```js +// Choose the "browser" implementation explicitly. +//=> ! NOTE ! Will break in Node.js environments! +import { random } from '@lukeed/csprng/browser'; + +const array = random(1024); +//=> Uint8Array(1024) [...] + +// --- + +// Choose the "node" implementation explicitly. +//=> ! NOTE ! Will break in browser environments! +import { random } from '@lukeed/csprng/node'; + +const array = random(1024); +//=> +``` + + +## API + +### random(length) +Returns: `Buffer` or `Uint8Array` + +Returns a typed array of given `length`. + + +#### length +Type: `Number` + +The desired length of your output TypedArray. + + +## Related + +- [uid](https://github.com/lukeed/uid) - A tiny (134B) and fast utility to randomize unique IDs of fixed length +- [@lukeed/uuid](https://github.com/lukeed/uuid) - A tiny (230B), fast, and cryptographically secure UUID (V4) generator for Node and the browser + + +## License + +MIT © [Luke Edwards](https://lukeed.com) diff --git a/node_modules/@mapbox/mapbox-gl-supported/LICENSE.txt b/node_modules/@mapbox/mapbox-gl-supported/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..03483177d84dec658454eb6478bf3f27fe284470 --- /dev/null +++ b/node_modules/@mapbox/mapbox-gl-supported/LICENSE.txt @@ -0,0 +1,30 @@ + +BSD 3-Clause License + +Copyright (c) 2017, Mapbox +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/@mapbox/mapbox-gl-supported/README.md b/node_modules/@mapbox/mapbox-gl-supported/README.md new file mode 100644 index 0000000000000000000000000000000000000000..bd12a78e14403a206f54def22a323f27d6adaaf8 --- /dev/null +++ b/node_modules/@mapbox/mapbox-gl-supported/README.md @@ -0,0 +1,34 @@ +# Mapbox GL JS Supported + +This library determines if a browser supports [Mapbox GL JS](http://github.com/mapbox/mapbox-gl-js). + +## Testing Your Browser + +You may test your browser [here](http://mapbox.github.io/mapbox-gl-supported). + +## Using Mapbox GL JS Supported with a ` + +``` + +## Using Mapbox GL JS Supported with [Browserify](http://browserify.org/) + +```bash +npm install --save @mapbox/mapbox-gl-supported +``` + +```js +var mapboxglSupported = require('@mapbox/mapbox-gl-supported'); + +if (mapboxglSupported.supported()) { + ... +} +``` diff --git a/node_modules/@mapbox/mapbox-gl-supported/index.d.ts b/node_modules/@mapbox/mapbox-gl-supported/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..506b6a172a776e7ca7824c198b7da82aa767bc58 --- /dev/null +++ b/node_modules/@mapbox/mapbox-gl-supported/index.d.ts @@ -0,0 +1,13 @@ +declare type IsSupportedOptions = { + failIfMajorPerformanceCaveat: boolean; +} + +declare type IsSupported = { + webGLContextAttributes: WebGLContextAttributes; + ( + options?: IsSupportedOptions + ): boolean; +}; + +export const supported: IsSupported; +export function notSupportedReason(options?: IsSupportedOptions): string; diff --git a/node_modules/@mapbox/mapbox-gl-supported/index.js b/node_modules/@mapbox/mapbox-gl-supported/index.js new file mode 100644 index 0000000000000000000000000000000000000000..dceb99b2fdf89011477263dc4dd4a70fb2efb5eb --- /dev/null +++ b/node_modules/@mapbox/mapbox-gl-supported/index.js @@ -0,0 +1,122 @@ +'use strict'; + +exports.supported = isSupported; +exports.notSupportedReason = notSupportedReason; + +/** + * Test whether the current browser supports Mapbox GL JS + * @param {Object} options + * @param {boolean} [options.failIfMajorPerformanceCaveat=false] Return `false` + * if the performance of Mapbox GL JS would be dramatically worse than + * expected (i.e. a software renderer is would be used) + * @return {boolean} + */ +function isSupported(options) { + return !notSupportedReason(options); +} + +function notSupportedReason(options) { + if (!isBrowser()) return 'not a browser'; + if (!isWorkerSupported()) return 'insufficient worker support'; + if (!isCanvasGetImageDataSupported()) return 'insufficient Canvas/getImageData support'; + if (!isWebGLSupportedCached(options && options.failIfMajorPerformanceCaveat)) return 'insufficient WebGL2 support'; + if (!isNotIE()) return 'insufficient ECMAScript 6 support'; +} + +function isBrowser() { + return typeof window !== 'undefined' && typeof document !== 'undefined'; +} + +function isWorkerSupported() { + if (!('Worker' in window && 'Blob' in window && 'URL' in window)) { + return false; + } + + var blob = new Blob([''], { type: 'text/javascript' }); + var workerURL = URL.createObjectURL(blob); + var supported; + var worker; + + try { + worker = new Worker(workerURL); + supported = true; + } catch (e) { + supported = false; + } + + if (worker) { + worker.terminate(); + } + URL.revokeObjectURL(workerURL); + + return supported; +} + +// Some browsers or browser extensions block access to canvas data to prevent fingerprinting. +// Mapbox GL uses this API to load sprites and images in general. +function isCanvasGetImageDataSupported() { + var canvas = document.createElement('canvas'); + canvas.width = canvas.height = 1; + var context = canvas.getContext('2d'); + if (!context) { + return false; + } + var imageData = context.getImageData(0, 0, 1, 1); + return imageData && imageData.width === canvas.width; +} + +var isWebGLSupportedCache = {}; +function isWebGLSupportedCached(failIfMajorPerformanceCaveat) { + + if (isWebGLSupportedCache[failIfMajorPerformanceCaveat] === undefined) { + isWebGLSupportedCache[failIfMajorPerformanceCaveat] = isWebGLSupported(failIfMajorPerformanceCaveat); + } + + return isWebGLSupportedCache[failIfMajorPerformanceCaveat]; +} + +isSupported.webGLContextAttributes = { + antialias: false, + alpha: true, + stencil: true, + depth: true +}; + +function getWebGLContext(failIfMajorPerformanceCaveat) { + var canvas = document.createElement('canvas'); + + var attributes = Object.create(isSupported.webGLContextAttributes); + attributes.failIfMajorPerformanceCaveat = failIfMajorPerformanceCaveat; + + return canvas.getContext('webgl2', attributes); +} + +function isWebGLSupported(failIfMajorPerformanceCaveat) { + var gl = getWebGLContext(failIfMajorPerformanceCaveat); + if (!gl) { + return false; + } + + // Try compiling a shader and get its compile status. Some browsers like Brave block this API + // to prevent fingerprinting. Unfortunately, this also means that Mapbox GL won't work. + var shader; + try { + shader = gl.createShader(gl.VERTEX_SHADER); + } catch (e) { + // some older browsers throw an exception that `createShader` is not defined + // so handle this separately from the case where browsers block `createShader` + // for security reasons + return false; + } + + if (!shader || gl.isContextLost()) { + return false; + } + gl.shaderSource(shader, 'void main() {}'); + gl.compileShader(shader); + return gl.getShaderParameter(shader, gl.COMPILE_STATUS) === true; +} + +function isNotIE() { + return !document.documentMode; +} diff --git a/node_modules/@mapbox/mapbox-gl-supported/mapbox-gl-supported.js b/node_modules/@mapbox/mapbox-gl-supported/mapbox-gl-supported.js new file mode 100644 index 0000000000000000000000000000000000000000..0a45ca6bc29f1b8435abfeacab7fd80ad8c8f9d0 --- /dev/null +++ b/node_modules/@mapbox/mapbox-gl-supported/mapbox-gl-supported.js @@ -0,0 +1 @@ +!function(e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).mapboxgl=e()}(function(){return function r(o,i,u){function a(t,e){if(!i[t]){if(!o[t]){var n="function"==typeof require&&require;if(!e&&n)return n(t,!0);if(f)return f(t,!0);throw(e=new Error("Cannot find module '"+t+"'")).code="MODULE_NOT_FOUND",e}n=i[t]={exports:{}},o[t][0].call(n.exports,function(e){return a(o[t][1][e]||e)},n,n.exports,r,o,i,u)}return i[t].exports}for(var f="function"==typeof require&&require,e=0;e + +### Point + +A standalone point geometry with useful accessor, comparison, and +modification methods. + +#### Parameters + +* `x` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** the x-coordinate. This could be longitude or screen pixels, or any other sort of unit. +* `y` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** the y-coordinate. This could be latitude or screen pixels, or any other sort of unit. + +#### Examples + +```javascript +const point = new Point(-77, 38); +``` + +#### clone + +Clone this point, returning a new point that can be modified +without affecting the old one. + +Returns **[Point](#point)** the clone + +#### add + +Add this point's x & y coordinates to another point, +yielding a new point. + +##### Parameters + +* `p` **[Point](#point)** the other point + +Returns **[Point](#point)** output point + +#### sub + +Subtract this point's x & y coordinates to from point, +yielding a new point. + +##### Parameters + +* `p` **[Point](#point)** the other point + +Returns **[Point](#point)** output point + +#### multByPoint + +Multiply this point's x & y coordinates by point, +yielding a new point. + +##### Parameters + +* `p` **[Point](#point)** the other point + +Returns **[Point](#point)** output point + +#### divByPoint + +Divide this point's x & y coordinates by point, +yielding a new point. + +##### Parameters + +* `p` **[Point](#point)** the other point + +Returns **[Point](#point)** output point + +#### mult + +Multiply this point's x & y coordinates by a factor, +yielding a new point. + +##### Parameters + +* `k` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** factor + +Returns **[Point](#point)** output point + +#### div + +Divide this point's x & y coordinates by a factor, +yielding a new point. + +##### Parameters + +* `k` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** factor + +Returns **[Point](#point)** output point + +#### rotate + +Rotate this point around the 0, 0 origin by an angle a, +given in radians + +##### Parameters + +* `a` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** angle to rotate around, in radians + +Returns **[Point](#point)** output point + +#### rotateAround + +Rotate this point around p point by an angle a, +given in radians + +##### Parameters + +* `a` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** angle to rotate around, in radians +* `p` **[Point](#point)** Point to rotate around + +Returns **[Point](#point)** output point + +#### matMult + +Multiply this point by a 4x1 transformation matrix + +##### Parameters + +* `m` **\[[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number), [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number), [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number), [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)]** transformation matrix + +Returns **[Point](#point)** output point + +#### unit + +Calculate this point but as a unit vector from 0, 0, meaning +that the distance from the resulting point to the 0, 0 +coordinate will be equal to 1 and the angle from the resulting +point to the 0, 0 coordinate will be the same as before. + +Returns **[Point](#point)** unit vector point + +#### perp + +Compute a perpendicular point, where the new y coordinate +is the old x coordinate and the new x coordinate is the old y +coordinate multiplied by -1 + +Returns **[Point](#point)** perpendicular point + +#### round + +Return a version of this point with the x & y coordinates +rounded to integers. + +Returns **[Point](#point)** rounded point + +#### mag + +Return the magnitude of this point: this is the Euclidean +distance from the 0, 0 coordinate to this point's x and y +coordinates. + +Returns **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** magnitude + +#### equals + +Judge whether this point is equal to another point, returning +true or false. + +##### Parameters + +* `other` **[Point](#point)** the other point + +Returns **[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** whether the points are equal + +#### dist + +Calculate the distance from this point to another point + +##### Parameters + +* `p` **[Point](#point)** the other point + +Returns **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** distance + +#### distSqr + +Calculate the distance from this point to another point, +without the square root step. Useful if you're comparing +relative distances. + +##### Parameters + +* `p` **[Point](#point)** the other point + +Returns **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** distance + +#### angle + +Get the angle from the 0, 0 coordinate to this point, in radians +coordinates. + +Returns **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** angle + +#### angleTo + +Get the angle from this point to another point, in radians + +##### Parameters + +* `b` **[Point](#point)** the other point + +Returns **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** angle + +#### angleWith + +Get the angle between this point and another point, in radians + +##### Parameters + +* `b` **[Point](#point)** the other point + +Returns **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** angle + +#### angleWithSep + +Find the angle of the two vectors, solving the formula for +the cross product a x b = |a||b|sin(θ) for θ. + +##### Parameters + +* `x` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** the x-coordinate +* `y` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** the y-coordinate + +Returns **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** the angle in radians + +#### convert + +Construct a point from an array if necessary, otherwise if the input +is already a Point, or an unknown type, return it unchanged + +##### Parameters + +* `a` **(\[[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number), [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)] | [Point](#point))** any kind of input value + +##### Examples + +```javascript +// this +var point = Point.convert([0, 1]); +// is equivalent to +var point = new Point(0, 1); +``` + +Returns **[Point](#point)** constructed point, or passed-through value. diff --git a/node_modules/@mapbox/point-geometry/index.d.ts b/node_modules/@mapbox/point-geometry/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dac3d12b3946021cba3be14cde81955ce7ea2e62 --- /dev/null +++ b/node_modules/@mapbox/point-geometry/index.d.ts @@ -0,0 +1,214 @@ +/** + * A standalone point geometry with useful accessor, comparison, and + * modification methods. + * + * @class + * @param {number} x the x-coordinate. This could be longitude or screen pixels, or any other sort of unit. + * @param {number} y the y-coordinate. This could be latitude or screen pixels, or any other sort of unit. + * + * @example + * const point = new Point(-77, 38); + */ +declare function Point(x: number, y: number): void; +declare class Point { + /** + * A standalone point geometry with useful accessor, comparison, and + * modification methods. + * + * @class + * @param {number} x the x-coordinate. This could be longitude or screen pixels, or any other sort of unit. + * @param {number} y the y-coordinate. This could be latitude or screen pixels, or any other sort of unit. + * + * @example + * const point = new Point(-77, 38); + */ + constructor(x: number, y: number); + x: number; + y: number; + /** + * Clone this point, returning a new point that can be modified + * without affecting the old one. + * @return {Point} the clone + */ + clone(): Point; + /** + * Add this point's x & y coordinates to another point, + * yielding a new point. + * @param {Point} p the other point + * @return {Point} output point + */ + add(p: Point): Point; + /** + * Subtract this point's x & y coordinates to from point, + * yielding a new point. + * @param {Point} p the other point + * @return {Point} output point + */ + sub(p: Point): Point; + /** + * Multiply this point's x & y coordinates by point, + * yielding a new point. + * @param {Point} p the other point + * @return {Point} output point + */ + multByPoint(p: Point): Point; + /** + * Divide this point's x & y coordinates by point, + * yielding a new point. + * @param {Point} p the other point + * @return {Point} output point + */ + divByPoint(p: Point): Point; + /** + * Multiply this point's x & y coordinates by a factor, + * yielding a new point. + * @param {number} k factor + * @return {Point} output point + */ + mult(k: number): Point; + /** + * Divide this point's x & y coordinates by a factor, + * yielding a new point. + * @param {number} k factor + * @return {Point} output point + */ + div(k: number): Point; + /** + * Rotate this point around the 0, 0 origin by an angle a, + * given in radians + * @param {number} a angle to rotate around, in radians + * @return {Point} output point + */ + rotate(a: number): Point; + /** + * Rotate this point around p point by an angle a, + * given in radians + * @param {number} a angle to rotate around, in radians + * @param {Point} p Point to rotate around + * @return {Point} output point + */ + rotateAround(a: number, p: Point): Point; + /** + * Multiply this point by a 4x1 transformation matrix + * @param {[number, number, number, number]} m transformation matrix + * @return {Point} output point + */ + matMult(m: [number, number, number, number]): Point; + /** + * Calculate this point but as a unit vector from 0, 0, meaning + * that the distance from the resulting point to the 0, 0 + * coordinate will be equal to 1 and the angle from the resulting + * point to the 0, 0 coordinate will be the same as before. + * @return {Point} unit vector point + */ + unit(): Point; + /** + * Compute a perpendicular point, where the new y coordinate + * is the old x coordinate and the new x coordinate is the old y + * coordinate multiplied by -1 + * @return {Point} perpendicular point + */ + perp(): Point; + /** + * Return a version of this point with the x & y coordinates + * rounded to integers. + * @return {Point} rounded point + */ + round(): Point; + /** + * Return the magnitude of this point: this is the Euclidean + * distance from the 0, 0 coordinate to this point's x and y + * coordinates. + * @return {number} magnitude + */ + mag(): number; + /** + * Judge whether this point is equal to another point, returning + * true or false. + * @param {Point} other the other point + * @return {boolean} whether the points are equal + */ + equals(other: Point): boolean; + /** + * Calculate the distance from this point to another point + * @param {Point} p the other point + * @return {number} distance + */ + dist(p: Point): number; + /** + * Calculate the distance from this point to another point, + * without the square root step. Useful if you're comparing + * relative distances. + * @param {Point} p the other point + * @return {number} distance + */ + distSqr(p: Point): number; + /** + * Get the angle from the 0, 0 coordinate to this point, in radians + * coordinates. + * @return {number} angle + */ + angle(): number; + /** + * Get the angle from this point to another point, in radians + * @param {Point} b the other point + * @return {number} angle + */ + angleTo(b: Point): number; + /** + * Get the angle between this point and another point, in radians + * @param {Point} b the other point + * @return {number} angle + */ + angleWith(b: Point): number; + /** + * Find the angle of the two vectors, solving the formula for + * the cross product a x b = |a||b|sin(θ) for θ. + * @param {number} x the x-coordinate + * @param {number} y the y-coordinate + * @return {number} the angle in radians + */ + angleWithSep(x: number, y: number): number; + /** @param {[number, number, number, number]} m */ + _matMult(m: [number, number, number, number]): this; + /** @param {Point} p */ + _add(p: Point): this; + /** @param {Point} p */ + _sub(p: Point): this; + /** @param {number} k */ + _mult(k: number): this; + /** @param {number} k */ + _div(k: number): this; + /** @param {Point} p */ + _multByPoint(p: Point): this; + /** @param {Point} p */ + _divByPoint(p: Point): this; + _unit(): this; + _perp(): this; + /** @param {number} angle */ + _rotate(angle: number): this; + /** + * @param {number} angle + * @param {Point} p + */ + _rotateAround(angle: number, p: Point): this; + _round(): this; +} +declare namespace Point { + /** + * Construct a point from an array if necessary, otherwise if the input + * is already a Point, return it unchanged. + * @param {Point | [number, number] | {x: number, y: number}} p input value + * @return {Point} constructed point. + * @example + * // this + * var point = Point.convert([0, 1]); + * // is equivalent to + * var point = new Point(0, 1); + */ + function convert(p: Point | [number, number] | { + x: number; + y: number; + }): Point; +} +export default Point; diff --git a/node_modules/@mapbox/point-geometry/index.js b/node_modules/@mapbox/point-geometry/index.js new file mode 100644 index 0000000000000000000000000000000000000000..2d0830f30a9f95f5d87a5f63e4e9296b8605fd58 --- /dev/null +++ b/node_modules/@mapbox/point-geometry/index.js @@ -0,0 +1,323 @@ +/** + * A standalone point geometry with useful accessor, comparison, and + * modification methods. + * + * @class + * @param {number} x the x-coordinate. This could be longitude or screen pixels, or any other sort of unit. + * @param {number} y the y-coordinate. This could be latitude or screen pixels, or any other sort of unit. + * + * @example + * const point = new Point(-77, 38); + */ +export default function Point(x, y) { + this.x = x; + this.y = y; +} + +Point.prototype = { + /** + * Clone this point, returning a new point that can be modified + * without affecting the old one. + * @return {Point} the clone + */ + clone() { return new Point(this.x, this.y); }, + + /** + * Add this point's x & y coordinates to another point, + * yielding a new point. + * @param {Point} p the other point + * @return {Point} output point + */ + add(p) { return this.clone()._add(p); }, + + /** + * Subtract this point's x & y coordinates to from point, + * yielding a new point. + * @param {Point} p the other point + * @return {Point} output point + */ + sub(p) { return this.clone()._sub(p); }, + + /** + * Multiply this point's x & y coordinates by point, + * yielding a new point. + * @param {Point} p the other point + * @return {Point} output point + */ + multByPoint(p) { return this.clone()._multByPoint(p); }, + + /** + * Divide this point's x & y coordinates by point, + * yielding a new point. + * @param {Point} p the other point + * @return {Point} output point + */ + divByPoint(p) { return this.clone()._divByPoint(p); }, + + /** + * Multiply this point's x & y coordinates by a factor, + * yielding a new point. + * @param {number} k factor + * @return {Point} output point + */ + mult(k) { return this.clone()._mult(k); }, + + /** + * Divide this point's x & y coordinates by a factor, + * yielding a new point. + * @param {number} k factor + * @return {Point} output point + */ + div(k) { return this.clone()._div(k); }, + + /** + * Rotate this point around the 0, 0 origin by an angle a, + * given in radians + * @param {number} a angle to rotate around, in radians + * @return {Point} output point + */ + rotate(a) { return this.clone()._rotate(a); }, + + /** + * Rotate this point around p point by an angle a, + * given in radians + * @param {number} a angle to rotate around, in radians + * @param {Point} p Point to rotate around + * @return {Point} output point + */ + rotateAround(a, p) { return this.clone()._rotateAround(a, p); }, + + /** + * Multiply this point by a 4x1 transformation matrix + * @param {[number, number, number, number]} m transformation matrix + * @return {Point} output point + */ + matMult(m) { return this.clone()._matMult(m); }, + + /** + * Calculate this point but as a unit vector from 0, 0, meaning + * that the distance from the resulting point to the 0, 0 + * coordinate will be equal to 1 and the angle from the resulting + * point to the 0, 0 coordinate will be the same as before. + * @return {Point} unit vector point + */ + unit() { return this.clone()._unit(); }, + + /** + * Compute a perpendicular point, where the new y coordinate + * is the old x coordinate and the new x coordinate is the old y + * coordinate multiplied by -1 + * @return {Point} perpendicular point + */ + perp() { return this.clone()._perp(); }, + + /** + * Return a version of this point with the x & y coordinates + * rounded to integers. + * @return {Point} rounded point + */ + round() { return this.clone()._round(); }, + + /** + * Return the magnitude of this point: this is the Euclidean + * distance from the 0, 0 coordinate to this point's x and y + * coordinates. + * @return {number} magnitude + */ + mag() { + return Math.sqrt(this.x * this.x + this.y * this.y); + }, + + /** + * Judge whether this point is equal to another point, returning + * true or false. + * @param {Point} other the other point + * @return {boolean} whether the points are equal + */ + equals(other) { + return this.x === other.x && + this.y === other.y; + }, + + /** + * Calculate the distance from this point to another point + * @param {Point} p the other point + * @return {number} distance + */ + dist(p) { + return Math.sqrt(this.distSqr(p)); + }, + + /** + * Calculate the distance from this point to another point, + * without the square root step. Useful if you're comparing + * relative distances. + * @param {Point} p the other point + * @return {number} distance + */ + distSqr(p) { + const dx = p.x - this.x, + dy = p.y - this.y; + return dx * dx + dy * dy; + }, + + /** + * Get the angle from the 0, 0 coordinate to this point, in radians + * coordinates. + * @return {number} angle + */ + angle() { + return Math.atan2(this.y, this.x); + }, + + /** + * Get the angle from this point to another point, in radians + * @param {Point} b the other point + * @return {number} angle + */ + angleTo(b) { + return Math.atan2(this.y - b.y, this.x - b.x); + }, + + /** + * Get the angle between this point and another point, in radians + * @param {Point} b the other point + * @return {number} angle + */ + angleWith(b) { + return this.angleWithSep(b.x, b.y); + }, + + /** + * Find the angle of the two vectors, solving the formula for + * the cross product a x b = |a||b|sin(θ) for θ. + * @param {number} x the x-coordinate + * @param {number} y the y-coordinate + * @return {number} the angle in radians + */ + angleWithSep(x, y) { + return Math.atan2( + this.x * y - this.y * x, + this.x * x + this.y * y); + }, + + /** @param {[number, number, number, number]} m */ + _matMult(m) { + const x = m[0] * this.x + m[1] * this.y, + y = m[2] * this.x + m[3] * this.y; + this.x = x; + this.y = y; + return this; + }, + + /** @param {Point} p */ + _add(p) { + this.x += p.x; + this.y += p.y; + return this; + }, + + /** @param {Point} p */ + _sub(p) { + this.x -= p.x; + this.y -= p.y; + return this; + }, + + /** @param {number} k */ + _mult(k) { + this.x *= k; + this.y *= k; + return this; + }, + + /** @param {number} k */ + _div(k) { + this.x /= k; + this.y /= k; + return this; + }, + + /** @param {Point} p */ + _multByPoint(p) { + this.x *= p.x; + this.y *= p.y; + return this; + }, + + /** @param {Point} p */ + _divByPoint(p) { + this.x /= p.x; + this.y /= p.y; + return this; + }, + + _unit() { + this._div(this.mag()); + return this; + }, + + _perp() { + const y = this.y; + this.y = this.x; + this.x = -y; + return this; + }, + + /** @param {number} angle */ + _rotate(angle) { + const cos = Math.cos(angle), + sin = Math.sin(angle), + x = cos * this.x - sin * this.y, + y = sin * this.x + cos * this.y; + this.x = x; + this.y = y; + return this; + }, + + /** + * @param {number} angle + * @param {Point} p + */ + _rotateAround(angle, p) { + const cos = Math.cos(angle), + sin = Math.sin(angle), + x = p.x + cos * (this.x - p.x) - sin * (this.y - p.y), + y = p.y + sin * (this.x - p.x) + cos * (this.y - p.y); + this.x = x; + this.y = y; + return this; + }, + + _round() { + this.x = Math.round(this.x); + this.y = Math.round(this.y); + return this; + }, + + constructor: Point +}; + +/** + * Construct a point from an array if necessary, otherwise if the input + * is already a Point, return it unchanged. + * @param {Point | [number, number] | {x: number, y: number}} p input value + * @return {Point} constructed point. + * @example + * // this + * var point = Point.convert([0, 1]); + * // is equivalent to + * var point = new Point(0, 1); + */ +Point.convert = function (p) { + if (p instanceof Point) { + return /** @type {Point} */ (p); + } + if (Array.isArray(p)) { + return new Point(+p[0], +p[1]); + } + if (p.x !== undefined && p.y !== undefined) { + return new Point(+p.x, +p.y); + } + throw new Error('Expected [x, y] or {x, y} point format'); +}; diff --git a/node_modules/@mapbox/point-geometry/package.json b/node_modules/@mapbox/point-geometry/package.json new file mode 100644 index 0000000000000000000000000000000000000000..bcef7d794c640bc799ba2598a308a62ec47bbdd6 --- /dev/null +++ b/node_modules/@mapbox/point-geometry/package.json @@ -0,0 +1,40 @@ +{ + "name": "@mapbox/point-geometry", + "version": "1.1.0", + "description": "a point geometry with transforms", + "main": "index.js", + "type": "module", + "exports": "./index.js", + "types": "index.d.ts", + "scripts": { + "lint": "eslint --fix index.js test.js", + "pretest": "npm run lint", + "test": "tsc && node test.js", + "doc": "documentation readme index.js --section=API --markdown-toc=false", + "cov": "node --test --experimental-test-coverage" + }, + "repository": { + "type": "git", + "url": "git@github.com:mapbox/point-geometry.git" + }, + "keywords": [ + "point", + "geometry", + "primitive" + ], + "author": "Tom MacWright", + "license": "ISC", + "bugs": { + "url": "https://github.com/mapbox/point-geometry/issues" + }, + "homepage": "https://github.com/mapbox/point-geometry", + "devDependencies": { + "documentation": "^14.0.3", + "eslint": "^9.6.0", + "eslint-config-mourner": "^4.0.2", + "typescript": "^5.5.3" + }, + "files": [ + "index.d.ts" + ] +} diff --git a/node_modules/@mapbox/tiny-sdf/LICENSE.txt b/node_modules/@mapbox/tiny-sdf/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..f061cfdf968ea50e1ff7821ce13b171df69558bb --- /dev/null +++ b/node_modules/@mapbox/tiny-sdf/LICENSE.txt @@ -0,0 +1,9 @@ +BSD-2-Clause +Copyright (c) 2016-2024 Mapbox, Inc. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/@mapbox/tiny-sdf/README.md b/node_modules/@mapbox/tiny-sdf/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c7843ce207d4af8615bf04a8d00d3063979a49d0 --- /dev/null +++ b/node_modules/@mapbox/tiny-sdf/README.md @@ -0,0 +1,63 @@ +# TinySDF [![Volodymyr Agafonkin's projects](https://img.shields.io/badge/simply-awesome-brightgreen.svg)](https://github.com/mourner/projects) [![Node](https://github.com/mapbox/tiny-sdf/actions/workflows/node.yml/badge.svg)](https://github.com/mapbox/tiny-sdf/actions/workflows/node.yml) + +TinySDF is a tiny and fast JavaScript library for generating SDF (signed distance field) +from system fonts on the browser using Canvas 2D and +[Felzenszwalb/Huttenlocher distance transform](https://cs.brown.edu/~pff/papers/dt-final.pdf). +This is very useful for [rendering text with WebGL](https://www.mapbox.com/blog/text-signed-distance-fields/). + +## [Demo](http://mapbox.github.io/tiny-sdf) + +## Usage + +Create a TinySDF for drawing glyph SDFs based on font parameters: + +```js +const tinySdf = new TinySDF({ + fontSize: 24, // Font size in pixels + fontFamily: 'sans-serif', // CSS font-family + fontWeight: 'normal', // CSS font-weight + fontStyle: 'normal', // CSS font-style + buffer: 3, // Whitespace buffer around a glyph in pixels + radius: 8, // How many pixels around the glyph shape to use for encoding distance + cutoff: 0.25 // How much of the radius (relative) is used for the inside part of the glyph +}); + +const glyph = tinySdf.draw('泽'); // draw a single character +``` + +Returns an object with the following properties: + +- `data` is a `Uint8ClampedArray` array of alpha values (0–255) for a `width` x `height` grid. +- `width`: Width of the returned bitmap. +- `height`: Height of the returned bitmap. +- `glyphTop`: Maximum ascent of the glyph from alphabetic baseline. +- `glyphLeft`: Currently hardwired to 0 (actual glyph differences are encoded in the rasterization). +- `glyphWidth`: Width of the rasterized portion of the glyph. +- `glyphHeight` Height of the rasterized portion of the glyph. +- `glyphAdvance`: Layout advance. + +TinySDF is provided as a ES module, so it's only supported on modern browsers, excluding IE. + +```html + +``` + +In Node, you can't use `require` — only `import` in ESM-capable versions (v12.15+): + +```js +import TinySDF from '@mapbox/tiny-sdf'; +``` + +## Development + +```bash +npm test # run tests +npm start # start server for the demo page +``` + +## License + +This implementation is licensed under the [BSD 2-Clause license](https://opensource.org/licenses/BSD-2-Clause). It's based directly on the algorithm published in the Felzenszwalb/Huttenlocher paper, and is not a port of the existing C++ implementation provided by the paper's authors. diff --git a/node_modules/@mapbox/tiny-sdf/index.d.ts b/node_modules/@mapbox/tiny-sdf/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..679ee9fe6101003723aadc429375547173134f1d --- /dev/null +++ b/node_modules/@mapbox/tiny-sdf/index.d.ts @@ -0,0 +1,24 @@ +export declare type TinySDFOptions = { + fontSize?: number; + buffer?: number; + radius?: number; + cutoff?: number; + fontFamily?: string; + fontWeight?: string; + fontStyle?: string; + lang?: string; +}; + +export default class TinySDF { + constructor(options: TinySDFOptions); + draw(char: string): { + data: Uint8ClampedArray; + width: number; + height: number; + glyphWidth: number; + glyphHeight: number; + glyphTop: number; + glyphLeft: number; + glyphAdvance: number; + }; +} diff --git a/node_modules/@mapbox/tiny-sdf/index.js b/node_modules/@mapbox/tiny-sdf/index.js new file mode 100644 index 0000000000000000000000000000000000000000..0183c06bdf34d3d5280c2d7d033ca895aab6fef8 --- /dev/null +++ b/node_modules/@mapbox/tiny-sdf/index.js @@ -0,0 +1,163 @@ +const INF = 1e20; + +// lookup table for gamma-corrected, signed squared alpha distance values +const alphaTable = new Float64Array(256); +for (let i = 0; i < 256; i++) { + const d = 0.5 - Math.pow(i / 255, 1 / 2.2); + alphaTable[i] = d * Math.abs(d); +} +alphaTable[255] = -INF; + +export default class TinySDF { + constructor({ + fontSize = 24, + buffer = 3, + radius = 8, + cutoff = 0.25, + fontFamily = 'sans-serif', + fontWeight = 'normal', + fontStyle = 'normal', + lang = null + } = {}) { + this.buffer = buffer; // padding around a glyph's bounding box + this.radius = radius; // how many pixels around the glyph edge are encoded as signed distances + this.cutoff = cutoff; // how much of the SDF byte range represents inside vs outside the edge + this.lang = lang; // language of the Canvas drawing context + + // make the canvas size big enough to both have the specified buffer around the glyph + // for "halo", and account for some glyphs possibly being larger than their font size + const size = this.size = fontSize + buffer * 4; + + const canvas = this._createCanvas(size); + const ctx = this.ctx = canvas.getContext('2d', {willReadFrequently: true}); + ctx.font = `${fontStyle} ${fontWeight} ${fontSize}px ${fontFamily}`; + + ctx.textBaseline = 'alphabetic'; + ctx.textAlign = 'left'; // Necessary so that RTL text doesn't have different alignment + ctx.fillStyle = 'black'; + + // two grids of squared distances: one for the outside of the glyph shape, one for the inside; + // the signed distance is derived as sqrt(outer) - sqrt(inner) + this.gridOuter = new Float64Array(size * size); + this.gridInner = new Float64Array(size * size); + this.f = new Float64Array(size); + this.z = new Float64Array(size + 1); + this.v = new Uint16Array(size); + } + + _createCanvas(size) { + if (typeof OffscreenCanvas !== 'undefined') { + return new OffscreenCanvas(size, size); + } + const canvas = document.createElement('canvas'); + canvas.width = canvas.height = size; + return canvas; + } + + draw(char) { + const { + width: glyphAdvance, + actualBoundingBoxAscent, + actualBoundingBoxDescent, + actualBoundingBoxLeft, + actualBoundingBoxRight + } = this.ctx.measureText(char); + + // The integer/pixel part of the alignment is encoded in metrics.glyphTop/glyphLeft + // The remainder is implicitly encoded in the rasterization + const glyphTop = Math.ceil(actualBoundingBoxAscent); + // actualBoundingBoxLeft is positive when ink extends LEFT of the origin (per spec), + // so negate to get the ink's left edge in canvas x-coords (positive = right of origin) + const glyphLeft = Math.floor(-actualBoundingBoxLeft); + + // If the glyph overflows the canvas size, it will be clipped at the bottom/right + const glyphWidth = Math.max(0, Math.min(this.size - this.buffer, Math.ceil(actualBoundingBoxRight) - glyphLeft)); + const glyphHeight = Math.max(0, Math.min(this.size - this.buffer, glyphTop + Math.ceil(actualBoundingBoxDescent))); + + const width = glyphWidth + 2 * this.buffer; + const height = glyphHeight + 2 * this.buffer; + + const len = Math.max(width * height, 0); + const data = new Uint8ClampedArray(len); + const glyph = {data, width, height, glyphWidth, glyphHeight, glyphTop, glyphLeft, glyphAdvance}; + if (glyphWidth === 0 || glyphHeight === 0) return glyph; + + const {ctx, buffer, gridInner, gridOuter} = this; + if (this.lang) ctx.lang = this.lang; + ctx.clearRect(buffer, buffer, glyphWidth, glyphHeight); + ctx.fillText(char, buffer - glyphLeft, buffer + glyphTop); + const imgData = ctx.getImageData(buffer, buffer, glyphWidth, glyphHeight); + + // default: outside the glyph (INF distance) for outer, inside (0 distance) for inner + gridOuter.fill(INF, 0, len); + gridInner.fill(0, 0, len); + + // for anti-aliased pixels, treat partial coverage as a distance approximation: + // a fully covered pixel gets 0 outer / INF inner; a partial pixel gets a small + // non-zero outer or inner distance based on how far its coverage deviates from 0.5 + let imgIdx = 3; // start at the alpha channel of the first pixel + for (let y = 0; y < glyphHeight; y++) { + let j = (y + buffer) * width + buffer; + for (let x = 0; x < glyphWidth; x++, imgIdx += 4, j++) { + const a = imgData.data[imgIdx]; // alpha value + if (a === 0) continue; // empty pixels + const t = alphaTable[a]; + gridOuter[j] = Math.max(0, t); + gridInner[j] = Math.max(0, -t); + } + } + + edt(gridOuter, 0, 0, width, height, width, this.f, this.v, this.z); + // Pad the inner EDT region by 1 px so ink pixels touching the bbox edge can see the + // outside-ink seeds in the buffer region; clamp to buffer so we don't underflow when buffer=0 + const pad = Math.min(buffer, 1); + edt(gridInner, buffer - pad, buffer - pad, glyphWidth + 2 * pad, glyphHeight + 2 * pad, width, this.f, this.v, this.z); + + // encode signed distance as a byte: inside the glyph maps to high values, outside to low, + // with the edge gradient spanning [-radius * cutoff, radius * (1 - cutoff)] pixels around the edge; + // Uint8ClampedArray clamps beyond that + const scale = 255 / this.radius; + const base = 255 * (1 - this.cutoff); + for (let i = 0; i < len; i++) { + const d = Math.sqrt(gridOuter[i]) - Math.sqrt(gridInner[i]); + data[i] = Math.round(base - scale * d); + } + + return glyph; + } +} + +// 2D Euclidean squared distance transform by Felzenszwalb & Huttenlocher https://cs.brown.edu/~pff/papers/dt-final.pdf +function edt(data, x0, y0, width, height, gridSize, f, v, z) { + for (let x = x0; x < x0 + width; x++) edt1d(data, y0 * gridSize + x, gridSize, height, f, v, z); + for (let y = y0; y < y0 + height; y++) edt1d(data, y * gridSize + x0, 1, width, f, v, z); +} + +// 1D squared distance transform +function edt1d(grid, offset, stride, length, f, v, z) { + v[0] = 0; + z[0] = -INF; + z[1] = INF; + f[0] = grid[offset]; + + for (let q = 1, k = 0, s = 0; q < length; q++) { + f[q] = grid[offset + q * stride]; + const q2 = q * q; + do { + const r = v[k]; + s = (f[q] - f[r] + q2 - r * r) / (q - r) / 2; + } while (s <= z[k] && --k > -1); + + k++; + v[k] = q; + z[k] = s; + z[k + 1] = INF; + } + + for (let q = 0, k = 0; q < length; q++) { + while (z[k + 1] < q) k++; + const r = v[k]; + const qr = q - r; + grid[offset + q * stride] = f[r] + qr * qr; + } +} diff --git a/node_modules/@mapbox/tiny-sdf/package.json b/node_modules/@mapbox/tiny-sdf/package.json new file mode 100644 index 0000000000000000000000000000000000000000..afab6a5daa8ad0d911fe58c599955493ae2db4fc --- /dev/null +++ b/node_modules/@mapbox/tiny-sdf/package.json @@ -0,0 +1,45 @@ +{ + "name": "@mapbox/tiny-sdf", + "version": "2.2.0", + "description": "Browser-side SDF font generator", + "type": "module", + "main": "index.js", + "exports": "./index.js", + "typings": "./index.d.ts", + "scripts": { + "pretest": "eslint index.js index.html test", + "test": "node --test", + "bench": "node ./test/bench.js", + "start": "st --no-cache --localhost --index index.html ." + }, + "repository": { + "type": "git", + "url": "git+https://github.com/mapbox/tiny-sdf.git" + }, + "keywords": [ + "sdf", + "signed distance fields", + "font", + "canvas", + "text", + "distance transform" + ], + "author": "Vladimir Agafonkin", + "license": "BSD-2-Clause", + "bugs": { + "url": "https://github.com/mapbox/tiny-sdf/issues" + }, + "homepage": "https://github.com/mapbox/tiny-sdf#readme", + "files": [ + "index.d.ts" + ], + "devDependencies": { + "canvas": "^3.2.3", + "eslint": "^10.3.0", + "eslint-config-mourner": "^4.1.0", + "eslint-plugin-html": "^8.1.4", + "pixelmatch": "^7.2.0", + "pngjs": "^7.0.0", + "st": "^3.0.3" + } +} diff --git a/node_modules/@mapbox/unitbezier/LICENSE b/node_modules/@mapbox/unitbezier/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..03afecb0c11e16704fb218b58758b19c53f15045 --- /dev/null +++ b/node_modules/@mapbox/unitbezier/LICENSE @@ -0,0 +1,28 @@ +BSD-2-Clause + +Copyright (C) 2008 Apple Inc. All Rights Reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Ported from Webkit +http://svn.webkit.org/repository/webkit/trunk/Source/WebCore/platform/graphics/UnitBezier.h diff --git a/node_modules/@mapbox/unitbezier/README.md b/node_modules/@mapbox/unitbezier/README.md new file mode 100644 index 0000000000000000000000000000000000000000..bb7776b1222cb4b785f7b43f2596fac03d99ca22 --- /dev/null +++ b/node_modules/@mapbox/unitbezier/README.md @@ -0,0 +1,17 @@ +[![Build Status](https://travis-ci.org/mapbox/unitbezier.svg)](https://travis-ci.org/mapbox/unitbezier) + +# unitbezier + +Unit bezier interpolation function: a port to JavaScript from Webkit: + +http://svn.webkit.org/repository/webkit/trunk/Source/WebCore/platform/graphics/UnitBezier.h + +## api + +### new UnitBezier(p1x, p1y, p2x, p2y) + +Initialize a new bezier curve given the points + +### bezier.solve(x, epsilon) + +Evaluate bezier for value `x` (ranging from 0 to 1) with `epsilon` precision (1e-6 by default). diff --git a/node_modules/@mapbox/unitbezier/index.d.ts b/node_modules/@mapbox/unitbezier/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..422324e340f48f23c7d89700f29016a5843fc5a1 --- /dev/null +++ b/node_modules/@mapbox/unitbezier/index.d.ts @@ -0,0 +1,8 @@ +export default class UnitBezier { + constructor(p1x: number, p1y: number, p2x: number, p2y: number); + sampleCurveX(t: number): number; + sampleCurveY(t: number): number; + sampleCurveDerivativeX(t: number): number; + solveCurveX(x: number, epsilon?: number): number; + solve(x: number, epsilon?: number): number; +} diff --git a/node_modules/@mapbox/unitbezier/index.js b/node_modules/@mapbox/unitbezier/index.js new file mode 100644 index 0000000000000000000000000000000000000000..833ac6c73ee74e8702fdebd4d8d53a32d0ac6ce2 --- /dev/null +++ b/node_modules/@mapbox/unitbezier/index.js @@ -0,0 +1,78 @@ +'use strict'; + +module.exports = UnitBezier; + +function UnitBezier(p1x, p1y, p2x, p2y) { + // Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1). + this.cx = 3.0 * p1x; + this.bx = 3.0 * (p2x - p1x) - this.cx; + this.ax = 1.0 - this.cx - this.bx; + + this.cy = 3.0 * p1y; + this.by = 3.0 * (p2y - p1y) - this.cy; + this.ay = 1.0 - this.cy - this.by; + + this.p1x = p1x; + this.p1y = p1y; + this.p2x = p2x; + this.p2y = p2y; +} + +UnitBezier.prototype = { + sampleCurveX: function (t) { + // `ax t^3 + bx t^2 + cx t' expanded using Horner's rule. + return ((this.ax * t + this.bx) * t + this.cx) * t; + }, + + sampleCurveY: function (t) { + return ((this.ay * t + this.by) * t + this.cy) * t; + }, + + sampleCurveDerivativeX: function (t) { + return (3.0 * this.ax * t + 2.0 * this.bx) * t + this.cx; + }, + + solveCurveX: function (x, epsilon) { + if (epsilon === undefined) epsilon = 1e-6; + + if (x < 0.0) return 0.0; + if (x > 1.0) return 1.0; + + var t = x; + + // First try a few iterations of Newton's method - normally very fast. + for (var i = 0; i < 8; i++) { + var x2 = this.sampleCurveX(t) - x; + if (Math.abs(x2) < epsilon) return t; + + var d2 = this.sampleCurveDerivativeX(t); + if (Math.abs(d2) < 1e-6) break; + + t = t - x2 / d2; + } + + // Fall back to the bisection method for reliability. + var t0 = 0.0; + var t1 = 1.0; + t = x; + + for (i = 0; i < 20; i++) { + x2 = this.sampleCurveX(t); + if (Math.abs(x2 - x) < epsilon) break; + + if (x > x2) { + t0 = t; + } else { + t1 = t; + } + + t = (t1 - t0) * 0.5 + t0; + } + + return t; + }, + + solve: function (x, epsilon) { + return this.sampleCurveY(this.solveCurveX(x, epsilon)); + } +}; diff --git a/node_modules/@mapbox/unitbezier/package.json b/node_modules/@mapbox/unitbezier/package.json new file mode 100644 index 0000000000000000000000000000000000000000..aa73694ba7d203b733fdd1a40227ba0017a68186 --- /dev/null +++ b/node_modules/@mapbox/unitbezier/package.json @@ -0,0 +1,39 @@ +{ + "name": "@mapbox/unitbezier", + "version": "0.0.1", + "description": "unit bezier curve interpolation", + "main": "index.js", + "typings": "index.d.ts", + "scripts": { + "pretest": "eslint index.js test/*.js", + "test": "node test/unitbezier.js" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "repository": { + "type": "git", + "url": "git@github.com:mapbox/unitbezier.git" + }, + "keywords": [ + "unit", + "bezier", + "interpolation", + "webkit" + ], + "author": "", + "license": "BSD-2-Clause", + "bugs": { + "url": "https://github.com/mapbox/unitbezier/issues" + }, + "homepage": "https://github.com/mapbox/unitbezier", + "devDependencies": { + "eslint": "^8.0.1", + "eslint-config-mourner": "^2.0.3", + "tape": "^5.3.1" + }, + "eslintConfig": { + "extends": "mourner" + } +} diff --git a/node_modules/@mapbox/vector-tile/LICENSE.txt b/node_modules/@mapbox/vector-tile/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..9b3f9c5d3189317f8882173f225e73599e050c07 --- /dev/null +++ b/node_modules/@mapbox/vector-tile/LICENSE.txt @@ -0,0 +1,27 @@ +Copyright (c) 2024, Mapbox + +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + * Neither the name of Mapbox nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/@mapbox/vector-tile/README.md b/node_modules/@mapbox/vector-tile/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8fd010e80afec5c06af1a11686bcca70d6659ae3 --- /dev/null +++ b/node_modules/@mapbox/vector-tile/README.md @@ -0,0 +1,95 @@ +# vector-tile + +This library reads [Mapbox Vector Tiles](https://github.com/mapbox/vector-tile-spec) and allows access to the layers and features. + +## Example + +```js +import {VectorTile} from '@mapbox/vector-tile'; +import Protobuf from 'pbf'; + +const tile = new VectorTile(new Protobuf(data)); + +// Contains a map of all layers +tile.layers; + +const landuse = tile.layers.landuse; + +// Amount of features in this layer +landuse.length; + +// Returns the first feature +landuse.feature(0); +``` + +Vector tiles contained in [serialtiles-spec](https://github.com/mapbox/serialtiles-spec) +are gzip-encoded, so a complete example of parsing them with the native +zlib module would be: + +```js +import {VectorTile} from '@mapbox/vector-tile'; +import Protobuf from 'pbf'; +import {gunzipSync} from 'zlib'; + +const buffer = gunzipSync(data); +const tile = new VectorTile(new Protobuf(buffer)); +``` + +## Install + +To install: + + npm install @mapbox/vector-tile + + +## API Reference + +### VectorTile + +An object that parses vector tile data and makes it readable. + +#### Constructor + +- **new VectorTile(protobuf[, end])** — + parses the vector tile data contained in the given [Protobuf](https://github.com/mapbox/pbf) object, + saving resulting layers in the created object as a `layers` property. Optionally accepts end index. + +#### Properties + +- **layers** (Object) — an object containing parsed layers in the form of `{: , ...}`, +where each layer is a `VectorTileLayer` object. + + +### VectorTileLayer + +An object that contains the data for a single vector tile layer. + +#### Properties + +- **version** (`Number`, default: `1`) +- **name** (`String`) — layer name +- **extent** (`Number`, default: `4096`) — tile extent size +- **length** (`Number`) — number of features in the layer + +#### Methods + +- **feature(i)** — get a feature (`VectorTileFeature`) by the given index from the layer. + + +### VectorTileFeature + +An object that contains the data for a single feature. + +#### Properties + +- **type** (`Number`) — type of the feature (also see `VectorTileFeature.types`) +- **extent** (`Number`) — feature extent size +- **id** (`Number`) — feature identifier, if present +- **properties** (`Object`) — object literal with feature properties + +#### Methods + +- **loadGeometry()** — parses feature geometry and returns an array of + [Point](https://github.com/mapbox/point-geometry) arrays (with each point having `x` and `y` properties) +- **bbox()** — calculates and returns the bounding box of the feature in the form `[x1, y1, x2, y2]` +- **toGeoJSON(x, y, z)** — returns a GeoJSON representation of the feature. (`x`, `y`, and `z` refer to the containing tile's index.) diff --git a/node_modules/@mapbox/vector-tile/index.d.ts b/node_modules/@mapbox/vector-tile/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2898551958912076f00e02674819d19e7428ade1 --- /dev/null +++ b/node_modules/@mapbox/vector-tile/index.d.ts @@ -0,0 +1,80 @@ +/** classifies an array of rings into polygons with outer rings and holes + * @param {Point[][]} rings + */ +export function classifyRings(rings: Point[][]): Point[][][]; +/** @import Pbf from 'pbf' */ +/** @import {Feature} from 'geojson' */ +export class VectorTileFeature { + /** + * @param {Pbf} pbf + * @param {number} end + * @param {number} extent + * @param {string[]} keys + * @param {(number | string | boolean)[]} values + */ + constructor(pbf: Pbf, end: number, extent: number, keys: string[], values: (number | string | boolean)[]); + /** @type {Record} */ + properties: Record; + extent: number; + /** @type {0 | 1 | 2 | 3} */ + type: 0 | 1 | 2 | 3; + /** @type {number | undefined} */ + id: number | undefined; + /** @private */ + private _pbf; + /** @private */ + private _geometry; + /** @private */ + private _keys; + /** @private */ + private _values; + loadGeometry(): Point[][]; + bbox(): number[]; + /** + * @param {number} x + * @param {number} y + * @param {number} z + * @return {Feature} + */ + toGeoJSON(x: number, y: number, z: number): Feature; +} +export namespace VectorTileFeature { + let types: ["Unknown", "Point", "LineString", "Polygon"]; +} +export class VectorTileLayer { + /** + * @param {Pbf} pbf + * @param {number} [end] + */ + constructor(pbf: Pbf, end?: number); + version: number; + name: string; + extent: number; + length: number; + /** @private */ + private _pbf; + /** @private + * @type {string[]} */ + private _keys; + /** @private + * @type {(number | string | boolean)[]} */ + private _values; + /** @private + * @type {number[]} */ + private _features; + /** return feature `i` from this layer as a `VectorTileFeature` + * @param {number} i + */ + feature(i: number): VectorTileFeature; +} +export class VectorTile { + /** + * @param {Pbf} pbf + * @param {number} [end] + */ + constructor(pbf: Pbf, end?: number); + layers: Record; +} +import Point from '@mapbox/point-geometry'; +import type { Feature } from 'geojson'; +import type Pbf from 'pbf'; diff --git a/node_modules/@mapbox/vector-tile/index.js b/node_modules/@mapbox/vector-tile/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e177c7111194249fd48432ca88f2abc2c7277780 --- /dev/null +++ b/node_modules/@mapbox/vector-tile/index.js @@ -0,0 +1,370 @@ + +import Point from '@mapbox/point-geometry'; + +/** @import Pbf from 'pbf' */ +/** @import {Feature} from 'geojson' */ + +export class VectorTileFeature { + /** + * @param {Pbf} pbf + * @param {number} end + * @param {number} extent + * @param {string[]} keys + * @param {(number | string | boolean)[]} values + */ + constructor(pbf, end, extent, keys, values) { + // Public + + /** @type {Record} */ + this.properties = Object.create(null); + + this.extent = extent; + /** @type {0 | 1 | 2 | 3} */ + this.type = 0; + + /** @type {number | undefined} */ + this.id = undefined; + + /** @private */ + this._pbf = pbf; + /** @private */ + this._geometry = -1; + /** @private */ + this._keys = keys; + /** @private */ + this._values = values; + + while (pbf.pos < end) { + const tag = pbf.readVarint(); + if (tag === 8) this.id = pbf.readVarint(); + else if (tag === 18) { + const tagsEnd = pbf.readVarint() + pbf.pos; + while (pbf.pos < tagsEnd) { + const key = keys[pbf.readVarint()]; + const value = values[pbf.readVarint()]; + this.properties[key] = value; + } + } else if (tag === 24) this.type = /** @type {0 | 1 | 2 | 3} */ (pbf.readVarint()); + else if (tag === 34) { + this._geometry = pbf.pos; + pbf.skip(tag); + } else pbf.skip(tag); + } + } + + loadGeometry() { + if (this._geometry < 0) throw new Error('feature has no geometry'); + const pbf = this._pbf; + pbf.pos = this._geometry; + + const end = pbf.readVarint() + pbf.pos; + + /** @type Point[][] */ + const lines = []; + + /** @type Point[] | undefined */ + let line; + + let cmd = 1; + let length = 0; + let x = 0; + let y = 0; + + while (pbf.pos < end) { + if (length <= 0) { + const cmdLen = pbf.readVarint(); + cmd = cmdLen & 0x7; + length = cmdLen >> 3; + if (length === 0) continue; + } + + length--; + + if (cmd === 1) { // moveTo + x += pbf.readSVarint(); + y += pbf.readSVarint(); + if (line) lines.push(line); + line = [new Point(x, y)]; + + } else if (cmd === 2) { // lineTo + x += pbf.readSVarint(); + y += pbf.readSVarint(); + if (line) line.push(new Point(x, y)); + + } else if (cmd === 7) { + + // Workaround for https://github.com/mapbox/mapnik-vector-tile/issues/90 + if (line) { + line.push(line[0].clone()); // closePolygon + } + + } else { + throw new Error(`unknown command ${cmd}`); + } + } + + if (line) lines.push(line); + + return lines; + } + + bbox() { + if (this._geometry < 0) throw new Error('feature has no geometry'); + const pbf = this._pbf; + pbf.pos = this._geometry; + + const end = pbf.readVarint() + pbf.pos; + let cmd = 1, + length = 0, + x = 0, + y = 0, + x1 = Infinity, + x2 = -Infinity, + y1 = Infinity, + y2 = -Infinity; + + while (pbf.pos < end) { + if (length <= 0) { + const cmdLen = pbf.readVarint(); + cmd = cmdLen & 0x7; + length = cmdLen >> 3; + if (length === 0) continue; + } + + length--; + + if (cmd === 1 || cmd === 2) { + x += pbf.readSVarint(); + y += pbf.readSVarint(); + if (x < x1) x1 = x; + if (x > x2) x2 = x; + if (y < y1) y1 = y; + if (y > y2) y2 = y; + + } else if (cmd !== 7) { + throw new Error(`unknown command ${cmd}`); + } + } + + return [x1, y1, x2, y2]; + } + + /** + * @param {number} x + * @param {number} y + * @param {number} z + * @return {Feature} + */ + toGeoJSON(x, y, z) { + const size = this.extent * Math.pow(2, z), + x0 = this.extent * x, + y0 = this.extent * y, + vtCoords = this.loadGeometry(); + + /** @param {Point} p */ + function projectPoint(p) { + return [ + (p.x + x0) * 360 / size - 180, + 360 / Math.PI * Math.atan(Math.exp((1 - (p.y + y0) * 2 / size) * Math.PI)) - 90 + ]; + } + + /** @param {Point[]} line */ + function projectLine(line) { + return line.map(projectPoint); + } + + /** @type {Feature["geometry"]} */ + let geometry; + + if (this.type === 1) { + const points = []; + for (const line of vtCoords) { + points.push(line[0]); + } + const coordinates = projectLine(points); + geometry = points.length === 1 ? + {type: 'Point', coordinates: coordinates[0]} : + {type: 'MultiPoint', coordinates}; + + } else if (this.type === 2) { + + const coordinates = vtCoords.map(projectLine); + geometry = coordinates.length === 1 ? + {type: 'LineString', coordinates: coordinates[0]} : + {type: 'MultiLineString', coordinates}; + + } else if (this.type === 3) { + const polygons = classifyRings(vtCoords); + const coordinates = []; + for (const polygon of polygons) { + coordinates.push(polygon.map(projectLine)); + } + geometry = coordinates.length === 1 ? + {type: 'Polygon', coordinates: coordinates[0]} : + {type: 'MultiPolygon', coordinates}; + } else { + + throw new Error('unknown feature type'); + } + + /** @type {Feature} */ + const result = { + type: 'Feature', + geometry, + properties: this.properties + }; + + if (this.id != null) { + result.id = this.id; + } + + return result; + } +} + +/** @type {['Unknown', 'Point', 'LineString', 'Polygon']} */ +VectorTileFeature.types = ['Unknown', 'Point', 'LineString', 'Polygon']; + +/** classifies an array of rings into polygons with outer rings and holes + * @param {Point[][]} rings + */ +export function classifyRings(rings) { + const len = rings.length; + + if (len <= 1) return [rings]; + + const polygons = []; + let polygon, ccw; + + for (let i = 0; i < len; i++) { + const area = signedArea(rings[i]); + if (area === 0) continue; + + if (ccw === undefined) ccw = area < 0; + + if (ccw === area < 0) { + if (polygon) polygons.push(polygon); + polygon = [rings[i]]; + + } else if (polygon) { + polygon.push(rings[i]); + } + } + if (polygon) polygons.push(polygon); + + return polygons; +} + +/** @param {Point[]} ring */ +function signedArea(ring) { + let sum = 0; + for (let i = 0, len = ring.length, j = len - 1, p1, p2; i < len; j = i++) { + p1 = ring[i]; + p2 = ring[j]; + sum += (p2.x - p1.x) * (p1.y + p2.y); + } + return sum; +} + +export class VectorTileLayer { + /** + * @param {Pbf} pbf + * @param {number} [end] + */ + constructor(pbf, end) { + // Public + this.version = 1; + this.name = ''; + this.extent = 4096; + this.length = 0; + + /** @private */ + this._pbf = pbf; + + /** @private + * @type {string[]} */ + this._keys = []; + + /** @private + * @type {(number | string | boolean)[]} */ + this._values = []; + + /** @private + * @type {number[]} */ + this._features = []; + + if (end === undefined) end = pbf.length; + while (pbf.pos < end) { + const tag = pbf.readVarint(); + if (tag === 10) this.name = pbf.readString(); + else if (tag === 18) { + this._features.push(pbf.pos); + pbf.skip(tag); + } else if (tag === 26) this._keys.push(pbf.readString()); + else if (tag === 34) this._values.push(readValueMessage(pbf)); + else if (tag === 40) this.extent = pbf.readVarint(); + else if (tag === 120) this.version = pbf.readVarint(); + else pbf.skip(tag); + } + + this.length = this._features.length; + } + + /** return feature `i` from this layer as a `VectorTileFeature` + * @param {number} i + */ + feature(i) { + if (i < 0 || i >= this._features.length) throw new Error('feature index out of bounds'); + + this._pbf.pos = this._features[i]; + + const end = this._pbf.readVarint() + this._pbf.pos; + return new VectorTileFeature(this._pbf, end, this.extent, this._keys, this._values); + } +} + +/** + * @param {Pbf} pbf + */ +function readValueMessage(pbf) { + let value = null; + const end = pbf.readVarint() + pbf.pos; + + while (pbf.pos < end) { + const tag = pbf.readVarint(); + value = + tag === 10 ? pbf.readString() : + tag === 21 ? pbf.readFloat() : + tag === 25 ? pbf.readDouble() : + tag === 32 ? pbf.readVarint64() : + tag === 40 ? pbf.readVarint() : + tag === 48 ? pbf.readSVarint() : + tag === 56 ? pbf.readBoolean() : + (pbf.skip(tag), null); + } + if (value == null) { + throw new Error('unknown feature value'); + } + + return value; +} + +export class VectorTile { + /** + * @param {Pbf} pbf + * @param {number} [end] + */ + constructor(pbf, end = pbf.length) { + /** @type {Record} */ + const layers = Object.create(null); + while (pbf.pos < end) { + const tag = pbf.readVarint(); + if (tag === 26) { + const layer = new VectorTileLayer(pbf, pbf.readVarint() + pbf.pos); + if (layer.length) layers[layer.name] = layer; + } else pbf.skip(tag); + } + this.layers = layers; + } +} diff --git a/node_modules/@mapbox/vector-tile/package.json b/node_modules/@mapbox/vector-tile/package.json new file mode 100644 index 0000000000000000000000000000000000000000..c3e99d209d64f48dff2df5ac49f84f433a38eb9a --- /dev/null +++ b/node_modules/@mapbox/vector-tile/package.json @@ -0,0 +1,34 @@ +{ + "name": "@mapbox/vector-tile", + "description": "Parses vector tiles", + "repository": { + "url": "git+https://github.com/mapbox/vector-tile-js.git" + }, + "version": "2.0.5", + "type": "module", + "exports": "./index.js", + "license": "BSD-3-Clause", + "main": "index.js", + "types": "index.d.ts", + "dependencies": { + "@mapbox/point-geometry": "~1.1.0", + "@types/geojson": "^7946.0.16", + "pbf": "^4.0.2" + }, + "devDependencies": { + "benchmark": "^2.1.4", + "eslint": "^10.4.0", + "eslint-config-mourner": "^4.1.0", + "typescript": "^6.0.3" + }, + "scripts": { + "lint": "eslint index.js test/*.js", + "pretest": "npm run lint", + "test": "tsc && node --test", + "cov": "node --test --experimental-test-coverage", + "prepublishOnly": "npm test" + }, + "files": [ + "index.d.ts" + ] +} diff --git a/node_modules/@modelcontextprotocol/sdk/LICENSE b/node_modules/@modelcontextprotocol/sdk/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..3d48435454b105021b4f777c11b6b07d8d2ffea3 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Anthropic, PBC + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@modelcontextprotocol/sdk/README.md b/node_modules/@modelcontextprotocol/sdk/README.md new file mode 100644 index 0000000000000000000000000000000000000000..2d2f19ae376bee6081437c4d6f8e251bf3fd3ce5 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/README.md @@ -0,0 +1,172 @@ +# MCP TypeScript SDK [![NPM Version](https://img.shields.io/npm/v/%40modelcontextprotocol%2Fsdk)](https://www.npmjs.com/package/@modelcontextprotocol/sdk) [![MIT licensed](https://img.shields.io/npm/l/%40modelcontextprotocol%2Fsdk)](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/LICENSE) + +
+Table of Contents + +- [Overview](#overview) +- [Installation](#installation) +- [Quick Start](#quick-start) +- [Core Concepts](#core-concepts) +- [Examples](#examples) +- [Documentation](#documentation) +- [Contributing](#contributing) +- [License](#license) + +
+ +## Overview + +The Model Context Protocol allows applications to provide context for LLMs in a standardized way, separating the concerns of providing context from the actual LLM interaction. This TypeScript SDK implements +[the full MCP specification](https://modelcontextprotocol.io/specification/draft), making it easy to: + +- Create MCP servers that expose resources, prompts and tools +- Build MCP clients that can connect to any MCP server +- Use standard transports like stdio and Streamable HTTP + +## Installation + +```bash +npm install @modelcontextprotocol/sdk zod +``` + +This SDK has a **required peer dependency** on `zod` for schema validation. The SDK internally imports from `zod/v4`, but maintains backwards compatibility with projects using Zod v3.25 or later. You can use either API in your code by importing from `zod/v3` or `zod/v4`: + +## Quick Start + +To see the SDK in action end-to-end, start from the runnable examples in `src/examples`: + +1. **Install dependencies** (from the SDK repo root): + + ```bash + npm install + ``` + +2. **Run the example Streamable HTTP server**: + + ```bash + npx tsx src/examples/server/simpleStreamableHttp.ts + ``` + +3. **Run the interactive client in another terminal**: + + ```bash + npx tsx src/examples/client/simpleStreamableHttp.ts + ``` + +This pair of examples demonstrates tools, resources, prompts, sampling, elicitation, tasks and logging. For a guided walkthrough and variations (stateless servers, JSON-only responses, SSE compatibility, OAuth, etc.), see [docs/server.md](docs/server.md) and +[docs/client.md](docs/client.md). + +## Core Concepts + +### Servers and transports + +An MCP server is typically created with `McpServer` and connected to a transport such as Streamable HTTP or stdio. The SDK supports: + +- **Streamable HTTP** for remote servers (recommended). +- **HTTP + SSE** for backwards compatibility only. +- **stdio** for local, process-spawned integrations. + +Runnable server examples live under `src/examples/server` and are documented in [docs/server.md](docs/server.md). + +### Tools, resources, prompts + +- **Tools** let LLMs ask your server to take actions (computation, side effects, network calls). +- **Resources** expose read-only data that clients can surface to users or models. +- **Prompts** are reusable templates that help users talk to models in a consistent way. + +The detailed APIs, including `ResourceTemplate`, completions, and display-name metadata, are covered in [docs/server.md](docs/server.md#tools-resources-and-prompts), with runnable implementations in [`simpleStreamableHttp.ts`](src/examples/server/simpleStreamableHttp.ts). + +### Capabilities: sampling, elicitation, and tasks + +The SDK includes higher-level capabilities for richer workflows: + +- **Sampling**: server-side tools can ask connected clients to run LLM completions. +- **Form elicitation**: tools can request non-sensitive input via structured forms. +- **URL elicitation**: servers can ask users to complete secure flows in a browser (e.g., API key entry, payments, OAuth). +- **Tasks (experimental)**: long-running tool calls can be turned into tasks that you poll or resume later. + +Conceptual overviews and links to runnable examples are in: + +- [docs/capabilities.md](docs/capabilities.md) + +Key example servers include: + +- [`toolWithSampleServer.ts`](src/examples/server/toolWithSampleServer.ts) +- [`elicitationFormExample.ts`](src/examples/server/elicitationFormExample.ts) +- [`elicitationUrlExample.ts`](src/examples/server/elicitationUrlExample.ts) + +### Clients + +The high-level `Client` class connects to MCP servers over different transports and exposes helpers like `listTools`, `callTool`, `listResources`, `readResource`, `listPrompts`, and `getPrompt`. + +Runnable clients live under `src/examples/client` and are described in [docs/client.md](docs/client.md), including: + +- Interactive Streamable HTTP client ([`simpleStreamableHttp.ts`](src/examples/client/simpleStreamableHttp.ts)) +- Streamable HTTP client with SSE fallback ([`streamableHttpWithSseFallbackClient.ts`](src/examples/client/streamableHttpWithSseFallbackClient.ts)) +- OAuth-enabled clients and polling/parallel examples + +### Node.js Web Crypto (globalThis.crypto) compatibility + +Some parts of the SDK (for example, JWT-based client authentication in `auth-extensions.ts` via `jose`) rely on the Web Crypto API exposed as `globalThis.crypto`. + +See [docs/faq.md](docs/faq.md) for details on supported Node.js versions and how to polyfill `globalThis.crypto` when running on older Node.js runtimes. + +## Examples + +The SDK ships runnable examples under `src/examples`. Use these tables to find the scenario you care about and jump straight to the corresponding code and docs. + +### Server examples + +| Scenario | Description | Example file(s) | Related docs | +| --------------------------------------------------- | ------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ | +| Streamable HTTP server (stateful) | Feature-rich server with tools, resources, prompts, logging, tasks, sampling, and optional OAuth. | [`simpleStreamableHttp.ts`](src/examples/server/simpleStreamableHttp.ts) | [`server.md`](docs/server.md), [`capabilities.md`](docs/capabilities.md) | +| Streamable HTTP server (stateless) | No session tracking; good for simple API-style servers. | [`simpleStatelessStreamableHttp.ts`](src/examples/server/simpleStatelessStreamableHttp.ts) | [`server.md`](docs/server.md) | +| JSON response mode (no SSE) | Streamable HTTP with JSON responses only and limited notifications. | [`jsonResponseStreamableHttp.ts`](src/examples/server/jsonResponseStreamableHttp.ts) | [`server.md`](docs/server.md) | +| Server notifications over Streamable HTTP | Demonstrates server-initiated notifications using SSE with Streamable HTTP. | [`standaloneSseWithGetStreamableHttp.ts`](src/examples/server/standaloneSseWithGetStreamableHttp.ts) | [`server.md`](docs/server.md) | +| Deprecated HTTP+SSE server | Legacy HTTP+SSE transport for backwards-compatibility testing. | [`simpleSseServer.ts`](src/examples/server/simpleSseServer.ts) | [`server.md`](docs/server.md) | +| Backwards-compatible server (Streamable HTTP + SSE) | Single server that supports both Streamable HTTP and legacy SSE clients. | [`sseAndStreamableHttpCompatibleServer.ts`](src/examples/server/sseAndStreamableHttpCompatibleServer.ts) | [`server.md`](docs/server.md) | +| Form elicitation server | Uses form elicitation to collect non-sensitive user input. | [`elicitationFormExample.ts`](src/examples/server/elicitationFormExample.ts) | [`capabilities.md`](docs/capabilities.md#elicitation) | +| URL elicitation server | Demonstrates URL-mode elicitation in an OAuth-protected server. | [`elicitationUrlExample.ts`](src/examples/server/elicitationUrlExample.ts) | [`capabilities.md`](docs/capabilities.md#elicitation) | +| Sampling and tasks server | Combines tools, logging, sampling, and experimental task-based execution. | [`toolWithSampleServer.ts`](src/examples/server/toolWithSampleServer.ts) | [`capabilities.md`](docs/capabilities.md) | +| OAuth demo authorization server | In-memory OAuth provider used with the example servers. | [`demoInMemoryOAuthProvider.ts`](src/examples/server/demoInMemoryOAuthProvider.ts) | [`server.md`](docs/server.md) | + +### Client examples + +| Scenario | Description | Example file(s) | Related docs | +| --------------------------------------------------- | ---------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ | +| Interactive Streamable HTTP client | CLI client that exercises tools, resources, prompts, elicitation, and tasks. | [`simpleStreamableHttp.ts`](src/examples/client/simpleStreamableHttp.ts) | [`client.md`](docs/client.md) | +| Backwards-compatible client (Streamable HTTP → SSE) | Tries Streamable HTTP first, then falls back to SSE on 4xx responses. | [`streamableHttpWithSseFallbackClient.ts`](src/examples/client/streamableHttpWithSseFallbackClient.ts) | [`client.md`](docs/client.md), [`server.md`](docs/server.md) | +| SSE polling client | Polls a legacy SSE server and demonstrates notification handling. | [`ssePollingClient.ts`](src/examples/client/ssePollingClient.ts) | [`client.md`](docs/client.md) | +| Parallel tool calls client | Shows how to run multiple tool calls in parallel. | [`parallelToolCallsClient.ts`](src/examples/client/parallelToolCallsClient.ts) | [`client.md`](docs/client.md) | +| Multiple clients in parallel | Demonstrates connecting multiple clients concurrently to the same server. | [`multipleClientsParallel.ts`](src/examples/client/multipleClientsParallel.ts) | [`client.md`](docs/client.md) | +| OAuth clients | Examples of client_credentials (basic and private_key_jwt) and reusable providers. | [`simpleOAuthClient.ts`](src/examples/client/simpleOAuthClient.ts), [`simpleOAuthClientProvider.ts`](src/examples/client/simpleOAuthClientProvider.ts), [`simpleClientCredentials.ts`](src/examples/client/simpleClientCredentials.ts) | [`client.md`](docs/client.md) | +| URL elicitation client | Works with the URL elicitation server to drive secure browser flows. | [`elicitationUrlExample.ts`](src/examples/client/elicitationUrlExample.ts) | [`capabilities.md`](docs/capabilities.md#elicitation) | + +Shared utilities: + +- In-memory event store for resumability: [`inMemoryEventStore.ts`](src/examples/shared/inMemoryEventStore.ts) (see [`server.md`](docs/server.md)). + +For more details on how to run these examples (including recommended commands and deployment diagrams), see `src/examples/README.md`. + +## Documentation + +- Local SDK docs: + - [docs/server.md](docs/server.md) – building and running MCP servers, transports, tools/resources/prompts, CORS, DNS rebinding, and multi-node deployment. + - [docs/client.md](docs/client.md) – using the high-level client, transports, backwards compatibility, and OAuth helpers. + - [docs/capabilities.md](docs/capabilities.md) – sampling, elicitation (form and URL), and experimental task-based execution. + - [docs/protocol.md](docs/protocol.md) – protocol features: ping, progress, cancellation, pagination, capability negotiation, and JSON Schema. + - [docs/faq.md](docs/faq.md) – environment and troubleshooting FAQs (including Node.js Web Crypto support). +- External references: + - [V1 API reference](https://modelcontextprotocol.github.io/typescript-sdk/) + - [V2 API reference](https://modelcontextprotocol.github.io/typescript-sdk/v2/) + - [Model Context Protocol documentation](https://modelcontextprotocol.io) + - [MCP Specification](https://spec.modelcontextprotocol.io) + - [Example Servers](https://github.com/modelcontextprotocol/servers) + +## Contributing + +Issues and pull requests are welcome on GitHub at . + +## License + +This project is licensed under the MIT License—see the [LICENSE](LICENSE) file for details. diff --git a/node_modules/@modelcontextprotocol/sdk/package.json b/node_modules/@modelcontextprotocol/sdk/package.json new file mode 100644 index 0000000000000000000000000000000000000000..22d26ca56e0d3611f8865c476b604791967de173 --- /dev/null +++ b/node_modules/@modelcontextprotocol/sdk/package.json @@ -0,0 +1,164 @@ +{ + "name": "@modelcontextprotocol/sdk", + "version": "1.29.0", + "description": "Model Context Protocol implementation for TypeScript", + "license": "MIT", + "author": "Anthropic, PBC (https://anthropic.com)", + "homepage": "https://modelcontextprotocol.io", + "bugs": "https://github.com/modelcontextprotocol/typescript-sdk/issues", + "type": "module", + "repository": { + "type": "git", + "url": "git+https://github.com/modelcontextprotocol/typescript-sdk.git" + }, + "engines": { + "node": ">=18" + }, + "keywords": [ + "modelcontextprotocol", + "mcp" + ], + "exports": { + ".": { + "types": "./dist/esm/index.d.ts", + "import": "./dist/esm/index.js", + "require": "./dist/cjs/index.js" + }, + "./client": { + "types": "./dist/esm/client/index.d.ts", + "import": "./dist/esm/client/index.js", + "require": "./dist/cjs/client/index.js" + }, + "./server": { + "types": "./dist/esm/server/index.d.ts", + "import": "./dist/esm/server/index.js", + "require": "./dist/cjs/server/index.js" + }, + "./validation": { + "types": "./dist/esm/validation/index.d.ts", + "import": "./dist/esm/validation/index.js", + "require": "./dist/cjs/validation/index.js" + }, + "./validation/ajv": { + "types": "./dist/esm/validation/ajv-provider.d.ts", + "import": "./dist/esm/validation/ajv-provider.js", + "require": "./dist/cjs/validation/ajv-provider.js" + }, + "./validation/cfworker": { + "types": "./dist/esm/validation/cfworker-provider.d.ts", + "import": "./dist/esm/validation/cfworker-provider.js", + "require": "./dist/cjs/validation/cfworker-provider.js" + }, + "./experimental": { + "types": "./dist/esm/experimental/index.d.ts", + "import": "./dist/esm/experimental/index.js", + "require": "./dist/cjs/experimental/index.js" + }, + "./experimental/tasks": { + "types": "./dist/esm/experimental/tasks/index.d.ts", + "import": "./dist/esm/experimental/tasks/index.js", + "require": "./dist/cjs/experimental/tasks/index.js" + }, + "./*": { + "types": "./dist/esm/*.d.ts", + "import": "./dist/esm/*", + "require": "./dist/cjs/*" + } + }, + "typesVersions": { + "*": { + "*": [ + "./dist/esm/*" + ] + } + }, + "files": [ + "dist" + ], + "scripts": { + "fetch:spec-types": "tsx scripts/fetch-spec-types.ts", + "typecheck": "tsgo --noEmit", + "build": "npm run build:esm && npm run build:cjs", + "build:esm": "mkdir -p dist/esm && echo '{\"type\": \"module\"}' > dist/esm/package.json && tsc -p tsconfig.prod.json", + "build:esm:w": "npm run build:esm -- -w", + "build:cjs": "mkdir -p dist/cjs && echo '{\"type\": \"commonjs\"}' > dist/cjs/package.json && tsc -p tsconfig.cjs.json", + "build:cjs:w": "npm run build:cjs -- -w", + "examples:simple-server:w": "tsx --watch src/examples/server/simpleStreamableHttp.ts --oauth", + "prepack": "npm run build:esm && npm run build:cjs", + "lint": "eslint src/ && prettier --check .", + "lint:fix": "eslint src/ --fix && prettier --write .", + "check": "npm run typecheck && npm run lint", + "test": "vitest run", + "test:watch": "vitest", + "start": "npm run server", + "server": "tsx watch --clear-screen=false scripts/cli.ts server", + "client": "tsx scripts/cli.ts client", + "test:conformance:server": "test/conformance/scripts/run-server-conformance.sh --expected-failures test/conformance/conformance-baseline.yml", + "test:conformance:server:all": "test/conformance/scripts/run-server-conformance.sh --suite all --expected-failures test/conformance/conformance-baseline.yml", + "test:conformance:server:run": "npx tsx test/conformance/src/everythingServer.ts", + "test:conformance:client": "npx @modelcontextprotocol/conformance client --command 'npx tsx test/conformance/src/everythingClient.ts' --expected-failures test/conformance/conformance-baseline.yml", + "test:conformance:client:all": "npx @modelcontextprotocol/conformance client --command 'npx tsx test/conformance/src/everythingClient.ts' --suite all --expected-failures test/conformance/conformance-baseline.yml" + }, + "dependencies": { + "@hono/node-server": "^1.19.9", + "ajv": "^8.17.1", + "ajv-formats": "^3.0.1", + "content-type": "^1.0.5", + "cors": "^2.8.5", + "cross-spawn": "^7.0.5", + "eventsource": "^3.0.2", + "eventsource-parser": "^3.0.0", + "express": "^5.2.1", + "express-rate-limit": "^8.2.1", + "hono": "^4.11.4", + "jose": "^6.1.3", + "json-schema-typed": "^8.0.2", + "pkce-challenge": "^5.0.0", + "raw-body": "^3.0.0", + "zod": "^3.25 || ^4.0", + "zod-to-json-schema": "^3.25.1" + }, + "peerDependencies": { + "@cfworker/json-schema": "^4.1.1", + "zod": "^3.25 || ^4.0" + }, + "peerDependenciesMeta": { + "@cfworker/json-schema": { + "optional": true + }, + "zod": { + "optional": false + } + }, + "devDependencies": { + "@cfworker/json-schema": "^4.1.1", + "@eslint/js": "^9.39.1", + "@modelcontextprotocol/conformance": "^0.1.14", + "@types/content-type": "^1.1.8", + "@types/cors": "^2.8.17", + "@types/cross-spawn": "^6.0.6", + "@types/eventsource": "^1.1.15", + "@types/express": "^5.0.0", + "@types/express-serve-static-core": "^5.1.0", + "@types/node": "^22.12.0", + "@types/supertest": "^6.0.2", + "@types/ws": "^8.5.12", + "@typescript/native-preview": "^7.0.0-dev.20251103.1", + "eslint": "^9.8.0", + "eslint-config-prettier": "^10.1.8", + "eslint-plugin-n": "^17.23.1", + "prettier": "3.6.2", + "supertest": "^7.0.0", + "tsx": "^4.16.5", + "typescript": "^5.5.4", + "typescript-eslint": "^8.48.1", + "vitest": "^4.0.8", + "ws": "^8.18.0" + }, + "resolutions": { + "strip-ansi": "6.0.1" + }, + "overrides": { + "qs": "6.14.1" + } +} diff --git a/node_modules/@mswjs/interceptors/ClientRequest/package.json b/node_modules/@mswjs/interceptors/ClientRequest/package.json new file mode 100644 index 0000000000000000000000000000000000000000..483dc2463c0f5c20fdcd7f967eb345c278283d34 --- /dev/null +++ b/node_modules/@mswjs/interceptors/ClientRequest/package.json @@ -0,0 +1,11 @@ +{ + "main": "../lib/node/interceptors/ClientRequest/index.cjs", + "module": "../lib/node/interceptors/ClientRequest/index.mjs", + "browser": null, + "exports": { + ".": { + "import": "./../lib/node/interceptors/ClientRequest/index.mjs", + "default": "./../lib/node/interceptors/ClientRequest/index.cjs" + } + } +} diff --git a/node_modules/@mswjs/interceptors/LICENSE.md b/node_modules/@mswjs/interceptors/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..e5c461e5fd63682eba93307cade8b073c7782489 --- /dev/null +++ b/node_modules/@mswjs/interceptors/LICENSE.md @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) 2018–present Artem Zakharchenko + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@mswjs/interceptors/README.md b/node_modules/@mswjs/interceptors/README.md new file mode 100644 index 0000000000000000000000000000000000000000..fb5e324f65124bdefea78a28ee79c3355cb8dc65 --- /dev/null +++ b/node_modules/@mswjs/interceptors/README.md @@ -0,0 +1,638 @@ +[![Latest version](https://img.shields.io/npm/v/@mswjs/interceptors.svg)](https://www.npmjs.com/package/@mswjs/interceptors) + +# `@mswjs/interceptors` + +Low-level network interception library. + +This library supports intercepting the following protocols: + +- HTTP (via the `http` module, `XMLHttpRequest`, or `globalThis.fetch`); +- [WebSocket](#websocket-interception) (the `WebSocket` class in Undici and in the browser). + +## Motivation + +While there are a lot of network mocking libraries, they tend to use request interception as an implementation detail, giving you a high-level API that includes request matching, timeouts, recording, and so forth. + +This library is a barebones implementation that provides as little abstraction as possible to execute arbitrary logic upon any request. It's primarily designed as an underlying component for high-level API mocking solutions such as [Mock Service Worker](https://github.com/mswjs/msw). + +### How is this library different? + +A traditional API mocking implementation in Node.js looks roughly like this: + +```js +import http from 'node:http' + +// Store the original request function. +const originalHttpRequest = http.request + +// Override the request function entirely. +http.request = function (...args) { + // Decide if the outgoing request matches a predicate. + if (predicate(args)) { + // If it does, never create a request, respond to it + // using the mocked response from this blackbox. + return coerceToResponse.bind(this, mock) + } + + // Otherwise, construct the original request + // and perform it as-is. + return originalHttpRequest(...args) +} +``` + +The core philosophy of Interceptors is to _run as much of the underlying network code as possible_. Strange for a network mocking library, isn't it? Turns out, respecting the system's integrity and executing more of the network code leads to more resilient tests and also helps to uncover bugs in the code that would otherwise go unnoticed. + +Interceptors heavily rely on _class extension_ instead of function and module overrides. By extending the native network code, it can surgically insert the interception and mocking pieces only where necessary, leaving the rest of the system intact. + +```js +class XMLHttpRequestProxy extends XMLHttpRequest { + async send() { + // Call the request listeners and see if any of them + // returns a mocked response for this request. + const mockedResponse = await waitForRequestListeners({ request }) + + // If there is a mocked response, use it. This actually + // transitions the XMLHttpRequest instance into the correct + // response state (below is a simplified illustration). + if (mockedResponse) { + // Handle the response headers. + this.request.status = mockedResponse.status + this.request.statusText = mockedResponse.statusText + this.request.responseUrl = mockedResponse.url + this.readyState = 2 + this.trigger('readystatechange') + + // Start streaming the response body. + this.trigger('loadstart') + this.readyState = 3 + this.trigger('readystatechange') + await streamResponseBody(mockedResponse) + + // Finish the response. + this.trigger('load') + this.trigger('loadend') + this.readyState = 4 + return + } + + // Otherwise, perform the original "XMLHttpRequest.prototype.send" call. + return super.send(...args) + } +} +``` + +> The request interception algorithms differ dramatically based on the request API. Interceptors accommodate for them all, bringing the intercepted requests to a common ground—the Fetch API `Request` instance. The same applies for responses, where a Fetch API `Response` instance is translated to the appropriate response format. + +This library aims to provide _full specification compliance_ with the APIs and protocols it extends. + +## What this library does + +This library extends the following native modules: + +- `http.get`/`http.request` +- `https.get`/`https.request` +- `XMLHttpRequest` +- `fetch` +- `WebSocket` + +Once extended, it intercepts and normalizes all requests to the Fetch API `Request` instances. This way, no matter the request source (`http.ClientRequest`, `XMLHttpRequest`, `window.Request`, etc), you always get a specification-compliant request instance to work with. + +You can respond to the intercepted HTTP request by constructing a Fetch API Response instance. Instead of designing custom abstractions, this library respects the Fetch API specification and takes the responsibility to coerce a single response declaration to the appropriate response formats based on the request-issuing modules (like `http.OutgoingMessage` to respond to `http.ClientRequest`, or updating `XMLHttpRequest` response-related properties). + +## What this library doesn't do + +- Does **not** provide any request matching logic; +- Does **not** handle requests by default. + +## Limitations + +- Interceptors will hang indefinitely if you call `req.end()` in the `connect` event listener of the respective `socket`: + +```ts +req.on('socket', (socket) => { + socket.on('connect', () => { + // ❌ While this is allowed in Node.js, this cannot be handled in Interceptors. + req.end() + }) +}) +``` + +> This limitation is intrinsic to the interception algorithm used by the library. In order for it to emit the `connect` event on the socket, the library must know if you've handled the request in any way (e.g. responded with a mocked response or errored it). For that, it emits the `request` event on the interceptor where you can handle the request. Since you can consume the request stream in the `request` event, it waits until the request body stream is complete (i.e. until `req.end()` is called). This creates a catch 22 that causes this limitation. + +## Getting started + +```bash +npm install @mswjs/interceptors +``` + +## Interceptors + +To use this library you need to choose one or multiple interceptors to apply. There are different interceptors exported by this library to spy on respective request-issuing modules: + +- `ClientRequestInterceptor` to spy on `http.ClientRequest` (`http.get`/`http.request`); +- `XMLHttpRequestInterceptor` to spy on `XMLHttpRequest`; +- `FetchInterceptor` to spy on `fetch`. + +Use an interceptor by constructing it and attaching request/response listeners: + +```js +import { ClientRequestInterceptor } from '@mswjs/interceptors/ClientRequest' + +const interceptor = new ClientRequestInterceptor() + +// Enable the interception of requests. +interceptor.apply() + +// Listen to any "http.ClientRequest" being dispatched, +// and log its method and full URL. +interceptor.on('request', ({ request, requestId }) => { + console.log(request.method, request.url) +}) + +// Listen to any responses sent to "http.ClientRequest". +// Note that this listener is read-only and cannot affect responses. +interceptor.on( + 'response', + ({ response, isMockedResponse, request, requestId }) => { + console.log('response to %s %s was:', request.method, request.url, response) + } +) +``` + +All HTTP request interceptors implement the same events: + +- `request`, emitted whenever a request has been dispatched; +- `response`, emitted whenever any request receives a response. + +### Using multiple interceptors + +You can combine multiple interceptors to capture requests from different request-issuing modules at once. + +```js +import { BatchInterceptor } from '@mswjs/interceptors' +import { ClientRequestInterceptor } from '@mswjs/interceptors/ClientRequest' +import { XMLHttpRequestInterceptor } from '@mswjs/interceptors/XMLHttpRequest' + +const interceptor = new BatchInterceptor({ + name: 'my-interceptor', + interceptors: [ + new ClientRequestInterceptor(), + new XMLHttpRequestInterceptor(), + ], +}) + +interceptor.apply() + +// This "request" listener will be called on both +// "http.ClientRequest" and "XMLHttpRequest" being dispatched. +interceptor.on('request', listener) +``` + +> Note that you can use [pre-defined presets](#presets) that cover all the request sources for a given environment type. + +## Presets + +When using [`BatchInterceptor`](#batchinterceptor), you can provide a pre-defined preset to its "interceptors" option to capture all request for that environment. + +### Node.js preset + +This preset combines `ClientRequestInterceptor`, `XMLHttpRequestInterceptor` and is meant to be used in Node.js. + +```js +import { BatchInterceptor } from '@mswjs/interceptors' +import nodeInterceptors from '@mswjs/interceptors/presets/node' + +const interceptor = new BatchInterceptor({ + name: 'my-interceptor', + interceptors: nodeInterceptors, +}) + +interceptor.apply() + +interceptor.on('request', listener) +``` + +### Browser preset + +This preset combines `XMLHttpRequestInterceptor` and `FetchInterceptor` and is meant to be used in a browser. + +```js +import { BatchInterceptor } from '@mswjs/interceptors' +import browserInterceptors from '@mswjs/interceptors/presets/browser' + +const interceptor = new BatchInterceptor({ + name: 'my-interceptor', + interceptors: browserInterceptors, +}) + +interceptor.on('request', listener) +``` + +## Introspecting requests + +All HTTP request interceptors emit a "request" event. In the listener to this event, they expose a `request` reference, which is a [Fetch API Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) instance. + +> There are many ways to describe a request in Node.js but this library coerces different request definitions to a single specification-compliant `Request` instance to make the handling consistent. + +```js +interceptor.on('request', ({ request, requestId, controller }) => { + console.log(request.method, request.url) +}) +``` + +Since the exposed `request` instance implements the Fetch API specification, you can operate with it just as you do with the regular browser request. For example, this is how you would read the request body as JSON: + +```js +interceptor.on('request', async ({ request, requestId }) => { + const json = await request.clone().json() +}) +``` + +> **Do not forget to clone the request before reading its body!** + +## Modifying requests + +Request representations are readonly. You can, however, mutate the intercepted request's headers in the "request" listener: + +```js +interceptor.on('request', ({ request }) => { + request.headers.set('X-My-Header', 'true') +}) +``` + +> This restriction is done so that the library wouldn't have to unnecessarily synchronize the actual request instance and its Fetch API request representation. As of now, this library is not meant to be used as a full-scale proxy. + +## Mocking responses + +Although this library can be used purely for request introspection purposes, you can also affect request resolution by responding to any intercepted request within the "request" event. + +Access the `controller` object from the request event listener arguments and call its `controller.respondWith()` method, providing it with a mocked `Response` instance: + +```js +interceptor.on('request', ({ request, controller }) => { + controller.respondWith( + new Response( + JSON.stringify({ + firstName: 'John', + lastName: 'Maverick', + }), + { + status: 201, + statusText: 'Created', + headers: { + 'Content-Type': 'application/json', + }, + } + ) + ) +}) +``` + +> We use Fetch API `Response` class as the middle-ground for mocked response definition. This library then coerces the response instance to the appropriate response format (e.g. to `http.OutgoingMessage` in the case of `http.ClientRequest`). + +**The `Response` class is built-in in since Node.js 18. Use a Fetch API-compatible polyfill, like `node-fetch`, for older versions of Node.js.`** + +Note that a single request _can only be handled once_. You may want to introduce conditional logic, like routing, in your request listener but it's generally advised to use a higher-level library like [Mock Service Worker](https://github.com/mswjs/msw) that does request matching for you. + +Requests must be responded to within the same tick as the request listener. This means you cannot respond to a request using `setTimeout`, as this will delegate the callback to the next tick. If you wish to introduce asynchronous side-effects in the listener, consider making it an `async` function, awaiting any side-effects you need. + +```js +// Respond to all requests with a 500 response +// delayed by 500ms. +interceptor.on('request', async ({ controller }) => { + await sleep(500) + controller.respondWith(new Response(null, { status: 500 })) +}) +``` + +### Mocking response errors + +You can provide an instance of `Response.error()` to error the pending request. + +```js +interceptor.on('request', ({ request, controller }) => { + controller.respondWith(Response.error()) +}) +``` + +This will automatically translate to the appropriate request error based on the request client that issued the request. **Use this method to produce a generic network error**. + +> Note that the standard `Response.error()` API does not accept an error message. + +## Mocking errors + +Use the `controller.errorWith()` method to error the request. + +```js +interceptor.on('request', ({ request, controller }) => { + controller.errorWith(new Error('reason')) +}) +``` + +Unlike responding with `Response.error()`, you can provide an exact error reason to use to `.errorWith()`. **Use this method to error the request**. + +> Note that it is up to the request client to respect your custom error. Some clients, like `ClientRequest` will use the provided error message, while others, like `fetch`, will produce a generic `TypeError: failed to fetch` responses. Interceptors will try to preserve the original error in the `cause` property of such generic errors. + +## Observing responses + +You can use the "response" event to transparently observe any incoming responses in your Node.js process. + +```js +interceptor.on( + 'response', + ({ response, isMockedResponse, request, requestId }) => { + // react to the incoming response... + } +) +``` + +> Note that the `isMockedResponse` property will only be set to `true` if you resolved this request in the "request" event listener using the `controller.respondWith()` method and providing a mocked `Response` instance. + +## Error handling + +By default, all unhandled exceptions thrown within the `request` listener are coerced to 500 error responses, emulating those exceptions occurring on the actual server. You can listen to the exceptions by adding the `unhandledException` listener to the interceptor: + +```js +interceptor.on( + 'unhandledException', + ({ error, request, requestId, controller }) => { + console.log(error) + } +) +``` + +To opt out from the default coercion of unhandled exceptions to server responses, you need to either: + +1. Respond to the request with [a mocked response](#mocking-responses) (including error responses); +1. Propagate the error up by throwing it explicitly in the `unhandledException` listener. + +Here's an example of propagating the unhandled exception up: + +```js +interceptor.on('unhandledException', ({ error }) => { + // Now, any unhandled exception will NOT be coerced to a 500 error response, + // and instead will be thrown during the process execution as-is. + throw error +}) +``` + +## WebSocket interception + +You can intercept a WebSocket communication using the `WebSocketInterceptor` class. + +> [!IMPORTANT] +> This library only supports intercepting WebSocket connections created using the global WHATWG `WebSocket` class. Third-party transports, such as HTTP/XHR polling, are not supported by design due to their contrived nature. + +```js +import { WebSocketInterceptor } from '@mswjs/interceptors/WebSocket' + +const interceptor = new WebSocketInterceptor() +``` + +Unlike the HTTP-based interceptors that share the same `request`/`response` events, the WebSocket interceptor only emits the `connection` event and let's you handle the incoming/outgoing events in its listener. + +### Important defaults + +1. Intercepted WebSocket connections are _not opened_. To open the actual WebSocket connection, call [`server.connect()`](#connect) in the interceptor. +1. Once connected to the actual server, the outgoing client events are _forwarded to that server by default_. If you wish to prevent a client message from reaching the server, call `event.preventDefault()` for that client message event. +1. Once connected to the actual server, the incoming server events are _forwarded to the client by default_. If you wish to prevent a server message from reaching the client, call `event.preventDefault()` for the server message event. +1. Once connected to the actual server, the `close` event received from that server is _forwarded to the client by default_. If you wish to prevent that, call `event.preventDefault()` for that close event of the server. + +### WebSocket connection + +Whenever a WebSocket instance is constructed, the `connection` event is emitted on the WebSocket interceptor. + +```js +intereceptor.on('connection', ({ client }) => { + console.log(client.url) +}) +``` + +The `connection` event exposes the following arguments: + +| Name | Type | Description | +| -------- | --------------------------------------------------------- | ----------------------------------------------------------------------------------- | +| `client` | [`WebSocketClientConnection`](#websocketclientconnection) | An object representing a connected WebSocket client instance. | +| `server` | [`WebSocketServerConnection`](#websocketserverconnection) | An object representing the original WebSocket server connection. | +| `info` | `object` | Additional WebSocket connection information (like the original client `protocols`). | + +### `WebSocketClientConnection` + +#### `.addEventListener(type, listener)` + +- `type`, `string` +- `listener`, `EventListener` + +Adds an event listener to the given event type of the WebSocket client. + +```ts +interface WebSocketServerConnectionEventMap { + // Dispatched when the WebSocket client sends data. + message: (this: WebSocket, event: MessageEvent) => void + + // Dispatched when the WebSocket client is closed. + close: (this: WebSocket, event: CloseEvent) => void +} +``` + +```js +client.addEventListener('message', (event) => { + console.log('outgoing:', event.data) +}) +``` + +#### `.removeEventListener(type, listener)` + +- `type`, `string` +- `listener`, `EventListener` + +Removes the listener for the given event type. + +#### `.send(data)` + +- `data`, `string | Blob | ArrayBuffer` + +Sends the data to the intercepted WebSocket client. + +```js +client.send('text') +client.send(new Blob(['blob'])) +client.send(new TextEncoder().encode('array buffer')) +``` + +#### `.close(code, reason)` + +- `code`, close [status code](https://www.rfc-editor.org/rfc/rfc6455#section-7.4.1). +- `reason`, [close reason](https://www.rfc-editor.org/rfc/rfc6455#section-7.1.6). + +Closes the client connection. Unlike the regular `WebSocket.prototype.close()`, the `client.close()` method can accept a non-configurable status codes, such as 1001, 1003, etc. + +```js +// Gracefully close the connection with the +// intercepted WebSocket client. +client.close() +``` + +```js +// Terminate the connection by emulating +// the server unable to process the received data. +client.close(1003) +``` + +### `WebSocketServerConnection` + +#### `.connect()` + +Establishes the connection to the original WebSocket server. Connection cannot be awaited. Any data sent via `server.send()` while connecting is buffered and flushed once the connection is open. + +#### `.addEventListener(type, listener)` + +- `type`, `string` +- `listener`, `EventListener` + +Adds an event listener to the given event type of the WebSocket server. + +```ts +interface WebSocketServerConnectionEventMap { + // Dispatched when the server connection is open. + open: (this: WebSocket, event: Event) => void + + // Dispatched when the server sends data to the client. + message: (this: WebSocket, event: MessageEvent) => void + + // Dispatched when the server connection closes. + close: (this: WebSocket, event: CloseEvent) => void +} +``` + +```js +server.addEventListener('message', (event) => { + console.log('incoming:', event.data) +}) +``` + +#### `.removeEventListener(type, listener)` + +- `type`, `string` +- `listener`, `EventListener` + +Removes the listener for the given event type. + +#### `.send(data)` + +- `data`, `string | Blob | ArrayBuffer` + +Sends the data to the original WebSocket server. Useful in a combination with the client-sent events forwarding: + +```js +client.addEventListener('message', (event) => { + server.send(event.data) +}) +``` + +#### `.close()` + +Closes the connection with the original WebSocket server. Unlike `client.close()`, closing the server connection does not accept any arguments and always assumes a graceful closure. Sending data via `server.send()` after the connection has been closed will have no effect. + +## API + +### `Interceptor` + +A generic class implemented by all interceptors. You do not interact with this class directly. + +```ts +class Interceptor { + // Applies the interceptor, enabling the interception of requests + // in the current process. + apply(): void + + // Listens to the public interceptor events. + // For HTTP requests, these are "request' and "response" events. + on(event, listener): void + + // Cleans up any side-effects introduced by the interceptor + // and disables the interception of requests. + dispose(): void +} +``` + +**For public consumption, use [interceptors](#interceptors) instead**. + +### `BatchInterceptor` + +Applies multiple request interceptors at the same time. + +```js +import { BatchInterceptor } from '@mswjs/interceptors' +import nodeInterceptors from '@mswjs/interceptors/presets/node' + +const interceptor = new BatchInterceptor({ + name: 'my-interceptor', + interceptors: nodeInterceptors, +}) + +interceptor.apply() + +interceptor.on('request', ({ request, requestId }) => { + // Inspect the intercepted "request". + // Optionally, return a mocked response. +}) +``` + +> Using the `/presets/node` interceptors preset is the recommended way to ensure all requests get intercepted, regardless of their origin. + +### `RemoteHttpInterceptor` + +Enables request interception in the current process while delegating the response resolution logic to the _parent process_. **Requires the current process to be a child process**. Requires the parent process to establish a resolver by calling the `createRemoteResolver` function. + +```js +// child.js +import { RemoteHttpInterceptor } from '@mswjs/interceptors/RemoteHttpInterceptor' +import { ClientRequestInterceptor } from '@mswjs/interceptors/ClientRequest' + +const interceptor = new RemoteHttpInterceptor({ + // Alternatively, you can use presets. + interceptors: [new ClientRequestInterceptor()], +}) + +interceptor.apply() + +process.on('disconnect', () => { + interceptor.dispose() +}) +``` + +You can still listen to and handle any requests in the child process via the `request` event listener. Keep in mind that a single request can only be responded to once. + +### `RemoteHttpResolver` + +Resolves an intercepted request in the given child `process`. Requires for that child process to enable request interception by calling the `createRemoteInterceptor` function. + +```js +// parent.js +import { spawn } from 'child_process' +import { RemoteHttpResolver } from '@mswjs/interceptors/RemoteHttpInterceptor' + +const appProcess = spawn('node', ['app.js'], { + stdio: ['inherit', 'inherit', 'inherit', 'ipc'], +}) + +const resolver = new RemoteHttpResolver({ + process: appProcess, +}) + +resolver.on('request', ({ request, requestId }) => { + // Optionally, return a mocked response + // for a request that occurred in the "appProcess". +}) + +resolver.apply() +``` + +## Special mention + +The following libraries were used as an inspiration to write this low-level API: + +- [`node`](https://github.com/nodejs/node) +- [`nock`](https://github.com/nock/nock) +- [`mock-xmlhttprequest`](https://github.com/berniegp/mock-xmlhttprequest) diff --git a/node_modules/@mswjs/interceptors/RemoteHttpInterceptor/package.json b/node_modules/@mswjs/interceptors/RemoteHttpInterceptor/package.json new file mode 100644 index 0000000000000000000000000000000000000000..920f5fee53e48768d7d637ef3b700bf7e91f7b90 --- /dev/null +++ b/node_modules/@mswjs/interceptors/RemoteHttpInterceptor/package.json @@ -0,0 +1,11 @@ +{ + "main": "../lib/node/RemoteHttpInterceptor.cjs", + "module": "../lib/node/RemoteHttpInterceptor.mjs", + "browser": null, + "exports": { + ".": { + "import": "./../lib/node/RemoteHttpInterceptor.mjs", + "default": "./../lib/node/RemoteHttpInterceptor.cjs" + } + } +} diff --git a/node_modules/@mswjs/interceptors/WebSocket/package.json b/node_modules/@mswjs/interceptors/WebSocket/package.json new file mode 100644 index 0000000000000000000000000000000000000000..443ef0f77674b26d7c8f0cfe2206aafdc2805d11 --- /dev/null +++ b/node_modules/@mswjs/interceptors/WebSocket/package.json @@ -0,0 +1,12 @@ +{ + "main": "../lib/browser/interceptors/WebSocket/index.cjs", + "module": "../lib/browser/interceptors/WebSocket/index.mjs", + "browser": "../lib/browser/interceptors/WebSocket/index.mjs", + "exports": { + ".": { + "browser": "./../lib/browser/interceptors/WebSocket/index.mjs", + "import": "./../lib/browser/interceptors/WebSocket/index.mjs", + "default": "./../lib/browser/interceptors/WebSocket/index.cjs" + } + } +} diff --git a/node_modules/@mswjs/interceptors/XMLHttpRequest/package.json b/node_modules/@mswjs/interceptors/XMLHttpRequest/package.json new file mode 100644 index 0000000000000000000000000000000000000000..bc0cbf043f32869b0fa19c342961624b82f7200a --- /dev/null +++ b/node_modules/@mswjs/interceptors/XMLHttpRequest/package.json @@ -0,0 +1,12 @@ +{ + "main": "../lib/node/interceptors/XMLHttpRequest/index.cjs", + "module": "../lib/node/interceptors/XMLHttpRequest/index.mjs", + "browser": "../lib/browser/interceptors/XMLHttpRequest/index.mjs", + "exports": { + ".": { + "browser": "./../lib/browser/interceptors/XMLHttpRequest/index.mjs", + "import": "./../lib/node/interceptors/XMLHttpRequest/index.mjs", + "default": "./../lib/node/interceptors/XMLHttpRequest/index.cjs" + } + } +} diff --git a/node_modules/@mswjs/interceptors/fetch/package.json b/node_modules/@mswjs/interceptors/fetch/package.json new file mode 100644 index 0000000000000000000000000000000000000000..5c7a419e9c3e15f67cc6393b6f15f6932b73cbae --- /dev/null +++ b/node_modules/@mswjs/interceptors/fetch/package.json @@ -0,0 +1,12 @@ +{ + "main": "../lib/node/interceptors/fetch/index.cjs", + "module": "../lib/node/interceptors/fetch/index.mjs", + "browser": "../lib/browser/interceptors/fetch/index.mjs", + "exports": { + ".": { + "browser": "./../lib/browser/interceptors/fetch/index.mjs", + "import": "./../lib/node/interceptors/fetch/index.mjs", + "default": "./../lib/node/interceptors/fetch/index.cjs" + } + } +} diff --git a/node_modules/@mswjs/interceptors/lib/browser/Interceptor-Deczogc8.d.cts b/node_modules/@mswjs/interceptors/lib/browser/Interceptor-Deczogc8.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..330846cb69b1d455822158aaee7bd5678b727b43 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/Interceptor-Deczogc8.d.cts @@ -0,0 +1,65 @@ +import { Logger } from "@open-draft/logger"; +import { Emitter, Listener } from "strict-event-emitter"; + +//#region src/Interceptor.d.ts +type InterceptorEventMap = Record; +type InterceptorSubscription = () => void; +/** + * Request header name to detect when a single request + * is being handled by nested interceptors (XHR -> ClientRequest). + * Obscure by design to prevent collisions with user-defined headers. + * Ideally, come up with the Interceptor-level mechanism for this. + * @see https://github.com/mswjs/interceptors/issues/378 + */ +declare const INTERNAL_REQUEST_ID_HEADER_NAME = "x-interceptors-internal-request-id"; +declare function getGlobalSymbol(symbol: Symbol): V | undefined; +declare function deleteGlobalSymbol(symbol: Symbol): void; +declare enum InterceptorReadyState { + INACTIVE = "INACTIVE", + APPLYING = "APPLYING", + APPLIED = "APPLIED", + DISPOSING = "DISPOSING", + DISPOSED = "DISPOSED", +} +type ExtractEventNames> = Events extends Record ? EventName : never; +declare class Interceptor { + private readonly symbol; + protected emitter: Emitter; + protected subscriptions: Array; + protected logger: Logger; + readyState: InterceptorReadyState; + constructor(symbol: symbol); + /** + * Determine if this interceptor can be applied + * in the current environment. + */ + protected checkEnvironment(): boolean; + /** + * Apply this interceptor to the current process. + * Returns an already running interceptor instance if it's present. + */ + apply(): void; + /** + * Setup the module augments and stubs necessary for this interceptor. + * This method is not run if there's a running interceptor instance + * to prevent instantiating an interceptor multiple times. + */ + protected setup(): void; + /** + * Listen to the interceptor's public events. + */ + on>(event: EventName, listener: Listener): this; + once>(event: EventName, listener: Listener): this; + off>(event: EventName, listener: Listener): this; + removeAllListeners>(event?: EventName): this; + /** + * Disposes of any side-effects this interceptor has introduced. + */ + dispose(): void; + private getInstance; + private setInstance; + private clearInstance; +} +//#endregion +export { InterceptorReadyState as a, getGlobalSymbol as c, InterceptorEventMap as i, INTERNAL_REQUEST_ID_HEADER_NAME as n, InterceptorSubscription as o, Interceptor as r, deleteGlobalSymbol as s, ExtractEventNames as t }; +//# sourceMappingURL=Interceptor-Deczogc8.d.cts.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/Interceptor-gqKgs-aF.d.mts b/node_modules/@mswjs/interceptors/lib/browser/Interceptor-gqKgs-aF.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..84ea6c02ee9b8ad7175602f41b6295935e1c7dfa --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/Interceptor-gqKgs-aF.d.mts @@ -0,0 +1,65 @@ +import { Logger } from "@open-draft/logger"; +import { Emitter, Listener } from "strict-event-emitter"; + +//#region src/Interceptor.d.ts +type InterceptorEventMap = Record; +type InterceptorSubscription = () => void; +/** + * Request header name to detect when a single request + * is being handled by nested interceptors (XHR -> ClientRequest). + * Obscure by design to prevent collisions with user-defined headers. + * Ideally, come up with the Interceptor-level mechanism for this. + * @see https://github.com/mswjs/interceptors/issues/378 + */ +declare const INTERNAL_REQUEST_ID_HEADER_NAME = "x-interceptors-internal-request-id"; +declare function getGlobalSymbol(symbol: Symbol): V | undefined; +declare function deleteGlobalSymbol(symbol: Symbol): void; +declare enum InterceptorReadyState { + INACTIVE = "INACTIVE", + APPLYING = "APPLYING", + APPLIED = "APPLIED", + DISPOSING = "DISPOSING", + DISPOSED = "DISPOSED", +} +type ExtractEventNames> = Events extends Record ? EventName : never; +declare class Interceptor { + private readonly symbol; + protected emitter: Emitter; + protected subscriptions: Array; + protected logger: Logger; + readyState: InterceptorReadyState; + constructor(symbol: symbol); + /** + * Determine if this interceptor can be applied + * in the current environment. + */ + protected checkEnvironment(): boolean; + /** + * Apply this interceptor to the current process. + * Returns an already running interceptor instance if it's present. + */ + apply(): void; + /** + * Setup the module augments and stubs necessary for this interceptor. + * This method is not run if there's a running interceptor instance + * to prevent instantiating an interceptor multiple times. + */ + protected setup(): void; + /** + * Listen to the interceptor's public events. + */ + on>(event: EventName, listener: Listener): this; + once>(event: EventName, listener: Listener): this; + off>(event: EventName, listener: Listener): this; + removeAllListeners>(event?: EventName): this; + /** + * Disposes of any side-effects this interceptor has introduced. + */ + dispose(): void; + private getInstance; + private setInstance; + private clearInstance; +} +//#endregion +export { InterceptorReadyState as a, getGlobalSymbol as c, InterceptorEventMap as i, INTERNAL_REQUEST_ID_HEADER_NAME as n, InterceptorSubscription as o, Interceptor as r, deleteGlobalSymbol as s, ExtractEventNames as t }; +//# sourceMappingURL=Interceptor-gqKgs-aF.d.mts.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/XMLHttpRequest-DrZAf3w6.mjs b/node_modules/@mswjs/interceptors/lib/browser/XMLHttpRequest-DrZAf3w6.mjs new file mode 100644 index 0000000000000000000000000000000000000000..178d44f3bcaed51799acc90c69d64a286470c6e2 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/XMLHttpRequest-DrZAf3w6.mjs @@ -0,0 +1,746 @@ +import { n as INTERNAL_REQUEST_ID_HEADER_NAME, r as Interceptor, t as createRequestId } from "./createRequestId-DYCsFHOi.mjs"; +import { i as FetchResponse, n as setRawRequest, o as RequestController, r as FetchRequest } from "./getRawRequest-B1BqgWG6.mjs"; +import { n as encodeBuffer, r as toArrayBuffer, t as decodeBuffer } from "./bufferUtils-BiiO6HZv.mjs"; +import { n as patchesRegistry, t as hasConfigurableGlobal } from "./hasConfigurableGlobal-C8zq1MCg.mjs"; +import { n as isResponseError, t as handleRequest } from "./handleRequest-CPPgsG7s.mjs"; +import { invariant } from "outvariant"; +import { isNodeProcess } from "is-node-process"; + +//#region src/interceptors/XMLHttpRequest/utils/concatArrayBuffer.ts +/** +* Concatenate two `Uint8Array` buffers. +*/ +function concatArrayBuffer(left, right) { + const result = new Uint8Array(left.byteLength + right.byteLength); + result.set(left, 0); + result.set(right, left.byteLength); + return result; +} + +//#endregion +//#region src/interceptors/XMLHttpRequest/polyfills/EventPolyfill.ts +var EventPolyfill = class { + constructor(type, options) { + this.NONE = 0; + this.CAPTURING_PHASE = 1; + this.AT_TARGET = 2; + this.BUBBLING_PHASE = 3; + this.type = ""; + this.srcElement = null; + this.currentTarget = null; + this.eventPhase = 0; + this.isTrusted = true; + this.composed = false; + this.cancelable = true; + this.defaultPrevented = false; + this.bubbles = true; + this.lengthComputable = true; + this.loaded = 0; + this.total = 0; + this.cancelBubble = false; + this.returnValue = true; + this.type = type; + this.target = options?.target || null; + this.currentTarget = options?.currentTarget || null; + this.timeStamp = Date.now(); + } + composedPath() { + return []; + } + initEvent(type, bubbles, cancelable) { + this.type = type; + this.bubbles = !!bubbles; + this.cancelable = !!cancelable; + } + preventDefault() { + this.defaultPrevented = true; + } + stopPropagation() {} + stopImmediatePropagation() {} +}; + +//#endregion +//#region src/interceptors/XMLHttpRequest/polyfills/ProgressEventPolyfill.ts +var ProgressEventPolyfill = class extends EventPolyfill { + constructor(type, init) { + super(type); + this.lengthComputable = init?.lengthComputable || false; + this.composed = init?.composed || false; + this.loaded = init?.loaded || 0; + this.total = init?.total || 0; + } +}; + +//#endregion +//#region src/interceptors/XMLHttpRequest/utils/createEvent.ts +const SUPPORTS_PROGRESS_EVENT = typeof ProgressEvent !== "undefined"; +function createEvent(target, type, init) { + const progressEvents = [ + "error", + "progress", + "loadstart", + "loadend", + "load", + "timeout", + "abort" + ]; + /** + * `ProgressEvent` is not supported in React Native. + * @see https://github.com/mswjs/interceptors/issues/40 + */ + const ProgressEventClass = SUPPORTS_PROGRESS_EVENT ? ProgressEvent : ProgressEventPolyfill; + return progressEvents.includes(type) ? new ProgressEventClass(type, { + lengthComputable: true, + loaded: init?.loaded || 0, + total: init?.total || 0 + }) : new EventPolyfill(type, { + target, + currentTarget: target + }); +} + +//#endregion +//#region src/utils/findPropertySource.ts +/** +* Returns the source object of the given property on the target object +* (the target itself, any parent in its prototype, or null). +*/ +function findPropertySource(target, propertyName) { + if (!(propertyName in target)) return null; + if (Object.prototype.hasOwnProperty.call(target, propertyName)) return target; + const prototype = Reflect.getPrototypeOf(target); + return prototype ? findPropertySource(prototype, propertyName) : null; +} + +//#endregion +//#region src/utils/createProxy.ts +function createProxy(target, options) { + return new Proxy(target, optionsToProxyHandler(options)); +} +function optionsToProxyHandler(options) { + const { constructorCall, methodCall, getProperty, setProperty } = options; + const handler = {}; + if (typeof constructorCall !== "undefined") handler.construct = function(target, args, newTarget) { + const next = Reflect.construct.bind(null, target, args, newTarget); + return constructorCall.call(newTarget, args, next); + }; + handler.set = function(target, propertyName, nextValue) { + const next = () => { + const propertySource = findPropertySource(target, propertyName) || target; + const ownDescriptors = Reflect.getOwnPropertyDescriptor(propertySource, propertyName); + if (typeof ownDescriptors?.set !== "undefined") { + ownDescriptors.set.apply(target, [nextValue]); + return true; + } + return Reflect.defineProperty(propertySource, propertyName, { + writable: true, + enumerable: true, + configurable: true, + value: nextValue + }); + }; + if (typeof setProperty !== "undefined") return setProperty.call(target, [propertyName, nextValue], next); + return next(); + }; + handler.get = function(target, propertyName, receiver) { + /** + * @note Using `Reflect.get()` here causes "TypeError: Illegal invocation". + */ + const next = () => target[propertyName]; + const value = typeof getProperty !== "undefined" ? getProperty.call(target, [propertyName, receiver], next) : next(); + if (typeof value === "function") return (...args) => { + const next$1 = value.bind(target, ...args); + if (typeof methodCall !== "undefined") return methodCall.call(target, [propertyName, args], next$1); + return next$1(); + }; + return value; + }; + return handler; +} + +//#endregion +//#region src/interceptors/XMLHttpRequest/utils/isDomParserSupportedType.ts +function isDomParserSupportedType(type) { + return [ + "application/xhtml+xml", + "application/xml", + "image/svg+xml", + "text/html", + "text/xml" + ].some((supportedType) => { + return type.startsWith(supportedType); + }); +} + +//#endregion +//#region src/utils/parseJson.ts +/** +* Parses a given string into JSON. +* Gracefully handles invalid JSON by returning `null`. +*/ +function parseJson(data) { + try { + return JSON.parse(data); + } catch (_) { + return null; + } +} + +//#endregion +//#region src/interceptors/XMLHttpRequest/utils/createResponse.ts +/** +* Creates a Fetch API `Response` instance from the given +* `XMLHttpRequest` instance and a response body. +*/ +function createResponse(request, body) { + return new FetchResponse(FetchResponse.isResponseWithBody(request.status) ? body : null, { + url: request.responseURL, + status: request.status, + statusText: request.statusText, + headers: createHeadersFromXMLHttpRequestHeaders(request.getAllResponseHeaders()) + }); +} +function createHeadersFromXMLHttpRequestHeaders(headersString) { + const headers = new Headers(); + const lines = headersString.split(/[\r\n]+/); + for (const line of lines) { + if (line.trim() === "") continue; + const [name, ...parts] = line.split(": "); + const value = parts.join(": "); + headers.append(name, value); + } + return headers; +} + +//#endregion +//#region src/interceptors/XMLHttpRequest/utils/getBodyByteLength.ts +/** +* Return a total byte length of the given request/response body. +* If the `Content-Length` header is present, it will be used as the byte length. +*/ +async function getBodyByteLength(input) { + const explicitContentLength = input.headers.get("content-length"); + if (explicitContentLength != null && explicitContentLength !== "") return Number(explicitContentLength); + return (await input.arrayBuffer()).byteLength; +} + +//#endregion +//#region src/interceptors/XMLHttpRequest/XMLHttpRequestController.ts +const kIsRequestHandled = Symbol("kIsRequestHandled"); +const IS_NODE = isNodeProcess(); +const kFetchRequest = Symbol("kFetchRequest"); +/** +* An `XMLHttpRequest` instance controller that allows us +* to handle any given request instance (e.g. responding to it). +*/ +var XMLHttpRequestController = class { + constructor(initialRequest, logger) { + this.initialRequest = initialRequest; + this.logger = logger; + this.method = "GET"; + this.url = null; + this[kIsRequestHandled] = false; + this.events = /* @__PURE__ */ new Map(); + this.uploadEvents = /* @__PURE__ */ new Map(); + this.requestId = createRequestId(); + this.requestHeaders = new Headers(); + this.responseBuffer = new Uint8Array(); + this.request = createProxy(initialRequest, { + setProperty: ([propertyName, nextValue], invoke) => { + switch (propertyName) { + case "ontimeout": { + const eventName = propertyName.slice(2); + /** + * @note Proxy callbacks to event listeners because JSDOM has trouble + * translating these properties to callbacks. It seemed to be operating + * on events exclusively. + */ + this.request.addEventListener(eventName, nextValue); + return invoke(); + } + default: return invoke(); + } + }, + methodCall: ([methodName, args], invoke) => { + switch (methodName) { + case "open": { + const [method, url] = args; + if (typeof url === "undefined") { + this.method = "GET"; + this.url = toAbsoluteUrl(method); + } else { + this.method = method; + this.url = toAbsoluteUrl(url); + } + this.logger = this.logger.extend(`${this.method} ${this.url.href}`); + this.logger.info("open", this.method, this.url.href); + return invoke(); + } + case "addEventListener": { + const [eventName, listener] = args; + this.registerEvent(eventName, listener); + this.logger.info("addEventListener", eventName, listener); + return invoke(); + } + case "setRequestHeader": { + const [name, value] = args; + this.requestHeaders.set(name, value); + this.logger.info("setRequestHeader", name, value); + return invoke(); + } + case "send": { + const [body] = args; + this.request.addEventListener("load", () => { + if (typeof this.onResponse !== "undefined") { + const fetchResponse = createResponse( + this.request, + /** + * The `response` property is the right way to read + * the ambiguous response body, as the request's "responseType" may differ. + * @see https://xhr.spec.whatwg.org/#the-response-attribute + */ + this.request.response + ); + this.onResponse.call(this, { + response: fetchResponse, + isMockedResponse: this[kIsRequestHandled], + request: fetchRequest, + requestId: this.requestId + }); + } + }); + const requestBody = typeof body === "string" ? encodeBuffer(body) : body; + const fetchRequest = this.toFetchApiRequest(requestBody); + this[kFetchRequest] = fetchRequest.clone(); + /** + * @note Start request handling on the next tick so that the user + * could add event listeners for "loadend" before the interceptor fires it. + */ + queueMicrotask(() => { + (this.onRequest?.call(this, { + request: fetchRequest, + requestId: this.requestId + }) || Promise.resolve()).finally(() => { + if (!this[kIsRequestHandled]) { + this.logger.info("request callback settled but request has not been handled (readystate %d), performing as-is...", this.request.readyState); + /** + * @note Set the intercepted request ID on the original request in Node.js + * so that if it triggers any other interceptors, they don't attempt + * to process it once again. + * + * For instance, XMLHttpRequest is often implemented via "http.ClientRequest" + * and we don't want for both XHR and ClientRequest interceptors to + * handle the same request at the same time (e.g. emit the "response" event twice). + */ + if (IS_NODE) this.request.setRequestHeader(INTERNAL_REQUEST_ID_HEADER_NAME, this.requestId); + return invoke(); + } + }); + }); + break; + } + default: return invoke(); + } + } + }); + /** + * Proxy the `.upload` property to gather the event listeners/callbacks. + */ + define(this.request, "upload", createProxy(this.request.upload, { + setProperty: ([propertyName, nextValue], invoke) => { + switch (propertyName) { + case "onloadstart": + case "onprogress": + case "onaboart": + case "onerror": + case "onload": + case "ontimeout": + case "onloadend": { + const eventName = propertyName.slice(2); + this.registerUploadEvent(eventName, nextValue); + } + } + return invoke(); + }, + methodCall: ([methodName, args], invoke) => { + switch (methodName) { + case "addEventListener": { + const [eventName, listener] = args; + this.registerUploadEvent(eventName, listener); + this.logger.info("upload.addEventListener", eventName, listener); + return invoke(); + } + } + } + })); + } + registerEvent(eventName, listener) { + const nextEvents = (this.events.get(eventName) || []).concat(listener); + this.events.set(eventName, nextEvents); + this.logger.info("registered event \"%s\"", eventName, listener); + } + registerUploadEvent(eventName, listener) { + const nextEvents = (this.uploadEvents.get(eventName) || []).concat(listener); + this.uploadEvents.set(eventName, nextEvents); + this.logger.info("registered upload event \"%s\"", eventName, listener); + } + /** + * Responds to the current request with the given + * Fetch API `Response` instance. + */ + async respondWith(response) { + /** + * @note Since `XMLHttpRequestController` delegates the handling of the responses + * to the "load" event listener that doesn't distinguish between the mocked and original + * responses, mark the request that had a mocked response with a corresponding symbol. + * + * Mark this request as having a mocked response immediately since + * calculating request/response total body length is asynchronous. + */ + this[kIsRequestHandled] = true; + /** + * Dispatch request upload events for requests with a body. + * @see https://github.com/mswjs/interceptors/issues/573 + */ + if (this[kFetchRequest]) { + const totalRequestBodyLength = await getBodyByteLength(this[kFetchRequest]); + this.trigger("loadstart", this.request.upload, { + loaded: 0, + total: totalRequestBodyLength + }); + this.trigger("progress", this.request.upload, { + loaded: totalRequestBodyLength, + total: totalRequestBodyLength + }); + this.trigger("load", this.request.upload, { + loaded: totalRequestBodyLength, + total: totalRequestBodyLength + }); + this.trigger("loadend", this.request.upload, { + loaded: totalRequestBodyLength, + total: totalRequestBodyLength + }); + } + this.logger.info("responding with a mocked response: %d %s", response.status, response.statusText); + define(this.request, "status", response.status); + define(this.request, "statusText", response.statusText); + define(this.request, "responseURL", this.url.href); + this.request.getResponseHeader = new Proxy(this.request.getResponseHeader, { apply: (_, __, args) => { + this.logger.info("getResponseHeader", args[0]); + if (this.request.readyState < this.request.HEADERS_RECEIVED) { + this.logger.info("headers not received yet, returning null"); + return null; + } + const headerValue = response.headers.get(args[0]); + this.logger.info("resolved response header \"%s\" to", args[0], headerValue); + return headerValue; + } }); + this.request.getAllResponseHeaders = new Proxy(this.request.getAllResponseHeaders, { apply: () => { + this.logger.info("getAllResponseHeaders"); + if (this.request.readyState < this.request.HEADERS_RECEIVED) { + this.logger.info("headers not received yet, returning empty string"); + return ""; + } + const allHeaders = Array.from(response.headers.entries()).map(([headerName, headerValue]) => { + return `${headerName}: ${headerValue}`; + }).join("\r\n"); + this.logger.info("resolved all response headers to", allHeaders); + return allHeaders; + } }); + Object.defineProperties(this.request, { + response: { + enumerable: true, + configurable: false, + get: () => this.response + }, + responseText: { + enumerable: true, + configurable: false, + get: () => this.responseText + }, + responseXML: { + enumerable: true, + configurable: false, + get: () => this.responseXML + } + }); + const totalResponseBodyLength = await getBodyByteLength(response.clone()); + this.logger.info("calculated response body length", totalResponseBodyLength); + this.trigger("loadstart", this.request, { + loaded: 0, + total: totalResponseBodyLength + }); + this.setReadyState(this.request.HEADERS_RECEIVED); + this.setReadyState(this.request.LOADING); + const finalizeResponse = () => { + this.logger.info("finalizing the mocked response..."); + this.setReadyState(this.request.DONE); + this.trigger("load", this.request, { + loaded: this.responseBuffer.byteLength, + total: totalResponseBodyLength + }); + this.trigger("loadend", this.request, { + loaded: this.responseBuffer.byteLength, + total: totalResponseBodyLength + }); + }; + if (response.body) { + this.logger.info("mocked response has body, streaming..."); + const reader = response.body.getReader(); + const readNextResponseBodyChunk = async () => { + const { value, done } = await reader.read(); + if (done) { + this.logger.info("response body stream done!"); + finalizeResponse(); + return; + } + if (value) { + this.logger.info("read response body chunk:", value); + this.responseBuffer = concatArrayBuffer(this.responseBuffer, value); + this.trigger("progress", this.request, { + loaded: this.responseBuffer.byteLength, + total: totalResponseBodyLength + }); + } + readNextResponseBodyChunk(); + }; + readNextResponseBodyChunk(); + } else finalizeResponse(); + } + responseBufferToText() { + return decodeBuffer(this.responseBuffer); + } + get response() { + this.logger.info("getResponse (responseType: %s)", this.request.responseType); + if (this.request.readyState !== this.request.DONE) return null; + switch (this.request.responseType) { + case "json": { + const responseJson = parseJson(this.responseBufferToText()); + this.logger.info("resolved response JSON", responseJson); + return responseJson; + } + case "arraybuffer": { + const arrayBuffer = toArrayBuffer(this.responseBuffer); + this.logger.info("resolved response ArrayBuffer", arrayBuffer); + return arrayBuffer; + } + case "blob": { + const mimeType = this.request.getResponseHeader("Content-Type") || "text/plain"; + const responseBlob = new Blob([this.responseBufferToText()], { type: mimeType }); + this.logger.info("resolved response Blob (mime type: %s)", responseBlob, mimeType); + return responseBlob; + } + default: { + const responseText = this.responseBufferToText(); + this.logger.info("resolving \"%s\" response type as text", this.request.responseType, responseText); + return responseText; + } + } + } + get responseText() { + /** + * Throw when trying to read the response body as text when the + * "responseType" doesn't expect text. This just respects the spec better. + * @see https://xhr.spec.whatwg.org/#the-responsetext-attribute + */ + invariant(this.request.responseType === "" || this.request.responseType === "text", "InvalidStateError: The object is in invalid state."); + if (this.request.readyState !== this.request.LOADING && this.request.readyState !== this.request.DONE) return ""; + const responseText = this.responseBufferToText(); + this.logger.info("getResponseText: \"%s\"", responseText); + return responseText; + } + get responseXML() { + invariant(this.request.responseType === "" || this.request.responseType === "document", "InvalidStateError: The object is in invalid state."); + if (this.request.readyState !== this.request.DONE) return null; + const contentType = this.request.getResponseHeader("Content-Type") || ""; + if (typeof DOMParser === "undefined") { + console.warn("Cannot retrieve XMLHttpRequest response body as XML: DOMParser is not defined. You are likely using an environment that is not browser or does not polyfill browser globals correctly."); + return null; + } + if (isDomParserSupportedType(contentType)) return new DOMParser().parseFromString(this.responseBufferToText(), contentType); + return null; + } + errorWith(error) { + /** + * @note Mark this request as handled even if it received a mock error. + * This prevents the controller from trying to perform this request as-is. + */ + this[kIsRequestHandled] = true; + this.logger.info("responding with an error"); + this.setReadyState(this.request.DONE); + this.trigger("error", this.request); + this.trigger("loadend", this.request); + } + /** + * Transitions this request's `readyState` to the given one. + */ + setReadyState(nextReadyState) { + this.logger.info("setReadyState: %d -> %d", this.request.readyState, nextReadyState); + if (this.request.readyState === nextReadyState) { + this.logger.info("ready state identical, skipping transition..."); + return; + } + define(this.request, "readyState", nextReadyState); + this.logger.info("set readyState to: %d", nextReadyState); + if (nextReadyState !== this.request.UNSENT) { + this.logger.info("triggering \"readystatechange\" event..."); + this.trigger("readystatechange", this.request); + } + } + /** + * Triggers given event on the `XMLHttpRequest` instance. + */ + trigger(eventName, target, options) { + const callback = target[`on${eventName}`]; + const event = createEvent(target, eventName, options); + this.logger.info("trigger \"%s\"", eventName, options || ""); + if (typeof callback === "function") { + this.logger.info("found a direct \"%s\" callback, calling...", eventName); + callback.call(target, event); + } + const events = target instanceof XMLHttpRequestUpload ? this.uploadEvents : this.events; + for (const [registeredEventName, listeners] of events) if (registeredEventName === eventName) { + this.logger.info("found %d listener(s) for \"%s\" event, calling...", listeners.length, eventName); + listeners.forEach((listener) => listener.call(target, event)); + } + } + /** + * Converts this `XMLHttpRequest` instance into a Fetch API `Request` instance. + */ + toFetchApiRequest(body) { + this.logger.info("converting request to a Fetch API Request..."); + const resolvedBody = body instanceof Document ? body.documentElement.innerText : body; + const fetchRequest = new FetchRequest(this.url.href, { + method: this.method, + headers: this.requestHeaders, + credentials: this.request.withCredentials ? "include" : "same-origin", + body: ["GET", "HEAD"].includes(this.method.toUpperCase()) ? null : resolvedBody + }); + define(fetchRequest, "headers", createProxy(fetchRequest.headers, { methodCall: ([methodName, args], invoke) => { + switch (methodName) { + case "append": + case "set": { + const [headerName, headerValue] = args; + this.request.setRequestHeader(headerName, headerValue); + break; + } + case "delete": { + const [headerName] = args; + console.warn(`XMLHttpRequest: Cannot remove a "${headerName}" header from the Fetch API representation of the "${fetchRequest.method} ${fetchRequest.url}" request. XMLHttpRequest headers cannot be removed.`); + break; + } + } + return invoke(); + } })); + setRawRequest(fetchRequest, this.request); + this.logger.info("converted request to a Fetch API Request!", fetchRequest); + return fetchRequest; + } +}; +function toAbsoluteUrl(url) { + /** + * @note XMLHttpRequest interceptor may run in environments + * that implement XMLHttpRequest but don't implement "location" + * (for example, React Native). If that's the case, return the + * input URL as-is (nothing to be relative to). + * @see https://github.com/mswjs/msw/issues/1777 + */ + if (typeof location === "undefined") return new URL(url); + return new URL(url.toString(), location.href); +} +function define(target, property, value) { + Reflect.defineProperty(target, property, { + writable: true, + enumerable: true, + value + }); +} + +//#endregion +//#region src/interceptors/XMLHttpRequest/XMLHttpRequestProxy.ts +/** +* Create a proxied `XMLHttpRequest` class. +* The proxied class establishes spies on certain methods, +* allowing us to intercept requests and respond to them. +*/ +function createXMLHttpRequestProxy({ emitter, logger }) { + return new Proxy(globalThis.XMLHttpRequest, { construct(target, args, newTarget) { + logger.info("constructed new XMLHttpRequest"); + const originalRequest = Reflect.construct(target, args, newTarget); + /** + * @note Forward prototype descriptors onto the proxied object. + * XMLHttpRequest is implemented in JSDOM in a way that assigns + * a bunch of descriptors, like "set responseType()" on the prototype. + * With this propagation, we make sure that those descriptors trigger + * when the user operates with the proxied request instance. + */ + const prototypeDescriptors = Object.getOwnPropertyDescriptors(target.prototype); + for (const propertyName in prototypeDescriptors) Reflect.defineProperty(originalRequest, propertyName, prototypeDescriptors[propertyName]); + const xhrRequestController = new XMLHttpRequestController(originalRequest, logger); + xhrRequestController.onRequest = async function({ request, requestId }) { + const controller = new RequestController(request, { + passthrough: () => { + this.logger.info("no mocked response received, performing request as-is..."); + }, + respondWith: async (response) => { + if (isResponseError(response)) { + this.errorWith(/* @__PURE__ */ new TypeError("Network error")); + return; + } + await this.respondWith(response); + }, + errorWith: (reason) => { + this.logger.info("request errored!", { error: reason }); + if (reason instanceof Error) this.errorWith(reason); + } + }); + this.logger.info("awaiting mocked response..."); + this.logger.info("emitting the \"request\" event for %s listener(s)...", emitter.listenerCount("request")); + await handleRequest({ + request, + requestId, + controller, + emitter + }); + }; + xhrRequestController.onResponse = async function({ response, isMockedResponse, request, requestId }) { + this.logger.info("emitting the \"response\" event for %s listener(s)...", emitter.listenerCount("response")); + emitter.emit("response", { + response, + isMockedResponse, + request, + requestId + }); + }; + return xhrRequestController.request; + } }); +} + +//#endregion +//#region src/interceptors/XMLHttpRequest/index.ts +var XMLHttpRequestInterceptor = class XMLHttpRequestInterceptor extends Interceptor { + static { + this.symbol = Symbol.for("xhr-interceptor"); + } + constructor() { + super(XMLHttpRequestInterceptor.symbol); + } + checkEnvironment() { + return hasConfigurableGlobal("XMLHttpRequest"); + } + setup() { + const logger = this.logger.extend("setup"); + logger.info("patching global XMLHttpRequest..."); + this.subscriptions.push(patchesRegistry.applyPatch(globalThis, "XMLHttpRequest", () => { + return createXMLHttpRequestProxy({ + emitter: this.emitter, + logger: this.logger + }); + })); + logger.info("global XMLHttpRequest patched!", globalThis.XMLHttpRequest.name); + } +}; + +//#endregion +export { XMLHttpRequestInterceptor as t }; +//# sourceMappingURL=XMLHttpRequest-DrZAf3w6.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/XMLHttpRequest-DrZAf3w6.mjs.map b/node_modules/@mswjs/interceptors/lib/browser/XMLHttpRequest-DrZAf3w6.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..a701c5b757174649eb6e6c872ba5bfa639046078 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/XMLHttpRequest-DrZAf3w6.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"XMLHttpRequest-DrZAf3w6.mjs","names":["handler: ProxyHandler","next","initialRequest: XMLHttpRequest","logger: Logger"],"sources":["../../src/interceptors/XMLHttpRequest/utils/concatArrayBuffer.ts","../../src/interceptors/XMLHttpRequest/polyfills/EventPolyfill.ts","../../src/interceptors/XMLHttpRequest/polyfills/ProgressEventPolyfill.ts","../../src/interceptors/XMLHttpRequest/utils/createEvent.ts","../../src/utils/findPropertySource.ts","../../src/utils/createProxy.ts","../../src/interceptors/XMLHttpRequest/utils/isDomParserSupportedType.ts","../../src/utils/parseJson.ts","../../src/interceptors/XMLHttpRequest/utils/createResponse.ts","../../src/interceptors/XMLHttpRequest/utils/getBodyByteLength.ts","../../src/interceptors/XMLHttpRequest/XMLHttpRequestController.ts","../../src/interceptors/XMLHttpRequest/XMLHttpRequestProxy.ts","../../src/interceptors/XMLHttpRequest/index.ts"],"sourcesContent":["/**\n * Concatenate two `Uint8Array` buffers.\n */\nexport function concatArrayBuffer(\n left: Uint8Array,\n right: Uint8Array\n): Uint8Array {\n const result = new Uint8Array(left.byteLength + right.byteLength)\n result.set(left, 0)\n result.set(right, left.byteLength)\n return result\n}\n","export class EventPolyfill implements Event {\n readonly NONE = 0\n readonly CAPTURING_PHASE = 1\n readonly AT_TARGET = 2\n readonly BUBBLING_PHASE = 3\n\n public type: string = ''\n public srcElement: EventTarget | null = null\n public target: EventTarget | null\n public currentTarget: EventTarget | null = null\n public eventPhase: number = 0\n public timeStamp: number\n public isTrusted: boolean = true\n public composed: boolean = false\n public cancelable: boolean = true\n public defaultPrevented: boolean = false\n public bubbles: boolean = true\n public lengthComputable: boolean = true\n public loaded: number = 0\n public total: number = 0\n\n cancelBubble: boolean = false\n returnValue: boolean = true\n\n constructor(\n type: string,\n options?: { target: EventTarget; currentTarget: EventTarget }\n ) {\n this.type = type\n this.target = options?.target || null\n this.currentTarget = options?.currentTarget || null\n this.timeStamp = Date.now()\n }\n\n public composedPath(): EventTarget[] {\n return []\n }\n\n public initEvent(type: string, bubbles?: boolean, cancelable?: boolean) {\n this.type = type\n this.bubbles = !!bubbles\n this.cancelable = !!cancelable\n }\n\n public preventDefault() {\n this.defaultPrevented = true\n }\n\n public stopPropagation() {}\n public stopImmediatePropagation() {}\n}\n","import { EventPolyfill } from './EventPolyfill'\n\nexport class ProgressEventPolyfill extends EventPolyfill {\n readonly lengthComputable: boolean\n readonly composed: boolean\n readonly loaded: number\n readonly total: number\n\n constructor(type: string, init?: ProgressEventInit) {\n super(type)\n\n this.lengthComputable = init?.lengthComputable || false\n this.composed = init?.composed || false\n this.loaded = init?.loaded || 0\n this.total = init?.total || 0\n }\n}\n","import { EventPolyfill } from '../polyfills/EventPolyfill'\nimport { ProgressEventPolyfill } from '../polyfills/ProgressEventPolyfill'\n\nconst SUPPORTS_PROGRESS_EVENT = typeof ProgressEvent !== 'undefined'\n\nexport function createEvent(\n target: XMLHttpRequest | XMLHttpRequestUpload,\n type: string,\n init?: ProgressEventInit\n): EventPolyfill | ProgressEvent {\n const progressEvents = [\n 'error',\n 'progress',\n 'loadstart',\n 'loadend',\n 'load',\n 'timeout',\n 'abort',\n ]\n\n /**\n * `ProgressEvent` is not supported in React Native.\n * @see https://github.com/mswjs/interceptors/issues/40\n */\n const ProgressEventClass = SUPPORTS_PROGRESS_EVENT\n ? ProgressEvent\n : ProgressEventPolyfill\n\n const event = progressEvents.includes(type)\n ? new ProgressEventClass(type, {\n lengthComputable: true,\n loaded: init?.loaded || 0,\n total: init?.total || 0,\n })\n : new EventPolyfill(type, {\n target,\n currentTarget: target,\n })\n\n return event\n}\n","/**\n * Returns the source object of the given property on the target object\n * (the target itself, any parent in its prototype, or null).\n */\nexport function findPropertySource(\n target: object,\n propertyName: string | symbol\n): object | null {\n if (!(propertyName in target)) {\n return null\n }\n\n const hasProperty = Object.prototype.hasOwnProperty.call(target, propertyName)\n if (hasProperty) {\n return target\n }\n\n const prototype = Reflect.getPrototypeOf(target)\n return prototype ? findPropertySource(prototype, propertyName) : null\n}\n","import { findPropertySource } from './findPropertySource'\n\nexport interface ProxyOptions> {\n constructorCall?(args: Array, next: NextFunction): Target\n\n methodCall?(\n this: Target,\n data: [methodName: F, args: Array],\n next: NextFunction\n ): void\n\n setProperty?(\n data: [propertyName: string | symbol, nextValue: unknown],\n next: NextFunction\n ): boolean\n\n getProperty?(\n data: [propertyName: string | symbol, receiver: Target],\n next: NextFunction\n ): void\n}\n\nexport type NextFunction = () => ReturnType\n\nexport function createProxy(\n target: Target,\n options: ProxyOptions\n): Target {\n const proxy = new Proxy(target, optionsToProxyHandler(options))\n\n return proxy\n}\n\nfunction optionsToProxyHandler>(\n options: ProxyOptions\n): ProxyHandler {\n const { constructorCall, methodCall, getProperty, setProperty } = options\n const handler: ProxyHandler = {}\n\n if (typeof constructorCall !== 'undefined') {\n handler.construct = function (target, args, newTarget) {\n const next = Reflect.construct.bind(null, target as any, args, newTarget)\n return constructorCall.call(newTarget, args, next)\n }\n }\n\n handler.set = function (target, propertyName, nextValue) {\n const next = () => {\n const propertySource = findPropertySource(target, propertyName) || target\n const ownDescriptors = Reflect.getOwnPropertyDescriptor(\n propertySource,\n propertyName\n )\n\n // Respect any custom setters present for this property.\n if (typeof ownDescriptors?.set !== 'undefined') {\n ownDescriptors.set.apply(target, [nextValue])\n return true\n }\n\n // Otherwise, set the property on the source.\n return Reflect.defineProperty(propertySource, propertyName, {\n writable: true,\n enumerable: true,\n configurable: true,\n value: nextValue,\n })\n }\n\n if (typeof setProperty !== 'undefined') {\n return setProperty.call(target, [propertyName, nextValue], next)\n }\n\n return next()\n }\n\n handler.get = function (target, propertyName, receiver) {\n /**\n * @note Using `Reflect.get()` here causes \"TypeError: Illegal invocation\".\n */\n const next = () => target[propertyName as any]\n\n const value =\n typeof getProperty !== 'undefined'\n ? getProperty.call(target, [propertyName, receiver], next)\n : next()\n\n if (typeof value === 'function') {\n return (...args: Array) => {\n const next = value.bind(target, ...args)\n\n if (typeof methodCall !== 'undefined') {\n return methodCall.call(target, [propertyName as any, args], next)\n }\n\n return next()\n }\n }\n\n return value\n }\n\n return handler\n}\n","export function isDomParserSupportedType(\n type: string\n): type is DOMParserSupportedType {\n const supportedTypes: Array = [\n 'application/xhtml+xml',\n 'application/xml',\n 'image/svg+xml',\n 'text/html',\n 'text/xml',\n ]\n return supportedTypes.some((supportedType) => {\n return type.startsWith(supportedType)\n })\n}\n","/**\n * Parses a given string into JSON.\n * Gracefully handles invalid JSON by returning `null`.\n */\nexport function parseJson(data: string): Record | null {\n try {\n const json = JSON.parse(data)\n return json\n } catch (_) {\n return null\n }\n}\n","import { FetchResponse } from '../../../utils/fetchUtils'\n\n/**\n * Creates a Fetch API `Response` instance from the given\n * `XMLHttpRequest` instance and a response body.\n */\nexport function createResponse(\n request: XMLHttpRequest,\n body: BodyInit | null\n): Response {\n /**\n * Handle XMLHttpRequest responses that must have null as the\n * response body when represented using Fetch API Response.\n * XMLHttpRequest response will always have an empty string\n * as the \"request.response\" in those cases, resulting in an error\n * when constructing a Response instance.\n * @see https://github.com/mswjs/interceptors/issues/379\n */\n const responseBodyOrNull = FetchResponse.isResponseWithBody(request.status)\n ? body\n : null\n\n return new FetchResponse(responseBodyOrNull, {\n url: request.responseURL,\n status: request.status,\n statusText: request.statusText,\n headers: createHeadersFromXMLHttpRequestHeaders(\n request.getAllResponseHeaders()\n ),\n })\n}\n\nfunction createHeadersFromXMLHttpRequestHeaders(headersString: string): Headers {\n const headers = new Headers()\n\n const lines = headersString.split(/[\\r\\n]+/)\n for (const line of lines) {\n if (line.trim() === '') {\n continue\n }\n\n const [name, ...parts] = line.split(': ')\n const value = parts.join(': ')\n\n headers.append(name, value)\n }\n\n return headers\n}\n","/**\n * Return a total byte length of the given request/response body.\n * If the `Content-Length` header is present, it will be used as the byte length.\n */\nexport async function getBodyByteLength(\n input: Request | Response\n): Promise {\n const explicitContentLength = input.headers.get('content-length')\n\n if (explicitContentLength != null && explicitContentLength !== '') {\n return Number(explicitContentLength)\n }\n\n const buffer = await input.arrayBuffer()\n return buffer.byteLength\n}\n","import { invariant } from 'outvariant'\nimport { isNodeProcess } from 'is-node-process'\nimport type { Logger } from '@open-draft/logger'\nimport { concatArrayBuffer } from './utils/concatArrayBuffer'\nimport { createEvent } from './utils/createEvent'\nimport {\n decodeBuffer,\n encodeBuffer,\n toArrayBuffer,\n} from '../../utils/bufferUtils'\nimport { createProxy } from '../../utils/createProxy'\nimport { isDomParserSupportedType } from './utils/isDomParserSupportedType'\nimport { parseJson } from '../../utils/parseJson'\nimport { createResponse } from './utils/createResponse'\nimport { INTERNAL_REQUEST_ID_HEADER_NAME } from '../../Interceptor'\nimport { createRequestId } from '../../createRequestId'\nimport { getBodyByteLength } from './utils/getBodyByteLength'\nimport { setRawRequest } from '../../getRawRequest'\nimport { FetchRequest } from '../../utils/fetchUtils'\n\nconst kIsRequestHandled = Symbol('kIsRequestHandled')\nconst IS_NODE = isNodeProcess()\nconst kFetchRequest = Symbol('kFetchRequest')\n\n/**\n * An `XMLHttpRequest` instance controller that allows us\n * to handle any given request instance (e.g. responding to it).\n */\nexport class XMLHttpRequestController {\n public request: XMLHttpRequest\n public requestId: string\n public onRequest?: (\n this: XMLHttpRequestController,\n args: {\n request: Request\n requestId: string\n }\n ) => Promise\n public onResponse?: (\n this: XMLHttpRequestController,\n args: {\n response: Response\n isMockedResponse: boolean\n request: Request\n requestId: string\n }\n ) => void;\n\n [kIsRequestHandled]: boolean;\n [kFetchRequest]?: Request\n private method: string = 'GET'\n private url: URL = null as any\n private requestHeaders: Headers\n private responseBuffer: Uint8Array\n private events: Map>\n private uploadEvents: Map<\n keyof XMLHttpRequestEventTargetEventMap,\n Array\n >\n\n constructor(\n readonly initialRequest: XMLHttpRequest,\n public logger: Logger\n ) {\n this[kIsRequestHandled] = false\n\n this.events = new Map()\n this.uploadEvents = new Map()\n this.requestId = createRequestId()\n this.requestHeaders = new Headers()\n this.responseBuffer = new Uint8Array()\n\n this.request = createProxy(initialRequest, {\n setProperty: ([propertyName, nextValue], invoke) => {\n switch (propertyName) {\n case 'ontimeout': {\n const eventName = propertyName.slice(\n 2\n ) as keyof XMLHttpRequestEventTargetEventMap\n\n /**\n * @note Proxy callbacks to event listeners because JSDOM has trouble\n * translating these properties to callbacks. It seemed to be operating\n * on events exclusively.\n */\n this.request.addEventListener(eventName, nextValue as any)\n\n return invoke()\n }\n\n default: {\n return invoke()\n }\n }\n },\n methodCall: ([methodName, args], invoke) => {\n switch (methodName) {\n case 'open': {\n const [method, url] = args as [string, string | undefined]\n\n if (typeof url === 'undefined') {\n this.method = 'GET'\n this.url = toAbsoluteUrl(method)\n } else {\n this.method = method\n this.url = toAbsoluteUrl(url)\n }\n\n this.logger = this.logger.extend(`${this.method} ${this.url.href}`)\n this.logger.info('open', this.method, this.url.href)\n\n return invoke()\n }\n\n case 'addEventListener': {\n const [eventName, listener] = args as [\n keyof XMLHttpRequestEventTargetEventMap,\n Function,\n ]\n\n this.registerEvent(eventName, listener)\n this.logger.info('addEventListener', eventName, listener)\n\n return invoke()\n }\n\n case 'setRequestHeader': {\n const [name, value] = args as [string, string]\n this.requestHeaders.set(name, value)\n\n this.logger.info('setRequestHeader', name, value)\n\n return invoke()\n }\n\n case 'send': {\n const [body] = args as [\n body?: XMLHttpRequestBodyInit | Document | null,\n ]\n\n this.request.addEventListener('load', () => {\n if (typeof this.onResponse !== 'undefined') {\n // Create a Fetch API Response representation of whichever\n // response this XMLHttpRequest received. Note those may\n // be either a mocked and the original response.\n const fetchResponse = createResponse(\n this.request,\n /**\n * The `response` property is the right way to read\n * the ambiguous response body, as the request's \"responseType\" may differ.\n * @see https://xhr.spec.whatwg.org/#the-response-attribute\n */\n this.request.response\n )\n\n // Notify the consumer about the response.\n this.onResponse.call(this, {\n response: fetchResponse,\n isMockedResponse: this[kIsRequestHandled],\n request: fetchRequest,\n requestId: this.requestId!,\n })\n }\n })\n\n const requestBody =\n typeof body === 'string' ? encodeBuffer(body) : body\n\n // Delegate request handling to the consumer.\n const fetchRequest = this.toFetchApiRequest(requestBody)\n this[kFetchRequest] = fetchRequest.clone()\n\n /**\n * @note Start request handling on the next tick so that the user\n * could add event listeners for \"loadend\" before the interceptor fires it.\n */\n queueMicrotask(() => {\n const onceRequestSettled =\n this.onRequest?.call(this, {\n request: fetchRequest,\n requestId: this.requestId!,\n }) || Promise.resolve()\n\n onceRequestSettled.finally(() => {\n // If the consumer didn't handle the request (called `.respondWith()`) perform it as-is.\n if (!this[kIsRequestHandled]) {\n this.logger.info(\n 'request callback settled but request has not been handled (readystate %d), performing as-is...',\n this.request.readyState\n )\n\n /**\n * @note Set the intercepted request ID on the original request in Node.js\n * so that if it triggers any other interceptors, they don't attempt\n * to process it once again.\n *\n * For instance, XMLHttpRequest is often implemented via \"http.ClientRequest\"\n * and we don't want for both XHR and ClientRequest interceptors to\n * handle the same request at the same time (e.g. emit the \"response\" event twice).\n */\n if (IS_NODE) {\n this.request.setRequestHeader(\n INTERNAL_REQUEST_ID_HEADER_NAME,\n this.requestId!\n )\n }\n\n return invoke()\n }\n })\n })\n\n break\n }\n\n default: {\n return invoke()\n }\n }\n },\n })\n\n /**\n * Proxy the `.upload` property to gather the event listeners/callbacks.\n */\n define(\n this.request,\n 'upload',\n createProxy(this.request.upload, {\n setProperty: ([propertyName, nextValue], invoke) => {\n switch (propertyName) {\n case 'onloadstart':\n case 'onprogress':\n case 'onaboart':\n case 'onerror':\n case 'onload':\n case 'ontimeout':\n case 'onloadend': {\n const eventName = propertyName.slice(\n 2\n ) as keyof XMLHttpRequestEventTargetEventMap\n\n this.registerUploadEvent(eventName, nextValue as Function)\n }\n }\n\n return invoke()\n },\n methodCall: ([methodName, args], invoke) => {\n switch (methodName) {\n case 'addEventListener': {\n const [eventName, listener] = args as [\n keyof XMLHttpRequestEventTargetEventMap,\n Function,\n ]\n this.registerUploadEvent(eventName, listener)\n this.logger.info('upload.addEventListener', eventName, listener)\n\n return invoke()\n }\n }\n },\n })\n )\n }\n\n private registerEvent(\n eventName: keyof XMLHttpRequestEventTargetEventMap,\n listener: Function\n ): void {\n const prevEvents = this.events.get(eventName) || []\n const nextEvents = prevEvents.concat(listener)\n this.events.set(eventName, nextEvents)\n\n this.logger.info('registered event \"%s\"', eventName, listener)\n }\n\n private registerUploadEvent(\n eventName: keyof XMLHttpRequestEventTargetEventMap,\n listener: Function\n ): void {\n const prevEvents = this.uploadEvents.get(eventName) || []\n const nextEvents = prevEvents.concat(listener)\n this.uploadEvents.set(eventName, nextEvents)\n\n this.logger.info('registered upload event \"%s\"', eventName, listener)\n }\n\n /**\n * Responds to the current request with the given\n * Fetch API `Response` instance.\n */\n public async respondWith(response: Response): Promise {\n /**\n * @note Since `XMLHttpRequestController` delegates the handling of the responses\n * to the \"load\" event listener that doesn't distinguish between the mocked and original\n * responses, mark the request that had a mocked response with a corresponding symbol.\n *\n * Mark this request as having a mocked response immediately since\n * calculating request/response total body length is asynchronous.\n */\n this[kIsRequestHandled] = true\n\n /**\n * Dispatch request upload events for requests with a body.\n * @see https://github.com/mswjs/interceptors/issues/573\n */\n if (this[kFetchRequest]) {\n const totalRequestBodyLength = await getBodyByteLength(\n this[kFetchRequest]\n )\n\n this.trigger('loadstart', this.request.upload, {\n loaded: 0,\n total: totalRequestBodyLength,\n })\n this.trigger('progress', this.request.upload, {\n loaded: totalRequestBodyLength,\n total: totalRequestBodyLength,\n })\n this.trigger('load', this.request.upload, {\n loaded: totalRequestBodyLength,\n total: totalRequestBodyLength,\n })\n\n this.trigger('loadend', this.request.upload, {\n loaded: totalRequestBodyLength,\n total: totalRequestBodyLength,\n })\n }\n\n this.logger.info(\n 'responding with a mocked response: %d %s',\n response.status,\n response.statusText\n )\n\n define(this.request, 'status', response.status)\n define(this.request, 'statusText', response.statusText)\n define(this.request, 'responseURL', this.url.href)\n\n this.request.getResponseHeader = new Proxy(this.request.getResponseHeader, {\n apply: (_, __, args: [name: string]) => {\n this.logger.info('getResponseHeader', args[0])\n\n if (this.request.readyState < this.request.HEADERS_RECEIVED) {\n this.logger.info('headers not received yet, returning null')\n\n // Headers not received yet, nothing to return.\n return null\n }\n\n const headerValue = response.headers.get(args[0])\n this.logger.info(\n 'resolved response header \"%s\" to',\n args[0],\n headerValue\n )\n\n return headerValue\n },\n })\n\n this.request.getAllResponseHeaders = new Proxy(\n this.request.getAllResponseHeaders,\n {\n apply: () => {\n this.logger.info('getAllResponseHeaders')\n\n if (this.request.readyState < this.request.HEADERS_RECEIVED) {\n this.logger.info('headers not received yet, returning empty string')\n\n // Headers not received yet, nothing to return.\n return ''\n }\n\n const headersList = Array.from(response.headers.entries())\n const allHeaders = headersList\n .map(([headerName, headerValue]) => {\n return `${headerName}: ${headerValue}`\n })\n .join('\\r\\n')\n\n this.logger.info('resolved all response headers to', allHeaders)\n\n return allHeaders\n },\n }\n )\n\n // Update the response getters to resolve against the mocked response.\n Object.defineProperties(this.request, {\n response: {\n enumerable: true,\n configurable: false,\n get: () => this.response,\n },\n responseText: {\n enumerable: true,\n configurable: false,\n get: () => this.responseText,\n },\n responseXML: {\n enumerable: true,\n configurable: false,\n get: () => this.responseXML,\n },\n })\n\n const totalResponseBodyLength = await getBodyByteLength(response.clone())\n\n this.logger.info('calculated response body length', totalResponseBodyLength)\n\n this.trigger('loadstart', this.request, {\n loaded: 0,\n total: totalResponseBodyLength,\n })\n\n this.setReadyState(this.request.HEADERS_RECEIVED)\n this.setReadyState(this.request.LOADING)\n\n const finalizeResponse = () => {\n this.logger.info('finalizing the mocked response...')\n\n this.setReadyState(this.request.DONE)\n\n this.trigger('load', this.request, {\n loaded: this.responseBuffer.byteLength,\n total: totalResponseBodyLength,\n })\n\n this.trigger('loadend', this.request, {\n loaded: this.responseBuffer.byteLength,\n total: totalResponseBodyLength,\n })\n }\n\n if (response.body) {\n this.logger.info('mocked response has body, streaming...')\n\n const reader = response.body.getReader()\n\n const readNextResponseBodyChunk = async () => {\n const { value, done } = await reader.read()\n\n if (done) {\n this.logger.info('response body stream done!')\n finalizeResponse()\n return\n }\n\n if (value) {\n this.logger.info('read response body chunk:', value)\n this.responseBuffer = concatArrayBuffer(this.responseBuffer, value)\n\n this.trigger('progress', this.request, {\n loaded: this.responseBuffer.byteLength,\n total: totalResponseBodyLength,\n })\n }\n\n readNextResponseBodyChunk()\n }\n\n readNextResponseBodyChunk()\n } else {\n finalizeResponse()\n }\n }\n\n private responseBufferToText(): string {\n return decodeBuffer(this.responseBuffer)\n }\n\n get response(): unknown {\n this.logger.info(\n 'getResponse (responseType: %s)',\n this.request.responseType\n )\n\n if (this.request.readyState !== this.request.DONE) {\n return null\n }\n\n switch (this.request.responseType) {\n case 'json': {\n const responseJson = parseJson(this.responseBufferToText())\n this.logger.info('resolved response JSON', responseJson)\n\n return responseJson\n }\n\n case 'arraybuffer': {\n const arrayBuffer = toArrayBuffer(this.responseBuffer)\n this.logger.info('resolved response ArrayBuffer', arrayBuffer)\n\n return arrayBuffer\n }\n\n case 'blob': {\n const mimeType =\n this.request.getResponseHeader('Content-Type') || 'text/plain'\n const responseBlob = new Blob([this.responseBufferToText()], {\n type: mimeType,\n })\n\n this.logger.info(\n 'resolved response Blob (mime type: %s)',\n responseBlob,\n mimeType\n )\n\n return responseBlob\n }\n\n default: {\n const responseText = this.responseBufferToText()\n this.logger.info(\n 'resolving \"%s\" response type as text',\n this.request.responseType,\n responseText\n )\n\n return responseText\n }\n }\n }\n\n get responseText(): string {\n /**\n * Throw when trying to read the response body as text when the\n * \"responseType\" doesn't expect text. This just respects the spec better.\n * @see https://xhr.spec.whatwg.org/#the-responsetext-attribute\n */\n invariant(\n this.request.responseType === '' || this.request.responseType === 'text',\n 'InvalidStateError: The object is in invalid state.'\n )\n\n if (\n this.request.readyState !== this.request.LOADING &&\n this.request.readyState !== this.request.DONE\n ) {\n return ''\n }\n\n const responseText = this.responseBufferToText()\n this.logger.info('getResponseText: \"%s\"', responseText)\n\n return responseText\n }\n\n get responseXML(): Document | null {\n invariant(\n this.request.responseType === '' ||\n this.request.responseType === 'document',\n 'InvalidStateError: The object is in invalid state.'\n )\n\n if (this.request.readyState !== this.request.DONE) {\n return null\n }\n\n const contentType = this.request.getResponseHeader('Content-Type') || ''\n\n if (typeof DOMParser === 'undefined') {\n console.warn(\n 'Cannot retrieve XMLHttpRequest response body as XML: DOMParser is not defined. You are likely using an environment that is not browser or does not polyfill browser globals correctly.'\n )\n return null\n }\n\n if (isDomParserSupportedType(contentType)) {\n return new DOMParser().parseFromString(\n this.responseBufferToText(),\n contentType\n )\n }\n\n return null\n }\n\n public errorWith(error?: Error): void {\n /**\n * @note Mark this request as handled even if it received a mock error.\n * This prevents the controller from trying to perform this request as-is.\n */\n this[kIsRequestHandled] = true\n this.logger.info('responding with an error')\n\n this.setReadyState(this.request.DONE)\n this.trigger('error', this.request)\n this.trigger('loadend', this.request)\n }\n\n /**\n * Transitions this request's `readyState` to the given one.\n */\n private setReadyState(nextReadyState: number): void {\n this.logger.info(\n 'setReadyState: %d -> %d',\n this.request.readyState,\n nextReadyState\n )\n\n if (this.request.readyState === nextReadyState) {\n this.logger.info('ready state identical, skipping transition...')\n return\n }\n\n define(this.request, 'readyState', nextReadyState)\n\n this.logger.info('set readyState to: %d', nextReadyState)\n\n if (nextReadyState !== this.request.UNSENT) {\n this.logger.info('triggering \"readystatechange\" event...')\n\n this.trigger('readystatechange', this.request)\n }\n }\n\n /**\n * Triggers given event on the `XMLHttpRequest` instance.\n */\n private trigger<\n EventName extends keyof (XMLHttpRequestEventTargetEventMap & {\n readystatechange: ProgressEvent\n }),\n >(\n eventName: EventName,\n target: XMLHttpRequest | XMLHttpRequestUpload,\n options?: ProgressEventInit\n ): void {\n const callback = (target as XMLHttpRequest)[`on${eventName}`]\n const event = createEvent(target, eventName, options)\n\n this.logger.info('trigger \"%s\"', eventName, options || '')\n\n // Invoke direct callbacks.\n if (typeof callback === 'function') {\n this.logger.info('found a direct \"%s\" callback, calling...', eventName)\n callback.call(target as XMLHttpRequest, event)\n }\n\n // Invoke event listeners.\n const events =\n target instanceof XMLHttpRequestUpload ? this.uploadEvents : this.events\n\n for (const [registeredEventName, listeners] of events) {\n if (registeredEventName === eventName) {\n this.logger.info(\n 'found %d listener(s) for \"%s\" event, calling...',\n listeners.length,\n eventName\n )\n\n listeners.forEach((listener) => listener.call(target, event))\n }\n }\n }\n\n /**\n * Converts this `XMLHttpRequest` instance into a Fetch API `Request` instance.\n */\n private toFetchApiRequest(\n body: XMLHttpRequestBodyInit | Document | null | undefined\n ): Request {\n this.logger.info('converting request to a Fetch API Request...')\n\n // If the `Document` is used as the body of this XMLHttpRequest,\n // set its inner text as the Fetch API Request body.\n const resolvedBody =\n body instanceof Document ? body.documentElement.innerText : body\n\n const fetchRequest = new FetchRequest(this.url.href, {\n method: this.method,\n headers: this.requestHeaders,\n /**\n * @see https://xhr.spec.whatwg.org/#cross-origin-credentials\n */\n credentials: this.request.withCredentials ? 'include' : 'same-origin',\n body: ['GET', 'HEAD'].includes(this.method.toUpperCase())\n ? null\n : resolvedBody,\n })\n\n const proxyHeaders = createProxy(fetchRequest.headers, {\n methodCall: ([methodName, args], invoke) => {\n // Forward the latest state of the internal request headers\n // because the interceptor might have modified them\n // without responding to the request.\n switch (methodName) {\n case 'append':\n case 'set': {\n const [headerName, headerValue] = args as [string, string]\n this.request.setRequestHeader(headerName, headerValue)\n break\n }\n\n case 'delete': {\n const [headerName] = args as [string]\n console.warn(\n `XMLHttpRequest: Cannot remove a \"${headerName}\" header from the Fetch API representation of the \"${fetchRequest.method} ${fetchRequest.url}\" request. XMLHttpRequest headers cannot be removed.`\n )\n break\n }\n }\n\n return invoke()\n },\n })\n define(fetchRequest, 'headers', proxyHeaders)\n setRawRequest(fetchRequest, this.request)\n\n this.logger.info('converted request to a Fetch API Request!', fetchRequest)\n\n return fetchRequest\n }\n}\n\nfunction toAbsoluteUrl(url: string | URL): URL {\n /**\n * @note XMLHttpRequest interceptor may run in environments\n * that implement XMLHttpRequest but don't implement \"location\"\n * (for example, React Native). If that's the case, return the\n * input URL as-is (nothing to be relative to).\n * @see https://github.com/mswjs/msw/issues/1777\n */\n if (typeof location === 'undefined') {\n return new URL(url)\n }\n\n return new URL(url.toString(), location.href)\n}\n\nfunction define(\n target: object,\n property: string | symbol,\n value: unknown\n): void {\n Reflect.defineProperty(target, property, {\n // Ensure writable properties to allow redefining readonly properties.\n writable: true,\n enumerable: true,\n value,\n })\n}\n","import type { Logger } from '@open-draft/logger'\nimport { XMLHttpRequestEmitter } from '.'\nimport { RequestController } from '../../RequestController'\nimport { XMLHttpRequestController } from './XMLHttpRequestController'\nimport { handleRequest } from '../../utils/handleRequest'\nimport { isResponseError } from '../../utils/responseUtils'\n\nexport interface XMLHttpRequestProxyOptions {\n emitter: XMLHttpRequestEmitter\n logger: Logger\n}\n\n/**\n * Create a proxied `XMLHttpRequest` class.\n * The proxied class establishes spies on certain methods,\n * allowing us to intercept requests and respond to them.\n */\nexport function createXMLHttpRequestProxy({\n emitter,\n logger,\n}: XMLHttpRequestProxyOptions) {\n const XMLHttpRequestProxy = new Proxy(globalThis.XMLHttpRequest, {\n construct(target, args, newTarget) {\n logger.info('constructed new XMLHttpRequest')\n\n const originalRequest = Reflect.construct(\n target,\n args,\n newTarget\n ) as XMLHttpRequest\n\n /**\n * @note Forward prototype descriptors onto the proxied object.\n * XMLHttpRequest is implemented in JSDOM in a way that assigns\n * a bunch of descriptors, like \"set responseType()\" on the prototype.\n * With this propagation, we make sure that those descriptors trigger\n * when the user operates with the proxied request instance.\n */\n const prototypeDescriptors = Object.getOwnPropertyDescriptors(\n target.prototype\n )\n for (const propertyName in prototypeDescriptors) {\n Reflect.defineProperty(\n originalRequest,\n propertyName,\n prototypeDescriptors[propertyName]\n )\n }\n\n const xhrRequestController = new XMLHttpRequestController(\n originalRequest,\n logger\n )\n\n xhrRequestController.onRequest = async function ({ request, requestId }) {\n const controller = new RequestController(request, {\n passthrough: () => {\n this.logger.info(\n 'no mocked response received, performing request as-is...'\n )\n },\n respondWith: async (response) => {\n if (isResponseError(response)) {\n this.errorWith(new TypeError('Network error'))\n return\n }\n\n await this.respondWith(response)\n },\n errorWith: (reason) => {\n this.logger.info('request errored!', { error: reason })\n\n if (reason instanceof Error) {\n this.errorWith(reason)\n }\n },\n })\n\n this.logger.info('awaiting mocked response...')\n\n this.logger.info(\n 'emitting the \"request\" event for %s listener(s)...',\n emitter.listenerCount('request')\n )\n\n await handleRequest({\n request,\n requestId,\n controller,\n emitter,\n })\n }\n\n xhrRequestController.onResponse = async function ({\n response,\n isMockedResponse,\n request,\n requestId,\n }) {\n this.logger.info(\n 'emitting the \"response\" event for %s listener(s)...',\n emitter.listenerCount('response')\n )\n\n emitter.emit('response', {\n response,\n isMockedResponse,\n request,\n requestId,\n })\n }\n\n // Return the proxied request from the controller\n // so that the controller can react to the consumer's interactions\n // with this request (opening/sending/etc).\n return xhrRequestController.request\n },\n })\n\n return XMLHttpRequestProxy\n}\n","import { Emitter } from 'strict-event-emitter'\nimport { HttpRequestEventMap } from '../../glossary'\nimport { Interceptor } from '../../Interceptor'\nimport { createXMLHttpRequestProxy } from './XMLHttpRequestProxy'\nimport { hasConfigurableGlobal } from '../../utils/hasConfigurableGlobal'\nimport { patchesRegistry } from '../../utils/patchesRegistry'\n\nexport type XMLHttpRequestEmitter = Emitter\n\nexport class XMLHttpRequestInterceptor extends Interceptor {\n static symbol = Symbol.for('xhr-interceptor')\n\n constructor() {\n super(XMLHttpRequestInterceptor.symbol)\n }\n\n protected checkEnvironment() {\n return hasConfigurableGlobal('XMLHttpRequest')\n }\n\n protected setup() {\n const logger = this.logger.extend('setup')\n\n logger.info('patching global XMLHttpRequest...')\n\n this.subscriptions.push(\n patchesRegistry.applyPatch(globalThis, 'XMLHttpRequest', () => {\n return createXMLHttpRequestProxy({\n emitter: this.emitter,\n logger: this.logger,\n })\n })\n )\n\n logger.info(\n 'global XMLHttpRequest patched!',\n globalThis.XMLHttpRequest.name\n )\n }\n}\n"],"mappings":";;;;;;;;;;;;AAGA,SAAgB,kBACd,MACA,OACY;CACZ,MAAM,SAAS,IAAI,WAAW,KAAK,aAAa,MAAM,WAAW;AACjE,QAAO,IAAI,MAAM,EAAE;AACnB,QAAO,IAAI,OAAO,KAAK,WAAW;AAClC,QAAO;;;;;ACVT,IAAa,gBAAb,MAA4C;CAwB1C,YACE,MACA,SACA;cA1Bc;yBACW;mBACN;wBACK;cAEJ;oBACkB;uBAEG;oBACf;mBAEA;kBACD;oBACE;0BACM;iBACT;0BACS;gBACX;eACD;sBAEC;qBACD;AAMrB,OAAK,OAAO;AACZ,OAAK,SAAS,SAAS,UAAU;AACjC,OAAK,gBAAgB,SAAS,iBAAiB;AAC/C,OAAK,YAAY,KAAK,KAAK;;CAG7B,AAAO,eAA8B;AACnC,SAAO,EAAE;;CAGX,AAAO,UAAU,MAAc,SAAmB,YAAsB;AACtE,OAAK,OAAO;AACZ,OAAK,UAAU,CAAC,CAAC;AACjB,OAAK,aAAa,CAAC,CAAC;;CAGtB,AAAO,iBAAiB;AACtB,OAAK,mBAAmB;;CAG1B,AAAO,kBAAkB;CACzB,AAAO,2BAA2B;;;;;AC/CpC,IAAa,wBAAb,cAA2C,cAAc;CAMvD,YAAY,MAAc,MAA0B;AAClD,QAAM,KAAK;AAEX,OAAK,mBAAmB,MAAM,oBAAoB;AAClD,OAAK,WAAW,MAAM,YAAY;AAClC,OAAK,SAAS,MAAM,UAAU;AAC9B,OAAK,QAAQ,MAAM,SAAS;;;;;;ACXhC,MAAM,0BAA0B,OAAO,kBAAkB;AAEzD,SAAgB,YACd,QACA,MACA,MAC+B;CAC/B,MAAM,iBAAiB;EACrB;EACA;EACA;EACA;EACA;EACA;EACA;EAC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I,UAAU,gBAAgB,CAAC;AAC9C;;AAGF,WAAM,KAAK,YAAY,SAAS;;IAElC,YAAY,WAAW;AACrB,UAAK,OAAO,KAAK,oBAAoB,EAAE,OAAO,QAAQ,CAAC;AAEvD,SAAI,kBAAkB,MACpB,MAAK,UAAU,OAAO;;IAG3B,CAAC;AAEF,QAAK,OAAO,KAAK,8BAA8B;AAE/C,QAAK,OAAO,KACV,wDACA,QAAQ,cAAc,UAAU,CACjC;AAED,SAAM,cAAc;IAClB;IACA;IACA;IACA;IACD,CAAC;;AAGJ,uBAAqB,aAAa,eAAgB,EAChD,UACA,kBACA,SACA,aACC;AACD,QAAK,OAAO,KACV,yDACA,QAAQ,cAAc,WAAW,CAClC;AAED,WAAQ,KAAK,YAAY;IACvB;IACA;IACA;IACA;IACD,CAAC;;AAMJ,SAAO,qBAAqB;IAE/B,CAAC;;;;;AC5GJ,IAAa,4BAAb,MAAa,kCAAkC,YAAiC;;gBAC9D,OAAO,IAAI,kBAAkB;;CAE7C,cAAc;AACZ,QAAM,0BAA0B,OAAO;;CAGzC,AAAU,mBAAmB;AAC3B,SAAO,sBAAsB,iBAAiB;;CAGhD,AAAU,QAAQ;EAChB,MAAM,SAAS,KAAK,OAAO,OAAO,QAAQ;AAE1C,SAAO,KAAK,oCAAoC;AAEhD,OAAK,cAAc,KACjB,gBAAgB,WAAW,YAAY,wBAAwB;AAC7D,UAAO,0BAA0B;IAC/B,SAAS,KAAK;IACd,QAAQ,KAAK;IACd,CAAC;IACF,CACH;AAED,SAAO,KACL,kCACA,WAAW,eAAe,KAC3B"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/XMLHttpRequest-gXuzzX1g.cjs b/node_modules/@mswjs/interceptors/lib/browser/XMLHttpRequest-gXuzzX1g.cjs new file mode 100644 index 0000000000000000000000000000000000000000..44c5a443572a9f146bd766a330c869340d45e05c --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/XMLHttpRequest-gXuzzX1g.cjs @@ -0,0 +1,751 @@ +const require_createRequestId = require('./createRequestId-DOf8Ktjs.cjs'); +const require_getRawRequest = require('./getRawRequest-DdfaiPVH.cjs'); +const require_bufferUtils = require('./bufferUtils-Uc0eRItL.cjs'); +const require_hasConfigurableGlobal = require('./hasConfigurableGlobal-CS7adEvV.cjs'); +const require_handleRequest = require('./handleRequest-CJim54xG.cjs'); +let outvariant = require("outvariant"); +let is_node_process = require("is-node-process"); + +//#region src/interceptors/XMLHttpRequest/utils/concatArrayBuffer.ts +/** +* Concatenate two `Uint8Array` buffers. +*/ +function concatArrayBuffer(left, right) { + const result = new Uint8Array(left.byteLength + right.byteLength); + result.set(left, 0); + result.set(right, left.byteLength); + return result; +} + +//#endregion +//#region src/interceptors/XMLHttpRequest/polyfills/EventPolyfill.ts +var EventPolyfill = class { + constructor(type, options) { + this.NONE = 0; + this.CAPTURING_PHASE = 1; + this.AT_TARGET = 2; + this.BUBBLING_PHASE = 3; + this.type = ""; + this.srcElement = null; + this.currentTarget = null; + this.eventPhase = 0; + this.isTrusted = true; + this.composed = false; + this.cancelable = true; + this.defaultPrevented = false; + this.bubbles = true; + this.lengthComputable = true; + this.loaded = 0; + this.total = 0; + this.cancelBubble = false; + this.returnValue = true; + this.type = type; + this.target = options?.target || null; + this.currentTarget = options?.currentTarget || null; + this.timeStamp = Date.now(); + } + composedPath() { + return []; + } + initEvent(type, bubbles, cancelable) { + this.type = type; + this.bubbles = !!bubbles; + this.cancelable = !!cancelable; + } + preventDefault() { + this.defaultPrevented = true; + } + stopPropagation() {} + stopImmediatePropagation() {} +}; + +//#endregion +//#region src/interceptors/XMLHttpRequest/polyfills/ProgressEventPolyfill.ts +var ProgressEventPolyfill = class extends EventPolyfill { + constructor(type, init) { + super(type); + this.lengthComputable = init?.lengthComputable || false; + this.composed = init?.composed || false; + this.loaded = init?.loaded || 0; + this.total = init?.total || 0; + } +}; + +//#endregion +//#region src/interceptors/XMLHttpRequest/utils/createEvent.ts +const SUPPORTS_PROGRESS_EVENT = typeof ProgressEvent !== "undefined"; +function createEvent(target, type, init) { + const progressEvents = [ + "error", + "progress", + "loadstart", + "loadend", + "load", + "timeout", + "abort" + ]; + /** + * `ProgressEvent` is not supported in React Native. + * @see https://github.com/mswjs/interceptors/issues/40 + */ + const ProgressEventClass = SUPPORTS_PROGRESS_EVENT ? ProgressEvent : ProgressEventPolyfill; + return progressEvents.includes(type) ? new ProgressEventClass(type, { + lengthComputable: true, + loaded: init?.loaded || 0, + total: init?.total || 0 + }) : new EventPolyfill(type, { + target, + currentTarget: target + }); +} + +//#endregion +//#region src/utils/findPropertySource.ts +/** +* Returns the source object of the given property on the target object +* (the target itself, any parent in its prototype, or null). +*/ +function findPropertySource(target, propertyName) { + if (!(propertyName in target)) return null; + if (Object.prototype.hasOwnProperty.call(target, propertyName)) return target; + const prototype = Reflect.getPrototypeOf(target); + return prototype ? findPropertySource(prototype, propertyName) : null; +} + +//#endregion +//#region src/utils/createProxy.ts +function createProxy(target, options) { + return new Proxy(target, optionsToProxyHandler(options)); +} +function optionsToProxyHandler(options) { + const { constructorCall, methodCall, getProperty, setProperty } = options; + const handler = {}; + if (typeof constructorCall !== "undefined") handler.construct = function(target, args, newTarget) { + const next = Reflect.construct.bind(null, target, args, newTarget); + return constructorCall.call(newTarget, args, next); + }; + handler.set = function(target, propertyName, nextValue) { + const next = () => { + const propertySource = findPropertySource(target, propertyName) || target; + const ownDescriptors = Reflect.getOwnPropertyDescriptor(propertySource, propertyName); + if (typeof ownDescriptors?.set !== "undefined") { + ownDescriptors.set.apply(target, [nextValue]); + return true; + } + return Reflect.defineProperty(propertySource, propertyName, { + writable: true, + enumerable: true, + configurable: true, + value: nextValue + }); + }; + if (typeof setProperty !== "undefined") return setProperty.call(target, [propertyName, nextValue], next); + return next(); + }; + handler.get = function(target, propertyName, receiver) { + /** + * @note Using `Reflect.get()` here causes "TypeError: Illegal invocation". + */ + const next = () => target[propertyName]; + const value = typeof getProperty !== "undefined" ? getProperty.call(target, [propertyName, receiver], next) : next(); + if (typeof value === "function") return (...args) => { + const next$1 = value.bind(target, ...args); + if (typeof methodCall !== "undefined") return methodCall.call(target, [propertyName, args], next$1); + return next$1(); + }; + return value; + }; + return handler; +} + +//#endregion +//#region src/interceptors/XMLHttpRequest/utils/isDomParserSupportedType.ts +function isDomParserSupportedType(type) { + return [ + "application/xhtml+xml", + "application/xml", + "image/svg+xml", + "text/html", + "text/xml" + ].some((supportedType) => { + return type.startsWith(supportedType); + }); +} + +//#endregion +//#region src/utils/parseJson.ts +/** +* Parses a given string into JSON. +* Gracefully handles invalid JSON by returning `null`. +*/ +function parseJson(data) { + try { + return JSON.parse(data); + } catch (_) { + return null; + } +} + +//#endregion +//#region src/interceptors/XMLHttpRequest/utils/createResponse.ts +/** +* Creates a Fetch API `Response` instance from the given +* `XMLHttpRequest` instance and a response body. +*/ +function createResponse(request, body) { + return new require_getRawRequest.FetchResponse(require_getRawRequest.FetchResponse.isResponseWithBody(request.status) ? body : null, { + url: request.responseURL, + status: request.status, + statusText: request.statusText, + headers: createHeadersFromXMLHttpRequestHeaders(request.getAllResponseHeaders()) + }); +} +function createHeadersFromXMLHttpRequestHeaders(headersString) { + const headers = new Headers(); + const lines = headersString.split(/[\r\n]+/); + for (const line of lines) { + if (line.trim() === "") continue; + const [name, ...parts] = line.split(": "); + const value = parts.join(": "); + headers.append(name, value); + } + return headers; +} + +//#endregion +//#region src/interceptors/XMLHttpRequest/utils/getBodyByteLength.ts +/** +* Return a total byte length of the given request/response body. +* If the `Content-Length` header is present, it will be used as the byte length. +*/ +async function getBodyByteLength(input) { + const explicitContentLength = input.headers.get("content-length"); + if (explicitContentLength != null && explicitContentLength !== "") return Number(explicitContentLength); + return (await input.arrayBuffer()).byteLength; +} + +//#endregion +//#region src/interceptors/XMLHttpRequest/XMLHttpRequestController.ts +const kIsRequestHandled = Symbol("kIsRequestHandled"); +const IS_NODE = (0, is_node_process.isNodeProcess)(); +const kFetchRequest = Symbol("kFetchRequest"); +/** +* An `XMLHttpRequest` instance controller that allows us +* to handle any given request instance (e.g. responding to it). +*/ +var XMLHttpRequestController = class { + constructor(initialRequest, logger) { + this.initialRequest = initialRequest; + this.logger = logger; + this.method = "GET"; + this.url = null; + this[kIsRequestHandled] = false; + this.events = /* @__PURE__ */ new Map(); + this.uploadEvents = /* @__PURE__ */ new Map(); + this.requestId = require_createRequestId.createRequestId(); + this.requestHeaders = new Headers(); + this.responseBuffer = new Uint8Array(); + this.request = createProxy(initialRequest, { + setProperty: ([propertyName, nextValue], invoke) => { + switch (propertyName) { + case "ontimeout": { + const eventName = propertyName.slice(2); + /** + * @note Proxy callbacks to event listeners because JSDOM has trouble + * translating these properties to callbacks. It seemed to be operating + * on events exclusively. + */ + this.request.addEventListener(eventName, nextValue); + return invoke(); + } + default: return invoke(); + } + }, + methodCall: ([methodName, args], invoke) => { + switch (methodName) { + case "open": { + const [method, url] = args; + if (typeof url === "undefined") { + this.method = "GET"; + this.url = toAbsoluteUrl(method); + } else { + this.method = method; + this.url = toAbsoluteUrl(url); + } + this.logger = this.logger.extend(`${this.method} ${this.url.href}`); + this.logger.info("open", this.method, this.url.href); + return invoke(); + } + case "addEventListener": { + const [eventName, listener] = args; + this.registerEvent(eventName, listener); + this.logger.info("addEventListener", eventName, listener); + return invoke(); + } + case "setRequestHeader": { + const [name, value] = args; + this.requestHeaders.set(name, value); + this.logger.info("setRequestHeader", name, value); + return invoke(); + } + case "send": { + const [body] = args; + this.request.addEventListener("load", () => { + if (typeof this.onResponse !== "undefined") { + const fetchResponse = createResponse( + this.request, + /** + * The `response` property is the right way to read + * the ambiguous response body, as the request's "responseType" may differ. + * @see https://xhr.spec.whatwg.org/#the-response-attribute + */ + this.request.response + ); + this.onResponse.call(this, { + response: fetchResponse, + isMockedResponse: this[kIsRequestHandled], + request: fetchRequest, + requestId: this.requestId + }); + } + }); + const requestBody = typeof body === "string" ? require_bufferUtils.encodeBuffer(body) : body; + const fetchRequest = this.toFetchApiRequest(requestBody); + this[kFetchRequest] = fetchRequest.clone(); + /** + * @note Start request handling on the next tick so that the user + * could add event listeners for "loadend" before the interceptor fires it. + */ + queueMicrotask(() => { + (this.onRequest?.call(this, { + request: fetchRequest, + requestId: this.requestId + }) || Promise.resolve()).finally(() => { + if (!this[kIsRequestHandled]) { + this.logger.info("request callback settled but request has not been handled (readystate %d), performing as-is...", this.request.readyState); + /** + * @note Set the intercepted request ID on the original request in Node.js + * so that if it triggers any other interceptors, they don't attempt + * to process it once again. + * + * For instance, XMLHttpRequest is often implemented via "http.ClientRequest" + * and we don't want for both XHR and ClientRequest interceptors to + * handle the same request at the same time (e.g. emit the "response" event twice). + */ + if (IS_NODE) this.request.setRequestHeader(require_createRequestId.INTERNAL_REQUEST_ID_HEADER_NAME, this.requestId); + return invoke(); + } + }); + }); + break; + } + default: return invoke(); + } + } + }); + /** + * Proxy the `.upload` property to gather the event listeners/callbacks. + */ + define(this.request, "upload", createProxy(this.request.upload, { + setProperty: ([propertyName, nextValue], invoke) => { + switch (propertyName) { + case "onloadstart": + case "onprogress": + case "onaboart": + case "onerror": + case "onload": + case "ontimeout": + case "onloadend": { + const eventName = propertyName.slice(2); + this.registerUploadEvent(eventName, nextValue); + } + } + return invoke(); + }, + methodCall: ([methodName, args], invoke) => { + switch (methodName) { + case "addEventListener": { + const [eventName, listener] = args; + this.registerUploadEvent(eventName, listener); + this.logger.info("upload.addEventListener", eventName, listener); + return invoke(); + } + } + } + })); + } + registerEvent(eventName, listener) { + const nextEvents = (this.events.get(eventName) || []).concat(listener); + this.events.set(eventName, nextEvents); + this.logger.info("registered event \"%s\"", eventName, listener); + } + registerUploadEvent(eventName, listener) { + const nextEvents = (this.uploadEvents.get(eventName) || []).concat(listener); + this.uploadEvents.set(eventName, nextEvents); + this.logger.info("registered upload event \"%s\"", eventName, listener); + } + /** + * Responds to the current request with the given + * Fetch API `Response` instance. + */ + async respondWith(response) { + /** + * @note Since `XMLHttpRequestController` delegates the handling of the responses + * to the "load" event listener that doesn't distinguish between the mocked and original + * responses, mark the request that had a mocked response with a corresponding symbol. + * + * Mark this request as having a mocked response immediately since + * calculating request/response total body length is asynchronous. + */ + this[kIsRequestHandled] = true; + /** + * Dispatch request upload events for requests with a body. + * @see https://github.com/mswjs/interceptors/issues/573 + */ + if (this[kFetchRequest]) { + const totalRequestBodyLength = await getBodyByteLength(this[kFetchRequest]); + this.trigger("loadstart", this.request.upload, { + loaded: 0, + total: totalRequestBodyLength + }); + this.trigger("progress", this.request.upload, { + loaded: totalRequestBodyLength, + total: totalRequestBodyLength + }); + this.trigger("load", this.request.upload, { + loaded: totalRequestBodyLength, + total: totalRequestBodyLength + }); + this.trigger("loadend", this.request.upload, { + loaded: totalRequestBodyLength, + total: totalRequestBodyLength + }); + } + this.logger.info("responding with a mocked response: %d %s", response.status, response.statusText); + define(this.request, "status", response.status); + define(this.request, "statusText", response.statusText); + define(this.request, "responseURL", this.url.href); + this.request.getResponseHeader = new Proxy(this.request.getResponseHeader, { apply: (_, __, args) => { + this.logger.info("getResponseHeader", args[0]); + if (this.request.readyState < this.request.HEADERS_RECEIVED) { + this.logger.info("headers not received yet, returning null"); + return null; + } + const headerValue = response.headers.get(args[0]); + this.logger.info("resolved response header \"%s\" to", args[0], headerValue); + return headerValue; + } }); + this.request.getAllResponseHeaders = new Proxy(this.request.getAllResponseHeaders, { apply: () => { + this.logger.info("getAllResponseHeaders"); + if (this.request.readyState < this.request.HEADERS_RECEIVED) { + this.logger.info("headers not received yet, returning empty string"); + return ""; + } + const allHeaders = Array.from(response.headers.entries()).map(([headerName, headerValue]) => { + return `${headerName}: ${headerValue}`; + }).join("\r\n"); + this.logger.info("resolved all response headers to", allHeaders); + return allHeaders; + } }); + Object.defineProperties(this.request, { + response: { + enumerable: true, + configurable: false, + get: () => this.response + }, + responseText: { + enumerable: true, + configurable: false, + get: () => this.responseText + }, + responseXML: { + enumerable: true, + configurable: false, + get: () => this.responseXML + } + }); + const totalResponseBodyLength = await getBodyByteLength(response.clone()); + this.logger.info("calculated response body length", totalResponseBodyLength); + this.trigger("loadstart", this.request, { + loaded: 0, + total: totalResponseBodyLength + }); + this.setReadyState(this.request.HEADERS_RECEIVED); + this.setReadyState(this.request.LOADING); + const finalizeResponse = () => { + this.logger.info("finalizing the mocked response..."); + this.setReadyState(this.request.DONE); + this.trigger("load", this.request, { + loaded: this.responseBuffer.byteLength, + total: totalResponseBodyLength + }); + this.trigger("loadend", this.request, { + loaded: this.responseBuffer.byteLength, + total: totalResponseBodyLength + }); + }; + if (response.body) { + this.logger.info("mocked response has body, streaming..."); + const reader = response.body.getReader(); + const readNextResponseBodyChunk = async () => { + const { value, done } = await reader.read(); + if (done) { + this.logger.info("response body stream done!"); + finalizeResponse(); + return; + } + if (value) { + this.logger.info("read response body chunk:", value); + this.responseBuffer = concatArrayBuffer(this.responseBuffer, value); + this.trigger("progress", this.request, { + loaded: this.responseBuffer.byteLength, + total: totalResponseBodyLength + }); + } + readNextResponseBodyChunk(); + }; + readNextResponseBodyChunk(); + } else finalizeResponse(); + } + responseBufferToText() { + return require_bufferUtils.decodeBuffer(this.responseBuffer); + } + get response() { + this.logger.info("getResponse (responseType: %s)", this.request.responseType); + if (this.request.readyState !== this.request.DONE) return null; + switch (this.request.responseType) { + case "json": { + const responseJson = parseJson(this.responseBufferToText()); + this.logger.info("resolved response JSON", responseJson); + return responseJson; + } + case "arraybuffer": { + const arrayBuffer = require_bufferUtils.toArrayBuffer(this.responseBuffer); + this.logger.info("resolved response ArrayBuffer", arrayBuffer); + return arrayBuffer; + } + case "blob": { + const mimeType = this.request.getResponseHeader("Content-Type") || "text/plain"; + const responseBlob = new Blob([this.responseBufferToText()], { type: mimeType }); + this.logger.info("resolved response Blob (mime type: %s)", responseBlob, mimeType); + return responseBlob; + } + default: { + const responseText = this.responseBufferToText(); + this.logger.info("resolving \"%s\" response type as text", this.request.responseType, responseText); + return responseText; + } + } + } + get responseText() { + /** + * Throw when trying to read the response body as text when the + * "responseType" doesn't expect text. This just respects the spec better. + * @see https://xhr.spec.whatwg.org/#the-responsetext-attribute + */ + (0, outvariant.invariant)(this.request.responseType === "" || this.request.responseType === "text", "InvalidStateError: The object is in invalid state."); + if (this.request.readyState !== this.request.LOADING && this.request.readyState !== this.request.DONE) return ""; + const responseText = this.responseBufferToText(); + this.logger.info("getResponseText: \"%s\"", responseText); + return responseText; + } + get responseXML() { + (0, outvariant.invariant)(this.request.responseType === "" || this.request.responseType === "document", "InvalidStateError: The object is in invalid state."); + if (this.request.readyState !== this.request.DONE) return null; + const contentType = this.request.getResponseHeader("Content-Type") || ""; + if (typeof DOMParser === "undefined") { + console.warn("Cannot retrieve XMLHttpRequest response body as XML: DOMParser is not defined. You are likely using an environment that is not browser or does not polyfill browser globals correctly."); + return null; + } + if (isDomParserSupportedType(contentType)) return new DOMParser().parseFromString(this.responseBufferToText(), contentType); + return null; + } + errorWith(error) { + /** + * @note Mark this request as handled even if it received a mock error. + * This prevents the controller from trying to perform this request as-is. + */ + this[kIsRequestHandled] = true; + this.logger.info("responding with an error"); + this.setReadyState(this.request.DONE); + this.trigger("error", this.request); + this.trigger("loadend", this.request); + } + /** + * Transitions this request's `readyState` to the given one. + */ + setReadyState(nextReadyState) { + this.logger.info("setReadyState: %d -> %d", this.request.readyState, nextReadyState); + if (this.request.readyState === nextReadyState) { + this.logger.info("ready state identical, skipping transition..."); + return; + } + define(this.request, "readyState", nextReadyState); + this.logger.info("set readyState to: %d", nextReadyState); + if (nextReadyState !== this.request.UNSENT) { + this.logger.info("triggering \"readystatechange\" event..."); + this.trigger("readystatechange", this.request); + } + } + /** + * Triggers given event on the `XMLHttpRequest` instance. + */ + trigger(eventName, target, options) { + const callback = target[`on${eventName}`]; + const event = createEvent(target, eventName, options); + this.logger.info("trigger \"%s\"", eventName, options || ""); + if (typeof callback === "function") { + this.logger.info("found a direct \"%s\" callback, calling...", eventName); + callback.call(target, event); + } + const events = target instanceof XMLHttpRequestUpload ? this.uploadEvents : this.events; + for (const [registeredEventName, listeners] of events) if (registeredEventName === eventName) { + this.logger.info("found %d listener(s) for \"%s\" event, calling...", listeners.length, eventName); + listeners.forEach((listener) => listener.call(target, event)); + } + } + /** + * Converts this `XMLHttpRequest` instance into a Fetch API `Request` instance. + */ + toFetchApiRequest(body) { + this.logger.info("converting request to a Fetch API Request..."); + const resolvedBody = body instanceof Document ? body.documentElement.innerText : body; + const fetchRequest = new require_getRawRequest.FetchRequest(this.url.href, { + method: this.method, + headers: this.requestHeaders, + credentials: this.request.withCredentials ? "include" : "same-origin", + body: ["GET", "HEAD"].includes(this.method.toUpperCase()) ? null : resolvedBody + }); + define(fetchRequest, "headers", createProxy(fetchRequest.headers, { methodCall: ([methodName, args], invoke) => { + switch (methodName) { + case "append": + case "set": { + const [headerName, headerValue] = args; + this.request.setRequestHeader(headerName, headerValue); + break; + } + case "delete": { + const [headerName] = args; + console.warn(`XMLHttpRequest: Cannot remove a "${headerName}" header from the Fetch API representation of the "${fetchRequest.method} ${fetchRequest.url}" request. XMLHttpRequest headers cannot be removed.`); + break; + } + } + return invoke(); + } })); + require_getRawRequest.setRawRequest(fetchRequest, this.request); + this.logger.info("converted request to a Fetch API Request!", fetchRequest); + return fetchRequest; + } +}; +function toAbsoluteUrl(url) { + /** + * @note XMLHttpRequest interceptor may run in environments + * that implement XMLHttpRequest but don't implement "location" + * (for example, React Native). If that's the case, return the + * input URL as-is (nothing to be relative to). + * @see https://github.com/mswjs/msw/issues/1777 + */ + if (typeof location === "undefined") return new URL(url); + return new URL(url.toString(), location.href); +} +function define(target, property, value) { + Reflect.defineProperty(target, property, { + writable: true, + enumerable: true, + value + }); +} + +//#endregion +//#region src/interceptors/XMLHttpRequest/XMLHttpRequestProxy.ts +/** +* Create a proxied `XMLHttpRequest` class. +* The proxied class establishes spies on certain methods, +* allowing us to intercept requests and respond to them. +*/ +function createXMLHttpRequestProxy({ emitter, logger }) { + return new Proxy(globalThis.XMLHttpRequest, { construct(target, args, newTarget) { + logger.info("constructed new XMLHttpRequest"); + const originalRequest = Reflect.construct(target, args, newTarget); + /** + * @note Forward prototype descriptors onto the proxied object. + * XMLHttpRequest is implemented in JSDOM in a way that assigns + * a bunch of descriptors, like "set responseType()" on the prototype. + * With this propagation, we make sure that those descriptors trigger + * when the user operates with the proxied request instance. + */ + const prototypeDescriptors = Object.getOwnPropertyDescriptors(target.prototype); + for (const propertyName in prototypeDescriptors) Reflect.defineProperty(originalRequest, propertyName, prototypeDescriptors[propertyName]); + const xhrRequestController = new XMLHttpRequestController(originalRequest, logger); + xhrRequestController.onRequest = async function({ request, requestId }) { + const controller = new require_getRawRequest.RequestController(request, { + passthrough: () => { + this.logger.info("no mocked response received, performing request as-is..."); + }, + respondWith: async (response) => { + if (require_handleRequest.isResponseError(response)) { + this.errorWith(/* @__PURE__ */ new TypeError("Network error")); + return; + } + await this.respondWith(response); + }, + errorWith: (reason) => { + this.logger.info("request errored!", { error: reason }); + if (reason instanceof Error) this.errorWith(reason); + } + }); + this.logger.info("awaiting mocked response..."); + this.logger.info("emitting the \"request\" event for %s listener(s)...", emitter.listenerCount("request")); + await require_handleRequest.handleRequest({ + request, + requestId, + controller, + emitter + }); + }; + xhrRequestController.onResponse = async function({ response, isMockedResponse, request, requestId }) { + this.logger.info("emitting the \"response\" event for %s listener(s)...", emitter.listenerCount("response")); + emitter.emit("response", { + response, + isMockedResponse, + request, + requestId + }); + }; + return xhrRequestController.request; + } }); +} + +//#endregion +//#region src/interceptors/XMLHttpRequest/index.ts +var XMLHttpRequestInterceptor = class XMLHttpRequestInterceptor extends require_createRequestId.Interceptor { + static { + this.symbol = Symbol.for("xhr-interceptor"); + } + constructor() { + super(XMLHttpRequestInterceptor.symbol); + } + checkEnvironment() { + return require_hasConfigurableGlobal.hasConfigurableGlobal("XMLHttpRequest"); + } + setup() { + const logger = this.logger.extend("setup"); + logger.info("patching global XMLHttpRequest..."); + this.subscriptions.push(require_hasConfigurableGlobal.patchesRegistry.applyPatch(globalThis, "XMLHttpRequest", () => { + return createXMLHttpRequestProxy({ + emitter: this.emitter, + logger: this.logger + }); + })); + logger.info("global XMLHttpRequest patched!", globalThis.XMLHttpRequest.name); + } +}; + +//#endregion +Object.defineProperty(exports, 'XMLHttpRequestInterceptor', { + enumerable: true, + get: function () { + return XMLHttpRequestInterceptor; + } +}); +//# sourceMappingURL=XMLHttpRequest-gXuzzX1g.cjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/XMLHttpRequest-gXuzzX1g.cjs.map b/node_modules/@mswjs/interceptors/lib/browser/XMLHttpRequest-gXuzzX1g.cjs.map new file mode 100644 index 0000000000000000000000000000000000000000..8da60c332ba5b240dad1f8af8e8e8b257b9edc94 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/XMLHttpRequest-gXuzzX1g.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"XMLHttpRequest-gXuzzX1g.cjs","names":["handler: ProxyHandler","next","FetchResponse","initialRequest: XMLHttpRequest","logger: Logger","createRequestId","encodeBuffer","INTERNAL_REQUEST_ID_HEADER_NAME","decodeBuffer","toArrayBuffer","FetchRequest","RequestController","isResponseError","handleRequest","Interceptor","hasConfigurableGlobal","patchesRegistry"],"sources":["../../src/interceptors/XMLHttpRequest/utils/concatArrayBuffer.ts","../../src/interceptors/XMLHttpRequest/polyfills/EventPolyfill.ts","../../src/interceptors/XMLHttpRequest/polyfills/ProgressEventPolyfill.ts","../../src/interceptors/XMLHttpRequest/utils/createEvent.ts","../../src/utils/findPropertySource.ts","../../src/utils/createProxy.ts","../../src/interceptors/XMLHttpRequest/utils/isDomParserSupportedType.ts","../../src/utils/parseJson.ts","../../src/interceptors/XMLHttpRequest/utils/createResponse.ts","../../src/interceptors/XMLHttpRequest/utils/getBodyByteLength.ts","../../src/interceptors/XMLHttpRequest/XMLHttpRequestController.ts","../../src/interceptors/XMLHttpRequest/XMLHttpRequestProxy.ts","../../src/interceptors/XMLHttpRequest/index.ts"],"sourcesContent":["/**\n * Concatenate two `Uint8Array` buffers.\n */\nexport function concatArrayBuffer(\n left: Uint8Array,\n right: Uint8Array\n): Uint8Array {\n const result = new Uint8Array(left.byteLength + right.byteLength)\n result.set(left, 0)\n result.set(right, left.byteLength)\n return result\n}\n","export class EventPolyfill implements Event {\n readonly NONE = 0\n readonly CAPTURING_PHASE = 1\n readonly AT_TARGET = 2\n readonly BUBBLING_PHASE = 3\n\n public type: string = ''\n public srcElement: EventTarget | null = null\n public target: EventTarget | null\n public currentTarget: EventTarget | null = null\n public eventPhase: number = 0\n public timeStamp: number\n public isTrusted: boolean = true\n public composed: boolean = false\n public cancelable: boolean = true\n public defaultPrevented: boolean = false\n public bubbles: boolean = true\n public lengthComputable: boolean = true\n public loaded: number = 0\n public total: number = 0\n\n cancelBubble: boolean = false\n returnValue: boolean = true\n\n constructor(\n type: string,\n options?: { target: EventTarget; currentTarget: EventTarget }\n ) {\n this.type = type\n this.target = options?.target || null\n this.currentTarget = options?.currentTarget || null\n this.timeStamp = Date.now()\n }\n\n public composedPath(): EventTarget[] {\n return []\n }\n\n public initEvent(type: string, bubbles?: boolean, cancelable?: boolean) {\n this.type = type\n this.bubbles = !!bubbles\n this.cancelable = !!cancelable\n }\n\n public preventDefault() {\n this.defaultPrevented = true\n }\n\n public stopPropagation() {}\n public stopImmediatePropagation() {}\n}\n","import { EventPolyfill } from './EventPolyfill'\n\nexport class ProgressEventPolyfill extends EventPolyfill {\n readonly lengthComputable: boolean\n readonly composed: boolean\n readonly loaded: number\n readonly total: number\n\n constructor(type: string, init?: ProgressEventInit) {\n super(type)\n\n this.lengthComputable = init?.lengthComputable || false\n this.composed = init?.composed || false\n this.loaded = init?.loaded || 0\n this.total = init?.total || 0\n }\n}\n","import { EventPolyfill } from '../polyfills/EventPolyfill'\nimport { ProgressEventPolyfill } from '../polyfills/ProgressEventPolyfill'\n\nconst SUPPORTS_PROGRESS_EVENT = typeof ProgressEvent !== 'undefined'\n\nexport function createEvent(\n target: XMLHttpRequest | XMLHttpRequestUpload,\n type: string,\n init?: ProgressEventInit\n): EventPolyfill | ProgressEvent {\n const progressEvents = [\n 'error',\n 'progress',\n 'loadstart',\n 'loadend',\n 'load',\n 'timeout',\n 'abort',\n ]\n\n /**\n * `ProgressEvent` is not supported in React Native.\n * @see https://github.com/mswjs/interceptors/issues/40\n */\n const ProgressEventClass = SUPPORTS_PROGRESS_EVENT\n ? ProgressEvent\n : ProgressEventPolyfill\n\n const event = progressEvents.includes(type)\n ? new ProgressEventClass(type, {\n lengthComputable: true,\n loaded: init?.loaded || 0,\n total: init?.total || 0,\n })\n : new EventPolyfill(type, {\n target,\n currentTarget: target,\n })\n\n return event\n}\n","/**\n * Returns the source object of the given property on the target object\n * (the target itself, any parent in its prototype, or null).\n */\nexport function findPropertySource(\n target: object,\n propertyName: string | symbol\n): object | null {\n if (!(propertyName in target)) {\n return null\n }\n\n const hasProperty = Object.prototype.hasOwnProperty.call(target, propertyName)\n if (hasProperty) {\n return target\n }\n\n const prototype = Reflect.getPrototypeOf(target)\n return prototype ? findPropertySource(prototype, propertyName) : null\n}\n","import { findPropertySource } from './findPropertySource'\n\nexport interface ProxyOptions> {\n constructorCall?(args: Array, next: NextFunction): Target\n\n methodCall?(\n this: Target,\n data: [methodName: F, args: Array],\n next: NextFunction\n ): void\n\n setProperty?(\n data: [propertyName: string | symbol, nextValue: unknown],\n next: NextFunction\n ): boolean\n\n getProperty?(\n data: [propertyName: string | symbol, receiver: Target],\n next: NextFunction\n ): void\n}\n\nexport type NextFunction = () => ReturnType\n\nexport function createProxy(\n target: Target,\n options: ProxyOptions\n): Target {\n const proxy = new Proxy(target, optionsToProxyHandler(options))\n\n return proxy\n}\n\nfunction optionsToProxyHandler>(\n options: ProxyOptions\n): ProxyHandler {\n const { constructorCall, methodCall, getProperty, setProperty } = options\n const handler: ProxyHandler = {}\n\n if (typeof constructorCall !== 'undefined') {\n handler.construct = function (target, args, newTarget) {\n const next = Reflect.construct.bind(null, target as any, args, newTarget)\n return constructorCall.call(newTarget, args, next)\n }\n }\n\n handler.set = function (target, propertyName, nextValue) {\n const next = () => {\n const propertySource = findPropertySource(target, propertyName) || target\n const ownDescriptors = Reflect.getOwnPropertyDescriptor(\n propertySource,\n propertyName\n )\n\n // Respect any custom setters present for this property.\n if (typeof ownDescriptors?.set !== 'undefined') {\n ownDescriptors.set.apply(target, [nextValue])\n return true\n }\n\n // Otherwise, set the property on the source.\n return Reflect.defineProperty(propertySource, propertyName, {\n writable: true,\n enumerable: true,\n configurable: true,\n value: nextValue,\n })\n }\n\n if (typeof setProperty !== 'undefined') {\n return setProperty.call(target, [propertyName, nextValue], next)\n }\n\n return next()\n }\n\n handler.get = function (target, propertyName, receiver) {\n /**\n * @note Using `Reflect.get()` here causes \"TypeError: Illegal invocation\".\n */\n const next = () => target[propertyName as any]\n\n const value =\n typeof getProperty !== 'undefined'\n ? getProperty.call(target, [propertyName, receiver], next)\n : next()\n\n if (typeof value === 'function') {\n return (...args: Array) => {\n const next = value.bind(target, ...args)\n\n if (typeof methodCall !== 'undefined') {\n return methodCall.call(target, [propertyName as any, args], next)\n }\n\n return next()\n }\n }\n\n return value\n }\n\n return handler\n}\n","export function isDomParserSupportedType(\n type: string\n): type is DOMParserSupportedType {\n const supportedTypes: Array = [\n 'application/xhtml+xml',\n 'application/xml',\n 'image/svg+xml',\n 'text/html',\n 'text/xml',\n ]\n return supportedTypes.some((supportedType) => {\n return type.startsWith(supportedType)\n })\n}\n","/**\n * Parses a given string into JSON.\n * Gracefully handles invalid JSON by returning `null`.\n */\nexport function parseJson(data: string): Record | null {\n try {\n const json = JSON.parse(data)\n return json\n } catch (_) {\n return null\n }\n}\n","import { FetchResponse } from '../../../utils/fetchUtils'\n\n/**\n * Creates a Fetch API `Response` instance from the given\n * `XMLHttpRequest` instance and a response body.\n */\nexport function createResponse(\n request: XMLHttpRequest,\n body: BodyInit | null\n): Response {\n /**\n * Handle XMLHttpRequest responses that must have null as the\n * response body when represented using Fetch API Response.\n * XMLHttpRequest response will always have an empty string\n * as the \"request.response\" in those cases, resulting in an error\n * when constructing a Response instance.\n * @see https://github.com/mswjs/interceptors/issues/379\n */\n const responseBodyOrNull = FetchResponse.isResponseWithBody(request.status)\n ? body\n : null\n\n return new FetchResponse(responseBodyOrNull, {\n url: request.responseURL,\n status: request.status,\n statusText: request.statusText,\n headers: createHeadersFromXMLHttpRequestHeaders(\n request.getAllResponseHeaders()\n ),\n })\n}\n\nfunction createHeadersFromXMLHttpRequestHeaders(headersString: string): Headers {\n const headers = new Headers()\n\n const lines = headersString.split(/[\\r\\n]+/)\n for (const line of lines) {\n if (line.trim() === '') {\n continue\n }\n\n const [name, ...parts] = line.split(': ')\n const value = parts.join(': ')\n\n headers.append(name, value)\n }\n\n return headers\n}\n","/**\n * Return a total byte length of the given request/response body.\n * If the `Content-Length` header is present, it will be used as the byte length.\n */\nexport async function getBodyByteLength(\n input: Request | Response\n): Promise {\n const explicitContentLength = input.headers.get('content-length')\n\n if (explicitContentLength != null && explicitContentLength !== '') {\n return Number(explicitContentLength)\n }\n\n const buffer = await input.arrayBuffer()\n return buffer.byteLength\n}\n","import { invariant } from 'outvariant'\nimport { isNodeProcess } from 'is-node-process'\nimport type { Logger } from '@open-draft/logger'\nimport { concatArrayBuffer } from './utils/concatArrayBuffer'\nimport { createEvent } from './utils/createEvent'\nimport {\n decodeBuffer,\n encodeBuffer,\n toArrayBuffer,\n} from '../../utils/bufferUtils'\nimport { createProxy } from '../../utils/createProxy'\nimport { isDomParserSupportedType } from './utils/isDomParserSupportedType'\nimport { parseJson } from '../../utils/parseJson'\nimport { createResponse } from './utils/createResponse'\nimport { INTERNAL_REQUEST_ID_HEADER_NAME } from '../../Interceptor'\nimport { createRequestId } from '../../createRequestId'\nimport { getBodyByteLength } from './utils/getBodyByteLength'\nimport { setRawRequest } from '../../getRawRequest'\nimport { FetchRequest } from '../../utils/fetchUtils'\n\nconst kIsRequestHandled = Symbol('kIsRequestHandled')\nconst IS_NODE = isNodeProcess()\nconst kFetchRequest = Symbol('kFetchRequest')\n\n/**\n * An `XMLHttpRequest` instance controller that allows us\n * to handle any given request instance (e.g. responding to it).\n */\nexport class XMLHttpRequestController {\n public request: XMLHttpRequest\n public requestId: string\n public onRequest?: (\n this: XMLHttpRequestController,\n args: {\n request: Request\n requestId: string\n }\n ) => Promise\n public onResponse?: (\n this: XMLHttpRequestController,\n args: {\n response: Response\n isMockedResponse: boolean\n request: Request\n requestId: string\n }\n ) => void;\n\n [kIsRequestHandled]: boolean;\n [kFetchRequest]?: Request\n private method: string = 'GET'\n private url: URL = null as any\n private requestHeaders: Headers\n private responseBuffer: Uint8Array\n private events: Map>\n private uploadEvents: Map<\n keyof XMLHttpRequestEventTargetEventMap,\n Array\n >\n\n constructor(\n readonly initialRequest: XMLHttpRequest,\n public logger: Logger\n ) {\n this[kIsRequestHandled] = false\n\n this.events = new Map()\n this.uploadEvents = new Map()\n this.requestId = createRequestId()\n this.requestHeaders = new Headers()\n this.responseBuffer = new Uint8Array()\n\n this.request = createProxy(initialRequest, {\n setProperty: ([propertyName, nextValue], invoke) => {\n switch (propertyName) {\n case 'ontimeout': {\n const eventName = propertyName.slice(\n 2\n ) as keyof XMLHttpRequestEventTargetEventMap\n\n /**\n * @note Proxy callbacks to event listeners because JSDOM has trouble\n * translating these properties to callbacks. It seemed to be operating\n * on events exclusively.\n */\n this.request.addEventListener(eventName, nextValue as any)\n\n return invoke()\n }\n\n default: {\n return invoke()\n }\n }\n },\n methodCall: ([methodName, args], invoke) => {\n switch (methodName) {\n case 'open': {\n const [method, url] = args as [string, string | undefined]\n\n if (typeof url === 'undefined') {\n this.method = 'GET'\n this.url = toAbsoluteUrl(method)\n } else {\n this.method = method\n this.url = toAbsoluteUrl(url)\n }\n\n this.logger = this.logger.extend(`${this.method} ${this.url.href}`)\n this.logger.info('open', this.method, this.url.href)\n\n return invoke()\n }\n\n case 'addEventListener': {\n const [eventName, listener] = args as [\n keyof XMLHttpRequestEventTargetEventMap,\n Function,\n ]\n\n this.registerEvent(eventName, listener)\n this.logger.info('addEventListener', eventName, listener)\n\n return invoke()\n }\n\n case 'setRequestHeader': {\n const [name, value] = args as [string, string]\n this.requestHeaders.set(name, value)\n\n this.logger.info('setRequestHeader', name, value)\n\n return invoke()\n }\n\n case 'send': {\n const [body] = args as [\n body?: XMLHttpRequestBodyInit | Document | null,\n ]\n\n this.request.addEventListener('load', () => {\n if (typeof this.onResponse !== 'undefined') {\n // Create a Fetch API Response representation of whichever\n // response this XMLHttpRequest received. Note those may\n // be either a mocked and the original response.\n const fetchResponse = createResponse(\n this.request,\n /**\n * The `response` property is the right way to read\n * the ambiguous response body, as the request's \"responseType\" may differ.\n * @see https://xhr.spec.whatwg.org/#the-response-attribute\n */\n this.request.response\n )\n\n // Notify the consumer about the response.\n this.onResponse.call(this, {\n response: fetchResponse,\n isMockedResponse: this[kIsRequestHandled],\n request: fetchRequest,\n requestId: this.requestId!,\n })\n }\n })\n\n const requestBody =\n typeof body === 'string' ? encodeBuffer(body) : body\n\n // Delegate request handling to the consumer.\n const fetchRequest = this.toFetchApiRequest(requestBody)\n this[kFetchRequest] = fetchRequest.clone()\n\n /**\n * @note Start request handling on the next tick so that the user\n * could add event listeners for \"loadend\" before the interceptor fires it.\n */\n queueMicrotask(() => {\n const onceRequestSettled =\n this.onRequest?.call(this, {\n request: fetchRequest,\n requestId: this.requestId!,\n }) || Promise.resolve()\n\n onceRequestSettled.finally(() => {\n // If the consumer didn't handle the request (called `.respondWith()`) perform it as-is.\n if (!this[kIsRequestHandled]) {\n this.logger.info(\n 'request callback settled but request has not been handled (readystate %d), performing as-is...',\n this.request.readyState\n )\n\n /**\n * @note Set the intercepted request ID on the original request in Node.js\n * so that if it triggers any other interceptors, they don't attempt\n * to process it once again.\n *\n * For instance, XMLHttpRequest is often implemented via \"http.ClientRequest\"\n * and we don't want for both XHR and ClientRequest interceptors to\n * handle the same request at the same time (e.g. emit the \"response\" event twice).\n */\n if (IS_NODE) {\n this.request.setRequestHeader(\n INTERNAL_REQUEST_ID_HEADER_NAME,\n this.requestId!\n )\n }\n\n return invoke()\n }\n })\n })\n\n break\n }\n\n default: {\n return invoke()\n }\n }\n },\n })\n\n /**\n * Proxy the `.upload` property to gather the event listeners/callbacks.\n */\n define(\n this.request,\n 'upload',\n createProxy(this.request.upload, {\n setProperty: ([propertyName, nextValue], invoke) => {\n switch (propertyName) {\n case 'onloadstart':\n case 'onprogress':\n case 'onaboart':\n case 'onerror':\n case 'onload':\n case 'ontimeout':\n case 'onloadend': {\n const eventName = propertyName.slice(\n 2\n ) as keyof XMLHttpRequestEventTargetEventMap\n\n this.registerUploadEvent(eventName, nextValue as Function)\n }\n }\n\n return invoke()\n },\n methodCall: ([methodName, args], invoke) => {\n switch (methodName) {\n case 'addEventListener': {\n const [eventName, listener] = args as [\n keyof XMLHttpRequestEventTargetEventMap,\n Function,\n ]\n this.registerUploadEvent(eventName, listener)\n this.logger.info('upload.addEventListener', eventName, listener)\n\n return invoke()\n }\n }\n },\n })\n )\n }\n\n private registerEvent(\n eventName: keyof XMLHttpRequestEventTargetEventMap,\n listener: Function\n ): void {\n const prevEvents = this.events.get(eventName) || []\n const nextEvents = prevEvents.concat(listener)\n this.events.set(eventName, nextEvents)\n\n this.logger.info('registered event \"%s\"', eventName, listener)\n }\n\n private registerUploadEvent(\n eventName: keyof XMLHttpRequestEventTargetEventMap,\n listener: Function\n ): void {\n const prevEvents = this.uploadEvents.get(eventName) || []\n const nextEvents = prevEvents.concat(listener)\n this.uploadEvents.set(eventName, nextEvents)\n\n this.logger.info('registered upload event \"%s\"', eventName, listener)\n }\n\n /**\n * Responds to the current request with the given\n * Fetch API `Response` instance.\n */\n public async respondWith(response: Response): Promise {\n /**\n * @note Since `XMLHttpRequestController` delegates the handling of the responses\n * to the \"load\" event listener that doesn't distinguish between the mocked and original\n * responses, mark the request that had a mocked response with a corresponding symbol.\n *\n * Mark this request as having a mocked response immediately since\n * calculating request/response total body length is asynchronous.\n */\n this[kIsRequestHandled] = true\n\n /**\n * Dispatch request upload events for requests with a body.\n * @see https://github.com/mswjs/interceptors/issues/573\n */\n if (this[kFetchRequest]) {\n const totalRequestBodyLength = await getBodyByteLength(\n this[kFetchRequest]\n )\n\n this.trigger('loadstart', this.request.upload, {\n loaded: 0,\n total: totalRequestBodyLength,\n })\n this.trigger('progress', this.request.upload, {\n loaded: totalRequestBodyLength,\n total: totalRequestBodyLength,\n })\n this.trigger('load', this.request.upload, {\n loaded: totalRequestBodyLength,\n total: totalRequestBodyLength,\n })\n\n this.trigger('loadend', this.request.upload, {\n loaded: totalRequestBodyLength,\n total: totalRequestBodyLength,\n })\n }\n\n this.logger.info(\n 'responding with a mocked response: %d %s',\n response.status,\n response.statusText\n )\n\n define(this.request, 'status', response.status)\n define(this.request, 'statusText', response.statusText)\n define(this.request, 'responseURL', this.url.href)\n\n this.request.getResponseHeader = new Proxy(this.request.getResponseHeader, {\n apply: (_, __, args: [name: string]) => {\n this.logger.info('getResponseHeader', args[0])\n\n if (this.request.readyState < this.request.HEADERS_RECEIVED) {\n this.logger.info('headers not received yet, returning null')\n\n // Headers not received yet, nothing to return.\n return null\n }\n\n const headerValue = response.headers.get(args[0])\n this.logger.info(\n 'resolved response header \"%s\" to',\n args[0],\n headerValue\n )\n\n return headerValue\n },\n })\n\n this.request.getAllResponseHeaders = new Proxy(\n this.request.getAllResponseHeaders,\n {\n apply: () => {\n this.logger.info('getAllResponseHeaders')\n\n if (this.request.readyState < this.request.HEADERS_RECEIVED) {\n this.logger.info('headers not received yet, returning empty string')\n\n // Headers not received yet, nothing to return.\n return ''\n }\n\n const headersList = Array.from(response.headers.entries())\n const allHeaders = headersList\n .map(([headerName, headerValue]) => {\n return `${headerName}: ${headerValue}`\n })\n .join('\\r\\n')\n\n this.logger.info('resolved all response headers to', allHeaders)\n\n return allHeaders\n },\n }\n )\n\n // Update the response getters to resolve against the mocked response.\n Object.defineProperties(this.request, {\n response: {\n enumerable: true,\n configurable: false,\n get: () => this.response,\n },\n responseText: {\n enumerable: true,\n configurable: false,\n get: () => this.responseText,\n },\n responseXML: {\n enumerable: true,\n configurable: false,\n get: () => this.responseXML,\n },\n })\n\n const totalResponseBodyLength = await getBodyByteLength(response.clone())\n\n this.logger.info('calculated response body length', totalResponseBodyLength)\n\n this.trigger('loadstart', this.request, {\n loaded: 0,\n total: totalResponseBodyLength,\n })\n\n this.setReadyState(this.request.HEADERS_RECEIVED)\n this.setReadyState(this.request.LOADING)\n\n const finalizeResponse = () => {\n this.logger.info('finalizing the mocked response...')\n\n this.setReadyState(this.request.DONE)\n\n this.trigger('load', this.request, {\n loaded: this.responseBuffer.byteLength,\n total: totalResponseBodyLength,\n })\n\n this.trigger('loadend', this.request, {\n loaded: this.responseBuffer.byteLength,\n total: totalResponseBodyLength,\n })\n }\n\n if (response.body) {\n this.logger.info('mocked response has body, streaming...')\n\n const reader = response.body.getReader()\n\n const readNextResponseBodyChunk = async () => {\n const { value, done } = await reader.read()\n\n if (done) {\n this.logger.info('response body stream done!')\n finalizeResponse()\n return\n }\n\n if (value) {\n this.logger.info('read response body chunk:', value)\n this.responseBuffer = concatArrayBuffer(this.responseBuffer, value)\n\n this.trigger('progress', this.request, {\n loaded: this.responseBuffer.byteLength,\n total: totalResponseBodyLength,\n })\n }\n\n readNextResponseBodyChunk()\n }\n\n readNextResponseBodyChunk()\n } else {\n finalizeResponse()\n }\n }\n\n private responseBufferToText(): string {\n return decodeBuffer(this.responseBuffer)\n }\n\n get response(): unknown {\n this.logger.info(\n 'getResponse (responseType: %s)',\n this.request.responseType\n )\n\n if (this.request.readyState !== this.request.DONE) {\n return null\n }\n\n switch (this.request.responseType) {\n case 'json': {\n const responseJson = parseJson(this.responseBufferToText())\n this.logger.info('resolved response JSON', responseJson)\n\n return responseJson\n }\n\n case 'arraybuffer': {\n const arrayBuffer = toArrayBuffer(this.responseBuffer)\n this.logger.info('resolved response ArrayBuffer', arrayBuffer)\n\n return arrayBuffer\n }\n\n case 'blob': {\n const mimeType =\n this.request.getResponseHeader('Content-Type') || 'text/plain'\n const responseBlob = new Blob([this.responseBufferToText()], {\n type: mimeType,\n })\n\n this.logger.info(\n 'resolved response Blob (mime type: %s)',\n responseBlob,\n mimeType\n )\n\n return responseBlob\n }\n\n default: {\n const responseText = this.responseBufferToText()\n this.logger.info(\n 'resolving \"%s\" response type as text',\n this.request.responseType,\n responseText\n )\n\n return responseText\n }\n }\n }\n\n get responseText(): string {\n /**\n * Throw when trying to read the response body as text when the\n * \"responseType\" doesn't expect text. This just respects the spec better.\n * @see https://xhr.spec.whatwg.org/#the-responsetext-attribute\n */\n invariant(\n this.request.responseType === '' || this.request.responseType === 'text',\n 'InvalidStateError: The object is in invalid state.'\n )\n\n if (\n this.request.readyState !== this.request.LOADING &&\n this.request.readyState !== this.request.DONE\n ) {\n return ''\n }\n\n const responseText = this.responseBufferToText()\n this.logger.info('getResponseText: \"%s\"', responseText)\n\n return responseText\n }\n\n get responseXML(): Document | null {\n invariant(\n this.request.responseType === '' ||\n this.request.responseType === 'document',\n 'InvalidStateError: The object is in invalid state.'\n )\n\n if (this.request.readyState !== this.request.DONE) {\n return null\n }\n\n const contentType = this.request.getResponseHeader('Content-Type') || ''\n\n if (typeof DOMParser === 'undefined') {\n console.warn(\n 'Cannot retrieve XMLHttpRequest response body as XML: DOMParser is not defined. You are likely using an environment that is not browser or does not polyfill browser globals correctly.'\n )\n return null\n }\n\n if (isDomParserSupportedType(contentType)) {\n return new DOMParser().parseFromString(\n this.responseBufferToText(),\n contentType\n )\n }\n\n return null\n }\n\n public errorWith(error?: Error): void {\n /**\n * @note Mark this request as handled even if it received a mock error.\n * This prevents the controller from trying to perform this request as-is.\n */\n this[kIsRequestHandled] = true\n this.logger.info('responding with an error')\n\n this.setReadyState(this.request.DONE)\n this.trigger('error', this.request)\n this.trigger('loadend', this.request)\n }\n\n /**\n * Transitions this request's `readyState` to the given one.\n */\n private setReadyState(nextReadyState: number): void {\n this.logger.info(\n 'setReadyState: %d -> %d',\n this.request.readyState,\n nextReadyState\n )\n\n if (this.request.readyState === nextReadyState) {\n this.logger.info('ready state identical, skipping transition...')\n return\n }\n\n define(this.request, 'readyState', nextReadyState)\n\n this.logger.info('set readyState to: %d', nextReadyState)\n\n if (nextReadyState !== this.request.UNSENT) {\n this.logger.info('triggering \"readystatechange\" event...')\n\n this.trigger('readystatechange', this.request)\n }\n }\n\n /**\n * Triggers given event on the `XMLHttpRequest` instance.\n */\n private trigger<\n EventName extends keyof (XMLHttpRequestEventTargetEventMap & {\n readystatechange: ProgressEvent\n }),\n >(\n eventName: EventName,\n target: XMLHttpRequest | XMLHttpRequestUpload,\n options?: ProgressEventInit\n ): void {\n const callback = (target as XMLHttpRequest)[`on${eventName}`]\n const event = createEvent(target, eventName, options)\n\n this.logger.info('trigger \"%s\"', eventName, options || '')\n\n // Invoke direct callbacks.\n if (typeof callback === 'function') {\n this.logger.info('found a direct \"%s\" callback, calling...', eventName)\n callback.call(target as XMLHttpRequest, event)\n }\n\n // Invoke event listeners.\n const events =\n target instanceof XMLHttpRequestUpload ? this.uploadEvents : this.events\n\n for (const [registeredEventName, listeners] of events) {\n if (registeredEventName === eventName) {\n this.logger.info(\n 'found %d listener(s) for \"%s\" event, calling...',\n listeners.length,\n eventName\n )\n\n listeners.forEach((listener) => listener.call(target, event))\n }\n }\n }\n\n /**\n * Converts this `XMLHttpRequest` instance into a Fetch API `Request` instance.\n */\n private toFetchApiRequest(\n body: XMLHttpRequestBodyInit | Document | null | undefined\n ): Request {\n this.logger.info('converting request to a Fetch API Request...')\n\n // If the `Document` is used as the body of this XMLHttpRequest,\n // set its inner text as the Fetch API Request body.\n const resolvedBody =\n body instanceof Document ? body.documentElement.innerText : body\n\n const fetchRequest = new FetchRequest(this.url.href, {\n method: this.method,\n headers: this.requestHeaders,\n /**\n * @see https://xhr.spec.whatwg.org/#cross-origin-credentials\n */\n credentials: this.request.withCredentials ? 'include' : 'same-origin',\n body: ['GET', 'HEAD'].includes(this.method.toUpperCase())\n ? null\n : resolvedBody,\n })\n\n const proxyHeaders = createProxy(fetchRequest.headers, {\n methodCall: ([methodName, args], invoke) => {\n // Forward the latest state of the internal request headers\n // because the interceptor might have modified them\n // without responding to the request.\n switch (methodName) {\n case 'append':\n case 'set': {\n const [headerName, headerValue] = args as [string, string]\n this.request.setRequestHeader(headerName, headerValue)\n break\n }\n\n case 'delete': {\n const [headerName] = args as [string]\n console.warn(\n `XMLHttpRequest: Cannot remove a \"${headerName}\" header from the Fetch API representation of the \"${fetchRequest.method} ${fetchRequest.url}\" request. XMLHttpRequest headers cannot be removed.`\n )\n break\n }\n }\n\n return invoke()\n },\n })\n define(fetchRequest, 'headers', proxyHeaders)\n setRawRequest(fetchRequest, this.request)\n\n this.logger.info('converted request to a Fetch API Request!', fetchRequest)\n\n return fetchRequest\n }\n}\n\nfunction toAbsoluteUrl(url: string | URL): URL {\n /**\n * @note XMLHttpRequest interceptor may run in environments\n * that implement XMLHttpRequest but don't implement \"location\"\n * (for example, React Native). If that's the case, return the\n * input URL as-is (nothing to be relative to).\n * @see https://github.com/mswjs/msw/issues/1777\n */\n if (typeof location === 'undefined') {\n return new URL(url)\n }\n\n return new URL(url.toString(), location.href)\n}\n\nfunction define(\n target: object,\n property: string | symbol,\n value: unknown\n): void {\n Reflect.defineProperty(target, property, {\n // Ensure writable properties to allow redefining readonly properties.\n writable: true,\n enumerable: true,\n value,\n })\n}\n","import type { Logger } from '@open-draft/logger'\nimport { XMLHttpRequestEmitter } from '.'\nimport { RequestController } from '../../RequestController'\nimport { XMLHttpRequestController } from './XMLHttpRequestController'\nimport { handleRequest } from '../../utils/handleRequest'\nimport { isResponseError } from '../../utils/responseUtils'\n\nexport interface XMLHttpRequestProxyOptions {\n emitter: XMLHttpRequestEmitter\n logger: Logger\n}\n\n/**\n * Create a proxied `XMLHttpRequest` class.\n * The proxied class establishes spies on certain methods,\n * allowing us to intercept requests and respond to them.\n */\nexport function createXMLHttpRequestProxy({\n emitter,\n logger,\n}: XMLHttpRequestProxyOptions) {\n const XMLHttpRequestProxy = new Proxy(globalThis.XMLHttpRequest, {\n construct(target, args, newTarget) {\n logger.info('constructed new XMLHttpRequest')\n\n const originalRequest = Reflect.construct(\n target,\n args,\n newTarget\n ) as XMLHttpRequest\n\n /**\n * @note Forward prototype descriptors onto the proxied object.\n * XMLHttpRequest is implemented in JSDOM in a way that assigns\n * a bunch of descriptors, like \"set responseType()\" on the prototype.\n * With this propagation, we make sure that those descriptors trigger\n * when the user operates with the proxied request instance.\n */\n const prototypeDescriptors = Object.getOwnPropertyDescriptors(\n target.prototype\n )\n for (const propertyName in prototypeDescriptors) {\n Reflect.defineProperty(\n originalRequest,\n propertyName,\n prototypeDescriptors[propertyName]\n )\n }\n\n const xhrRequestController = new XMLHttpRequestController(\n originalRequest,\n logger\n )\n\n xhrRequestController.onRequest = async function ({ request, requestId }) {\n const controller = new RequestController(request, {\n passthrough: () => {\n this.logger.info(\n 'no mocked response received, performing request as-is...'\n )\n },\n respondWith: async (response) => {\n if (isResponseError(response)) {\n this.errorWith(new TypeError('Network error'))\n return\n }\n\n await this.respondWith(response)\n },\n errorWith: (reason) => {\n this.logger.info('request errored!', { error: reason })\n\n if (reason instanceof Error) {\n this.errorWith(reason)\n }\n },\n })\n\n this.logger.info('awaiting mocked response...')\n\n this.logger.info(\n 'emitting the \"request\" event for %s listener(s)...',\n emitter.listenerCount('request')\n )\n\n await handleRequest({\n request,\n requestId,\n controller,\n emitter,\n })\n }\n\n xhrRequestController.onResponse = async function ({\n response,\n isMockedResponse,\n request,\n requestId,\n }) {\n this.logger.info(\n 'emitting the \"response\" event for %s listener(s)...',\n emitter.listenerCount('response')\n )\n\n emitter.emit('response', {\n response,\n isMockedResponse,\n request,\n requestId,\n })\n }\n\n // Return the proxied request from the controller\n // so that the controller can react to the consumer's interactions\n // with this request (opening/sending/etc).\n return xhrRequestController.request\n },\n })\n\n return XMLHttpRequestProxy\n}\n","import { Emitter } from 'strict-event-emitter'\nimport { HttpRequestEventMap } from '../../glossary'\nimport { Interceptor } from '../../Interceptor'\nimport { createXMLHttpRequestProxy } from './XMLHttpRequestProxy'\nimport { hasConfigurableGlobal } from '../../utils/hasConfigurableGlobal'\nimport { patchesRegistry } from '../../utils/patchesRegistry'\n\nexport type XMLHttpRequestEmitter = Emitter\n\nexport class XMLHttpRequestInterceptor extends Interceptor {\n static symbol = Symbol.for('xhr-interceptor')\n\n constructor() {\n super(XMLHttpRequestInterceptor.symbol)\n }\n\n protected checkEnvironment() {\n return hasConfigurableGlobal('XMLHttpRequest')\n }\n\n protected setup() {\n const logger = this.logger.extend('setup')\n\n logger.info('patching global XMLHttpRequest...')\n\n this.subscriptions.push(\n patchesRegistry.applyPatch(globalThis, 'XMLHttpRequest', () => {\n return createXMLHttpRequestProxy({\n emitter: this.emitter,\n logger: this.logger,\n })\n })\n )\n\n logger.info(\n 'global XMLHttpRequest patched!',\n globalThis.XMLHttpRequest.name\n )\n }\n}\n"],"mappings":";;;;;;;;;;;;AAGA,SAAgB,kBACd,MACA,OACY;CACZ,MAAM,SAAS,IAAI,WAAW,KAAK,aAAa,MAAM,WAAW;AACjE,QAAO,IAAI,MAAM,EAAE;AACnB,QAAO,IAAI,OAAO,KAAK,WAAW;AAClC,QAAO;;;;;ACVT,IAAa,gBAAb,MAA4C;CAwB1C,YACE,MACA,SACA;cA1Bc;yBACW;mBACN;wBACK;cAEJ;oBACkB;uBAEG;oBACf;mBAEA;kBACD;oBACE;0BACM;iBACT;0BACS;gBACX;eACD;sBAEC;qBACD;AAMrB,OAAK,OAAO;AACZ,OAAK,SAAS,SAAS,UAAU;AACjC,OAAK,gBAAgB,SAAS,iBAAiB;AAC/C,OAAK,YAAY,KAAK,KAAK;;CAG7B,AAAO,eAA8B;AACnC,SAAO,EAAE;;CAGX,AAAO,UAAU,MAAc,SAAmB,YAAsB;AACtE,OAAK,OAAO;AACZ,OAAK,UAAU,CAAC,CAAC;AACjB,OAAK,aAAa,CAAC,CAAC;;CAGtB,AAAO,iBAAiB;AACtB,OAAK,mBAAmB;;CAG1B,AAAO,kBAAkB;CACzB,AAAO,2BAA2B;;;;;AC/CpC,IA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B;IAC/B,SAAS,KAAK;IACd,QAAQ,KAAK;IACd,CAAC;IACF,CACH;AAED,SAAO,KACL,kCACA,WAAW,eAAe,KAC3B"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/bufferUtils-BiiO6HZv.mjs b/node_modules/@mswjs/interceptors/lib/browser/bufferUtils-BiiO6HZv.mjs new file mode 100644 index 0000000000000000000000000000000000000000..19ecb4d1acc2583420b0c3b2627e81366349a725 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/bufferUtils-BiiO6HZv.mjs @@ -0,0 +1,20 @@ +//#region src/utils/bufferUtils.ts +const encoder = new TextEncoder(); +function encodeBuffer(text) { + return encoder.encode(text); +} +function decodeBuffer(buffer, encoding) { + return new TextDecoder(encoding).decode(buffer); +} +/** +* Create an `ArrayBuffer` from the given `Uint8Array`. +* Takes the byte offset into account to produce the right buffer +* in the case when the buffer is bigger than the data view. +*/ +function toArrayBuffer(array) { + return array.buffer.slice(array.byteOffset, array.byteOffset + array.byteLength); +} + +//#endregion +export { encodeBuffer as n, toArrayBuffer as r, decodeBuffer as t }; +//# sourceMappingURL=bufferUtils-BiiO6HZv.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/bufferUtils-BiiO6HZv.mjs.map b/node_modules/@mswjs/interceptors/lib/browser/bufferUtils-BiiO6HZv.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..0d0ba0e36bea504dae4354deb93dc58a254e104a --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/bufferUtils-BiiO6HZv.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"bufferUtils-BiiO6HZv.mjs","names":[],"sources":["../../src/utils/bufferUtils.ts"],"sourcesContent":["const encoder = new TextEncoder()\n\nexport function encodeBuffer(text: string): Uint8Array {\n return encoder.encode(text)\n}\n\nexport function decodeBuffer(buffer: ArrayBuffer, encoding?: string): string {\n const decoder = new TextDecoder(encoding)\n return decoder.decode(buffer)\n}\n\n/**\n * Create an `ArrayBuffer` from the given `Uint8Array`.\n * Takes the byte offset into account to produce the right buffer\n * in the case when the buffer is bigger than the data view.\n */\nexport function toArrayBuffer(array: Uint8Array): ArrayBuffer {\n return array.buffer.slice(\n array.byteOffset,\n array.byteOffset + array.byteLength\n )\n}\n"],"mappings":";AAAA,MAAM,UAAU,IAAI,aAAa;AAEjC,SAAgB,aAAa,MAA0B;AACrD,QAAO,QAAQ,OAAO,KAAK;;AAG7B,SAAgB,aAAa,QAAqB,UAA2B;AAE3E,QADgB,IAAI,YAAY,SAAS,CAC1B,OAAO,OAAO;;;;;;;AAQ/B,SAAgB,cAAc,OAAgC;AAC5D,QAAO,MAAM,OAAO,MAClB,MAAM,YACN,MAAM,aAAa,MAAM,WAC1B"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/bufferUtils-Uc0eRItL.cjs b/node_modules/@mswjs/interceptors/lib/browser/bufferUtils-Uc0eRItL.cjs new file mode 100644 index 0000000000000000000000000000000000000000..85a4f08b9c8a79baa1569a23751f197256ce0f6f --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/bufferUtils-Uc0eRItL.cjs @@ -0,0 +1,38 @@ + +//#region src/utils/bufferUtils.ts +const encoder = new TextEncoder(); +function encodeBuffer(text) { + return encoder.encode(text); +} +function decodeBuffer(buffer, encoding) { + return new TextDecoder(encoding).decode(buffer); +} +/** +* Create an `ArrayBuffer` from the given `Uint8Array`. +* Takes the byte offset into account to produce the right buffer +* in the case when the buffer is bigger than the data view. +*/ +function toArrayBuffer(array) { + return array.buffer.slice(array.byteOffset, array.byteOffset + array.byteLength); +} + +//#endregion +Object.defineProperty(exports, 'decodeBuffer', { + enumerable: true, + get: function () { + return decodeBuffer; + } +}); +Object.defineProperty(exports, 'encodeBuffer', { + enumerable: true, + get: function () { + return encodeBuffer; + } +}); +Object.defineProperty(exports, 'toArrayBuffer', { + enumerable: true, + get: function () { + return toArrayBuffer; + } +}); +//# sourceMappingURL=bufferUtils-Uc0eRItL.cjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/bufferUtils-Uc0eRItL.cjs.map b/node_modules/@mswjs/interceptors/lib/browser/bufferUtils-Uc0eRItL.cjs.map new file mode 100644 index 0000000000000000000000000000000000000000..4aa78537e4485a867a16a0fa5bf1bb87e5e1d480 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/bufferUtils-Uc0eRItL.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"bufferUtils-Uc0eRItL.cjs","names":[],"sources":["../../src/utils/bufferUtils.ts"],"sourcesContent":["const encoder = new TextEncoder()\n\nexport function encodeBuffer(text: string): Uint8Array {\n return encoder.encode(text)\n}\n\nexport function decodeBuffer(buffer: ArrayBuffer, encoding?: string): string {\n const decoder = new TextDecoder(encoding)\n return decoder.decode(buffer)\n}\n\n/**\n * Create an `ArrayBuffer` from the given `Uint8Array`.\n * Takes the byte offset into account to produce the right buffer\n * in the case when the buffer is bigger than the data view.\n */\nexport function toArrayBuffer(array: Uint8Array): ArrayBuffer {\n return array.buffer.slice(\n array.byteOffset,\n array.byteOffset + array.byteLength\n )\n}\n"],"mappings":";;AAAA,MAAM,UAAU,IAAI,aAAa;AAEjC,SAAgB,aAAa,MAA0B;AACrD,QAAO,QAAQ,OAAO,KAAK;;AAG7B,SAAgB,aAAa,QAAqB,UAA2B;AAE3E,QADgB,IAAI,YAAY,SAAS,CAC1B,OAAO,OAAO;;;;;;;AAQ/B,SAAgB,cAAc,OAAgC;AAC5D,QAAO,MAAM,OAAO,MAClB,MAAM,YACN,MAAM,aAAa,MAAM,WAC1B"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/createRequestId-DOf8Ktjs.cjs b/node_modules/@mswjs/interceptors/lib/browser/createRequestId-DOf8Ktjs.cjs new file mode 100644 index 0000000000000000000000000000000000000000..8e5c3d499881fdde86af7049c46147a4d2234bbc --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/createRequestId-DOf8Ktjs.cjs @@ -0,0 +1,205 @@ +let _open_draft_logger = require("@open-draft/logger"); +let strict_event_emitter = require("strict-event-emitter"); + +//#region src/Interceptor.ts +/** +* Request header name to detect when a single request +* is being handled by nested interceptors (XHR -> ClientRequest). +* Obscure by design to prevent collisions with user-defined headers. +* Ideally, come up with the Interceptor-level mechanism for this. +* @see https://github.com/mswjs/interceptors/issues/378 +*/ +const INTERNAL_REQUEST_ID_HEADER_NAME = "x-interceptors-internal-request-id"; +function getGlobalSymbol(symbol) { + return globalThis[symbol] || void 0; +} +function setGlobalSymbol(symbol, value) { + globalThis[symbol] = value; +} +function deleteGlobalSymbol(symbol) { + delete globalThis[symbol]; +} +let InterceptorReadyState = /* @__PURE__ */ function(InterceptorReadyState$1) { + InterceptorReadyState$1["INACTIVE"] = "INACTIVE"; + InterceptorReadyState$1["APPLYING"] = "APPLYING"; + InterceptorReadyState$1["APPLIED"] = "APPLIED"; + InterceptorReadyState$1["DISPOSING"] = "DISPOSING"; + InterceptorReadyState$1["DISPOSED"] = "DISPOSED"; + return InterceptorReadyState$1; +}({}); +var Interceptor = class { + constructor(symbol) { + this.symbol = symbol; + this.readyState = InterceptorReadyState.INACTIVE; + this.emitter = new strict_event_emitter.Emitter(); + this.subscriptions = []; + this.logger = new _open_draft_logger.Logger(symbol.description); + this.emitter.setMaxListeners(0); + this.logger.info("constructing the interceptor..."); + } + /** + * Determine if this interceptor can be applied + * in the current environment. + */ + checkEnvironment() { + return true; + } + /** + * Apply this interceptor to the current process. + * Returns an already running interceptor instance if it's present. + */ + apply() { + const logger = this.logger.extend("apply"); + logger.info("applying the interceptor..."); + if (this.readyState === InterceptorReadyState.APPLIED) { + logger.info("intercepted already applied!"); + return; + } + if (!this.checkEnvironment()) { + logger.info("the interceptor cannot be applied in this environment!"); + return; + } + this.readyState = InterceptorReadyState.APPLYING; + const runningInstance = this.getInstance(); + if (runningInstance) { + logger.info("found a running instance, reusing..."); + this.on = (event, listener) => { + logger.info("proxying the \"%s\" listener", event); + runningInstance.emitter.addListener(event, listener); + this.subscriptions.push(() => { + runningInstance.emitter.removeListener(event, listener); + logger.info("removed proxied \"%s\" listener!", event); + }); + return this; + }; + this.readyState = InterceptorReadyState.APPLIED; + return; + } + logger.info("no running instance found, setting up a new instance..."); + this.setup(); + this.setInstance(); + this.readyState = InterceptorReadyState.APPLIED; + } + /** + * Setup the module augments and stubs necessary for this interceptor. + * This method is not run if there's a running interceptor instance + * to prevent instantiating an interceptor multiple times. + */ + setup() {} + /** + * Listen to the interceptor's public events. + */ + on(event, listener) { + const logger = this.logger.extend("on"); + if (this.readyState === InterceptorReadyState.DISPOSING || this.readyState === InterceptorReadyState.DISPOSED) { + logger.info("cannot listen to events, already disposed!"); + return this; + } + logger.info("adding \"%s\" event listener:", event, listener); + this.emitter.on(event, listener); + return this; + } + once(event, listener) { + this.emitter.once(event, listener); + return this; + } + off(event, listener) { + this.emitter.off(event, listener); + return this; + } + removeAllListeners(event) { + this.emitter.removeAllListeners(event); + return this; + } + /** + * Disposes of any side-effects this interceptor has introduced. + */ + dispose() { + const logger = this.logger.extend("dispose"); + if (this.readyState === InterceptorReadyState.DISPOSED) { + logger.info("cannot dispose, already disposed!"); + return; + } + logger.info("disposing the interceptor..."); + this.readyState = InterceptorReadyState.DISPOSING; + if (!this.getInstance()) { + logger.info("no interceptors running, skipping dispose..."); + return; + } + this.clearInstance(); + logger.info("global symbol deleted:", getGlobalSymbol(this.symbol)); + if (this.subscriptions.length > 0) { + logger.info("disposing of %d subscriptions...", this.subscriptions.length); + for (const dispose of this.subscriptions) dispose(); + this.subscriptions = []; + logger.info("disposed of all subscriptions!", this.subscriptions.length); + } + this.emitter.removeAllListeners(); + logger.info("destroyed the listener!"); + this.readyState = InterceptorReadyState.DISPOSED; + } + getInstance() { + const instance = getGlobalSymbol(this.symbol); + this.logger.info("retrieved global instance:", instance?.constructor?.name); + return instance; + } + setInstance() { + setGlobalSymbol(this.symbol, this); + this.logger.info("set global instance!", this.symbol.description); + } + clearInstance() { + deleteGlobalSymbol(this.symbol); + this.logger.info("cleared global instance!", this.symbol.description); + } +}; + +//#endregion +//#region src/createRequestId.ts +/** +* Generate a random ID string to represent a request. +* @example +* createRequestId() +* // "f774b6c9c600f" +*/ +function createRequestId() { + return Math.random().toString(16).slice(2); +} + +//#endregion +Object.defineProperty(exports, 'INTERNAL_REQUEST_ID_HEADER_NAME', { + enumerable: true, + get: function () { + return INTERNAL_REQUEST_ID_HEADER_NAME; + } +}); +Object.defineProperty(exports, 'Interceptor', { + enumerable: true, + get: function () { + return Interceptor; + } +}); +Object.defineProperty(exports, 'InterceptorReadyState', { + enumerable: true, + get: function () { + return InterceptorReadyState; + } +}); +Object.defineProperty(exports, 'createRequestId', { + enumerable: true, + get: function () { + return createRequestId; + } +}); +Object.defineProperty(exports, 'deleteGlobalSymbol', { + enumerable: true, + get: function () { + return deleteGlobalSymbol; + } +}); +Object.defineProperty(exports, 'getGlobalSymbol', { + enumerable: true, + get: function () { + return getGlobalSymbol; + } +}); +//# sourceMappingURL=createRequestId-DOf8Ktjs.cjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/createRequestId-DOf8Ktjs.cjs.map b/node_modules/@mswjs/interceptors/lib/browser/createRequestId-DOf8Ktjs.cjs.map new file mode 100644 index 0000000000000000000000000000000000000000..8c9a215369f84dfd7272fc693d05d20784fc4c12 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/createRequestId-DOf8Ktjs.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"createRequestId-DOf8Ktjs.cjs","names":["symbol: symbol","Emitter","Logger"],"sources":["../../src/Interceptor.ts","../../src/createRequestId.ts"],"sourcesContent":["import { Logger } from '@open-draft/logger'\nimport { Emitter, Listener } from 'strict-event-emitter'\n\nexport type InterceptorEventMap = Record\nexport type InterceptorSubscription = () => void\n\n/**\n * Request header name to detect when a single request\n * is being handled by nested interceptors (XHR -> ClientRequest).\n * Obscure by design to prevent collisions with user-defined headers.\n * Ideally, come up with the Interceptor-level mechanism for this.\n * @see https://github.com/mswjs/interceptors/issues/378\n */\nexport const INTERNAL_REQUEST_ID_HEADER_NAME =\n 'x-interceptors-internal-request-id'\n\nexport function getGlobalSymbol(symbol: Symbol): V | undefined {\n return (\n // @ts-ignore https://github.com/Microsoft/TypeScript/issues/24587\n globalThis[symbol] || undefined\n )\n}\n\nfunction setGlobalSymbol(symbol: Symbol, value: any): void {\n // @ts-ignore\n globalThis[symbol] = value\n}\n\nexport function deleteGlobalSymbol(symbol: Symbol): void {\n // @ts-ignore\n delete globalThis[symbol]\n}\n\nexport enum InterceptorReadyState {\n INACTIVE = 'INACTIVE',\n APPLYING = 'APPLYING',\n APPLIED = 'APPLIED',\n DISPOSING = 'DISPOSING',\n DISPOSED = 'DISPOSED',\n}\n\nexport type ExtractEventNames> =\n Events extends Record ? EventName : never\n\nexport class Interceptor {\n protected emitter: Emitter\n protected subscriptions: Array\n protected logger: Logger\n\n public readyState: InterceptorReadyState\n\n constructor(private readonly symbol: symbol) {\n this.readyState = InterceptorReadyState.INACTIVE\n\n this.emitter = new Emitter()\n this.subscriptions = []\n this.logger = new Logger(symbol.description!)\n\n // Do not limit the maximum number of listeners\n // so not to limit the maximum amount of parallel events emitted.\n this.emitter.setMaxListeners(0)\n\n this.logger.info('constructing the interceptor...')\n }\n\n /**\n * Determine if this interceptor can be applied\n * in the current environment.\n */\n protected checkEnvironment(): boolean {\n return true\n }\n\n /**\n * Apply this interceptor to the current process.\n * Returns an already running interceptor instance if it's present.\n */\n public apply(): void {\n const logger = this.logger.extend('apply')\n logger.info('applying the interceptor...')\n\n if (this.readyState === InterceptorReadyState.APPLIED) {\n logger.info('intercepted already applied!')\n return\n }\n\n const shouldApply = this.checkEnvironment()\n\n if (!shouldApply) {\n logger.info('the interceptor cannot be applied in this environment!')\n return\n }\n\n this.readyState = InterceptorReadyState.APPLYING\n\n // Whenever applying a new interceptor, check if it hasn't been applied already.\n // This enables to apply the same interceptor multiple times, for example from a different\n // interceptor, only proxying events but keeping the stubs in a single place.\n const runningInstance = this.getInstance()\n\n if (runningInstance) {\n logger.info('found a running instance, reusing...')\n\n // Proxy any listeners you set on this instance to the running instance.\n this.on = (event, listener) => {\n logger.info('proxying the \"%s\" listener', event)\n\n // Add listeners to the running instance so they appear\n // at the top of the event listeners list and are executed first.\n runningInstance.emitter.addListener(event, listener)\n\n // Ensure that once this interceptor instance is disposed,\n // it removes all listeners it has appended to the running interceptor instance.\n this.subscriptions.push(() => {\n runningInstance.emitter.removeListener(event, listener)\n logger.info('removed proxied \"%s\" listener!', event)\n })\n\n return this\n }\n\n this.readyState = InterceptorReadyState.APPLIED\n\n return\n }\n\n logger.info('no running instance found, setting up a new instance...')\n\n // Setup the interceptor.\n this.setup()\n\n // Store the newly applied interceptor instance globally.\n this.setInstance()\n\n this.readyState = InterceptorReadyState.APPLIED\n }\n\n /**\n * Setup the module augments and stubs necessary for this interceptor.\n * This method is not run if there's a running interceptor instance\n * to prevent instantiating an interceptor multiple times.\n */\n protected setup(): void {}\n\n /**\n * Listen to the interceptor's public events.\n */\n public on>(\n event: EventName,\n listener: Listener\n ): this {\n const logger = this.logger.extend('on')\n\n if (\n this.readyState === InterceptorReadyState.DISPOSING ||\n this.readyState === InterceptorReadyState.DISPOSED\n ) {\n logger.info('cannot listen to events, already disposed!')\n return this\n }\n\n logger.info('adding \"%s\" event listener:', event, listener)\n\n this.emitter.on(event, listener)\n return this\n }\n\n public once>(\n event: EventName,\n listener: Listener\n ): this {\n this.emitter.once(event, listener)\n return this\n }\n\n public off>(\n event: EventName,\n listener: Listener\n ): this {\n this.emitter.off(event, listener)\n return this\n }\n\n public removeAllListeners>(\n event?: EventName\n ): this {\n this.emitter.removeAllListeners(event)\n return this\n }\n\n /**\n * Disposes of any side-effects this interceptor has introduced.\n */\n public dispose(): void {\n const logger = this.logger.extend('dispose')\n\n if (this.readyState === InterceptorReadyState.DISPOSED) {\n logger.info('cannot dispose, already disposed!')\n return\n }\n\n logger.info('disposing the interceptor...')\n this.readyState = InterceptorReadyState.DISPOSING\n\n if (!this.getInstance()) {\n logger.info('no interceptors running, skipping dispose...')\n return\n }\n\n // Delete the global symbol as soon as possible,\n // indicating that the interceptor is no longer running.\n this.clearInstance()\n\n logger.info('global symbol deleted:', getGlobalSymbol(this.symbol))\n\n if (this.subscriptions.length > 0) {\n logger.info('disposing of %d subscriptions...', this.subscriptions.length)\n\n for (const dispose of this.subscriptions) {\n dispose()\n }\n\n this.subscriptions = []\n\n logger.info('disposed of all subscriptions!', this.subscriptions.length)\n }\n\n this.emitter.removeAllListeners()\n logger.info('destroyed the listener!')\n\n this.readyState = InterceptorReadyState.DISPOSED\n }\n\n private getInstance(): this | undefined {\n const instance = getGlobalSymbol(this.symbol)\n this.logger.info('retrieved global instance:', instance?.constructor?.name)\n return instance\n }\n\n private setInstance(): void {\n setGlobalSymbol(this.symbol, this)\n this.logger.info('set global instance!', this.symbol.description)\n }\n\n private clearInstance(): void {\n deleteGlobalSymbol(this.symbol)\n this.logger.info('cleared global instance!', this.symbol.description)\n }\n}\n","/**\n * Generate a random ID string to represent a request.\n * @example\n * createRequestId()\n * // \"f774b6c9c600f\"\n */\nexport function createRequestId(): string {\n return Math.random().toString(16).slice(2)\n}\n"],"mappings":";;;;;;;;;;;AAaA,MAAa,kCACX;AAEF,SAAgB,gBAAmB,QAA+B;AAChE,QAEE,WAAW,WAAW;;AAI1B,SAAS,gBAAgB,QAAgB,OAAkB;AAEzD,YAAW,UAAU;;AAGvB,SAAgB,mBAAmB,QAAsB;AAEvD,QAAO,WAAW;;AAGpB,IAAY,0EAAL;AACL;AACA;AACA;AACA;AACA;;;AAMF,IAAa,cAAb,MAA6D;CAO3D,YAAY,AAAiBA,QAAgB;EAAhB;AAC3B,OAAK,aAAa,sBAAsB;AAExC,OAAK,UAAU,IAAIC,8BAAS;AAC5B,OAAK,gBAAgB,EAAE;AACvB,OAAK,SAAS,IAAIC,0BAAO,OAAO,YAAa;AAI7C,OAAK,QA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C,SAAO;;CAGT,AAAO,mBACL,OACM;AACN,OAAK,QAAQ,mBAAmB,MAAM;AACtC,SAAO;;;;;CAMT,AAAO,UAAgB;EACrB,MAAM,SAAS,KAAK,OAAO,OAAO,UAAU;AAE5C,MAAI,KAAK,eAAe,sBAAsB,UAAU;AACtD,UAAO,KAAK,oCAAoC;AAChD;;AAGF,SAAO,KAAK,+BAA+B;AAC3C,OAAK,aAAa,sBAAsB;AAExC,MAAI,CAAC,KAAK,aAAa,EAAE;AACvB,UAAO,KAAK,+CAA+C;AAC3D;;AAKF,OAAK,eAAe;AAEpB,SAAO,KAAK,0BAA0B,gBAAgB,KAAK,OAAO,CAAC;AAEnE,MAAI,KAAK,cAAc,SAAS,GAAG;AACjC,UAAO,KAAK,oCAAoC,KAAK,cAAc,OAAO;AAE1E,QAAK,MAAM,WAAW,KAAK,cACzB,UAAS;AAGX,QAAK,gBAAgB,EAAE;AAEvB,UAAO,KAAK,kCAAkC,KAAK,cAAc,OAAO;;AAG1E,OAAK,QAAQ,oBAAoB;AACjC,SAAO,KAAK,0BAA0B;AAEtC,OAAK,aAAa,sBAAsB;;CAG1C,AAAQ,cAAgC;EACtC,MAAM,WAAW,gBAAsB,KAAK,OAAO;AACnD,OAAK,OAAO,KAAK,8BAA8B,UAAU,aAAa,KAAK;AAC3E,SAAO;;CAGT,AAAQ,cAAoB;AAC1B,kBAAgB,KAAK,QAAQ,KAAK;AAClC,OAAK,OAAO,KAAK,wBAAwB,KAAK,OAAO,YAAY;;CAGnE,AAAQ,gBAAsB;AAC5B,qBAAmB,KAAK,OAAO;AAC/B,OAAK,OAAO,KAAK,4BAA4B,KAAK,OAAO,YAAY;;;;;;;;;;;;AChPzE,SAAgB,kBAA0B;AACxC,QAAO,KAAK,QAAQ,CAAC,SAAS,GAAG,CAAC,MAAM,EAAE"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/createRequestId-DYCsFHOi.mjs b/node_modules/@mswjs/interceptors/lib/browser/createRequestId-DYCsFHOi.mjs new file mode 100644 index 0000000000000000000000000000000000000000..47e8e358102ab48764cd80d0c6a4bc085c26dcb3 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/createRequestId-DYCsFHOi.mjs @@ -0,0 +1,170 @@ +import { Logger } from "@open-draft/logger"; +import { Emitter } from "strict-event-emitter"; + +//#region src/Interceptor.ts +/** +* Request header name to detect when a single request +* is being handled by nested interceptors (XHR -> ClientRequest). +* Obscure by design to prevent collisions with user-defined headers. +* Ideally, come up with the Interceptor-level mechanism for this. +* @see https://github.com/mswjs/interceptors/issues/378 +*/ +const INTERNAL_REQUEST_ID_HEADER_NAME = "x-interceptors-internal-request-id"; +function getGlobalSymbol(symbol) { + return globalThis[symbol] || void 0; +} +function setGlobalSymbol(symbol, value) { + globalThis[symbol] = value; +} +function deleteGlobalSymbol(symbol) { + delete globalThis[symbol]; +} +let InterceptorReadyState = /* @__PURE__ */ function(InterceptorReadyState$1) { + InterceptorReadyState$1["INACTIVE"] = "INACTIVE"; + InterceptorReadyState$1["APPLYING"] = "APPLYING"; + InterceptorReadyState$1["APPLIED"] = "APPLIED"; + InterceptorReadyState$1["DISPOSING"] = "DISPOSING"; + InterceptorReadyState$1["DISPOSED"] = "DISPOSED"; + return InterceptorReadyState$1; +}({}); +var Interceptor = class { + constructor(symbol) { + this.symbol = symbol; + this.readyState = InterceptorReadyState.INACTIVE; + this.emitter = new Emitter(); + this.subscriptions = []; + this.logger = new Logger(symbol.description); + this.emitter.setMaxListeners(0); + this.logger.info("constructing the interceptor..."); + } + /** + * Determine if this interceptor can be applied + * in the current environment. + */ + checkEnvironment() { + return true; + } + /** + * Apply this interceptor to the current process. + * Returns an already running interceptor instance if it's present. + */ + apply() { + const logger = this.logger.extend("apply"); + logger.info("applying the interceptor..."); + if (this.readyState === InterceptorReadyState.APPLIED) { + logger.info("intercepted already applied!"); + return; + } + if (!this.checkEnvironment()) { + logger.info("the interceptor cannot be applied in this environment!"); + return; + } + this.readyState = InterceptorReadyState.APPLYING; + const runningInstance = this.getInstance(); + if (runningInstance) { + logger.info("found a running instance, reusing..."); + this.on = (event, listener) => { + logger.info("proxying the \"%s\" listener", event); + runningInstance.emitter.addListener(event, listener); + this.subscriptions.push(() => { + runningInstance.emitter.removeListener(event, listener); + logger.info("removed proxied \"%s\" listener!", event); + }); + return this; + }; + this.readyState = InterceptorReadyState.APPLIED; + return; + } + logger.info("no running instance found, setting up a new instance..."); + this.setup(); + this.setInstance(); + this.readyState = InterceptorReadyState.APPLIED; + } + /** + * Setup the module augments and stubs necessary for this interceptor. + * This method is not run if there's a running interceptor instance + * to prevent instantiating an interceptor multiple times. + */ + setup() {} + /** + * Listen to the interceptor's public events. + */ + on(event, listener) { + const logger = this.logger.extend("on"); + if (this.readyState === InterceptorReadyState.DISPOSING || this.readyState === InterceptorReadyState.DISPOSED) { + logger.info("cannot listen to events, already disposed!"); + return this; + } + logger.info("adding \"%s\" event listener:", event, listener); + this.emitter.on(event, listener); + return this; + } + once(event, listener) { + this.emitter.once(event, listener); + return this; + } + off(event, listener) { + this.emitter.off(event, listener); + return this; + } + removeAllListeners(event) { + this.emitter.removeAllListeners(event); + return this; + } + /** + * Disposes of any side-effects this interceptor has introduced. + */ + dispose() { + const logger = this.logger.extend("dispose"); + if (this.readyState === InterceptorReadyState.DISPOSED) { + logger.info("cannot dispose, already disposed!"); + return; + } + logger.info("disposing the interceptor..."); + this.readyState = InterceptorReadyState.DISPOSING; + if (!this.getInstance()) { + logger.info("no interceptors running, skipping dispose..."); + return; + } + this.clearInstance(); + logger.info("global symbol deleted:", getGlobalSymbol(this.symbol)); + if (this.subscriptions.length > 0) { + logger.info("disposing of %d subscriptions...", this.subscriptions.length); + for (const dispose of this.subscriptions) dispose(); + this.subscriptions = []; + logger.info("disposed of all subscriptions!", this.subscriptions.length); + } + this.emitter.removeAllListeners(); + logger.info("destroyed the listener!"); + this.readyState = InterceptorReadyState.DISPOSED; + } + getInstance() { + const instance = getGlobalSymbol(this.symbol); + this.logger.info("retrieved global instance:", instance?.constructor?.name); + return instance; + } + setInstance() { + setGlobalSymbol(this.symbol, this); + this.logger.info("set global instance!", this.symbol.description); + } + clearInstance() { + deleteGlobalSymbol(this.symbol); + this.logger.info("cleared global instance!", this.symbol.description); + } +}; + +//#endregion +//#region src/createRequestId.ts +/** +* Generate a random ID string to represent a request. +* @example +* createRequestId() +* // "f774b6c9c600f" +*/ +function createRequestId() { + return Math.random().toString(16).slice(2); +} + +//#endregion +export { deleteGlobalSymbol as a, InterceptorReadyState as i, INTERNAL_REQUEST_ID_HEADER_NAME as n, getGlobalSymbol as o, Interceptor as r, createRequestId as t }; +//# sourceMappingURL=createRequestId-DYCsFHOi.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/createRequestId-DYCsFHOi.mjs.map b/node_modules/@mswjs/interceptors/lib/browser/createRequestId-DYCsFHOi.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..3db859c79b03eea58498a054699104881c88c27e --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/createRequestId-DYCsFHOi.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"createRequestId-DYCsFHOi.mjs","names":["symbol: symbol"],"sources":["../../src/Interceptor.ts","../../src/createRequestId.ts"],"sourcesContent":["import { Logger } from '@open-draft/logger'\nimport { Emitter, Listener } from 'strict-event-emitter'\n\nexport type InterceptorEventMap = Record\nexport type InterceptorSubscription = () => void\n\n/**\n * Request header name to detect when a single request\n * is being handled by nested interceptors (XHR -> ClientRequest).\n * Obscure by design to prevent collisions with user-defined headers.\n * Ideally, come up with the Interceptor-level mechanism for this.\n * @see https://github.com/mswjs/interceptors/issues/378\n */\nexport const INTERNAL_REQUEST_ID_HEADER_NAME =\n 'x-interceptors-internal-request-id'\n\nexport function getGlobalSymbol(symbol: Symbol): V | undefined {\n return (\n // @ts-ignore https://github.com/Microsoft/TypeScript/issues/24587\n globalThis[symbol] || undefined\n )\n}\n\nfunction setGlobalSymbol(symbol: Symbol, value: any): void {\n // @ts-ignore\n globalThis[symbol] = value\n}\n\nexport function deleteGlobalSymbol(symbol: Symbol): void {\n // @ts-ignore\n delete globalThis[symbol]\n}\n\nexport enum InterceptorReadyState {\n INACTIVE = 'INACTIVE',\n APPLYING = 'APPLYING',\n APPLIED = 'APPLIED',\n DISPOSING = 'DISPOSING',\n DISPOSED = 'DISPOSED',\n}\n\nexport type ExtractEventNames> =\n Events extends Record ? EventName : never\n\nexport class Interceptor {\n protected emitter: Emitter\n protected subscriptions: Array\n protected logger: Logger\n\n public readyState: InterceptorReadyState\n\n constructor(private readonly symbol: symbol) {\n this.readyState = InterceptorReadyState.INACTIVE\n\n this.emitter = new Emitter()\n this.subscriptions = []\n this.logger = new Logger(symbol.description!)\n\n // Do not limit the maximum number of listeners\n // so not to limit the maximum amount of parallel events emitted.\n this.emitter.setMaxListeners(0)\n\n this.logger.info('constructing the interceptor...')\n }\n\n /**\n * Determine if this interceptor can be applied\n * in the current environment.\n */\n protected checkEnvironment(): boolean {\n return true\n }\n\n /**\n * Apply this interceptor to the current process.\n * Returns an already running interceptor instance if it's present.\n */\n public apply(): void {\n const logger = this.logger.extend('apply')\n logger.info('applying the interceptor...')\n\n if (this.readyState === InterceptorReadyState.APPLIED) {\n logger.info('intercepted already applied!')\n return\n }\n\n const shouldApply = this.checkEnvironment()\n\n if (!shouldApply) {\n logger.info('the interceptor cannot be applied in this environment!')\n return\n }\n\n this.readyState = InterceptorReadyState.APPLYING\n\n // Whenever applying a new interceptor, check if it hasn't been applied already.\n // This enables to apply the same interceptor multiple times, for example from a different\n // interceptor, only proxying events but keeping the stubs in a single place.\n const runningInstance = this.getInstance()\n\n if (runningInstance) {\n logger.info('found a running instance, reusing...')\n\n // Proxy any listeners you set on this instance to the running instance.\n this.on = (event, listener) => {\n logger.info('proxying the \"%s\" listener', event)\n\n // Add listeners to the running instance so they appear\n // at the top of the event listeners list and are executed first.\n runningInstance.emitter.addListener(event, listener)\n\n // Ensure that once this interceptor instance is disposed,\n // it removes all listeners it has appended to the running interceptor instance.\n this.subscriptions.push(() => {\n runningInstance.emitter.removeListener(event, listener)\n logger.info('removed proxied \"%s\" listener!', event)\n })\n\n return this\n }\n\n this.readyState = InterceptorReadyState.APPLIED\n\n return\n }\n\n logger.info('no running instance found, setting up a new instance...')\n\n // Setup the interceptor.\n this.setup()\n\n // Store the newly applied interceptor instance globally.\n this.setInstance()\n\n this.readyState = InterceptorReadyState.APPLIED\n }\n\n /**\n * Setup the module augments and stubs necessary for this interceptor.\n * This method is not run if there's a running interceptor instance\n * to prevent instantiating an interceptor multiple times.\n */\n protected setup(): void {}\n\n /**\n * Listen to the interceptor's public events.\n */\n public on>(\n event: EventName,\n listener: Listener\n ): this {\n const logger = this.logger.extend('on')\n\n if (\n this.readyState === InterceptorReadyState.DISPOSING ||\n this.readyState === InterceptorReadyState.DISPOSED\n ) {\n logger.info('cannot listen to events, already disposed!')\n return this\n }\n\n logger.info('adding \"%s\" event listener:', event, listener)\n\n this.emitter.on(event, listener)\n return this\n }\n\n public once>(\n event: EventName,\n listener: Listener\n ): this {\n this.emitter.once(event, listener)\n return this\n }\n\n public off>(\n event: EventName,\n listener: Listener\n ): this {\n this.emitter.off(event, listener)\n return this\n }\n\n public removeAllListeners>(\n event?: EventName\n ): this {\n this.emitter.removeAllListeners(event)\n return this\n }\n\n /**\n * Disposes of any side-effects this interceptor has introduced.\n */\n public dispose(): void {\n const logger = this.logger.extend('dispose')\n\n if (this.readyState === InterceptorReadyState.DISPOSED) {\n logger.info('cannot dispose, already disposed!')\n return\n }\n\n logger.info('disposing the interceptor...')\n this.readyState = InterceptorReadyState.DISPOSING\n\n if (!this.getInstance()) {\n logger.info('no interceptors running, skipping dispose...')\n return\n }\n\n // Delete the global symbol as soon as possible,\n // indicating that the interceptor is no longer running.\n this.clearInstance()\n\n logger.info('global symbol deleted:', getGlobalSymbol(this.symbol))\n\n if (this.subscriptions.length > 0) {\n logger.info('disposing of %d subscriptions...', this.subscriptions.length)\n\n for (const dispose of this.subscriptions) {\n dispose()\n }\n\n this.subscriptions = []\n\n logger.info('disposed of all subscriptions!', this.subscriptions.length)\n }\n\n this.emitter.removeAllListeners()\n logger.info('destroyed the listener!')\n\n this.readyState = InterceptorReadyState.DISPOSED\n }\n\n private getInstance(): this | undefined {\n const instance = getGlobalSymbol(this.symbol)\n this.logger.info('retrieved global instance:', instance?.constructor?.name)\n return instance\n }\n\n private setInstance(): void {\n setGlobalSymbol(this.symbol, this)\n this.logger.info('set global instance!', this.symbol.description)\n }\n\n private clearInstance(): void {\n deleteGlobalSymbol(this.symbol)\n this.logger.info('cleared global instance!', this.symbol.description)\n }\n}\n","/**\n * Generate a random ID string to represent a request.\n * @example\n * createRequestId()\n * // \"f774b6c9c600f\"\n */\nexport function createRequestId(): string {\n return Math.random().toString(16).slice(2)\n}\n"],"mappings":";;;;;;;;;;;AAaA,MAAa,kCACX;AAEF,SAAgB,gBAAmB,QAA+B;AAChE,QAEE,WAAW,WAAW;;AAI1B,SAAS,gBAAgB,QAAgB,OAAkB;AAEzD,YAAW,UAAU;;AAGvB,SAAgB,mBAAmB,QAAsB;AAEvD,QAAO,WAAW;;AAGpB,IAAY,0EAAL;AACL;AACA;AACA;AACA;AACA;;;AAMF,IAAa,cAAb,MAA6D;CAO3D,YAAY,AAAiBA,QAAgB;EAAhB;AAC3B,OAAK,aAAa,sBAAsB;AAExC,OAAK,UAAU,IAAI,SAAS;AAC5B,OAAK,gBAAgB,EAAE;AACvB,OAAK,SAAS,IAAI,OAAO,OAAO,YAAa;AAI7C,OAAK,QAAQ,gBAAgB,EAAE;AAE/B,OAAK,OAAO,KAAK,kCAAkC;;;;;;CAOrD,AAAU,mBAA4B;AACpC,SAAO;;;;;;CAOT,AAAO,QAAc;EACnB,MAAM,SAAS,KAAK,OAAO,OAAO,QAAQ;AAC1C,SAAO,KAAK,8BAA8B;AAE1C,MAAI,KAAK,eAAe,sBAAsB,SAAS;AACrD,UAAO,KAAK,+BAA+B;AAC3C;;A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BAAsB;AAExC,MAAI,CAAC,KAAK,aAAa,EAAE;AACvB,UAAO,KAAK,+CAA+C;AAC3D;;AAKF,OAAK,eAAe;AAEpB,SAAO,KAAK,0BAA0B,gBAAgB,KAAK,OAAO,CAAC;AAEnE,MAAI,KAAK,cAAc,SAAS,GAAG;AACjC,UAAO,KAAK,oCAAoC,KAAK,cAAc,OAAO;AAE1E,QAAK,MAAM,WAAW,KAAK,cACzB,UAAS;AAGX,QAAK,gBAAgB,EAAE;AAEvB,UAAO,KAAK,kCAAkC,KAAK,cAAc,OAAO;;AAG1E,OAAK,QAAQ,oBAAoB;AACjC,SAAO,KAAK,0BAA0B;AAEtC,OAAK,aAAa,sBAAsB;;CAG1C,AAAQ,cAAgC;EACtC,MAAM,WAAW,gBAAsB,KAAK,OAAO;AACnD,OAAK,OAAO,KAAK,8BAA8B,UAAU,aAAa,KAAK;AAC3E,SAAO;;CAGT,AAAQ,cAAoB;AAC1B,kBAAgB,KAAK,QAAQ,KAAK;AAClC,OAAK,OAAO,KAAK,wBAAwB,KAAK,OAAO,YAAY;;CAGnE,AAAQ,gBAAsB;AAC5B,qBAAmB,KAAK,OAAO;AAC/B,OAAK,OAAO,KAAK,4BAA4B,KAAK,OAAO,YAAY;;;;;;;;;;;;AChPzE,SAAgB,kBAA0B;AACxC,QAAO,KAAK,QAAQ,CAAC,SAAS,GAAG,CAAC,MAAM,EAAE"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/fetch-5IMPqr9e.mjs b/node_modules/@mswjs/interceptors/lib/browser/fetch-5IMPqr9e.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ff7e15e2e4b6d91614f01fd4e5439f67ed72ea70 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/fetch-5IMPqr9e.mjs @@ -0,0 +1,236 @@ +import { r as Interceptor, t as createRequestId } from "./createRequestId-DYCsFHOi.mjs"; +import { a as canParseUrl, i as FetchResponse, n as setRawRequest, o as RequestController, r as FetchRequest } from "./getRawRequest-B1BqgWG6.mjs"; +import { n as patchesRegistry, r as emitAsync, t as hasConfigurableGlobal } from "./hasConfigurableGlobal-C8zq1MCg.mjs"; +import { n as isResponseError, t as handleRequest } from "./handleRequest-CPPgsG7s.mjs"; +import { DeferredPromise } from "@open-draft/deferred-promise"; +import { until } from "@open-draft/until"; + +//#region src/interceptors/fetch/utils/createNetworkError.ts +function createNetworkError(cause) { + return Object.assign(/* @__PURE__ */ new TypeError("Failed to fetch"), { cause }); +} + +//#endregion +//#region src/interceptors/fetch/utils/followRedirect.ts +const REQUEST_BODY_HEADERS = [ + "content-encoding", + "content-language", + "content-location", + "content-type", + "content-length" +]; +const kRedirectCount = Symbol("kRedirectCount"); +/** +* @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1210 +*/ +async function followFetchRedirect(request, response) { + if (response.status !== 303 && request.body != null) return Promise.reject(createNetworkError()); + const requestUrl = new URL(request.url); + let locationUrl; + try { + locationUrl = new URL(response.headers.get("location"), request.url); + } catch (error) { + return Promise.reject(createNetworkError(error)); + } + if (!(locationUrl.protocol === "http:" || locationUrl.protocol === "https:")) return Promise.reject(createNetworkError("URL scheme must be a HTTP(S) scheme")); + if (Reflect.get(request, kRedirectCount) > 20) return Promise.reject(createNetworkError("redirect count exceeded")); + Object.defineProperty(request, kRedirectCount, { value: (Reflect.get(request, kRedirectCount) || 0) + 1 }); + if (request.mode === "cors" && (locationUrl.username || locationUrl.password) && !sameOrigin(requestUrl, locationUrl)) return Promise.reject(createNetworkError("cross origin not allowed for request mode \"cors\"")); + const requestInit = {}; + if ([301, 302].includes(response.status) && request.method === "POST" || response.status === 303 && !["HEAD", "GET"].includes(request.method)) { + requestInit.method = "GET"; + requestInit.body = null; + REQUEST_BODY_HEADERS.forEach((headerName) => { + request.headers.delete(headerName); + }); + } + if (!sameOrigin(requestUrl, locationUrl)) { + request.headers.delete("authorization"); + request.headers.delete("proxy-authorization"); + request.headers.delete("cookie"); + request.headers.delete("host"); + } + /** + * @note Undici "safely" extracts the request body. + * I suspect we cannot dispatch this request again + * since its body has been read and the stream is locked. + */ + requestInit.headers = request.headers; + const finalResponse = await fetch(new Request(locationUrl, requestInit)); + Object.defineProperty(finalResponse, "redirected", { + value: true, + configurable: true + }); + return finalResponse; +} +/** +* @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/util.js#L761 +*/ +function sameOrigin(left, right) { + if (left.origin === right.origin && left.origin === "null") return true; + if (left.protocol === right.protocol && left.hostname === right.hostname && left.port === right.port) return true; + return false; +} + +//#endregion +//#region src/interceptors/fetch/utils/brotli-decompress.browser.ts +var BrotliDecompressionStream = class extends TransformStream { + constructor() { + console.warn("[Interceptors]: Brotli decompression of response streams is not supported in the browser"); + super({ transform(chunk, controller) { + controller.enqueue(chunk); + } }); + } +}; + +//#endregion +//#region src/interceptors/fetch/utils/decompression.ts +var PipelineStream = class extends TransformStream { + constructor(transformStreams, ...strategies) { + super({}, ...strategies); + const readable = [super.readable, ...transformStreams].reduce((readable$1, transform) => readable$1.pipeThrough(transform)); + Object.defineProperty(this, "readable", { get() { + return readable; + } }); + } +}; +function parseContentEncoding(contentEncoding) { + return contentEncoding.toLowerCase().split(",").map((coding) => coding.trim()); +} +function createDecompressionStream(contentEncoding) { + if (contentEncoding === "") return null; + const codings = parseContentEncoding(contentEncoding); + if (codings.length === 0) return null; + return new PipelineStream(codings.reduceRight((transformers, coding) => { + if (coding === "gzip" || coding === "x-gzip") return transformers.concat(new DecompressionStream("gzip")); + else if (coding === "deflate") return transformers.concat(new DecompressionStream("deflate")); + else if (coding === "br") return transformers.concat(new BrotliDecompressionStream()); + else transformers.length = 0; + return transformers; + }, [])); +} +function decompressResponse(response) { + if (response.body === null) return null; + const decompressionStream = createDecompressionStream(response.headers.get("content-encoding") || ""); + if (!decompressionStream) return null; + response.body.pipeTo(decompressionStream.writable); + return decompressionStream.readable; +} + +//#endregion +//#region src/interceptors/fetch/index.ts +var FetchInterceptor = class FetchInterceptor extends Interceptor { + static { + this.symbol = Symbol.for("fetch-interceptor"); + } + constructor() { + super(FetchInterceptor.symbol); + } + checkEnvironment() { + return hasConfigurableGlobal("fetch"); + } + async setup() { + const logger = this.logger.extend("setup"); + const pureFetch = globalThis.fetch; + const fetchProxy = async (input, init) => { + const requestId = createRequestId(); + const request = new FetchRequest(typeof input === "string" && typeof location !== "undefined" && !canParseUrl(input) ? new URL(input, location.href) : input, init); + /** + * @note Set the raw request only if a Request instance was provided to fetch. + */ + if (input instanceof Request) setRawRequest(request, input); + const responsePromise = new DeferredPromise(); + const controller = new RequestController(request, { + passthrough: async () => { + this.logger.info("request has not been handled, passthrough..."); + /** + * @note Clone the request instance right before performing it. + * This preserves any modifications made to the intercepted request + * in the "request" listener. This also allows the user to read the + * request body in the "response" listener (otherwise "unusable"). + */ + const requestCloneForResponseEvent = request.clone(); + const { error: responseError, data: originalResponse } = await until(() => pureFetch(request)); + if (responseError) return responsePromise.reject(responseError); + this.logger.info("original fetch performed", originalResponse); + if (this.emitter.listenerCount("response") > 0) { + this.logger.info("emitting the \"response\" event..."); + const responseClone = FetchResponse.clone(originalResponse); + await emitAsync(this.emitter, "response", { + response: responseClone, + isMockedResponse: false, + request: requestCloneForResponseEvent, + requestId + }); + } + responsePromise.resolve(originalResponse); + }, + respondWith: async (rawResponse) => { + if (isResponseError(rawResponse)) { + this.logger.info("request has errored!", { response: rawResponse }); + responsePromise.reject(createNetworkError(rawResponse)); + return; + } + this.logger.info("received mocked response!", { rawResponse }); + const response = new FetchResponse(decompressResponse(rawResponse) || rawResponse.body, { + url: request.url, + status: rawResponse.status, + statusText: rawResponse.statusText, + headers: rawResponse.headers + }); + /** + * Undici's handling of following redirect responses. + * Treat the "manual" redirect mode as a regular mocked response. + * This way, the client can manually follow the redirect it receives. + * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1173 + */ + if (FetchResponse.isRedirectResponse(response.status)) { + if (request.redirect === "error") { + responsePromise.reject(createNetworkError("unexpected redirect")); + return; + } + if (request.redirect === "follow") { + followFetchRedirect(request, response).then((response$1) => { + responsePromise.resolve(response$1); + }, (reason) => { + responsePromise.reject(reason); + }); + return; + } + } + if (this.emitter.listenerCount("response") > 0) { + this.logger.info("emitting the \"response\" event..."); + await emitAsync(this.emitter, "response", { + response: FetchResponse.clone(response), + isMockedResponse: true, + request, + requestId + }); + } + responsePromise.resolve(response); + }, + errorWith: (reason) => { + this.logger.info("request has been aborted!", { reason }); + responsePromise.reject(reason); + } + }); + this.logger.info("[%s] %s", request.method, request.url); + this.logger.info("awaiting for the mocked response..."); + this.logger.info("emitting the \"request\" event for %s listener(s)...", this.emitter.listenerCount("request")); + await handleRequest({ + request, + requestId, + emitter: this.emitter, + controller + }); + return responsePromise; + }; + logger.info("patching global fetch..."); + this.subscriptions.push(patchesRegistry.applyPatch(globalThis, "fetch", () => fetchProxy)); + logger.info("global fetch patched!", globalThis.fetch.name); + } +}; + +//#endregion +export { FetchInterceptor as t }; +//# sourceMappingURL=fetch-5IMPqr9e.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/fetch-5IMPqr9e.mjs.map b/node_modules/@mswjs/interceptors/lib/browser/fetch-5IMPqr9e.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..3e82a9e203d008c058e4408bbbb37620bc34f508 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/fetch-5IMPqr9e.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"fetch-5IMPqr9e.mjs","names":["locationUrl: URL","requestInit: RequestInit","readable","fetchProxy: typeof fetch","response"],"sources":["../../src/interceptors/fetch/utils/createNetworkError.ts","../../src/interceptors/fetch/utils/followRedirect.ts","../../src/interceptors/fetch/utils/brotli-decompress.browser.ts","../../src/interceptors/fetch/utils/decompression.ts","../../src/interceptors/fetch/index.ts"],"sourcesContent":["export function createNetworkError(cause?: unknown) {\n return Object.assign(new TypeError('Failed to fetch'), {\n cause,\n })\n}\n","import { createNetworkError } from './createNetworkError'\n\nconst REQUEST_BODY_HEADERS = [\n 'content-encoding',\n 'content-language',\n 'content-location',\n 'content-type',\n 'content-length',\n]\n\nconst kRedirectCount = Symbol('kRedirectCount')\n\n/**\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1210\n */\nexport async function followFetchRedirect(\n request: Request,\n response: Response\n): Promise {\n if (response.status !== 303 && request.body != null) {\n return Promise.reject(createNetworkError())\n }\n\n const requestUrl = new URL(request.url)\n\n let locationUrl: URL\n try {\n // If the location is a relative URL, use the request URL as the base URL.\n locationUrl = new URL(response.headers.get('location')!, request.url) \n } catch (error) {\n return Promise.reject(createNetworkError(error))\n }\n\n if (\n !(locationUrl.protocol === 'http:' || locationUrl.protocol === 'https:')\n ) {\n return Promise.reject(\n createNetworkError('URL scheme must be a HTTP(S) scheme')\n )\n }\n\n if (Reflect.get(request, kRedirectCount) > 20) {\n return Promise.reject(createNetworkError('redirect count exceeded'))\n }\n\n Object.defineProperty(request, kRedirectCount, {\n value: (Reflect.get(request, kRedirectCount) || 0) + 1,\n })\n\n if (\n request.mode === 'cors' &&\n (locationUrl.username || locationUrl.password) &&\n !sameOrigin(requestUrl, locationUrl)\n ) {\n return Promise.reject(\n createNetworkError('cross origin not allowed for request mode \"cors\"')\n )\n }\n\n const requestInit: RequestInit = {}\n\n if (\n ([301, 302].includes(response.status) && request.method === 'POST') ||\n (response.status === 303 && !['HEAD', 'GET'].includes(request.method))\n ) {\n requestInit.method = 'GET'\n requestInit.body = null\n\n REQUEST_BODY_HEADERS.forEach((headerName) => {\n request.headers.delete(headerName)\n })\n }\n\n if (!sameOrigin(requestUrl, locationUrl)) {\n request.headers.delete('authorization')\n request.headers.delete('proxy-authorization')\n request.headers.delete('cookie')\n request.headers.delete('host')\n }\n\n /**\n * @note Undici \"safely\" extracts the request body.\n * I suspect we cannot dispatch this request again\n * since its body has been read and the stream is locked.\n */\n\n requestInit.headers = request.headers\n const finalResponse = await fetch(new Request(locationUrl, requestInit))\n Object.defineProperty(finalResponse, 'redirected', {\n value: true,\n configurable: true,\n })\n\n return finalResponse\n}\n\n/**\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/util.js#L761\n */\nfunction sameOrigin(left: URL, right: URL): boolean {\n if (left.origin === right.origin && left.origin === 'null') {\n return true\n }\n\n if (\n left.protocol === right.protocol &&\n left.hostname === right.hostname &&\n left.port === right.port\n ) {\n return true\n }\n\n return false\n}\n","export class BrotliDecompressionStream extends TransformStream {\n constructor() {\n console.warn(\n '[Interceptors]: Brotli decompression of response streams is not supported in the browser'\n )\n\n super({\n transform(chunk, controller) {\n // Keep the stream as passthrough, it does nothing.\n controller.enqueue(chunk)\n },\n })\n }\n}\n","// Import from an internal alias that resolves to different modules\n// depending on the environment. This way, we can keep the fetch interceptor\n// intact while using different strategies for Brotli decompression.\nimport { BrotliDecompressionStream } from 'internal:brotli-decompress'\n\nclass PipelineStream extends TransformStream {\n constructor(\n transformStreams: Array,\n ...strategies: Array\n ) {\n super({}, ...strategies)\n\n const readable = [super.readable as any, ...transformStreams].reduce(\n (readable, transform) => readable.pipeThrough(transform)\n )\n\n Object.defineProperty(this, 'readable', {\n get() {\n return readable\n },\n })\n }\n}\n\nexport function parseContentEncoding(contentEncoding: string): Array {\n return contentEncoding\n .toLowerCase()\n .split(',')\n .map((coding) => coding.trim())\n}\n\nfunction createDecompressionStream(\n contentEncoding: string\n): TransformStream | null {\n if (contentEncoding === '') {\n return null\n }\n\n const codings = parseContentEncoding(contentEncoding)\n\n if (codings.length === 0) {\n return null\n }\n\n const transformers = codings.reduceRight>(\n (transformers, coding) => {\n if (coding === 'gzip' || coding === 'x-gzip') {\n return transformers.concat(new DecompressionStream('gzip'))\n } else if (coding === 'deflate') {\n return transformers.concat(new DecompressionStream('deflate'))\n } else if (coding === 'br') {\n return transformers.concat(new BrotliDecompressionStream())\n } else {\n transformers.length = 0\n }\n\n return transformers\n },\n []\n )\n\n return new PipelineStream(transformers)\n}\n\nexport function decompressResponse(\n response: Response\n): ReadableStream | null {\n if (response.body === null) {\n return null\n }\n\n const decompressionStream = createDecompressionStream(\n response.headers.get('content-encoding') || ''\n )\n\n if (!decompressionStream) {\n return null\n }\n\n // Use `pipeTo` and return the decompression stream's readable\n // instead of `pipeThrough` because that will lock the original\n // response stream, making it unusable as the input to Response.\n response.body.pipeTo(decompressionStream.writable)\n return decompressionStream.readable\n}\n","import { until } from '@open-draft/until'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { HttpRequestEventMap } from '../../glossary'\nimport { Interceptor } from '../../Interceptor'\nimport { RequestController } from '../../RequestController'\nimport { emitAsync } from '../../utils/emitAsync'\nimport { handleRequest } from '../../utils/handleRequest'\nimport { canParseUrl } from '../../utils/canParseUrl'\nimport { createRequestId } from '../../createRequestId'\nimport { createNetworkError } from './utils/createNetworkError'\nimport { followFetchRedirect } from './utils/followRedirect'\nimport { decompressResponse } from './utils/decompression'\nimport { hasConfigurableGlobal } from '../../utils/hasConfigurableGlobal'\nimport { FetchRequest, FetchResponse } from '../../utils/fetchUtils'\nimport { setRawRequest } from '../../getRawRequest'\nimport { isResponseError } from '../../utils/responseUtils'\nimport { patchesRegistry } from '../../utils/patchesRegistry'\n\nexport class FetchInterceptor extends Interceptor {\n static symbol = Symbol.for('fetch-interceptor')\n\n constructor() {\n super(FetchInterceptor.symbol)\n }\n\n protected checkEnvironment() {\n return hasConfigurableGlobal('fetch')\n }\n\n protected async setup() {\n const logger = this.logger.extend('setup')\n\n const pureFetch = globalThis.fetch\n\n const fetchProxy: typeof fetch = async (input, init) => {\n const requestId = createRequestId()\n\n /**\n * @note Resolve potentially relative request URL\n * against the present `location`. This is mainly\n * for native `fetch` in JSDOM.\n * @see https://github.com/mswjs/msw/issues/1625\n */\n const resolvedInput =\n typeof input === 'string' &&\n typeof location !== 'undefined' &&\n !canParseUrl(input)\n ? new URL(input, location.href)\n : input\n\n const request = new FetchRequest(resolvedInput, init)\n\n /**\n * @note Set the raw request only if a Request instance was provided to fetch.\n */\n if (input instanceof Request) {\n setRawRequest(request, input)\n }\n\n const responsePromise = new DeferredPromise()\n\n const controller = new RequestController(request, {\n passthrough: async () => {\n this.logger.info('request has not been handled, passthrough...')\n\n /**\n * @note Clone the request instance right before performing it.\n * This preserves any modifications made to the intercepted request\n * in the \"request\" listener. This also allows the user to read the\n * request body in the \"response\" listener (otherwise \"unusable\").\n */\n const requestCloneForResponseEvent = request.clone()\n\n // Perform the intercepted request as-is.\n const { error: responseError, data: originalResponse } = await until(\n () => pureFetch(request)\n )\n\n if (responseError) {\n return responsePromise.reject(responseError)\n }\n\n this.logger.info('original fetch performed', originalResponse)\n\n if (this.emitter.listenerCount('response') > 0) {\n this.logger.info('emitting the \"response\" event...')\n\n const responseClone = FetchResponse.clone(originalResponse)\n await emitAsync(this.emitter, 'response', {\n response: responseClone,\n isMockedResponse: false,\n request: requestCloneForResponseEvent,\n requestId,\n })\n }\n\n // Resolve the response promise with the original response\n // since the `fetch()` return this internal promise.\n responsePromise.resolve(originalResponse)\n },\n respondWith: async (rawResponse) => {\n // Handle mocked `Response.error()` (i.e. request errors).\n if (isResponseError(rawResponse)) {\n this.logger.info('request has errored!', { response: rawResponse })\n responsePromise.reject(createNetworkError(rawResponse))\n return\n }\n\n this.logger.info('received mocked response!', {\n rawResponse,\n })\n\n // Decompress the mocked response body, if applicable.\n const decompressedStream = decompressResponse(rawResponse)\n const response = new FetchResponse(\n decompressedStream || rawResponse.body,\n {\n url: request.url,\n status: rawResponse.status,\n statusText: rawResponse.statusText,\n headers: rawResponse.headers,\n }\n )\n\n /**\n * Undici's handling of following redirect responses.\n * Treat the \"manual\" redirect mode as a regular mocked response.\n * This way, the client can manually follow the redirect it receives.\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1173\n */\n if (FetchResponse.isRedirectResponse(response.status)) {\n // Reject the request promise if its `redirect` is set to `error`\n // and it receives a mocked redirect response.\n if (request.redirect === 'error') {\n responsePromise.reject(createNetworkError('unexpected redirect'))\n return\n }\n\n if (request.redirect === 'follow') {\n followFetchRedirect(request, response).then(\n (response) => {\n responsePromise.resolve(response)\n },\n (reason) => {\n responsePromise.reject(reason)\n }\n )\n return\n }\n }\n\n if (this.emitter.listenerCount('response') > 0) {\n this.logger.info('emitting the \"response\" event...')\n\n // Await the response listeners to finish before resolving\n // the response promise. This ensures all your logic finishes\n // before the interceptor resolves the pending response.\n await emitAsync(this.emitter, 'response', {\n // Clone the mocked response for the \"response\" event listener.\n // This way, the listener can read the response and not lock its body\n // for the actual fetch consumer.\n response: FetchResponse.clone(response),\n isMockedResponse: true,\n request,\n requestId,\n })\n }\n\n responsePromise.resolve(response)\n },\n errorWith: (reason) => {\n this.logger.info('request has been aborted!', { reason })\n responsePromise.reject(reason)\n },\n })\n\n this.logger.info('[%s] %s', request.method, request.url)\n this.logger.info('awaiting for the mocked response...')\n\n this.logger.info(\n 'emitting the \"request\" event for %s listener(s)...',\n this.emitter.listenerCount('request')\n )\n\n await handleRequest({\n request,\n requestId,\n emitter: this.emitter,\n controller,\n })\n\n return responsePromise\n }\n\n logger.info('patching global fetch...')\n\n this.subscriptions.push(\n patchesRegistry.applyPatch(globalThis, 'fetch', () => fetchProxy)\n )\n\n logger.info('global fetch patched!', globalThis.fetch.name)\n }\n}\n"],"mappings":";;;;;;;;AAAA,SAAgB,mBAAmB,OAAiB;AAClD,QAAO,OAAO,uBAAO,IAAI,UAAU,kBAAkB,EAAE,EACrD,OACD,CAAC;;;;;ACDJ,MAAM,uBAAuB;CAC3B;CACA;CACA;CACA;CACA;CACD;AAED,MAAM,iBAAiB,OAAO,iBAAiB;;;;AAK/C,eAAsB,oBACpB,SACA,UACmB;AACnB,KAAI,SAAS,WAAW,OAAO,QAAQ,Q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SAAM,cAAc;IAClB;IACA;IACA,SAAS,KAAK;IACd;IACD,CAAC;AAEF,UAAO;;AAGT,SAAO,KAAK,2BAA2B;AAEvC,OAAK,cAAc,KACjB,gBAAgB,WAAW,YAAY,eAAe,WAAW,CAClE;AAED,SAAO,KAAK,yBAAyB,WAAW,MAAM,KAAK"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/fetch-Bt9rMY9c.cjs b/node_modules/@mswjs/interceptors/lib/browser/fetch-Bt9rMY9c.cjs new file mode 100644 index 0000000000000000000000000000000000000000..b8a9756759a22bbe2082ce62907df47dc3b685da --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/fetch-Bt9rMY9c.cjs @@ -0,0 +1,241 @@ +const require_createRequestId = require('./createRequestId-DOf8Ktjs.cjs'); +const require_getRawRequest = require('./getRawRequest-DdfaiPVH.cjs'); +const require_hasConfigurableGlobal = require('./hasConfigurableGlobal-CS7adEvV.cjs'); +const require_handleRequest = require('./handleRequest-CJim54xG.cjs'); +let _open_draft_deferred_promise = require("@open-draft/deferred-promise"); +let _open_draft_until = require("@open-draft/until"); + +//#region src/interceptors/fetch/utils/createNetworkError.ts +function createNetworkError(cause) { + return Object.assign(/* @__PURE__ */ new TypeError("Failed to fetch"), { cause }); +} + +//#endregion +//#region src/interceptors/fetch/utils/followRedirect.ts +const REQUEST_BODY_HEADERS = [ + "content-encoding", + "content-language", + "content-location", + "content-type", + "content-length" +]; +const kRedirectCount = Symbol("kRedirectCount"); +/** +* @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1210 +*/ +async function followFetchRedirect(request, response) { + if (response.status !== 303 && request.body != null) return Promise.reject(createNetworkError()); + const requestUrl = new URL(request.url); + let locationUrl; + try { + locationUrl = new URL(response.headers.get("location"), request.url); + } catch (error) { + return Promise.reject(createNetworkError(error)); + } + if (!(locationUrl.protocol === "http:" || locationUrl.protocol === "https:")) return Promise.reject(createNetworkError("URL scheme must be a HTTP(S) scheme")); + if (Reflect.get(request, kRedirectCount) > 20) return Promise.reject(createNetworkError("redirect count exceeded")); + Object.defineProperty(request, kRedirectCount, { value: (Reflect.get(request, kRedirectCount) || 0) + 1 }); + if (request.mode === "cors" && (locationUrl.username || locationUrl.password) && !sameOrigin(requestUrl, locationUrl)) return Promise.reject(createNetworkError("cross origin not allowed for request mode \"cors\"")); + const requestInit = {}; + if ([301, 302].includes(response.status) && request.method === "POST" || response.status === 303 && !["HEAD", "GET"].includes(request.method)) { + requestInit.method = "GET"; + requestInit.body = null; + REQUEST_BODY_HEADERS.forEach((headerName) => { + request.headers.delete(headerName); + }); + } + if (!sameOrigin(requestUrl, locationUrl)) { + request.headers.delete("authorization"); + request.headers.delete("proxy-authorization"); + request.headers.delete("cookie"); + request.headers.delete("host"); + } + /** + * @note Undici "safely" extracts the request body. + * I suspect we cannot dispatch this request again + * since its body has been read and the stream is locked. + */ + requestInit.headers = request.headers; + const finalResponse = await fetch(new Request(locationUrl, requestInit)); + Object.defineProperty(finalResponse, "redirected", { + value: true, + configurable: true + }); + return finalResponse; +} +/** +* @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/util.js#L761 +*/ +function sameOrigin(left, right) { + if (left.origin === right.origin && left.origin === "null") return true; + if (left.protocol === right.protocol && left.hostname === right.hostname && left.port === right.port) return true; + return false; +} + +//#endregion +//#region src/interceptors/fetch/utils/brotli-decompress.browser.ts +var BrotliDecompressionStream = class extends TransformStream { + constructor() { + console.warn("[Interceptors]: Brotli decompression of response streams is not supported in the browser"); + super({ transform(chunk, controller) { + controller.enqueue(chunk); + } }); + } +}; + +//#endregion +//#region src/interceptors/fetch/utils/decompression.ts +var PipelineStream = class extends TransformStream { + constructor(transformStreams, ...strategies) { + super({}, ...strategies); + const readable = [super.readable, ...transformStreams].reduce((readable$1, transform) => readable$1.pipeThrough(transform)); + Object.defineProperty(this, "readable", { get() { + return readable; + } }); + } +}; +function parseContentEncoding(contentEncoding) { + return contentEncoding.toLowerCase().split(",").map((coding) => coding.trim()); +} +function createDecompressionStream(contentEncoding) { + if (contentEncoding === "") return null; + const codings = parseContentEncoding(contentEncoding); + if (codings.length === 0) return null; + return new PipelineStream(codings.reduceRight((transformers, coding) => { + if (coding === "gzip" || coding === "x-gzip") return transformers.concat(new DecompressionStream("gzip")); + else if (coding === "deflate") return transformers.concat(new DecompressionStream("deflate")); + else if (coding === "br") return transformers.concat(new BrotliDecompressionStream()); + else transformers.length = 0; + return transformers; + }, [])); +} +function decompressResponse(response) { + if (response.body === null) return null; + const decompressionStream = createDecompressionStream(response.headers.get("content-encoding") || ""); + if (!decompressionStream) return null; + response.body.pipeTo(decompressionStream.writable); + return decompressionStream.readable; +} + +//#endregion +//#region src/interceptors/fetch/index.ts +var FetchInterceptor = class FetchInterceptor extends require_createRequestId.Interceptor { + static { + this.symbol = Symbol.for("fetch-interceptor"); + } + constructor() { + super(FetchInterceptor.symbol); + } + checkEnvironment() { + return require_hasConfigurableGlobal.hasConfigurableGlobal("fetch"); + } + async setup() { + const logger = this.logger.extend("setup"); + const pureFetch = globalThis.fetch; + const fetchProxy = async (input, init) => { + const requestId = require_createRequestId.createRequestId(); + const request = new require_getRawRequest.FetchRequest(typeof input === "string" && typeof location !== "undefined" && !require_getRawRequest.canParseUrl(input) ? new URL(input, location.href) : input, init); + /** + * @note Set the raw request only if a Request instance was provided to fetch. + */ + if (input instanceof Request) require_getRawRequest.setRawRequest(request, input); + const responsePromise = new _open_draft_deferred_promise.DeferredPromise(); + const controller = new require_getRawRequest.RequestController(request, { + passthrough: async () => { + this.logger.info("request has not been handled, passthrough..."); + /** + * @note Clone the request instance right before performing it. + * This preserves any modifications made to the intercepted request + * in the "request" listener. This also allows the user to read the + * request body in the "response" listener (otherwise "unusable"). + */ + const requestCloneForResponseEvent = request.clone(); + const { error: responseError, data: originalResponse } = await (0, _open_draft_until.until)(() => pureFetch(request)); + if (responseError) return responsePromise.reject(responseError); + this.logger.info("original fetch performed", originalResponse); + if (this.emitter.listenerCount("response") > 0) { + this.logger.info("emitting the \"response\" event..."); + const responseClone = require_getRawRequest.FetchResponse.clone(originalResponse); + await require_hasConfigurableGlobal.emitAsync(this.emitter, "response", { + response: responseClone, + isMockedResponse: false, + request: requestCloneForResponseEvent, + requestId + }); + } + responsePromise.resolve(originalResponse); + }, + respondWith: async (rawResponse) => { + if (require_handleRequest.isResponseError(rawResponse)) { + this.logger.info("request has errored!", { response: rawResponse }); + responsePromise.reject(createNetworkError(rawResponse)); + return; + } + this.logger.info("received mocked response!", { rawResponse }); + const response = new require_getRawRequest.FetchResponse(decompressResponse(rawResponse) || rawResponse.body, { + url: request.url, + status: rawResponse.status, + statusText: rawResponse.statusText, + headers: rawResponse.headers + }); + /** + * Undici's handling of following redirect responses. + * Treat the "manual" redirect mode as a regular mocked response. + * This way, the client can manually follow the redirect it receives. + * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1173 + */ + if (require_getRawRequest.FetchResponse.isRedirectResponse(response.status)) { + if (request.redirect === "error") { + responsePromise.reject(createNetworkError("unexpected redirect")); + return; + } + if (request.redirect === "follow") { + followFetchRedirect(request, response).then((response$1) => { + responsePromise.resolve(response$1); + }, (reason) => { + responsePromise.reject(reason); + }); + return; + } + } + if (this.emitter.listenerCount("response") > 0) { + this.logger.info("emitting the \"response\" event..."); + await require_hasConfigurableGlobal.emitAsync(this.emitter, "response", { + response: require_getRawRequest.FetchResponse.clone(response), + isMockedResponse: true, + request, + requestId + }); + } + responsePromise.resolve(response); + }, + errorWith: (reason) => { + this.logger.info("request has been aborted!", { reason }); + responsePromise.reject(reason); + } + }); + this.logger.info("[%s] %s", request.method, request.url); + this.logger.info("awaiting for the mocked response..."); + this.logger.info("emitting the \"request\" event for %s listener(s)...", this.emitter.listenerCount("request")); + await require_handleRequest.handleRequest({ + request, + requestId, + emitter: this.emitter, + controller + }); + return responsePromise; + }; + logger.info("patching global fetch..."); + this.subscriptions.push(require_hasConfigurableGlobal.patchesRegistry.applyPatch(globalThis, "fetch", () => fetchProxy)); + logger.info("global fetch patched!", globalThis.fetch.name); + } +}; + +//#endregion +Object.defineProperty(exports, 'FetchInterceptor', { + enumerable: true, + get: function () { + return FetchInterceptor; + } +}); +//# sourceMappingURL=fetch-Bt9rMY9c.cjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/fetch-Bt9rMY9c.cjs.map b/node_modules/@mswjs/interceptors/lib/browser/fetch-Bt9rMY9c.cjs.map new file mode 100644 index 0000000000000000000000000000000000000000..7b7555b4526f0001ce8aa3a7462f8b82cfe405ed --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/fetch-Bt9rMY9c.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"fetch-Bt9rMY9c.cjs","names":["locationUrl: URL","requestInit: RequestInit","readable","Interceptor","hasConfigurableGlobal","fetchProxy: typeof fetch","createRequestId","FetchRequest","canParseUrl","DeferredPromise","RequestController","FetchResponse","emitAsync","isResponseError","response","handleRequest","patchesRegistry"],"sources":["../../src/interceptors/fetch/utils/createNetworkError.ts","../../src/interceptors/fetch/utils/followRedirect.ts","../../src/interceptors/fetch/utils/brotli-decompress.browser.ts","../../src/interceptors/fetch/utils/decompression.ts","../../src/interceptors/fetch/index.ts"],"sourcesContent":["export function createNetworkError(cause?: unknown) {\n return Object.assign(new TypeError('Failed to fetch'), {\n cause,\n })\n}\n","import { createNetworkError } from './createNetworkError'\n\nconst REQUEST_BODY_HEADERS = [\n 'content-encoding',\n 'content-language',\n 'content-location',\n 'content-type',\n 'content-length',\n]\n\nconst kRedirectCount = Symbol('kRedirectCount')\n\n/**\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1210\n */\nexport async function followFetchRedirect(\n request: Request,\n response: Response\n): Promise {\n if (response.status !== 303 && request.body != null) {\n return Promise.reject(createNetworkError())\n }\n\n const requestUrl = new URL(request.url)\n\n let locationUrl: URL\n try {\n // If the location is a relative URL, use the request URL as the base URL.\n locationUrl = new URL(response.headers.get('location')!, request.url) \n } catch (error) {\n return Promise.reject(createNetworkError(error))\n }\n\n if (\n !(locationUrl.protocol === 'http:' || locationUrl.protocol === 'https:')\n ) {\n return Promise.reject(\n createNetworkError('URL scheme must be a HTTP(S) scheme')\n )\n }\n\n if (Reflect.get(request, kRedirectCount) > 20) {\n return Promise.reject(createNetworkError('redirect count exceeded'))\n }\n\n Object.defineProperty(request, kRedirectCount, {\n value: (Reflect.get(request, kRedirectCount) || 0) + 1,\n })\n\n if (\n request.mode === 'cors' &&\n (locationUrl.username || locationUrl.password) &&\n !sameOrigin(requestUrl, locationUrl)\n ) {\n return Promise.reject(\n createNetworkError('cross origin not allowed for request mode \"cors\"')\n )\n }\n\n const requestInit: RequestInit = {}\n\n if (\n ([301, 302].includes(response.status) && request.method === 'POST') ||\n (response.status === 303 && !['HEAD', 'GET'].includes(request.method))\n ) {\n requestInit.method = 'GET'\n requestInit.body = null\n\n REQUEST_BODY_HEADERS.forEach((headerName) => {\n request.headers.delete(headerName)\n })\n }\n\n if (!sameOrigin(requestUrl, locationUrl)) {\n request.headers.delete('authorization')\n request.headers.delete('proxy-authorization')\n request.headers.delete('cookie')\n request.headers.delete('host')\n }\n\n /**\n * @note Undici \"safely\" extracts the request body.\n * I suspect we cannot dispatch this request again\n * since its body has been read and the stream is locked.\n */\n\n requestInit.headers = request.headers\n const finalResponse = await fetch(new Request(locationUrl, requestInit))\n Object.defineProperty(finalResponse, 'redirected', {\n value: true,\n configurable: true,\n })\n\n return finalResponse\n}\n\n/**\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/util.js#L761\n */\nfunction sameOrigin(left: URL, right: URL): boolean {\n if (left.origin === right.origin && left.origin === 'null') {\n return true\n }\n\n if (\n left.protocol === right.protocol &&\n left.hostname === right.hostname &&\n left.port === right.port\n ) {\n return true\n }\n\n return false\n}\n","export class BrotliDecompressionStream extends TransformStream {\n constructor() {\n console.warn(\n '[Interceptors]: Brotli decompression of response streams is not supported in the browser'\n )\n\n super({\n transform(chunk, controller) {\n // Keep the stream as passthrough, it does nothing.\n controller.enqueue(chunk)\n },\n })\n }\n}\n","// Import from an internal alias that resolves to different modules\n// depending on the environment. This way, we can keep the fetch interceptor\n// intact while using different strategies for Brotli decompression.\nimport { BrotliDecompressionStream } from 'internal:brotli-decompress'\n\nclass PipelineStream extends TransformStream {\n constructor(\n transformStreams: Array,\n ...strategies: Array\n ) {\n super({}, ...strategies)\n\n const readable = [super.readable as any, ...transformStreams].reduce(\n (readable, transform) => readable.pipeThrough(transform)\n )\n\n Object.defineProperty(this, 'readable', {\n get() {\n return readable\n },\n })\n }\n}\n\nexport function parseContentEncoding(contentEncoding: string): Array {\n return contentEncoding\n .toLowerCase()\n .split(',')\n .map((coding) => coding.trim())\n}\n\nfunction createDecompressionStream(\n contentEncoding: string\n): TransformStream | null {\n if (contentEncoding === '') {\n return null\n }\n\n const codings = parseContentEncoding(contentEncoding)\n\n if (codings.length === 0) {\n return null\n }\n\n const transformers = codings.reduceRight>(\n (transformers, coding) => {\n if (coding === 'gzip' || coding === 'x-gzip') {\n return transformers.concat(new DecompressionStream('gzip'))\n } else if (coding === 'deflate') {\n return transformers.concat(new DecompressionStream('deflate'))\n } else if (coding === 'br') {\n return transformers.concat(new BrotliDecompressionStream())\n } else {\n transformers.length = 0\n }\n\n return transformers\n },\n []\n )\n\n return new PipelineStream(transformers)\n}\n\nexport function decompressResponse(\n response: Response\n): ReadableStream | null {\n if (response.body === null) {\n return null\n }\n\n const decompressionStream = createDecompressionStream(\n response.headers.get('content-encoding') || ''\n )\n\n if (!decompressionStream) {\n return null\n }\n\n // Use `pipeTo` and return the decompression stream's readable\n // instead of `pipeThrough` because that will lock the original\n // response stream, making it unusable as the input to Response.\n response.body.pipeTo(decompressionStream.writable)\n return decompressionStream.readable\n}\n","import { until } from '@open-draft/until'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { HttpRequestEventMap } from '../../glossary'\nimport { Interceptor } from '../../Interceptor'\nimport { RequestController } from '../../RequestController'\nimport { emitAsync } from '../../utils/emitAsync'\nimport { handleRequest } from '../../utils/handleRequest'\nimport { canParseUrl } from '../../utils/canParseUrl'\nimport { createRequestId } from '../../createRequestId'\nimport { createNetworkError } from './utils/createNetworkError'\nimport { followFetchRedirect } from './utils/followRedirect'\nimport { decompressResponse } from './utils/decompression'\nimport { hasConfigurableGlobal } from '../../utils/hasConfigurableGlobal'\nimport { FetchRequest, FetchResponse } from '../../utils/fetchUtils'\nimport { setRawRequest } from '../../getRawRequest'\nimport { isResponseError } from '../../utils/responseUtils'\nimport { patchesRegistry } from '../../utils/patchesRegistry'\n\nexport class FetchInterceptor extends Interceptor {\n static symbol = Symbol.for('fetch-interceptor')\n\n constructor() {\n super(FetchInterceptor.symbol)\n }\n\n protected checkEnvironment() {\n return hasConfigurableGlobal('fetch')\n }\n\n protected async setup() {\n const logger = this.logger.extend('setup')\n\n const pureFetch = globalThis.fetch\n\n const fetchProxy: typeof fetch = async (input, init) => {\n const requestId = createRequestId()\n\n /**\n * @note Resolve potentially relative request URL\n * against the present `location`. This is mainly\n * for native `fetch` in JSDOM.\n * @see https://github.com/mswjs/msw/issues/1625\n */\n const resolvedInput =\n typeof input === 'string' &&\n typeof location !== 'undefined' &&\n !canParseUrl(input)\n ? new URL(input, location.href)\n : input\n\n const request = new FetchRequest(resolvedInput, init)\n\n /**\n * @note Set the raw request only if a Request instance was provided to fetch.\n */\n if (input instanceof Request) {\n setRawRequest(request, input)\n }\n\n const responsePromise = new DeferredPromise()\n\n const controller = new RequestController(request, {\n passthrough: async () => {\n this.logger.info('request has not been handled, passthrough...')\n\n /**\n * @note Clone the request instance right before performing it.\n * This preserves any modifications made to the intercepted request\n * in the \"request\" listener. This also allows the user to read the\n * request body in the \"response\" listener (otherwise \"unusable\").\n */\n const requestCloneForResponseEvent = request.clone()\n\n // Perform the intercepted request as-is.\n const { error: responseError, data: originalResponse } = await until(\n () => pureFetch(request)\n )\n\n if (responseError) {\n return responsePromise.reject(responseError)\n }\n\n this.logger.info('original fetch performed', originalResponse)\n\n if (this.emitter.listenerCount('response') > 0) {\n this.logger.info('emitting the \"response\" event...')\n\n const responseClone = FetchResponse.clone(originalResponse)\n await emitAsync(this.emitter, 'response', {\n response: responseClone,\n isMockedResponse: false,\n request: requestCloneForResponseEvent,\n requestId,\n })\n }\n\n // Resolve the response promise with the original response\n // since the `fetch()` return this internal promise.\n responsePromise.resolve(originalResponse)\n },\n respondWith: async (rawResponse) => {\n // Handle mocked `Response.error()` (i.e. request errors).\n if (isResponseError(rawResponse)) {\n this.logger.info('request has errored!', { response: rawResponse })\n responsePromise.reject(createNetworkError(rawResponse))\n return\n }\n\n this.logger.info('received mocked response!', {\n rawResponse,\n })\n\n // Decompress the mocked response body, if applicable.\n const decompressedStream = decompressResponse(rawResponse)\n const response = new FetchResponse(\n decompressedStream || rawResponse.body,\n {\n url: request.url,\n status: rawResponse.status,\n statusText: rawResponse.statusText,\n headers: rawResponse.headers,\n }\n )\n\n /**\n * Undici's handling of following redirect responses.\n * Treat the \"manual\" redirect mode as a regular mocked response.\n * This way, the client can manually follow the redirect it receives.\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1173\n */\n if (FetchResponse.isRedirectResponse(response.status)) {\n // Reject the request promise if its `redirect` is set to `error`\n // and it receives a mocked redirect response.\n if (request.redirect === 'error') {\n responsePromise.reject(createNetworkError('unexpected redirect'))\n return\n }\n\n if (request.redirect === 'follow') {\n followFetchRedirect(request, response).then(\n (response) => {\n responsePromise.resolve(response)\n },\n (reason) => {\n responsePromise.reject(reason)\n }\n )\n return\n }\n }\n\n if (this.emitter.listenerCount('response') > 0) {\n this.logger.info('emitting the \"response\" event...')\n\n // Await the response listeners to finish before resolving\n // the response promise. This ensures all your logic finishes\n // before the interceptor resolves the pending response.\n await emitAsync(this.emitter, 'response', {\n // Clone the mocked response for the \"response\" event listener.\n // This way, the listener can read the response and not lock its body\n // for the actual fetch consumer.\n response: FetchResponse.clone(response),\n isMockedResponse: true,\n request,\n requestId,\n })\n }\n\n responsePromise.resolve(response)\n },\n errorWith: (reason) => {\n this.logger.info('request has been aborted!', { reason })\n responsePromise.reject(reason)\n },\n })\n\n this.logger.info('[%s] %s', request.method, request.url)\n this.logger.info('awaiting for the mocked response...')\n\n this.logger.info(\n 'emitting the \"request\" event for %s listener(s)...',\n this.emitter.listenerCount('request')\n )\n\n await handleRequest({\n request,\n requestId,\n emitter: this.emitter,\n controller,\n })\n\n return responsePromise\n }\n\n logger.info('patching global fetch...')\n\n this.subscriptions.push(\n patchesRegistry.applyPatch(globalThis, 'fetch', () => fetchProxy)\n )\n\n logger.info('global fetch patched!', globalThis.fetch.name)\n }\n}\n"],"mappings":";;;;;;;;AAAA,SAAgB,mBAAmB,OAAiB;AAClD,QAAO,OAAO,uBAAO,IAAI,UAAU,kBAAkB,EAAE,EACrD,OACD,CAAC;;;;;ACDJ,MAAM,uBAAuB;CAC3B;CACA;CACA;CACA;CACA;CACD;AAED,MAAM,iBAAiB,OAAO,iBAAiB;;;;AAK/C,eAAsB,oBACpB,SACA,UACmB;AACnB,KAAI,SAAS,WAAW,OAAO,QAAQ,QAAQ,KAC7C,QAAO,QAAQ,OAAO,oBAAoB,CAAC;CAG7C,MAAM,aAAa,IAAI,IAAI,QAAQ,IAAI;CAEvC,IAAIA;AACJ,KAAI;AAEF,gBAAc,IAAI,IAAI,SAAS,QAAQ,IAAI,WAAW,EAAG,QAAQ,IAAI;UAC9D,OAAO;AACd,SAAO,QAAQ,OAAO,mBAAmB,MAAM,CAAC;;AAGlD,KACE,EAAE,YAAY,aAAa,WAAW,YAAY,aAAa,UAE/D,QAAO,QAAQ,OACb,mBAAmB,sCAAsC,CAC1D;AAGH,KAAI,QAAQ,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AAY,IAElC,YAAY,MAClC;MACE,KAAK,QAAQ;MACb,QAAQ,YAAY;MACpB,YAAY,YAAY;MACxB,SAAS,YAAY;MACtB,CACF;;;;;;;AAQD,SAAIA,oCAAc,mBAAmB,SAAS,OAAO,EAAE;AAGrD,UAAI,QAAQ,aAAa,SAAS;AAChC,uBAAgB,OAAO,mBAAmB,sBAAsB,CAAC;AACjE;;AAGF,UAAI,QAAQ,aAAa,UAAU;AACjC,2BAAoB,SAAS,SAAS,CAAC,MACpC,eAAa;AACZ,wBAAgB,QAAQG,WAAS;WAElC,WAAW;AACV,wBAAgB,OAAO,OAAO;SAEjC;AACD;;;AAIJ,SAAI,KAAK,QAAQ,cAAc,WAAW,GAAG,GAAG;AAC9C,WAAK,OAAO,KAAK,qCAAmC;AAKpD,YAAMF,wCAAU,KAAK,SAAS,YAAY;OAIxC,UAAUD,oCAAc,MAAM,SAAS;OACvC,kBAAkB;OAClB;OACA;OACD,CAAC;;AAGJ,qBAAgB,QAAQ,SAAS;;IAEnC,YAAY,WAAW;AACrB,UAAK,OAAO,KAAK,6BAA6B,EAAE,QAAQ,CAAC;AACzD,qBAAgB,OAAO,OAAO;;IAEjC,CAAC;AAEF,QAAK,OAAO,KAAK,WAAW,QAAQ,QAAQ,QAAQ,IAAI;AACxD,QAAK,OAAO,KAAK,sCAAsC;AAEvD,QAAK,OAAO,KACV,wDACA,KAAK,QAAQ,cAAc,UAAU,CACtC;AAED,SAAMI,oCAAc;IAClB;IACA;IACA,SAAS,KAAK;IACd;IACD,CAAC;AAEF,UAAO;;AAGT,SAAO,KAAK,2BAA2B;AAEvC,OAAK,cAAc,KACjBC,8CAAgB,WAAW,YAAY,eAAe,WAAW,CAClE;AAED,SAAO,KAAK,yBAAyB,WAAW,MAAM,KAAK"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/getRawRequest-B1BqgWG6.mjs b/node_modules/@mswjs/interceptors/lib/browser/getRawRequest-B1BqgWG6.mjs new file mode 100644 index 0000000000000000000000000000000000000000..0a60205c6abb0dc844f9720751c0f88b5e83c219 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/getRawRequest-B1BqgWG6.mjs @@ -0,0 +1,335 @@ +import { DeferredPromise } from "@open-draft/deferred-promise"; +import { invariant } from "outvariant"; + +//#region src/InterceptorError.ts +var InterceptorError = class InterceptorError extends Error { + constructor(message) { + super(message); + this.name = "InterceptorError"; + Object.setPrototypeOf(this, InterceptorError.prototype); + } +}; + +//#endregion +//#region src/RequestController.ts +var RequestController = class RequestController { + static { + this.PENDING = 0; + } + static { + this.PASSTHROUGH = 1; + } + static { + this.RESPONSE = 2; + } + static { + this.ERROR = 3; + } + constructor(request, source) { + this.request = request; + this.source = source; + this.readyState = RequestController.PENDING; + this.handled = new DeferredPromise(); + } + get #handled() { + return this.handled; + } + /** + * Perform this request as-is. + */ + async passthrough() { + invariant.as(InterceptorError, this.readyState === RequestController.PENDING, "Failed to passthrough the \"%s %s\" request: the request has already been handled", this.request.method, this.request.url); + this.readyState = RequestController.PASSTHROUGH; + await this.source.passthrough(); + this.#handled.resolve(); + } + /** + * Respond to this request with the given `Response` instance. + * + * @example + * controller.respondWith(new Response()) + * controller.respondWith(Response.json({ id })) + * controller.respondWith(Response.error()) + */ + respondWith(response) { + invariant.as(InterceptorError, this.readyState === RequestController.PENDING, "Failed to respond to the \"%s %s\" request with \"%d %s\": the request has already been handled (%d)", this.request.method, this.request.url, response.status, response.statusText || "OK", this.readyState); + this.readyState = RequestController.RESPONSE; + this.#handled.resolve(); + /** + * @note Although `source.respondWith()` is potentially asynchronous, + * do NOT await it for backward-compatibility. Awaiting it will short-circuit + * the request listener invocation as soon as a listener responds to a request. + * Ideally, that's what we want, but that's not what we promise the user. + */ + this.source.respondWith(response); + } + /** + * Error this request with the given reason. + * + * @example + * controller.errorWith() + * controller.errorWith(new Error('Oops!')) + * controller.errorWith({ message: 'Oops!'}) + */ + errorWith(reason) { + invariant.as(InterceptorError, this.readyState === RequestController.PENDING, "Failed to error the \"%s %s\" request with \"%s\": the request has already been handled (%d)", this.request.method, this.request.url, reason?.toString(), this.readyState); + this.readyState = RequestController.ERROR; + this.source.errorWith(reason); + this.#handled.resolve(); + } +}; + +//#endregion +//#region src/utils/canParseUrl.ts +/** +* Returns a boolean indicating whether the given URL string +* can be parsed into a `URL` instance. +* A substitute for `URL.canParse()` for Node.js 18. +*/ +function canParseUrl(url) { + try { + new URL(url); + return true; + } catch (_error) { + return false; + } +} + +//#endregion +//#region src/utils/getValueBySymbol.ts +/** +* Returns the value behind the symbol with the given name. +*/ +function getValueBySymbol(symbolName, source) { + const symbol = Object.getOwnPropertySymbols(source).find((symbol$1) => { + return symbol$1.description === symbolName; + }); + if (symbol) return Reflect.get(source, symbol); +} + +//#endregion +//#region src/utils/fetchUtils.ts +var FetchRequest = class FetchRequest extends Request { + static #resolveProperty(input, init = {}, key) { + return init[key] ?? (input instanceof Request ? input[key] : void 0); + } + /** + * Check if the given request method is configurable. + * @see https://fetch.spec.whatwg.org/#methods + */ + static isConfigurableMethod(method) { + return method !== "CONNECT" && method !== "TRACE" && method !== "TRACK"; + } + static isMethodWithBody(method) { + return method !== "HEAD" && method !== "GET" && FetchRequest.isConfigurableMethod(method); + } + /** + * Check if the given request `mode` is configurable. + * @see https://fetch.spec.whatwg.org/#concept-request-mode + */ + static isConfigurableMode(mode) { + return mode !== "navigate" && mode !== "websocket" && mode !== "webtransport"; + } + constructor(input, init) { + const method = FetchRequest.#resolveProperty(input, init, "method") || "GET"; + const safeMethod = FetchRequest.isConfigurableMethod(method) ? method : "GET"; + const hasExplicitBody = init != null && "body" in init; + /** + * Only include `body` in the super init when it needs to be overridden. + * When `input` is a Request and no explicit body is in `init`, let the + * Request constructor handle body transfer naturally so it properly + * marks the original request's body as consumed (bodyUsed = true). + */ + const bodyInit = !FetchRequest.isMethodWithBody(method) ? { body: void 0 } : hasExplicitBody ? { body: init.body } : {}; + const mode = FetchRequest.#resolveProperty(input, init, "mode") ?? void 0; + const safeMode = FetchRequest.isConfigurableMode(mode) ? mode : void 0; + super(input, { + ...init || {}, + method: safeMethod, + mode: safeMode, + duplex: init?.duplex ?? (FetchRequest.isMethodWithBody(method) ? "half" : void 0), + ...bodyInit + }); + if (method !== safeMethod) this.#setInternalProperty("method", method); + if (method === "CONNECT") { + const url = new URL(input instanceof Request ? input.url : input); + let authority; + /** + * @note Node.js has a bug parsing raw CONNECT requests URLs like + * "http://127.0.0.1:1337/localhost:80". It would treat "localhost:" as a protocol. + */ + if (url.protocol === "localhost:") authority = url.href; + else authority = url.pathname.replace(/^\/+/, ""); + /** + * @note Define "url" as a getter because Undici uses their own + * logic to resolve the "request.url" property. Simply reassigning + * its value doesn't do anything. This is a destructive action + * but it's safe because "CONNECT" requests are forbidden per fetch. + */ + Object.defineProperty(this, "url", { + get: () => authority, + enumerable: true, + configurable: true + }); + } + if (mode != null && mode !== safeMode) this.#setInternalProperty("mode", mode); + } + #setInternalProperty(key, value) { + const internalState = getValueBySymbol("state", this); + if (internalState) Reflect.set(internalState, key, value); + else Object.defineProperty(this, key, { + value, + enumerable: true, + configurable: true, + writable: false + }); + } +}; +const kStatus = Symbol("kStatus"); +const kUrl = Symbol("kUrl"); +var FetchResponse = class FetchResponse extends Response { + static { + this.STATUS_CODES_WITHOUT_BODY = [ + 101, + 103, + 204, + 205, + 304 + ]; + } + static { + this.STATUS_CODES_WITH_REDIRECT = [ + 301, + 302, + 303, + 307, + 308 + ]; + } + static isConfigurableStatusCode(status) { + return status >= 200 && status <= 599; + } + static isRedirectResponse(status) { + return FetchResponse.STATUS_CODES_WITH_REDIRECT.includes(status); + } + /** + * Returns a boolean indicating whether the given response status + * code represents a response that can have a body. + */ + static isResponseWithBody(status) { + return !FetchResponse.STATUS_CODES_WITHOUT_BODY.includes(status); + } + static setStatus(status, response) { + /** + * @note Undici keeps an internal "Symbol(state)" that holds + * the actual value of response status. Update that in Node.js. + */ + const internalState = getValueBySymbol("state", response); + if (internalState) internalState.status = status; + else Object.defineProperty(response, "status", { + value: status, + enumerable: true, + configurable: true, + writable: false + }); + Object.defineProperty(response, kStatus, { + value: status, + enumerable: false + }); + } + static setUrl(url, response) { + if (!url || url === "about:" || !canParseUrl(url)) return; + const state = getValueBySymbol("state", response); + if (state) state.urlList.push(new URL(url)); + else Object.defineProperty(response, "url", { + value: url, + enumerable: true, + configurable: true, + writable: false + }); + Object.defineProperty(response, kUrl, { + value: url, + enumerable: false + }); + } + /** + * Parses the given raw HTTP headers into a Fetch API `Headers` instance. + */ + static parseRawHeaders(rawHeaders) { + const headers = new Headers(); + for (let line = 0; line < rawHeaders.length; line += 2) headers.append(rawHeaders[line], rawHeaders[line + 1]); + return headers; + } + /** + * Safely clones the given `Response`. + * Coerces response clone exceptions into 500 mocked responses. + * Handy in the environments that introduce arbitrary response + * cloning restrictions, like "101 Switching Protocols" cloning + * in "miniflare". + */ + static clone(response) { + try { + return response.clone(); + } catch (error) { + return Response.json(error instanceof Error ? { + name: error.name, + message: error.message, + stack: error.stack + } : {}, { + status: 500, + statusText: "Unclonable Response" + }); + } + } + constructor(body, init = {}) { + const status = init.status ?? 200; + const safeStatus = FetchResponse.isConfigurableStatusCode(status) ? status : 200; + const finalBody = FetchResponse.isResponseWithBody(status) ? body : null; + super(finalBody, { + status: safeStatus, + statusText: init.statusText, + headers: init.headers + }); + /** + * Since Node.js v24, Undici stores the Response state in an inaccessible field "#state". + * Forward the modified status/URL to the cloned response manually. + * @see https://github.com/nodejs/undici/blob/f734c87280e626c75f59aad55b65eb6a89cef392/lib/web/fetch/response.js#L242 + */ + if (status !== safeStatus) FetchResponse.setStatus(status, this); + FetchResponse.setUrl(init.url, this); + } + clone() { + const clonedResponse = super.clone(); + const customStatus = Reflect.get(this, kStatus); + if (customStatus) FetchResponse.setStatus(customStatus, clonedResponse); + const customUrl = Reflect.get(this, kUrl); + if (customUrl) FetchResponse.setUrl(customUrl, clonedResponse); + return clonedResponse; + } +}; + +//#endregion +//#region src/getRawRequest.ts +const kRawRequest = Symbol("kRawRequest"); +/** +* Returns a raw request instance associated with this request. +* +* @example +* interceptor.on('request', ({ request }) => { +* const rawRequest = getRawRequest(request) +* +* if (rawRequest instanceof http.ClientRequest) { +* console.log(rawRequest.rawHeaders) +* } +* }) +*/ +function getRawRequest(request) { + return Reflect.get(request, kRawRequest); +} +function setRawRequest(request, rawRequest) { + Reflect.set(request, kRawRequest, rawRequest); +} + +//#endregion +export { canParseUrl as a, FetchResponse as i, setRawRequest as n, RequestController as o, FetchRequest as r, InterceptorError as s, getRawRequest as t }; +//# sourceMappingURL=getRawRequest-B1BqgWG6.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/getRawRequest-B1BqgWG6.mjs.map b/node_modules/@mswjs/interceptors/lib/browser/getRawRequest-B1BqgWG6.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..6c12cfac125d39effd0ee2ab7391f7c4f7a34116 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/getRawRequest-B1BqgWG6.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"getRawRequest-B1BqgWG6.mjs","names":["request: Request","source: RequestControllerSource","#handled","symbol","#resolveProperty","bodyInit: { body?: BodyInit | null }","#setInternalProperty","authority: string"],"sources":["../../src/InterceptorError.ts","../../src/RequestController.ts","../../src/utils/canParseUrl.ts","../../src/utils/getValueBySymbol.ts","../../src/utils/fetchUtils.ts","../../src/getRawRequest.ts"],"sourcesContent":["export class InterceptorError extends Error {\n constructor(message?: string) {\n super(message)\n this.name = 'InterceptorError'\n Object.setPrototypeOf(this, InterceptorError.prototype)\n }\n}\n","import { DeferredPromise } from '@open-draft/deferred-promise'\nimport { invariant } from 'outvariant'\nimport { InterceptorError } from './InterceptorError'\n\nexport interface RequestControllerSource {\n passthrough(): void\n respondWith(response: Response): void\n errorWith(reason?: unknown): void\n}\n\nexport class RequestController {\n static PENDING = 0 as const\n static PASSTHROUGH = 1 as const\n static RESPONSE = 2 as const\n static ERROR = 3 as const\n\n public readyState: number\n\n /**\n * A Promise that resolves when this controller handles a request.\n * See `controller.readyState` for more information on the handling result.\n */\n public handled: Promise\n\n constructor(\n protected readonly request: Request,\n protected readonly source: RequestControllerSource\n ) {\n this.readyState = RequestController.PENDING\n this.handled = new DeferredPromise()\n }\n\n get #handled() {\n return this.handled as DeferredPromise\n }\n\n /**\n * Perform this request as-is.\n */\n public async passthrough(): Promise {\n invariant.as(\n InterceptorError,\n this.readyState === RequestController.PENDING,\n 'Failed to passthrough the \"%s %s\" request: the request has already been handled',\n this.request.method,\n this.request.url\n )\n\n this.readyState = RequestController.PASSTHROUGH\n await this.source.passthrough()\n this.#handled.resolve()\n }\n\n /**\n * Respond to this request with the given `Response` instance.\n *\n * @example\n * controller.respondWith(new Response())\n * controller.respondWith(Response.json({ id }))\n * controller.respondWith(Response.error())\n */\n public respondWith(response: Response): void {\n invariant.as(\n InterceptorError,\n this.readyState === RequestController.PENDING,\n 'Failed to respond to the \"%s %s\" request with \"%d %s\": the request has already been handled (%d)',\n this.request.method,\n this.request.url,\n response.status,\n response.statusText || 'OK',\n this.readyState\n )\n\n this.readyState = RequestController.RESPONSE\n this.#handled.resolve()\n\n /**\n * @note Although `source.respondWith()` is potentially asynchronous,\n * do NOT await it for backward-compatibility. Awaiting it will short-circuit\n * the request listener invocation as soon as a listener responds to a request.\n * Ideally, that's what we want, but that's not what we promise the user.\n */\n this.source.respondWith(response)\n }\n\n /**\n * Error this request with the given reason.\n *\n * @example\n * controller.errorWith()\n * controller.errorWith(new Error('Oops!'))\n * controller.errorWith({ message: 'Oops!'})\n */\n public errorWith(reason?: unknown): void {\n invariant.as(\n InterceptorError,\n this.readyState === RequestController.PENDING,\n 'Failed to error the \"%s %s\" request with \"%s\": the request has already been handled (%d)',\n this.request.method,\n this.request.url,\n reason?.toString(),\n this.readyState\n )\n\n this.readyState = RequestController.ERROR\n this.source.errorWith(reason)\n this.#handled.resolve()\n }\n}\n","/**\n * Returns a boolean indicating whether the given URL string\n * can be parsed into a `URL` instance.\n * A substitute for `URL.canParse()` for Node.js 18.\n */\nexport function canParseUrl(url: string): boolean {\n try {\n new URL(url)\n return true\n } catch (_error) {\n return false\n }\n}\n","/**\n * Returns the value behind the symbol with the given name.\n */\nexport function getValueBySymbol(\n symbolName: string,\n source: object\n): T | undefined {\n const ownSymbols = Object.getOwnPropertySymbols(source)\n\n const symbol = ownSymbols.find((symbol) => {\n return symbol.description === symbolName\n })\n\n if (symbol) {\n return Reflect.get(source, symbol)\n }\n\n return\n}\n","import { canParseUrl } from './canParseUrl'\nimport { getValueBySymbol } from './getValueBySymbol'\n\ninterface UndiciRequestState extends RequestInit {}\n\ninterface FetchRequestInit extends Omit {\n mode?: RequestMode | 'websocket' | 'webtransport'\n duplex?: 'half' | 'full'\n}\n\nexport class FetchRequest extends Request {\n static #resolveProperty(\n input: RequestInfo | URL,\n init: FetchRequestInit = {},\n key: T\n ): FetchRequestInit[T] {\n return init[key] ?? (input instanceof Request ? input[key] : undefined)\n }\n\n /**\n * Check if the given request method is configurable.\n * @see https://fetch.spec.whatwg.org/#methods\n */\n static isConfigurableMethod(method: string): boolean {\n return method !== 'CONNECT' && method !== 'TRACE' && method !== 'TRACK'\n }\n\n static isMethodWithBody(method: string): boolean {\n return (\n method !== 'HEAD' &&\n method !== 'GET' &&\n FetchRequest.isConfigurableMethod(method)\n )\n }\n\n /**\n * Check if the given request `mode` is configurable.\n * @see https://fetch.spec.whatwg.org/#concept-request-mode\n */\n static isConfigurableMode(mode: string): boolean {\n return (\n mode !== 'navigate' && mode !== 'websocket' && mode !== 'webtransport'\n )\n }\n\n constructor(input: URL | RequestInfo, init?: FetchRequestInit) {\n const method = FetchRequest.#resolveProperty(input, init, 'method') || 'GET'\n const safeMethod = FetchRequest.isConfigurableMethod(method)\n ? method\n : 'GET'\n\n const hasExplicitBody = init != null && 'body' in init\n\n /**\n * Only include `body` in the super init when it needs to be overridden.\n * When `input` is a Request and no explicit body is in `init`, let the\n * Request constructor handle body transfer naturally so it properly\n * marks the original request's body as consumed (bodyUsed = true).\n */\n const bodyInit: { body?: BodyInit | null } = !FetchRequest.isMethodWithBody(\n method\n )\n ? { body: undefined }\n : hasExplicitBody\n ? { body: init.body }\n : {}\n\n const mode =\n (FetchRequest.#resolveProperty(input, init, 'mode') as RequestMode) ??\n undefined\n const safeMode = FetchRequest.isConfigurableMode(mode) ? mode : undefined\n\n super(input, {\n ...(init || {}),\n method: safeMethod,\n mode: safeMode,\n // @ts-expect-error Untyped Node.js property.\n duplex:\n init?.duplex ??\n (FetchRequest.isMethodWithBody(method) ? 'half' : undefined),\n ...bodyInit,\n })\n\n if (method !== safeMethod) {\n this.#setInternalProperty('method', method)\n }\n\n if (method === 'CONNECT') {\n const url = new URL(input instanceof Request ? input.url : input)\n\n let authority: string\n\n /**\n * @note Node.js has a bug parsing raw CONNECT requests URLs like\n * \"http://127.0.0.1:1337/localhost:80\". It would treat \"localhost:\" as a protocol.\n */\n if (url.protocol === 'localhost:') {\n authority = url.href\n } else {\n authority = url.pathname.replace(/^\\/+/, '')\n }\n\n /**\n * @note Define \"url\" as a getter because Undici uses their own\n * logic to resolve the \"request.url\" property. Simply reassigning\n * its value doesn't do anything. This is a destructive action\n * but it's safe because \"CONNECT\" requests are forbidden per fetch.\n */\n Object.defineProperty(this, 'url', {\n get: () => authority,\n enumerable: true,\n configurable: true,\n })\n }\n\n if (mode != null && mode !== safeMode) {\n this.#setInternalProperty('mode', mode)\n }\n }\n\n #setInternalProperty(\n key: T,\n value: Request[T]\n ): void {\n const internalState = getValueBySymbol('state', this)\n\n if (internalState) {\n Reflect.set(internalState, key, value)\n } else {\n Object.defineProperty(this, key, {\n value,\n enumerable: true,\n configurable: true,\n writable: false,\n })\n }\n }\n}\n\nexport interface FetchResponseInit extends ResponseInit {\n url?: string\n}\n\ninterface UndiciResponseState {\n aborted: boolean\n rangeRequested: boolean\n timingAllowPassed: boolean\n requestIncludesCredentials: boolean\n type: ResponseType\n status: number\n statusText: string\n timingInfo: unknown\n cacheState: unknown\n headersList: Record>\n urlList: Array\n body?: {\n stream: ReadableStream\n source: unknown\n length: number\n }\n}\n\nconst kStatus = Symbol('kStatus')\nconst kUrl = Symbol('kUrl')\n\nexport class FetchResponse extends Response {\n /**\n * Response status codes for responses that cannot have body.\n * @see https://fetch.spec.whatwg.org/#statuses\n */\n static readonly STATUS_CODES_WITHOUT_BODY = [101, 103, 204, 205, 304]\n\n static readonly STATUS_CODES_WITH_REDIRECT = [301, 302, 303, 307, 308]\n\n static isConfigurableStatusCode(status: number): boolean {\n return status >= 200 && status <= 599\n }\n\n static isRedirectResponse(status: number): boolean {\n return FetchResponse.STATUS_CODES_WITH_REDIRECT.includes(status)\n }\n\n /**\n * Returns a boolean indicating whether the given response status\n * code represents a response that can have a body.\n */\n static isResponseWithBody(status: number): boolean {\n return !FetchResponse.STATUS_CODES_WITHOUT_BODY.includes(status)\n }\n\n static setStatus(status: number, response: Response): void {\n /**\n * @note Undici keeps an internal \"Symbol(state)\" that holds\n * the actual value of response status. Update that in Node.js.\n */\n const internalState = getValueBySymbol(\n 'state',\n response\n )\n\n if (internalState) {\n internalState.status = status\n } else {\n Object.defineProperty(response, 'status', {\n value: status,\n enumerable: true,\n configurable: true,\n writable: false,\n })\n }\n\n Object.defineProperty(response, kStatus, {\n value: status,\n enumerable: false,\n })\n }\n\n static setUrl(url: string | undefined, response: Response): void {\n if (!url || url === 'about:' || !canParseUrl(url)) {\n return\n }\n\n const state = getValueBySymbol('state', response)\n\n if (state) {\n // In Undici, push the URL to the internal list of URLs.\n // This will respect the `response.url` getter logic correctly.\n state.urlList.push(new URL(url))\n } else {\n // In other libraries, redefine the `url` property directly.\n Object.defineProperty(response, 'url', {\n value: url,\n enumerable: true,\n configurable: true,\n writable: false,\n })\n }\n\n Object.defineProperty(response, kUrl, {\n value: url,\n enumerable: false,\n })\n }\n\n /**\n * Parses the given raw HTTP headers into a Fetch API `Headers` instance.\n */\n static parseRawHeaders(rawHeaders: Array): Headers {\n const headers = new Headers()\n\n for (let line = 0; line < rawHeaders.length; line += 2) {\n headers.append(rawHeaders[line], rawHeaders[line + 1])\n }\n\n return headers\n }\n\n /**\n * Safely clones the given `Response`.\n * Coerces response clone exceptions into 500 mocked responses.\n * Handy in the environments that introduce arbitrary response\n * cloning restrictions, like \"101 Switching Protocols\" cloning\n * in \"miniflare\".\n */\n static clone(response: Response): Response {\n try {\n const clone = response.clone()\n return clone\n } catch (error) {\n return Response.json(\n error instanceof Error\n ? {\n name: error.name,\n message: error.message,\n stack: error.stack,\n }\n : {},\n {\n status: 500,\n statusText: 'Unclonable Response',\n }\n )\n }\n }\n\n constructor(body?: BodyInit | null, init: FetchResponseInit = {}) {\n const status = init.status ?? 200\n const safeStatus = FetchResponse.isConfigurableStatusCode(status)\n ? status\n : 200\n const finalBody = FetchResponse.isResponseWithBody(status) ? body : null\n\n super(finalBody, {\n status: safeStatus,\n statusText: init.statusText,\n headers: init.headers,\n })\n\n /**\n * Since Node.js v24, Undici stores the Response state in an inaccessible field \"#state\".\n * Forward the modified status/URL to the cloned response manually.\n * @see https://github.com/nodejs/undici/blob/f734c87280e626c75f59aad55b65eb6a89cef392/lib/web/fetch/response.js#L242\n */\n if (status !== safeStatus) {\n FetchResponse.setStatus(status, this)\n }\n\n FetchResponse.setUrl(init.url, this)\n }\n\n public clone() {\n const clonedResponse = super.clone()\n\n const customStatus = Reflect.get(this, kStatus) as number | undefined\n\n if (customStatus) {\n FetchResponse.setStatus(customStatus, clonedResponse)\n }\n\n const customUrl = Reflect.get(this, kUrl) as string | undefined\n\n if (customUrl) {\n FetchResponse.setUrl(customUrl, clonedResponse)\n }\n\n return clonedResponse\n }\n}\n","const kRawRequest = Symbol('kRawRequest')\n\n/**\n * Returns a raw request instance associated with this request.\n *\n * @example\n * interceptor.on('request', ({ request }) => {\n * const rawRequest = getRawRequest(request)\n *\n * if (rawRequest instanceof http.ClientRequest) {\n * console.log(rawRequest.rawHeaders)\n * }\n * })\n */\nexport function getRawRequest(request: Request): unknown | undefined {\n return Reflect.get(request, kRawRequest)\n}\n\nexport function setRawRequest(request: Request, rawRequest: unknown): void {\n Reflect.set(request, kRawRequest, rawRequest)\n}\n"],"mappings":";;;;AAAA,IAAa,mBAAb,MAAa,yBAAyB,MAAM;CAC1C,YAAY,SAAkB;AAC5B,QAAM,QAAQ;AACd,OAAK,OAAO;AACZ,SAAO,eAAe,MAAM,iBAAiB,UAAU;;;;;;ACM3D,IAAa,oBAAb,MAAa,kBAAkB;;iBACZ;;;qBACI;;;kBACH;;;eACH;;CAUf,YACE,AAAmBA,SACnB,AAAmBC,QACnB;EAFmB;EACA;AAEnB,OAAK,aAAa,kBAAkB;AACpC,OAAK,UAAU,IAAI,iBAAuB;;CAG5C,KAAIC,UAAW;AACb,SAAO,KAAK;;;;;CAMd,MAAa,cAA6B;AACxC,YAAU,GACR,kBACA,KAAK,eAAe,kBAAkB,SACtC,qFACA,KAAK,QAAQ,QACb,KAAK,QAAQ,IACd;AAED,OAAK,aAAa,kBAAkB;AACpC,QAAM,KAAK,OAAO,aAAa;AAC/B,QAAKA,QAAS,SAAS;;;;;;;;;;CAWzB,AAAO,YAAY,UAA0B;AAC3C,YAAU,GACR,kBACA,KAAK,eAAe,kBAAkB,SACtC,wGACA,KAAK,QAAQ,QACb,KAAK,QAAQ,KACb,SAAS,QACT,SAAS,cAAc,MACvB,KAAK,WACN;AAED,OAAK,aAAa,kBAAkB;AACpC,QAAKA,QAAS,SAAS;;;;;;;AAQvB,OAAK,OAAO,YAAY,SAAS;;;;;;;;;;CAWnC,AAAO,UAAU,QAAwB;AACvC,YAAU,GACR,kBACA,KAAK,eAAe,kBAAkB,SACtC,gGACA,KAAK,QAAQ,QACb,KAAK,QAAQ,KACb,QAAQ,UAAU,EAClB,KAAK,WACN;AAED,OAAK,aAAa,kBAAkB;AACpC,OAAK,OAAO,UAAU,OAAO;AAC7B,QAAKA,QAAS,SAAS;;;;;;;;;;;ACrG3B,SAAgB,YAAY,KAAsB;AAChD,KAAI;AACF,MAAI,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IAAI,MAAM,KAAK;AAEzC,MAAI,UACF,eAAc,OAAO,WAAW,eAAe;AAGjD,SAAO;;;;;;ACrUX,MAAM,cAAc,OAAO,cAAc;;;;;;;;;;;;;AAczC,SAAgB,cAAc,SAAuC;AACnE,QAAO,QAAQ,IAAI,SAAS,YAAY;;AAG1C,SAAgB,cAAc,SAAkB,YAA2B;AACzE,SAAQ,IAAI,SAAS,aAAa,WAAW"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/getRawRequest-DdfaiPVH.cjs b/node_modules/@mswjs/interceptors/lib/browser/getRawRequest-DdfaiPVH.cjs new file mode 100644 index 0000000000000000000000000000000000000000..2f91b6b2a330d5979e9d1fb34d1651d5f877da77 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/getRawRequest-DdfaiPVH.cjs @@ -0,0 +1,376 @@ +let _open_draft_deferred_promise = require("@open-draft/deferred-promise"); +let outvariant = require("outvariant"); + +//#region src/InterceptorError.ts +var InterceptorError = class InterceptorError extends Error { + constructor(message) { + super(message); + this.name = "InterceptorError"; + Object.setPrototypeOf(this, InterceptorError.prototype); + } +}; + +//#endregion +//#region src/RequestController.ts +var RequestController = class RequestController { + static { + this.PENDING = 0; + } + static { + this.PASSTHROUGH = 1; + } + static { + this.RESPONSE = 2; + } + static { + this.ERROR = 3; + } + constructor(request, source) { + this.request = request; + this.source = source; + this.readyState = RequestController.PENDING; + this.handled = new _open_draft_deferred_promise.DeferredPromise(); + } + get #handled() { + return this.handled; + } + /** + * Perform this request as-is. + */ + async passthrough() { + outvariant.invariant.as(InterceptorError, this.readyState === RequestController.PENDING, "Failed to passthrough the \"%s %s\" request: the request has already been handled", this.request.method, this.request.url); + this.readyState = RequestController.PASSTHROUGH; + await this.source.passthrough(); + this.#handled.resolve(); + } + /** + * Respond to this request with the given `Response` instance. + * + * @example + * controller.respondWith(new Response()) + * controller.respondWith(Response.json({ id })) + * controller.respondWith(Response.error()) + */ + respondWith(response) { + outvariant.invariant.as(InterceptorError, this.readyState === RequestController.PENDING, "Failed to respond to the \"%s %s\" request with \"%d %s\": the request has already been handled (%d)", this.request.method, this.request.url, response.status, response.statusText || "OK", this.readyState); + this.readyState = RequestController.RESPONSE; + this.#handled.resolve(); + /** + * @note Although `source.respondWith()` is potentially asynchronous, + * do NOT await it for backward-compatibility. Awaiting it will short-circuit + * the request listener invocation as soon as a listener responds to a request. + * Ideally, that's what we want, but that's not what we promise the user. + */ + this.source.respondWith(response); + } + /** + * Error this request with the given reason. + * + * @example + * controller.errorWith() + * controller.errorWith(new Error('Oops!')) + * controller.errorWith({ message: 'Oops!'}) + */ + errorWith(reason) { + outvariant.invariant.as(InterceptorError, this.readyState === RequestController.PENDING, "Failed to error the \"%s %s\" request with \"%s\": the request has already been handled (%d)", this.request.method, this.request.url, reason?.toString(), this.readyState); + this.readyState = RequestController.ERROR; + this.source.errorWith(reason); + this.#handled.resolve(); + } +}; + +//#endregion +//#region src/utils/canParseUrl.ts +/** +* Returns a boolean indicating whether the given URL string +* can be parsed into a `URL` instance. +* A substitute for `URL.canParse()` for Node.js 18. +*/ +function canParseUrl(url) { + try { + new URL(url); + return true; + } catch (_error) { + return false; + } +} + +//#endregion +//#region src/utils/getValueBySymbol.ts +/** +* Returns the value behind the symbol with the given name. +*/ +function getValueBySymbol(symbolName, source) { + const symbol = Object.getOwnPropertySymbols(source).find((symbol$1) => { + return symbol$1.description === symbolName; + }); + if (symbol) return Reflect.get(source, symbol); +} + +//#endregion +//#region src/utils/fetchUtils.ts +var FetchRequest = class FetchRequest extends Request { + static #resolveProperty(input, init = {}, key) { + return init[key] ?? (input instanceof Request ? input[key] : void 0); + } + /** + * Check if the given request method is configurable. + * @see https://fetch.spec.whatwg.org/#methods + */ + static isConfigurableMethod(method) { + return method !== "CONNECT" && method !== "TRACE" && method !== "TRACK"; + } + static isMethodWithBody(method) { + return method !== "HEAD" && method !== "GET" && FetchRequest.isConfigurableMethod(method); + } + /** + * Check if the given request `mode` is configurable. + * @see https://fetch.spec.whatwg.org/#concept-request-mode + */ + static isConfigurableMode(mode) { + return mode !== "navigate" && mode !== "websocket" && mode !== "webtransport"; + } + constructor(input, init) { + const method = FetchRequest.#resolveProperty(input, init, "method") || "GET"; + const safeMethod = FetchRequest.isConfigurableMethod(method) ? method : "GET"; + const hasExplicitBody = init != null && "body" in init; + /** + * Only include `body` in the super init when it needs to be overridden. + * When `input` is a Request and no explicit body is in `init`, let the + * Request constructor handle body transfer naturally so it properly + * marks the original request's body as consumed (bodyUsed = true). + */ + const bodyInit = !FetchRequest.isMethodWithBody(method) ? { body: void 0 } : hasExplicitBody ? { body: init.body } : {}; + const mode = FetchRequest.#resolveProperty(input, init, "mode") ?? void 0; + const safeMode = FetchRequest.isConfigurableMode(mode) ? mode : void 0; + super(input, { + ...init || {}, + method: safeMethod, + mode: safeMode, + duplex: init?.duplex ?? (FetchRequest.isMethodWithBody(method) ? "half" : void 0), + ...bodyInit + }); + if (method !== safeMethod) this.#setInternalProperty("method", method); + if (method === "CONNECT") { + const url = new URL(input instanceof Request ? input.url : input); + let authority; + /** + * @note Node.js has a bug parsing raw CONNECT requests URLs like + * "http://127.0.0.1:1337/localhost:80". It would treat "localhost:" as a protocol. + */ + if (url.protocol === "localhost:") authority = url.href; + else authority = url.pathname.replace(/^\/+/, ""); + /** + * @note Define "url" as a getter because Undici uses their own + * logic to resolve the "request.url" property. Simply reassigning + * its value doesn't do anything. This is a destructive action + * but it's safe because "CONNECT" requests are forbidden per fetch. + */ + Object.defineProperty(this, "url", { + get: () => authority, + enumerable: true, + configurable: true + }); + } + if (mode != null && mode !== safeMode) this.#setInternalProperty("mode", mode); + } + #setInternalProperty(key, value) { + const internalState = getValueBySymbol("state", this); + if (internalState) Reflect.set(internalState, key, value); + else Object.defineProperty(this, key, { + value, + enumerable: true, + configurable: true, + writable: false + }); + } +}; +const kStatus = Symbol("kStatus"); +const kUrl = Symbol("kUrl"); +var FetchResponse = class FetchResponse extends Response { + static { + this.STATUS_CODES_WITHOUT_BODY = [ + 101, + 103, + 204, + 205, + 304 + ]; + } + static { + this.STATUS_CODES_WITH_REDIRECT = [ + 301, + 302, + 303, + 307, + 308 + ]; + } + static isConfigurableStatusCode(status) { + return status >= 200 && status <= 599; + } + static isRedirectResponse(status) { + return FetchResponse.STATUS_CODES_WITH_REDIRECT.includes(status); + } + /** + * Returns a boolean indicating whether the given response status + * code represents a response that can have a body. + */ + static isResponseWithBody(status) { + return !FetchResponse.STATUS_CODES_WITHOUT_BODY.includes(status); + } + static setStatus(status, response) { + /** + * @note Undici keeps an internal "Symbol(state)" that holds + * the actual value of response status. Update that in Node.js. + */ + const internalState = getValueBySymbol("state", response); + if (internalState) internalState.status = status; + else Object.defineProperty(response, "status", { + value: status, + enumerable: true, + configurable: true, + writable: false + }); + Object.defineProperty(response, kStatus, { + value: status, + enumerable: false + }); + } + static setUrl(url, response) { + if (!url || url === "about:" || !canParseUrl(url)) return; + const state = getValueBySymbol("state", response); + if (state) state.urlList.push(new URL(url)); + else Object.defineProperty(response, "url", { + value: url, + enumerable: true, + configurable: true, + writable: false + }); + Object.defineProperty(response, kUrl, { + value: url, + enumerable: false + }); + } + /** + * Parses the given raw HTTP headers into a Fetch API `Headers` instance. + */ + static parseRawHeaders(rawHeaders) { + const headers = new Headers(); + for (let line = 0; line < rawHeaders.length; line += 2) headers.append(rawHeaders[line], rawHeaders[line + 1]); + return headers; + } + /** + * Safely clones the given `Response`. + * Coerces response clone exceptions into 500 mocked responses. + * Handy in the environments that introduce arbitrary response + * cloning restrictions, like "101 Switching Protocols" cloning + * in "miniflare". + */ + static clone(response) { + try { + return response.clone(); + } catch (error) { + return Response.json(error instanceof Error ? { + name: error.name, + message: error.message, + stack: error.stack + } : {}, { + status: 500, + statusText: "Unclonable Response" + }); + } + } + constructor(body, init = {}) { + const status = init.status ?? 200; + const safeStatus = FetchResponse.isConfigurableStatusCode(status) ? status : 200; + const finalBody = FetchResponse.isResponseWithBody(status) ? body : null; + super(finalBody, { + status: safeStatus, + statusText: init.statusText, + headers: init.headers + }); + /** + * Since Node.js v24, Undici stores the Response state in an inaccessible field "#state". + * Forward the modified status/URL to the cloned response manually. + * @see https://github.com/nodejs/undici/blob/f734c87280e626c75f59aad55b65eb6a89cef392/lib/web/fetch/response.js#L242 + */ + if (status !== safeStatus) FetchResponse.setStatus(status, this); + FetchResponse.setUrl(init.url, this); + } + clone() { + const clonedResponse = super.clone(); + const customStatus = Reflect.get(this, kStatus); + if (customStatus) FetchResponse.setStatus(customStatus, clonedResponse); + const customUrl = Reflect.get(this, kUrl); + if (customUrl) FetchResponse.setUrl(customUrl, clonedResponse); + return clonedResponse; + } +}; + +//#endregion +//#region src/getRawRequest.ts +const kRawRequest = Symbol("kRawRequest"); +/** +* Returns a raw request instance associated with this request. +* +* @example +* interceptor.on('request', ({ request }) => { +* const rawRequest = getRawRequest(request) +* +* if (rawRequest instanceof http.ClientRequest) { +* console.log(rawRequest.rawHeaders) +* } +* }) +*/ +function getRawRequest(request) { + return Reflect.get(request, kRawRequest); +} +function setRawRequest(request, rawRequest) { + Reflect.set(request, kRawRequest, rawRequest); +} + +//#endregion +Object.defineProperty(exports, 'FetchRequest', { + enumerable: true, + get: function () { + return FetchRequest; + } +}); +Object.defineProperty(exports, 'FetchResponse', { + enumerable: true, + get: function () { + return FetchResponse; + } +}); +Object.defineProperty(exports, 'InterceptorError', { + enumerable: true, + get: function () { + return InterceptorError; + } +}); +Object.defineProperty(exports, 'RequestController', { + enumerable: true, + get: function () { + return RequestController; + } +}); +Object.defineProperty(exports, 'canParseUrl', { + enumerable: true, + get: function () { + return canParseUrl; + } +}); +Object.defineProperty(exports, 'getRawRequest', { + enumerable: true, + get: function () { + return getRawRequest; + } +}); +Object.defineProperty(exports, 'setRawRequest', { + enumerable: true, + get: function () { + return setRawRequest; + } +}); +//# sourceMappingURL=getRawRequest-DdfaiPVH.cjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/getRawRequest-DdfaiPVH.cjs.map b/node_modules/@mswjs/interceptors/lib/browser/getRawRequest-DdfaiPVH.cjs.map new file mode 100644 index 0000000000000000000000000000000000000000..dec52677684bdbfc3561a708e14cd1c157041b74 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/getRawRequest-DdfaiPVH.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"getRawRequest-DdfaiPVH.cjs","names":["request: Request","source: RequestControllerSource","DeferredPromise","#handled","symbol","#resolveProperty","bodyInit: { body?: BodyInit | null }","#setInternalProperty","authority: string"],"sources":["../../src/InterceptorError.ts","../../src/RequestController.ts","../../src/utils/canParseUrl.ts","../../src/utils/getValueBySymbol.ts","../../src/utils/fetchUtils.ts","../../src/getRawRequest.ts"],"sourcesContent":["export class InterceptorError extends Error {\n constructor(message?: string) {\n super(message)\n this.name = 'InterceptorError'\n Object.setPrototypeOf(this, InterceptorError.prototype)\n }\n}\n","import { DeferredPromise } from '@open-draft/deferred-promise'\nimport { invariant } from 'outvariant'\nimport { InterceptorError } from './InterceptorError'\n\nexport interface RequestControllerSource {\n passthrough(): void\n respondWith(response: Response): void\n errorWith(reason?: unknown): void\n}\n\nexport class RequestController {\n static PENDING = 0 as const\n static PASSTHROUGH = 1 as const\n static RESPONSE = 2 as const\n static ERROR = 3 as const\n\n public readyState: number\n\n /**\n * A Promise that resolves when this controller handles a request.\n * See `controller.readyState` for more information on the handling result.\n */\n public handled: Promise\n\n constructor(\n protected readonly request: Request,\n protected readonly source: RequestControllerSource\n ) {\n this.readyState = RequestController.PENDING\n this.handled = new DeferredPromise()\n }\n\n get #handled() {\n return this.handled as DeferredPromise\n }\n\n /**\n * Perform this request as-is.\n */\n public async passthrough(): Promise {\n invariant.as(\n InterceptorError,\n this.readyState === RequestController.PENDING,\n 'Failed to passthrough the \"%s %s\" request: the request has already been handled',\n this.request.method,\n this.request.url\n )\n\n this.readyState = RequestController.PASSTHROUGH\n await this.source.passthrough()\n this.#handled.resolve()\n }\n\n /**\n * Respond to this request with the given `Response` instance.\n *\n * @example\n * controller.respondWith(new Response())\n * controller.respondWith(Response.json({ id }))\n * controller.respondWith(Response.error())\n */\n public respondWith(response: Response): void {\n invariant.as(\n InterceptorError,\n this.readyState === RequestController.PENDING,\n 'Failed to respond to the \"%s %s\" request with \"%d %s\": the request has already been handled (%d)',\n this.request.method,\n this.request.url,\n response.status,\n response.statusText || 'OK',\n this.readyState\n )\n\n this.readyState = RequestController.RESPONSE\n this.#handled.resolve()\n\n /**\n * @note Although `source.respondWith()` is potentially asynchronous,\n * do NOT await it for backward-compatibility. Awaiting it will short-circuit\n * the request listener invocation as soon as a listener responds to a request.\n * Ideally, that's what we want, but that's not what we promise the user.\n */\n this.source.respondWith(response)\n }\n\n /**\n * Error this request with the given reason.\n *\n * @example\n * controller.errorWith()\n * controller.errorWith(new Error('Oops!'))\n * controller.errorWith({ message: 'Oops!'})\n */\n public errorWith(reason?: unknown): void {\n invariant.as(\n InterceptorError,\n this.readyState === RequestController.PENDING,\n 'Failed to error the \"%s %s\" request with \"%s\": the request has already been handled (%d)',\n this.request.method,\n this.request.url,\n reason?.toString(),\n this.readyState\n )\n\n this.readyState = RequestController.ERROR\n this.source.errorWith(reason)\n this.#handled.resolve()\n }\n}\n","/**\n * Returns a boolean indicating whether the given URL string\n * can be parsed into a `URL` instance.\n * A substitute for `URL.canParse()` for Node.js 18.\n */\nexport function canParseUrl(url: string): boolean {\n try {\n new URL(url)\n return true\n } catch (_error) {\n return false\n }\n}\n","/**\n * Returns the value behind the symbol with the given name.\n */\nexport function getValueBySymbol(\n symbolName: string,\n source: object\n): T | undefined {\n const ownSymbols = Object.getOwnPropertySymbols(source)\n\n const symbol = ownSymbols.find((symbol) => {\n return symbol.description === symbolName\n })\n\n if (symbol) {\n return Reflect.get(source, symbol)\n }\n\n return\n}\n","import { canParseUrl } from './canParseUrl'\nimport { getValueBySymbol } from './getValueBySymbol'\n\ninterface UndiciRequestState extends RequestInit {}\n\ninterface FetchRequestInit extends Omit {\n mode?: RequestMode | 'websocket' | 'webtransport'\n duplex?: 'half' | 'full'\n}\n\nexport class FetchRequest extends Request {\n static #resolveProperty(\n input: RequestInfo | URL,\n init: FetchRequestInit = {},\n key: T\n ): FetchRequestInit[T] {\n return init[key] ?? (input instanceof Request ? input[key] : undefined)\n }\n\n /**\n * Check if the given request method is configurable.\n * @see https://fetch.spec.whatwg.org/#methods\n */\n static isConfigurableMethod(method: string): boolean {\n return method !== 'CONNECT' && method !== 'TRACE' && method !== 'TRACK'\n }\n\n static isMethodWithBody(method: string): boolean {\n return (\n method !== 'HEAD' &&\n method !== 'GET' &&\n FetchRequest.isConfigurableMethod(method)\n )\n }\n\n /**\n * Check if the given request `mode` is configurable.\n * @see https://fetch.spec.whatwg.org/#concept-request-mode\n */\n static isConfigurableMode(mode: string): boolean {\n return (\n mode !== 'navigate' && mode !== 'websocket' && mode !== 'webtransport'\n )\n }\n\n constructor(input: URL | RequestInfo, init?: FetchRequestInit) {\n const method = FetchRequest.#resolveProperty(input, init, 'method') || 'GET'\n const safeMethod = FetchRequest.isConfigurableMethod(method)\n ? method\n : 'GET'\n\n const hasExplicitBody = init != null && 'body' in init\n\n /**\n * Only include `body` in the super init when it needs to be overridden.\n * When `input` is a Request and no explicit body is in `init`, let the\n * Request constructor handle body transfer naturally so it properly\n * marks the original request's body as consumed (bodyUsed = true).\n */\n const bodyInit: { body?: BodyInit | null } = !FetchRequest.isMethodWithBody(\n method\n )\n ? { body: undefined }\n : hasExplicitBody\n ? { body: init.body }\n : {}\n\n const mode =\n (FetchRequest.#resolveProperty(input, init, 'mode') as RequestMode) ??\n undefined\n const safeMode = FetchRequest.isConfigurableMode(mode) ? mode : undefined\n\n super(input, {\n ...(init || {}),\n method: safeMethod,\n mode: safeMode,\n // @ts-expect-error Untyped Node.js property.\n duplex:\n init?.duplex ??\n (FetchRequest.isMethodWithBody(method) ? 'half' : undefined),\n ...bodyInit,\n })\n\n if (method !== safeMethod) {\n this.#setInternalProperty('method', method)\n }\n\n if (method === 'CONNECT') {\n const url = new URL(input instanceof Request ? input.url : input)\n\n let authority: string\n\n /**\n * @note Node.js has a bug parsing raw CONNECT requests URLs like\n * \"http://127.0.0.1:1337/localhost:80\". It would treat \"localhost:\" as a protocol.\n */\n if (url.protocol === 'localhost:') {\n authority = url.href\n } else {\n authority = url.pathname.replace(/^\\/+/, '')\n }\n\n /**\n * @note Define \"url\" as a getter because Undici uses their own\n * logic to resolve the \"request.url\" property. Simply reassigning\n * its value doesn't do anything. This is a destructive action\n * but it's safe because \"CONNECT\" requests are forbidden per fetch.\n */\n Object.defineProperty(this, 'url', {\n get: () => authority,\n enumerable: true,\n configurable: true,\n })\n }\n\n if (mode != null && mode !== safeMode) {\n this.#setInternalProperty('mode', mode)\n }\n }\n\n #setInternalProperty(\n key: T,\n value: Request[T]\n ): void {\n const internalState = getValueBySymbol('state', this)\n\n if (internalState) {\n Reflect.set(internalState, key, value)\n } else {\n Object.defineProperty(this, key, {\n value,\n enumerable: true,\n configurable: true,\n writable: false,\n })\n }\n }\n}\n\nexport interface FetchResponseInit extends ResponseInit {\n url?: string\n}\n\ninterface UndiciResponseState {\n aborted: boolean\n rangeRequested: boolean\n timingAllowPassed: boolean\n requestIncludesCredentials: boolean\n type: ResponseType\n status: number\n statusText: string\n timingInfo: unknown\n cacheState: unknown\n headersList: Record>\n urlList: Array\n body?: {\n stream: ReadableStream\n source: unknown\n length: number\n }\n}\n\nconst kStatus = Symbol('kStatus')\nconst kUrl = Symbol('kUrl')\n\nexport class FetchResponse extends Response {\n /**\n * Response status codes for responses that cannot have body.\n * @see https://fetch.spec.whatwg.org/#statuses\n */\n static readonly STATUS_CODES_WITHOUT_BODY = [101, 103, 204, 205, 304]\n\n static readonly STATUS_CODES_WITH_REDIRECT = [301, 302, 303, 307, 308]\n\n static isConfigurableStatusCode(status: number): boolean {\n return status >= 200 && status <= 599\n }\n\n static isRedirectResponse(status: number): boolean {\n return FetchResponse.STATUS_CODES_WITH_REDIRECT.includes(status)\n }\n\n /**\n * Returns a boolean indicating whether the given response status\n * code represents a response that can have a body.\n */\n static isResponseWithBody(status: number): boolean {\n return !FetchResponse.STATUS_CODES_WITHOUT_BODY.includes(status)\n }\n\n static setStatus(status: number, response: Response): void {\n /**\n * @note Undici keeps an internal \"Symbol(state)\" that holds\n * the actual value of response status. Update that in Node.js.\n */\n const internalState = getValueBySymbol(\n 'state',\n response\n )\n\n if (internalState) {\n internalState.status = status\n } else {\n Object.defineProperty(response, 'status', {\n value: status,\n enumerable: true,\n configurable: true,\n writable: false,\n })\n }\n\n Object.defineProperty(response, kStatus, {\n value: status,\n enumerable: false,\n })\n }\n\n static setUrl(url: string | undefined, response: Response): void {\n if (!url || url === 'about:' || !canParseUrl(url)) {\n return\n }\n\n const state = getValueBySymbol('state', response)\n\n if (state) {\n // In Undici, push the URL to the internal list of URLs.\n // This will respect the `response.url` getter logic correctly.\n state.urlList.push(new URL(url))\n } else {\n // In other libraries, redefine the `url` property directly.\n Object.defineProperty(response, 'url', {\n value: url,\n enumerable: true,\n configurable: true,\n writable: false,\n })\n }\n\n Object.defineProperty(response, kUrl, {\n value: url,\n enumerable: false,\n })\n }\n\n /**\n * Parses the given raw HTTP headers into a Fetch API `Headers` instance.\n */\n static parseRawHeaders(rawHeaders: Array): Headers {\n const headers = new Headers()\n\n for (let line = 0; line < rawHeaders.length; line += 2) {\n headers.append(rawHeaders[line], rawHeaders[line + 1])\n }\n\n return headers\n }\n\n /**\n * Safely clones the given `Response`.\n * Coerces response clone exceptions into 500 mocked responses.\n * Handy in the environments that introduce arbitrary response\n * cloning restrictions, like \"101 Switching Protocols\" cloning\n * in \"miniflare\".\n */\n static clone(response: Response): Response {\n try {\n const clone = response.clone()\n return clone\n } catch (error) {\n return Response.json(\n error instanceof Error\n ? {\n name: error.name,\n message: error.message,\n stack: error.stack,\n }\n : {},\n {\n status: 500,\n statusText: 'Unclonable Response',\n }\n )\n }\n }\n\n constructor(body?: BodyInit | null, init: FetchResponseInit = {}) {\n const status = init.status ?? 200\n const safeStatus = FetchResponse.isConfigurableStatusCode(status)\n ? status\n : 200\n const finalBody = FetchResponse.isResponseWithBody(status) ? body : null\n\n super(finalBody, {\n status: safeStatus,\n statusText: init.statusText,\n headers: init.headers,\n })\n\n /**\n * Since Node.js v24, Undici stores the Response state in an inaccessible field \"#state\".\n * Forward the modified status/URL to the cloned response manually.\n * @see https://github.com/nodejs/undici/blob/f734c87280e626c75f59aad55b65eb6a89cef392/lib/web/fetch/response.js#L242\n */\n if (status !== safeStatus) {\n FetchResponse.setStatus(status, this)\n }\n\n FetchResponse.setUrl(init.url, this)\n }\n\n public clone() {\n const clonedResponse = super.clone()\n\n const customStatus = Reflect.get(this, kStatus) as number | undefined\n\n if (customStatus) {\n FetchResponse.setStatus(customStatus, clonedResponse)\n }\n\n const customUrl = Reflect.get(this, kUrl) as string | undefined\n\n if (customUrl) {\n FetchResponse.setUrl(customUrl, clonedResponse)\n }\n\n return clonedResponse\n }\n}\n","const kRawRequest = Symbol('kRawRequest')\n\n/**\n * Returns a raw request instance associated with this request.\n *\n * @example\n * interceptor.on('request', ({ request }) => {\n * const rawRequest = getRawRequest(request)\n *\n * if (rawRequest instanceof http.ClientRequest) {\n * console.log(rawRequest.rawHeaders)\n * }\n * })\n */\nexport function getRawRequest(request: Request): unknown | undefined {\n return Reflect.get(request, kRawRequest)\n}\n\nexport function setRawRequest(request: Request, rawRequest: unknown): void {\n Reflect.set(request, kRawRequest, rawRequest)\n}\n"],"mappings":";;;;AAAA,IAAa,mBAAb,MAAa,yBAAyB,MAAM;CAC1C,YAAY,SAAkB;AAC5B,QAAM,QAAQ;AACd,OAAK,OAAO;AACZ,SAAO,eAAe,MAAM,iBAAiB,UAAU;;;;;;ACM3D,IAAa,oBAAb,MAAa,kBAAkB;;iBACZ;;;qBACI;;;kBACH;;;eACH;;CAUf,YACE,AAAmBA,SACnB,AAAmBC,QACnB;EAFmB;EACA;AAEnB,OAAK,aAAa,kBAAkB;AACpC,OAAK,UAAU,IAAIC,8CAAuB;;CAG5C,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ACnD,SAAQ,OAAO,WAAW,OAAO,WAAW,OAAO,GAAG;AAGxD,SAAO;;;;;;;;;CAUT,OAAO,MAAM,UAA8B;AACzC,MAAI;AAEF,UADc,SAAS,OAAO;WAEvB,OAAO;AACd,UAAO,SAAS,KACd,iBAAiB,QACb;IACE,MAAM,MAAM;IACZ,SAAS,MAAM;IACf,OAAO,MAAM;IACd,GACD,EAAE,EACN;IACE,QAAQ;IACR,YAAY;IACb,CACF;;;CAIL,YAAY,MAAwB,OAA0B,EAAE,EAAE;EAChE,MAAM,SAAS,KAAK,UAAU;EAC9B,MAAM,aAAa,cAAc,yBAAyB,OAAO,GAC7D,SACA;EACJ,MAAM,YAAY,cAAc,mBAAmB,OAAO,GAAG,OAAO;AAEpE,QAAM,WAAW;GACf,QAAQ;GACR,YAAY,KAAK;GACjB,SAAS,KAAK;GACf,CAAC;;;;;;AAOF,MAAI,WAAW,WACb,eAAc,UAAU,QAAQ,KAAK;AAGvC,gBAAc,OAAO,KAAK,KAAK,KAAK;;CAGtC,AAAO,QAAQ;EACb,MAAM,iBAAiB,MAAM,OAAO;EAEpC,MAAM,eAAe,QAAQ,IAAI,MAAM,QAAQ;AAE/C,MAAI,aACF,eAAc,UAAU,cAAc,eAAe;EAGvD,MAAM,YAAY,QAAQ,IAAI,MAAM,KAAK;AAEzC,MAAI,UACF,eAAc,OAAO,WAAW,eAAe;AAGjD,SAAO;;;;;;ACrUX,MAAM,cAAc,OAAO,cAAc;;;;;;;;;;;;;AAczC,SAAgB,cAAc,SAAuC;AACnE,QAAO,QAAQ,IAAI,SAAS,YAAY;;AAG1C,SAAgB,cAAc,SAAkB,YAA2B;AACzE,SAAQ,IAAI,SAAS,aAAa,WAAW"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/glossary-1lhZx6Aw.d.cts b/node_modules/@mswjs/interceptors/lib/browser/glossary-1lhZx6Aw.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..2cdd51d02c58a899dc281963d270fcaedae54615 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/glossary-1lhZx6Aw.d.cts @@ -0,0 +1,69 @@ +//#region src/RequestController.d.ts +interface RequestControllerSource { + passthrough(): void; + respondWith(response: Response): void; + errorWith(reason?: unknown): void; +} +declare class RequestController { + #private; + protected readonly request: Request; + protected readonly source: RequestControllerSource; + static PENDING: 0; + static PASSTHROUGH: 1; + static RESPONSE: 2; + static ERROR: 3; + readyState: number; + /** + * A Promise that resolves when this controller handles a request. + * See `controller.readyState` for more information on the handling result. + */ + handled: Promise; + constructor(request: Request, source: RequestControllerSource); + /** + * Perform this request as-is. + */ + passthrough(): Promise; + /** + * Respond to this request with the given `Response` instance. + * + * @example + * controller.respondWith(new Response()) + * controller.respondWith(Response.json({ id })) + * controller.respondWith(Response.error()) + */ + respondWith(response: Response): void; + /** + * Error this request with the given reason. + * + * @example + * controller.errorWith() + * controller.errorWith(new Error('Oops!')) + * controller.errorWith({ message: 'Oops!'}) + */ + errorWith(reason?: unknown): void; +} +//#endregion +//#region src/glossary.d.ts +type RequestCredentials = 'omit' | 'include' | 'same-origin'; +type HttpRequestEventMap = { + request: [args: { + request: Request; + requestId: string; + controller: RequestController; + }]; + response: [args: { + response: Response; + isMockedResponse: boolean; + request: Request; + requestId: string; + }]; + unhandledException: [args: { + error: unknown; + request: Request; + requestId: string; + controller: RequestController; + }]; +}; +//#endregion +export { RequestControllerSource as i, RequestCredentials as n, RequestController as r, HttpRequestEventMap as t }; +//# sourceMappingURL=glossary-1lhZx6Aw.d.cts.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/glossary-nkHWcwvY.d.mts b/node_modules/@mswjs/interceptors/lib/browser/glossary-nkHWcwvY.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..12caee677f08acf54c98daf49b72b891c4677939 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/glossary-nkHWcwvY.d.mts @@ -0,0 +1,69 @@ +//#region src/RequestController.d.ts +interface RequestControllerSource { + passthrough(): void; + respondWith(response: Response): void; + errorWith(reason?: unknown): void; +} +declare class RequestController { + #private; + protected readonly request: Request; + protected readonly source: RequestControllerSource; + static PENDING: 0; + static PASSTHROUGH: 1; + static RESPONSE: 2; + static ERROR: 3; + readyState: number; + /** + * A Promise that resolves when this controller handles a request. + * See `controller.readyState` for more information on the handling result. + */ + handled: Promise; + constructor(request: Request, source: RequestControllerSource); + /** + * Perform this request as-is. + */ + passthrough(): Promise; + /** + * Respond to this request with the given `Response` instance. + * + * @example + * controller.respondWith(new Response()) + * controller.respondWith(Response.json({ id })) + * controller.respondWith(Response.error()) + */ + respondWith(response: Response): void; + /** + * Error this request with the given reason. + * + * @example + * controller.errorWith() + * controller.errorWith(new Error('Oops!')) + * controller.errorWith({ message: 'Oops!'}) + */ + errorWith(reason?: unknown): void; +} +//#endregion +//#region src/glossary.d.ts +type RequestCredentials = 'omit' | 'include' | 'same-origin'; +type HttpRequestEventMap = { + request: [args: { + request: Request; + requestId: string; + controller: RequestController; + }]; + response: [args: { + response: Response; + isMockedResponse: boolean; + request: Request; + requestId: string; + }]; + unhandledException: [args: { + error: unknown; + request: Request; + requestId: string; + controller: RequestController; + }]; +}; +//#endregion +export { RequestControllerSource as i, RequestCredentials as n, RequestController as r, HttpRequestEventMap as t }; +//# sourceMappingURL=glossary-nkHWcwvY.d.mts.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/handleRequest-CJim54xG.cjs b/node_modules/@mswjs/interceptors/lib/browser/handleRequest-CJim54xG.cjs new file mode 100644 index 0000000000000000000000000000000000000000..c5109dc06ce14fafcae04fc91d54dd2c31604f79 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/handleRequest-CJim54xG.cjs @@ -0,0 +1,191 @@ +const require_getRawRequest = require('./getRawRequest-DdfaiPVH.cjs'); +const require_hasConfigurableGlobal = require('./hasConfigurableGlobal-CS7adEvV.cjs'); +let _open_draft_deferred_promise = require("@open-draft/deferred-promise"); +let _open_draft_until = require("@open-draft/until"); + +//#region src/utils/isObject.ts +/** +* Determines if a given value is an instance of object. +*/ +function isObject(value, loose = false) { + return loose ? Object.prototype.toString.call(value).startsWith("[object ") : Object.prototype.toString.call(value) === "[object Object]"; +} + +//#endregion +//#region src/utils/isPropertyAccessible.ts +/** +* A function that validates if property access is possible on an object +* without throwing. It returns `true` if the property access is possible +* and `false` otherwise. +* +* Environments like miniflare will throw on property access on certain objects +* like Request and Response, for unimplemented properties. +*/ +function isPropertyAccessible(obj, key) { + try { + obj[key]; + return true; + } catch { + return false; + } +} + +//#endregion +//#region src/utils/responseUtils.ts +/** +* Creates a generic 500 Unhandled Exception response. +*/ +function createServerErrorResponse(body) { + return new Response(JSON.stringify(body instanceof Error ? { + name: body.name, + message: body.message, + stack: body.stack + } : body), { + status: 500, + statusText: "Unhandled Exception", + headers: { "Content-Type": "application/json" } + }); +} +/** +* Check if the given response is a `Response.error()`. +* +* @note Some environments, like Miniflare (Cloudflare) do not +* implement the "Response.type" property and throw on its access. +* Safely check if we can access "type" on "Response" before continuing. +* @see https://github.com/mswjs/msw/issues/1834 +*/ +function isResponseError(response) { + return response != null && response instanceof Response && isPropertyAccessible(response, "type") && response.type === "error"; +} +/** +* Check if the given value is a `Response` or a Response-like object. +* This is different from `value instanceof Response` because it supports +* custom `Response` constructors, like the one when using Undici directly. +*/ +function isResponseLike(value) { + return isObject(value, true) && isPropertyAccessible(value, "status") && isPropertyAccessible(value, "statusText") && isPropertyAccessible(value, "bodyUsed"); +} + +//#endregion +//#region src/utils/isNodeLikeError.ts +function isNodeLikeError(error) { + if (error == null) return false; + if (!(error instanceof Error)) return false; + return "code" in error && "errno" in error; +} + +//#endregion +//#region src/utils/handleRequest.ts +async function handleRequest(options) { + const handleResponse = async (response) => { + if (response instanceof Error) { + await options.controller.errorWith(response); + return true; + } + if (isResponseError(response)) { + await options.controller.respondWith(response); + return true; + } + /** + * Handle normal responses or response-like objects. + * @note This must come before the arbitrary object check + * since Response instances are, in fact, objects. + */ + if (isResponseLike(response)) { + await options.controller.respondWith(response); + return true; + } + if (isObject(response)) { + await options.controller.errorWith(response); + return true; + } + return false; + }; + const handleResponseError = async (error) => { + if (error instanceof require_getRawRequest.InterceptorError) throw result.error; + if (isNodeLikeError(error)) { + await options.controller.errorWith(error); + return true; + } + if (error instanceof Response) return await handleResponse(error); + return false; + }; + const requestAbortPromise = new _open_draft_deferred_promise.DeferredPromise(); + const onAbort = () => { + requestAbortPromise.reject(options.request.signal?.reason); + }; + /** + * @note `signal` is not always defined in React Native. + */ + if (options.request.signal) { + if (options.request.signal.aborted) { + await options.controller.errorWith(options.request.signal.reason); + return; + } + options.request.signal.addEventListener("abort", onAbort, { once: true }); + } + const result = await (0, _open_draft_until.until)(async () => { + const requestListenersPromise = require_hasConfigurableGlobal.emitAsync(options.emitter, "request", { + requestId: options.requestId, + request: options.request, + controller: options.controller + }); + await Promise.race([ + requestAbortPromise, + requestListenersPromise, + options.controller.handled + ]); + }); + options.request.signal?.removeEventListener("abort", onAbort); + if (requestAbortPromise.state === "rejected") { + await options.controller.errorWith(requestAbortPromise.rejectionReason); + return; + } + if (result.error) { + if (await handleResponseError(result.error)) return; + if (options.emitter.listenerCount("unhandledException") > 0) { + const unhandledExceptionController = new require_getRawRequest.RequestController(options.request, { + passthrough() {}, + async respondWith(response) { + await handleResponse(response); + }, + async errorWith(reason) { + /** + * @note Handle the result of the unhandled controller + * in the same way as the original request controller. + * The exception here is that thrown errors within the + * "unhandledException" event do NOT result in another + * emit of the same event. They are forwarded as-is. + */ + await options.controller.errorWith(reason); + } + }); + await require_hasConfigurableGlobal.emitAsync(options.emitter, "unhandledException", { + error: result.error, + request: options.request, + requestId: options.requestId, + controller: unhandledExceptionController + }); + if (unhandledExceptionController.readyState !== require_getRawRequest.RequestController.PENDING) return; + } + await options.controller.respondWith(createServerErrorResponse(result.error)); + return; + } + if (options.controller.readyState === require_getRawRequest.RequestController.PENDING) return await options.controller.passthrough(); + return options.controller.handled; +} + +//#endregion +Object.defineProperty(exports, 'handleRequest', { + enumerable: true, + get: function () { + return handleRequest; + } +}); +Object.defineProperty(exports, 'isResponseError', { + enumerable: true, + get: function () { + return isResponseError; + } +}); +//# sourceMappingURL=handleRequest-CJim54xG.cjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/handleRequest-CJim54xG.cjs.map b/node_modules/@mswjs/interceptors/lib/browser/handleRequest-CJim54xG.cjs.map new file mode 100644 index 0000000000000000000000000000000000000000..d96f77c4b7e3e4420760df9d643dafe078b7e7c8 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/handleRequest-CJim54xG.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"handleRequest-CJim54xG.cjs","names":["InterceptorError","DeferredPromise","emitAsync","RequestController"],"sources":["../../src/utils/isObject.ts","../../src/utils/isPropertyAccessible.ts","../../src/utils/responseUtils.ts","../../src/utils/isNodeLikeError.ts","../../src/utils/handleRequest.ts"],"sourcesContent":["/**\n * Determines if a given value is an instance of object.\n */\nexport function isObject(value: any, loose = false): value is T {\n return loose\n ? Object.prototype.toString.call(value).startsWith('[object ')\n : Object.prototype.toString.call(value) === '[object Object]'\n}\n","/**\n * A function that validates if property access is possible on an object\n * without throwing. It returns `true` if the property access is possible\n * and `false` otherwise.\n *\n * Environments like miniflare will throw on property access on certain objects\n * like Request and Response, for unimplemented properties.\n */\nexport function isPropertyAccessible>(\n obj: Obj,\n key: keyof Obj\n) {\n try {\n obj[key]\n return true\n } catch {\n return false\n }\n}\n","import { isObject } from './isObject'\nimport { isPropertyAccessible } from './isPropertyAccessible'\n\n/**\n * Creates a generic 500 Unhandled Exception response.\n */\nexport function createServerErrorResponse(body: unknown): Response {\n return new Response(\n JSON.stringify(\n body instanceof Error\n ? {\n name: body.name,\n message: body.message,\n stack: body.stack,\n }\n : body\n ),\n {\n status: 500,\n statusText: 'Unhandled Exception',\n headers: {\n 'Content-Type': 'application/json',\n },\n }\n )\n}\n\nexport type ResponseError = Response & { type: 'error' }\n\n/**\n * Check if the given response is a `Response.error()`.\n *\n * @note Some environments, like Miniflare (Cloudflare) do not\n * implement the \"Response.type\" property and throw on its access.\n * Safely check if we can access \"type\" on \"Response\" before continuing.\n * @see https://github.com/mswjs/msw/issues/1834\n */\nexport function isResponseError(response: unknown): response is ResponseError {\n return (\n response != null &&\n response instanceof Response &&\n isPropertyAccessible(response, 'type') &&\n response.type === 'error'\n )\n}\n\n/**\n * Check if the given value is a `Response` or a Response-like object.\n * This is different from `value instanceof Response` because it supports\n * custom `Response` constructors, like the one when using Undici directly.\n */\nexport function isResponseLike(value: unknown): value is Response {\n return (\n isObject>(value, true) &&\n isPropertyAccessible(value, 'status') &&\n isPropertyAccessible(value, 'statusText') &&\n isPropertyAccessible(value, 'bodyUsed')\n )\n}\n","export function isNodeLikeError(\n error: unknown\n): error is NodeJS.ErrnoException {\n if (error == null) {\n return false\n }\n\n if (!(error instanceof Error)) {\n return false\n }\n\n return 'code' in error && 'errno' in error\n}\n","import type { Emitter } from 'strict-event-emitter'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { until } from '@open-draft/until'\nimport type { HttpRequestEventMap } from '../glossary'\nimport { emitAsync } from './emitAsync'\nimport { RequestController } from '../RequestController'\nimport {\n createServerErrorResponse,\n isResponseError,\n isResponseLike,\n} from './responseUtils'\nimport { InterceptorError } from '../InterceptorError'\nimport { isNodeLikeError } from './isNodeLikeError'\nimport { isObject } from './isObject'\n\ninterface HandleRequestOptions {\n requestId: string\n request: Request\n emitter: Emitter\n controller: RequestController\n}\n\nexport async function handleRequest(\n options: HandleRequestOptions\n): Promise {\n const handleResponse = async (\n response: Response | Error | Record\n ) => {\n if (response instanceof Error) {\n await options.controller.errorWith(response)\n return true\n }\n\n // Handle \"Response.error()\" instances.\n if (isResponseError(response)) {\n await options.controller.respondWith(response)\n return true\n }\n\n /**\n * Handle normal responses or response-like objects.\n * @note This must come before the arbitrary object check\n * since Response instances are, in fact, objects.\n */\n if (isResponseLike(response)) {\n await options.controller.respondWith(response)\n return true\n }\n\n // Handle arbitrary objects provided to `.errorWith(reason)`.\n if (isObject(response)) {\n await options.controller.errorWith(response)\n return true\n }\n\n return false\n }\n\n const handleResponseError = async (error: unknown): Promise => {\n // Forward the special interceptor error instances\n // to the developer. These must not be handled in any way.\n if (error instanceof InterceptorError) {\n throw result.error\n }\n\n // Support mocking Node.js-like errors.\n if (isNodeLikeError(error)) {\n await options.controller.errorWith(error)\n return true\n }\n\n // Handle thrown responses.\n if (error instanceof Response) {\n return await handleResponse(error)\n }\n\n return false\n }\n\n // Add the last \"request\" listener to check if the request\n // has been handled in any way. If it hasn't, resolve the\n // response promise with undefined.\n // options.emitter.once('request', async ({ requestId: pendingRequestId }) => {\n // if (\n // pendingRequestId === options.requestId &&\n // options.controller.readyState === RequestController.PENDING\n // ) {\n // await options.controller.passthrough()\n // }\n // })\n\n const requestAbortPromise = new DeferredPromise()\n const onAbort = () => {\n requestAbortPromise.reject(options.request.signal?.reason)\n }\n\n /**\n * @note `signal` is not always defined in React Native.\n */\n if (options.request.signal) {\n if (options.request.signal.aborted) {\n await options.controller.errorWith(options.request.signal.reason)\n return\n }\n\n options.request.signal.addEventListener('abort', onAbort, { once: true })\n }\n\n const result = await until(async () => {\n // Emit the \"request\" event and wait until all the listeners\n // for that event are finished (e.g. async listeners awaited).\n // By the end of this promise, the developer cannot affect the\n // request anymore.\n const requestListenersPromise = emitAsync(options.emitter, 'request', {\n requestId: options.requestId,\n request: options.request,\n controller: options.controller,\n })\n\n await Promise.race([\n // Short-circuit the request handling promise if the request gets aborted.\n requestAbortPromise,\n requestListenersPromise,\n options.controller.handled,\n ])\n })\n\n options.request.signal?.removeEventListener('abort', onAbort)\n\n // Handle the request being aborted while waiting for the request listeners.\n if (requestAbortPromise.state === 'rejected') {\n await options.controller.errorWith(requestAbortPromise.rejectionReason)\n return\n }\n\n if (result.error) {\n // Handle the error during the request listener execution.\n // These can be thrown responses or request errors.\n if (await handleResponseError(result.error)) {\n return\n }\n\n // If the developer has added \"unhandledException\" listeners,\n // allow them to handle the error. They can translate it to a\n // mocked response, network error, or forward it as-is.\n if (options.emitter.listenerCount('unhandledException') > 0) {\n // Create a new request controller just for the unhandled exception case.\n // This is needed because the original controller might have been already\n // interacted with (e.g. \"respondWith\" or \"errorWith\" called on it).\n const unhandledExceptionController = new RequestController(\n options.request,\n {\n /**\n * @note Intentionally empty passthrough handle.\n * This controller is created within another controller and we only need\n * to know if `unhandledException` listeners handled the request.\n */\n passthrough() {},\n async respondWith(response) {\n await handleResponse(response)\n },\n async errorWith(reason) {\n /**\n * @note Handle the result of the unhandled controller\n * in the same way as the original request controller.\n * The exception here is that thrown errors within the\n * \"unhandledException\" event do NOT result in another\n * emit of the same event. They are forwarded as-is.\n */\n await options.controller.errorWith(reason)\n },\n }\n )\n\n await emitAsync(options.emitter, 'unhandledException', {\n error: result.error,\n request: options.request,\n requestId: options.requestId,\n controller: unhandledExceptionController,\n })\n\n // If all the \"unhandledException\" listeners have finished\n // but have not handled the request in any way, passthrough.\n if (\n unhandledExceptionController.readyState !== RequestController.PENDING\n ) {\n return\n }\n }\n\n // Otherwise, coerce unhandled exceptions to a 500 Internal Server Error response.\n await options.controller.respondWith(\n createServerErrorResponse(result.error)\n )\n return\n }\n\n // If the request hasn't been handled by this point, passthrough.\n if (options.controller.readyState === RequestController.PENDING) {\n return await options.controller.passthrough()\n }\n\n return options.controller.handled\n}\n"],"mappings":";;;;;;;;;AAGA,SAAgB,SAAY,OAAY,QAAQ,OAAmB;AACjE,QAAO,QACH,OAAO,UAAU,SAAS,KAAK,MAAM,CAAC,WAAW,WAAW,GAC5D,OAAO,UAAU,SAAS,KAAK,MAAM,KAAK;;;;;;;;;;;;;ACEhD,SAAgB,qBACd,KACA,KACA;AACA,KAAI;AACF,MAAI;AACJ,SAAO;SACD;AACN,SAAO;;;;;;;;;ACVX,SAAgB,0BAA0B,MAAyB;AACjE,QAAO,IAAI,SACT,KAAK,UACH,gBAAgB,QACZ;EACE,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G/C,QAAO,QAAQ,WAAW"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/handleRequest-CPPgsG7s.mjs b/node_modules/@mswjs/interceptors/lib/browser/handleRequest-CPPgsG7s.mjs new file mode 100644 index 0000000000000000000000000000000000000000..cd51c02a7fb76c914bf0300294128a8903d82a60 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/handleRequest-CPPgsG7s.mjs @@ -0,0 +1,180 @@ +import { o as RequestController, s as InterceptorError } from "./getRawRequest-B1BqgWG6.mjs"; +import { r as emitAsync } from "./hasConfigurableGlobal-C8zq1MCg.mjs"; +import { DeferredPromise } from "@open-draft/deferred-promise"; +import { until } from "@open-draft/until"; + +//#region src/utils/isObject.ts +/** +* Determines if a given value is an instance of object. +*/ +function isObject(value, loose = false) { + return loose ? Object.prototype.toString.call(value).startsWith("[object ") : Object.prototype.toString.call(value) === "[object Object]"; +} + +//#endregion +//#region src/utils/isPropertyAccessible.ts +/** +* A function that validates if property access is possible on an object +* without throwing. It returns `true` if the property access is possible +* and `false` otherwise. +* +* Environments like miniflare will throw on property access on certain objects +* like Request and Response, for unimplemented properties. +*/ +function isPropertyAccessible(obj, key) { + try { + obj[key]; + return true; + } catch { + return false; + } +} + +//#endregion +//#region src/utils/responseUtils.ts +/** +* Creates a generic 500 Unhandled Exception response. +*/ +function createServerErrorResponse(body) { + return new Response(JSON.stringify(body instanceof Error ? { + name: body.name, + message: body.message, + stack: body.stack + } : body), { + status: 500, + statusText: "Unhandled Exception", + headers: { "Content-Type": "application/json" } + }); +} +/** +* Check if the given response is a `Response.error()`. +* +* @note Some environments, like Miniflare (Cloudflare) do not +* implement the "Response.type" property and throw on its access. +* Safely check if we can access "type" on "Response" before continuing. +* @see https://github.com/mswjs/msw/issues/1834 +*/ +function isResponseError(response) { + return response != null && response instanceof Response && isPropertyAccessible(response, "type") && response.type === "error"; +} +/** +* Check if the given value is a `Response` or a Response-like object. +* This is different from `value instanceof Response` because it supports +* custom `Response` constructors, like the one when using Undici directly. +*/ +function isResponseLike(value) { + return isObject(value, true) && isPropertyAccessible(value, "status") && isPropertyAccessible(value, "statusText") && isPropertyAccessible(value, "bodyUsed"); +} + +//#endregion +//#region src/utils/isNodeLikeError.ts +function isNodeLikeError(error) { + if (error == null) return false; + if (!(error instanceof Error)) return false; + return "code" in error && "errno" in error; +} + +//#endregion +//#region src/utils/handleRequest.ts +async function handleRequest(options) { + const handleResponse = async (response) => { + if (response instanceof Error) { + await options.controller.errorWith(response); + return true; + } + if (isResponseError(response)) { + await options.controller.respondWith(response); + return true; + } + /** + * Handle normal responses or response-like objects. + * @note This must come before the arbitrary object check + * since Response instances are, in fact, objects. + */ + if (isResponseLike(response)) { + await options.controller.respondWith(response); + return true; + } + if (isObject(response)) { + await options.controller.errorWith(response); + return true; + } + return false; + }; + const handleResponseError = async (error) => { + if (error instanceof InterceptorError) throw result.error; + if (isNodeLikeError(error)) { + await options.controller.errorWith(error); + return true; + } + if (error instanceof Response) return await handleResponse(error); + return false; + }; + const requestAbortPromise = new DeferredPromise(); + const onAbort = () => { + requestAbortPromise.reject(options.request.signal?.reason); + }; + /** + * @note `signal` is not always defined in React Native. + */ + if (options.request.signal) { + if (options.request.signal.aborted) { + await options.controller.errorWith(options.request.signal.reason); + return; + } + options.request.signal.addEventListener("abort", onAbort, { once: true }); + } + const result = await until(async () => { + const requestListenersPromise = emitAsync(options.emitter, "request", { + requestId: options.requestId, + request: options.request, + controller: options.controller + }); + await Promise.race([ + requestAbortPromise, + requestListenersPromise, + options.controller.handled + ]); + }); + options.request.signal?.removeEventListener("abort", onAbort); + if (requestAbortPromise.state === "rejected") { + await options.controller.errorWith(requestAbortPromise.rejectionReason); + return; + } + if (result.error) { + if (await handleResponseError(result.error)) return; + if (options.emitter.listenerCount("unhandledException") > 0) { + const unhandledExceptionController = new RequestController(options.request, { + passthrough() {}, + async respondWith(response) { + await handleResponse(response); + }, + async errorWith(reason) { + /** + * @note Handle the result of the unhandled controller + * in the same way as the original request controller. + * The exception here is that thrown errors within the + * "unhandledException" event do NOT result in another + * emit of the same event. They are forwarded as-is. + */ + await options.controller.errorWith(reason); + } + }); + await emitAsync(options.emitter, "unhandledException", { + error: result.error, + request: options.request, + requestId: options.requestId, + controller: unhandledExceptionController + }); + if (unhandledExceptionController.readyState !== RequestController.PENDING) return; + } + await options.controller.respondWith(createServerErrorResponse(result.error)); + return; + } + if (options.controller.readyState === RequestController.PENDING) return await options.controller.passthrough(); + return options.controller.handled; +} + +//#endregion +export { isResponseError as n, handleRequest as t }; +//# sourceMappingURL=handleRequest-CPPgsG7s.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/handleRequest-CPPgsG7s.mjs.map b/node_modules/@mswjs/interceptors/lib/browser/handleRequest-CPPgsG7s.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..38119969a49cc61983acdb4b02130f520b9384b5 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/handleRequest-CPPgsG7s.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"handleRequest-CPPgsG7s.mjs","names":[],"sources":["../../src/utils/isObject.ts","../../src/utils/isPropertyAccessible.ts","../../src/utils/responseUtils.ts","../../src/utils/isNodeLikeError.ts","../../src/utils/handleRequest.ts"],"sourcesContent":["/**\n * Determines if a given value is an instance of object.\n */\nexport function isObject(value: any, loose = false): value is T {\n return loose\n ? Object.prototype.toString.call(value).startsWith('[object ')\n : Object.prototype.toString.call(value) === '[object Object]'\n}\n","/**\n * A function that validates if property access is possible on an object\n * without throwing. It returns `true` if the property access is possible\n * and `false` otherwise.\n *\n * Environments like miniflare will throw on property access on certain objects\n * like Request and Response, for unimplemented properties.\n */\nexport function isPropertyAccessible>(\n obj: Obj,\n key: keyof Obj\n) {\n try {\n obj[key]\n return true\n } catch {\n return false\n }\n}\n","import { isObject } from './isObject'\nimport { isPropertyAccessible } from './isPropertyAccessible'\n\n/**\n * Creates a generic 500 Unhandled Exception response.\n */\nexport function createServerErrorResponse(body: unknown): Response {\n return new Response(\n JSON.stringify(\n body instanceof Error\n ? {\n name: body.name,\n message: body.message,\n stack: body.stack,\n }\n : body\n ),\n {\n status: 500,\n statusText: 'Unhandled Exception',\n headers: {\n 'Content-Type': 'application/json',\n },\n }\n )\n}\n\nexport type ResponseError = Response & { type: 'error' }\n\n/**\n * Check if the given response is a `Response.error()`.\n *\n * @note Some environments, like Miniflare (Cloudflare) do not\n * implement the \"Response.type\" property and throw on its access.\n * Safely check if we can access \"type\" on \"Response\" before continuing.\n * @see https://github.com/mswjs/msw/issues/1834\n */\nexport function isResponseError(response: unknown): response is ResponseError {\n return (\n response != null &&\n response instanceof Response &&\n isPropertyAccessible(response, 'type') &&\n response.type === 'error'\n )\n}\n\n/**\n * Check if the given value is a `Response` or a Response-like object.\n * This is different from `value instanceof Response` because it supports\n * custom `Response` constructors, like the one when using Undici directly.\n */\nexport function isResponseLike(value: unknown): value is Response {\n return (\n isObject>(value, true) &&\n isPropertyAccessible(value, 'status') &&\n isPropertyAccessible(value, 'statusText') &&\n isPropertyAccessible(value, 'bodyUsed')\n )\n}\n","export function isNodeLikeError(\n error: unknown\n): error is NodeJS.ErrnoException {\n if (error == null) {\n return false\n }\n\n if (!(error instanceof Error)) {\n return false\n }\n\n return 'code' in error && 'errno' in error\n}\n","import type { Emitter } from 'strict-event-emitter'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { until } from '@open-draft/until'\nimport type { HttpRequestEventMap } from '../glossary'\nimport { emitAsync } from './emitAsync'\nimport { RequestController } from '../RequestController'\nimport {\n createServerErrorResponse,\n isResponseError,\n isResponseLike,\n} from './responseUtils'\nimport { InterceptorError } from '../InterceptorError'\nimport { isNodeLikeError } from './isNodeLikeError'\nimport { isObject } from './isObject'\n\ninterface HandleRequestOptions {\n requestId: string\n request: Request\n emitter: Emitter\n controller: RequestController\n}\n\nexport async function handleRequest(\n options: HandleRequestOptions\n): Promise {\n const handleResponse = async (\n response: Response | Error | Record\n ) => {\n if (response instanceof Error) {\n await options.controller.errorWith(response)\n return true\n }\n\n // Handle \"Response.error()\" instances.\n if (isResponseError(response)) {\n await options.controller.respondWith(response)\n return true\n }\n\n /**\n * Handle normal responses or response-like objects.\n * @note This must come before the arbitrary object check\n * since Response instances are, in fact, objects.\n */\n if (isResponseLike(response)) {\n await options.controller.respondWith(response)\n return true\n }\n\n // Handle arbitrary objects provided to `.errorWith(reason)`.\n if (isObject(response)) {\n await options.controller.errorWith(response)\n return true\n }\n\n return false\n }\n\n const handleResponseError = async (error: unknown): Promise => {\n // Forward the special interceptor error instances\n // to the developer. These must not be handled in any way.\n if (error instanceof InterceptorError) {\n throw result.error\n }\n\n // Support mocking Node.js-like errors.\n if (isNodeLikeError(error)) {\n await options.controller.errorWith(error)\n return true\n }\n\n // Handle thrown responses.\n if (error instanceof Response) {\n return await handleResponse(error)\n }\n\n return false\n }\n\n // Add the last \"request\" listener to check if the request\n // has been handled in any way. If it hasn't, resolve the\n // response promise with undefined.\n // options.emitter.once('request', async ({ requestId: pendingRequestId }) => {\n // if (\n // pendingRequestId === options.requestId &&\n // options.controller.readyState === RequestController.PENDING\n // ) {\n // await options.controller.passthrough()\n // }\n // })\n\n const requestAbortPromise = new DeferredPromise()\n const onAbort = () => {\n requestAbortPromise.reject(options.request.signal?.reason)\n }\n\n /**\n * @note `signal` is not always defined in React Native.\n */\n if (options.request.signal) {\n if (options.request.signal.aborted) {\n await options.controller.errorWith(options.request.signal.reason)\n return\n }\n\n options.request.signal.addEventListener('abort', onAbort, { once: true })\n }\n\n const result = await until(async () => {\n // Emit the \"request\" event and wait until all the listeners\n // for that event are finished (e.g. async listeners awaited).\n // By the end of this promise, the developer cannot affect the\n // request anymore.\n const requestListenersPromise = emitAsync(options.emitter, 'request', {\n requestId: options.requestId,\n request: options.request,\n controller: options.controller,\n })\n\n await Promise.race([\n // Short-circuit the request handling promise if the request gets aborted.\n requestAbortPromise,\n requestListenersPromise,\n options.controller.handled,\n ])\n })\n\n options.request.signal?.removeEventListener('abort', onAbort)\n\n // Handle the request being aborted while waiting for the request listeners.\n if (requestAbortPromise.state === 'rejected') {\n await options.controller.errorWith(requestAbortPromise.rejectionReason)\n return\n }\n\n if (result.error) {\n // Handle the error during the request listener execution.\n // These can be thrown responses or request errors.\n if (await handleResponseError(result.error)) {\n return\n }\n\n // If the developer has added \"unhandledException\" listeners,\n // allow them to handle the error. They can translate it to a\n // mocked response, network error, or forward it as-is.\n if (options.emitter.listenerCount('unhandledException') > 0) {\n // Create a new request controller just for the unhandled exception case.\n // This is needed because the original controller might have been already\n // interacted with (e.g. \"respondWith\" or \"errorWith\" called on it).\n const unhandledExceptionController = new RequestController(\n options.request,\n {\n /**\n * @note Intentionally empty passthrough handle.\n * This controller is created within another controller and we only need\n * to know if `unhandledException` listeners handled the request.\n */\n passthrough() {},\n async respondWith(response) {\n await handleResponse(response)\n },\n async errorWith(reason) {\n /**\n * @note Handle the result of the unhandled controller\n * in the same way as the original request controller.\n * The exception here is that thrown errors within the\n * \"unhandledException\" event do NOT result in another\n * emit of the same event. They are forwarded as-is.\n */\n await options.controller.errorWith(reason)\n },\n }\n )\n\n await emitAsync(options.emitter, 'unhandledException', {\n error: result.error,\n request: options.request,\n requestId: options.requestId,\n controller: unhandledExceptionController,\n })\n\n // If all the \"unhandledException\" listeners have finished\n // but have not handled the request in any way, passthrough.\n if (\n unhandledExceptionController.readyState !== RequestController.PENDING\n ) {\n return\n }\n }\n\n // Otherwise, coerce unhandled exceptions to a 500 Internal Server Error response.\n await options.controller.respondWith(\n createServerErrorResponse(result.error)\n )\n return\n }\n\n // If the request hasn't been handled by this point, passthrough.\n if (options.controller.readyState === RequestController.PENDING) {\n return await options.controller.passthrough()\n }\n\n return options.controller.handled\n}\n"],"mappings":";;;;;;;;;AAGA,SAAgB,SAAY,OAAY,QAAQ,OAAmB;AACjE,QAAO,QACH,OAAO,UAAU,SAAS,KAAK,MAAM,CAAC,WAAW,WAAW,GAC5D,OAAO,UAAU,SAAS,KAAK,MAA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;AAIF,OACE,6BAA6B,eAAe,kBAAkB,QAE9D;;AAKJ,QAAM,QAAQ,WAAW,YACvB,0BAA0B,OAAO,MAAM,CACxC;AACD;;AAIF,KAAI,QAAQ,WAAW,eAAe,kBAAkB,QACtD,QAAO,MAAM,QAAQ,WAAW,aAAa;AAG/C,QAAO,QAAQ,WAAW"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/hasConfigurableGlobal-C8zq1MCg.mjs b/node_modules/@mswjs/interceptors/lib/browser/hasConfigurableGlobal-C8zq1MCg.mjs new file mode 100644 index 0000000000000000000000000000000000000000..8b6f4aec35883eb4a76fd8f1ecf78b986d90aedb --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/hasConfigurableGlobal-C8zq1MCg.mjs @@ -0,0 +1,109 @@ +import { invariant } from "outvariant"; + +//#region src/utils/emitAsync.ts +/** +* Emits an event on the given emitter but executes +* the listeners sequentially. This accounts for asynchronous +* listeners (e.g. those having "sleep" and handling the request). +*/ +async function emitAsync(emitter, eventName, ...data) { + const listeners = emitter.listeners(eventName); + if (listeners.length === 0) return; + for (const listener of listeners) await listener.apply(emitter, data); +} + +//#endregion +//#region src/utils/patchesRegistry.ts +var PatchesRegistry = class { + #replacements = /* @__PURE__ */ new Map(); + applyPatch(owner, key, getNextValue) { + const ownerReplacements = this.#replacements.get(owner); + invariant(!ownerReplacements?.has(key), `Failed to replace a global value at "${String(key)}": already replaced.`); + const match = getDeepPropertyDescriptor(owner, key); + if (typeof match === "undefined") { + console.warn(`Failed to replace a global value at "${String(key)}": not a global value.`); + return () => {}; + } + if (match.descriptor.configurable) Object.defineProperty(owner, key, { + value: getNextValue(owner[key]), + enumerable: true, + configurable: true + }); + else if (match.descriptor.writable) owner[key] = getNextValue(owner[key]); + else throw new Error(`Failed to patch a non-configurable non-writable property "${key.toString()}"`); + const restorePatch = () => { + const currentReplacements = this.#replacements.get(owner); + if (!currentReplacements?.has(key)) return; + if (match.owner === owner) + /** + * @note Restoring non-configurable properties works as long as "writable: true" + * and none of the other descriptor properties except for "value" have changed. + */ + Object.defineProperty(match.owner, key, match.descriptor); + else + /** + * @todo Delete the proxy property set by the registry. + * If the match's owner isn't the original owner, the property is likely nested in the prototype. + * The registry does not meddle with those, they are left intact. + */ + Reflect.deleteProperty(owner, key); + currentReplacements.delete(key); + if (currentReplacements.size === 0) this.#replacements.delete(owner); + }; + if (ownerReplacements) ownerReplacements.set(key, restorePatch); + else this.#replacements.set(owner, new Map([[key, restorePatch]])); + return restorePatch; + } + restoreAllPatches() { + const errors = []; + for (const [, ownerReplacements] of this.#replacements) for (const [, restorePatch] of ownerReplacements) try { + restorePatch(); + } catch (error) { + if (error instanceof Error) errors.push(error); + else throw error; + } + if (errors.length > 0) throw new AggregateError(errors, "FOO!"); + } +}; +const patchesRegistry = new PatchesRegistry(); +/** +* Returns a property descriptor for the given property on the owner. +* Walks down the prototype chain if the property does not exist on the owner. +* Handy for getting a global property descriptor where `globalThis` is +* replaced with a controlled class (e.g. ServiceWorkerGlobalScope). +*/ +function getDeepPropertyDescriptor(owner, key) { + let currentOwner = owner; + let descriptor; + while (currentOwner) { + descriptor = Object.getOwnPropertyDescriptor(currentOwner, key); + if (descriptor) return { + owner: currentOwner, + descriptor + }; + currentOwner = Object.getPrototypeOf(currentOwner); + } +} + +//#endregion +//#region src/utils/hasConfigurableGlobal.ts +/** +* Returns a boolean indicating whether the given global property +* is defined and is configurable. +*/ +function hasConfigurableGlobal(propertyName) { + const match = getDeepPropertyDescriptor(globalThis, propertyName); + if (typeof match === "undefined") return false; + const { descriptor } = match; + if (typeof descriptor.get === "function" && typeof descriptor.get() === "undefined") return false; + if (typeof descriptor.get === "undefined" && descriptor.value == null) return false; + if (typeof descriptor.set === "undefined" && !descriptor.configurable) { + console.error(`[MSW] Failed to apply interceptor: the global \`${propertyName}\` property is non-configurable. This is likely an issue with your environment. If you are using a framework, please open an issue about this in their repository.`); + return false; + } + return true; +} + +//#endregion +export { patchesRegistry as n, emitAsync as r, hasConfigurableGlobal as t }; +//# sourceMappingURL=hasConfigurableGlobal-C8zq1MCg.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/hasConfigurableGlobal-C8zq1MCg.mjs.map b/node_modules/@mswjs/interceptors/lib/browser/hasConfigurableGlobal-C8zq1MCg.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..7c7ab7f6c104946d8a2af4a552ff390411e2baef --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/hasConfigurableGlobal-C8zq1MCg.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"hasConfigurableGlobal-C8zq1MCg.mjs","names":["#replacements","errors: Array","currentOwner: Owner | null","descriptor: PropertyDescriptor | undefined"],"sources":["../../src/utils/emitAsync.ts","../../src/utils/patchesRegistry.ts","../../src/utils/hasConfigurableGlobal.ts"],"sourcesContent":["import { Emitter, EventMap } from 'strict-event-emitter'\n\n/**\n * Emits an event on the given emitter but executes\n * the listeners sequentially. This accounts for asynchronous\n * listeners (e.g. those having \"sleep\" and handling the request).\n */\nexport async function emitAsync<\n Events extends EventMap,\n EventName extends keyof Events\n>(\n emitter: Emitter,\n eventName: EventName,\n ...data: Events[EventName]\n): Promise {\n const listeners = emitter.listeners(eventName)\n\n if (listeners.length === 0) {\n return\n }\n\n for (const listener of listeners) {\n await listener.apply(emitter, data)\n }\n}\n","import { invariant } from 'outvariant'\n\nclass PatchesRegistry {\n #replacements = new Map void>>()\n\n public applyPatch(\n owner: Owner,\n key: K,\n getNextValue: (realValue: Owner[K]) => Owner[K]\n ): () => void {\n const ownerReplacements = this.#replacements.get(owner)\n\n invariant(\n !ownerReplacements?.has(key),\n `Failed to replace a global value at \"${String(key)}\": already replaced.`\n )\n\n const match = getDeepPropertyDescriptor(owner, key)\n\n if (typeof match === 'undefined') {\n console.warn(\n `Failed to replace a global value at \"${String(key)}\": not a global value.`\n )\n return () => {}\n }\n\n if (match.descriptor.configurable) {\n Object.defineProperty(owner, key, {\n value: getNextValue(owner[key]),\n enumerable: true,\n configurable: true,\n })\n } else if (match.descriptor.writable) {\n owner[key] = getNextValue(owner[key])\n } else {\n throw new Error(\n `Failed to patch a non-configurable non-writable property \"${key.toString()}\"`\n )\n }\n\n const restorePatch = () => {\n const currentReplacements = this.#replacements.get(owner)\n\n if (!currentReplacements?.has(key)) {\n return\n }\n\n if (match.owner === owner) {\n /**\n * @note Restoring non-configurable properties works as long as \"writable: true\"\n * and none of the other descriptor properties except for \"value\" have changed.\n */\n Object.defineProperty(match.owner, key, match.descriptor)\n } else {\n /**\n * @todo Delete the proxy property set by the registry.\n * If the match's owner isn't the original owner, the property is likely nested in the prototype.\n * The registry does not meddle with those, they are left intact.\n */\n Reflect.deleteProperty(owner, key)\n }\n\n currentReplacements.delete(key)\n\n if (currentReplacements.size === 0) {\n this.#replacements.delete(owner)\n }\n }\n\n if (ownerReplacements) {\n ownerReplacements.set(key, restorePatch)\n } else {\n this.#replacements.set(owner, new Map([[key, restorePatch]]))\n }\n\n return restorePatch\n }\n\n public restoreAllPatches(): void {\n const errors: Array = []\n\n for (const [, ownerReplacements] of this.#replacements) {\n for (const [, restorePatch] of ownerReplacements) {\n try {\n restorePatch()\n } catch (error) {\n if (error instanceof Error) {\n errors.push(error)\n } else {\n throw error\n }\n }\n }\n }\n\n if (errors.length > 0) {\n throw new AggregateError(errors, 'FOO!')\n }\n }\n}\n\nexport const patchesRegistry = new PatchesRegistry()\n\ninterface DeepDescriptorMatch {\n owner: object\n descriptor: PropertyDescriptor\n}\n\n/**\n * Returns a property descriptor for the given property on the owner.\n * Walks down the prototype chain if the property does not exist on the owner.\n * Handy for getting a global property descriptor where `globalThis` is\n * replaced with a controlled class (e.g. ServiceWorkerGlobalScope).\n */\nexport function getDeepPropertyDescriptor(\n owner: Owner,\n key: keyof Owner\n): DeepDescriptorMatch | undefined {\n let currentOwner: Owner | null = owner\n let descriptor: PropertyDescriptor | undefined\n\n while (currentOwner) {\n descriptor = Object.getOwnPropertyDescriptor(currentOwner, key)\n\n if (descriptor) {\n return {\n owner: currentOwner,\n descriptor,\n }\n }\n\n currentOwner = Object.getPrototypeOf(currentOwner)\n }\n}\n","import { getDeepPropertyDescriptor } from './patchesRegistry'\n\n/**\n * Returns a boolean indicating whether the given global property\n * is defined and is configurable.\n */\nexport function hasConfigurableGlobal(\n propertyName: keyof typeof globalThis\n): boolean {\n const match = getDeepPropertyDescriptor(globalThis, propertyName)\n\n // The property is not set at all.\n if (typeof match === 'undefined') {\n return false\n }\n\n const { descriptor } = match\n\n // The property is set to a getter that returns undefined.\n if (\n typeof descriptor.get === 'function' &&\n typeof descriptor.get() === 'undefined'\n ) {\n return false\n }\n\n // The property is set to a value equal to undefined.\n if (typeof descriptor.get === 'undefined' && descriptor.value == null) {\n return false\n }\n\n if (typeof descriptor.set === 'undefined' && !descriptor.configurable) {\n console.error(\n `[MSW] Failed to apply interceptor: the global \\`${propertyName}\\` property is non-configurable. This is likely an issue with your environment. If you are using a framework, please open an issue about this in their repository.`\n )\n return false\n }\n\n return true\n}\n"],"mappings":";;;;;;;;AAOA,eAAsB,UAIpB,SACA,WACA,GAAG,MACY;CACf,MAAM,YAAY,QAAQ,UAAU,UAAU;AAE9C,KAAI,UAAU,WAAW,EACvB;AAGF,MAAK,MAAM,YAAY,UACrB,OAAM,SAAS,MAAM,SAAS,KAAK;;;;;ACpBvC,IAAM,kBAAN,MAAsB;CACpB,gCAAgB,IAAI,KAA2C;CAE/D,AAAO,WACL,OACA,KACA,cACY;EACZ,MAAM,oBAAoB,MAAKA,aAAc,IAAI,MAAM;AAEvD,YACE,CAAC,mBAAmB,IAAI,IAAI,EAC5B,wCAAwC,OAAO,IAAI,CAAC,sBACrD;EAED,MAAM,QAAQ,0BAA0B,OAAO,IAAI;AAEnD,MAAI,OAAO,UAAU,aAAa;AAChC,WAAQ,KACN,wCAAwC,OAAO,IAAI,CAAC,wBACrD;AACD,gBAAa;;AAGf,MAAI,MAAM,WAAW,aACnB,QAAO,eAAe,OAAO,KA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Y,aAAa;AAGjE,KAAI,OAAO,UAAU,YACnB,QAAO;CAGT,MAAM,EAAE,eAAe;AAGvB,KACE,OAAO,WAAW,QAAQ,cAC1B,OAAO,WAAW,KAAK,KAAK,YAE5B,QAAO;AAIT,KAAI,OAAO,WAAW,QAAQ,eAAe,WAAW,SAAS,KAC/D,QAAO;AAGT,KAAI,OAAO,WAAW,QAAQ,eAAe,CAAC,WAAW,cAAc;AACrE,UAAQ,MACN,mDAAmD,aAAa,oKACjE;AACD,SAAO;;AAGT,QAAO"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/hasConfigurableGlobal-CS7adEvV.cjs b/node_modules/@mswjs/interceptors/lib/browser/hasConfigurableGlobal-CS7adEvV.cjs new file mode 100644 index 0000000000000000000000000000000000000000..95cea4c2a9408dbd49520024054ad8ad31a7b36b --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/hasConfigurableGlobal-CS7adEvV.cjs @@ -0,0 +1,126 @@ +let outvariant = require("outvariant"); + +//#region src/utils/emitAsync.ts +/** +* Emits an event on the given emitter but executes +* the listeners sequentially. This accounts for asynchronous +* listeners (e.g. those having "sleep" and handling the request). +*/ +async function emitAsync(emitter, eventName, ...data) { + const listeners = emitter.listeners(eventName); + if (listeners.length === 0) return; + for (const listener of listeners) await listener.apply(emitter, data); +} + +//#endregion +//#region src/utils/patchesRegistry.ts +var PatchesRegistry = class { + #replacements = /* @__PURE__ */ new Map(); + applyPatch(owner, key, getNextValue) { + const ownerReplacements = this.#replacements.get(owner); + (0, outvariant.invariant)(!ownerReplacements?.has(key), `Failed to replace a global value at "${String(key)}": already replaced.`); + const match = getDeepPropertyDescriptor(owner, key); + if (typeof match === "undefined") { + console.warn(`Failed to replace a global value at "${String(key)}": not a global value.`); + return () => {}; + } + if (match.descriptor.configurable) Object.defineProperty(owner, key, { + value: getNextValue(owner[key]), + enumerable: true, + configurable: true + }); + else if (match.descriptor.writable) owner[key] = getNextValue(owner[key]); + else throw new Error(`Failed to patch a non-configurable non-writable property "${key.toString()}"`); + const restorePatch = () => { + const currentReplacements = this.#replacements.get(owner); + if (!currentReplacements?.has(key)) return; + if (match.owner === owner) + /** + * @note Restoring non-configurable properties works as long as "writable: true" + * and none of the other descriptor properties except for "value" have changed. + */ + Object.defineProperty(match.owner, key, match.descriptor); + else + /** + * @todo Delete the proxy property set by the registry. + * If the match's owner isn't the original owner, the property is likely nested in the prototype. + * The registry does not meddle with those, they are left intact. + */ + Reflect.deleteProperty(owner, key); + currentReplacements.delete(key); + if (currentReplacements.size === 0) this.#replacements.delete(owner); + }; + if (ownerReplacements) ownerReplacements.set(key, restorePatch); + else this.#replacements.set(owner, new Map([[key, restorePatch]])); + return restorePatch; + } + restoreAllPatches() { + const errors = []; + for (const [, ownerReplacements] of this.#replacements) for (const [, restorePatch] of ownerReplacements) try { + restorePatch(); + } catch (error) { + if (error instanceof Error) errors.push(error); + else throw error; + } + if (errors.length > 0) throw new AggregateError(errors, "FOO!"); + } +}; +const patchesRegistry = new PatchesRegistry(); +/** +* Returns a property descriptor for the given property on the owner. +* Walks down the prototype chain if the property does not exist on the owner. +* Handy for getting a global property descriptor where `globalThis` is +* replaced with a controlled class (e.g. ServiceWorkerGlobalScope). +*/ +function getDeepPropertyDescriptor(owner, key) { + let currentOwner = owner; + let descriptor; + while (currentOwner) { + descriptor = Object.getOwnPropertyDescriptor(currentOwner, key); + if (descriptor) return { + owner: currentOwner, + descriptor + }; + currentOwner = Object.getPrototypeOf(currentOwner); + } +} + +//#endregion +//#region src/utils/hasConfigurableGlobal.ts +/** +* Returns a boolean indicating whether the given global property +* is defined and is configurable. +*/ +function hasConfigurableGlobal(propertyName) { + const match = getDeepPropertyDescriptor(globalThis, propertyName); + if (typeof match === "undefined") return false; + const { descriptor } = match; + if (typeof descriptor.get === "function" && typeof descriptor.get() === "undefined") return false; + if (typeof descriptor.get === "undefined" && descriptor.value == null) return false; + if (typeof descriptor.set === "undefined" && !descriptor.configurable) { + console.error(`[MSW] Failed to apply interceptor: the global \`${propertyName}\` property is non-configurable. This is likely an issue with your environment. If you are using a framework, please open an issue about this in their repository.`); + return false; + } + return true; +} + +//#endregion +Object.defineProperty(exports, 'emitAsync', { + enumerable: true, + get: function () { + return emitAsync; + } +}); +Object.defineProperty(exports, 'hasConfigurableGlobal', { + enumerable: true, + get: function () { + return hasConfigurableGlobal; + } +}); +Object.defineProperty(exports, 'patchesRegistry', { + enumerable: true, + get: function () { + return patchesRegistry; + } +}); +//# sourceMappingURL=hasConfigurableGlobal-CS7adEvV.cjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/hasConfigurableGlobal-CS7adEvV.cjs.map b/node_modules/@mswjs/interceptors/lib/browser/hasConfigurableGlobal-CS7adEvV.cjs.map new file mode 100644 index 0000000000000000000000000000000000000000..1756e60292dd0c0c29b75397c45cc671d295d47d --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/hasConfigurableGlobal-CS7adEvV.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"hasConfigurableGlobal-CS7adEvV.cjs","names":["#replacements","errors: Array","currentOwner: Owner | null","descriptor: PropertyDescriptor | undefined"],"sources":["../../src/utils/emitAsync.ts","../../src/utils/patchesRegistry.ts","../../src/utils/hasConfigurableGlobal.ts"],"sourcesContent":["import { Emitter, EventMap } from 'strict-event-emitter'\n\n/**\n * Emits an event on the given emitter but executes\n * the listeners sequentially. This accounts for asynchronous\n * listeners (e.g. those having \"sleep\" and handling the request).\n */\nexport async function emitAsync<\n Events extends EventMap,\n EventName extends keyof Events\n>(\n emitter: Emitter,\n eventName: EventName,\n ...data: Events[EventName]\n): Promise {\n const listeners = emitter.listeners(eventName)\n\n if (listeners.length === 0) {\n return\n }\n\n for (const listener of listeners) {\n await listener.apply(emitter, data)\n }\n}\n","import { invariant } from 'outvariant'\n\nclass PatchesRegistry {\n #replacements = new Map void>>()\n\n public applyPatch(\n owner: Owner,\n key: K,\n getNextValue: (realValue: Owner[K]) => Owner[K]\n ): () => void {\n const ownerReplacements = this.#replacements.get(owner)\n\n invariant(\n !ownerReplacements?.has(key),\n `Failed to replace a global value at \"${String(key)}\": already replaced.`\n )\n\n const match = getDeepPropertyDescriptor(owner, key)\n\n if (typeof match === 'undefined') {\n console.warn(\n `Failed to replace a global value at \"${String(key)}\": not a global value.`\n )\n return () => {}\n }\n\n if (match.descriptor.configurable) {\n Object.defineProperty(owner, key, {\n value: getNextValue(owner[key]),\n enumerable: true,\n configurable: true,\n })\n } else if (match.descriptor.writable) {\n owner[key] = getNextValue(owner[key])\n } else {\n throw new Error(\n `Failed to patch a non-configurable non-writable property \"${key.toString()}\"`\n )\n }\n\n const restorePatch = () => {\n const currentReplacements = this.#replacements.get(owner)\n\n if (!currentReplacements?.has(key)) {\n return\n }\n\n if (match.owner === owner) {\n /**\n * @note Restoring non-configurable properties works as long as \"writable: true\"\n * and none of the other descriptor properties except for \"value\" have changed.\n */\n Object.defineProperty(match.owner, key, match.descriptor)\n } else {\n /**\n * @todo Delete the proxy property set by the registry.\n * If the match's owner isn't the original owner, the property is likely nested in the prototype.\n * The registry does not meddle with those, they are left intact.\n */\n Reflect.deleteProperty(owner, key)\n }\n\n currentReplacements.delete(key)\n\n if (currentReplacements.size === 0) {\n this.#replacements.delete(owner)\n }\n }\n\n if (ownerReplacements) {\n ownerReplacements.set(key, restorePatch)\n } else {\n this.#replacements.set(owner, new Map([[key, restorePatch]]))\n }\n\n return restorePatch\n }\n\n public restoreAllPatches(): void {\n const errors: Array = []\n\n for (const [, ownerReplacements] of this.#replacements) {\n for (const [, restorePatch] of ownerReplacements) {\n try {\n restorePatch()\n } catch (error) {\n if (error instanceof Error) {\n errors.push(error)\n } else {\n throw error\n }\n }\n }\n }\n\n if (errors.length > 0) {\n throw new AggregateError(errors, 'FOO!')\n }\n }\n}\n\nexport const patchesRegistry = new PatchesRegistry()\n\ninterface DeepDescriptorMatch {\n owner: object\n descriptor: PropertyDescriptor\n}\n\n/**\n * Returns a property descriptor for the given property on the owner.\n * Walks down the prototype chain if the property does not exist on the owner.\n * Handy for getting a global property descriptor where `globalThis` is\n * replaced with a controlled class (e.g. ServiceWorkerGlobalScope).\n */\nexport function getDeepPropertyDescriptor(\n owner: Owner,\n key: keyof Owner\n): DeepDescriptorMatch | undefined {\n let currentOwner: Owner | null = owner\n let descriptor: PropertyDescriptor | undefined\n\n while (currentOwner) {\n descriptor = Object.getOwnPropertyDescriptor(currentOwner, key)\n\n if (descriptor) {\n return {\n owner: currentOwner,\n descriptor,\n }\n }\n\n currentOwner = Object.getPrototypeOf(currentOwner)\n }\n}\n","import { getDeepPropertyDescriptor } from './patchesRegistry'\n\n/**\n * Returns a boolean indicating whether the given global property\n * is defined and is configurable.\n */\nexport function hasConfigurableGlobal(\n propertyName: keyof typeof globalThis\n): boolean {\n const match = getDeepPropertyDescriptor(globalThis, propertyName)\n\n // The property is not set at all.\n if (typeof match === 'undefined') {\n return false\n }\n\n const { descriptor } = match\n\n // The property is set to a getter that returns undefined.\n if (\n typeof descriptor.get === 'function' &&\n typeof descriptor.get() === 'undefined'\n ) {\n return false\n }\n\n // The property is set to a value equal to undefined.\n if (typeof descriptor.get === 'undefined' && descriptor.value == null) {\n return false\n }\n\n if (typeof descriptor.set === 'undefined' && !descriptor.configurable) {\n console.error(\n `[MSW] Failed to apply interceptor: the global \\`${propertyName}\\` property is non-configurable. This is likely an issue with your environment. If you are using a framework, please open an issue about this in their repository.`\n )\n return false\n }\n\n return true\n}\n"],"mappings":";;;;;;;;AAOA,eAAsB,UAIpB,SACA,WACA,GAAG,MACY;CACf,MAAM,YAAY,QAAQ,UAAU,UAAU;AAE9C,KAAI,UAAU,WAAW,EACvB;AAGF,MAAK,MAAM,YAAY,UACrB,OAAM,SAAS,MAAM,SAAS,KAAK;;;;;ACpBvC,IAAM,kBAAN,MAAsB;CACpB,gCAAgB,IAAI,KAA2C;CAE/D,AAAO,WACL,OACA,KACA,cACY;EACZ,MAAM,oBAAoB,MAAKA,aAAc,IAAI,MAAM;A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AAapD,SAAgB,0BACd,OACA,KACiC;CACjC,IAAIE,eAA6B;CACjC,IAAIC;AAEJ,QAAO,cAAc;AACnB,eAAa,OAAO,yBAAyB,cAAc,IAAI;AAE/D,MAAI,WACF,QAAO;GACL,OAAO;GACP;GACD;AAGH,iBAAe,OAAO,eAAe,aAAa;;;;;;;;;;AC7HtD,SAAgB,sBACd,cACS;CACT,MAAM,QAAQ,0BAA0B,YAAY,aAAa;AAGjE,KAAI,OAAO,UAAU,YACnB,QAAO;CAGT,MAAM,EAAE,eAAe;AAGvB,KACE,OAAO,WAAW,QAAQ,cAC1B,OAAO,WAAW,KAAK,KAAK,YAE5B,QAAO;AAIT,KAAI,OAAO,WAAW,QAAQ,eAAe,WAAW,SAAS,KAC/D,QAAO;AAGT,KAAI,OAAO,WAAW,QAAQ,eAAe,CAAC,WAAW,cAAc;AACrE,UAAQ,MACN,mDAAmD,aAAa,oKACjE;AACD,SAAO;;AAGT,QAAO"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/index.cjs b/node_modules/@mswjs/interceptors/lib/browser/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..7d11e3ff9d0cbc72506b4c46d1bea1987fbfdf36 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/index.cjs @@ -0,0 +1,70 @@ +const require_createRequestId = require('./createRequestId-DOf8Ktjs.cjs'); +const require_getRawRequest = require('./getRawRequest-DdfaiPVH.cjs'); +const require_bufferUtils = require('./bufferUtils-Uc0eRItL.cjs'); +const require_resolveWebSocketUrl = require('./resolveWebSocketUrl-6K6EgqsA.cjs'); + +//#region src/BatchInterceptor.ts +/** +* A batch interceptor that exposes a single interface +* to apply and operate with multiple interceptors at once. +*/ +var BatchInterceptor = class BatchInterceptor extends require_createRequestId.Interceptor { + constructor(options) { + BatchInterceptor.symbol = Symbol.for(options.name); + super(BatchInterceptor.symbol); + this.interceptors = options.interceptors; + } + setup() { + const logger = this.logger.extend("setup"); + logger.info("applying all %d interceptors...", this.interceptors.length); + for (const interceptor of this.interceptors) { + logger.info("applying \"%s\" interceptor...", interceptor.constructor.name); + interceptor.apply(); + logger.info("adding interceptor dispose subscription"); + this.subscriptions.push(() => interceptor.dispose()); + } + } + on(event, listener) { + for (const interceptor of this.interceptors) interceptor.on(event, listener); + return this; + } + once(event, listener) { + for (const interceptor of this.interceptors) interceptor.once(event, listener); + return this; + } + off(event, listener) { + for (const interceptor of this.interceptors) interceptor.off(event, listener); + return this; + } + removeAllListeners(event) { + for (const interceptors of this.interceptors) interceptors.removeAllListeners(event); + return this; + } +}; + +//#endregion +//#region src/utils/getCleanUrl.ts +/** +* Removes query parameters and hashes from a given URL. +*/ +function getCleanUrl(url, isAbsolute = true) { + return [isAbsolute && url.origin, url.pathname].filter(Boolean).join(""); +} + +//#endregion +exports.BatchInterceptor = BatchInterceptor; +exports.FetchRequest = require_getRawRequest.FetchRequest; +exports.FetchResponse = require_getRawRequest.FetchResponse; +exports.INTERNAL_REQUEST_ID_HEADER_NAME = require_createRequestId.INTERNAL_REQUEST_ID_HEADER_NAME; +exports.Interceptor = require_createRequestId.Interceptor; +exports.InterceptorReadyState = require_createRequestId.InterceptorReadyState; +exports.RequestController = require_getRawRequest.RequestController; +exports.createRequestId = require_createRequestId.createRequestId; +exports.decodeBuffer = require_bufferUtils.decodeBuffer; +exports.deleteGlobalSymbol = require_createRequestId.deleteGlobalSymbol; +exports.encodeBuffer = require_bufferUtils.encodeBuffer; +exports.getCleanUrl = getCleanUrl; +exports.getGlobalSymbol = require_createRequestId.getGlobalSymbol; +exports.getRawRequest = require_getRawRequest.getRawRequest; +exports.resolveWebSocketUrl = require_resolveWebSocketUrl.resolveWebSocketUrl; +//# sourceMappingURL=index.cjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/index.cjs.map b/node_modules/@mswjs/interceptors/lib/browser/index.cjs.map new file mode 100644 index 0000000000000000000000000000000000000000..fd646b744574eeed69e2247129170c6b4937c654 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/index.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.cjs","names":["Interceptor"],"sources":["../../src/BatchInterceptor.ts","../../src/utils/getCleanUrl.ts"],"sourcesContent":["import { EventMap, Listener } from 'strict-event-emitter'\nimport { Interceptor, ExtractEventNames } from './Interceptor'\n\nexport interface BatchInterceptorOptions<\n InterceptorList extends ReadonlyArray>,\n> {\n name: string\n interceptors: InterceptorList\n}\n\nexport type ExtractEventMapType<\n InterceptorList extends ReadonlyArray>,\n> =\n InterceptorList extends ReadonlyArray\n ? InterceptorType extends Interceptor\n ? EventMap\n : never\n : never\n\n/**\n * A batch interceptor that exposes a single interface\n * to apply and operate with multiple interceptors at once.\n */\nexport class BatchInterceptor<\n InterceptorList extends ReadonlyArray>,\n Events extends EventMap = ExtractEventMapType,\n> extends Interceptor {\n static symbol: symbol\n\n private interceptors: InterceptorList\n\n constructor(options: BatchInterceptorOptions) {\n BatchInterceptor.symbol = Symbol.for(options.name)\n super(BatchInterceptor.symbol)\n this.interceptors = options.interceptors\n }\n\n protected setup() {\n const logger = this.logger.extend('setup')\n\n logger.info('applying all %d interceptors...', this.interceptors.length)\n\n for (const interceptor of this.interceptors) {\n logger.info('applying \"%s\" interceptor...', interceptor.constructor.name)\n interceptor.apply()\n\n logger.info('adding interceptor dispose subscription')\n this.subscriptions.push(() => interceptor.dispose())\n }\n }\n\n public on>(\n event: EventName,\n listener: Listener\n ): this {\n // Instead of adding a listener to the batch interceptor,\n // propagate the listener to each of the individual interceptors.\n for (const interceptor of this.interceptors) {\n interceptor.on(event, listener)\n }\n\n return this\n }\n\n public once>(\n event: EventName,\n listener: Listener\n ): this {\n for (const interceptor of this.interceptors) {\n interceptor.once(event, listener)\n }\n\n return this\n }\n\n public off>(\n event: EventName,\n listener: Listener\n ): this {\n for (const interceptor of this.interceptors) {\n interceptor.off(event, listener)\n }\n\n return this\n }\n\n public removeAllListeners>(\n event?: EventName | undefined\n ): this {\n for (const interceptors of this.interceptors) {\n interceptors.removeAllListeners(event)\n }\n\n return this\n }\n}\n","/**\n * Removes query parameters and hashes from a given URL.\n */\nexport function getCleanUrl(url: URL, isAbsolute: boolean = true): string {\n return [isAbsolute && url.origin, url.pathname].filter(Boolean).join('')\n}\n"],"mappings":";;;;;;;;;;AAuBA,IAAa,mBAAb,MAAa,yBAGHA,oCAAoB;CAK5B,YAAY,SAAmD;AAC7D,mBAAiB,SAAS,OAAO,IAAI,QAAQ,KAAK;AAClD,QAAM,iBAAiB,OAAO;AAC9B,OAAK,eAAe,QAAQ;;CAG9B,AAAU,QAAQ;EAChB,MAAM,SAAS,KAAK,OAAO,OAAO,QAAQ;AAE1C,SAAO,KAAK,mCAAmC,KAAK,aAAa,OAAO;AAExE,OAAK,MAAM,eAAe,KAAK,cAAc;AAC3C,UAAO,KAAK,kCAAgC,YAAY,YAAY,KAAK;AACzE,eAAY,OAAO;AAEnB,UAAO,KAAK,0CAA0C;AACtD,QAAK,cAAc,WAAW,YAAY,SAAS,CAAC;;;CAIxD,AAAO,GACL,OACA,UACM;AAGN,OAAK,MAAM,eAAe,KAAK,aAC7B,aAAY,GAAG,OAAO,SAAS;AAGjC,SAAO;;CAGT,AAAO,KACL,OACA,UACM;AACN,OAAK,MAAM,eAAe,KAAK,aAC7B,aAAY,KAAK,OAAO,SAAS;AAGnC,SAAO;;CAGT,AAAO,IACL,OACA,UACM;AACN,OAAK,MAAM,eAAe,KAAK,aAC7B,aAAY,IAAI,OAAO,SAAS;AAGlC,SAAO;;CAGT,AAAO,mBACL,OACM;AACN,OAAK,MAAM,gBAAgB,KAAK,aAC9B,cAAa,mBAAmB,MAAM;AAGxC,SAAO;;;;;;;;;AC1FX,SAAgB,YAAY,KAAU,aAAsB,MAAc;AACxE,QAAO,CAAC,cAAc,IAAI,QAAQ,IAAI,SAAS,CAAC,OAAO,QAAQ,CAAC,KAAK,GAAG"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/index.d.cts b/node_modules/@mswjs/interceptors/lib/browser/index.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..32f462236724b85e5076fc2d4094fcdde4ea77cd --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/index.d.cts @@ -0,0 +1,125 @@ +import { i as RequestControllerSource, n as RequestCredentials, r as RequestController, t as HttpRequestEventMap } from "./glossary-1lhZx6Aw.cjs"; +import { a as InterceptorReadyState, c as getGlobalSymbol, i as InterceptorEventMap, n as INTERNAL_REQUEST_ID_HEADER_NAME, o as InterceptorSubscription, r as Interceptor, s as deleteGlobalSymbol, t as ExtractEventNames } from "./Interceptor-Deczogc8.cjs"; +import { EventMap, Listener } from "strict-event-emitter"; + +//#region src/BatchInterceptor.d.ts +interface BatchInterceptorOptions>> { + name: string; + interceptors: InterceptorList; +} +type ExtractEventMapType>> = InterceptorList extends ReadonlyArray ? InterceptorType extends Interceptor ? EventMap : never : never; +/** + * A batch interceptor that exposes a single interface + * to apply and operate with multiple interceptors at once. + */ +declare class BatchInterceptor>, Events extends EventMap = ExtractEventMapType> extends Interceptor { + static symbol: symbol; + private interceptors; + constructor(options: BatchInterceptorOptions); + protected setup(): void; + on>(event: EventName, listener: Listener): this; + once>(event: EventName, listener: Listener): this; + off>(event: EventName, listener: Listener): this; + removeAllListeners>(event?: EventName | undefined): this; +} +//#endregion +//#region src/createRequestId.d.ts +/** + * Generate a random ID string to represent a request. + * @example + * createRequestId() + * // "f774b6c9c600f" + */ +declare function createRequestId(): string; +//#endregion +//#region src/utils/getCleanUrl.d.ts +/** + * Removes query parameters and hashes from a given URL. + */ +declare function getCleanUrl(url: URL, isAbsolute?: boolean): string; +//#endregion +//#region src/utils/bufferUtils.d.ts +declare function encodeBuffer(text: string): Uint8Array; +declare function decodeBuffer(buffer: ArrayBuffer, encoding?: string): string; +//#endregion +//#region src/utils/fetchUtils.d.ts +interface FetchRequestInit extends Omit { + mode?: RequestMode | 'websocket' | 'webtransport'; + duplex?: 'half' | 'full'; +} +declare class FetchRequest extends Request { + #private; + /** + * Check if the given request method is configurable. + * @see https://fetch.spec.whatwg.org/#methods + */ + static isConfigurableMethod(method: string): boolean; + static isMethodWithBody(method: string): boolean; + /** + * Check if the given request `mode` is configurable. + * @see https://fetch.spec.whatwg.org/#concept-request-mode + */ + static isConfigurableMode(mode: string): boolean; + constructor(input: URL | RequestInfo, init?: FetchRequestInit); +} +interface FetchResponseInit extends ResponseInit { + url?: string; +} +declare class FetchResponse extends Response { + /** + * Response status codes for responses that cannot have body. + * @see https://fetch.spec.whatwg.org/#statuses + */ + static readonly STATUS_CODES_WITHOUT_BODY: number[]; + static readonly STATUS_CODES_WITH_REDIRECT: number[]; + static isConfigurableStatusCode(status: number): boolean; + static isRedirectResponse(status: number): boolean; + /** + * Returns a boolean indicating whether the given response status + * code represents a response that can have a body. + */ + static isResponseWithBody(status: number): boolean; + static setStatus(status: number, response: Response): void; + static setUrl(url: string | undefined, response: Response): void; + /** + * Parses the given raw HTTP headers into a Fetch API `Headers` instance. + */ + static parseRawHeaders(rawHeaders: Array): Headers; + /** + * Safely clones the given `Response`. + * Coerces response clone exceptions into 500 mocked responses. + * Handy in the environments that introduce arbitrary response + * cloning restrictions, like "101 Switching Protocols" cloning + * in "miniflare". + */ + static clone(response: Response): Response; + constructor(body?: BodyInit | null, init?: FetchResponseInit); + clone(): Response; +} +//#endregion +//#region src/getRawRequest.d.ts +/** + * Returns a raw request instance associated with this request. + * + * @example + * interceptor.on('request', ({ request }) => { + * const rawRequest = getRawRequest(request) + * + * if (rawRequest instanceof http.ClientRequest) { + * console.log(rawRequest.rawHeaders) + * } + * }) + */ +declare function getRawRequest(request: Request): unknown | undefined; +//#endregion +//#region src/utils/resolveWebSocketUrl.d.ts +/** + * Resolve potentially relative WebSocket URLs the same way + * the browser does (replace the protocol, use the origin, etc). + * + * @see https://websockets.spec.whatwg.org//#dom-websocket-websocket + */ +declare function resolveWebSocketUrl(url: string | URL): string; +//#endregion +export { BatchInterceptor, BatchInterceptorOptions, ExtractEventMapType, ExtractEventNames, FetchRequest, FetchResponse, HttpRequestEventMap, INTERNAL_REQUEST_ID_HEADER_NAME, Interceptor, InterceptorEventMap, InterceptorReadyState, InterceptorSubscription, RequestController, type RequestControllerSource, RequestCredentials, createRequestId, decodeBuffer, deleteGlobalSymbol, encodeBuffer, getCleanUrl, getGlobalSymbol, getRawRequest, resolveWebSocketUrl }; +//# sourceMappingURL=index.d.cts.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/index.d.mts b/node_modules/@mswjs/interceptors/lib/browser/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..c57354b120639b7ad3b92e6f6db56b69b8b5ee45 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/index.d.mts @@ -0,0 +1,125 @@ +import { i as RequestControllerSource, n as RequestCredentials, r as RequestController, t as HttpRequestEventMap } from "./glossary-nkHWcwvY.mjs"; +import { a as InterceptorReadyState, c as getGlobalSymbol, i as InterceptorEventMap, n as INTERNAL_REQUEST_ID_HEADER_NAME, o as InterceptorSubscription, r as Interceptor, s as deleteGlobalSymbol, t as ExtractEventNames } from "./Interceptor-gqKgs-aF.mjs"; +import { EventMap, Listener } from "strict-event-emitter"; + +//#region src/BatchInterceptor.d.ts +interface BatchInterceptorOptions>> { + name: string; + interceptors: InterceptorList; +} +type ExtractEventMapType>> = InterceptorList extends ReadonlyArray ? InterceptorType extends Interceptor ? EventMap : never : never; +/** + * A batch interceptor that exposes a single interface + * to apply and operate with multiple interceptors at once. + */ +declare class BatchInterceptor>, Events extends EventMap = ExtractEventMapType> extends Interceptor { + static symbol: symbol; + private interceptors; + constructor(options: BatchInterceptorOptions); + protected setup(): void; + on>(event: EventName, listener: Listener): this; + once>(event: EventName, listener: Listener): this; + off>(event: EventName, listener: Listener): this; + removeAllListeners>(event?: EventName | undefined): this; +} +//#endregion +//#region src/createRequestId.d.ts +/** + * Generate a random ID string to represent a request. + * @example + * createRequestId() + * // "f774b6c9c600f" + */ +declare function createRequestId(): string; +//#endregion +//#region src/utils/getCleanUrl.d.ts +/** + * Removes query parameters and hashes from a given URL. + */ +declare function getCleanUrl(url: URL, isAbsolute?: boolean): string; +//#endregion +//#region src/utils/bufferUtils.d.ts +declare function encodeBuffer(text: string): Uint8Array; +declare function decodeBuffer(buffer: ArrayBuffer, encoding?: string): string; +//#endregion +//#region src/utils/fetchUtils.d.ts +interface FetchRequestInit extends Omit { + mode?: RequestMode | 'websocket' | 'webtransport'; + duplex?: 'half' | 'full'; +} +declare class FetchRequest extends Request { + #private; + /** + * Check if the given request method is configurable. + * @see https://fetch.spec.whatwg.org/#methods + */ + static isConfigurableMethod(method: string): boolean; + static isMethodWithBody(method: string): boolean; + /** + * Check if the given request `mode` is configurable. + * @see https://fetch.spec.whatwg.org/#concept-request-mode + */ + static isConfigurableMode(mode: string): boolean; + constructor(input: URL | RequestInfo, init?: FetchRequestInit); +} +interface FetchResponseInit extends ResponseInit { + url?: string; +} +declare class FetchResponse extends Response { + /** + * Response status codes for responses that cannot have body. + * @see https://fetch.spec.whatwg.org/#statuses + */ + static readonly STATUS_CODES_WITHOUT_BODY: number[]; + static readonly STATUS_CODES_WITH_REDIRECT: number[]; + static isConfigurableStatusCode(status: number): boolean; + static isRedirectResponse(status: number): boolean; + /** + * Returns a boolean indicating whether the given response status + * code represents a response that can have a body. + */ + static isResponseWithBody(status: number): boolean; + static setStatus(status: number, response: Response): void; + static setUrl(url: string | undefined, response: Response): void; + /** + * Parses the given raw HTTP headers into a Fetch API `Headers` instance. + */ + static parseRawHeaders(rawHeaders: Array): Headers; + /** + * Safely clones the given `Response`. + * Coerces response clone exceptions into 500 mocked responses. + * Handy in the environments that introduce arbitrary response + * cloning restrictions, like "101 Switching Protocols" cloning + * in "miniflare". + */ + static clone(response: Response): Response; + constructor(body?: BodyInit | null, init?: FetchResponseInit); + clone(): Response; +} +//#endregion +//#region src/getRawRequest.d.ts +/** + * Returns a raw request instance associated with this request. + * + * @example + * interceptor.on('request', ({ request }) => { + * const rawRequest = getRawRequest(request) + * + * if (rawRequest instanceof http.ClientRequest) { + * console.log(rawRequest.rawHeaders) + * } + * }) + */ +declare function getRawRequest(request: Request): unknown | undefined; +//#endregion +//#region src/utils/resolveWebSocketUrl.d.ts +/** + * Resolve potentially relative WebSocket URLs the same way + * the browser does (replace the protocol, use the origin, etc). + * + * @see https://websockets.spec.whatwg.org//#dom-websocket-websocket + */ +declare function resolveWebSocketUrl(url: string | URL): string; +//#endregion +export { BatchInterceptor, BatchInterceptorOptions, ExtractEventMapType, ExtractEventNames, FetchRequest, FetchResponse, HttpRequestEventMap, INTERNAL_REQUEST_ID_HEADER_NAME, Interceptor, InterceptorEventMap, InterceptorReadyState, InterceptorSubscription, RequestController, type RequestControllerSource, RequestCredentials, createRequestId, decodeBuffer, deleteGlobalSymbol, encodeBuffer, getCleanUrl, getGlobalSymbol, getRawRequest, resolveWebSocketUrl }; +//# sourceMappingURL=index.d.mts.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/index.mjs b/node_modules/@mswjs/interceptors/lib/browser/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..240a72315e15f26e14bf6de9faf26cc6f995e3b1 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/index.mjs @@ -0,0 +1,56 @@ +import { a as deleteGlobalSymbol, i as InterceptorReadyState, n as INTERNAL_REQUEST_ID_HEADER_NAME, o as getGlobalSymbol, r as Interceptor, t as createRequestId } from "./createRequestId-DYCsFHOi.mjs"; +import { i as FetchResponse, o as RequestController, r as FetchRequest, t as getRawRequest } from "./getRawRequest-B1BqgWG6.mjs"; +import { n as encodeBuffer, t as decodeBuffer } from "./bufferUtils-BiiO6HZv.mjs"; +import { t as resolveWebSocketUrl } from "./resolveWebSocketUrl-C83-x9iE.mjs"; + +//#region src/BatchInterceptor.ts +/** +* A batch interceptor that exposes a single interface +* to apply and operate with multiple interceptors at once. +*/ +var BatchInterceptor = class BatchInterceptor extends Interceptor { + constructor(options) { + BatchInterceptor.symbol = Symbol.for(options.name); + super(BatchInterceptor.symbol); + this.interceptors = options.interceptors; + } + setup() { + const logger = this.logger.extend("setup"); + logger.info("applying all %d interceptors...", this.interceptors.length); + for (const interceptor of this.interceptors) { + logger.info("applying \"%s\" interceptor...", interceptor.constructor.name); + interceptor.apply(); + logger.info("adding interceptor dispose subscription"); + this.subscriptions.push(() => interceptor.dispose()); + } + } + on(event, listener) { + for (const interceptor of this.interceptors) interceptor.on(event, listener); + return this; + } + once(event, listener) { + for (const interceptor of this.interceptors) interceptor.once(event, listener); + return this; + } + off(event, listener) { + for (const interceptor of this.interceptors) interceptor.off(event, listener); + return this; + } + removeAllListeners(event) { + for (const interceptors of this.interceptors) interceptors.removeAllListeners(event); + return this; + } +}; + +//#endregion +//#region src/utils/getCleanUrl.ts +/** +* Removes query parameters and hashes from a given URL. +*/ +function getCleanUrl(url, isAbsolute = true) { + return [isAbsolute && url.origin, url.pathname].filter(Boolean).join(""); +} + +//#endregion +export { BatchInterceptor, FetchRequest, FetchResponse, INTERNAL_REQUEST_ID_HEADER_NAME, Interceptor, InterceptorReadyState, RequestController, createRequestId, decodeBuffer, deleteGlobalSymbol, encodeBuffer, getCleanUrl, getGlobalSymbol, getRawRequest, resolveWebSocketUrl }; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/index.mjs.map b/node_modules/@mswjs/interceptors/lib/browser/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..4045a2949de76907fb56ae7f13f4cdfc411274f3 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.mjs","names":[],"sources":["../../src/BatchInterceptor.ts","../../src/utils/getCleanUrl.ts"],"sourcesContent":["import { EventMap, Listener } from 'strict-event-emitter'\nimport { Interceptor, ExtractEventNames } from './Interceptor'\n\nexport interface BatchInterceptorOptions<\n InterceptorList extends ReadonlyArray>,\n> {\n name: string\n interceptors: InterceptorList\n}\n\nexport type ExtractEventMapType<\n InterceptorList extends ReadonlyArray>,\n> =\n InterceptorList extends ReadonlyArray\n ? InterceptorType extends Interceptor\n ? EventMap\n : never\n : never\n\n/**\n * A batch interceptor that exposes a single interface\n * to apply and operate with multiple interceptors at once.\n */\nexport class BatchInterceptor<\n InterceptorList extends ReadonlyArray>,\n Events extends EventMap = ExtractEventMapType,\n> extends Interceptor {\n static symbol: symbol\n\n private interceptors: InterceptorList\n\n constructor(options: BatchInterceptorOptions) {\n BatchInterceptor.symbol = Symbol.for(options.name)\n super(BatchInterceptor.symbol)\n this.interceptors = options.interceptors\n }\n\n protected setup() {\n const logger = this.logger.extend('setup')\n\n logger.info('applying all %d interceptors...', this.interceptors.length)\n\n for (const interceptor of this.interceptors) {\n logger.info('applying \"%s\" interceptor...', interceptor.constructor.name)\n interceptor.apply()\n\n logger.info('adding interceptor dispose subscription')\n this.subscriptions.push(() => interceptor.dispose())\n }\n }\n\n public on>(\n event: EventName,\n listener: Listener\n ): this {\n // Instead of adding a listener to the batch interceptor,\n // propagate the listener to each of the individual interceptors.\n for (const interceptor of this.interceptors) {\n interceptor.on(event, listener)\n }\n\n return this\n }\n\n public once>(\n event: EventName,\n listener: Listener\n ): this {\n for (const interceptor of this.interceptors) {\n interceptor.once(event, listener)\n }\n\n return this\n }\n\n public off>(\n event: EventName,\n listener: Listener\n ): this {\n for (const interceptor of this.interceptors) {\n interceptor.off(event, listener)\n }\n\n return this\n }\n\n public removeAllListeners>(\n event?: EventName | undefined\n ): this {\n for (const interceptors of this.interceptors) {\n interceptors.removeAllListeners(event)\n }\n\n return this\n }\n}\n","/**\n * Removes query parameters and hashes from a given URL.\n */\nexport function getCleanUrl(url: URL, isAbsolute: boolean = true): string {\n return [isAbsolute && url.origin, url.pathname].filter(Boolean).join('')\n}\n"],"mappings":";;;;;;;;;;AAuBA,IAAa,mBAAb,MAAa,yBAGH,YAAoB;CAK5B,YAAY,SAAmD;AAC7D,mBAAiB,SAAS,OAAO,IAAI,QAAQ,KAAK;AAClD,QAAM,iBAAiB,OAAO;AAC9B,OAAK,eAAe,QAAQ;;CAG9B,AAAU,QAAQ;EAChB,MAAM,SAAS,KAAK,OAAO,OAAO,QAAQ;AAE1C,SAAO,KAAK,mCAAmC,KAAK,aAAa,OAAO;AAExE,OAAK,MAAM,eAAe,KAAK,cAAc;AAC3C,UAAO,KAAK,kCAAgC,YAAY,YAAY,KAAK;AACzE,eAAY,OAAO;AAEnB,UAAO,KAAK,0CAA0C;AACtD,QAAK,cAAc,WAAW,YAAY,SAAS,CAAC;;;CAIxD,AAAO,GACL,OACA,UACM;AAGN,OAAK,MAAM,eAAe,KAAK,aAC7B,aAAY,GAAG,OAAO,SAAS;AAGjC,SAAO;;CAGT,AAAO,KACL,OACA,UACM;AACN,OAAK,MAAM,eAAe,KAAK,aAC7B,aAAY,KAAK,OAAO,SAAS;AAGnC,SAAO;;CAGT,AAAO,IACL,OACA,UACM;AACN,OAAK,MAAM,eAAe,KAAK,aAC7B,aAAY,IAAI,OAAO,SAAS;AAGlC,SAAO;;CAGT,AAAO,mBACL,OACM;AACN,OAAK,MAAM,gBAAgB,KAAK,aAC9B,cAAa,mBAAmB,MAAM;AAGxC,SAAO;;;;;;;;;AC1FX,SAAgB,YAAY,KAAU,aAAsB,MAAc;AACxE,QAAO,CAAC,cAAc,IAAI,QAAQ,IAAI,SAAS,CAAC,OAAO,QAAQ,CAAC,KAAK,GAAG"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/interceptors/WebSocket/index.cjs b/node_modules/@mswjs/interceptors/lib/browser/interceptors/WebSocket/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..5b812215fb84763df78386ccec2a35065666d3ed --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/interceptors/WebSocket/index.cjs @@ -0,0 +1,618 @@ +const require_createRequestId = require('../../createRequestId-DOf8Ktjs.cjs'); +const require_resolveWebSocketUrl = require('../../resolveWebSocketUrl-6K6EgqsA.cjs'); +const require_hasConfigurableGlobal = require('../../hasConfigurableGlobal-CS7adEvV.cjs'); +let _open_draft_deferred_promise = require("@open-draft/deferred-promise"); +let outvariant = require("outvariant"); + +//#region src/interceptors/WebSocket/utils/bindEvent.ts +function bindEvent(target, event) { + Object.defineProperties(event, { + target: { + value: target, + enumerable: true, + writable: true + }, + currentTarget: { + value: target, + enumerable: true, + writable: true + } + }); + return event; +} + +//#endregion +//#region src/interceptors/WebSocket/utils/events.ts +const kCancelable = Symbol("kCancelable"); +const kDefaultPrevented = Symbol("kDefaultPrevented"); +/** +* A `MessageEvent` superset that supports event cancellation +* in Node.js. It's rather non-intrusive so it can be safely +* used in the browser as well. +* +* @see https://github.com/nodejs/node/issues/51767 +*/ +var CancelableMessageEvent = class extends MessageEvent { + constructor(type, init) { + super(type, init); + this[kCancelable] = !!init.cancelable; + this[kDefaultPrevented] = false; + } + get cancelable() { + return this[kCancelable]; + } + set cancelable(nextCancelable) { + this[kCancelable] = nextCancelable; + } + get defaultPrevented() { + return this[kDefaultPrevented]; + } + set defaultPrevented(nextDefaultPrevented) { + this[kDefaultPrevented] = nextDefaultPrevented; + } + preventDefault() { + if (this.cancelable && !this[kDefaultPrevented]) this[kDefaultPrevented] = true; + } +}; +var CloseEvent = class extends Event { + constructor(type, init = {}) { + super(type, init); + this.code = init.code === void 0 ? 0 : init.code; + this.reason = init.reason === void 0 ? "" : init.reason; + this.wasClean = init.wasClean === void 0 ? false : init.wasClean; + } +}; +var CancelableCloseEvent = class extends CloseEvent { + constructor(type, init = {}) { + super(type, init); + this[kCancelable] = !!init.cancelable; + this[kDefaultPrevented] = false; + } + get cancelable() { + return this[kCancelable]; + } + set cancelable(nextCancelable) { + this[kCancelable] = nextCancelable; + } + get defaultPrevented() { + return this[kDefaultPrevented]; + } + set defaultPrevented(nextDefaultPrevented) { + this[kDefaultPrevented] = nextDefaultPrevented; + } + preventDefault() { + if (this.cancelable && !this[kDefaultPrevented]) this[kDefaultPrevented] = true; + } +}; + +//#endregion +//#region src/interceptors/WebSocket/WebSocketClientConnection.ts +const kEmitter$1 = Symbol("kEmitter"); +const kBoundListener$1 = Symbol("kBoundListener"); +var WebSocketClientConnectionProtocol = class {}; +/** +* The WebSocket client instance represents an incoming +* client connection. The user can control the connection, +* send and receive events. +*/ +var WebSocketClientConnection = class { + constructor(socket, transport) { + this.socket = socket; + this.transport = transport; + this.id = require_createRequestId.createRequestId(); + this.url = new URL(socket.url); + this[kEmitter$1] = new EventTarget(); + this.transport.addEventListener("outgoing", (event) => { + const message = bindEvent(this.socket, new CancelableMessageEvent("message", { + data: event.data, + origin: event.origin, + cancelable: true + })); + this[kEmitter$1].dispatchEvent(message); + if (message.defaultPrevented) event.preventDefault(); + }); + /** + * Emit the "close" event on the "client" connection + * whenever the underlying transport is closed. + * @note "client.close()" does NOT dispatch the "close" + * event on the WebSocket because it uses non-configurable + * close status code. Thus, we listen to the transport + * instead of the WebSocket's "close" event. + */ + this.transport.addEventListener("close", (event) => { + this[kEmitter$1].dispatchEvent(bindEvent(this.socket, new CloseEvent("close", event))); + }); + } + /** + * Listen for the outgoing events from the connected WebSocket client. + */ + addEventListener(type, listener, options) { + if (!Reflect.has(listener, kBoundListener$1)) { + const boundListener = listener.bind(this.socket); + Object.defineProperty(listener, kBoundListener$1, { + value: boundListener, + enumerable: false, + configurable: false + }); + } + this[kEmitter$1].addEventListener(type, Reflect.get(listener, kBoundListener$1), options); + } + /** + * Removes the listener for the given event. + */ + removeEventListener(event, listener, options) { + this[kEmitter$1].removeEventListener(event, Reflect.get(listener, kBoundListener$1), options); + } + /** + * Send data to the connected client. + */ + send(data) { + this.transport.send(data); + } + /** + * Close the WebSocket connection. + * @param {number} code A status code (see https://www.rfc-editor.org/rfc/rfc6455#section-7.4.1). + * @param {string} reason A custom connection close reason. + */ + close(code, reason) { + this.transport.close(code, reason); + } +}; + +//#endregion +//#region src/interceptors/WebSocket/WebSocketOverride.ts +const WEBSOCKET_CLOSE_CODE_RANGE_ERROR = "InvalidAccessError: close code out of user configurable range"; +const kPassthroughPromise = Symbol("kPassthroughPromise"); +const kOnSend = Symbol("kOnSend"); +const kClose = Symbol("kClose"); +var WebSocketOverride = class extends EventTarget { + static { + this.CONNECTING = 0; + } + static { + this.OPEN = 1; + } + static { + this.CLOSING = 2; + } + static { + this.CLOSED = 3; + } + constructor(url, protocols) { + super(); + this.CONNECTING = 0; + this.OPEN = 1; + this.CLOSING = 2; + this.CLOSED = 3; + this._onopen = null; + this._onmessage = null; + this._onerror = null; + this._onclose = null; + this.url = require_resolveWebSocketUrl.resolveWebSocketUrl(url); + this.protocol = ""; + this.extensions = ""; + this.binaryType = "blob"; + this.readyState = this.CONNECTING; + this.bufferedAmount = 0; + this[kPassthroughPromise] = new _open_draft_deferred_promise.DeferredPromise(); + queueMicrotask(async () => { + if (await this[kPassthroughPromise]) return; + this.protocol = typeof protocols === "string" ? protocols : Array.isArray(protocols) && protocols.length > 0 ? protocols[0] : ""; + /** + * @note Check that nothing has prevented this connection + * (e.g. called `client.close()` in the connection listener). + * If the connection has been prevented, never dispatch the open event,. + */ + if (this.readyState === this.CONNECTING) { + this.readyState = this.OPEN; + this.dispatchEvent(bindEvent(this, new Event("open"))); + } + }); + } + set onopen(listener) { + this.removeEventListener("open", this._onopen); + this._onopen = listener; + if (listener !== null) this.addEventListener("open", listener); + } + get onopen() { + return this._onopen; + } + set onmessage(listener) { + this.removeEventListener("message", this._onmessage); + this._onmessage = listener; + if (listener !== null) this.addEventListener("message", listener); + } + get onmessage() { + return this._onmessage; + } + set onerror(listener) { + this.removeEventListener("error", this._onerror); + this._onerror = listener; + if (listener !== null) this.addEventListener("error", listener); + } + get onerror() { + return this._onerror; + } + set onclose(listener) { + this.removeEventListener("close", this._onclose); + this._onclose = listener; + if (listener !== null) this.addEventListener("close", listener); + } + get onclose() { + return this._onclose; + } + /** + * @see https://websockets.spec.whatwg.org/#ref-for-dom-websocket-send%E2%91%A0 + */ + send(data) { + if (this.readyState === this.CONNECTING) { + this.close(); + throw new DOMException("InvalidStateError"); + } + if (this.readyState === this.CLOSING || this.readyState === this.CLOSED) return; + this.bufferedAmount += getDataSize(data); + queueMicrotask(() => { + this.bufferedAmount = 0; + /** + * @note Notify the parent about outgoing data. + * This notifies the transport and the connection + * listens to the outgoing data to emit the "message" event. + */ + this[kOnSend]?.(data); + }); + } + close(code = 1e3, reason) { + (0, outvariant.invariant)(code, WEBSOCKET_CLOSE_CODE_RANGE_ERROR); + (0, outvariant.invariant)(code === 1e3 || code >= 3e3 && code <= 4999, WEBSOCKET_CLOSE_CODE_RANGE_ERROR); + this[kClose](code, reason); + } + [kClose](code = 1e3, reason, wasClean = true) { + /** + * @note Move this check here so that even internal closures, + * like those triggered by the `server` connection, are not + * performed twice. + */ + if (this.readyState === this.CLOSING || this.readyState === this.CLOSED) return; + this.readyState = this.CLOSING; + queueMicrotask(() => { + this.readyState = this.CLOSED; + this.dispatchEvent(bindEvent(this, new CloseEvent("close", { + code, + reason, + wasClean + }))); + this._onopen = null; + this._onmessage = null; + this._onerror = null; + this._onclose = null; + }); + } + addEventListener(type, listener, options) { + return super.addEventListener(type, listener, options); + } + removeEventListener(type, callback, options) { + return super.removeEventListener(type, callback, options); + } +}; +function getDataSize(data) { + if (typeof data === "string") return data.length; + if (data instanceof Blob) return data.size; + return data.byteLength; +} + +//#endregion +//#region src/interceptors/WebSocket/WebSocketServerConnection.ts +const kEmitter = Symbol("kEmitter"); +const kBoundListener = Symbol("kBoundListener"); +const kSend = Symbol("kSend"); +var WebSocketServerConnectionProtocol = class {}; +/** +* The WebSocket server instance represents the actual production +* WebSocket server connection. It's idle by default but you can +* establish it by calling `server.connect()`. +*/ +var WebSocketServerConnection = class { + constructor(client, transport, createConnection) { + this.client = client; + this.transport = transport; + this.createConnection = createConnection; + this[kEmitter] = new EventTarget(); + this.mockCloseController = new AbortController(); + this.realCloseController = new AbortController(); + this.transport.addEventListener("outgoing", (event) => { + if (typeof this.realWebSocket === "undefined") return; + queueMicrotask(() => { + if (!event.defaultPrevented) + /** + * @note Use the internal send mechanism so consumers can tell + * apart direct user calls to `server.send()` and internal calls. + * E.g. MSW has to ignore this internal call to log out messages correctly. + */ + this[kSend](event.data); + }); + }); + this.transport.addEventListener("incoming", this.handleIncomingMessage.bind(this)); + } + /** + * The `WebSocket` instance connected to the original server. + * Accessing this before calling `server.connect()` will throw. + */ + get socket() { + (0, outvariant.invariant)(this.realWebSocket, "Cannot access \"socket\" on the original WebSocket server object: the connection is not open. Did you forget to call `server.connect()`?"); + return this.realWebSocket; + } + /** + * Open connection to the original WebSocket server. + */ + connect() { + (0, outvariant.invariant)(!this.realWebSocket || this.realWebSocket.readyState !== WebSocket.OPEN, "Failed to call \"connect()\" on the original WebSocket instance: the connection already open"); + const realWebSocket = this.createConnection(); + realWebSocket.binaryType = this.client.binaryType; + realWebSocket.addEventListener("open", (event) => { + this[kEmitter].dispatchEvent(bindEvent(this.realWebSocket, new Event("open", event))); + }, { once: true }); + realWebSocket.addEventListener("message", (event) => { + this.transport.dispatchEvent(bindEvent(this.realWebSocket, new MessageEvent("incoming", { + data: event.data, + origin: event.origin + }))); + }); + this.client.addEventListener("close", (event) => { + this.handleMockClose(event); + }, { signal: this.mockCloseController.signal }); + realWebSocket.addEventListener("close", (event) => { + this.handleRealClose(event); + }, { signal: this.realCloseController.signal }); + realWebSocket.addEventListener("error", () => { + const errorEvent = bindEvent(realWebSocket, new Event("error", { cancelable: true })); + this[kEmitter].dispatchEvent(errorEvent); + if (!errorEvent.defaultPrevented) this.client.dispatchEvent(bindEvent(this.client, new Event("error"))); + }); + this.realWebSocket = realWebSocket; + } + /** + * Listen for the incoming events from the original WebSocket server. + */ + addEventListener(event, listener, options) { + if (!Reflect.has(listener, kBoundListener)) { + const boundListener = listener.bind(this.client); + Object.defineProperty(listener, kBoundListener, { + value: boundListener, + enumerable: false + }); + } + this[kEmitter].addEventListener(event, Reflect.get(listener, kBoundListener), options); + } + /** + * Remove the listener for the given event. + */ + removeEventListener(event, listener, options) { + this[kEmitter].removeEventListener(event, Reflect.get(listener, kBoundListener), options); + } + /** + * Send data to the original WebSocket server. + * @example + * server.send('hello') + * server.send(new Blob(['hello'])) + * server.send(new TextEncoder().encode('hello')) + */ + send(data) { + this[kSend](data); + } + [kSend](data) { + const { realWebSocket } = this; + (0, outvariant.invariant)(realWebSocket, "Failed to call \"server.send()\" for \"%s\": the connection is not open. Did you forget to call \"server.connect()\"?", this.client.url); + if (realWebSocket.readyState === WebSocket.CLOSING || realWebSocket.readyState === WebSocket.CLOSED) return; + if (realWebSocket.readyState === WebSocket.CONNECTING) { + realWebSocket.addEventListener("open", () => { + realWebSocket.send(data); + }, { once: true }); + return; + } + realWebSocket.send(data); + } + /** + * Close the actual server connection. + */ + close() { + const { realWebSocket } = this; + (0, outvariant.invariant)(realWebSocket, "Failed to close server connection for \"%s\": the connection is not open. Did you forget to call \"server.connect()\"?", this.client.url); + this.realCloseController.abort(); + if (realWebSocket.readyState === WebSocket.CLOSING || realWebSocket.readyState === WebSocket.CLOSED) return; + realWebSocket.close(); + queueMicrotask(() => { + this[kEmitter].dispatchEvent(bindEvent(this.realWebSocket, new CancelableCloseEvent("close", { + code: 1e3, + cancelable: true + }))); + }); + } + handleIncomingMessage(event) { + const messageEvent = bindEvent(event.target, new CancelableMessageEvent("message", { + data: event.data, + origin: event.origin, + cancelable: true + })); + /** + * @note Emit "message" event on the server connection + * instance to let the interceptor know about these + * incoming events from the original server. In that listener, + * the interceptor can modify or skip the event forwarding + * to the mock WebSocket instance. + */ + this[kEmitter].dispatchEvent(messageEvent); + /** + * @note Forward the incoming server events to the client. + * Preventing the default on the message event stops this. + */ + if (!messageEvent.defaultPrevented) this.client.dispatchEvent(bindEvent( + /** + * @note Bind the forwarded original server events + * to the mock WebSocket instance so it would + * dispatch them straight away. + */ + this.client, + new MessageEvent("message", { + data: event.data, + origin: event.origin + }) + )); + } + handleMockClose(_event) { + if (this.realWebSocket) this.realWebSocket.close(); + } + handleRealClose(event) { + this.mockCloseController.abort(); + const closeEvent = bindEvent(this.realWebSocket, new CancelableCloseEvent("close", { + code: event.code, + reason: event.reason, + wasClean: event.wasClean, + cancelable: true + })); + this[kEmitter].dispatchEvent(closeEvent); + if (!closeEvent.defaultPrevented) this.client[kClose](event.code, event.reason); + } +}; + +//#endregion +//#region src/interceptors/WebSocket/WebSocketClassTransport.ts +/** +* Abstraction over the given mock `WebSocket` instance that allows +* for controlling that instance (e.g. sending and receiving messages). +*/ +var WebSocketClassTransport = class extends EventTarget { + constructor(socket) { + super(); + this.socket = socket; + this.socket.addEventListener("close", (event) => { + this.dispatchEvent(bindEvent(this.socket, new CloseEvent("close", event))); + }); + /** + * Emit the "outgoing" event on the transport + * whenever the WebSocket client sends data ("ws.send()"). + */ + this.socket[kOnSend] = (data) => { + this.dispatchEvent(bindEvent(this.socket, new CancelableMessageEvent("outgoing", { + data, + origin: this.socket.url, + cancelable: true + }))); + }; + } + addEventListener(type, callback, options) { + return super.addEventListener(type, callback, options); + } + dispatchEvent(event) { + return super.dispatchEvent(event); + } + send(data) { + queueMicrotask(() => { + if (this.socket.readyState === this.socket.CLOSING || this.socket.readyState === this.socket.CLOSED) return; + const dispatchEvent = () => { + this.socket.dispatchEvent(bindEvent( + /** + * @note Setting this event's "target" to the + * WebSocket override instance is important. + * This way it can tell apart original incoming events + * (must be forwarded to the transport) from the + * mocked message events like the one below + * (must be dispatched on the client instance). + */ + this.socket, + new MessageEvent("message", { + data, + origin: this.socket.url + }) + )); + }; + if (this.socket.readyState === this.socket.CONNECTING) this.socket.addEventListener("open", () => { + dispatchEvent(); + }, { once: true }); + else dispatchEvent(); + }); + } + close(code, reason) { + /** + * @note Call the internal close method directly + * to allow closing the connection with the status codes + * that are non-configurable by the user (> 1000 <= 1015). + */ + this.socket[kClose](code, reason); + } +}; + +//#endregion +//#region src/interceptors/WebSocket/index.ts +/** +* Intercept the outgoing WebSocket connections created using +* the global `WebSocket` class. +*/ +var WebSocketInterceptor = class WebSocketInterceptor extends require_createRequestId.Interceptor { + static { + this.symbol = Symbol.for("websocket-interceptor"); + } + constructor() { + super(WebSocketInterceptor.symbol); + } + checkEnvironment() { + return require_hasConfigurableGlobal.hasConfigurableGlobal("WebSocket"); + } + setup() { + const logger = this.logger.extend("setup"); + const WebSocketProxy = new Proxy(globalThis.WebSocket, { construct: (target, args, newTarget) => { + const [url, protocols] = args; + const createConnection = () => { + return Reflect.construct(target, args, newTarget); + }; + const socket = new WebSocketOverride(url, protocols); + const transport = new WebSocketClassTransport(socket); + queueMicrotask(async () => { + try { + const server = new WebSocketServerConnection(socket, transport, createConnection); + const hasConnectionListeners = this.emitter.listenerCount("connection") > 0; + await require_hasConfigurableGlobal.emitAsync(this.emitter, "connection", { + client: new WebSocketClientConnection(socket, transport), + server, + info: { protocols } + }); + if (hasConnectionListeners) socket[kPassthroughPromise].resolve(false); + else { + socket[kPassthroughPromise].resolve(true); + server.connect(); + server.addEventListener("open", () => { + socket.dispatchEvent(bindEvent(socket, new Event("open"))); + if (server["realWebSocket"]) socket.protocol = server["realWebSocket"].protocol; + }); + } + } catch (error) { + /** + * @note Translate unhandled exceptions during the connection + * handling (i.e. interceptor exceptions) as WebSocket connection + * closures with error. This prevents from the exceptions occurring + * in `queueMicrotask` from being process-wide and uncatchable. + */ + if (error instanceof Error) { + socket.dispatchEvent(new Event("error")); + if (socket.readyState !== WebSocket.CLOSING && socket.readyState !== WebSocket.CLOSED) socket[kClose](1011, error.message, false); + console.error(error); + } + } + }); + return socket; + } }); + logger.info("patching global WebSocket..."); + this.subscriptions.push(require_hasConfigurableGlobal.patchesRegistry.applyPatch(globalThis, "WebSocket", () => WebSocketProxy)); + logger.info("global WebSocket patched!", globalThis.WebSocket.name); + } +}; + +//#endregion +exports.CancelableCloseEvent = CancelableCloseEvent; +exports.CancelableMessageEvent = CancelableMessageEvent; +exports.CloseEvent = CloseEvent; +exports.WebSocketClientConnection = WebSocketClientConnection; +exports.WebSocketClientConnectionProtocol = WebSocketClientConnectionProtocol; +exports.WebSocketInterceptor = WebSocketInterceptor; +exports.WebSocketServerConnection = WebSocketServerConnection; +exports.WebSocketServerConnectionProtocol = WebSocketServerConnectionProtocol; +//# sourceMappingURL=index.cjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/interceptors/WebSocket/index.cjs.map b/node_modules/@mswjs/interceptors/lib/browser/interceptors/WebSocket/index.cjs.map new file mode 100644 index 0000000000000000000000000000000000000000..40d3dc46d7fb1c6501752324e727553ab2fd150d --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/interceptors/WebSocket/index.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.cjs","names":["kEmitter","kBoundListener","socket: WebSocket","transport: WebSocketTransport","createRequestId","resolveWebSocketUrl","DeferredPromise","client: WebSocketOverride","transport: WebSocketClassTransport","createConnection: () => WebSocket","socket: WebSocketOverride","Interceptor","hasConfigurableGlobal","emitAsync","patchesRegistry"],"sources":["../../../../src/interceptors/WebSocket/utils/bindEvent.ts","../../../../src/interceptors/WebSocket/utils/events.ts","../../../../src/interceptors/WebSocket/WebSocketClientConnection.ts","../../../../src/interceptors/WebSocket/WebSocketOverride.ts","../../../../src/interceptors/WebSocket/WebSocketServerConnection.ts","../../../../src/interceptors/WebSocket/WebSocketClassTransport.ts","../../../../src/interceptors/WebSocket/index.ts"],"sourcesContent":["type EventWithTarget = E & { target: T }\n\nexport function bindEvent(\n target: T,\n event: E\n): EventWithTarget {\n Object.defineProperties(event, {\n target: {\n value: target,\n enumerable: true,\n writable: true,\n },\n currentTarget: {\n value: target,\n enumerable: true,\n writable: true,\n },\n })\n\n return event as EventWithTarget\n}\n","const kCancelable = Symbol('kCancelable')\nconst kDefaultPrevented = Symbol('kDefaultPrevented')\n\n/**\n * A `MessageEvent` superset that supports event cancellation\n * in Node.js. It's rather non-intrusive so it can be safely\n * used in the browser as well.\n *\n * @see https://github.com/nodejs/node/issues/51767\n */\nexport class CancelableMessageEvent extends MessageEvent {\n [kCancelable]: boolean;\n [kDefaultPrevented]: boolean\n\n constructor(type: string, init: MessageEventInit) {\n super(type, init)\n this[kCancelable] = !!init.cancelable\n this[kDefaultPrevented] = false\n }\n\n get cancelable() {\n return this[kCancelable]\n }\n\n set cancelable(nextCancelable) {\n this[kCancelable] = nextCancelable\n }\n\n get defaultPrevented() {\n return this[kDefaultPrevented]\n }\n\n set defaultPrevented(nextDefaultPrevented) {\n this[kDefaultPrevented] = nextDefaultPrevented\n }\n\n public preventDefault(): void {\n if (this.cancelable && !this[kDefaultPrevented]) {\n this[kDefaultPrevented] = true\n }\n }\n}\n\ninterface CloseEventInit extends EventInit {\n code?: number\n reason?: string\n wasClean?: boolean\n}\n\nexport class CloseEvent extends Event {\n public code: number\n public reason: string\n public wasClean: boolean\n\n constructor(type: string, init: CloseEventInit = {}) {\n super(type, init)\n this.code = init.code === undefined ? 0 : init.code\n this.reason = init.reason === undefined ? '' : init.reason\n this.wasClean = init.wasClean === undefined ? false : init.wasClean\n }\n}\n\nexport class CancelableCloseEvent extends CloseEvent {\n [kCancelable]: boolean;\n [kDefaultPrevented]: boolean\n\n constructor(type: string, init: CloseEventInit = {}) {\n super(type, init)\n this[kCancelable] = !!init.cancelable\n this[kDefaultPrevented] = false\n }\n\n get cancelable() {\n return this[kCancelable]\n }\n\n set cancelable(nextCancelable) {\n this[kCancelable] = nextCancelable\n }\n\n get defaultPrevented() {\n return this[kDefaultPrevented]\n }\n\n set defaultPrevented(nextDefaultPrevented) {\n this[kDefaultPrevented] = nextDefaultPrevented\n }\n\n public preventDefault(): void {\n if (this.cancelable && !this[kDefaultPrevented]) {\n this[kDefaultPrevented] = true\n }\n }\n}\n","import type { WebSocketData, WebSocketTransport } from './WebSocketTransport'\nimport type { WebSocketEventListener } from './WebSocketOverride'\nimport { bindEvent } from './utils/bindEvent'\nimport { CancelableMessageEvent, CloseEvent } from './utils/events'\nimport { createRequestId } from '../../createRequestId'\n\nconst kEmitter = Symbol('kEmitter')\nconst kBoundListener = Symbol('kBoundListener')\n\nexport interface WebSocketClientEventMap {\n message: MessageEvent\n close: CloseEvent\n}\n\nexport abstract class WebSocketClientConnectionProtocol {\n abstract id: string\n abstract url: URL\n public abstract send(data: WebSocketData): void\n public abstract close(code?: number, reason?: string): void\n\n public abstract addEventListener<\n EventType extends keyof WebSocketClientEventMap,\n >(\n type: EventType,\n listener: WebSocketEventListener,\n options?: AddEventListenerOptions | boolean\n ): void\n\n public abstract removeEventListener<\n EventType extends keyof WebSocketClientEventMap,\n >(\n event: EventType,\n listener: WebSocketEventListener,\n options?: EventListenerOptions | boolean\n ): void\n}\n\n/**\n * The WebSocket client instance represents an incoming\n * client connection. The user can control the connection,\n * send and receive events.\n */\nexport class WebSocketClientConnection implements WebSocketClientConnectionProtocol {\n public readonly id: string\n public readonly url: URL\n\n private [kEmitter]: EventTarget\n\n constructor(\n public readonly socket: WebSocket,\n private readonly transport: WebSocketTransport\n ) {\n this.id = createRequestId()\n this.url = new URL(socket.url)\n this[kEmitter] = new EventTarget()\n\n // Emit outgoing client data (\"ws.send()\") as \"message\"\n // events on the \"client\" connection.\n this.transport.addEventListener('outgoing', (event) => {\n const message = bindEvent(\n this.socket,\n new CancelableMessageEvent('message', {\n data: event.data,\n origin: event.origin,\n cancelable: true,\n })\n )\n\n this[kEmitter].dispatchEvent(message)\n\n // This is a bit silly but forward the cancellation state\n // of the \"client\" message event to the \"outgoing\" transport event.\n // This way, other agens (like \"server\" connection) can know\n // whether the client listener has pervented the default.\n if (message.defaultPrevented) {\n event.preventDefault()\n }\n })\n\n /**\n * Emit the \"close\" event on the \"client\" connection\n * whenever the underlying transport is closed.\n * @note \"client.close()\" does NOT dispatch the \"close\"\n * event on the WebSocket because it uses non-configurable\n * close status code. Thus, we listen to the transport\n * instead of the WebSocket's \"close\" event.\n */\n this.transport.addEventListener('close', (event) => {\n this[kEmitter].dispatchEvent(\n bindEvent(this.socket, new CloseEvent('close', event))\n )\n })\n }\n\n /**\n * Listen for the outgoing events from the connected WebSocket client.\n */\n public addEventListener(\n type: EventType,\n listener: WebSocketEventListener,\n options?: AddEventListenerOptions | boolean\n ): void {\n if (!Reflect.has(listener, kBoundListener)) {\n const boundListener = listener.bind(this.socket)\n\n // Store the bound listener on the original listener\n // so the exact bound function can be accessed in \"removeEventListener()\".\n Object.defineProperty(listener, kBoundListener, {\n value: boundListener,\n enumerable: false,\n configurable: false,\n })\n }\n\n this[kEmitter].addEventListener(\n type,\n Reflect.get(listener, kBoundListener) as EventListener,\n options\n )\n }\n\n /**\n * Removes the listener for the given event.\n */\n public removeEventListener(\n event: EventType,\n listener: WebSocketEventListener,\n options?: EventListenerOptions | boolean\n ): void {\n this[kEmitter].removeEventListener(\n event,\n Reflect.get(listener, kBoundListener) as EventListener,\n options\n )\n }\n\n /**\n * Send data to the connected client.\n */\n public send(data: WebSocketData): void {\n this.transport.send(data)\n }\n\n /**\n * Close the WebSocket connection.\n * @param {number} code A status code (see https://www.rfc-editor.org/rfc/rfc6455#section-7.4.1).\n * @param {string} reason A custom connection close reason.\n */\n public close(code?: number, reason?: string): void {\n this.transport.close(code, reason)\n }\n}\n","import { invariant } from 'outvariant'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport type { WebSocketData } from './WebSocketTransport'\nimport { bindEvent } from './utils/bindEvent'\nimport { CloseEvent } from './utils/events'\nimport { resolveWebSocketUrl } from '../../utils/resolveWebSocketUrl'\n\nexport type WebSocketEventListener<\n EventType extends WebSocketEventMap[keyof WebSocketEventMap] = Event,\n> = (this: WebSocket, event: EventType) => void\n\nconst WEBSOCKET_CLOSE_CODE_RANGE_ERROR =\n 'InvalidAccessError: close code out of user configurable range'\n\nexport const kPassthroughPromise = Symbol('kPassthroughPromise')\nexport const kOnSend = Symbol('kOnSend')\nexport const kClose = Symbol('kClose')\n\nexport class WebSocketOverride extends EventTarget implements WebSocket {\n static readonly CONNECTING = 0\n static readonly OPEN = 1\n static readonly CLOSING = 2\n static readonly CLOSED = 3\n readonly CONNECTING = 0\n readonly OPEN = 1\n readonly CLOSING = 2\n readonly CLOSED = 3\n\n public url: string\n public protocol: string\n public extensions: string\n public binaryType: BinaryType\n public readyState: WebSocket['readyState']\n public bufferedAmount: number\n\n private _onopen: WebSocketEventListener | null = null\n private _onmessage: WebSocketEventListener<\n MessageEvent\n > | null = null\n private _onerror: WebSocketEventListener | null = null\n private _onclose: WebSocketEventListener | null = null\n\n private [kPassthroughPromise]: DeferredPromise\n private [kOnSend]?: (data: WebSocketData) => void\n\n constructor(url: string | URL, protocols?: string | Array) {\n super()\n this.url = resolveWebSocketUrl(url)\n this.protocol = ''\n this.extensions = ''\n this.binaryType = 'blob'\n this.readyState = this.CONNECTING\n this.bufferedAmount = 0\n\n this[kPassthroughPromise] = new DeferredPromise()\n\n queueMicrotask(async () => {\n if (await this[kPassthroughPromise]) {\n return\n }\n\n this.protocol =\n typeof protocols === 'string'\n ? protocols\n : Array.isArray(protocols) && protocols.length > 0\n ? protocols[0]\n : ''\n\n /**\n * @note Check that nothing has prevented this connection\n * (e.g. called `client.close()` in the connection listener).\n * If the connection has been prevented, never dispatch the open event,.\n */\n if (this.readyState === this.CONNECTING) {\n this.readyState = this.OPEN\n this.dispatchEvent(bindEvent(this, new Event('open')))\n }\n })\n }\n\n set onopen(listener: WebSocketEventListener | null) {\n this.removeEventListener('open', this._onopen)\n this._onopen = listener\n if (listener !== null) {\n this.addEventListener('open', listener)\n }\n }\n get onopen(): WebSocketEventListener | null {\n return this._onopen\n }\n\n set onmessage(\n listener: WebSocketEventListener> | null\n ) {\n this.removeEventListener(\n 'message',\n this._onmessage as WebSocketEventListener\n )\n this._onmessage = listener\n if (listener !== null) {\n this.addEventListener('message', listener)\n }\n }\n get onmessage(): WebSocketEventListener> | null {\n return this._onmessage\n }\n\n set onerror(listener: WebSocketEventListener | null) {\n this.removeEventListener('error', this._onerror)\n this._onerror = listener\n if (listener !== null) {\n this.addEventListener('error', listener)\n }\n }\n get onerror(): WebSocketEventListener | null {\n return this._onerror\n }\n\n set onclose(listener: WebSocketEventListener | null) {\n this.removeEventListener('close', this._onclose as WebSocketEventListener)\n this._onclose = listener\n if (listener !== null) {\n this.addEventListener('close', listener)\n }\n }\n get onclose(): WebSocketEventListener | null {\n return this._onclose\n }\n\n /**\n * @see https://websockets.spec.whatwg.org/#ref-for-dom-websocket-send%E2%91%A0\n */\n public send(data: WebSocketData): void {\n if (this.readyState === this.CONNECTING) {\n this.close()\n throw new DOMException('InvalidStateError')\n }\n\n // Sending when the socket is about to close\n // discards the sent data.\n if (this.readyState === this.CLOSING || this.readyState === this.CLOSED) {\n return\n }\n\n // Buffer the data to send in this even loop\n // but send it in the next.\n this.bufferedAmount += getDataSize(data)\n\n queueMicrotask(() => {\n // This is a bit optimistic but since no actual data transfer\n // is involved, all the data will be \"sent\" on the next tick.\n this.bufferedAmount = 0\n\n /**\n * @note Notify the parent about outgoing data.\n * This notifies the transport and the connection\n * listens to the outgoing data to emit the \"message\" event.\n */\n this[kOnSend]?.(data)\n })\n }\n\n public close(code: number = 1000, reason?: string): void {\n invariant(code, WEBSOCKET_CLOSE_CODE_RANGE_ERROR)\n invariant(\n code === 1000 || (code >= 3000 && code <= 4999),\n WEBSOCKET_CLOSE_CODE_RANGE_ERROR\n )\n\n this[kClose](code, reason)\n }\n\n private [kClose](\n code: number = 1000,\n reason?: string,\n wasClean = true\n ): void {\n /**\n * @note Move this check here so that even internal closures,\n * like those triggered by the `server` connection, are not\n * performed twice.\n */\n if (this.readyState === this.CLOSING || this.readyState === this.CLOSED) {\n return\n }\n\n this.readyState = this.CLOSING\n\n queueMicrotask(() => {\n this.readyState = this.CLOSED\n\n this.dispatchEvent(\n bindEvent(\n this,\n new CloseEvent('close', {\n code,\n reason,\n wasClean,\n })\n )\n )\n\n // Remove all event listeners once the socket is closed.\n this._onopen = null\n this._onmessage = null\n this._onerror = null\n this._onclose = null\n })\n }\n\n public addEventListener(\n type: K,\n listener: (this: WebSocket, event: WebSocketEventMap[K]) => void,\n options?: boolean | AddEventListenerOptions\n ): void\n public addEventListener(\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions\n ): void\n public addEventListener(\n type: unknown,\n listener: unknown,\n options?: unknown\n ): void {\n return super.addEventListener(\n type as string,\n listener as EventListener,\n options as AddEventListenerOptions\n )\n }\n\n removeEventListener(\n type: K,\n callback: EventListenerOrEventListenerObject | null,\n options?: boolean | EventListenerOptions\n ): void {\n return super.removeEventListener(type, callback, options)\n }\n}\n\nfunction getDataSize(data: WebSocketData): number {\n if (typeof data === 'string') {\n return data.length\n }\n\n if (data instanceof Blob) {\n return data.size\n }\n\n return data.byteLength\n}\n","import { invariant } from 'outvariant'\nimport {\n kClose,\n WebSocketEventListener,\n WebSocketOverride,\n} from './WebSocketOverride'\nimport type { WebSocketData } from './WebSocketTransport'\nimport type { WebSocketClassTransport } from './WebSocketClassTransport'\nimport { bindEvent } from './utils/bindEvent'\nimport {\n CancelableMessageEvent,\n CancelableCloseEvent,\n CloseEvent,\n} from './utils/events'\n\nconst kEmitter = Symbol('kEmitter')\nconst kBoundListener = Symbol('kBoundListener')\nconst kSend = Symbol('kSend')\n\nexport interface WebSocketServerEventMap {\n open: Event\n message: MessageEvent\n error: Event\n close: CloseEvent\n}\n\nexport abstract class WebSocketServerConnectionProtocol {\n public abstract connect(): void\n public abstract send(data: WebSocketData): void\n public abstract close(): void\n\n public abstract addEventListener<\n EventType extends keyof WebSocketServerEventMap,\n >(\n event: EventType,\n listener: WebSocketEventListener,\n options?: AddEventListenerOptions | boolean\n ): void\n\n public abstract removeEventListener<\n EventType extends keyof WebSocketServerEventMap,\n >(\n event: EventType,\n listener: WebSocketEventListener,\n options?: EventListenerOptions | boolean\n ): void\n}\n\n/**\n * The WebSocket server instance represents the actual production\n * WebSocket server connection. It's idle by default but you can\n * establish it by calling `server.connect()`.\n */\nexport class WebSocketServerConnection implements WebSocketServerConnectionProtocol {\n /**\n * A WebSocket instance connected to the original server.\n */\n private realWebSocket?: WebSocket\n private mockCloseController: AbortController\n private realCloseController: AbortController\n private [kEmitter]: EventTarget\n\n constructor(\n private readonly client: WebSocketOverride,\n private readonly transport: WebSocketClassTransport,\n private readonly createConnection: () => WebSocket\n ) {\n this[kEmitter] = new EventTarget()\n this.mockCloseController = new AbortController()\n this.realCloseController = new AbortController()\n\n // Automatically forward outgoing client events\n // to the actual server unless the outgoing message event\n // has been prevented. The \"outgoing\" transport event it\n // dispatched by the \"client\" connection.\n this.transport.addEventListener('outgoing', (event) => {\n // Ignore client messages if the server connection\n // hasn't been established yet. Nowhere to forward.\n if (typeof this.realWebSocket === 'undefined') {\n return\n }\n\n // Every outgoing client message can prevent this forwarding\n // by preventing the default of the outgoing message event.\n // This listener will be added before user-defined listeners,\n // so execute the logic on the next tick.\n queueMicrotask(() => {\n if (!event.defaultPrevented) {\n /**\n * @note Use the internal send mechanism so consumers can tell\n * apart direct user calls to `server.send()` and internal calls.\n * E.g. MSW has to ignore this internal call to log out messages correctly.\n */\n this[kSend](event.data)\n }\n })\n })\n\n this.transport.addEventListener(\n 'incoming',\n this.handleIncomingMessage.bind(this)\n )\n }\n\n /**\n * The `WebSocket` instance connected to the original server.\n * Accessing this before calling `server.connect()` will throw.\n */\n public get socket(): WebSocket {\n invariant(\n this.realWebSocket,\n 'Cannot access \"socket\" on the original WebSocket server object: the connection is not open. Did you forget to call `server.connect()`?'\n )\n\n return this.realWebSocket\n }\n\n /**\n * Open connection to the original WebSocket server.\n */\n public connect(): void {\n invariant(\n !this.realWebSocket || this.realWebSocket.readyState !== WebSocket.OPEN,\n 'Failed to call \"connect()\" on the original WebSocket instance: the connection already open'\n )\n\n const realWebSocket = this.createConnection()\n\n // Inherit the binary type from the mock WebSocket client.\n realWebSocket.binaryType = this.client.binaryType\n\n // Allow the interceptor to listen to when the server connection\n // has been established. This isn't necessary to operate with the connection\n // but may be beneficial in some cases (like conditionally adding logging).\n realWebSocket.addEventListener(\n 'open',\n (event) => {\n this[kEmitter].dispatchEvent(\n bindEvent(this.realWebSocket!, new Event('open', event))\n )\n },\n { once: true }\n )\n\n realWebSocket.addEventListener('message', (event) => {\n // Dispatch the \"incoming\" transport event instead of\n // invoking the internal handler directly. This way,\n // anyone can listen to the \"incoming\" event but this\n // class is the one resulting in it.\n this.transport.dispatchEvent(\n bindEvent(\n this.realWebSocket!,\n new MessageEvent('incoming', {\n data: event.data,\n origin: event.origin,\n })\n )\n )\n })\n\n // Close the original connection when the mock client closes.\n // E.g. \"client.close()\" was called. This is never forwarded anywhere.\n this.client.addEventListener(\n 'close',\n (event) => {\n this.handleMockClose(event)\n },\n {\n signal: this.mockCloseController.signal,\n }\n )\n\n // Forward the \"close\" event to let the interceptor handle\n // closures initiated by the original server.\n realWebSocket.addEventListener(\n 'close',\n (event) => {\n this.handleRealClose(event)\n },\n {\n signal: this.realCloseController.signal,\n }\n )\n\n realWebSocket.addEventListener('error', () => {\n const errorEvent = bindEvent(\n realWebSocket,\n new Event('error', { cancelable: true })\n )\n\n // Emit the \"error\" event on the `server` connection\n // to let the interceptor react to original server errors.\n this[kEmitter].dispatchEvent(errorEvent)\n\n // If the error event from the original server hasn't been prevented,\n // forward it to the underlying client.\n if (!errorEvent.defaultPrevented) {\n this.client.dispatchEvent(bindEvent(this.client, new Event('error')))\n }\n })\n\n this.realWebSocket = realWebSocket\n }\n\n /**\n * Listen for the incoming events from the original WebSocket server.\n */\n public addEventListener(\n event: EventType,\n listener: WebSocketEventListener,\n options?: AddEventListenerOptions | boolean\n ): void {\n if (!Reflect.has(listener, kBoundListener)) {\n const boundListener = listener.bind(this.client)\n\n // Store the bound listener on the original listener\n // so the exact bound function can be accessed in \"removeEventListener()\".\n Object.defineProperty(listener, kBoundListener, {\n value: boundListener,\n enumerable: false,\n })\n }\n\n this[kEmitter].addEventListener(\n event,\n Reflect.get(listener, kBoundListener) as EventListener,\n options\n )\n }\n\n /**\n * Remove the listener for the given event.\n */\n public removeEventListener(\n event: EventType,\n listener: WebSocketEventListener,\n options?: EventListenerOptions | boolean\n ): void {\n this[kEmitter].removeEventListener(\n event,\n Reflect.get(listener, kBoundListener) as EventListener,\n options\n )\n }\n\n /**\n * Send data to the original WebSocket server.\n * @example\n * server.send('hello')\n * server.send(new Blob(['hello']))\n * server.send(new TextEncoder().encode('hello'))\n */\n public send(data: WebSocketData): void {\n this[kSend](data)\n }\n\n private [kSend](data: WebSocketData): void {\n const { realWebSocket } = this\n\n invariant(\n realWebSocket,\n 'Failed to call \"server.send()\" for \"%s\": the connection is not open. Did you forget to call \"server.connect()\"?',\n this.client.url\n )\n\n // Silently ignore writes on the closed original WebSocket.\n if (\n realWebSocket.readyState === WebSocket.CLOSING ||\n realWebSocket.readyState === WebSocket.CLOSED\n ) {\n return\n }\n\n // Delegate the send to when the original connection is open.\n // Unlike the mock, connecting to the original server may take time\n // so we cannot call this on the next tick.\n if (realWebSocket.readyState === WebSocket.CONNECTING) {\n realWebSocket.addEventListener(\n 'open',\n () => {\n realWebSocket.send(data)\n },\n { once: true }\n )\n return\n }\n\n // Send the data to the original WebSocket server.\n realWebSocket.send(data)\n }\n\n /**\n * Close the actual server connection.\n */\n public close(): void {\n const { realWebSocket } = this\n\n invariant(\n realWebSocket,\n 'Failed to close server connection for \"%s\": the connection is not open. Did you forget to call \"server.connect()\"?',\n this.client.url\n )\n\n // Remove the \"close\" event listener from the server\n // so it doesn't close the underlying WebSocket client\n // when you call \"server.close()\". This also prevents the\n // `close` event on the `server` connection from being dispatched twice.\n this.realCloseController.abort()\n\n if (\n realWebSocket.readyState === WebSocket.CLOSING ||\n realWebSocket.readyState === WebSocket.CLOSED\n ) {\n return\n }\n\n // Close the actual client connection.\n realWebSocket.close()\n\n // Dispatch the \"close\" event on the `server` connection.\n queueMicrotask(() => {\n this[kEmitter].dispatchEvent(\n bindEvent(\n this.realWebSocket,\n new CancelableCloseEvent('close', {\n /**\n * @note `server.close()` in the interceptor\n * always results in clean closures.\n */\n code: 1000,\n cancelable: true,\n })\n )\n )\n })\n }\n\n private handleIncomingMessage(event: MessageEvent): void {\n // Clone the event to dispatch it on this class\n // once again and prevent the \"already being dispatched\"\n // exception. Clone it here so we can observe this event\n // being prevented in the \"server.on()\" listeners.\n const messageEvent = bindEvent(\n event.target,\n new CancelableMessageEvent('message', {\n data: event.data,\n origin: event.origin,\n cancelable: true,\n })\n )\n\n /**\n * @note Emit \"message\" event on the server connection\n * instance to let the interceptor know about these\n * incoming events from the original server. In that listener,\n * the interceptor can modify or skip the event forwarding\n * to the mock WebSocket instance.\n */\n this[kEmitter].dispatchEvent(messageEvent)\n\n /**\n * @note Forward the incoming server events to the client.\n * Preventing the default on the message event stops this.\n */\n if (!messageEvent.defaultPrevented) {\n this.client.dispatchEvent(\n bindEvent(\n /**\n * @note Bind the forwarded original server events\n * to the mock WebSocket instance so it would\n * dispatch them straight away.\n */\n this.client,\n // Clone the message event again to prevent\n // the \"already being dispatched\" exception.\n new MessageEvent('message', {\n data: event.data,\n origin: event.origin,\n })\n )\n )\n }\n }\n\n private handleMockClose(_event: Event): void {\n // Close the original connection if the mock client closes.\n if (this.realWebSocket) {\n this.realWebSocket.close()\n }\n }\n\n private handleRealClose(event: CloseEvent): void {\n // For closures originating from the original server,\n // remove the \"close\" listener from the mock client.\n // original close -> (?) client[kClose]() --X--> \"close\" (again).\n this.mockCloseController.abort()\n\n const closeEvent = bindEvent(\n this.realWebSocket,\n new CancelableCloseEvent('close', {\n code: event.code,\n reason: event.reason,\n wasClean: event.wasClean,\n cancelable: true,\n })\n )\n\n this[kEmitter].dispatchEvent(closeEvent)\n\n // If the close event from the server hasn't been prevented,\n // forward the closure to the mock client.\n if (!closeEvent.defaultPrevented) {\n // Close the intercepted client forcefully to\n // allow non-configurable status codes from the server.\n // If the socket has been closed by now, no harm calling\n // this again—it will have no effect.\n this.client[kClose](event.code, event.reason)\n }\n }\n}\n","import { bindEvent } from './utils/bindEvent'\nimport {\n StrictEventListenerOrEventListenerObject,\n WebSocketData,\n WebSocketTransport,\n WebSocketTransportEventMap,\n} from './WebSocketTransport'\nimport { kOnSend, kClose, WebSocketOverride } from './WebSocketOverride'\nimport { CancelableMessageEvent, CloseEvent } from './utils/events'\n\n/**\n * Abstraction over the given mock `WebSocket` instance that allows\n * for controlling that instance (e.g. sending and receiving messages).\n */\nexport class WebSocketClassTransport\n extends EventTarget\n implements WebSocketTransport\n{\n constructor(protected readonly socket: WebSocketOverride) {\n super()\n\n // Emit the \"close\" event on the transport if the close\n // originates from the WebSocket client. E.g. the application\n // calls \"ws.close()\", not the interceptor.\n this.socket.addEventListener('close', (event) => {\n this.dispatchEvent(bindEvent(this.socket, new CloseEvent('close', event)))\n })\n\n /**\n * Emit the \"outgoing\" event on the transport\n * whenever the WebSocket client sends data (\"ws.send()\").\n */\n this.socket[kOnSend] = (data) => {\n this.dispatchEvent(\n bindEvent(\n this.socket,\n // Dispatch this as cancelable because \"client\" connection\n // re-creates this message event (cannot dispatch the same event).\n new CancelableMessageEvent('outgoing', {\n data,\n origin: this.socket.url,\n cancelable: true,\n })\n )\n )\n }\n }\n\n public addEventListener(\n type: EventType,\n callback: StrictEventListenerOrEventListenerObject<\n WebSocketTransportEventMap[EventType]\n > | null,\n options?: boolean | AddEventListenerOptions\n ): void {\n return super.addEventListener(type, callback as EventListener, options)\n }\n\n public dispatchEvent(\n event: WebSocketTransportEventMap[EventType]\n ): boolean {\n return super.dispatchEvent(event)\n }\n\n public send(data: WebSocketData): void {\n queueMicrotask(() => {\n if (\n this.socket.readyState === this.socket.CLOSING ||\n this.socket.readyState === this.socket.CLOSED\n ) {\n return\n }\n\n const dispatchEvent = () => {\n this.socket.dispatchEvent(\n bindEvent(\n /**\n * @note Setting this event's \"target\" to the\n * WebSocket override instance is important.\n * This way it can tell apart original incoming events\n * (must be forwarded to the transport) from the\n * mocked message events like the one below\n * (must be dispatched on the client instance).\n */\n this.socket,\n new MessageEvent('message', {\n data,\n origin: this.socket.url,\n })\n )\n )\n }\n\n if (this.socket.readyState === this.socket.CONNECTING) {\n this.socket.addEventListener(\n 'open',\n () => {\n dispatchEvent()\n },\n { once: true }\n )\n } else {\n dispatchEvent()\n }\n })\n }\n\n public close(code: number, reason?: string): void {\n /**\n * @note Call the internal close method directly\n * to allow closing the connection with the status codes\n * that are non-configurable by the user (> 1000 <= 1015).\n */\n this.socket[kClose](code, reason)\n }\n}\n","import { Interceptor } from '../../Interceptor'\nimport {\n WebSocketClientConnectionProtocol,\n WebSocketClientConnection,\n type WebSocketClientEventMap,\n} from './WebSocketClientConnection'\nimport {\n WebSocketServerConnectionProtocol,\n WebSocketServerConnection,\n type WebSocketServerEventMap,\n} from './WebSocketServerConnection'\nimport { WebSocketClassTransport } from './WebSocketClassTransport'\nimport {\n kClose,\n kPassthroughPromise,\n WebSocketOverride,\n} from './WebSocketOverride'\nimport { bindEvent } from './utils/bindEvent'\nimport { hasConfigurableGlobal } from '../../utils/hasConfigurableGlobal'\nimport { emitAsync } from '../../utils/emitAsync'\nimport { patchesRegistry } from '../../utils/patchesRegistry'\n\nexport {\n type WebSocketData,\n type WebSocketTransport,\n} from './WebSocketTransport'\nexport {\n WebSocketClientEventMap,\n WebSocketClientConnectionProtocol,\n WebSocketClientConnection,\n WebSocketServerEventMap,\n WebSocketServerConnectionProtocol,\n WebSocketServerConnection,\n}\n\nexport {\n CloseEvent,\n CancelableCloseEvent,\n CancelableMessageEvent,\n} from './utils/events'\n\nexport type WebSocketEventMap = {\n connection: [args: WebSocketConnectionData]\n}\n\nexport type WebSocketConnectionData = {\n /**\n * The incoming WebSocket client connection.\n */\n client: WebSocketClientConnection\n\n /**\n * The original WebSocket server connection.\n */\n server: WebSocketServerConnection\n\n /**\n * The connection information.\n */\n info: {\n /**\n * The protocols supported by the WebSocket client.\n */\n protocols: string | Array | undefined\n }\n}\n\n/**\n * Intercept the outgoing WebSocket connections created using\n * the global `WebSocket` class.\n */\nexport class WebSocketInterceptor extends Interceptor {\n static symbol = Symbol.for('websocket-interceptor')\n\n constructor() {\n super(WebSocketInterceptor.symbol)\n }\n\n protected checkEnvironment(): boolean {\n return hasConfigurableGlobal('WebSocket')\n }\n\n protected setup(): void {\n const logger = this.logger.extend('setup')\n\n const WebSocketProxy = new Proxy(globalThis.WebSocket, {\n construct: (\n target,\n args: ConstructorParameters,\n newTarget\n ) => {\n const [url, protocols] = args\n\n const createConnection = (): WebSocket => {\n return Reflect.construct(target, args, newTarget)\n }\n\n // All WebSocket instances are mocked and don't forward\n // any events to the original server (no connection established).\n // To forward the events, the user must use the \"server.send()\" API.\n const socket = new WebSocketOverride(url, protocols)\n const transport = new WebSocketClassTransport(socket)\n\n // Emit the \"connection\" event to the interceptor on the next tick\n // so the client can modify WebSocket options, like \"binaryType\"\n // while the connection is already pending.\n queueMicrotask(async () => {\n try {\n const server = new WebSocketServerConnection(\n socket,\n transport,\n createConnection\n )\n\n const hasConnectionListeners =\n this.emitter.listenerCount('connection') > 0\n\n // The \"globalThis.WebSocket\" class stands for\n // the client-side connection. Assume it's established\n // as soon as the WebSocket instance is constructed.\n await emitAsync(this.emitter, 'connection', {\n client: new WebSocketClientConnection(socket, transport),\n server,\n info: {\n protocols,\n },\n })\n\n if (hasConnectionListeners) {\n socket[kPassthroughPromise].resolve(false)\n } else {\n socket[kPassthroughPromise].resolve(true)\n\n server.connect()\n\n // Forward the \"open\" event from the original server\n // to the mock WebSocket client in the case of a passthrough connection.\n server.addEventListener('open', () => {\n socket.dispatchEvent(bindEvent(socket, new Event('open')))\n\n // Forward the original connection protocol to the\n // mock WebSocket client.\n if (server['realWebSocket']) {\n socket.protocol = server['realWebSocket'].protocol\n }\n })\n }\n } catch (error) {\n /**\n * @note Translate unhandled exceptions during the connection\n * handling (i.e. interceptor exceptions) as WebSocket connection\n * closures with error. This prevents from the exceptions occurring\n * in `queueMicrotask` from being process-wide and uncatchable.\n */\n if (error instanceof Error) {\n socket.dispatchEvent(new Event('error'))\n\n // No need to close the connection if it's already being closed.\n // E.g. the interceptor called `client.close()` and then threw an error.\n if (\n socket.readyState !== WebSocket.CLOSING &&\n socket.readyState !== WebSocket.CLOSED\n ) {\n socket[kClose](1011, error.message, false)\n }\n\n console.error(error)\n }\n }\n })\n\n return socket\n },\n })\n\n logger.info('patching global WebSocket...')\n\n this.subscriptions.push(\n patchesRegistry.applyPatch(globalThis, 'WebSocket', () => WebSocketProxy)\n )\n\n logger.info('global WebSocket patched!', globalThis.WebSocket.name)\n }\n}\n"],"mappings":";;;;;;;AAEA,SAAgB,UACd,QACA,OACuB;AACvB,QAAO,iBAAiB,OAAO;EAC7B,QAAQ;GACN,OAAO;GACP,YAAY;GACZ,UAAU;GACX;EACD,eAAe;GACb,OAAO;GACP,YAAY;GACZ,UAAU;GACX;EACF,CAAC;AAEF,QAAO;;;;;ACnBT,MAAM,cAAc,OAAO,cAAc;AACzC,MAAM,oBAAoB,OAAO,oBAAoB;;;;;;;;AASrD,IAAa,yBAAb,cAAqD,aAAgB;CAInE,YAAY,MAAc,MAA2B;AACnD,QAAM,MAAM,KAAK;AACjB,OAAK,eAAe,CAAC,CAAC,KAAK;AAC3B,OAAK,qBAAqB;;CAG5B,IAAI,aAAa;AACf,SAAO,KAAK;;CAGd,IAAI,WAAW,gBAAgB;AAC7B,OAAK,eAAe;;CAGtB,IAAI,mBAAmB;AACrB,SAAO,KAAK;;CAGd,IAAI,iBAAiB,sBAAsB;AACzC,OAAK,qBAAqB;;CAG5B,AAAO,iBAAuB;AAC5B,MAAI,KAAK,cAAc,CAAC,KAAK,mBAC3B,MAAK,qBAAqB;;;AAWhC,IAAa,aAAb,cAAgC,MAAM;CAKpC,YAAY,MAAc,OAAuB,EAAE,EAAE;AACnD,QAAM,MAAM,KAAK;AACjB,OAAK,OAAO,KAAK,SAAS,SAAY,IAAI,KAAK;AAC/C,OAAK,SAAS,KAAK,WAAW,SAAY,KAAK,KAAK;AACpD,OAAK,WAAW,KAAK,aAAa,SAAY,QAAQ,KAAK;;;AAI/D,IAAa,uBAAb,cAA0C,WAAW;CAInD,YAAY,MAAc,OAAuB,EAAE,EAAE;AACnD,QAAM,MAAM,KAAK;AACjB,OAAK,eAAe,CAAC,CA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AM,yBAAoC;AACxC,WAAO,QAAQ,UAAU,QAAQ,MAAM,UAAU;;GAMnD,MAAM,SAAS,IAAI,kBAAkB,KAAK,UAAU;GACpD,MAAM,YAAY,IAAI,wBAAwB,OAAO;AAKrD,kBAAe,YAAY;AACzB,QAAI;KACF,MAAM,SAAS,IAAI,0BACjB,QACA,WACA,iBACD;KAED,MAAM,yBACJ,KAAK,QAAQ,cAAc,aAAa,GAAG;AAK7C,WAAMC,wCAAU,KAAK,SAAS,cAAc;MAC1C,QAAQ,IAAI,0BAA0B,QAAQ,UAAU;MACxD;MACA,MAAM,EACJ,WACD;MACF,CAAC;AAEF,SAAI,uBACF,QAAO,qBAAqB,QAAQ,MAAM;UACrC;AACL,aAAO,qBAAqB,QAAQ,KAAK;AAEzC,aAAO,SAAS;AAIhB,aAAO,iBAAiB,cAAc;AACpC,cAAO,cAAc,UAAU,QAAQ,IAAI,MAAM,OAAO,CAAC,CAAC;AAI1D,WAAI,OAAO,iBACT,QAAO,WAAW,OAAO,iBAAiB;QAE5C;;aAEG,OAAO;;;;;;;AAOd,SAAI,iBAAiB,OAAO;AAC1B,aAAO,cAAc,IAAI,MAAM,QAAQ,CAAC;AAIxC,UACE,OAAO,eAAe,UAAU,WAChC,OAAO,eAAe,UAAU,OAEhC,QAAO,QAAQ,MAAM,MAAM,SAAS,MAAM;AAG5C,cAAQ,MAAM,MAAM;;;KAGxB;AAEF,UAAO;KAEV,CAAC;AAEF,SAAO,KAAK,+BAA+B;AAE3C,OAAK,cAAc,KACjBC,8CAAgB,WAAW,YAAY,mBAAmB,eAAe,CAC1E;AAED,SAAO,KAAK,6BAA6B,WAAW,UAAU,KAAK"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/interceptors/WebSocket/index.d.cts b/node_modules/@mswjs/interceptors/lib/browser/interceptors/WebSocket/index.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..0012ec21c551933673227ab4eed086a928f7040d --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/interceptors/WebSocket/index.d.cts @@ -0,0 +1,277 @@ +import { r as Interceptor } from "../../Interceptor-Deczogc8.cjs"; + +//#region src/interceptors/WebSocket/utils/events.d.ts +declare const kCancelable: unique symbol; +declare const kDefaultPrevented: unique symbol; +/** + * A `MessageEvent` superset that supports event cancellation + * in Node.js. It's rather non-intrusive so it can be safely + * used in the browser as well. + * + * @see https://github.com/nodejs/node/issues/51767 + */ +declare class CancelableMessageEvent extends MessageEvent { + [kCancelable]: boolean; + [kDefaultPrevented]: boolean; + constructor(type: string, init: MessageEventInit); + get cancelable(): boolean; + set cancelable(nextCancelable: boolean); + get defaultPrevented(): boolean; + set defaultPrevented(nextDefaultPrevented: boolean); + preventDefault(): void; +} +interface CloseEventInit extends EventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +declare class CloseEvent extends Event { + code: number; + reason: string; + wasClean: boolean; + constructor(type: string, init?: CloseEventInit); +} +declare class CancelableCloseEvent extends CloseEvent { + [kCancelable]: boolean; + [kDefaultPrevented]: boolean; + constructor(type: string, init?: CloseEventInit); + get cancelable(): boolean; + set cancelable(nextCancelable: boolean); + get defaultPrevented(): boolean; + set defaultPrevented(nextDefaultPrevented: boolean); + preventDefault(): void; +} +//#endregion +//#region src/interceptors/WebSocket/WebSocketTransport.d.ts +type WebSocketData = string | ArrayBufferLike | Blob | ArrayBufferView; +type WebSocketTransportEventMap = { + incoming: MessageEvent; + outgoing: MessageEvent; + close: CloseEvent; +}; +type StrictEventListenerOrEventListenerObject = ((this: WebSocket, event: EventType) => void) | { + handleEvent(this: WebSocket, event: EventType): void; +}; +interface WebSocketTransport { + addEventListener(event: EventType, listener: StrictEventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions): void; + dispatchEvent(event: WebSocketTransportEventMap[EventType]): boolean; + /** + * Send the data from the server to this client. + */ + send(data: WebSocketData): void; + /** + * Close the client connection. + */ + close(code?: number, reason?: string): void; +} +//#endregion +//#region src/interceptors/WebSocket/WebSocketOverride.d.ts +type WebSocketEventListener = (this: WebSocket, event: EventType) => void; +declare const kPassthroughPromise: unique symbol; +declare const kOnSend: unique symbol; +declare const kClose: unique symbol; +declare class WebSocketOverride extends EventTarget implements WebSocket { + static readonly CONNECTING = 0; + static readonly OPEN = 1; + static readonly CLOSING = 2; + static readonly CLOSED = 3; + readonly CONNECTING = 0; + readonly OPEN = 1; + readonly CLOSING = 2; + readonly CLOSED = 3; + url: string; + protocol: string; + extensions: string; + binaryType: BinaryType; + readyState: WebSocket['readyState']; + bufferedAmount: number; + private _onopen; + private _onmessage; + private _onerror; + private _onclose; + private [kPassthroughPromise]; + private [kOnSend]?; + constructor(url: string | URL, protocols?: string | Array); + set onopen(listener: WebSocketEventListener | null); + get onopen(): WebSocketEventListener | null; + set onmessage(listener: WebSocketEventListener> | null); + get onmessage(): WebSocketEventListener> | null; + set onerror(listener: WebSocketEventListener | null); + get onerror(): WebSocketEventListener | null; + set onclose(listener: WebSocketEventListener | null); + get onclose(): WebSocketEventListener | null; + /** + * @see https://websockets.spec.whatwg.org/#ref-for-dom-websocket-send%E2%91%A0 + */ + send(data: WebSocketData): void; + close(code?: number, reason?: string): void; + private [kClose]; + addEventListener(type: K, listener: (this: WebSocket, event: WebSocketEventMap[K]) => void, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, callback: EventListenerOrEventListenerObject | null, options?: boolean | EventListenerOptions): void; +} +//#endregion +//#region src/interceptors/WebSocket/WebSocketClientConnection.d.ts +declare const kEmitter$1: unique symbol; +interface WebSocketClientEventMap { + message: MessageEvent; + close: CloseEvent; +} +declare abstract class WebSocketClientConnectionProtocol { + abstract id: string; + abstract url: URL; + abstract send(data: WebSocketData): void; + abstract close(code?: number, reason?: string): void; + abstract addEventListener(type: EventType, listener: WebSocketEventListener, options?: AddEventListenerOptions | boolean): void; + abstract removeEventListener(event: EventType, listener: WebSocketEventListener, options?: EventListenerOptions | boolean): void; +} +/** + * The WebSocket client instance represents an incoming + * client connection. The user can control the connection, + * send and receive events. + */ +declare class WebSocketClientConnection implements WebSocketClientConnectionProtocol { + readonly socket: WebSocket; + private readonly transport; + readonly id: string; + readonly url: URL; + private [kEmitter$1]; + constructor(socket: WebSocket, transport: WebSocketTransport); + /** + * Listen for the outgoing events from the connected WebSocket client. + */ + addEventListener(type: EventType, listener: WebSocketEventListener, options?: AddEventListenerOptions | boolean): void; + /** + * Removes the listener for the given event. + */ + removeEventListener(event: EventType, listener: WebSocketEventListener, options?: EventListenerOptions | boolean): void; + /** + * Send data to the connected client. + */ + send(data: WebSocketData): void; + /** + * Close the WebSocket connection. + * @param {number} code A status code (see https://www.rfc-editor.org/rfc/rfc6455#section-7.4.1). + * @param {string} reason A custom connection close reason. + */ + close(code?: number, reason?: string): void; +} +//#endregion +//#region src/interceptors/WebSocket/WebSocketClassTransport.d.ts +/** + * Abstraction over the given mock `WebSocket` instance that allows + * for controlling that instance (e.g. sending and receiving messages). + */ +declare class WebSocketClassTransport extends EventTarget implements WebSocketTransport { + protected readonly socket: WebSocketOverride; + constructor(socket: WebSocketOverride); + addEventListener(type: EventType, callback: StrictEventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions): void; + dispatchEvent(event: WebSocketTransportEventMap[EventType]): boolean; + send(data: WebSocketData): void; + close(code: number, reason?: string): void; +} +//#endregion +//#region src/interceptors/WebSocket/WebSocketServerConnection.d.ts +declare const kEmitter: unique symbol; +declare const kSend: unique symbol; +interface WebSocketServerEventMap { + open: Event; + message: MessageEvent; + error: Event; + close: CloseEvent; +} +declare abstract class WebSocketServerConnectionProtocol { + abstract connect(): void; + abstract send(data: WebSocketData): void; + abstract close(): void; + abstract addEventListener(event: EventType, listener: WebSocketEventListener, options?: AddEventListenerOptions | boolean): void; + abstract removeEventListener(event: EventType, listener: WebSocketEventListener, options?: EventListenerOptions | boolean): void; +} +/** + * The WebSocket server instance represents the actual production + * WebSocket server connection. It's idle by default but you can + * establish it by calling `server.connect()`. + */ +declare class WebSocketServerConnection implements WebSocketServerConnectionProtocol { + private readonly client; + private readonly transport; + private readonly createConnection; + /** + * A WebSocket instance connected to the original server. + */ + private realWebSocket?; + private mockCloseController; + private realCloseController; + private [kEmitter]; + constructor(client: WebSocketOverride, transport: WebSocketClassTransport, createConnection: () => WebSocket); + /** + * The `WebSocket` instance connected to the original server. + * Accessing this before calling `server.connect()` will throw. + */ + get socket(): WebSocket; + /** + * Open connection to the original WebSocket server. + */ + connect(): void; + /** + * Listen for the incoming events from the original WebSocket server. + */ + addEventListener(event: EventType, listener: WebSocketEventListener, options?: AddEventListenerOptions | boolean): void; + /** + * Remove the listener for the given event. + */ + removeEventListener(event: EventType, listener: WebSocketEventListener, options?: EventListenerOptions | boolean): void; + /** + * Send data to the original WebSocket server. + * @example + * server.send('hello') + * server.send(new Blob(['hello'])) + * server.send(new TextEncoder().encode('hello')) + */ + send(data: WebSocketData): void; + private [kSend]; + /** + * Close the actual server connection. + */ + close(): void; + private handleIncomingMessage; + private handleMockClose; + private handleRealClose; +} +//#endregion +//#region src/interceptors/WebSocket/index.d.ts +type WebSocketEventMap$1 = { + connection: [args: WebSocketConnectionData]; +}; +type WebSocketConnectionData = { + /** + * The incoming WebSocket client connection. + */ + client: WebSocketClientConnection; + /** + * The original WebSocket server connection. + */ + server: WebSocketServerConnection; + /** + * The connection information. + */ + info: { + /** + * The protocols supported by the WebSocket client. + */ + protocols: string | Array | undefined; + }; +}; +/** + * Intercept the outgoing WebSocket connections created using + * the global `WebSocket` class. + */ +declare class WebSocketInterceptor extends Interceptor { + static symbol: symbol; + constructor(); + protected checkEnvironment(): boolean; + protected setup(): void; +} +//#endregion +export { CancelableCloseEvent, CancelableMessageEvent, CloseEvent, WebSocketClientConnection, WebSocketClientConnectionProtocol, WebSocketClientEventMap, WebSocketConnectionData, type WebSocketData, WebSocketEventMap$1 as WebSocketEventMap, WebSocketInterceptor, WebSocketServerConnection, WebSocketServerConnectionProtocol, WebSocketServerEventMap, type WebSocketTransport }; +//# sourceMappingURL=index.d.cts.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/interceptors/WebSocket/index.d.mts b/node_modules/@mswjs/interceptors/lib/browser/interceptors/WebSocket/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..f2a3b66f009bdf531b5a5ad89bd04340002e3d65 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/interceptors/WebSocket/index.d.mts @@ -0,0 +1,277 @@ +import { r as Interceptor } from "../../Interceptor-gqKgs-aF.mjs"; + +//#region src/interceptors/WebSocket/utils/events.d.ts +declare const kCancelable: unique symbol; +declare const kDefaultPrevented: unique symbol; +/** + * A `MessageEvent` superset that supports event cancellation + * in Node.js. It's rather non-intrusive so it can be safely + * used in the browser as well. + * + * @see https://github.com/nodejs/node/issues/51767 + */ +declare class CancelableMessageEvent extends MessageEvent { + [kCancelable]: boolean; + [kDefaultPrevented]: boolean; + constructor(type: string, init: MessageEventInit); + get cancelable(): boolean; + set cancelable(nextCancelable: boolean); + get defaultPrevented(): boolean; + set defaultPrevented(nextDefaultPrevented: boolean); + preventDefault(): void; +} +interface CloseEventInit extends EventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +declare class CloseEvent extends Event { + code: number; + reason: string; + wasClean: boolean; + constructor(type: string, init?: CloseEventInit); +} +declare class CancelableCloseEvent extends CloseEvent { + [kCancelable]: boolean; + [kDefaultPrevented]: boolean; + constructor(type: string, init?: CloseEventInit); + get cancelable(): boolean; + set cancelable(nextCancelable: boolean); + get defaultPrevented(): boolean; + set defaultPrevented(nextDefaultPrevented: boolean); + preventDefault(): void; +} +//#endregion +//#region src/interceptors/WebSocket/WebSocketTransport.d.ts +type WebSocketData = string | ArrayBufferLike | Blob | ArrayBufferView; +type WebSocketTransportEventMap = { + incoming: MessageEvent; + outgoing: MessageEvent; + close: CloseEvent; +}; +type StrictEventListenerOrEventListenerObject = ((this: WebSocket, event: EventType) => void) | { + handleEvent(this: WebSocket, event: EventType): void; +}; +interface WebSocketTransport { + addEventListener(event: EventType, listener: StrictEventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions): void; + dispatchEvent(event: WebSocketTransportEventMap[EventType]): boolean; + /** + * Send the data from the server to this client. + */ + send(data: WebSocketData): void; + /** + * Close the client connection. + */ + close(code?: number, reason?: string): void; +} +//#endregion +//#region src/interceptors/WebSocket/WebSocketOverride.d.ts +type WebSocketEventListener = (this: WebSocket, event: EventType) => void; +declare const kPassthroughPromise: unique symbol; +declare const kOnSend: unique symbol; +declare const kClose: unique symbol; +declare class WebSocketOverride extends EventTarget implements WebSocket { + static readonly CONNECTING = 0; + static readonly OPEN = 1; + static readonly CLOSING = 2; + static readonly CLOSED = 3; + readonly CONNECTING = 0; + readonly OPEN = 1; + readonly CLOSING = 2; + readonly CLOSED = 3; + url: string; + protocol: string; + extensions: string; + binaryType: BinaryType; + readyState: WebSocket['readyState']; + bufferedAmount: number; + private _onopen; + private _onmessage; + private _onerror; + private _onclose; + private [kPassthroughPromise]; + private [kOnSend]?; + constructor(url: string | URL, protocols?: string | Array); + set onopen(listener: WebSocketEventListener | null); + get onopen(): WebSocketEventListener | null; + set onmessage(listener: WebSocketEventListener> | null); + get onmessage(): WebSocketEventListener> | null; + set onerror(listener: WebSocketEventListener | null); + get onerror(): WebSocketEventListener | null; + set onclose(listener: WebSocketEventListener | null); + get onclose(): WebSocketEventListener | null; + /** + * @see https://websockets.spec.whatwg.org/#ref-for-dom-websocket-send%E2%91%A0 + */ + send(data: WebSocketData): void; + close(code?: number, reason?: string): void; + private [kClose]; + addEventListener(type: K, listener: (this: WebSocket, event: WebSocketEventMap[K]) => void, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, callback: EventListenerOrEventListenerObject | null, options?: boolean | EventListenerOptions): void; +} +//#endregion +//#region src/interceptors/WebSocket/WebSocketClientConnection.d.ts +declare const kEmitter$1: unique symbol; +interface WebSocketClientEventMap { + message: MessageEvent; + close: CloseEvent; +} +declare abstract class WebSocketClientConnectionProtocol { + abstract id: string; + abstract url: URL; + abstract send(data: WebSocketData): void; + abstract close(code?: number, reason?: string): void; + abstract addEventListener(type: EventType, listener: WebSocketEventListener, options?: AddEventListenerOptions | boolean): void; + abstract removeEventListener(event: EventType, listener: WebSocketEventListener, options?: EventListenerOptions | boolean): void; +} +/** + * The WebSocket client instance represents an incoming + * client connection. The user can control the connection, + * send and receive events. + */ +declare class WebSocketClientConnection implements WebSocketClientConnectionProtocol { + readonly socket: WebSocket; + private readonly transport; + readonly id: string; + readonly url: URL; + private [kEmitter$1]; + constructor(socket: WebSocket, transport: WebSocketTransport); + /** + * Listen for the outgoing events from the connected WebSocket client. + */ + addEventListener(type: EventType, listener: WebSocketEventListener, options?: AddEventListenerOptions | boolean): void; + /** + * Removes the listener for the given event. + */ + removeEventListener(event: EventType, listener: WebSocketEventListener, options?: EventListenerOptions | boolean): void; + /** + * Send data to the connected client. + */ + send(data: WebSocketData): void; + /** + * Close the WebSocket connection. + * @param {number} code A status code (see https://www.rfc-editor.org/rfc/rfc6455#section-7.4.1). + * @param {string} reason A custom connection close reason. + */ + close(code?: number, reason?: string): void; +} +//#endregion +//#region src/interceptors/WebSocket/WebSocketClassTransport.d.ts +/** + * Abstraction over the given mock `WebSocket` instance that allows + * for controlling that instance (e.g. sending and receiving messages). + */ +declare class WebSocketClassTransport extends EventTarget implements WebSocketTransport { + protected readonly socket: WebSocketOverride; + constructor(socket: WebSocketOverride); + addEventListener(type: EventType, callback: StrictEventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions): void; + dispatchEvent(event: WebSocketTransportEventMap[EventType]): boolean; + send(data: WebSocketData): void; + close(code: number, reason?: string): void; +} +//#endregion +//#region src/interceptors/WebSocket/WebSocketServerConnection.d.ts +declare const kEmitter: unique symbol; +declare const kSend: unique symbol; +interface WebSocketServerEventMap { + open: Event; + message: MessageEvent; + error: Event; + close: CloseEvent; +} +declare abstract class WebSocketServerConnectionProtocol { + abstract connect(): void; + abstract send(data: WebSocketData): void; + abstract close(): void; + abstract addEventListener(event: EventType, listener: WebSocketEventListener, options?: AddEventListenerOptions | boolean): void; + abstract removeEventListener(event: EventType, listener: WebSocketEventListener, options?: EventListenerOptions | boolean): void; +} +/** + * The WebSocket server instance represents the actual production + * WebSocket server connection. It's idle by default but you can + * establish it by calling `server.connect()`. + */ +declare class WebSocketServerConnection implements WebSocketServerConnectionProtocol { + private readonly client; + private readonly transport; + private readonly createConnection; + /** + * A WebSocket instance connected to the original server. + */ + private realWebSocket?; + private mockCloseController; + private realCloseController; + private [kEmitter]; + constructor(client: WebSocketOverride, transport: WebSocketClassTransport, createConnection: () => WebSocket); + /** + * The `WebSocket` instance connected to the original server. + * Accessing this before calling `server.connect()` will throw. + */ + get socket(): WebSocket; + /** + * Open connection to the original WebSocket server. + */ + connect(): void; + /** + * Listen for the incoming events from the original WebSocket server. + */ + addEventListener(event: EventType, listener: WebSocketEventListener, options?: AddEventListenerOptions | boolean): void; + /** + * Remove the listener for the given event. + */ + removeEventListener(event: EventType, listener: WebSocketEventListener, options?: EventListenerOptions | boolean): void; + /** + * Send data to the original WebSocket server. + * @example + * server.send('hello') + * server.send(new Blob(['hello'])) + * server.send(new TextEncoder().encode('hello')) + */ + send(data: WebSocketData): void; + private [kSend]; + /** + * Close the actual server connection. + */ + close(): void; + private handleIncomingMessage; + private handleMockClose; + private handleRealClose; +} +//#endregion +//#region src/interceptors/WebSocket/index.d.ts +type WebSocketEventMap$1 = { + connection: [args: WebSocketConnectionData]; +}; +type WebSocketConnectionData = { + /** + * The incoming WebSocket client connection. + */ + client: WebSocketClientConnection; + /** + * The original WebSocket server connection. + */ + server: WebSocketServerConnection; + /** + * The connection information. + */ + info: { + /** + * The protocols supported by the WebSocket client. + */ + protocols: string | Array | undefined; + }; +}; +/** + * Intercept the outgoing WebSocket connections created using + * the global `WebSocket` class. + */ +declare class WebSocketInterceptor extends Interceptor { + static symbol: symbol; + constructor(); + protected checkEnvironment(): boolean; + protected setup(): void; +} +//#endregion +export { CancelableCloseEvent, CancelableMessageEvent, CloseEvent, WebSocketClientConnection, WebSocketClientConnectionProtocol, WebSocketClientEventMap, WebSocketConnectionData, type WebSocketData, WebSocketEventMap$1 as WebSocketEventMap, WebSocketInterceptor, WebSocketServerConnection, WebSocketServerConnectionProtocol, WebSocketServerEventMap, type WebSocketTransport }; +//# sourceMappingURL=index.d.mts.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/interceptors/WebSocket/index.mjs b/node_modules/@mswjs/interceptors/lib/browser/interceptors/WebSocket/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..56f46a052b85b21bbfd176212177f3e6745f6d9b --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/interceptors/WebSocket/index.mjs @@ -0,0 +1,611 @@ +import { r as Interceptor, t as createRequestId } from "../../createRequestId-DYCsFHOi.mjs"; +import { t as resolveWebSocketUrl } from "../../resolveWebSocketUrl-C83-x9iE.mjs"; +import { n as patchesRegistry, r as emitAsync, t as hasConfigurableGlobal } from "../../hasConfigurableGlobal-C8zq1MCg.mjs"; +import { DeferredPromise } from "@open-draft/deferred-promise"; +import { invariant } from "outvariant"; + +//#region src/interceptors/WebSocket/utils/bindEvent.ts +function bindEvent(target, event) { + Object.defineProperties(event, { + target: { + value: target, + enumerable: true, + writable: true + }, + currentTarget: { + value: target, + enumerable: true, + writable: true + } + }); + return event; +} + +//#endregion +//#region src/interceptors/WebSocket/utils/events.ts +const kCancelable = Symbol("kCancelable"); +const kDefaultPrevented = Symbol("kDefaultPrevented"); +/** +* A `MessageEvent` superset that supports event cancellation +* in Node.js. It's rather non-intrusive so it can be safely +* used in the browser as well. +* +* @see https://github.com/nodejs/node/issues/51767 +*/ +var CancelableMessageEvent = class extends MessageEvent { + constructor(type, init) { + super(type, init); + this[kCancelable] = !!init.cancelable; + this[kDefaultPrevented] = false; + } + get cancelable() { + return this[kCancelable]; + } + set cancelable(nextCancelable) { + this[kCancelable] = nextCancelable; + } + get defaultPrevented() { + return this[kDefaultPrevented]; + } + set defaultPrevented(nextDefaultPrevented) { + this[kDefaultPrevented] = nextDefaultPrevented; + } + preventDefault() { + if (this.cancelable && !this[kDefaultPrevented]) this[kDefaultPrevented] = true; + } +}; +var CloseEvent = class extends Event { + constructor(type, init = {}) { + super(type, init); + this.code = init.code === void 0 ? 0 : init.code; + this.reason = init.reason === void 0 ? "" : init.reason; + this.wasClean = init.wasClean === void 0 ? false : init.wasClean; + } +}; +var CancelableCloseEvent = class extends CloseEvent { + constructor(type, init = {}) { + super(type, init); + this[kCancelable] = !!init.cancelable; + this[kDefaultPrevented] = false; + } + get cancelable() { + return this[kCancelable]; + } + set cancelable(nextCancelable) { + this[kCancelable] = nextCancelable; + } + get defaultPrevented() { + return this[kDefaultPrevented]; + } + set defaultPrevented(nextDefaultPrevented) { + this[kDefaultPrevented] = nextDefaultPrevented; + } + preventDefault() { + if (this.cancelable && !this[kDefaultPrevented]) this[kDefaultPrevented] = true; + } +}; + +//#endregion +//#region src/interceptors/WebSocket/WebSocketClientConnection.ts +const kEmitter$1 = Symbol("kEmitter"); +const kBoundListener$1 = Symbol("kBoundListener"); +var WebSocketClientConnectionProtocol = class {}; +/** +* The WebSocket client instance represents an incoming +* client connection. The user can control the connection, +* send and receive events. +*/ +var WebSocketClientConnection = class { + constructor(socket, transport) { + this.socket = socket; + this.transport = transport; + this.id = createRequestId(); + this.url = new URL(socket.url); + this[kEmitter$1] = new EventTarget(); + this.transport.addEventListener("outgoing", (event) => { + const message = bindEvent(this.socket, new CancelableMessageEvent("message", { + data: event.data, + origin: event.origin, + cancelable: true + })); + this[kEmitter$1].dispatchEvent(message); + if (message.defaultPrevented) event.preventDefault(); + }); + /** + * Emit the "close" event on the "client" connection + * whenever the underlying transport is closed. + * @note "client.close()" does NOT dispatch the "close" + * event on the WebSocket because it uses non-configurable + * close status code. Thus, we listen to the transport + * instead of the WebSocket's "close" event. + */ + this.transport.addEventListener("close", (event) => { + this[kEmitter$1].dispatchEvent(bindEvent(this.socket, new CloseEvent("close", event))); + }); + } + /** + * Listen for the outgoing events from the connected WebSocket client. + */ + addEventListener(type, listener, options) { + if (!Reflect.has(listener, kBoundListener$1)) { + const boundListener = listener.bind(this.socket); + Object.defineProperty(listener, kBoundListener$1, { + value: boundListener, + enumerable: false, + configurable: false + }); + } + this[kEmitter$1].addEventListener(type, Reflect.get(listener, kBoundListener$1), options); + } + /** + * Removes the listener for the given event. + */ + removeEventListener(event, listener, options) { + this[kEmitter$1].removeEventListener(event, Reflect.get(listener, kBoundListener$1), options); + } + /** + * Send data to the connected client. + */ + send(data) { + this.transport.send(data); + } + /** + * Close the WebSocket connection. + * @param {number} code A status code (see https://www.rfc-editor.org/rfc/rfc6455#section-7.4.1). + * @param {string} reason A custom connection close reason. + */ + close(code, reason) { + this.transport.close(code, reason); + } +}; + +//#endregion +//#region src/interceptors/WebSocket/WebSocketOverride.ts +const WEBSOCKET_CLOSE_CODE_RANGE_ERROR = "InvalidAccessError: close code out of user configurable range"; +const kPassthroughPromise = Symbol("kPassthroughPromise"); +const kOnSend = Symbol("kOnSend"); +const kClose = Symbol("kClose"); +var WebSocketOverride = class extends EventTarget { + static { + this.CONNECTING = 0; + } + static { + this.OPEN = 1; + } + static { + this.CLOSING = 2; + } + static { + this.CLOSED = 3; + } + constructor(url, protocols) { + super(); + this.CONNECTING = 0; + this.OPEN = 1; + this.CLOSING = 2; + this.CLOSED = 3; + this._onopen = null; + this._onmessage = null; + this._onerror = null; + this._onclose = null; + this.url = resolveWebSocketUrl(url); + this.protocol = ""; + this.extensions = ""; + this.binaryType = "blob"; + this.readyState = this.CONNECTING; + this.bufferedAmount = 0; + this[kPassthroughPromise] = new DeferredPromise(); + queueMicrotask(async () => { + if (await this[kPassthroughPromise]) return; + this.protocol = typeof protocols === "string" ? protocols : Array.isArray(protocols) && protocols.length > 0 ? protocols[0] : ""; + /** + * @note Check that nothing has prevented this connection + * (e.g. called `client.close()` in the connection listener). + * If the connection has been prevented, never dispatch the open event,. + */ + if (this.readyState === this.CONNECTING) { + this.readyState = this.OPEN; + this.dispatchEvent(bindEvent(this, new Event("open"))); + } + }); + } + set onopen(listener) { + this.removeEventListener("open", this._onopen); + this._onopen = listener; + if (listener !== null) this.addEventListener("open", listener); + } + get onopen() { + return this._onopen; + } + set onmessage(listener) { + this.removeEventListener("message", this._onmessage); + this._onmessage = listener; + if (listener !== null) this.addEventListener("message", listener); + } + get onmessage() { + return this._onmessage; + } + set onerror(listener) { + this.removeEventListener("error", this._onerror); + this._onerror = listener; + if (listener !== null) this.addEventListener("error", listener); + } + get onerror() { + return this._onerror; + } + set onclose(listener) { + this.removeEventListener("close", this._onclose); + this._onclose = listener; + if (listener !== null) this.addEventListener("close", listener); + } + get onclose() { + return this._onclose; + } + /** + * @see https://websockets.spec.whatwg.org/#ref-for-dom-websocket-send%E2%91%A0 + */ + send(data) { + if (this.readyState === this.CONNECTING) { + this.close(); + throw new DOMException("InvalidStateError"); + } + if (this.readyState === this.CLOSING || this.readyState === this.CLOSED) return; + this.bufferedAmount += getDataSize(data); + queueMicrotask(() => { + this.bufferedAmount = 0; + /** + * @note Notify the parent about outgoing data. + * This notifies the transport and the connection + * listens to the outgoing data to emit the "message" event. + */ + this[kOnSend]?.(data); + }); + } + close(code = 1e3, reason) { + invariant(code, WEBSOCKET_CLOSE_CODE_RANGE_ERROR); + invariant(code === 1e3 || code >= 3e3 && code <= 4999, WEBSOCKET_CLOSE_CODE_RANGE_ERROR); + this[kClose](code, reason); + } + [kClose](code = 1e3, reason, wasClean = true) { + /** + * @note Move this check here so that even internal closures, + * like those triggered by the `server` connection, are not + * performed twice. + */ + if (this.readyState === this.CLOSING || this.readyState === this.CLOSED) return; + this.readyState = this.CLOSING; + queueMicrotask(() => { + this.readyState = this.CLOSED; + this.dispatchEvent(bindEvent(this, new CloseEvent("close", { + code, + reason, + wasClean + }))); + this._onopen = null; + this._onmessage = null; + this._onerror = null; + this._onclose = null; + }); + } + addEventListener(type, listener, options) { + return super.addEventListener(type, listener, options); + } + removeEventListener(type, callback, options) { + return super.removeEventListener(type, callback, options); + } +}; +function getDataSize(data) { + if (typeof data === "string") return data.length; + if (data instanceof Blob) return data.size; + return data.byteLength; +} + +//#endregion +//#region src/interceptors/WebSocket/WebSocketServerConnection.ts +const kEmitter = Symbol("kEmitter"); +const kBoundListener = Symbol("kBoundListener"); +const kSend = Symbol("kSend"); +var WebSocketServerConnectionProtocol = class {}; +/** +* The WebSocket server instance represents the actual production +* WebSocket server connection. It's idle by default but you can +* establish it by calling `server.connect()`. +*/ +var WebSocketServerConnection = class { + constructor(client, transport, createConnection) { + this.client = client; + this.transport = transport; + this.createConnection = createConnection; + this[kEmitter] = new EventTarget(); + this.mockCloseController = new AbortController(); + this.realCloseController = new AbortController(); + this.transport.addEventListener("outgoing", (event) => { + if (typeof this.realWebSocket === "undefined") return; + queueMicrotask(() => { + if (!event.defaultPrevented) + /** + * @note Use the internal send mechanism so consumers can tell + * apart direct user calls to `server.send()` and internal calls. + * E.g. MSW has to ignore this internal call to log out messages correctly. + */ + this[kSend](event.data); + }); + }); + this.transport.addEventListener("incoming", this.handleIncomingMessage.bind(this)); + } + /** + * The `WebSocket` instance connected to the original server. + * Accessing this before calling `server.connect()` will throw. + */ + get socket() { + invariant(this.realWebSocket, "Cannot access \"socket\" on the original WebSocket server object: the connection is not open. Did you forget to call `server.connect()`?"); + return this.realWebSocket; + } + /** + * Open connection to the original WebSocket server. + */ + connect() { + invariant(!this.realWebSocket || this.realWebSocket.readyState !== WebSocket.OPEN, "Failed to call \"connect()\" on the original WebSocket instance: the connection already open"); + const realWebSocket = this.createConnection(); + realWebSocket.binaryType = this.client.binaryType; + realWebSocket.addEventListener("open", (event) => { + this[kEmitter].dispatchEvent(bindEvent(this.realWebSocket, new Event("open", event))); + }, { once: true }); + realWebSocket.addEventListener("message", (event) => { + this.transport.dispatchEvent(bindEvent(this.realWebSocket, new MessageEvent("incoming", { + data: event.data, + origin: event.origin + }))); + }); + this.client.addEventListener("close", (event) => { + this.handleMockClose(event); + }, { signal: this.mockCloseController.signal }); + realWebSocket.addEventListener("close", (event) => { + this.handleRealClose(event); + }, { signal: this.realCloseController.signal }); + realWebSocket.addEventListener("error", () => { + const errorEvent = bindEvent(realWebSocket, new Event("error", { cancelable: true })); + this[kEmitter].dispatchEvent(errorEvent); + if (!errorEvent.defaultPrevented) this.client.dispatchEvent(bindEvent(this.client, new Event("error"))); + }); + this.realWebSocket = realWebSocket; + } + /** + * Listen for the incoming events from the original WebSocket server. + */ + addEventListener(event, listener, options) { + if (!Reflect.has(listener, kBoundListener)) { + const boundListener = listener.bind(this.client); + Object.defineProperty(listener, kBoundListener, { + value: boundListener, + enumerable: false + }); + } + this[kEmitter].addEventListener(event, Reflect.get(listener, kBoundListener), options); + } + /** + * Remove the listener for the given event. + */ + removeEventListener(event, listener, options) { + this[kEmitter].removeEventListener(event, Reflect.get(listener, kBoundListener), options); + } + /** + * Send data to the original WebSocket server. + * @example + * server.send('hello') + * server.send(new Blob(['hello'])) + * server.send(new TextEncoder().encode('hello')) + */ + send(data) { + this[kSend](data); + } + [kSend](data) { + const { realWebSocket } = this; + invariant(realWebSocket, "Failed to call \"server.send()\" for \"%s\": the connection is not open. Did you forget to call \"server.connect()\"?", this.client.url); + if (realWebSocket.readyState === WebSocket.CLOSING || realWebSocket.readyState === WebSocket.CLOSED) return; + if (realWebSocket.readyState === WebSocket.CONNECTING) { + realWebSocket.addEventListener("open", () => { + realWebSocket.send(data); + }, { once: true }); + return; + } + realWebSocket.send(data); + } + /** + * Close the actual server connection. + */ + close() { + const { realWebSocket } = this; + invariant(realWebSocket, "Failed to close server connection for \"%s\": the connection is not open. Did you forget to call \"server.connect()\"?", this.client.url); + this.realCloseController.abort(); + if (realWebSocket.readyState === WebSocket.CLOSING || realWebSocket.readyState === WebSocket.CLOSED) return; + realWebSocket.close(); + queueMicrotask(() => { + this[kEmitter].dispatchEvent(bindEvent(this.realWebSocket, new CancelableCloseEvent("close", { + code: 1e3, + cancelable: true + }))); + }); + } + handleIncomingMessage(event) { + const messageEvent = bindEvent(event.target, new CancelableMessageEvent("message", { + data: event.data, + origin: event.origin, + cancelable: true + })); + /** + * @note Emit "message" event on the server connection + * instance to let the interceptor know about these + * incoming events from the original server. In that listener, + * the interceptor can modify or skip the event forwarding + * to the mock WebSocket instance. + */ + this[kEmitter].dispatchEvent(messageEvent); + /** + * @note Forward the incoming server events to the client. + * Preventing the default on the message event stops this. + */ + if (!messageEvent.defaultPrevented) this.client.dispatchEvent(bindEvent( + /** + * @note Bind the forwarded original server events + * to the mock WebSocket instance so it would + * dispatch them straight away. + */ + this.client, + new MessageEvent("message", { + data: event.data, + origin: event.origin + }) + )); + } + handleMockClose(_event) { + if (this.realWebSocket) this.realWebSocket.close(); + } + handleRealClose(event) { + this.mockCloseController.abort(); + const closeEvent = bindEvent(this.realWebSocket, new CancelableCloseEvent("close", { + code: event.code, + reason: event.reason, + wasClean: event.wasClean, + cancelable: true + })); + this[kEmitter].dispatchEvent(closeEvent); + if (!closeEvent.defaultPrevented) this.client[kClose](event.code, event.reason); + } +}; + +//#endregion +//#region src/interceptors/WebSocket/WebSocketClassTransport.ts +/** +* Abstraction over the given mock `WebSocket` instance that allows +* for controlling that instance (e.g. sending and receiving messages). +*/ +var WebSocketClassTransport = class extends EventTarget { + constructor(socket) { + super(); + this.socket = socket; + this.socket.addEventListener("close", (event) => { + this.dispatchEvent(bindEvent(this.socket, new CloseEvent("close", event))); + }); + /** + * Emit the "outgoing" event on the transport + * whenever the WebSocket client sends data ("ws.send()"). + */ + this.socket[kOnSend] = (data) => { + this.dispatchEvent(bindEvent(this.socket, new CancelableMessageEvent("outgoing", { + data, + origin: this.socket.url, + cancelable: true + }))); + }; + } + addEventListener(type, callback, options) { + return super.addEventListener(type, callback, options); + } + dispatchEvent(event) { + return super.dispatchEvent(event); + } + send(data) { + queueMicrotask(() => { + if (this.socket.readyState === this.socket.CLOSING || this.socket.readyState === this.socket.CLOSED) return; + const dispatchEvent = () => { + this.socket.dispatchEvent(bindEvent( + /** + * @note Setting this event's "target" to the + * WebSocket override instance is important. + * This way it can tell apart original incoming events + * (must be forwarded to the transport) from the + * mocked message events like the one below + * (must be dispatched on the client instance). + */ + this.socket, + new MessageEvent("message", { + data, + origin: this.socket.url + }) + )); + }; + if (this.socket.readyState === this.socket.CONNECTING) this.socket.addEventListener("open", () => { + dispatchEvent(); + }, { once: true }); + else dispatchEvent(); + }); + } + close(code, reason) { + /** + * @note Call the internal close method directly + * to allow closing the connection with the status codes + * that are non-configurable by the user (> 1000 <= 1015). + */ + this.socket[kClose](code, reason); + } +}; + +//#endregion +//#region src/interceptors/WebSocket/index.ts +/** +* Intercept the outgoing WebSocket connections created using +* the global `WebSocket` class. +*/ +var WebSocketInterceptor = class WebSocketInterceptor extends Interceptor { + static { + this.symbol = Symbol.for("websocket-interceptor"); + } + constructor() { + super(WebSocketInterceptor.symbol); + } + checkEnvironment() { + return hasConfigurableGlobal("WebSocket"); + } + setup() { + const logger = this.logger.extend("setup"); + const WebSocketProxy = new Proxy(globalThis.WebSocket, { construct: (target, args, newTarget) => { + const [url, protocols] = args; + const createConnection = () => { + return Reflect.construct(target, args, newTarget); + }; + const socket = new WebSocketOverride(url, protocols); + const transport = new WebSocketClassTransport(socket); + queueMicrotask(async () => { + try { + const server = new WebSocketServerConnection(socket, transport, createConnection); + const hasConnectionListeners = this.emitter.listenerCount("connection") > 0; + await emitAsync(this.emitter, "connection", { + client: new WebSocketClientConnection(socket, transport), + server, + info: { protocols } + }); + if (hasConnectionListeners) socket[kPassthroughPromise].resolve(false); + else { + socket[kPassthroughPromise].resolve(true); + server.connect(); + server.addEventListener("open", () => { + socket.dispatchEvent(bindEvent(socket, new Event("open"))); + if (server["realWebSocket"]) socket.protocol = server["realWebSocket"].protocol; + }); + } + } catch (error) { + /** + * @note Translate unhandled exceptions during the connection + * handling (i.e. interceptor exceptions) as WebSocket connection + * closures with error. This prevents from the exceptions occurring + * in `queueMicrotask` from being process-wide and uncatchable. + */ + if (error instanceof Error) { + socket.dispatchEvent(new Event("error")); + if (socket.readyState !== WebSocket.CLOSING && socket.readyState !== WebSocket.CLOSED) socket[kClose](1011, error.message, false); + console.error(error); + } + } + }); + return socket; + } }); + logger.info("patching global WebSocket..."); + this.subscriptions.push(patchesRegistry.applyPatch(globalThis, "WebSocket", () => WebSocketProxy)); + logger.info("global WebSocket patched!", globalThis.WebSocket.name); + } +}; + +//#endregion +export { CancelableCloseEvent, CancelableMessageEvent, CloseEvent, WebSocketClientConnection, WebSocketClientConnectionProtocol, WebSocketInterceptor, WebSocketServerConnection, WebSocketServerConnectionProtocol }; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/interceptors/WebSocket/index.mjs.map b/node_modules/@mswjs/interceptors/lib/browser/interceptors/WebSocket/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..09ac678fbccc1b9772fe3092806429699165c9ab --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/interceptors/WebSocket/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.mjs","names":["kEmitter","kBoundListener","socket: WebSocket","transport: WebSocketTransport","client: WebSocketOverride","transport: WebSocketClassTransport","createConnection: () => WebSocket","socket: WebSocketOverride"],"sources":["../../../../src/interceptors/WebSocket/utils/bindEvent.ts","../../../../src/interceptors/WebSocket/utils/events.ts","../../../../src/interceptors/WebSocket/WebSocketClientConnection.ts","../../../../src/interceptors/WebSocket/WebSocketOverride.ts","../../../../src/interceptors/WebSocket/WebSocketServerConnection.ts","../../../../src/interceptors/WebSocket/WebSocketClassTransport.ts","../../../../src/interceptors/WebSocket/index.ts"],"sourcesContent":["type EventWithTarget = E & { target: T }\n\nexport function bindEvent(\n target: T,\n event: E\n): EventWithTarget {\n Object.defineProperties(event, {\n target: {\n value: target,\n enumerable: true,\n writable: true,\n },\n currentTarget: {\n value: target,\n enumerable: true,\n writable: true,\n },\n })\n\n return event as EventWithTarget\n}\n","const kCancelable = Symbol('kCancelable')\nconst kDefaultPrevented = Symbol('kDefaultPrevented')\n\n/**\n * A `MessageEvent` superset that supports event cancellation\n * in Node.js. It's rather non-intrusive so it can be safely\n * used in the browser as well.\n *\n * @see https://github.com/nodejs/node/issues/51767\n */\nexport class CancelableMessageEvent extends MessageEvent {\n [kCancelable]: boolean;\n [kDefaultPrevented]: boolean\n\n constructor(type: string, init: MessageEventInit) {\n super(type, init)\n this[kCancelable] = !!init.cancelable\n this[kDefaultPrevented] = false\n }\n\n get cancelable() {\n return this[kCancelable]\n }\n\n set cancelable(nextCancelable) {\n this[kCancelable] = nextCancelable\n }\n\n get defaultPrevented() {\n return this[kDefaultPrevented]\n }\n\n set defaultPrevented(nextDefaultPrevented) {\n this[kDefaultPrevented] = nextDefaultPrevented\n }\n\n public preventDefault(): void {\n if (this.cancelable && !this[kDefaultPrevented]) {\n this[kDefaultPrevented] = true\n }\n }\n}\n\ninterface CloseEventInit extends EventInit {\n code?: number\n reason?: string\n wasClean?: boolean\n}\n\nexport class CloseEvent extends Event {\n public code: number\n public reason: string\n public wasClean: boolean\n\n constructor(type: string, init: CloseEventInit = {}) {\n super(type, init)\n this.code = init.code === undefined ? 0 : init.code\n this.reason = init.reason === undefined ? '' : init.reason\n this.wasClean = init.wasClean === undefined ? false : init.wasClean\n }\n}\n\nexport class CancelableCloseEvent extends CloseEvent {\n [kCancelable]: boolean;\n [kDefaultPrevented]: boolean\n\n constructor(type: string, init: CloseEventInit = {}) {\n super(type, init)\n this[kCancelable] = !!init.cancelable\n this[kDefaultPrevented] = false\n }\n\n get cancelable() {\n return this[kCancelable]\n }\n\n set cancelable(nextCancelable) {\n this[kCancelable] = nextCancelable\n }\n\n get defaultPrevented() {\n return this[kDefaultPrevented]\n }\n\n set defaultPrevented(nextDefaultPrevented) {\n this[kDefaultPrevented] = nextDefaultPrevented\n }\n\n public preventDefault(): void {\n if (this.cancelable && !this[kDefaultPrevented]) {\n this[kDefaultPrevented] = true\n }\n }\n}\n","import type { WebSocketData, WebSocketTransport } from './WebSocketTransport'\nimport type { WebSocketEventListener } from './WebSocketOverride'\nimport { bindEvent } from './utils/bindEvent'\nimport { CancelableMessageEvent, CloseEvent } from './utils/events'\nimport { createRequestId } from '../../createRequestId'\n\nconst kEmitter = Symbol('kEmitter')\nconst kBoundListener = Symbol('kBoundListener')\n\nexport interface WebSocketClientEventMap {\n message: MessageEvent\n close: CloseEvent\n}\n\nexport abstract class WebSocketClientConnectionProtocol {\n abstract id: string\n abstract url: URL\n public abstract send(data: WebSocketData): void\n public abstract close(code?: number, reason?: string): void\n\n public abstract addEventListener<\n EventType extends keyof WebSocketClientEventMap,\n >(\n type: EventType,\n listener: WebSocketEventListener,\n options?: AddEventListenerOptions | boolean\n ): void\n\n public abstract removeEventListener<\n EventType extends keyof WebSocketClientEventMap,\n >(\n event: EventType,\n listener: WebSocketEventListener,\n options?: EventListenerOptions | boolean\n ): void\n}\n\n/**\n * The WebSocket client instance represents an incoming\n * client connection. The user can control the connection,\n * send and receive events.\n */\nexport class WebSocketClientConnection implements WebSocketClientConnectionProtocol {\n public readonly id: string\n public readonly url: URL\n\n private [kEmitter]: EventTarget\n\n constructor(\n public readonly socket: WebSocket,\n private readonly transport: WebSocketTransport\n ) {\n this.id = createRequestId()\n this.url = new URL(socket.url)\n this[kEmitter] = new EventTarget()\n\n // Emit outgoing client data (\"ws.send()\") as \"message\"\n // events on the \"client\" connection.\n this.transport.addEventListener('outgoing', (event) => {\n const message = bindEvent(\n this.socket,\n new CancelableMessageEvent('message', {\n data: event.data,\n origin: event.origin,\n cancelable: true,\n })\n )\n\n this[kEmitter].dispatchEvent(message)\n\n // This is a bit silly but forward the cancellation state\n // of the \"client\" message event to the \"outgoing\" transport event.\n // This way, other agens (like \"server\" connection) can know\n // whether the client listener has pervented the default.\n if (message.defaultPrevented) {\n event.preventDefault()\n }\n })\n\n /**\n * Emit the \"close\" event on the \"client\" connection\n * whenever the underlying transport is closed.\n * @note \"client.close()\" does NOT dispatch the \"close\"\n * event on the WebSocket because it uses non-configurable\n * close status code. Thus, we listen to the transport\n * instead of the WebSocket's \"close\" event.\n */\n this.transport.addEventListener('close', (event) => {\n this[kEmitter].dispatchEvent(\n bindEvent(this.socket, new CloseEvent('close', event))\n )\n })\n }\n\n /**\n * Listen for the outgoing events from the connected WebSocket client.\n */\n public addEventListener(\n type: EventType,\n listener: WebSocketEventListener,\n options?: AddEventListenerOptions | boolean\n ): void {\n if (!Reflect.has(listener, kBoundListener)) {\n const boundListener = listener.bind(this.socket)\n\n // Store the bound listener on the original listener\n // so the exact bound function can be accessed in \"removeEventListener()\".\n Object.defineProperty(listener, kBoundListener, {\n value: boundListener,\n enumerable: false,\n configurable: false,\n })\n }\n\n this[kEmitter].addEventListener(\n type,\n Reflect.get(listener, kBoundListener) as EventListener,\n options\n )\n }\n\n /**\n * Removes the listener for the given event.\n */\n public removeEventListener(\n event: EventType,\n listener: WebSocketEventListener,\n options?: EventListenerOptions | boolean\n ): void {\n this[kEmitter].removeEventListener(\n event,\n Reflect.get(listener, kBoundListener) as EventListener,\n options\n )\n }\n\n /**\n * Send data to the connected client.\n */\n public send(data: WebSocketData): void {\n this.transport.send(data)\n }\n\n /**\n * Close the WebSocket connection.\n * @param {number} code A status code (see https://www.rfc-editor.org/rfc/rfc6455#section-7.4.1).\n * @param {string} reason A custom connection close reason.\n */\n public close(code?: number, reason?: string): void {\n this.transport.close(code, reason)\n }\n}\n","import { invariant } from 'outvariant'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport type { WebSocketData } from './WebSocketTransport'\nimport { bindEvent } from './utils/bindEvent'\nimport { CloseEvent } from './utils/events'\nimport { resolveWebSocketUrl } from '../../utils/resolveWebSocketUrl'\n\nexport type WebSocketEventListener<\n EventType extends WebSocketEventMap[keyof WebSocketEventMap] = Event,\n> = (this: WebSocket, event: EventType) => void\n\nconst WEBSOCKET_CLOSE_CODE_RANGE_ERROR =\n 'InvalidAccessError: close code out of user configurable range'\n\nexport const kPassthroughPromise = Symbol('kPassthroughPromise')\nexport const kOnSend = Symbol('kOnSend')\nexport const kClose = Symbol('kClose')\n\nexport class WebSocketOverride extends EventTarget implements WebSocket {\n static readonly CONNECTING = 0\n static readonly OPEN = 1\n static readonly CLOSING = 2\n static readonly CLOSED = 3\n readonly CONNECTING = 0\n readonly OPEN = 1\n readonly CLOSING = 2\n readonly CLOSED = 3\n\n public url: string\n public protocol: string\n public extensions: string\n public binaryType: BinaryType\n public readyState: WebSocket['readyState']\n public bufferedAmount: number\n\n private _onopen: WebSocketEventListener | null = null\n private _onmessage: WebSocketEventListener<\n MessageEvent\n > | null = null\n private _onerror: WebSocketEventListener | null = null\n private _onclose: WebSocketEventListener | null = null\n\n private [kPassthroughPromise]: DeferredPromise\n private [kOnSend]?: (data: WebSocketData) => void\n\n constructor(url: string | URL, protocols?: string | Array) {\n super()\n this.url = resolveWebSocketUrl(url)\n this.protocol = ''\n this.extensions = ''\n this.binaryType = 'blob'\n this.readyState = this.CONNECTING\n this.bufferedAmount = 0\n\n this[kPassthroughPromise] = new DeferredPromise()\n\n queueMicrotask(async () => {\n if (await this[kPassthroughPromise]) {\n return\n }\n\n this.protocol =\n typeof protocols === 'string'\n ? protocols\n : Array.isArray(protocols) && protocols.length > 0\n ? protocols[0]\n : ''\n\n /**\n * @note Check that nothing has prevented this connection\n * (e.g. called `client.close()` in the connection listener).\n * If the connection has been prevented, never dispatch the open event,.\n */\n if (this.readyState === this.CONNECTING) {\n this.readyState = this.OPEN\n this.dispatchEvent(bindEvent(this, new Event('open')))\n }\n })\n }\n\n set onopen(listener: WebSocketEventListener | null) {\n this.removeEventListener('open', this._onopen)\n this._onopen = listener\n if (listener !== null) {\n this.addEventListener('open', listener)\n }\n }\n get onopen(): WebSocketEventListener | null {\n return this._onopen\n }\n\n set onmessage(\n listener: WebSocketEventListener> | null\n ) {\n this.removeEventListener(\n 'message',\n this._onmessage as WebSocketEventListener\n )\n this._onmessage = listener\n if (listener !== null) {\n this.addEventListener('message', listener)\n }\n }\n get onmessage(): WebSocketEventListener> | null {\n return this._onmessage\n }\n\n set onerror(listener: WebSocketEventListener | null) {\n this.removeEventListener('error', this._onerror)\n this._onerror = listener\n if (listener !== null) {\n this.addEventListener('error', listener)\n }\n }\n get onerror(): WebSocketEventListener | null {\n return this._onerror\n }\n\n set onclose(listener: WebSocketEventListener | null) {\n this.removeEventListener('close', this._onclose as WebSocketEventListener)\n this._onclose = listener\n if (listener !== null) {\n this.addEventListener('close', listener)\n }\n }\n get onclose(): WebSocketEventListener | null {\n return this._onclose\n }\n\n /**\n * @see https://websockets.spec.whatwg.org/#ref-for-dom-websocket-send%E2%91%A0\n */\n public send(data: WebSocketData): void {\n if (this.readyState === this.CONNECTING) {\n this.close()\n throw new DOMException('InvalidStateError')\n }\n\n // Sending when the socket is about to close\n // discards the sent data.\n if (this.readyState === this.CLOSING || this.readyState === this.CLOSED) {\n return\n }\n\n // Buffer the data to send in this even loop\n // but send it in the next.\n this.bufferedAmount += getDataSize(data)\n\n queueMicrotask(() => {\n // This is a bit optimistic but since no actual data transfer\n // is involved, all the data will be \"sent\" on the next tick.\n this.bufferedAmount = 0\n\n /**\n * @note Notify the parent about outgoing data.\n * This notifies the transport and the connection\n * listens to the outgoing data to emit the \"message\" event.\n */\n this[kOnSend]?.(data)\n })\n }\n\n public close(code: number = 1000, reason?: string): void {\n invariant(code, WEBSOCKET_CLOSE_CODE_RANGE_ERROR)\n invariant(\n code === 1000 || (code >= 3000 && code <= 4999),\n WEBSOCKET_CLOSE_CODE_RANGE_ERROR\n )\n\n this[kClose](code, reason)\n }\n\n private [kClose](\n code: number = 1000,\n reason?: string,\n wasClean = true\n ): void {\n /**\n * @note Move this check here so that even internal closures,\n * like those triggered by the `server` connection, are not\n * performed twice.\n */\n if (this.readyState === this.CLOSING || this.readyState === this.CLOSED) {\n return\n }\n\n this.readyState = this.CLOSING\n\n queueMicrotask(() => {\n this.readyState = this.CLOSED\n\n this.dispatchEvent(\n bindEvent(\n this,\n new CloseEvent('close', {\n code,\n reason,\n wasClean,\n })\n )\n )\n\n // Remove all event listeners once the socket is closed.\n this._onopen = null\n this._onmessage = null\n this._onerror = null\n this._onclose = null\n })\n }\n\n public addEventListener(\n type: K,\n listener: (this: WebSocket, event: WebSocketEventMap[K]) => void,\n options?: boolean | AddEventListenerOptions\n ): void\n public addEventListener(\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions\n ): void\n public addEventListener(\n type: unknown,\n listener: unknown,\n options?: unknown\n ): void {\n return super.addEventListener(\n type as string,\n listener as EventListener,\n options as AddEventListenerOptions\n )\n }\n\n removeEventListener(\n type: K,\n callback: EventListenerOrEventListenerObject | null,\n options?: boolean | EventListenerOptions\n ): void {\n return super.removeEventListener(type, callback, options)\n }\n}\n\nfunction getDataSize(data: WebSocketData): number {\n if (typeof data === 'string') {\n return data.length\n }\n\n if (data instanceof Blob) {\n return data.size\n }\n\n return data.byteLength\n}\n","import { invariant } from 'outvariant'\nimport {\n kClose,\n WebSocketEventListener,\n WebSocketOverride,\n} from './WebSocketOverride'\nimport type { WebSocketData } from './WebSocketTransport'\nimport type { WebSocketClassTransport } from './WebSocketClassTransport'\nimport { bindEvent } from './utils/bindEvent'\nimport {\n CancelableMessageEvent,\n CancelableCloseEvent,\n CloseEvent,\n} from './utils/events'\n\nconst kEmitter = Symbol('kEmitter')\nconst kBoundListener = Symbol('kBoundListener')\nconst kSend = Symbol('kSend')\n\nexport interface WebSocketServerEventMap {\n open: Event\n message: MessageEvent\n error: Event\n close: CloseEvent\n}\n\nexport abstract class WebSocketServerConnectionProtocol {\n public abstract connect(): void\n public abstract send(data: WebSocketData): void\n public abstract close(): void\n\n public abstract addEventListener<\n EventType extends keyof WebSocketServerEventMap,\n >(\n event: EventType,\n listener: WebSocketEventListener,\n options?: AddEventListenerOptions | boolean\n ): void\n\n public abstract removeEventListener<\n EventType extends keyof WebSocketServerEventMap,\n >(\n event: EventType,\n listener: WebSocketEventListener,\n options?: EventListenerOptions | boolean\n ): void\n}\n\n/**\n * The WebSocket server instance represents the actual production\n * WebSocket server connection. It's idle by default but you can\n * establish it by calling `server.connect()`.\n */\nexport class WebSocketServerConnection implements WebSocketServerConnectionProtocol {\n /**\n * A WebSocket instance connected to the original server.\n */\n private realWebSocket?: WebSocket\n private mockCloseController: AbortController\n private realCloseController: AbortController\n private [kEmitter]: EventTarget\n\n constructor(\n private readonly client: WebSocketOverride,\n private readonly transport: WebSocketClassTransport,\n private readonly createConnection: () => WebSocket\n ) {\n this[kEmitter] = new EventTarget()\n this.mockCloseController = new AbortController()\n this.realCloseController = new AbortController()\n\n // Automatically forward outgoing client events\n // to the actual server unless the outgoing message event\n // has been prevented. The \"outgoing\" transport event it\n // dispatched by the \"client\" connection.\n this.transport.addEventListener('outgoing', (event) => {\n // Ignore client messages if the server connection\n // hasn't been established yet. Nowhere to forward.\n if (typeof this.realWebSocket === 'undefined') {\n return\n }\n\n // Every outgoing client message can prevent this forwarding\n // by preventing the default of the outgoing message event.\n // This listener will be added before user-defined listeners,\n // so execute the logic on the next tick.\n queueMicrotask(() => {\n if (!event.defaultPrevented) {\n /**\n * @note Use the internal send mechanism so consumers can tell\n * apart direct user calls to `server.send()` and internal calls.\n * E.g. MSW has to ignore this internal call to log out messages correctly.\n */\n this[kSend](event.data)\n }\n })\n })\n\n this.transport.addEventListener(\n 'incoming',\n this.handleIncomingMessage.bind(this)\n )\n }\n\n /**\n * The `WebSocket` instance connected to the original server.\n * Accessing this before calling `server.connect()` will throw.\n */\n public get socket(): WebSocket {\n invariant(\n this.realWebSocket,\n 'Cannot access \"socket\" on the original WebSocket server object: the connection is not open. Did you forget to call `server.connect()`?'\n )\n\n return this.realWebSocket\n }\n\n /**\n * Open connection to the original WebSocket server.\n */\n public connect(): void {\n invariant(\n !this.realWebSocket || this.realWebSocket.readyState !== WebSocket.OPEN,\n 'Failed to call \"connect()\" on the original WebSocket instance: the connection already open'\n )\n\n const realWebSocket = this.createConnection()\n\n // Inherit the binary type from the mock WebSocket client.\n realWebSocket.binaryType = this.client.binaryType\n\n // Allow the interceptor to listen to when the server connection\n // has been established. This isn't necessary to operate with the connection\n // but may be beneficial in some cases (like conditionally adding logging).\n realWebSocket.addEventListener(\n 'open',\n (event) => {\n this[kEmitter].dispatchEvent(\n bindEvent(this.realWebSocket!, new Event('open', event))\n )\n },\n { once: true }\n )\n\n realWebSocket.addEventListener('message', (event) => {\n // Dispatch the \"incoming\" transport event instead of\n // invoking the internal handler directly. This way,\n // anyone can listen to the \"incoming\" event but this\n // class is the one resulting in it.\n this.transport.dispatchEvent(\n bindEvent(\n this.realWebSocket!,\n new MessageEvent('incoming', {\n data: event.data,\n origin: event.origin,\n })\n )\n )\n })\n\n // Close the original connection when the mock client closes.\n // E.g. \"client.close()\" was called. This is never forwarded anywhere.\n this.client.addEventListener(\n 'close',\n (event) => {\n this.handleMockClose(event)\n },\n {\n signal: this.mockCloseController.signal,\n }\n )\n\n // Forward the \"close\" event to let the interceptor handle\n // closures initiated by the original server.\n realWebSocket.addEventListener(\n 'close',\n (event) => {\n this.handleRealClose(event)\n },\n {\n signal: this.realCloseController.signal,\n }\n )\n\n realWebSocket.addEventListener('error', () => {\n const errorEvent = bindEvent(\n realWebSocket,\n new Event('error', { cancelable: true })\n )\n\n // Emit the \"error\" event on the `server` connection\n // to let the interceptor react to original server errors.\n this[kEmitter].dispatchEvent(errorEvent)\n\n // If the error event from the original server hasn't been prevented,\n // forward it to the underlying client.\n if (!errorEvent.defaultPrevented) {\n this.client.dispatchEvent(bindEvent(this.client, new Event('error')))\n }\n })\n\n this.realWebSocket = realWebSocket\n }\n\n /**\n * Listen for the incoming events from the original WebSocket server.\n */\n public addEventListener(\n event: EventType,\n listener: WebSocketEventListener,\n options?: AddEventListenerOptions | boolean\n ): void {\n if (!Reflect.has(listener, kBoundListener)) {\n const boundListener = listener.bind(this.client)\n\n // Store the bound listener on the original listener\n // so the exact bound function can be accessed in \"removeEventListener()\".\n Object.defineProperty(listener, kBoundListener, {\n value: boundListener,\n enumerable: false,\n })\n }\n\n this[kEmitter].addEventListener(\n event,\n Reflect.get(listener, kBoundListener) as EventListener,\n options\n )\n }\n\n /**\n * Remove the listener for the given event.\n */\n public removeEventListener(\n event: EventType,\n listener: WebSocketEventListener,\n options?: EventListenerOptions | boolean\n ): void {\n this[kEmitter].removeEventListener(\n event,\n Reflect.get(listener, kBoundListener) as EventListener,\n options\n )\n }\n\n /**\n * Send data to the original WebSocket server.\n * @example\n * server.send('hello')\n * server.send(new Blob(['hello']))\n * server.send(new TextEncoder().encode('hello'))\n */\n public send(data: WebSocketData): void {\n this[kSend](data)\n }\n\n private [kSend](data: WebSocketData): void {\n const { realWebSocket } = this\n\n invariant(\n realWebSocket,\n 'Failed to call \"server.send()\" for \"%s\": the connection is not open. Did you forget to call \"server.connect()\"?',\n this.client.url\n )\n\n // Silently ignore writes on the closed original WebSocket.\n if (\n realWebSocket.readyState === WebSocket.CLOSING ||\n realWebSocket.readyState === WebSocket.CLOSED\n ) {\n return\n }\n\n // Delegate the send to when the original connection is open.\n // Unlike the mock, connecting to the original server may take time\n // so we cannot call this on the next tick.\n if (realWebSocket.readyState === WebSocket.CONNECTING) {\n realWebSocket.addEventListener(\n 'open',\n () => {\n realWebSocket.send(data)\n },\n { once: true }\n )\n return\n }\n\n // Send the data to the original WebSocket server.\n realWebSocket.send(data)\n }\n\n /**\n * Close the actual server connection.\n */\n public close(): void {\n const { realWebSocket } = this\n\n invariant(\n realWebSocket,\n 'Failed to close server connection for \"%s\": the connection is not open. Did you forget to call \"server.connect()\"?',\n this.client.url\n )\n\n // Remove the \"close\" event listener from the server\n // so it doesn't close the underlying WebSocket client\n // when you call \"server.close()\". This also prevents the\n // `close` event on the `server` connection from being dispatched twice.\n this.realCloseController.abort()\n\n if (\n realWebSocket.readyState === WebSocket.CLOSING ||\n realWebSocket.readyState === WebSocket.CLOSED\n ) {\n return\n }\n\n // Close the actual client connection.\n realWebSocket.close()\n\n // Dispatch the \"close\" event on the `server` connection.\n queueMicrotask(() => {\n this[kEmitter].dispatchEvent(\n bindEvent(\n this.realWebSocket,\n new CancelableCloseEvent('close', {\n /**\n * @note `server.close()` in the interceptor\n * always results in clean closures.\n */\n code: 1000,\n cancelable: true,\n })\n )\n )\n })\n }\n\n private handleIncomingMessage(event: MessageEvent): void {\n // Clone the event to dispatch it on this class\n // once again and prevent the \"already being dispatched\"\n // exception. Clone it here so we can observe this event\n // being prevented in the \"server.on()\" listeners.\n const messageEvent = bindEvent(\n event.target,\n new CancelableMessageEvent('message', {\n data: event.data,\n origin: event.origin,\n cancelable: true,\n })\n )\n\n /**\n * @note Emit \"message\" event on the server connection\n * instance to let the interceptor know about these\n * incoming events from the original server. In that listener,\n * the interceptor can modify or skip the event forwarding\n * to the mock WebSocket instance.\n */\n this[kEmitter].dispatchEvent(messageEvent)\n\n /**\n * @note Forward the incoming server events to the client.\n * Preventing the default on the message event stops this.\n */\n if (!messageEvent.defaultPrevented) {\n this.client.dispatchEvent(\n bindEvent(\n /**\n * @note Bind the forwarded original server events\n * to the mock WebSocket instance so it would\n * dispatch them straight away.\n */\n this.client,\n // Clone the message event again to prevent\n // the \"already being dispatched\" exception.\n new MessageEvent('message', {\n data: event.data,\n origin: event.origin,\n })\n )\n )\n }\n }\n\n private handleMockClose(_event: Event): void {\n // Close the original connection if the mock client closes.\n if (this.realWebSocket) {\n this.realWebSocket.close()\n }\n }\n\n private handleRealClose(event: CloseEvent): void {\n // For closures originating from the original server,\n // remove the \"close\" listener from the mock client.\n // original close -> (?) client[kClose]() --X--> \"close\" (again).\n this.mockCloseController.abort()\n\n const closeEvent = bindEvent(\n this.realWebSocket,\n new CancelableCloseEvent('close', {\n code: event.code,\n reason: event.reason,\n wasClean: event.wasClean,\n cancelable: true,\n })\n )\n\n this[kEmitter].dispatchEvent(closeEvent)\n\n // If the close event from the server hasn't been prevented,\n // forward the closure to the mock client.\n if (!closeEvent.defaultPrevented) {\n // Close the intercepted client forcefully to\n // allow non-configurable status codes from the server.\n // If the socket has been closed by now, no harm calling\n // this again—it will have no effect.\n this.client[kClose](event.code, event.reason)\n }\n }\n}\n","import { bindEvent } from './utils/bindEvent'\nimport {\n StrictEventListenerOrEventListenerObject,\n WebSocketData,\n WebSocketTransport,\n WebSocketTransportEventMap,\n} from './WebSocketTransport'\nimport { kOnSend, kClose, WebSocketOverride } from './WebSocketOverride'\nimport { CancelableMessageEvent, CloseEvent } from './utils/events'\n\n/**\n * Abstraction over the given mock `WebSocket` instance that allows\n * for controlling that instance (e.g. sending and receiving messages).\n */\nexport class WebSocketClassTransport\n extends EventTarget\n implements WebSocketTransport\n{\n constructor(protected readonly socket: WebSocketOverride) {\n super()\n\n // Emit the \"close\" event on the transport if the close\n // originates from the WebSocket client. E.g. the application\n // calls \"ws.close()\", not the interceptor.\n this.socket.addEventListener('close', (event) => {\n this.dispatchEvent(bindEvent(this.socket, new CloseEvent('close', event)))\n })\n\n /**\n * Emit the \"outgoing\" event on the transport\n * whenever the WebSocket client sends data (\"ws.send()\").\n */\n this.socket[kOnSend] = (data) => {\n this.dispatchEvent(\n bindEvent(\n this.socket,\n // Dispatch this as cancelable because \"client\" connection\n // re-creates this message event (cannot dispatch the same event).\n new CancelableMessageEvent('outgoing', {\n data,\n origin: this.socket.url,\n cancelable: true,\n })\n )\n )\n }\n }\n\n public addEventListener(\n type: EventType,\n callback: StrictEventListenerOrEventListenerObject<\n WebSocketTransportEventMap[EventType]\n > | null,\n options?: boolean | AddEventListenerOptions\n ): void {\n return super.addEventListener(type, callback as EventListener, options)\n }\n\n public dispatchEvent(\n event: WebSocketTransportEventMap[EventType]\n ): boolean {\n return super.dispatchEvent(event)\n }\n\n public send(data: WebSocketData): void {\n queueMicrotask(() => {\n if (\n this.socket.readyState === this.socket.CLOSING ||\n this.socket.readyState === this.socket.CLOSED\n ) {\n return\n }\n\n const dispatchEvent = () => {\n this.socket.dispatchEvent(\n bindEvent(\n /**\n * @note Setting this event's \"target\" to the\n * WebSocket override instance is important.\n * This way it can tell apart original incoming events\n * (must be forwarded to the transport) from the\n * mocked message events like the one below\n * (must be dispatched on the client instance).\n */\n this.socket,\n new MessageEvent('message', {\n data,\n origin: this.socket.url,\n })\n )\n )\n }\n\n if (this.socket.readyState === this.socket.CONNECTING) {\n this.socket.addEventListener(\n 'open',\n () => {\n dispatchEvent()\n },\n { once: true }\n )\n } else {\n dispatchEvent()\n }\n })\n }\n\n public close(code: number, reason?: string): void {\n /**\n * @note Call the internal close method directly\n * to allow closing the connection with the status codes\n * that are non-configurable by the user (> 1000 <= 1015).\n */\n this.socket[kClose](code, reason)\n }\n}\n","import { Interceptor } from '../../Interceptor'\nimport {\n WebSocketClientConnectionProtocol,\n WebSocketClientConnection,\n type WebSocketClientEventMap,\n} from './WebSocketClientConnection'\nimport {\n WebSocketServerConnectionProtocol,\n WebSocketServerConnection,\n type WebSocketServerEventMap,\n} from './WebSocketServerConnection'\nimport { WebSocketClassTransport } from './WebSocketClassTransport'\nimport {\n kClose,\n kPassthroughPromise,\n WebSocketOverride,\n} from './WebSocketOverride'\nimport { bindEvent } from './utils/bindEvent'\nimport { hasConfigurableGlobal } from '../../utils/hasConfigurableGlobal'\nimport { emitAsync } from '../../utils/emitAsync'\nimport { patchesRegistry } from '../../utils/patchesRegistry'\n\nexport {\n type WebSocketData,\n type WebSocketTransport,\n} from './WebSocketTransport'\nexport {\n WebSocketClientEventMap,\n WebSocketClientConnectionProtocol,\n WebSocketClientConnection,\n WebSocketServerEventMap,\n WebSocketServerConnectionProtocol,\n WebSocketServerConnection,\n}\n\nexport {\n CloseEvent,\n CancelableCloseEvent,\n CancelableMessageEvent,\n} from './utils/events'\n\nexport type WebSocketEventMap = {\n connection: [args: WebSocketConnectionData]\n}\n\nexport type WebSocketConnectionData = {\n /**\n * The incoming WebSocket client connection.\n */\n client: WebSocketClientConnection\n\n /**\n * The original WebSocket server connection.\n */\n server: WebSocketServerConnection\n\n /**\n * The connection information.\n */\n info: {\n /**\n * The protocols supported by the WebSocket client.\n */\n protocols: string | Array | undefined\n }\n}\n\n/**\n * Intercept the outgoing WebSocket connections created using\n * the global `WebSocket` class.\n */\nexport class WebSocketInterceptor extends Interceptor {\n static symbol = Symbol.for('websocket-interceptor')\n\n constructor() {\n super(WebSocketInterceptor.symbol)\n }\n\n protected checkEnvironment(): boolean {\n return hasConfigurableGlobal('WebSocket')\n }\n\n protected setup(): void {\n const logger = this.logger.extend('setup')\n\n const WebSocketProxy = new Proxy(globalThis.WebSocket, {\n construct: (\n target,\n args: ConstructorParameters,\n newTarget\n ) => {\n const [url, protocols] = args\n\n const createConnection = (): WebSocket => {\n return Reflect.construct(target, args, newTarget)\n }\n\n // All WebSocket instances are mocked and don't forward\n // any events to the original server (no connection established).\n // To forward the events, the user must use the \"server.send()\" API.\n const socket = new WebSocketOverride(url, protocols)\n const transport = new WebSocketClassTransport(socket)\n\n // Emit the \"connection\" event to the interceptor on the next tick\n // so the client can modify WebSocket options, like \"binaryType\"\n // while the connection is already pending.\n queueMicrotask(async () => {\n try {\n const server = new WebSocketServerConnection(\n socket,\n transport,\n createConnection\n )\n\n const hasConnectionListeners =\n this.emitter.listenerCount('connection') > 0\n\n // The \"globalThis.WebSocket\" class stands for\n // the client-side connection. Assume it's established\n // as soon as the WebSocket instance is constructed.\n await emitAsync(this.emitter, 'connection', {\n client: new WebSocketClientConnection(socket, transport),\n server,\n info: {\n protocols,\n },\n })\n\n if (hasConnectionListeners) {\n socket[kPassthroughPromise].resolve(false)\n } else {\n socket[kPassthroughPromise].resolve(true)\n\n server.connect()\n\n // Forward the \"open\" event from the original server\n // to the mock WebSocket client in the case of a passthrough connection.\n server.addEventListener('open', () => {\n socket.dispatchEvent(bindEvent(socket, new Event('open')))\n\n // Forward the original connection protocol to the\n // mock WebSocket client.\n if (server['realWebSocket']) {\n socket.protocol = server['realWebSocket'].protocol\n }\n })\n }\n } catch (error) {\n /**\n * @note Translate unhandled exceptions during the connection\n * handling (i.e. interceptor exceptions) as WebSocket connection\n * closures with error. This prevents from the exceptions occurring\n * in `queueMicrotask` from being process-wide and uncatchable.\n */\n if (error instanceof Error) {\n socket.dispatchEvent(new Event('error'))\n\n // No need to close the connection if it's already being closed.\n // E.g. the interceptor called `client.close()` and then threw an error.\n if (\n socket.readyState !== WebSocket.CLOSING &&\n socket.readyState !== WebSocket.CLOSED\n ) {\n socket[kClose](1011, error.message, false)\n }\n\n console.error(error)\n }\n }\n })\n\n return socket\n },\n })\n\n logger.info('patching global WebSocket...')\n\n this.subscriptions.push(\n patchesRegistry.applyPatch(globalThis, 'WebSocket', () => WebSocketProxy)\n )\n\n logger.info('global WebSocket patched!', globalThis.WebSocket.name)\n }\n}\n"],"mappings":";;;;;;;AAEA,SAAgB,UACd,QACA,OACuB;AACvB,QAAO,iBAAiB,OAAO;EAC7B,QAAQ;GACN,OAAO;GACP,YAAY;GACZ,UAAU;GACX;EACD,eAAe;GACb,OAAO;GACP,YAAY;GACZ,UAAU;GACX;EACF,CAAC;AAEF,QAAO;;;;;ACnBT,MAAM,cAAc,OAAO,cAAc;AACzC,MAAM,oBAAoB,OAAO,oBAAoB;;;;;;;;AASrD,IAAa,yBAAb,cAAqD,aAAgB;CAInE,YAAY,MAAc,MAA2B;AACnD,QAAM,MAAM,KAAK;AACjB,OAAK,eAAe,CAAC,CAAC,KAAK;AAC3B,OAAK,qBAAqB;;CAG5B,IAAI,aAAa;AACf,SAAO,KAAK;;CAGd,IAAI,WAAW,gBAAgB;AAC7B,OAAK,eAAe;;CAGtB,IAAI,mBAAmB;AACrB,SAAO,KAAK;;CAGd,IAAI,iBAAiB,sBAAsB;AACzC,OAAK,qBAAqB;;CAG5B,AAAO,iBAAuB;AAC5B,MAAI,KAAK,cAAc,CAAC,KAAK,mBAC3B,MAAK,qBAAqB;;;AAWhC,IAAa,aAAb,cAAgC,MAAM;CAKpC,YAAY,MAAc,OAAuB,EAAE,EA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WAAW,YAAY,mBAAmB,eAAe,CAC1E;AAED,SAAO,KAAK,6BAA6B,WAAW,UAAU,KAAK"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/interceptors/XMLHttpRequest/index.cjs b/node_modules/@mswjs/interceptors/lib/browser/interceptors/XMLHttpRequest/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..6bc94bef480e3113446e08af05c8df24397268e9 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/interceptors/XMLHttpRequest/index.cjs @@ -0,0 +1,8 @@ +require('../../createRequestId-DOf8Ktjs.cjs'); +require('../../getRawRequest-DdfaiPVH.cjs'); +require('../../bufferUtils-Uc0eRItL.cjs'); +require('../../hasConfigurableGlobal-CS7adEvV.cjs'); +require('../../handleRequest-CJim54xG.cjs'); +const require_XMLHttpRequest = require('../../XMLHttpRequest-gXuzzX1g.cjs'); + +exports.XMLHttpRequestInterceptor = require_XMLHttpRequest.XMLHttpRequestInterceptor; \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/interceptors/XMLHttpRequest/index.d.cts b/node_modules/@mswjs/interceptors/lib/browser/interceptors/XMLHttpRequest/index.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..465c1859641fb2f17af6a63a3159314debaa57e5 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/interceptors/XMLHttpRequest/index.d.cts @@ -0,0 +1,15 @@ +import { t as HttpRequestEventMap } from "../../glossary-1lhZx6Aw.cjs"; +import { r as Interceptor } from "../../Interceptor-Deczogc8.cjs"; +import { Emitter } from "strict-event-emitter"; + +//#region src/interceptors/XMLHttpRequest/index.d.ts +type XMLHttpRequestEmitter = Emitter; +declare class XMLHttpRequestInterceptor extends Interceptor { + static symbol: symbol; + constructor(); + protected checkEnvironment(): boolean; + protected setup(): void; +} +//#endregion +export { XMLHttpRequestEmitter, XMLHttpRequestInterceptor }; +//# sourceMappingURL=index.d.cts.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/interceptors/XMLHttpRequest/index.d.mts b/node_modules/@mswjs/interceptors/lib/browser/interceptors/XMLHttpRequest/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..1c481003924834c82995833603a03357fe12be78 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/interceptors/XMLHttpRequest/index.d.mts @@ -0,0 +1,15 @@ +import { t as HttpRequestEventMap } from "../../glossary-nkHWcwvY.mjs"; +import { r as Interceptor } from "../../Interceptor-gqKgs-aF.mjs"; +import { Emitter } from "strict-event-emitter"; + +//#region src/interceptors/XMLHttpRequest/index.d.ts +type XMLHttpRequestEmitter = Emitter; +declare class XMLHttpRequestInterceptor extends Interceptor { + static symbol: symbol; + constructor(); + protected checkEnvironment(): boolean; + protected setup(): void; +} +//#endregion +export { XMLHttpRequestEmitter, XMLHttpRequestInterceptor }; +//# sourceMappingURL=index.d.mts.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/interceptors/XMLHttpRequest/index.mjs b/node_modules/@mswjs/interceptors/lib/browser/interceptors/XMLHttpRequest/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..85eeb6f5479853360d70cd3eb318c6b881ad4c19 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/interceptors/XMLHttpRequest/index.mjs @@ -0,0 +1,8 @@ +import "../../createRequestId-DYCsFHOi.mjs"; +import "../../getRawRequest-B1BqgWG6.mjs"; +import "../../bufferUtils-BiiO6HZv.mjs"; +import "../../hasConfigurableGlobal-C8zq1MCg.mjs"; +import "../../handleRequest-CPPgsG7s.mjs"; +import { t as XMLHttpRequestInterceptor } from "../../XMLHttpRequest-DrZAf3w6.mjs"; + +export { XMLHttpRequestInterceptor }; \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/interceptors/fetch/index.cjs b/node_modules/@mswjs/interceptors/lib/browser/interceptors/fetch/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..2c41433788a8893a175ada2f75bebb116e6a0e52 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/interceptors/fetch/index.cjs @@ -0,0 +1,7 @@ +require('../../createRequestId-DOf8Ktjs.cjs'); +require('../../getRawRequest-DdfaiPVH.cjs'); +require('../../hasConfigurableGlobal-CS7adEvV.cjs'); +require('../../handleRequest-CJim54xG.cjs'); +const require_fetch = require('../../fetch-Bt9rMY9c.cjs'); + +exports.FetchInterceptor = require_fetch.FetchInterceptor; \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/interceptors/fetch/index.d.cts b/node_modules/@mswjs/interceptors/lib/browser/interceptors/fetch/index.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..de3761f1e08903d0743039287a7316dba66fc998 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/interceptors/fetch/index.d.cts @@ -0,0 +1,13 @@ +import { t as HttpRequestEventMap } from "../../glossary-1lhZx6Aw.cjs"; +import { r as Interceptor } from "../../Interceptor-Deczogc8.cjs"; + +//#region src/interceptors/fetch/index.d.ts +declare class FetchInterceptor extends Interceptor { + static symbol: symbol; + constructor(); + protected checkEnvironment(): boolean; + protected setup(): Promise; +} +//#endregion +export { FetchInterceptor }; +//# sourceMappingURL=index.d.cts.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/interceptors/fetch/index.d.mts b/node_modules/@mswjs/interceptors/lib/browser/interceptors/fetch/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..06cd2294ba0418cf9908b2115965f5dac55dfdd7 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/interceptors/fetch/index.d.mts @@ -0,0 +1,13 @@ +import { t as HttpRequestEventMap } from "../../glossary-nkHWcwvY.mjs"; +import { r as Interceptor } from "../../Interceptor-gqKgs-aF.mjs"; + +//#region src/interceptors/fetch/index.d.ts +declare class FetchInterceptor extends Interceptor { + static symbol: symbol; + constructor(); + protected checkEnvironment(): boolean; + protected setup(): Promise; +} +//#endregion +export { FetchInterceptor }; +//# sourceMappingURL=index.d.mts.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/interceptors/fetch/index.mjs b/node_modules/@mswjs/interceptors/lib/browser/interceptors/fetch/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..7d6f4c770f7c14e06a1b9d563c283107dd93bb4b --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/interceptors/fetch/index.mjs @@ -0,0 +1,7 @@ +import "../../createRequestId-DYCsFHOi.mjs"; +import "../../getRawRequest-B1BqgWG6.mjs"; +import "../../hasConfigurableGlobal-C8zq1MCg.mjs"; +import "../../handleRequest-CPPgsG7s.mjs"; +import { t as FetchInterceptor } from "../../fetch-5IMPqr9e.mjs"; + +export { FetchInterceptor }; \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/presets/browser.cjs b/node_modules/@mswjs/interceptors/lib/browser/presets/browser.cjs new file mode 100644 index 0000000000000000000000000000000000000000..0e8b1dba7d1da39b136c955174a86adde050b680 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/presets/browser.cjs @@ -0,0 +1,18 @@ +require('../createRequestId-DOf8Ktjs.cjs'); +require('../getRawRequest-DdfaiPVH.cjs'); +require('../bufferUtils-Uc0eRItL.cjs'); +require('../hasConfigurableGlobal-CS7adEvV.cjs'); +require('../handleRequest-CJim54xG.cjs'); +const require_fetch = require('../fetch-Bt9rMY9c.cjs'); +const require_XMLHttpRequest = require('../XMLHttpRequest-gXuzzX1g.cjs'); + +//#region src/presets/browser.ts +/** +* The default preset provisions the interception of requests +* regardless of their type (fetch/XMLHttpRequest). +*/ +var browser_default = [new require_fetch.FetchInterceptor(), new require_XMLHttpRequest.XMLHttpRequestInterceptor()]; + +//#endregion +module.exports = browser_default; +//# sourceMappingURL=browser.cjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/presets/browser.cjs.map b/node_modules/@mswjs/interceptors/lib/browser/presets/browser.cjs.map new file mode 100644 index 0000000000000000000000000000000000000000..b65deba0f45843b80fae3188f7682e7160262247 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/presets/browser.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"browser.cjs","names":["FetchInterceptor","XMLHttpRequestInterceptor"],"sources":["../../../src/presets/browser.ts"],"sourcesContent":["import { FetchInterceptor } from '../interceptors/fetch'\nimport { XMLHttpRequestInterceptor } from '../interceptors/XMLHttpRequest'\n\n/**\n * The default preset provisions the interception of requests\n * regardless of their type (fetch/XMLHttpRequest).\n */\nexport default [\n new FetchInterceptor(),\n new XMLHttpRequestInterceptor(),\n] as const\n"],"mappings":";;;;;;;;;;;;;AAOA,sBAAe,CACb,IAAIA,gCAAkB,EACtB,IAAIC,kDAA2B,CAChC"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/presets/browser.d.cts b/node_modules/@mswjs/interceptors/lib/browser/presets/browser.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..bb0810d766cb2a5d6a95c249fbdd32c1ca694816 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/presets/browser.d.cts @@ -0,0 +1,12 @@ +import { XMLHttpRequestInterceptor } from "../interceptors/XMLHttpRequest/index.cjs"; +import { FetchInterceptor } from "../interceptors/fetch/index.cjs"; + +//#region src/presets/browser.d.ts + +/** + * The default preset provisions the interception of requests + * regardless of their type (fetch/XMLHttpRequest). + */ +declare const _default: readonly [FetchInterceptor, XMLHttpRequestInterceptor]; +export = _default; +//# sourceMappingURL=browser.d.cts.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/presets/browser.d.mts b/node_modules/@mswjs/interceptors/lib/browser/presets/browser.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..448842d50f39f123019f38705ffc61000e4ea703 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/presets/browser.d.mts @@ -0,0 +1,14 @@ +import "../Interceptor-gqKgs-aF.mjs"; +import { XMLHttpRequestInterceptor } from "../interceptors/XMLHttpRequest/index.mjs"; +import { FetchInterceptor } from "../interceptors/fetch/index.mjs"; + +//#region src/presets/browser.d.ts + +/** + * The default preset provisions the interception of requests + * regardless of their type (fetch/XMLHttpRequest). + */ +declare const _default: readonly [FetchInterceptor, XMLHttpRequestInterceptor]; +//#endregion +export { _default as default }; +//# sourceMappingURL=browser.d.mts.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/presets/browser.mjs b/node_modules/@mswjs/interceptors/lib/browser/presets/browser.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c27a7a9cd9b043fb3eb9ce5f02d0d2c3071d3996 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/presets/browser.mjs @@ -0,0 +1,18 @@ +import "../createRequestId-DYCsFHOi.mjs"; +import "../getRawRequest-B1BqgWG6.mjs"; +import "../bufferUtils-BiiO6HZv.mjs"; +import "../hasConfigurableGlobal-C8zq1MCg.mjs"; +import "../handleRequest-CPPgsG7s.mjs"; +import { t as FetchInterceptor } from "../fetch-5IMPqr9e.mjs"; +import { t as XMLHttpRequestInterceptor } from "../XMLHttpRequest-DrZAf3w6.mjs"; + +//#region src/presets/browser.ts +/** +* The default preset provisions the interception of requests +* regardless of their type (fetch/XMLHttpRequest). +*/ +var browser_default = [new FetchInterceptor(), new XMLHttpRequestInterceptor()]; + +//#endregion +export { browser_default as default }; +//# sourceMappingURL=browser.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/presets/browser.mjs.map b/node_modules/@mswjs/interceptors/lib/browser/presets/browser.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..68d00a2bf6586c8160cc7af66f0e2fd3a7747ac9 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/presets/browser.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"browser.mjs","names":[],"sources":["../../../src/presets/browser.ts"],"sourcesContent":["import { FetchInterceptor } from '../interceptors/fetch'\nimport { XMLHttpRequestInterceptor } from '../interceptors/XMLHttpRequest'\n\n/**\n * The default preset provisions the interception of requests\n * regardless of their type (fetch/XMLHttpRequest).\n */\nexport default [\n new FetchInterceptor(),\n new XMLHttpRequestInterceptor(),\n] as const\n"],"mappings":";;;;;;;;;;;;;AAOA,sBAAe,CACb,IAAI,kBAAkB,EACtB,IAAI,2BAA2B,CAChC"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/resolveWebSocketUrl-6K6EgqsA.cjs b/node_modules/@mswjs/interceptors/lib/browser/resolveWebSocketUrl-6K6EgqsA.cjs new file mode 100644 index 0000000000000000000000000000000000000000..502003e6d89183eaa1683333479787cedc885a12 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/resolveWebSocketUrl-6K6EgqsA.cjs @@ -0,0 +1,31 @@ + +//#region src/utils/resolveWebSocketUrl.ts +/** +* Resolve potentially relative WebSocket URLs the same way +* the browser does (replace the protocol, use the origin, etc). +* +* @see https://websockets.spec.whatwg.org//#dom-websocket-websocket +*/ +function resolveWebSocketUrl(url) { + if (typeof url === "string") return resolveWebSocketUrl(new URL(url, typeof location !== "undefined" ? location.href : void 0)); + if (url.protocol === "http:") url.protocol = "ws:"; + else if (url.protocol === "https:") url.protocol = "wss:"; + if (url.protocol !== "ws:" && url.protocol !== "wss:") + /** + * @note These errors are modeled after the browser errors. + * The exact error messages aren't provided in the specification. + * Node.js uses more obscure error messages that I don't wish to replicate. + */ + throw new SyntaxError(`Failed to construct 'WebSocket': The URL's scheme must be either 'http', 'https', 'ws', or 'wss'. '${url.protocol}' is not allowed.`); + if (url.hash !== "") throw new SyntaxError(`Failed to construct 'WebSocket': The URL contains a fragment identifier ('${url.hash}'). Fragment identifiers are not allowed in WebSocket URLs.`); + return url.href; +} + +//#endregion +Object.defineProperty(exports, 'resolveWebSocketUrl', { + enumerable: true, + get: function () { + return resolveWebSocketUrl; + } +}); +//# sourceMappingURL=resolveWebSocketUrl-6K6EgqsA.cjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/resolveWebSocketUrl-6K6EgqsA.cjs.map b/node_modules/@mswjs/interceptors/lib/browser/resolveWebSocketUrl-6K6EgqsA.cjs.map new file mode 100644 index 0000000000000000000000000000000000000000..e1942ab2ad38bc9a7d5ea74fb4bcc2ff05af31df --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/resolveWebSocketUrl-6K6EgqsA.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"resolveWebSocketUrl-6K6EgqsA.cjs","names":[],"sources":["../../src/utils/resolveWebSocketUrl.ts"],"sourcesContent":["/**\n * Resolve potentially relative WebSocket URLs the same way\n * the browser does (replace the protocol, use the origin, etc).\n *\n * @see https://websockets.spec.whatwg.org//#dom-websocket-websocket\n */\nexport function resolveWebSocketUrl(url: string | URL): string {\n if (typeof url === 'string') {\n /**\n * @note Cast the string to a URL first so the parsing errors\n * are thrown as a part of the WebSocket constructor, not consumers.\n */\n const urlRecord = new URL(\n url,\n typeof location !== 'undefined' ? location.href : undefined\n )\n\n return resolveWebSocketUrl(urlRecord)\n }\n\n if (url.protocol === 'http:') {\n url.protocol = 'ws:'\n } else if (url.protocol === 'https:') {\n url.protocol = 'wss:'\n }\n\n if (url.protocol !== 'ws:' && url.protocol !== 'wss:') {\n /**\n * @note These errors are modeled after the browser errors.\n * The exact error messages aren't provided in the specification.\n * Node.js uses more obscure error messages that I don't wish to replicate.\n */\n throw new SyntaxError(\n `Failed to construct 'WebSocket': The URL's scheme must be either 'http', 'https', 'ws', or 'wss'. '${url.protocol}' is not allowed.`\n )\n }\n\n if (url.hash !== '') {\n throw new SyntaxError(\n `Failed to construct 'WebSocket': The URL contains a fragment identifier ('${url.hash}'). Fragment identifiers are not allowed in WebSocket URLs.`\n )\n }\n\n return url.href\n}\n"],"mappings":";;;;;;;;AAMA,SAAgB,oBAAoB,KAA2B;AAC7D,KAAI,OAAO,QAAQ,SAUjB,QAAO,oBALW,IAAI,IACpB,KACA,OAAO,aAAa,cAAc,SAAS,OAAO,OACnD,CAEoC;AAGvC,KAAI,IAAI,aAAa,QACnB,KAAI,WAAW;UACN,IAAI,aAAa,SAC1B,KAAI,WAAW;AAGjB,KAAI,IAAI,aAAa,SAAS,IAAI,aAAa;;;;;;AAM7C,OAAM,IAAI,YACR,sGAAsG,IAAI,SAAS,mBACpH;AAGH,KAAI,IAAI,SAAS,GACf,OAAM,IAAI,YACR,6EAA6E,IAAI,KAAK,6DACvF;AAGH,QAAO,IAAI"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/resolveWebSocketUrl-C83-x9iE.mjs b/node_modules/@mswjs/interceptors/lib/browser/resolveWebSocketUrl-C83-x9iE.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a2307c10cadb7624e87a7285154ea7575a73ab5e --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/resolveWebSocketUrl-C83-x9iE.mjs @@ -0,0 +1,25 @@ +//#region src/utils/resolveWebSocketUrl.ts +/** +* Resolve potentially relative WebSocket URLs the same way +* the browser does (replace the protocol, use the origin, etc). +* +* @see https://websockets.spec.whatwg.org//#dom-websocket-websocket +*/ +function resolveWebSocketUrl(url) { + if (typeof url === "string") return resolveWebSocketUrl(new URL(url, typeof location !== "undefined" ? location.href : void 0)); + if (url.protocol === "http:") url.protocol = "ws:"; + else if (url.protocol === "https:") url.protocol = "wss:"; + if (url.protocol !== "ws:" && url.protocol !== "wss:") + /** + * @note These errors are modeled after the browser errors. + * The exact error messages aren't provided in the specification. + * Node.js uses more obscure error messages that I don't wish to replicate. + */ + throw new SyntaxError(`Failed to construct 'WebSocket': The URL's scheme must be either 'http', 'https', 'ws', or 'wss'. '${url.protocol}' is not allowed.`); + if (url.hash !== "") throw new SyntaxError(`Failed to construct 'WebSocket': The URL contains a fragment identifier ('${url.hash}'). Fragment identifiers are not allowed in WebSocket URLs.`); + return url.href; +} + +//#endregion +export { resolveWebSocketUrl as t }; +//# sourceMappingURL=resolveWebSocketUrl-C83-x9iE.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/browser/resolveWebSocketUrl-C83-x9iE.mjs.map b/node_modules/@mswjs/interceptors/lib/browser/resolveWebSocketUrl-C83-x9iE.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..5da18ba662c5d684145ace36caffb30c046b1cca --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/browser/resolveWebSocketUrl-C83-x9iE.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"resolveWebSocketUrl-C83-x9iE.mjs","names":[],"sources":["../../src/utils/resolveWebSocketUrl.ts"],"sourcesContent":["/**\n * Resolve potentially relative WebSocket URLs the same way\n * the browser does (replace the protocol, use the origin, etc).\n *\n * @see https://websockets.spec.whatwg.org//#dom-websocket-websocket\n */\nexport function resolveWebSocketUrl(url: string | URL): string {\n if (typeof url === 'string') {\n /**\n * @note Cast the string to a URL first so the parsing errors\n * are thrown as a part of the WebSocket constructor, not consumers.\n */\n const urlRecord = new URL(\n url,\n typeof location !== 'undefined' ? location.href : undefined\n )\n\n return resolveWebSocketUrl(urlRecord)\n }\n\n if (url.protocol === 'http:') {\n url.protocol = 'ws:'\n } else if (url.protocol === 'https:') {\n url.protocol = 'wss:'\n }\n\n if (url.protocol !== 'ws:' && url.protocol !== 'wss:') {\n /**\n * @note These errors are modeled after the browser errors.\n * The exact error messages aren't provided in the specification.\n * Node.js uses more obscure error messages that I don't wish to replicate.\n */\n throw new SyntaxError(\n `Failed to construct 'WebSocket': The URL's scheme must be either 'http', 'https', 'ws', or 'wss'. '${url.protocol}' is not allowed.`\n )\n }\n\n if (url.hash !== '') {\n throw new SyntaxError(\n `Failed to construct 'WebSocket': The URL contains a fragment identifier ('${url.hash}'). Fragment identifiers are not allowed in WebSocket URLs.`\n )\n }\n\n return url.href\n}\n"],"mappings":";;;;;;;AAMA,SAAgB,oBAAoB,KAA2B;AAC7D,KAAI,OAAO,QAAQ,SAUjB,QAAO,oBALW,IAAI,IACpB,KACA,OAAO,aAAa,cAAc,SAAS,OAAO,OACnD,CAEoC;AAGvC,KAAI,IAAI,aAAa,QACnB,KAAI,WAAW;UACN,IAAI,aAAa,SAC1B,KAAI,WAAW;AAGjB,KAAI,IAAI,aAAa,SAAS,IAAI,aAAa;;;;;;AAM7C,OAAM,IAAI,YACR,sGAAsG,IAAI,SAAS,mBACpH;AAGH,KAAI,IAAI,SAAS,GACf,OAAM,IAAI,YACR,6EAA6E,IAAI,KAAK,6DACvF;AAGH,QAAO,IAAI"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/BatchInterceptor-BGhH8z1z.cjs b/node_modules/@mswjs/interceptors/lib/node/BatchInterceptor-BGhH8z1z.cjs new file mode 100644 index 0000000000000000000000000000000000000000..d112a0438bcb22e2d3a7893a5607cb2c6d2328fb --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/BatchInterceptor-BGhH8z1z.cjs @@ -0,0 +1,49 @@ +const require_fetchUtils = require('./fetchUtils-umV5xXBy.cjs'); + +//#region src/BatchInterceptor.ts +/** +* A batch interceptor that exposes a single interface +* to apply and operate with multiple interceptors at once. +*/ +var BatchInterceptor = class BatchInterceptor extends require_fetchUtils.Interceptor { + constructor(options) { + BatchInterceptor.symbol = Symbol.for(options.name); + super(BatchInterceptor.symbol); + this.interceptors = options.interceptors; + } + setup() { + const logger = this.logger.extend("setup"); + logger.info("applying all %d interceptors...", this.interceptors.length); + for (const interceptor of this.interceptors) { + logger.info("applying \"%s\" interceptor...", interceptor.constructor.name); + interceptor.apply(); + logger.info("adding interceptor dispose subscription"); + this.subscriptions.push(() => interceptor.dispose()); + } + } + on(event, listener) { + for (const interceptor of this.interceptors) interceptor.on(event, listener); + return this; + } + once(event, listener) { + for (const interceptor of this.interceptors) interceptor.once(event, listener); + return this; + } + off(event, listener) { + for (const interceptor of this.interceptors) interceptor.off(event, listener); + return this; + } + removeAllListeners(event) { + for (const interceptors of this.interceptors) interceptors.removeAllListeners(event); + return this; + } +}; + +//#endregion +Object.defineProperty(exports, 'BatchInterceptor', { + enumerable: true, + get: function () { + return BatchInterceptor; + } +}); +//# sourceMappingURL=BatchInterceptor-BGhH8z1z.cjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/BatchInterceptor-BGhH8z1z.cjs.map b/node_modules/@mswjs/interceptors/lib/node/BatchInterceptor-BGhH8z1z.cjs.map new file mode 100644 index 0000000000000000000000000000000000000000..f4362ceab446d015a3f9b0f6f1ecd67a658b559e --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/BatchInterceptor-BGhH8z1z.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"BatchInterceptor-BGhH8z1z.cjs","names":["Interceptor"],"sources":["../../src/BatchInterceptor.ts"],"sourcesContent":["import { EventMap, Listener } from 'strict-event-emitter'\nimport { Interceptor, ExtractEventNames } from './Interceptor'\n\nexport interface BatchInterceptorOptions<\n InterceptorList extends ReadonlyArray>,\n> {\n name: string\n interceptors: InterceptorList\n}\n\nexport type ExtractEventMapType<\n InterceptorList extends ReadonlyArray>,\n> =\n InterceptorList extends ReadonlyArray\n ? InterceptorType extends Interceptor\n ? EventMap\n : never\n : never\n\n/**\n * A batch interceptor that exposes a single interface\n * to apply and operate with multiple interceptors at once.\n */\nexport class BatchInterceptor<\n InterceptorList extends ReadonlyArray>,\n Events extends EventMap = ExtractEventMapType,\n> extends Interceptor {\n static symbol: symbol\n\n private interceptors: InterceptorList\n\n constructor(options: BatchInterceptorOptions) {\n BatchInterceptor.symbol = Symbol.for(options.name)\n super(BatchInterceptor.symbol)\n this.interceptors = options.interceptors\n }\n\n protected setup() {\n const logger = this.logger.extend('setup')\n\n logger.info('applying all %d interceptors...', this.interceptors.length)\n\n for (const interceptor of this.interceptors) {\n logger.info('applying \"%s\" interceptor...', interceptor.constructor.name)\n interceptor.apply()\n\n logger.info('adding interceptor dispose subscription')\n this.subscriptions.push(() => interceptor.dispose())\n }\n }\n\n public on>(\n event: EventName,\n listener: Listener\n ): this {\n // Instead of adding a listener to the batch interceptor,\n // propagate the listener to each of the individual interceptors.\n for (const interceptor of this.interceptors) {\n interceptor.on(event, listener)\n }\n\n return this\n }\n\n public once>(\n event: EventName,\n listener: Listener\n ): this {\n for (const interceptor of this.interceptors) {\n interceptor.once(event, listener)\n }\n\n return this\n }\n\n public off>(\n event: EventName,\n listener: Listener\n ): this {\n for (const interceptor of this.interceptors) {\n interceptor.off(event, listener)\n }\n\n return this\n }\n\n public removeAllListeners>(\n event?: EventName | undefined\n ): this {\n for (const interceptors of this.interceptors) {\n interceptors.removeAllListeners(event)\n }\n\n return this\n }\n}\n"],"mappings":";;;;;;;AAuBA,IAAa,mBAAb,MAAa,yBAGHA,+BAAoB;CAK5B,YAAY,SAAmD;AAC7D,mBAAiB,SAAS,OAAO,IAAI,QAAQ,KAAK;AAClD,QAAM,iBAAiB,OAAO;AAC9B,OAAK,eAAe,QAAQ;;CAG9B,AAAU,QAAQ;EAChB,MAAM,SAAS,KAAK,OAAO,OAAO,QAAQ;AAE1C,SAAO,KAAK,mCAAmC,KAAK,aAAa,OAAO;AAExE,OAAK,MAAM,eAAe,KAAK,cAAc;AAC3C,UAAO,KAAK,kCAAgC,YAAY,YAAY,KAAK;AACzE,eAAY,OAAO;AAEnB,UAAO,KAAK,0CAA0C;AACtD,QAAK,cAAc,WAAW,YAAY,SAAS,CAAC;;;CAIxD,AAAO,GACL,OACA,UACM;AAGN,OAAK,MAAM,eAAe,KAAK,aAC7B,aAAY,GAAG,OAAO,SAAS;AAGjC,SAAO;;CAGT,AAAO,KACL,OACA,UACM;AACN,OAAK,MAAM,eAAe,KAAK,aAC7B,aAAY,KAAK,OAAO,SAAS;AAGnC,SAAO;;CAGT,AAAO,IACL,OACA,UACM;AACN,OAAK,MAAM,eAAe,KAAK,aAC7B,aAAY,IAAI,OAAO,SAAS;AAGlC,SAAO;;CAGT,AAAO,mBACL,OACM;AACN,OAAK,MAAM,gBAAgB,KAAK,aAC9B,cAAa,mBAAmB,MAAM;AAGxC,SAAO"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/BatchInterceptor-C4-RX5rg.mjs b/node_modules/@mswjs/interceptors/lib/node/BatchInterceptor-C4-RX5rg.mjs new file mode 100644 index 0000000000000000000000000000000000000000..bf5b1bbbbbf8fc8def64eca246b7b5143e900939 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/BatchInterceptor-C4-RX5rg.mjs @@ -0,0 +1,44 @@ +import { c as Interceptor } from "./fetchUtils-BKJ1XmiO.mjs"; + +//#region src/BatchInterceptor.ts +/** +* A batch interceptor that exposes a single interface +* to apply and operate with multiple interceptors at once. +*/ +var BatchInterceptor = class BatchInterceptor extends Interceptor { + constructor(options) { + BatchInterceptor.symbol = Symbol.for(options.name); + super(BatchInterceptor.symbol); + this.interceptors = options.interceptors; + } + setup() { + const logger = this.logger.extend("setup"); + logger.info("applying all %d interceptors...", this.interceptors.length); + for (const interceptor of this.interceptors) { + logger.info("applying \"%s\" interceptor...", interceptor.constructor.name); + interceptor.apply(); + logger.info("adding interceptor dispose subscription"); + this.subscriptions.push(() => interceptor.dispose()); + } + } + on(event, listener) { + for (const interceptor of this.interceptors) interceptor.on(event, listener); + return this; + } + once(event, listener) { + for (const interceptor of this.interceptors) interceptor.once(event, listener); + return this; + } + off(event, listener) { + for (const interceptor of this.interceptors) interceptor.off(event, listener); + return this; + } + removeAllListeners(event) { + for (const interceptors of this.interceptors) interceptors.removeAllListeners(event); + return this; + } +}; + +//#endregion +export { BatchInterceptor as t }; +//# sourceMappingURL=BatchInterceptor-C4-RX5rg.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/BatchInterceptor-C4-RX5rg.mjs.map b/node_modules/@mswjs/interceptors/lib/node/BatchInterceptor-C4-RX5rg.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..25f6e91e2c2b13a4f9efd4cca6b9f99bf1559d6c --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/BatchInterceptor-C4-RX5rg.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"BatchInterceptor-C4-RX5rg.mjs","names":[],"sources":["../../src/BatchInterceptor.ts"],"sourcesContent":["import { EventMap, Listener } from 'strict-event-emitter'\nimport { Interceptor, ExtractEventNames } from './Interceptor'\n\nexport interface BatchInterceptorOptions<\n InterceptorList extends ReadonlyArray>,\n> {\n name: string\n interceptors: InterceptorList\n}\n\nexport type ExtractEventMapType<\n InterceptorList extends ReadonlyArray>,\n> =\n InterceptorList extends ReadonlyArray\n ? InterceptorType extends Interceptor\n ? EventMap\n : never\n : never\n\n/**\n * A batch interceptor that exposes a single interface\n * to apply and operate with multiple interceptors at once.\n */\nexport class BatchInterceptor<\n InterceptorList extends ReadonlyArray>,\n Events extends EventMap = ExtractEventMapType,\n> extends Interceptor {\n static symbol: symbol\n\n private interceptors: InterceptorList\n\n constructor(options: BatchInterceptorOptions) {\n BatchInterceptor.symbol = Symbol.for(options.name)\n super(BatchInterceptor.symbol)\n this.interceptors = options.interceptors\n }\n\n protected setup() {\n const logger = this.logger.extend('setup')\n\n logger.info('applying all %d interceptors...', this.interceptors.length)\n\n for (const interceptor of this.interceptors) {\n logger.info('applying \"%s\" interceptor...', interceptor.constructor.name)\n interceptor.apply()\n\n logger.info('adding interceptor dispose subscription')\n this.subscriptions.push(() => interceptor.dispose())\n }\n }\n\n public on>(\n event: EventName,\n listener: Listener\n ): this {\n // Instead of adding a listener to the batch interceptor,\n // propagate the listener to each of the individual interceptors.\n for (const interceptor of this.interceptors) {\n interceptor.on(event, listener)\n }\n\n return this\n }\n\n public once>(\n event: EventName,\n listener: Listener\n ): this {\n for (const interceptor of this.interceptors) {\n interceptor.once(event, listener)\n }\n\n return this\n }\n\n public off>(\n event: EventName,\n listener: Listener\n ): this {\n for (const interceptor of this.interceptors) {\n interceptor.off(event, listener)\n }\n\n return this\n }\n\n public removeAllListeners>(\n event?: EventName | undefined\n ): this {\n for (const interceptors of this.interceptors) {\n interceptors.removeAllListeners(event)\n }\n\n return this\n }\n}\n"],"mappings":";;;;;;;AAuBA,IAAa,mBAAb,MAAa,yBAGH,YAAoB;CAK5B,YAAY,SAAmD;AAC7D,mBAAiB,SAAS,OAAO,IAAI,QAAQ,KAAK;AAClD,QAAM,iBAAiB,OAAO;AAC9B,OAAK,eAAe,QAAQ;;CAG9B,AAAU,QAAQ;EAChB,MAAM,SAAS,KAAK,OAAO,OAAO,QAAQ;AAE1C,SAAO,KAAK,mCAAmC,KAAK,aAAa,OAAO;AAExE,OAAK,MAAM,eAAe,KAAK,cAAc;AAC3C,UAAO,KAAK,kCAAgC,YAAY,YAAY,KAAK;AACzE,eAAY,OAAO;AAEnB,UAAO,KAAK,0CAA0C;AACtD,QAAK,cAAc,WAAW,YAAY,SAAS,CAAC;;;CAIxD,AAAO,GACL,OACA,UACM;AAGN,OAAK,MAAM,eAAe,KAAK,aAC7B,aAAY,GAAG,OAAO,SAAS;AAGjC,SAAO;;CAGT,AAAO,KACL,OACA,UACM;AACN,OAAK,MAAM,eAAe,KAAK,aAC7B,aAAY,KAAK,OAAO,SAAS;AAGnC,SAAO;;CAGT,AAAO,IACL,OACA,UACM;AACN,OAAK,MAAM,eAAe,KAAK,aAC7B,aAAY,IAAI,OAAO,SAAS;AAGlC,SAAO;;CAGT,AAAO,mBACL,OACM;AACN,OAAK,MAAM,gBAAgB,KAAK,aAC9B,cAAa,mBAAmB,MAAM;AAGxC,SAAO"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/BatchInterceptor-KKF8Q47I.d.cts b/node_modules/@mswjs/interceptors/lib/node/BatchInterceptor-KKF8Q47I.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..a5300e047229c60c5b9938136bbb4cff4b3f5ef5 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/BatchInterceptor-KKF8Q47I.d.cts @@ -0,0 +1,26 @@ +import { r as Interceptor, t as ExtractEventNames } from "./Interceptor-BsZ21ue0.cjs"; +import { EventMap, Listener } from "strict-event-emitter"; + +//#region src/BatchInterceptor.d.ts +interface BatchInterceptorOptions>> { + name: string; + interceptors: InterceptorList; +} +type ExtractEventMapType>> = InterceptorList extends ReadonlyArray ? InterceptorType extends Interceptor ? EventMap : never : never; +/** + * A batch interceptor that exposes a single interface + * to apply and operate with multiple interceptors at once. + */ +declare class BatchInterceptor>, Events extends EventMap = ExtractEventMapType> extends Interceptor { + static symbol: symbol; + private interceptors; + constructor(options: BatchInterceptorOptions); + protected setup(): void; + on>(event: EventName, listener: Listener): this; + once>(event: EventName, listener: Listener): this; + off>(event: EventName, listener: Listener): this; + removeAllListeners>(event?: EventName | undefined): this; +} +//#endregion +export { BatchInterceptorOptions as n, ExtractEventMapType as r, BatchInterceptor as t }; +//# sourceMappingURL=BatchInterceptor-KKF8Q47I.d.cts.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/BatchInterceptor-rSr-NH_H.d.mts b/node_modules/@mswjs/interceptors/lib/node/BatchInterceptor-rSr-NH_H.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..80148a0829e8383e80c787afbdc1707f64236104 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/BatchInterceptor-rSr-NH_H.d.mts @@ -0,0 +1,26 @@ +import { r as Interceptor, t as ExtractEventNames } from "./Interceptor-soD-WpQO.mjs"; +import { EventMap, Listener } from "strict-event-emitter"; + +//#region src/BatchInterceptor.d.ts +interface BatchInterceptorOptions>> { + name: string; + interceptors: InterceptorList; +} +type ExtractEventMapType>> = InterceptorList extends ReadonlyArray ? InterceptorType extends Interceptor ? EventMap : never : never; +/** + * A batch interceptor that exposes a single interface + * to apply and operate with multiple interceptors at once. + */ +declare class BatchInterceptor>, Events extends EventMap = ExtractEventMapType> extends Interceptor { + static symbol: symbol; + private interceptors; + constructor(options: BatchInterceptorOptions); + protected setup(): void; + on>(event: EventName, listener: Listener): this; + once>(event: EventName, listener: Listener): this; + off>(event: EventName, listener: Listener): this; + removeAllListeners>(event?: EventName | undefined): this; +} +//#endregion +export { BatchInterceptorOptions as n, ExtractEventMapType as r, BatchInterceptor as t }; +//# sourceMappingURL=BatchInterceptor-rSr-NH_H.d.mts.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/ClientRequest-2loAH7xM.cjs b/node_modules/@mswjs/interceptors/lib/node/ClientRequest-2loAH7xM.cjs new file mode 100644 index 0000000000000000000000000000000000000000..6231f4d1b29b6d70dbf40c465ac18524f3e866c8 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/ClientRequest-2loAH7xM.cjs @@ -0,0 +1,1058 @@ +const require_chunk = require('./chunk-CbDLau6x.cjs'); +const require_fetchUtils = require('./fetchUtils-umV5xXBy.cjs'); +const require_getRawRequest = require('./getRawRequest-B6znU6il.cjs'); +const require_handleRequest = require('./handleRequest-C-cKYjIh.cjs'); +const require_node = require('./node-DIKcnzhK.cjs'); +let _open_draft_logger = require("@open-draft/logger"); +let outvariant = require("outvariant"); +let node_http = require("node:http"); +node_http = require_chunk.__toESM(node_http); +let node_https = require("node:https"); +node_https = require_chunk.__toESM(node_https); +let node_net = require("node:net"); +node_net = require_chunk.__toESM(node_net); +let _http_common = require("_http_common"); +let node_stream = require("node:stream"); +let node_url = require("node:url"); +let http = require("http"); + +//#region src/interceptors/Socket/utils/normalizeSocketWriteArgs.ts +/** +* Normalizes the arguments provided to the `Writable.prototype.write()` +* and `Writable.prototype.end()`. +*/ +function normalizeSocketWriteArgs(args) { + const normalized = [ + args[0], + void 0, + void 0 + ]; + if (typeof args[1] === "string") normalized[1] = args[1]; + else if (typeof args[1] === "function") normalized[2] = args[1]; + if (typeof args[2] === "function") normalized[2] = args[2]; + return normalized; +} + +//#endregion +//#region src/interceptors/Socket/MockSocket.ts +var MockSocket = class extends node_net.default.Socket { + constructor(options) { + super(); + this.options = options; + this.connecting = false; + this.connect(); + this._final = (callback) => { + callback(null); + }; + } + connect() { + this.connecting = true; + return this; + } + write(...args) { + const [chunk, encoding, callback] = normalizeSocketWriteArgs(args); + this.options.write(chunk, encoding, callback); + return true; + } + end(...args) { + const [chunk, encoding, callback] = normalizeSocketWriteArgs(args); + this.options.write(chunk, encoding, callback); + return super.end.apply(this, args); + } + push(chunk, encoding) { + this.options.read(chunk, encoding); + return super.push(chunk, encoding); + } +}; + +//#endregion +//#region src/interceptors/Socket/utils/baseUrlFromConnectionOptions.ts +function baseUrlFromConnectionOptions(options) { + if ("href" in options) return new URL(options.href); + const protocol = options.port === 443 ? "https:" : "http:"; + const host = options.host; + const url = new URL(`${protocol}//${host}`); + if (options.port) url.port = options.port.toString(); + if (options.path) url.pathname = options.path; + if (options.auth) { + const [username, password] = options.auth.split(":"); + url.username = username; + url.password = password; + } + return url; +} + +//#endregion +//#region src/interceptors/ClientRequest/utils/recordRawHeaders.ts +const kRawHeaders = Symbol("kRawHeaders"); +const kRestorePatches = Symbol("kRestorePatches"); +function recordRawHeader(headers, args, behavior) { + ensureRawHeadersSymbol(headers, []); + const rawHeaders = Reflect.get(headers, kRawHeaders); + if (behavior === "set") { + for (let index = rawHeaders.length - 1; index >= 0; index--) if (rawHeaders[index][0].toLowerCase() === args[0].toLowerCase()) rawHeaders.splice(index, 1); + } + rawHeaders.push(args); +} +/** +* Define the raw headers symbol on the given `Headers` instance. +* If the symbol already exists, this function does nothing. +*/ +function ensureRawHeadersSymbol(headers, rawHeaders) { + if (Reflect.has(headers, kRawHeaders)) return; + defineRawHeadersSymbol(headers, rawHeaders); +} +/** +* Define the raw headers symbol on the given `Headers` instance. +* If the symbol already exists, it gets overridden. +*/ +function defineRawHeadersSymbol(headers, rawHeaders) { + Object.defineProperty(headers, kRawHeaders, { + value: rawHeaders, + enumerable: false, + configurable: true + }); +} +/** +* Patch the global `Headers` class to store raw headers. +* This is for compatibility with `IncomingMessage.prototype.rawHeaders`. +* +* @note Node.js has their own raw headers symbol but it +* only records the first header name in case of multi-value headers. +* Any other headers are normalized before comparing. This makes it +* incompatible with the `rawHeaders` format. +* +* let h = new Headers() +* h.append('X-Custom', 'one') +* h.append('x-custom', 'two') +* h[Symbol('headers map')] // Map { 'X-Custom' => 'one, two' } +*/ +function recordRawFetchHeaders() { + if (Reflect.get(Headers, kRestorePatches)) return Reflect.get(Headers, kRestorePatches); + const { Headers: OriginalHeaders, Request: OriginalRequest, Response: OriginalResponse } = globalThis; + const { set, append, delete: headersDeleteMethod } = Headers.prototype; + Object.defineProperty(Headers, kRestorePatches, { + value: () => { + Headers.prototype.set = set; + Headers.prototype.append = append; + Headers.prototype.delete = headersDeleteMethod; + globalThis.Headers = OriginalHeaders; + globalThis.Request = OriginalRequest; + globalThis.Response = OriginalResponse; + Object.setPrototypeOf(require_fetchUtils.FetchRequest, OriginalRequest); + Object.setPrototypeOf(require_fetchUtils.FetchRequest.prototype, OriginalRequest.prototype); + Object.setPrototypeOf(require_fetchUtils.FetchResponse, OriginalResponse); + Object.setPrototypeOf(require_fetchUtils.FetchResponse.prototype, OriginalResponse.prototype); + Reflect.deleteProperty(Headers, kRestorePatches); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(globalThis, "Headers", { + enumerable: true, + writable: true, + value: new Proxy(Headers, { construct(target, args, newTarget) { + const headersInit = args[0] || []; + if (headersInit instanceof Headers && Reflect.has(headersInit, kRawHeaders)) { + const sanitizedHeaders = Reflect.get(headersInit, kRawHeaders).map((tuple) => [tuple[0], tuple[1]]); + const headers$1 = Reflect.construct(target, [sanitizedHeaders], newTarget); + ensureRawHeadersSymbol(headers$1, [...sanitizedHeaders]); + return headers$1; + } + const headers = Reflect.construct(target, args, newTarget); + if (!Reflect.has(headers, kRawHeaders)) ensureRawHeadersSymbol(headers, Array.isArray(headersInit) ? headersInit : Object.entries(headersInit)); + return headers; + } }) + }); + Headers.prototype.set = new Proxy(Headers.prototype.set, { apply(target, thisArg, args) { + recordRawHeader(thisArg, [args[0], args[1]], "set"); + return Reflect.apply(target, thisArg, args); + } }); + Headers.prototype.append = new Proxy(Headers.prototype.append, { apply(target, thisArg, args) { + recordRawHeader(thisArg, [args[0], args[1]], "append"); + return Reflect.apply(target, thisArg, args); + } }); + Headers.prototype.delete = new Proxy(Headers.prototype.delete, { apply(target, thisArg, args) { + const rawHeaders = Reflect.get(thisArg, kRawHeaders); + if (rawHeaders) { + for (let index = rawHeaders.length - 1; index >= 0; index--) if (rawHeaders[index][0].toLowerCase() === args[0].toLowerCase()) rawHeaders.splice(index, 1); + } + return Reflect.apply(target, thisArg, args); + } }); + Object.defineProperty(globalThis, "Request", { + enumerable: true, + writable: true, + value: new Proxy(Request, { construct(target, args, newTarget) { + const request = Reflect.construct(target, args, newTarget); + const inferredRawHeaders = []; + if (typeof args[0] === "object" && args[0].headers != null) inferredRawHeaders.push(...inferRawHeaders(args[0].headers)); + if (typeof args[1] === "object" && args[1].headers != null) inferredRawHeaders.push(...inferRawHeaders(args[1].headers)); + if (inferredRawHeaders.length > 0) ensureRawHeadersSymbol(request.headers, inferredRawHeaders); + return request; + } }) + }); + Object.defineProperty(globalThis, "Response", { + enumerable: true, + writable: true, + value: new Proxy(Response, { construct(target, args, newTarget) { + const response = Reflect.construct(target, args, newTarget); + if (typeof args[1] === "object" && args[1].headers != null) ensureRawHeadersSymbol(response.headers, inferRawHeaders(args[1].headers)); + return response; + } }) + }); + /** + * Re-parent FetchRequest/FetchResponse so their `super()` calls go + * through the proxied globalThis.Request/Response above. Without this, + * FetchRequest extends the statically-captured (original) Request, + * bypassing the construct proxy that records raw headers. + */ + Object.setPrototypeOf(require_fetchUtils.FetchRequest, globalThis.Request); + Object.setPrototypeOf(require_fetchUtils.FetchRequest.prototype, globalThis.Request.prototype); + Object.setPrototypeOf(require_fetchUtils.FetchResponse, globalThis.Response); + Object.setPrototypeOf(require_fetchUtils.FetchResponse.prototype, globalThis.Response.prototype); +} +function restoreHeadersPrototype() { + if (!Reflect.get(Headers, kRestorePatches)) return; + Reflect.get(Headers, kRestorePatches)(); +} +function getRawFetchHeaders(headers) { + if (!Reflect.has(headers, kRawHeaders)) return Array.from(headers.entries()); + const rawHeaders = Reflect.get(headers, kRawHeaders); + return rawHeaders.length > 0 ? rawHeaders : Array.from(headers.entries()); +} +/** +* Infers the raw headers from the given `HeadersInit` provided +* to the Request/Response constructor. +* +* If the `init.headers` is a Headers instance, use it directly. +* That means the headers were created standalone and already have +* the raw headers stored. +* If the `init.headers` is a HeadersInit, create a new Headers +* instance out of it. +*/ +function inferRawHeaders(headers) { + if (headers instanceof Headers) return Reflect.get(headers, kRawHeaders) || []; + return Reflect.get(new Headers(headers), kRawHeaders); +} + +//#endregion +//#region src/interceptors/ClientRequest/utils/parserUtils.ts +/** +* @see https://github.com/nodejs/node/blob/f3adc11e37b8bfaaa026ea85c1cf22e3a0e29ae9/lib/_http_common.js#L180 +*/ +function freeParser(parser, socket) { + if (parser._consumed) parser.unconsume(); + parser._headers = []; + parser._url = ""; + parser.socket = null; + parser.incoming = null; + parser.outgoing = null; + parser.maxHeaderPairs = 2e3; + parser._consumed = false; + parser.onIncoming = null; + parser[_http_common.HTTPParser.kOnHeaders] = null; + parser[_http_common.HTTPParser.kOnHeadersComplete] = null; + parser[_http_common.HTTPParser.kOnMessageBegin] = null; + parser[_http_common.HTTPParser.kOnMessageComplete] = null; + parser[_http_common.HTTPParser.kOnBody] = null; + parser[_http_common.HTTPParser.kOnExecute] = null; + parser[_http_common.HTTPParser.kOnTimeout] = null; + parser.remove(); + parser.free(); + if (socket) + /** + * @note Unassigning the socket's parser will fail this assertion + * if there's still some data being processed on the socket: + * @see https://github.com/nodejs/node/blob/4e1f39b678b37017ac9baa0971e3aeecd3b67b51/lib/_http_client.js#L613 + */ + if (socket.destroyed) socket.parser = null; + else socket.once("end", () => { + socket.parser = null; + }); +} + +//#endregion +//#region src/interceptors/ClientRequest/MockHttpSocket.ts +const kRequestId = Symbol("kRequestId"); +var MockHttpSocket = class extends MockSocket { + constructor(options) { + super({ + write: (chunk, encoding, callback) => { + if (this.socketState !== "passthrough") this.writeBuffer.push([ + chunk, + encoding, + callback + ]); + if (chunk) { + /** + * Forward any writes to the mock socket to the underlying original socket. + * This ensures functional duplex connections, like WebSocket. + * @see https://github.com/mswjs/interceptors/issues/682 + */ + if (this.socketState === "passthrough") this.originalSocket?.write(chunk, encoding, callback); + this.requestParser.execute(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding)); + } + }, + read: (chunk) => { + if (chunk !== null) + /** + * @todo We need to free the parser if the connection has been + * upgraded to a non-HTTP protocol. It won't be able to parse data + * from that point onward anyway. No need to keep it in memory. + */ + this.responseParser.execute(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); + } + }); + this.requestRawHeadersBuffer = []; + this.responseRawHeadersBuffer = []; + this.writeBuffer = []; + this.socketState = "unknown"; + this.onRequestHeaders = (rawHeaders) => { + this.requestRawHeadersBuffer.push(...rawHeaders); + }; + this.onRequestStart = (versionMajor, versionMinor, rawHeaders, _, path, __, ___, ____, shouldKeepAlive) => { + this.shouldKeepAlive = shouldKeepAlive; + const url = new URL(path || "", this.baseUrl); + const method = this.connectionOptions.method?.toUpperCase() || "GET"; + const headers = require_fetchUtils.FetchResponse.parseRawHeaders([...this.requestRawHeadersBuffer, ...rawHeaders || []]); + this.requestRawHeadersBuffer.length = 0; + const canHaveBody = method !== "GET" && method !== "HEAD"; + if (url.username || url.password) { + if (!headers.has("authorization")) headers.set("authorization", `Basic ${url.username}:${url.password}`); + url.username = ""; + url.password = ""; + } + this.requestStream = new node_stream.Readable({ read: () => { + this.flushWriteBuffer(); + } }); + const requestId = require_fetchUtils.createRequestId(); + this.request = new require_fetchUtils.FetchRequest(url, { + method, + headers, + credentials: "same-origin", + duplex: canHaveBody ? "half" : void 0, + body: canHaveBody ? node_stream.Readable.toWeb(this.requestStream) : null + }); + Reflect.set(this.request, kRequestId, requestId); + require_getRawRequest.setRawRequest(this.request, Reflect.get(this, "_httpMessage")); + require_node.setRawRequestBodyStream(this.request, this.requestStream); + /** + * @fixme Stop relying on the "X-Request-Id" request header + * to figure out if one interceptor has been invoked within another. + * @see https://github.com/mswjs/interceptors/issues/378 + */ + if (this.request.headers.has(require_fetchUtils.INTERNAL_REQUEST_ID_HEADER_NAME)) { + this.passthrough(); + return; + } + this.onRequest({ + requestId, + request: this.request, + socket: this + }); + }; + this.onResponseHeaders = (rawHeaders) => { + this.responseRawHeadersBuffer.push(...rawHeaders); + }; + this.onResponseStart = (versionMajor, versionMinor, rawHeaders, method, url, status, statusText) => { + const headers = require_fetchUtils.FetchResponse.parseRawHeaders([...this.responseRawHeadersBuffer, ...rawHeaders || []]); + this.responseRawHeadersBuffer.length = 0; + const response = new require_fetchUtils.FetchResponse( + /** + * @note The Fetch API response instance exposed to the consumer + * is created over the response stream of the HTTP parser. It is NOT + * related to the Socket instance. This way, you can read response body + * in response listener while the Socket instance delays the emission + * of "end" and other events until those response listeners are finished. + */ + require_fetchUtils.FetchResponse.isResponseWithBody(status) ? node_stream.Readable.toWeb(this.responseStream = new node_stream.Readable({ read() {} })) : null, + { + url, + status, + statusText, + headers + } + ); + (0, outvariant.invariant)(this.request, "Failed to handle a response: request does not exist"); + require_fetchUtils.FetchResponse.setUrl(this.request.url, response); + /** + * @fixme Stop relying on the "X-Request-Id" request header + * to figure out if one interceptor has been invoked within another. + * @see https://github.com/mswjs/interceptors/issues/378 + */ + if (this.request.headers.has(require_fetchUtils.INTERNAL_REQUEST_ID_HEADER_NAME)) return; + this.responseListenersPromise = this.onResponse({ + response, + isMockedResponse: this.socketState === "mock", + requestId: Reflect.get(this.request, kRequestId), + request: this.request, + socket: this + }); + }; + this.connectionOptions = options.connectionOptions; + this.createConnection = options.createConnection; + this.onRequest = options.onRequest; + this.onResponse = options.onResponse; + this.baseUrl = baseUrlFromConnectionOptions(this.connectionOptions); + this.requestParser = new _http_common.HTTPParser(); + this.requestParser.initialize(_http_common.HTTPParser.REQUEST, {}); + this.requestParser[_http_common.HTTPParser.kOnHeaders] = this.onRequestHeaders.bind(this); + this.requestParser[_http_common.HTTPParser.kOnHeadersComplete] = this.onRequestStart.bind(this); + this.requestParser[_http_common.HTTPParser.kOnBody] = this.onRequestBody.bind(this); + this.requestParser[_http_common.HTTPParser.kOnMessageComplete] = this.onRequestEnd.bind(this); + this.responseParser = new _http_common.HTTPParser(); + this.responseParser.initialize(_http_common.HTTPParser.RESPONSE, {}); + this.responseParser[_http_common.HTTPParser.kOnHeaders] = this.onResponseHeaders.bind(this); + this.responseParser[_http_common.HTTPParser.kOnHeadersComplete] = this.onResponseStart.bind(this); + this.responseParser[_http_common.HTTPParser.kOnBody] = this.onResponseBody.bind(this); + this.responseParser[_http_common.HTTPParser.kOnMessageComplete] = this.onResponseEnd.bind(this); + this.once("finish", () => freeParser(this.requestParser, this)); + if (this.baseUrl.protocol === "https:") { + Reflect.set(this, "encrypted", true); + Reflect.set(this, "authorized", false); + Reflect.set(this, "getProtocol", () => "TLSv1.3"); + Reflect.set(this, "getSession", () => void 0); + Reflect.set(this, "isSessionReused", () => false); + Reflect.set(this, "getCipher", () => ({ + name: "AES256-SHA", + standardName: "TLS_RSA_WITH_AES_256_CBC_SHA", + version: "TLSv1.3" + })); + } + } + emit(event, ...args) { + const emitEvent = super.emit.bind(this, event, ...args); + if (this.responseListenersPromise) { + this.responseListenersPromise.finally(emitEvent); + return this.listenerCount(event) > 0; + } + return emitEvent(); + } + destroy(error) { + freeParser(this.responseParser, this); + if (error) this.emit("error", error); + return super.destroy(error); + } + /** + * Establish this Socket connection as-is and pipe + * its data/events through this Socket. + */ + passthrough() { + this.socketState = "passthrough"; + if (this.destroyed) return; + const socket = this.createConnection(); + this.originalSocket = socket; + /** + * @note Inherit the original socket's connection handle. + * Without this, each push to the mock socket results in a + * new "connection" listener being added (i.e. buffering pushes). + * @see https://github.com/nodejs/node/blob/b18153598b25485ce4f54d0c5cb830a9457691ee/lib/net.js#L734 + */ + if ("_handle" in socket) Object.defineProperty(this, "_handle", { + value: socket._handle, + enumerable: true, + writable: true + }); + this.once("close", () => { + socket.removeAllListeners(); + if (!socket.destroyed) socket.destroy(); + this.originalSocket = void 0; + }); + this.address = socket.address.bind(socket); + let writeArgs; + let headersWritten = false; + while (writeArgs = this.writeBuffer.shift()) if (writeArgs !== void 0) { + if (!headersWritten) { + const [chunk, encoding, callback] = writeArgs; + const chunkString = chunk.toString(); + const chunkBeforeRequestHeaders = chunkString.slice(0, chunkString.indexOf("\r\n") + 2); + const chunkAfterRequestHeaders = chunkString.slice(chunk.indexOf("\r\n\r\n")); + const headersChunk = `${chunkBeforeRequestHeaders}${getRawFetchHeaders(this.request.headers).filter(([name]) => { + return name.toLowerCase() !== require_fetchUtils.INTERNAL_REQUEST_ID_HEADER_NAME; + }).map(([name, value]) => `${name}: ${value}`).join("\r\n")}${chunkAfterRequestHeaders}`; + socket.write(headersChunk, encoding, callback); + headersWritten = true; + continue; + } + socket.write(...writeArgs); + } + if (Reflect.get(socket, "encrypted")) [ + "encrypted", + "authorized", + "getProtocol", + "getSession", + "isSessionReused", + "getCipher" + ].forEach((propertyName) => { + Object.defineProperty(this, propertyName, { + enumerable: true, + get: () => { + const value = Reflect.get(socket, propertyName); + return typeof value === "function" ? value.bind(socket) : value; + } + }); + }); + socket.on("lookup", (...args) => this.emit("lookup", ...args)).on("connect", () => { + this.connecting = socket.connecting; + this.emit("connect"); + }).on("secureConnect", () => this.emit("secureConnect")).on("secure", () => this.emit("secure")).on("session", (session) => this.emit("session", session)).on("ready", () => this.emit("ready")).on("drain", () => this.emit("drain")).on("data", (chunk) => { + this.push(chunk); + }).on("error", (error) => { + Reflect.set(this, "_hadError", Reflect.get(socket, "_hadError")); + this.emit("error", error); + }).on("resume", () => this.emit("resume")).on("timeout", () => this.emit("timeout")).on("prefinish", () => this.emit("prefinish")).on("finish", () => this.emit("finish")).on("close", (hadError) => this.emit("close", hadError)).on("end", () => this.emit("end")); + } + /** + * Convert the given Fetch API `Response` instance to an + * HTTP message and push it to the socket. + */ + async respondWith(response) { + if (this.destroyed) return; + (0, outvariant.invariant)(this.socketState !== "mock", "[MockHttpSocket] Failed to respond to the \"%s %s\" request with \"%s %s\": the request has already been handled", this.request?.method, this.request?.url, response.status, response.statusText); + if (require_handleRequest.isPropertyAccessible(response, "type") && response.type === "error") { + this.errorWith(/* @__PURE__ */ new TypeError("Network error")); + return; + } + this.mockConnect(); + this.socketState = "mock"; + this.flushWriteBuffer(); + const serverResponse = new node_http.ServerResponse(new node_http.IncomingMessage(this)); + /** + * Assign a mock socket instance to the server response to + * spy on the response chunk writes. Push the transformed response chunks + * to this `MockHttpSocket` instance to trigger the "data" event. + * @note Providing the same `MockSocket` instance when creating `ServerResponse` + * does not have the same effect. + * @see https://github.com/nodejs/node/blob/10099bb3f7fd97bb9dd9667188426866b3098e07/test/parallel/test-http-server-response-standalone.js#L32 + */ + serverResponse.assignSocket(new MockSocket({ + write: (chunk, encoding, callback) => { + this.push(chunk, encoding); + callback?.(); + }, + read() {} + })); + /** + * @note Remove the `Connection` and `Date` response headers + * injected by `ServerResponse` by default. Those are required + * from the server but the interceptor is NOT technically a server. + * It's confusing to add response headers that the developer didn't + * specify themselves. They can always add these if they wish. + * @see https://www.rfc-editor.org/rfc/rfc9110#field.date + * @see https://www.rfc-editor.org/rfc/rfc9110#field.connection + */ + serverResponse.removeHeader("connection"); + serverResponse.removeHeader("date"); + const rawResponseHeaders = getRawFetchHeaders(response.headers); + /** + * @note Call `.writeHead` in order to set the raw response headers + * in the same case as they were provided by the developer. Using + * `.setHeader()`/`.appendHeader()` normalizes header names. + */ + serverResponse.writeHead(response.status, response.statusText || node_http.STATUS_CODES[response.status], rawResponseHeaders); + this.once("error", () => { + serverResponse.destroy(); + }); + if (response.body) try { + const reader = response.body.getReader(); + while (true) { + const { done, value } = await reader.read(); + if (done) { + serverResponse.end(); + break; + } + serverResponse.write(value); + } + } catch (error) { + if (error instanceof Error) { + serverResponse.destroy(); + /** + * @note Destroy the request socket gracefully. + * Response stream errors do NOT produce request errors. + */ + this.destroy(); + return; + } + serverResponse.destroy(); + throw error; + } + else serverResponse.end(); + if (!this.shouldKeepAlive) { + this.emit("readable"); + /** + * @todo @fixme This is likely a hack. + * Since we push null to the socket, it never propagates to the + * parser, and the parser never calls "onResponseEnd" to close + * the response stream. We are closing the stream here manually + * but that shouldn't be the case. + */ + this.responseStream?.push(null); + this.push(null); + } + } + /** + * Close this socket connection with the given error. + */ + errorWith(error) { + this.destroy(error); + } + mockConnect() { + this.connecting = false; + const isIPv6 = node_net.default.isIPv6(this.connectionOptions.hostname) || this.connectionOptions.family === 6; + const addressInfo = { + address: isIPv6 ? "::1" : "127.0.0.1", + family: isIPv6 ? "IPv6" : "IPv4", + port: this.connectionOptions.port + }; + this.address = () => addressInfo; + this.emit("lookup", null, addressInfo.address, addressInfo.family === "IPv6" ? 6 : 4, this.connectionOptions.host); + this.emit("connect"); + this.emit("ready"); + if (this.baseUrl.protocol === "https:") { + this.emit("secure"); + this.emit("secureConnect"); + this.emit("session", this.connectionOptions.session || Buffer.from("mock-session-renegotiate")); + this.emit("session", Buffer.from("mock-session-resume")); + } + } + flushWriteBuffer() { + for (const writeCall of this.writeBuffer) if (typeof writeCall[2] === "function") { + writeCall[2](); + /** + * @note Remove the callback from the write call + * so it doesn't get called twice on passthrough + * if `request.end()` was called within `request.write()`. + * @see https://github.com/mswjs/interceptors/issues/684 + */ + writeCall[2] = void 0; + } + } + onRequestBody(chunk) { + (0, outvariant.invariant)(this.requestStream, "Failed to write to a request stream: stream does not exist"); + this.requestStream.push(chunk); + } + onRequestEnd() { + if (this.requestStream) this.requestStream.push(null); + } + onResponseBody(chunk) { + (0, outvariant.invariant)(this.responseStream, "Failed to write to a response stream: stream does not exist"); + this.responseStream.push(chunk); + } + onResponseEnd() { + if (this.responseStream) this.responseStream.push(null); + } +}; + +//#endregion +//#region src/interceptors/ClientRequest/agents.ts +var MockAgent = class extends node_http.default.Agent { + constructor(options) { + super(); + this.customAgent = options.customAgent; + this.onRequest = options.onRequest; + this.onResponse = options.onResponse; + } + createConnection(options, callback) { + const createConnection = this.customAgent instanceof node_http.default.Agent ? this.customAgent.createConnection : super.createConnection; + const createConnectionOptions = this.customAgent instanceof node_http.default.Agent ? { + ...options, + ...this.customAgent.options + } : options; + return new MockHttpSocket({ + connectionOptions: options, + createConnection: createConnection.bind(this.customAgent || this, createConnectionOptions, callback), + onRequest: this.onRequest.bind(this), + onResponse: this.onResponse.bind(this) + }); + } +}; +var MockHttpsAgent = class extends node_https.default.Agent { + constructor(options) { + super(); + this.customAgent = options.customAgent; + this.onRequest = options.onRequest; + this.onResponse = options.onResponse; + } + createConnection(options, callback) { + const createConnection = this.customAgent instanceof node_http.default.Agent ? this.customAgent.createConnection : super.createConnection; + const createConnectionOptions = this.customAgent instanceof node_http.default.Agent ? { + ...options, + ...this.customAgent.options + } : options; + return new MockHttpSocket({ + connectionOptions: options, + createConnection: createConnection.bind(this.customAgent || this, createConnectionOptions, callback), + onRequest: this.onRequest.bind(this), + onResponse: this.onResponse.bind(this) + }); + } +}; + +//#endregion +//#region src/utils/getUrlByRequestOptions.ts +const logger$2 = new _open_draft_logger.Logger("utils getUrlByRequestOptions"); +const DEFAULT_PATH = "/"; +const DEFAULT_PROTOCOL = "http:"; +const DEFAULT_HOSTNAME = "localhost"; +const SSL_PORT = 443; +function getAgent(options) { + return options.agent instanceof http.Agent ? options.agent : void 0; +} +function getProtocolByRequestOptions(options) { + if (options.protocol) return options.protocol; + const agentProtocol = getAgent(options)?.protocol; + if (agentProtocol) return agentProtocol; + const port = getPortByRequestOptions(options); + return options.cert || port === SSL_PORT ? "https:" : options.uri?.protocol || DEFAULT_PROTOCOL; +} +function getPortByRequestOptions(options) { + if (options.port) return Number(options.port); + const agent = getAgent(options); + if (agent?.options.port) return Number(agent.options.port); + if (agent?.defaultPort) return Number(agent.defaultPort); +} +function getAuthByRequestOptions(options) { + if (options.auth) { + const [username, password] = options.auth.split(":"); + return { + username, + password + }; + } +} +/** +* Returns true if host looks like an IPv6 address without surrounding brackets +* It assumes any host containing `:` is definitely not IPv4 and probably IPv6, +* but note that this could include invalid IPv6 addresses as well. +*/ +function isRawIPv6Address(host) { + return host.includes(":") && !host.startsWith("[") && !host.endsWith("]"); +} +function getHostname(options) { + let host = options.hostname || options.host; + if (host) { + if (isRawIPv6Address(host)) host = `[${host}]`; + return new URL(`http://${host}`).hostname; + } + return DEFAULT_HOSTNAME; +} +/** +* Creates a `URL` instance from a given `RequestOptions` object. +*/ +function getUrlByRequestOptions(options) { + logger$2.info("request options", options); + if (options.uri) { + logger$2.info("constructing url from explicitly provided \"options.uri\": %s", options.uri); + return new URL(options.uri.href); + } + logger$2.info("figuring out url from request options..."); + const protocol = getProtocolByRequestOptions(options); + logger$2.info("protocol", protocol); + const port = getPortByRequestOptions(options); + logger$2.info("port", port); + const hostname = getHostname(options); + logger$2.info("hostname", hostname); + const path = options.path || DEFAULT_PATH; + logger$2.info("path", path); + const credentials = getAuthByRequestOptions(options); + logger$2.info("credentials", credentials); + const authString = credentials ? `${credentials.username}:${credentials.password}@` : ""; + logger$2.info("auth string:", authString); + const portString = typeof port !== "undefined" ? `:${port}` : ""; + const url = new URL(`${protocol}//${hostname}${portString}${path}`); + url.username = credentials?.username || ""; + url.password = credentials?.password || ""; + logger$2.info("created url:", url); + return url; +} + +//#endregion +//#region src/utils/cloneObject.ts +const logger$1 = new _open_draft_logger.Logger("cloneObject"); +function isPlainObject(obj) { + logger$1.info("is plain object?", obj); + if (obj == null || !obj.constructor?.name) { + logger$1.info("given object is undefined, not a plain object..."); + return false; + } + logger$1.info("checking the object constructor:", obj.constructor.name); + return obj.constructor.name === "Object"; +} +function cloneObject(obj) { + logger$1.info("cloning object:", obj); + const enumerableProperties = Object.entries(obj).reduce((acc, [key, value]) => { + logger$1.info("analyzing key-value pair:", key, value); + acc[key] = isPlainObject(value) ? cloneObject(value) : value; + return acc; + }, {}); + return isPlainObject(obj) ? enumerableProperties : Object.assign(Object.getPrototypeOf(obj), enumerableProperties); +} + +//#endregion +//#region src/interceptors/ClientRequest/utils/normalizeClientRequestArgs.ts +const logger = new _open_draft_logger.Logger("http normalizeClientRequestArgs"); +function resolveRequestOptions(args, url) { + if (typeof args[1] === "undefined" || typeof args[1] === "function") { + logger.info("request options not provided, deriving from the url", url); + return (0, node_url.urlToHttpOptions)(url); + } + if (args[1]) { + logger.info("has custom RequestOptions!", args[1]); + const requestOptionsFromUrl = (0, node_url.urlToHttpOptions)(url); + logger.info("derived RequestOptions from the URL:", requestOptionsFromUrl); + /** + * Clone the request options to lock their state + * at the moment they are provided to `ClientRequest`. + * @see https://github.com/mswjs/interceptors/issues/86 + */ + logger.info("cloning RequestOptions..."); + const clonedRequestOptions = cloneObject(args[1]); + logger.info("successfully cloned RequestOptions!", clonedRequestOptions); + return { + ...requestOptionsFromUrl, + ...clonedRequestOptions + }; + } + logger.info("using an empty object as request options"); + return {}; +} +/** +* Overrides the given `URL` instance with the explicit properties provided +* on the `RequestOptions` object. The options object takes precedence, +* and will replace URL properties like "host", "path", and "port", if specified. +*/ +function overrideUrlByRequestOptions(url, options) { + url.host = options.host || url.host; + url.hostname = options.hostname || url.hostname; + url.port = options.port ? options.port.toString() : url.port; + if (options.path) { + const parsedOptionsPath = (0, node_url.parse)(options.path, false); + url.pathname = parsedOptionsPath.pathname || ""; + url.search = parsedOptionsPath.search || ""; + } + return url; +} +function resolveCallback(args) { + return typeof args[1] === "function" ? args[1] : args[2]; +} +/** +* Normalizes parameters given to a `http.request` call +* so it always has a `URL` and `RequestOptions`. +*/ +function normalizeClientRequestArgs(defaultProtocol, args) { + let url; + let options; + let callback; + logger.info("arguments", args); + logger.info("using default protocol:", defaultProtocol); + if (args.length === 0) { + const url$1 = new node_url.URL("http://localhost"); + return [url$1, resolveRequestOptions(args, url$1)]; + } + if (typeof args[0] === "string") { + logger.info("first argument is a location string:", args[0]); + url = new node_url.URL(args[0]); + logger.info("created a url:", url); + const requestOptionsFromUrl = (0, node_url.urlToHttpOptions)(url); + logger.info("request options from url:", requestOptionsFromUrl); + options = resolveRequestOptions(args, url); + logger.info("resolved request options:", options); + callback = resolveCallback(args); + } else if (args[0] instanceof node_url.URL) { + url = args[0]; + logger.info("first argument is a URL:", url); + if (typeof args[1] !== "undefined" && require_handleRequest.isObject(args[1])) url = overrideUrlByRequestOptions(url, args[1]); + options = resolveRequestOptions(args, url); + logger.info("derived request options:", options); + callback = resolveCallback(args); + } else if ("hash" in args[0] && !("method" in args[0])) { + const [legacyUrl] = args; + logger.info("first argument is a legacy URL:", legacyUrl); + if (legacyUrl.hostname === null) { + /** + * We are dealing with a relative url, so use the path as an "option" and + * merge in any existing options, giving priority to existing options -- i.e. a path in any + * existing options will take precedence over the one contained in the url. This is consistent + * with the behaviour in ClientRequest. + * @see https://github.com/nodejs/node/blob/d84f1312915fe45fe0febe888db692c74894c382/lib/_http_client.js#L122 + */ + logger.info("given legacy URL is relative (no hostname)"); + return require_handleRequest.isObject(args[1]) ? normalizeClientRequestArgs(defaultProtocol, [{ + path: legacyUrl.path, + ...args[1] + }, args[2]]) : normalizeClientRequestArgs(defaultProtocol, [{ path: legacyUrl.path }, args[1]]); + } + logger.info("given legacy url is absolute"); + const resolvedUrl = new node_url.URL(legacyUrl.href); + return args[1] === void 0 ? normalizeClientRequestArgs(defaultProtocol, [resolvedUrl]) : typeof args[1] === "function" ? normalizeClientRequestArgs(defaultProtocol, [resolvedUrl, args[1]]) : normalizeClientRequestArgs(defaultProtocol, [ + resolvedUrl, + args[1], + args[2] + ]); + } else if (require_handleRequest.isObject(args[0])) { + options = { ...args[0] }; + logger.info("first argument is RequestOptions:", options); + options.protocol = options.protocol || defaultProtocol; + logger.info("normalized request options:", options); + url = getUrlByRequestOptions(options); + logger.info("created a URL from RequestOptions:", url.href); + callback = resolveCallback(args); + } else throw new Error(`Failed to construct ClientRequest with these parameters: ${args}`); + options.protocol = options.protocol || url.protocol; + options.method = options.method || "GET"; + /** + * Ensure that the default Agent is always set. + * This prevents the protocol mismatch for requests with { agent: false }, + * where the global Agent is inferred. + * @see https://github.com/mswjs/msw/issues/1150 + * @see https://github.com/nodejs/node/blob/418ff70b810f0e7112d48baaa72932a56cfa213b/lib/_http_client.js#L130 + * @see https://github.com/nodejs/node/blob/418ff70b810f0e7112d48baaa72932a56cfa213b/lib/_http_client.js#L157-L159 + */ + if (!options._defaultAgent) { + logger.info("has no default agent, setting the default agent for \"%s\"", options.protocol); + options._defaultAgent = options.protocol === "https:" ? node_https.globalAgent : node_http.globalAgent; + } + logger.info("successfully resolved url:", url.href); + logger.info("successfully resolved options:", options); + logger.info("successfully resolved callback:", callback); + /** + * @note If the user-provided URL is not a valid URL in Node.js, + * (e.g. the one provided by the JSDOM polyfills), case it to + * string. Otherwise, this throws on Node.js incompatibility + * (`ERR_INVALID_ARG_TYPE` on the connection listener) + * @see https://github.com/node-fetch/node-fetch/issues/1376#issuecomment-966435555 + */ + if (!(url instanceof node_url.URL)) url = url.toString(); + return [ + url, + options, + callback + ]; +} + +//#endregion +//#region src/interceptors/ClientRequest/index.ts +var ClientRequestInterceptor = class ClientRequestInterceptor extends require_fetchUtils.Interceptor { + static { + this.symbol = Symbol.for("client-request-interceptor"); + } + constructor() { + super(ClientRequestInterceptor.symbol); + this.onRequest = async ({ request, socket }) => { + const controller = new require_fetchUtils.RequestController(request, { + passthrough() { + socket.passthrough(); + }, + async respondWith(response) { + await socket.respondWith(response); + }, + errorWith(reason) { + if (reason instanceof Error) socket.errorWith(reason); + } + }); + await require_handleRequest.handleRequest({ + request, + requestId: Reflect.get(request, kRequestId), + controller, + emitter: this.emitter + }); + }; + this.onResponse = async ({ requestId, request, response, isMockedResponse }) => { + return require_handleRequest.emitAsync(this.emitter, "response", { + requestId, + request, + response, + isMockedResponse + }); + }; + } + setup() { + const { ClientRequest: OriginalClientRequest, get: originalGet, request: originalRequest } = node_http.default; + const { get: originalHttpsGet, request: originalHttpsRequest } = node_https.default; + const onRequest = this.onRequest.bind(this); + const onResponse = this.onResponse.bind(this); + node_http.default.ClientRequest = new Proxy(node_http.default.ClientRequest, { construct: (target, args) => { + const [url, options, callback] = normalizeClientRequestArgs("http:", args); + options.agent = new (options.protocol === "https:" ? MockHttpsAgent : MockAgent)({ + customAgent: options.agent, + onRequest, + onResponse + }); + return Reflect.construct(target, [ + url, + options, + callback + ]); + } }); + node_http.default.request = new Proxy(node_http.default.request, { apply: (target, thisArg, args) => { + const [url, options, callback] = normalizeClientRequestArgs("http:", args); + options.agent = new MockAgent({ + customAgent: options.agent, + onRequest, + onResponse + }); + return Reflect.apply(target, thisArg, [ + url, + options, + callback + ]); + } }); + node_http.default.get = new Proxy(node_http.default.get, { apply: (target, thisArg, args) => { + const [url, options, callback] = normalizeClientRequestArgs("http:", args); + options.agent = new MockAgent({ + customAgent: options.agent, + onRequest, + onResponse + }); + return Reflect.apply(target, thisArg, [ + url, + options, + callback + ]); + } }); + node_https.default.request = new Proxy(node_https.default.request, { apply: (target, thisArg, args) => { + const [url, options, callback] = normalizeClientRequestArgs("https:", args); + options.agent = new MockHttpsAgent({ + customAgent: options.agent, + onRequest, + onResponse + }); + return Reflect.apply(target, thisArg, [ + url, + options, + callback + ]); + } }); + node_https.default.get = new Proxy(node_https.default.get, { apply: (target, thisArg, args) => { + const [url, options, callback] = normalizeClientRequestArgs("https:", args); + options.agent = new MockHttpsAgent({ + customAgent: options.agent, + onRequest, + onResponse + }); + return Reflect.apply(target, thisArg, [ + url, + options, + callback + ]); + } }); + recordRawFetchHeaders(); + this.subscriptions.push(() => { + node_http.default.ClientRequest = OriginalClientRequest; + node_http.default.get = originalGet; + node_http.default.request = originalRequest; + node_https.default.get = originalHttpsGet; + node_https.default.request = originalHttpsRequest; + restoreHeadersPrototype(); + }); + } +}; + +//#endregion +Object.defineProperty(exports, 'ClientRequestInterceptor', { + enumerable: true, + get: function () { + return ClientRequestInterceptor; + } +}); +//# sourceMappingURL=ClientRequest-2loAH7xM.cjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/ClientRequest-2loAH7xM.cjs.map b/node_modules/@mswjs/interceptors/lib/node/ClientRequest-2loAH7xM.cjs.map new file mode 100644 index 0000000000000000000000000000000000000000..03e747fd3244819311c44c3d30069ee547b03527 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/ClientRequest-2loAH7xM.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"ClientRequest-2loAH7xM.cjs","names":["normalized: NormalizedSocketWriteArgs","net","options: MockSocketOptions","FetchRequest","FetchResponse","headers","inferredRawHeaders: RawHeaders","HTTPParser","FetchResponse","Readable","createRequestId","FetchRequest","INTERNAL_REQUEST_ID_HEADER_NAME","HTTPParser","writeArgs: NormalizedSocketWriteArgs | undefined","isPropertyAccessible","ServerResponse","IncomingMessage","STATUS_CODES","net","http","https","logger","Logger","Agent","logger","Logger","Logger","url: URL","options: ResolvedRequestOptions","callback: HttpRequestCallback | undefined","url","URL","isObject","httpsGlobalAgent","httpGlobalAgent","Interceptor","RequestController","handleRequest","emitAsync","http","https"],"sources":["../../src/interceptors/Socket/utils/normalizeSocketWriteArgs.ts","../../src/interceptors/Socket/MockSocket.ts","../../src/interceptors/Socket/utils/baseUrlFromConnectionOptions.ts","../../src/interceptors/ClientRequest/utils/recordRawHeaders.ts","../../src/interceptors/ClientRequest/utils/parserUtils.ts","../../src/interceptors/ClientRequest/MockHttpSocket.ts","../../src/interceptors/ClientRequest/agents.ts","../../src/utils/getUrlByRequestOptions.ts","../../src/utils/cloneObject.ts","../../src/interceptors/ClientRequest/utils/normalizeClientRequestArgs.ts","../../src/interceptors/ClientRequest/index.ts"],"sourcesContent":["export type WriteCallback = (error?: Error | null) => void\n\nexport type WriteArgs =\n | [chunk: unknown, callback?: WriteCallback]\n | [chunk: unknown, encoding: BufferEncoding, callback?: WriteCallback]\n\nexport type NormalizedSocketWriteArgs = [\n chunk: any,\n encoding?: BufferEncoding,\n callback?: WriteCallback,\n]\n\n/**\n * Normalizes the arguments provided to the `Writable.prototype.write()`\n * and `Writable.prototype.end()`.\n */\nexport function normalizeSocketWriteArgs(\n args: WriteArgs\n): NormalizedSocketWriteArgs {\n const normalized: NormalizedSocketWriteArgs = [args[0], undefined, undefined]\n\n if (typeof args[1] === 'string') {\n normalized[1] = args[1]\n } else if (typeof args[1] === 'function') {\n normalized[2] = args[1]\n }\n\n if (typeof args[2] === 'function') {\n normalized[2] = args[2]\n }\n\n return normalized\n}\n","import net from 'node:net'\nimport {\n normalizeSocketWriteArgs,\n type WriteArgs,\n type WriteCallback,\n} from './utils/normalizeSocketWriteArgs'\n\nexport interface MockSocketOptions {\n write: (\n chunk: Buffer | string,\n encoding: BufferEncoding | undefined,\n callback?: WriteCallback\n ) => void\n\n read: (chunk: Buffer, encoding: BufferEncoding | undefined) => void\n}\n\nexport class MockSocket extends net.Socket {\n public connecting: boolean\n\n constructor(protected readonly options: MockSocketOptions) {\n super()\n this.connecting = false\n this.connect()\n\n this._final = (callback) => {\n callback(null)\n }\n }\n\n public connect() {\n // The connection will remain pending until\n // the consumer decides to handle it.\n this.connecting = true\n return this\n }\n\n public write(...args: Array): boolean {\n const [chunk, encoding, callback] = normalizeSocketWriteArgs(\n args as WriteArgs\n )\n this.options.write(chunk, encoding, callback)\n return true\n }\n\n public end(...args: Array) {\n const [chunk, encoding, callback] = normalizeSocketWriteArgs(\n args as WriteArgs\n )\n this.options.write(chunk, encoding, callback)\n return super.end.apply(this, args as any)\n }\n\n public push(chunk: any, encoding?: BufferEncoding): boolean {\n this.options.read(chunk, encoding)\n return super.push(chunk, encoding)\n }\n}\n","export function baseUrlFromConnectionOptions(options: any): URL {\n if ('href' in options) {\n return new URL(options.href)\n }\n\n const protocol = options.port === 443 ? 'https:' : 'http:'\n const host = options.host\n\n const url = new URL(`${protocol}//${host}`)\n\n if (options.port) {\n url.port = options.port.toString()\n }\n\n if (options.path) {\n url.pathname = options.path\n }\n\n if (options.auth) {\n const [username, password] = options.auth.split(':')\n url.username = username\n url.password = password\n }\n\n return url\n}\n","import { FetchRequest, FetchResponse } from '../../../utils/fetchUtils'\n\ntype HeaderTuple = [string, string]\ntype RawHeaders = Array\ntype SetHeaderBehavior = 'set' | 'append'\n\nconst kRawHeaders = Symbol('kRawHeaders')\nconst kRestorePatches = Symbol('kRestorePatches')\n\nfunction recordRawHeader(\n headers: Headers,\n args: HeaderTuple,\n behavior: SetHeaderBehavior\n) {\n ensureRawHeadersSymbol(headers, [])\n const rawHeaders = Reflect.get(headers, kRawHeaders) as RawHeaders\n\n if (behavior === 'set') {\n // When recording a set header, ensure we remove any matching existing headers.\n for (let index = rawHeaders.length - 1; index >= 0; index--) {\n if (rawHeaders[index][0].toLowerCase() === args[0].toLowerCase()) {\n rawHeaders.splice(index, 1)\n }\n }\n }\n\n rawHeaders.push(args)\n}\n\n/**\n * Define the raw headers symbol on the given `Headers` instance.\n * If the symbol already exists, this function does nothing.\n */\nfunction ensureRawHeadersSymbol(\n headers: Headers,\n rawHeaders: RawHeaders\n): void {\n if (Reflect.has(headers, kRawHeaders)) {\n return\n }\n\n defineRawHeadersSymbol(headers, rawHeaders)\n}\n\n/**\n * Define the raw headers symbol on the given `Headers` instance.\n * If the symbol already exists, it gets overridden.\n */\nfunction defineRawHeadersSymbol(headers: Headers, rawHeaders: RawHeaders) {\n Object.defineProperty(headers, kRawHeaders, {\n value: rawHeaders,\n enumerable: false,\n // Mark the symbol as configurable so its value can be overridden.\n // Overrides happen when merging raw headers from multiple sources.\n // E.g. new Request(new Request(url, { headers }), { headers })\n configurable: true,\n })\n}\n\n/**\n * Patch the global `Headers` class to store raw headers.\n * This is for compatibility with `IncomingMessage.prototype.rawHeaders`.\n *\n * @note Node.js has their own raw headers symbol but it\n * only records the first header name in case of multi-value headers.\n * Any other headers are normalized before comparing. This makes it\n * incompatible with the `rawHeaders` format.\n *\n * let h = new Headers()\n * h.append('X-Custom', 'one')\n * h.append('x-custom', 'two')\n * h[Symbol('headers map')] // Map { 'X-Custom' => 'one, two' }\n */\nexport function recordRawFetchHeaders() {\n // Prevent patching the Headers prototype multiple times.\n if (Reflect.get(Headers, kRestorePatches)) {\n return Reflect.get(Headers, kRestorePatches)\n }\n\n const {\n Headers: OriginalHeaders,\n Request: OriginalRequest,\n Response: OriginalResponse,\n } = globalThis\n const { set, append, delete: headersDeleteMethod } = Headers.prototype\n\n Object.defineProperty(Headers, kRestorePatches, {\n value: () => {\n Headers.prototype.set = set\n Headers.prototype.append = append\n Headers.prototype.delete = headersDeleteMethod\n globalThis.Headers = OriginalHeaders\n\n globalThis.Request = OriginalRequest\n globalThis.Response = OriginalResponse\n\n Object.setPrototypeOf(FetchRequest, OriginalRequest)\n Object.setPrototypeOf(FetchRequest.prototype, OriginalRequest.prototype)\n Object.setPrototypeOf(FetchResponse, OriginalResponse)\n Object.setPrototypeOf(FetchResponse.prototype, OriginalResponse.prototype)\n\n Reflect.deleteProperty(Headers, kRestorePatches)\n },\n enumerable: false,\n /**\n * @note Mark this property as configurable\n * so we can delete it using `Reflect.delete` during cleanup.\n */\n configurable: true,\n })\n\n Object.defineProperty(globalThis, 'Headers', {\n enumerable: true,\n writable: true,\n value: new Proxy(Headers, {\n construct(target, args, newTarget) {\n const headersInit = args[0] || []\n\n if (\n headersInit instanceof Headers &&\n Reflect.has(headersInit, kRawHeaders)\n ) {\n // Ensure each header tuple has exactly 2 elements (name, value).\n // Node.js 24+ may have stored tuples with extra internal arguments.\n const rawHeadersFromInit = Reflect.get(\n headersInit,\n kRawHeaders\n ) as RawHeaders\n const sanitizedHeaders = rawHeadersFromInit.map(\n (tuple): HeaderTuple => [tuple[0], tuple[1]]\n )\n const headers = Reflect.construct(\n target,\n [sanitizedHeaders],\n newTarget\n )\n ensureRawHeadersSymbol(headers, [\n /**\n * @note Spread the retrieved headers to clone them.\n * This prevents multiple Headers instances from pointing\n * at the same internal \"rawHeaders\" array.\n */\n ...sanitizedHeaders,\n ])\n return headers\n }\n\n const headers = Reflect.construct(target, args, newTarget)\n\n // Request/Response constructors will set the symbol\n // upon creating a new instance, using the raw developer\n // input as the raw headers. Skip the symbol altogether\n // in those cases because the input to Headers will be normalized.\n if (!Reflect.has(headers, kRawHeaders)) {\n const rawHeadersInit = Array.isArray(headersInit)\n ? headersInit\n : Object.entries(headersInit)\n ensureRawHeadersSymbol(headers, rawHeadersInit)\n }\n\n return headers\n },\n }),\n })\n\n Headers.prototype.set = new Proxy(Headers.prototype.set, {\n apply(target, thisArg, args: HeaderTuple) {\n // Use only the first two arguments (name, value) to record raw headers.\n // Node.js 24+ may pass additional internal arguments that should not\n // be included in the raw headers array.\n recordRawHeader(thisArg, [args[0], args[1]], 'set')\n return Reflect.apply(target, thisArg, args)\n },\n })\n\n Headers.prototype.append = new Proxy(Headers.prototype.append, {\n apply(target, thisArg, args: HeaderTuple) {\n // Use only the first two arguments (name, value) to record raw headers.\n // Node.js 24+ may pass additional internal arguments that should not\n // be included in the raw headers array.\n recordRawHeader(thisArg, [args[0], args[1]], 'append')\n return Reflect.apply(target, thisArg, args)\n },\n })\n\n Headers.prototype.delete = new Proxy(Headers.prototype.delete, {\n apply(target, thisArg, args: [string]) {\n const rawHeaders = Reflect.get(thisArg, kRawHeaders) as RawHeaders\n\n if (rawHeaders) {\n for (let index = rawHeaders.length - 1; index >= 0; index--) {\n if (rawHeaders[index][0].toLowerCase() === args[0].toLowerCase()) {\n rawHeaders.splice(index, 1)\n }\n }\n }\n\n return Reflect.apply(target, thisArg, args)\n },\n })\n\n Object.defineProperty(globalThis, 'Request', {\n enumerable: true,\n writable: true,\n value: new Proxy(Request, {\n construct(target, args, newTarget) {\n const request = Reflect.construct(target, args, newTarget)\n const inferredRawHeaders: RawHeaders = []\n\n // Infer raw headers from a `Request` instance used as init.\n if (typeof args[0] === 'object' && args[0].headers != null) {\n inferredRawHeaders.push(...inferRawHeaders(args[0].headers))\n }\n\n // Infer raw headers from the \"headers\" init argument.\n if (typeof args[1] === 'object' && args[1].headers != null) {\n inferredRawHeaders.push(...inferRawHeaders(args[1].headers))\n }\n\n if (inferredRawHeaders.length > 0) {\n ensureRawHeadersSymbol(request.headers, inferredRawHeaders)\n }\n\n return request\n },\n }),\n })\n\n Object.defineProperty(globalThis, 'Response', {\n enumerable: true,\n writable: true,\n value: new Proxy(Response, {\n construct(target, args, newTarget) {\n const response = Reflect.construct(target, args, newTarget)\n\n if (typeof args[1] === 'object' && args[1].headers != null) {\n ensureRawHeadersSymbol(\n response.headers,\n inferRawHeaders(args[1].headers)\n )\n }\n\n return response\n },\n }),\n })\n\n /**\n * Re-parent FetchRequest/FetchResponse so their `super()` calls go\n * through the proxied globalThis.Request/Response above. Without this,\n * FetchRequest extends the statically-captured (original) Request,\n * bypassing the construct proxy that records raw headers.\n */\n Object.setPrototypeOf(FetchRequest, globalThis.Request)\n Object.setPrototypeOf(FetchRequest.prototype, globalThis.Request.prototype)\n Object.setPrototypeOf(FetchResponse, globalThis.Response)\n Object.setPrototypeOf(FetchResponse.prototype, globalThis.Response.prototype)\n}\n\nexport function restoreHeadersPrototype() {\n if (!Reflect.get(Headers, kRestorePatches)) {\n return\n }\n\n Reflect.get(Headers, kRestorePatches)()\n}\n\nexport function getRawFetchHeaders(headers: Headers): RawHeaders {\n // If the raw headers recording failed for some reason,\n // use the normalized header entries instead.\n if (!Reflect.has(headers, kRawHeaders)) {\n return Array.from(headers.entries())\n }\n\n const rawHeaders = Reflect.get(headers, kRawHeaders) as RawHeaders\n return rawHeaders.length > 0 ? rawHeaders : Array.from(headers.entries())\n}\n\n/**\n * Infers the raw headers from the given `HeadersInit` provided\n * to the Request/Response constructor.\n *\n * If the `init.headers` is a Headers instance, use it directly.\n * That means the headers were created standalone and already have\n * the raw headers stored.\n * If the `init.headers` is a HeadersInit, create a new Headers\n * instance out of it.\n */\nfunction inferRawHeaders(headers: HeadersInit): RawHeaders {\n if (headers instanceof Headers) {\n return Reflect.get(headers, kRawHeaders) || []\n }\n\n return Reflect.get(new Headers(headers), kRawHeaders)\n}\n","import type { Socket } from 'node:net'\nimport { HTTPParser } from '_http_common'\n\n/**\n * @see https://github.com/nodejs/node/blob/f3adc11e37b8bfaaa026ea85c1cf22e3a0e29ae9/lib/_http_common.js#L180\n */\nexport function freeParser(parser: HTTPParser, socket?: Socket): void {\n if (parser._consumed) {\n parser.unconsume()\n }\n\n parser._headers = []\n parser._url = ''\n parser.socket = null\n parser.incoming = null\n parser.outgoing = null\n parser.maxHeaderPairs = 2000\n parser._consumed = false\n parser.onIncoming = null\n\n parser[HTTPParser.kOnHeaders] = null\n parser[HTTPParser.kOnHeadersComplete] = null\n parser[HTTPParser.kOnMessageBegin] = null\n parser[HTTPParser.kOnMessageComplete] = null\n parser[HTTPParser.kOnBody] = null\n parser[HTTPParser.kOnExecute] = null\n parser[HTTPParser.kOnTimeout] = null\n\n parser.remove()\n parser.free()\n\n if (socket) {\n /**\n * @note Unassigning the socket's parser will fail this assertion\n * if there's still some data being processed on the socket:\n * @see https://github.com/nodejs/node/blob/4e1f39b678b37017ac9baa0971e3aeecd3b67b51/lib/_http_client.js#L613\n */\n if (socket.destroyed) {\n // @ts-expect-error Node.js internals.\n socket.parser = null\n } else {\n socket.once('end', () => {\n // @ts-expect-error Node.js internals.\n socket.parser = null\n })\n }\n }\n}\n","import net from 'node:net'\nimport {\n type HeadersCallback,\n HTTPParser,\n type RequestHeadersCompleteCallback,\n type ResponseHeadersCompleteCallback,\n} from '_http_common'\nimport { STATUS_CODES, IncomingMessage, ServerResponse } from 'node:http'\nimport { Readable } from 'node:stream'\nimport { invariant } from 'outvariant'\nimport { INTERNAL_REQUEST_ID_HEADER_NAME } from '../../Interceptor'\nimport { MockSocket } from '../Socket/MockSocket'\nimport type { NormalizedSocketWriteArgs } from '../Socket/utils/normalizeSocketWriteArgs'\nimport { isPropertyAccessible } from '../../utils/isPropertyAccessible'\nimport { baseUrlFromConnectionOptions } from '../Socket/utils/baseUrlFromConnectionOptions'\nimport { createRequestId } from '../../createRequestId'\nimport { getRawFetchHeaders } from './utils/recordRawHeaders'\nimport { FetchRequest, FetchResponse } from '../../utils/fetchUtils'\nimport { setRawRequest } from '../../getRawRequest'\nimport { setRawRequestBodyStream } from '../../utils/node'\nimport { freeParser } from './utils/parserUtils'\n\ntype HttpConnectionOptions = any\n\nexport type MockHttpSocketRequestCallback = (args: {\n requestId: string\n request: Request\n socket: MockHttpSocket\n}) => void\n\nexport type MockHttpSocketResponseCallback = (args: {\n requestId: string\n request: Request\n response: Response\n isMockedResponse: boolean\n socket: MockHttpSocket\n}) => Promise\n\ninterface MockHttpSocketOptions {\n connectionOptions: HttpConnectionOptions\n createConnection: () => net.Socket\n onRequest: MockHttpSocketRequestCallback\n onResponse: MockHttpSocketResponseCallback\n}\n\nexport const kRequestId = Symbol('kRequestId')\n\nexport class MockHttpSocket extends MockSocket {\n private connectionOptions: HttpConnectionOptions\n private createConnection: () => net.Socket\n private baseUrl: URL\n\n private onRequest: MockHttpSocketRequestCallback\n private onResponse: MockHttpSocketResponseCallback\n private responseListenersPromise?: Promise\n\n private requestRawHeadersBuffer: Array = []\n private responseRawHeadersBuffer: Array = []\n private writeBuffer: Array = []\n private request?: Request\n private requestParser: HTTPParser<0>\n private requestStream?: Readable\n private shouldKeepAlive?: boolean\n\n private socketState: 'unknown' | 'mock' | 'passthrough' = 'unknown'\n private responseParser: HTTPParser<1>\n private responseStream?: Readable\n private originalSocket?: net.Socket\n\n constructor(options: MockHttpSocketOptions) {\n super({\n write: (chunk, encoding, callback) => {\n // Buffer the writes so they can be flushed in case of the original connection\n // and when reading the request body in the interceptor. If the connection has\n // been established, no need to buffer the chunks anymore, they will be forwarded.\n if (this.socketState !== 'passthrough') {\n this.writeBuffer.push([chunk, encoding, callback])\n }\n\n if (chunk) {\n /**\n * Forward any writes to the mock socket to the underlying original socket.\n * This ensures functional duplex connections, like WebSocket.\n * @see https://github.com/mswjs/interceptors/issues/682\n */\n if (this.socketState === 'passthrough') {\n this.originalSocket?.write(chunk, encoding, callback)\n }\n\n this.requestParser.execute(\n Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding)\n )\n }\n },\n read: (chunk) => {\n if (chunk !== null) {\n /**\n * @todo We need to free the parser if the connection has been\n * upgraded to a non-HTTP protocol. It won't be able to parse data\n * from that point onward anyway. No need to keep it in memory.\n */\n this.responseParser.execute(\n Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)\n )\n }\n },\n })\n\n this.connectionOptions = options.connectionOptions\n this.createConnection = options.createConnection\n this.onRequest = options.onRequest\n this.onResponse = options.onResponse\n\n this.baseUrl = baseUrlFromConnectionOptions(this.connectionOptions)\n\n // Request parser.\n this.requestParser = new HTTPParser()\n this.requestParser.initialize(HTTPParser.REQUEST, {})\n this.requestParser[HTTPParser.kOnHeaders] = this.onRequestHeaders.bind(this)\n this.requestParser[HTTPParser.kOnHeadersComplete] =\n this.onRequestStart.bind(this)\n this.requestParser[HTTPParser.kOnBody] = this.onRequestBody.bind(this)\n this.requestParser[HTTPParser.kOnMessageComplete] =\n this.onRequestEnd.bind(this)\n\n // Response parser.\n this.responseParser = new HTTPParser()\n this.responseParser.initialize(HTTPParser.RESPONSE, {})\n this.responseParser[HTTPParser.kOnHeaders] =\n this.onResponseHeaders.bind(this)\n this.responseParser[HTTPParser.kOnHeadersComplete] =\n this.onResponseStart.bind(this)\n this.responseParser[HTTPParser.kOnBody] = this.onResponseBody.bind(this)\n this.responseParser[HTTPParser.kOnMessageComplete] =\n this.onResponseEnd.bind(this)\n\n // Once the socket is finished, nothing can write to it\n // anymore. It has also flushed any buffered chunks.\n this.once('finish', () => freeParser(this.requestParser, this))\n\n if (this.baseUrl.protocol === 'https:') {\n Reflect.set(this, 'encrypted', true)\n // The server certificate is not the same as a CA\n // passed to the TLS socket connection options.\n Reflect.set(this, 'authorized', false)\n Reflect.set(this, 'getProtocol', () => 'TLSv1.3')\n Reflect.set(this, 'getSession', () => undefined)\n Reflect.set(this, 'isSessionReused', () => false)\n Reflect.set(this, 'getCipher', () => ({\n name: 'AES256-SHA',\n standardName: 'TLS_RSA_WITH_AES_256_CBC_SHA',\n version: 'TLSv1.3',\n }))\n }\n }\n\n public emit(event: string | symbol, ...args: any[]): boolean {\n const emitEvent = super.emit.bind(this, event as any, ...args)\n\n if (this.responseListenersPromise) {\n this.responseListenersPromise.finally(emitEvent)\n return this.listenerCount(event) > 0\n }\n\n return emitEvent()\n }\n\n public destroy(error?: Error | undefined): this {\n // Destroy the response parser when the socket gets destroyed.\n // Normally, we should listen to the \"close\" event but it\n // can be suppressed by using the \"emitClose: false\" option.\n freeParser(this.responseParser, this)\n\n if (error) {\n this.emit('error', error)\n }\n\n return super.destroy(error)\n }\n\n /**\n * Establish this Socket connection as-is and pipe\n * its data/events through this Socket.\n */\n public passthrough(): void {\n this.socketState = 'passthrough'\n\n if (this.destroyed) {\n return\n }\n\n const socket = this.createConnection()\n this.originalSocket = socket\n\n /**\n * @note Inherit the original socket's connection handle.\n * Without this, each push to the mock socket results in a\n * new \"connection\" listener being added (i.e. buffering pushes).\n * @see https://github.com/nodejs/node/blob/b18153598b25485ce4f54d0c5cb830a9457691ee/lib/net.js#L734\n */\n if ('_handle' in socket) {\n Object.defineProperty(this, '_handle', {\n value: socket._handle,\n enumerable: true,\n writable: true,\n })\n }\n\n // The client-facing socket can be destroyed in two ways:\n // 1. The developer destroys the socket.\n // 2. The passthrough socket \"close\" is forwarded to the socket.\n this.once('close', () => {\n socket.removeAllListeners()\n\n // If the closure didn't originate from the passthrough socket, destroy it.\n if (!socket.destroyed) {\n socket.destroy()\n }\n\n this.originalSocket = undefined\n })\n\n this.address = socket.address.bind(socket)\n\n // Flush the buffered \"socket.write()\" calls onto\n // the original socket instance (i.e. write request body).\n // Exhaust the \"requestBuffer\" in case this Socket\n // gets reused for different requests.\n let writeArgs: NormalizedSocketWriteArgs | undefined\n let headersWritten = false\n\n while ((writeArgs = this.writeBuffer.shift())) {\n if (writeArgs !== undefined) {\n if (!headersWritten) {\n const [chunk, encoding, callback] = writeArgs\n const chunkString = chunk.toString()\n const chunkBeforeRequestHeaders = chunkString.slice(\n 0,\n chunkString.indexOf('\\r\\n') + 2\n )\n const chunkAfterRequestHeaders = chunkString.slice(\n chunk.indexOf('\\r\\n\\r\\n')\n )\n const rawRequestHeaders = getRawFetchHeaders(this.request!.headers)\n const requestHeadersString = rawRequestHeaders\n // Skip the internal request ID deduplication header.\n .filter(([name]) => {\n return name.toLowerCase() !== INTERNAL_REQUEST_ID_HEADER_NAME\n })\n .map(([name, value]) => `${name}: ${value}`)\n .join('\\r\\n')\n\n // Modify the HTTP request message headers\n // to reflect any changes to the request headers\n // from the \"request\" event listener.\n const headersChunk = `${chunkBeforeRequestHeaders}${requestHeadersString}${chunkAfterRequestHeaders}`\n socket.write(headersChunk, encoding, callback)\n headersWritten = true\n continue\n }\n\n socket.write(...writeArgs)\n }\n }\n\n // Forward TLS Socket properties onto this Socket instance\n // in the case of a TLS/SSL connection.\n if (Reflect.get(socket, 'encrypted')) {\n const tlsProperties = [\n 'encrypted',\n 'authorized',\n 'getProtocol',\n 'getSession',\n 'isSessionReused',\n 'getCipher',\n ]\n\n tlsProperties.forEach((propertyName) => {\n Object.defineProperty(this, propertyName, {\n enumerable: true,\n get: () => {\n const value = Reflect.get(socket, propertyName)\n return typeof value === 'function' ? value.bind(socket) : value\n },\n })\n })\n }\n\n socket\n .on('lookup', (...args) => this.emit('lookup', ...args))\n .on('connect', () => {\n this.connecting = socket.connecting\n this.emit('connect')\n })\n .on('secureConnect', () => this.emit('secureConnect'))\n .on('secure', () => this.emit('secure'))\n .on('session', (session) => this.emit('session', session))\n .on('ready', () => this.emit('ready'))\n .on('drain', () => this.emit('drain'))\n .on('data', (chunk) => {\n // Push the original response to this socket\n // so it triggers the HTTP response parser. This unifies\n // the handling pipeline for original and mocked response.\n this.push(chunk)\n })\n .on('error', (error) => {\n Reflect.set(this, '_hadError', Reflect.get(socket, '_hadError'))\n this.emit('error', error)\n })\n .on('resume', () => this.emit('resume'))\n .on('timeout', () => this.emit('timeout'))\n .on('prefinish', () => this.emit('prefinish'))\n .on('finish', () => this.emit('finish'))\n .on('close', (hadError) => this.emit('close', hadError))\n .on('end', () => this.emit('end'))\n }\n\n /**\n * Convert the given Fetch API `Response` instance to an\n * HTTP message and push it to the socket.\n */\n public async respondWith(response: Response): Promise {\n // Ignore the mocked response if the socket has been destroyed\n // (e.g. aborted or timed out),\n if (this.destroyed) {\n return\n }\n\n // Prevent recursive calls.\n invariant(\n this.socketState !== 'mock',\n '[MockHttpSocket] Failed to respond to the \"%s %s\" request with \"%s %s\": the request has already been handled',\n this.request?.method,\n this.request?.url,\n response.status,\n response.statusText\n )\n\n // Handle \"type: error\" responses.\n if (isPropertyAccessible(response, 'type') && response.type === 'error') {\n this.errorWith(new TypeError('Network error'))\n return\n }\n\n // First, emit all the connection events\n // to emulate a successful connection.\n this.mockConnect()\n this.socketState = 'mock'\n\n // Flush the write buffer to trigger write callbacks\n // if it hasn't been flushed already (e.g. someone started reading request stream).\n this.flushWriteBuffer()\n\n // Create a `ServerResponse` instance to delegate HTTP message parsing,\n // Transfer-Encoding, and other things to Node.js internals.\n const serverResponse = new ServerResponse(new IncomingMessage(this))\n\n /**\n * Assign a mock socket instance to the server response to\n * spy on the response chunk writes. Push the transformed response chunks\n * to this `MockHttpSocket` instance to trigger the \"data\" event.\n * @note Providing the same `MockSocket` instance when creating `ServerResponse`\n * does not have the same effect.\n * @see https://github.com/nodejs/node/blob/10099bb3f7fd97bb9dd9667188426866b3098e07/test/parallel/test-http-server-response-standalone.js#L32\n */\n serverResponse.assignSocket(\n new MockSocket({\n write: (chunk, encoding, callback) => {\n this.push(chunk, encoding)\n callback?.()\n },\n read() {},\n })\n )\n\n /**\n * @note Remove the `Connection` and `Date` response headers\n * injected by `ServerResponse` by default. Those are required\n * from the server but the interceptor is NOT technically a server.\n * It's confusing to add response headers that the developer didn't\n * specify themselves. They can always add these if they wish.\n * @see https://www.rfc-editor.org/rfc/rfc9110#field.date\n * @see https://www.rfc-editor.org/rfc/rfc9110#field.connection\n */\n serverResponse.removeHeader('connection')\n serverResponse.removeHeader('date')\n\n const rawResponseHeaders = getRawFetchHeaders(response.headers)\n\n /**\n * @note Call `.writeHead` in order to set the raw response headers\n * in the same case as they were provided by the developer. Using\n * `.setHeader()`/`.appendHeader()` normalizes header names.\n */\n serverResponse.writeHead(\n response.status,\n response.statusText || STATUS_CODES[response.status],\n rawResponseHeaders\n )\n\n // If the developer destroy the socket, gracefully destroy the response.\n this.once('error', () => {\n serverResponse.destroy()\n })\n\n if (response.body) {\n try {\n const reader = response.body.getReader()\n\n while (true) {\n const { done, value } = await reader.read()\n\n if (done) {\n serverResponse.end()\n break\n }\n\n serverResponse.write(value)\n }\n } catch (error) {\n if (error instanceof Error) {\n serverResponse.destroy()\n /**\n * @note Destroy the request socket gracefully.\n * Response stream errors do NOT produce request errors.\n */\n this.destroy()\n return\n }\n\n serverResponse.destroy()\n throw error\n }\n } else {\n serverResponse.end()\n }\n\n // Close the socket if the connection wasn't marked as keep-alive.\n if (!this.shouldKeepAlive) {\n this.emit('readable')\n\n /**\n * @todo @fixme This is likely a hack.\n * Since we push null to the socket, it never propagates to the\n * parser, and the parser never calls \"onResponseEnd\" to close\n * the response stream. We are closing the stream here manually\n * but that shouldn't be the case.\n */\n this.responseStream?.push(null)\n this.push(null)\n }\n }\n\n /**\n * Close this socket connection with the given error.\n */\n public errorWith(error?: Error): void {\n this.destroy(error)\n }\n\n private mockConnect(): void {\n // Calling this method immediately puts the socket\n // into the connected state.\n this.connecting = false\n\n const isIPv6 =\n net.isIPv6(this.connectionOptions.hostname) ||\n this.connectionOptions.family === 6\n const addressInfo = {\n address: isIPv6 ? '::1' : '127.0.0.1',\n family: isIPv6 ? 'IPv6' : 'IPv4',\n port: this.connectionOptions.port,\n }\n // Return fake address information for the socket.\n this.address = () => addressInfo\n this.emit(\n 'lookup',\n null,\n addressInfo.address,\n addressInfo.family === 'IPv6' ? 6 : 4,\n this.connectionOptions.host\n )\n this.emit('connect')\n this.emit('ready')\n\n if (this.baseUrl.protocol === 'https:') {\n this.emit('secure')\n this.emit('secureConnect')\n\n // A single TLS connection is represented by two \"session\" events.\n this.emit(\n 'session',\n this.connectionOptions.session ||\n Buffer.from('mock-session-renegotiate')\n )\n this.emit('session', Buffer.from('mock-session-resume'))\n }\n }\n\n private flushWriteBuffer(): void {\n for (const writeCall of this.writeBuffer) {\n if (typeof writeCall[2] === 'function') {\n writeCall[2]()\n /**\n * @note Remove the callback from the write call\n * so it doesn't get called twice on passthrough\n * if `request.end()` was called within `request.write()`.\n * @see https://github.com/mswjs/interceptors/issues/684\n */\n writeCall[2] = undefined\n }\n }\n }\n\n /**\n * This callback might be called when the request is \"slow\":\n * - Request headers were fragmented across multiple TCP packages;\n * - Request headers were too large to be processed in a single run\n * (e.g. more than 30 request headers).\n * @note This is called before request start.\n */\n private onRequestHeaders: HeadersCallback = (rawHeaders) => {\n this.requestRawHeadersBuffer.push(...rawHeaders)\n }\n\n private onRequestStart: RequestHeadersCompleteCallback = (\n versionMajor,\n versionMinor,\n rawHeaders,\n _,\n path,\n __,\n ___,\n ____,\n shouldKeepAlive\n ) => {\n this.shouldKeepAlive = shouldKeepAlive\n\n const url = new URL(path || '', this.baseUrl)\n const method = this.connectionOptions.method?.toUpperCase() || 'GET'\n const headers = FetchResponse.parseRawHeaders([\n ...this.requestRawHeadersBuffer,\n ...(rawHeaders || []),\n ])\n this.requestRawHeadersBuffer.length = 0\n\n const canHaveBody = method !== 'GET' && method !== 'HEAD'\n\n // Translate the basic authorization in the URL to the request header.\n // Constructing a Request instance with a URL containing auth is no-op.\n if (url.username || url.password) {\n if (!headers.has('authorization')) {\n headers.set('authorization', `Basic ${url.username}:${url.password}`)\n }\n url.username = ''\n url.password = ''\n }\n\n // Create a new stream for each request.\n // If this Socket is reused for multiple requests,\n // this ensures that each request gets its own stream.\n // One Socket instance can only handle one request at a time.\n this.requestStream = new Readable({\n /**\n * @note Provide the `read()` method so a `Readable` could be\n * used as the actual request body (the stream calls \"read()\").\n * We control the queue in the onRequestBody/End functions.\n */\n read: () => {\n // If the user attempts to read the request body,\n // flush the write buffer to trigger the callbacks.\n // This way, if the request stream ends in the write callback,\n // it will indeed end correctly.\n this.flushWriteBuffer()\n },\n })\n\n const requestId = createRequestId()\n this.request = new FetchRequest(url, {\n method,\n headers,\n credentials: 'same-origin',\n // @ts-expect-error Undocumented Fetch property.\n duplex: canHaveBody ? 'half' : undefined,\n body: canHaveBody ? (Readable.toWeb(this.requestStream!) as any) : null,\n })\n\n Reflect.set(this.request, kRequestId, requestId)\n\n // Set the raw `http.ClientRequest` instance on the request instance.\n // This is useful for cases like getting the raw headers of the request.\n setRawRequest(this.request, Reflect.get(this, '_httpMessage'))\n\n // Create a copy of the request body stream and store it on the request.\n // This is only needed for the consumers who wish to read the request body stream\n // of requests that cannot have a body per Fetch API specification (i.e. GET, HEAD).\n setRawRequestBodyStream(this.request, this.requestStream)\n\n // Skip handling the request that's already being handled\n // by another (parent) interceptor. For example, XMLHttpRequest\n // is often implemented via ClientRequest in Node.js (e.g. JSDOM).\n // In that case, XHR interceptor will bubble down to the ClientRequest\n // interceptor. No need to try to handle that request again.\n /**\n * @fixme Stop relying on the \"X-Request-Id\" request header\n * to figure out if one interceptor has been invoked within another.\n * @see https://github.com/mswjs/interceptors/issues/378\n */\n if (this.request.headers.has(INTERNAL_REQUEST_ID_HEADER_NAME)) {\n this.passthrough()\n return\n }\n\n this.onRequest({\n requestId,\n request: this.request,\n socket: this,\n })\n }\n\n private onRequestBody(chunk: Buffer): void {\n invariant(\n this.requestStream,\n 'Failed to write to a request stream: stream does not exist'\n )\n\n this.requestStream.push(chunk)\n }\n\n private onRequestEnd(): void {\n // Request end can be called for requests without body.\n if (this.requestStream) {\n this.requestStream.push(null)\n }\n }\n\n /**\n * This callback might be called when the response is \"slow\":\n * - Response headers were fragmented across multiple TCP packages;\n * - Response headers were too large to be processed in a single run\n * (e.g. more than 30 response headers).\n * @note This is called before response start.\n */\n private onResponseHeaders: HeadersCallback = (rawHeaders) => {\n this.responseRawHeadersBuffer.push(...rawHeaders)\n }\n\n private onResponseStart: ResponseHeadersCompleteCallback = (\n versionMajor,\n versionMinor,\n rawHeaders,\n method,\n url,\n status,\n statusText\n ) => {\n const headers = FetchResponse.parseRawHeaders([\n ...this.responseRawHeadersBuffer,\n ...(rawHeaders || []),\n ])\n this.responseRawHeadersBuffer.length = 0\n\n const response = new FetchResponse(\n /**\n * @note The Fetch API response instance exposed to the consumer\n * is created over the response stream of the HTTP parser. It is NOT\n * related to the Socket instance. This way, you can read response body\n * in response listener while the Socket instance delays the emission\n * of \"end\" and other events until those response listeners are finished.\n */\n FetchResponse.isResponseWithBody(status)\n ? (Readable.toWeb(\n (this.responseStream = new Readable({ read() {} }))\n ) as any)\n : null,\n {\n url,\n status,\n statusText,\n headers,\n }\n )\n\n invariant(\n this.request,\n 'Failed to handle a response: request does not exist'\n )\n\n FetchResponse.setUrl(this.request.url, response)\n\n /**\n * @fixme Stop relying on the \"X-Request-Id\" request header\n * to figure out if one interceptor has been invoked within another.\n * @see https://github.com/mswjs/interceptors/issues/378\n */\n if (this.request.headers.has(INTERNAL_REQUEST_ID_HEADER_NAME)) {\n return\n }\n\n this.responseListenersPromise = this.onResponse({\n response,\n isMockedResponse: this.socketState === 'mock',\n requestId: Reflect.get(this.request, kRequestId),\n request: this.request,\n socket: this,\n })\n }\n\n private onResponseBody(chunk: Buffer) {\n invariant(\n this.responseStream,\n 'Failed to write to a response stream: stream does not exist'\n )\n\n this.responseStream.push(chunk)\n }\n\n private onResponseEnd(): void {\n // Response end can be called for responses without body.\n if (this.responseStream) {\n this.responseStream.push(null)\n }\n }\n}\n","/**\n * Here's how requests are handled in Node.js:\n *\n * 1. http.ClientRequest instance calls `agent.addRequest(request, options, cb)`.\n * 2. Agent creates a new socket: `agent.createSocket(options, cb)`.\n * 3. Agent creates a new connection: `agent.createConnection(options, cb)`.\n */\nimport net from 'node:net'\nimport http from 'node:http'\nimport https from 'node:https'\nimport {\n MockHttpSocket,\n type MockHttpSocketRequestCallback,\n type MockHttpSocketResponseCallback,\n} from './MockHttpSocket'\n\ndeclare module 'node:http' {\n interface Agent {\n options?: http.AgentOptions\n createConnection(options: any, callback: any): net.Socket\n }\n}\n\ninterface MockAgentOptions {\n customAgent?: http.RequestOptions['agent']\n onRequest: MockHttpSocketRequestCallback\n onResponse: MockHttpSocketResponseCallback\n}\n\nexport class MockAgent extends http.Agent {\n private customAgent?: http.RequestOptions['agent']\n private onRequest: MockHttpSocketRequestCallback\n private onResponse: MockHttpSocketResponseCallback\n\n constructor(options: MockAgentOptions) {\n super()\n this.customAgent = options.customAgent\n this.onRequest = options.onRequest\n this.onResponse = options.onResponse\n }\n\n public createConnection(options: any, callback: any): net.Socket {\n const createConnection =\n this.customAgent instanceof http.Agent\n ? this.customAgent.createConnection\n : super.createConnection\n\n const createConnectionOptions =\n this.customAgent instanceof http.Agent\n ? {\n ...options,\n ...this.customAgent.options,\n }\n : options\n\n const socket = new MockHttpSocket({\n connectionOptions: options,\n createConnection: createConnection.bind(\n this.customAgent || this,\n createConnectionOptions,\n callback\n ),\n onRequest: this.onRequest.bind(this),\n onResponse: this.onResponse.bind(this),\n })\n\n return socket\n }\n}\n\nexport class MockHttpsAgent extends https.Agent {\n private customAgent?: https.RequestOptions['agent']\n private onRequest: MockHttpSocketRequestCallback\n private onResponse: MockHttpSocketResponseCallback\n\n constructor(options: MockAgentOptions) {\n super()\n this.customAgent = options.customAgent\n this.onRequest = options.onRequest\n this.onResponse = options.onResponse\n }\n\n public createConnection(options: any, callback: any): net.Socket {\n const createConnection =\n this.customAgent instanceof http.Agent\n ? this.customAgent.createConnection\n : super.createConnection\n\n const createConnectionOptions =\n this.customAgent instanceof http.Agent\n ? {\n ...options,\n ...this.customAgent.options,\n }\n : options\n\n const socket = new MockHttpSocket({\n connectionOptions: options,\n createConnection: createConnection.bind(\n this.customAgent || this,\n createConnectionOptions,\n callback\n ),\n onRequest: this.onRequest.bind(this),\n onResponse: this.onResponse.bind(this),\n })\n\n return socket\n }\n}\n","import { Agent } from 'http'\nimport { RequestOptions, Agent as HttpsAgent } from 'https'\nimport { Logger } from '@open-draft/logger'\n\nconst logger = new Logger('utils getUrlByRequestOptions')\n\n// Request instance constructed by the \"request\" library\n// has a \"self\" property that has a \"uri\" field. This is\n// reproducible by performing a \"XMLHttpRequest\" request in JSDOM.\nexport interface RequestSelf {\n uri?: URL\n}\n\nexport type ResolvedRequestOptions = RequestOptions & RequestSelf\n\nexport const DEFAULT_PATH = '/'\nconst DEFAULT_PROTOCOL = 'http:'\nconst DEFAULT_HOSTNAME = 'localhost'\nconst SSL_PORT = 443\n\nfunction getAgent(\n options: ResolvedRequestOptions\n): Agent | HttpsAgent | undefined {\n return options.agent instanceof Agent ? options.agent : undefined\n}\n\nfunction getProtocolByRequestOptions(options: ResolvedRequestOptions): string {\n if (options.protocol) {\n return options.protocol\n }\n\n const agent = getAgent(options)\n const agentProtocol = (agent as RequestOptions)?.protocol\n\n if (agentProtocol) {\n return agentProtocol\n }\n\n const port = getPortByRequestOptions(options)\n const isSecureRequest = options.cert || port === SSL_PORT\n\n return isSecureRequest ? 'https:' : options.uri?.protocol || DEFAULT_PROTOCOL\n}\n\nfunction getPortByRequestOptions(\n options: ResolvedRequestOptions\n): number | undefined {\n // Use the explicitly provided port.\n if (options.port) {\n return Number(options.port)\n }\n\n // Otherwise, try to resolve port from the agent.\n const agent = getAgent(options)\n\n if ((agent as HttpsAgent)?.options.port) {\n return Number((agent as HttpsAgent).options.port)\n }\n\n if ((agent as RequestOptions)?.defaultPort) {\n return Number((agent as RequestOptions).defaultPort)\n }\n\n // Lastly, return undefined indicating that the port\n // must inferred from the protocol. Do not infer it here.\n return undefined\n}\n\ninterface RequestAuth {\n username: string\n password: string\n}\n\nfunction getAuthByRequestOptions(\n options: ResolvedRequestOptions\n): RequestAuth | undefined {\n if (options.auth) {\n const [username, password] = options.auth.split(':')\n return { username, password }\n }\n}\n\n/**\n * Returns true if host looks like an IPv6 address without surrounding brackets\n * It assumes any host containing `:` is definitely not IPv4 and probably IPv6,\n * but note that this could include invalid IPv6 addresses as well.\n */\nfunction isRawIPv6Address(host: string): boolean {\n return host.includes(':') && !host.startsWith('[') && !host.endsWith(']')\n}\n\nfunction getHostname(options: ResolvedRequestOptions): string | undefined {\n let host = options.hostname || options.host\n\n if (host) {\n if (isRawIPv6Address(host)) {\n host = `[${host}]`\n }\n\n // Check the presence of the port, and if it's present,\n // remove it from the host, returning a hostname.\n return new URL(`http://${host}`).hostname\n }\n\n return DEFAULT_HOSTNAME\n}\n\n/**\n * Creates a `URL` instance from a given `RequestOptions` object.\n */\nexport function getUrlByRequestOptions(options: ResolvedRequestOptions): URL {\n logger.info('request options', options)\n\n if (options.uri) {\n logger.info(\n 'constructing url from explicitly provided \"options.uri\": %s',\n options.uri\n )\n return new URL(options.uri.href)\n }\n\n logger.info('figuring out url from request options...')\n\n const protocol = getProtocolByRequestOptions(options)\n logger.info('protocol', protocol)\n\n const port = getPortByRequestOptions(options)\n logger.info('port', port)\n\n const hostname = getHostname(options)\n logger.info('hostname', hostname)\n\n const path = options.path || DEFAULT_PATH\n logger.info('path', path)\n\n const credentials = getAuthByRequestOptions(options)\n logger.info('credentials', credentials)\n\n const authString = credentials\n ? `${credentials.username}:${credentials.password}@`\n : ''\n logger.info('auth string:', authString)\n\n const portString = typeof port !== 'undefined' ? `:${port}` : ''\n const url = new URL(`${protocol}//${hostname}${portString}${path}`)\n url.username = credentials?.username || ''\n url.password = credentials?.password || ''\n\n logger.info('created url:', url)\n\n return url\n}\n","import { Logger } from '@open-draft/logger'\n\nconst logger = new Logger('cloneObject')\n\nfunction isPlainObject(obj?: Record): boolean {\n logger.info('is plain object?', obj)\n\n if (obj == null || !obj.constructor?.name) {\n logger.info('given object is undefined, not a plain object...')\n return false\n }\n\n logger.info('checking the object constructor:', obj.constructor.name)\n return obj.constructor.name === 'Object'\n}\n\nexport function cloneObject>(\n obj: ObjectType\n): ObjectType {\n logger.info('cloning object:', obj)\n\n const enumerableProperties = Object.entries(obj).reduce>(\n (acc, [key, value]) => {\n logger.info('analyzing key-value pair:', key, value)\n\n // Recursively clone only plain objects, omitting class instances.\n acc[key] = isPlainObject(value) ? cloneObject(value) : value\n return acc\n },\n {}\n )\n\n return isPlainObject(obj)\n ? enumerableProperties\n : Object.assign(Object.getPrototypeOf(obj), enumerableProperties)\n}\n","import { urlToHttpOptions } from 'node:url'\nimport {\n Agent as HttpAgent,\n globalAgent as httpGlobalAgent,\n IncomingMessage,\n} from 'node:http'\nimport {\n RequestOptions,\n Agent as HttpsAgent,\n globalAgent as httpsGlobalAgent,\n} from 'node:https'\nimport {\n /**\n * @note Use the Node.js URL instead of the global URL\n * because environments like JSDOM may override the global,\n * breaking the compatibility with Node.js.\n * @see https://github.com/node-fetch/node-fetch/issues/1376#issuecomment-966435555\n */\n URL,\n Url as LegacyURL,\n parse as parseUrl,\n} from 'node:url'\nimport { Logger } from '@open-draft/logger'\nimport {\n ResolvedRequestOptions,\n getUrlByRequestOptions,\n} from '../../../utils/getUrlByRequestOptions'\nimport { cloneObject } from '../../../utils/cloneObject'\nimport { isObject } from '../../../utils/isObject'\n\nconst logger = new Logger('http normalizeClientRequestArgs')\n\nexport type HttpRequestCallback = (response: IncomingMessage) => void\n\nexport type ClientRequestArgs =\n // Request without any arguments is also possible.\n | []\n | [string | URL | LegacyURL, HttpRequestCallback?]\n | [string | URL | LegacyURL, RequestOptions, HttpRequestCallback?]\n | [RequestOptions, HttpRequestCallback?]\n\nfunction resolveRequestOptions(\n args: ClientRequestArgs,\n url: URL\n): RequestOptions {\n // Calling `fetch` provides only URL to `ClientRequest`\n // without any `RequestOptions` or callback.\n if (typeof args[1] === 'undefined' || typeof args[1] === 'function') {\n logger.info('request options not provided, deriving from the url', url)\n return urlToHttpOptions(url)\n }\n\n if (args[1]) {\n logger.info('has custom RequestOptions!', args[1])\n const requestOptionsFromUrl = urlToHttpOptions(url)\n\n logger.info('derived RequestOptions from the URL:', requestOptionsFromUrl)\n\n /**\n * Clone the request options to lock their state\n * at the moment they are provided to `ClientRequest`.\n * @see https://github.com/mswjs/interceptors/issues/86\n */\n logger.info('cloning RequestOptions...')\n const clonedRequestOptions = cloneObject(args[1])\n logger.info('successfully cloned RequestOptions!', clonedRequestOptions)\n\n return {\n ...requestOptionsFromUrl,\n ...clonedRequestOptions,\n }\n }\n\n logger.info('using an empty object as request options')\n return {} as RequestOptions\n}\n\n/**\n * Overrides the given `URL` instance with the explicit properties provided\n * on the `RequestOptions` object. The options object takes precedence,\n * and will replace URL properties like \"host\", \"path\", and \"port\", if specified.\n */\nfunction overrideUrlByRequestOptions(url: URL, options: RequestOptions): URL {\n url.host = options.host || url.host\n url.hostname = options.hostname || url.hostname\n url.port = options.port ? options.port.toString() : url.port\n\n if (options.path) {\n const parsedOptionsPath = parseUrl(options.path, false)\n url.pathname = parsedOptionsPath.pathname || ''\n url.search = parsedOptionsPath.search || ''\n }\n\n return url\n}\n\nfunction resolveCallback(\n args: ClientRequestArgs\n): HttpRequestCallback | undefined {\n return typeof args[1] === 'function' ? args[1] : args[2]\n}\n\nexport type NormalizedClientRequestArgs = [\n url: URL,\n options: ResolvedRequestOptions,\n callback?: HttpRequestCallback\n]\n\n/**\n * Normalizes parameters given to a `http.request` call\n * so it always has a `URL` and `RequestOptions`.\n */\nexport function normalizeClientRequestArgs(\n defaultProtocol: string,\n args: ClientRequestArgs\n): NormalizedClientRequestArgs {\n let url: URL\n let options: ResolvedRequestOptions\n let callback: HttpRequestCallback | undefined\n\n logger.info('arguments', args)\n logger.info('using default protocol:', defaultProtocol)\n\n // Support \"http.request()\" calls without any arguments.\n // That call results in a \"GET http://localhost\" request.\n if (args.length === 0) {\n const url = new URL('http://localhost')\n const options = resolveRequestOptions(args, url)\n return [url, options]\n }\n\n // Convert a url string into a URL instance\n // and derive request options from it.\n if (typeof args[0] === 'string') {\n logger.info('first argument is a location string:', args[0])\n\n url = new URL(args[0])\n logger.info('created a url:', url)\n\n const requestOptionsFromUrl = urlToHttpOptions(url)\n logger.info('request options from url:', requestOptionsFromUrl)\n\n options = resolveRequestOptions(args, url)\n logger.info('resolved request options:', options)\n\n callback = resolveCallback(args)\n }\n // Handle a given URL instance as-is\n // and derive request options from it.\n else if (args[0] instanceof URL) {\n url = args[0]\n logger.info('first argument is a URL:', url)\n\n // Check if the second provided argument is RequestOptions.\n // If it is, check if \"options.path\" was set and rewrite it\n // on the input URL.\n // Do this before resolving options from the URL below\n // to prevent query string from being duplicated in the path.\n if (typeof args[1] !== 'undefined' && isObject(args[1])) {\n url = overrideUrlByRequestOptions(url, args[1])\n }\n\n options = resolveRequestOptions(args, url)\n logger.info('derived request options:', options)\n\n callback = resolveCallback(args)\n }\n // Handle a legacy URL instance and re-normalize from either a RequestOptions object\n // or a WHATWG URL.\n else if ('hash' in args[0] && !('method' in args[0])) {\n const [legacyUrl] = args\n logger.info('first argument is a legacy URL:', legacyUrl)\n\n if (legacyUrl.hostname === null) {\n /**\n * We are dealing with a relative url, so use the path as an \"option\" and\n * merge in any existing options, giving priority to existing options -- i.e. a path in any\n * existing options will take precedence over the one contained in the url. This is consistent\n * with the behaviour in ClientRequest.\n * @see https://github.com/nodejs/node/blob/d84f1312915fe45fe0febe888db692c74894c382/lib/_http_client.js#L122\n */\n logger.info('given legacy URL is relative (no hostname)')\n\n return isObject(args[1])\n ? normalizeClientRequestArgs(defaultProtocol, [\n { path: legacyUrl.path, ...args[1] },\n args[2],\n ])\n : normalizeClientRequestArgs(defaultProtocol, [\n { path: legacyUrl.path },\n args[1] as HttpRequestCallback,\n ])\n }\n\n logger.info('given legacy url is absolute')\n\n // We are dealing with an absolute URL, so convert to WHATWG and try again.\n const resolvedUrl = new URL(legacyUrl.href)\n\n return args[1] === undefined\n ? normalizeClientRequestArgs(defaultProtocol, [resolvedUrl])\n : typeof args[1] === 'function'\n ? normalizeClientRequestArgs(defaultProtocol, [resolvedUrl, args[1]])\n : normalizeClientRequestArgs(defaultProtocol, [\n resolvedUrl,\n args[1],\n args[2],\n ])\n }\n // Handle a given \"RequestOptions\" object as-is\n // and derive the URL instance from it.\n else if (isObject(args[0])) {\n options = { ...(args[0] as any) }\n logger.info('first argument is RequestOptions:', options)\n\n // When handling a \"RequestOptions\" object without an explicit \"protocol\",\n // infer the protocol from the request issuing module (http/https).\n options.protocol = options.protocol || defaultProtocol\n logger.info('normalized request options:', options)\n\n url = getUrlByRequestOptions(options)\n logger.info('created a URL from RequestOptions:', url.href)\n\n callback = resolveCallback(args)\n } else {\n throw new Error(\n `Failed to construct ClientRequest with these parameters: ${args}`\n )\n }\n\n options.protocol = options.protocol || url.protocol\n options.method = options.method || 'GET'\n\n /**\n * Ensure that the default Agent is always set.\n * This prevents the protocol mismatch for requests with { agent: false },\n * where the global Agent is inferred.\n * @see https://github.com/mswjs/msw/issues/1150\n * @see https://github.com/nodejs/node/blob/418ff70b810f0e7112d48baaa72932a56cfa213b/lib/_http_client.js#L130\n * @see https://github.com/nodejs/node/blob/418ff70b810f0e7112d48baaa72932a56cfa213b/lib/_http_client.js#L157-L159\n */\n if (!options._defaultAgent) {\n logger.info(\n 'has no default agent, setting the default agent for \"%s\"',\n options.protocol\n )\n\n options._defaultAgent =\n options.protocol === 'https:' ? httpsGlobalAgent : httpGlobalAgent\n }\n\n logger.info('successfully resolved url:', url.href)\n logger.info('successfully resolved options:', options)\n logger.info('successfully resolved callback:', callback)\n\n /**\n * @note If the user-provided URL is not a valid URL in Node.js,\n * (e.g. the one provided by the JSDOM polyfills), case it to\n * string. Otherwise, this throws on Node.js incompatibility\n * (`ERR_INVALID_ARG_TYPE` on the connection listener)\n * @see https://github.com/node-fetch/node-fetch/issues/1376#issuecomment-966435555\n */\n if (!(url instanceof URL)) {\n url = (url as any).toString()\n }\n\n return [url, options, callback]\n}\n","import http from 'node:http'\nimport https from 'node:https'\nimport { Interceptor } from '../../Interceptor'\nimport type { HttpRequestEventMap } from '../../glossary'\nimport {\n kRequestId,\n MockHttpSocketRequestCallback,\n MockHttpSocketResponseCallback,\n} from './MockHttpSocket'\nimport { MockAgent, MockHttpsAgent } from './agents'\nimport { RequestController } from '../../RequestController'\nimport { emitAsync } from '../../utils/emitAsync'\nimport { normalizeClientRequestArgs } from './utils/normalizeClientRequestArgs'\nimport { handleRequest } from '../../utils/handleRequest'\nimport {\n recordRawFetchHeaders,\n restoreHeadersPrototype,\n} from './utils/recordRawHeaders'\n\nexport class ClientRequestInterceptor extends Interceptor {\n static symbol = Symbol.for('client-request-interceptor')\n\n constructor() {\n super(ClientRequestInterceptor.symbol)\n }\n\n protected setup(): void {\n const {\n ClientRequest: OriginalClientRequest,\n get: originalGet,\n request: originalRequest,\n } = http\n const { get: originalHttpsGet, request: originalHttpsRequest } = https\n\n const onRequest = this.onRequest.bind(this)\n const onResponse = this.onResponse.bind(this)\n\n // Support requests performed via the `ClientRequest` constructor directly.\n http.ClientRequest = new Proxy(http.ClientRequest, {\n construct: (target, args: Parameters) => {\n const [url, options, callback] = normalizeClientRequestArgs(\n 'http:',\n args\n )\n\n // Create a mock agent instance appropriate for the request protocol.\n const Agent = options.protocol === 'https:' ? MockHttpsAgent : MockAgent\n const mockAgent = new Agent({\n customAgent: options.agent,\n onRequest,\n onResponse,\n })\n options.agent = mockAgent\n\n return Reflect.construct(target, [url, options, callback])\n },\n })\n\n http.request = new Proxy(http.request, {\n apply: (target, thisArg, args: Parameters) => {\n const [url, options, callback] = normalizeClientRequestArgs(\n 'http:',\n args\n )\n const mockAgent = new MockAgent({\n customAgent: options.agent,\n onRequest,\n onResponse,\n })\n options.agent = mockAgent\n\n return Reflect.apply(target, thisArg, [url, options, callback])\n },\n })\n\n http.get = new Proxy(http.get, {\n apply: (target, thisArg, args: Parameters) => {\n const [url, options, callback] = normalizeClientRequestArgs(\n 'http:',\n args\n )\n\n const mockAgent = new MockAgent({\n customAgent: options.agent,\n onRequest,\n onResponse,\n })\n options.agent = mockAgent\n\n return Reflect.apply(target, thisArg, [url, options, callback])\n },\n })\n\n //\n // HTTPS.\n //\n\n https.request = new Proxy(https.request, {\n apply: (target, thisArg, args: Parameters) => {\n const [url, options, callback] = normalizeClientRequestArgs(\n 'https:',\n args\n )\n\n const mockAgent = new MockHttpsAgent({\n customAgent: options.agent,\n onRequest,\n onResponse,\n })\n options.agent = mockAgent\n\n return Reflect.apply(target, thisArg, [url, options, callback])\n },\n })\n\n https.get = new Proxy(https.get, {\n apply: (target, thisArg, args: Parameters) => {\n const [url, options, callback] = normalizeClientRequestArgs(\n 'https:',\n args\n )\n\n const mockAgent = new MockHttpsAgent({\n customAgent: options.agent,\n onRequest,\n onResponse,\n })\n options.agent = mockAgent\n\n return Reflect.apply(target, thisArg, [url, options, callback])\n },\n })\n\n // Spy on `Header.prototype.set` and `Header.prototype.append` calls\n // and record the raw header names provided. This is to support\n // `IncomingMessage.prototype.rawHeaders`.\n recordRawFetchHeaders()\n\n this.subscriptions.push(() => {\n http.ClientRequest = OriginalClientRequest\n\n http.get = originalGet\n http.request = originalRequest\n\n https.get = originalHttpsGet\n https.request = originalHttpsRequest\n\n restoreHeadersPrototype()\n })\n }\n\n private onRequest: MockHttpSocketRequestCallback = async ({\n request,\n socket,\n }) => {\n const controller = new RequestController(request, {\n passthrough() {\n socket.passthrough()\n },\n async respondWith(response) {\n await socket.respondWith(response)\n },\n errorWith(reason) {\n if (reason instanceof Error) {\n socket.errorWith(reason)\n }\n },\n })\n\n await handleRequest({\n request,\n requestId: Reflect.get(request, kRequestId),\n controller,\n emitter: this.emitter,\n })\n }\n\n public onResponse: MockHttpSocketResponseCallback = async ({\n requestId,\n request,\n response,\n isMockedResponse,\n }) => {\n // Return the promise to when all the response event listeners\n // are finished.\n return emitAsync(this.emitter, 'response', {\n requestId,\n request,\n response,\n isMockedResponse,\n })\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAgBA,SAAgB,yBACd,MAC2B;CAC3B,MAAMA,aAAwC;EAAC,KAAK;EAAI;EAAW;EAAU;AAE7E,KAAI,OAAO,KAAK,OAAO,SACrB,YAAW,KAAK,KAAK;UACZ,OAAO,KAAK,OAAO,WAC5B,YAAW,KAAK,KAAK;AAGvB,KAAI,OAAO,KAAK,OAAO,WACrB,YAAW,KAAK,KAAK;AAGvB,QAAO;;;;;ACdT,IAAa,aAAb,cAAgCC,iBAAI,OAAO;CAGz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s b/node_modules/@mswjs/interceptors/lib/node/ClientRequest-DGhBX21V.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1628fe71f530b204bf13a13d1f16833bd8104d5a --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/ClientRequest-DGhBX21V.mjs @@ -0,0 +1,1049 @@ +import { a as RequestController, c as Interceptor, i as createRequestId, n as FetchResponse, s as INTERNAL_REQUEST_ID_HEADER_NAME, t as FetchRequest } from "./fetchUtils-BKJ1XmiO.mjs"; +import { n as setRawRequest } from "./getRawRequest-C2-1urzA.mjs"; +import { a as isPropertyAccessible, i as emitAsync, r as isObject, t as handleRequest } from "./handleRequest-FIQv5pwH.mjs"; +import { n as setRawRequestBodyStream } from "./node-lsdNwZEW.mjs"; +import { Logger } from "@open-draft/logger"; +import { invariant } from "outvariant"; +import http, { IncomingMessage, STATUS_CODES, ServerResponse, globalAgent } from "node:http"; +import https, { globalAgent as globalAgent$1 } from "node:https"; +import net from "node:net"; +import { HTTPParser } from "_http_common"; +import { Readable } from "node:stream"; +import { URL as URL$1, parse, urlToHttpOptions } from "node:url"; +import { Agent } from "http"; + +//#region src/interceptors/Socket/utils/normalizeSocketWriteArgs.ts +/** +* Normalizes the arguments provided to the `Writable.prototype.write()` +* and `Writable.prototype.end()`. +*/ +function normalizeSocketWriteArgs(args) { + const normalized = [ + args[0], + void 0, + void 0 + ]; + if (typeof args[1] === "string") normalized[1] = args[1]; + else if (typeof args[1] === "function") normalized[2] = args[1]; + if (typeof args[2] === "function") normalized[2] = args[2]; + return normalized; +} + +//#endregion +//#region src/interceptors/Socket/MockSocket.ts +var MockSocket = class extends net.Socket { + constructor(options) { + super(); + this.options = options; + this.connecting = false; + this.connect(); + this._final = (callback) => { + callback(null); + }; + } + connect() { + this.connecting = true; + return this; + } + write(...args) { + const [chunk, encoding, callback] = normalizeSocketWriteArgs(args); + this.options.write(chunk, encoding, callback); + return true; + } + end(...args) { + const [chunk, encoding, callback] = normalizeSocketWriteArgs(args); + this.options.write(chunk, encoding, callback); + return super.end.apply(this, args); + } + push(chunk, encoding) { + this.options.read(chunk, encoding); + return super.push(chunk, encoding); + } +}; + +//#endregion +//#region src/interceptors/Socket/utils/baseUrlFromConnectionOptions.ts +function baseUrlFromConnectionOptions(options) { + if ("href" in options) return new URL(options.href); + const protocol = options.port === 443 ? "https:" : "http:"; + const host = options.host; + const url = new URL(`${protocol}//${host}`); + if (options.port) url.port = options.port.toString(); + if (options.path) url.pathname = options.path; + if (options.auth) { + const [username, password] = options.auth.split(":"); + url.username = username; + url.password = password; + } + return url; +} + +//#endregion +//#region src/interceptors/ClientRequest/utils/recordRawHeaders.ts +const kRawHeaders = Symbol("kRawHeaders"); +const kRestorePatches = Symbol("kRestorePatches"); +function recordRawHeader(headers, args, behavior) { + ensureRawHeadersSymbol(headers, []); + const rawHeaders = Reflect.get(headers, kRawHeaders); + if (behavior === "set") { + for (let index = rawHeaders.length - 1; index >= 0; index--) if (rawHeaders[index][0].toLowerCase() === args[0].toLowerCase()) rawHeaders.splice(index, 1); + } + rawHeaders.push(args); +} +/** +* Define the raw headers symbol on the given `Headers` instance. +* If the symbol already exists, this function does nothing. +*/ +function ensureRawHeadersSymbol(headers, rawHeaders) { + if (Reflect.has(headers, kRawHeaders)) return; + defineRawHeadersSymbol(headers, rawHeaders); +} +/** +* Define the raw headers symbol on the given `Headers` instance. +* If the symbol already exists, it gets overridden. +*/ +function defineRawHeadersSymbol(headers, rawHeaders) { + Object.defineProperty(headers, kRawHeaders, { + value: rawHeaders, + enumerable: false, + configurable: true + }); +} +/** +* Patch the global `Headers` class to store raw headers. +* This is for compatibility with `IncomingMessage.prototype.rawHeaders`. +* +* @note Node.js has their own raw headers symbol but it +* only records the first header name in case of multi-value headers. +* Any other headers are normalized before comparing. This makes it +* incompatible with the `rawHeaders` format. +* +* let h = new Headers() +* h.append('X-Custom', 'one') +* h.append('x-custom', 'two') +* h[Symbol('headers map')] // Map { 'X-Custom' => 'one, two' } +*/ +function recordRawFetchHeaders() { + if (Reflect.get(Headers, kRestorePatches)) return Reflect.get(Headers, kRestorePatches); + const { Headers: OriginalHeaders, Request: OriginalRequest, Response: OriginalResponse } = globalThis; + const { set, append, delete: headersDeleteMethod } = Headers.prototype; + Object.defineProperty(Headers, kRestorePatches, { + value: () => { + Headers.prototype.set = set; + Headers.prototype.append = append; + Headers.prototype.delete = headersDeleteMethod; + globalThis.Headers = OriginalHeaders; + globalThis.Request = OriginalRequest; + globalThis.Response = OriginalResponse; + Object.setPrototypeOf(FetchRequest, OriginalRequest); + Object.setPrototypeOf(FetchRequest.prototype, OriginalRequest.prototype); + Object.setPrototypeOf(FetchResponse, OriginalResponse); + Object.setPrototypeOf(FetchResponse.prototype, OriginalResponse.prototype); + Reflect.deleteProperty(Headers, kRestorePatches); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(globalThis, "Headers", { + enumerable: true, + writable: true, + value: new Proxy(Headers, { construct(target, args, newTarget) { + const headersInit = args[0] || []; + if (headersInit instanceof Headers && Reflect.has(headersInit, kRawHeaders)) { + const sanitizedHeaders = Reflect.get(headersInit, kRawHeaders).map((tuple) => [tuple[0], tuple[1]]); + const headers$1 = Reflect.construct(target, [sanitizedHeaders], newTarget); + ensureRawHeadersSymbol(headers$1, [...sanitizedHeaders]); + return headers$1; + } + const headers = Reflect.construct(target, args, newTarget); + if (!Reflect.has(headers, kRawHeaders)) ensureRawHeadersSymbol(headers, Array.isArray(headersInit) ? headersInit : Object.entries(headersInit)); + return headers; + } }) + }); + Headers.prototype.set = new Proxy(Headers.prototype.set, { apply(target, thisArg, args) { + recordRawHeader(thisArg, [args[0], args[1]], "set"); + return Reflect.apply(target, thisArg, args); + } }); + Headers.prototype.append = new Proxy(Headers.prototype.append, { apply(target, thisArg, args) { + recordRawHeader(thisArg, [args[0], args[1]], "append"); + return Reflect.apply(target, thisArg, args); + } }); + Headers.prototype.delete = new Proxy(Headers.prototype.delete, { apply(target, thisArg, args) { + const rawHeaders = Reflect.get(thisArg, kRawHeaders); + if (rawHeaders) { + for (let index = rawHeaders.length - 1; index >= 0; index--) if (rawHeaders[index][0].toLowerCase() === args[0].toLowerCase()) rawHeaders.splice(index, 1); + } + return Reflect.apply(target, thisArg, args); + } }); + Object.defineProperty(globalThis, "Request", { + enumerable: true, + writable: true, + value: new Proxy(Request, { construct(target, args, newTarget) { + const request = Reflect.construct(target, args, newTarget); + const inferredRawHeaders = []; + if (typeof args[0] === "object" && args[0].headers != null) inferredRawHeaders.push(...inferRawHeaders(args[0].headers)); + if (typeof args[1] === "object" && args[1].headers != null) inferredRawHeaders.push(...inferRawHeaders(args[1].headers)); + if (inferredRawHeaders.length > 0) ensureRawHeadersSymbol(request.headers, inferredRawHeaders); + return request; + } }) + }); + Object.defineProperty(globalThis, "Response", { + enumerable: true, + writable: true, + value: new Proxy(Response, { construct(target, args, newTarget) { + const response = Reflect.construct(target, args, newTarget); + if (typeof args[1] === "object" && args[1].headers != null) ensureRawHeadersSymbol(response.headers, inferRawHeaders(args[1].headers)); + return response; + } }) + }); + /** + * Re-parent FetchRequest/FetchResponse so their `super()` calls go + * through the proxied globalThis.Request/Response above. Without this, + * FetchRequest extends the statically-captured (original) Request, + * bypassing the construct proxy that records raw headers. + */ + Object.setPrototypeOf(FetchRequest, globalThis.Request); + Object.setPrototypeOf(FetchRequest.prototype, globalThis.Request.prototype); + Object.setPrototypeOf(FetchResponse, globalThis.Response); + Object.setPrototypeOf(FetchResponse.prototype, globalThis.Response.prototype); +} +function restoreHeadersPrototype() { + if (!Reflect.get(Headers, kRestorePatches)) return; + Reflect.get(Headers, kRestorePatches)(); +} +function getRawFetchHeaders(headers) { + if (!Reflect.has(headers, kRawHeaders)) return Array.from(headers.entries()); + const rawHeaders = Reflect.get(headers, kRawHeaders); + return rawHeaders.length > 0 ? rawHeaders : Array.from(headers.entries()); +} +/** +* Infers the raw headers from the given `HeadersInit` provided +* to the Request/Response constructor. +* +* If the `init.headers` is a Headers instance, use it directly. +* That means the headers were created standalone and already have +* the raw headers stored. +* If the `init.headers` is a HeadersInit, create a new Headers +* instance out of it. +*/ +function inferRawHeaders(headers) { + if (headers instanceof Headers) return Reflect.get(headers, kRawHeaders) || []; + return Reflect.get(new Headers(headers), kRawHeaders); +} + +//#endregion +//#region src/interceptors/ClientRequest/utils/parserUtils.ts +/** +* @see https://github.com/nodejs/node/blob/f3adc11e37b8bfaaa026ea85c1cf22e3a0e29ae9/lib/_http_common.js#L180 +*/ +function freeParser(parser, socket) { + if (parser._consumed) parser.unconsume(); + parser._headers = []; + parser._url = ""; + parser.socket = null; + parser.incoming = null; + parser.outgoing = null; + parser.maxHeaderPairs = 2e3; + parser._consumed = false; + parser.onIncoming = null; + parser[HTTPParser.kOnHeaders] = null; + parser[HTTPParser.kOnHeadersComplete] = null; + parser[HTTPParser.kOnMessageBegin] = null; + parser[HTTPParser.kOnMessageComplete] = null; + parser[HTTPParser.kOnBody] = null; + parser[HTTPParser.kOnExecute] = null; + parser[HTTPParser.kOnTimeout] = null; + parser.remove(); + parser.free(); + if (socket) + /** + * @note Unassigning the socket's parser will fail this assertion + * if there's still some data being processed on the socket: + * @see https://github.com/nodejs/node/blob/4e1f39b678b37017ac9baa0971e3aeecd3b67b51/lib/_http_client.js#L613 + */ + if (socket.destroyed) socket.parser = null; + else socket.once("end", () => { + socket.parser = null; + }); +} + +//#endregion +//#region src/interceptors/ClientRequest/MockHttpSocket.ts +const kRequestId = Symbol("kRequestId"); +var MockHttpSocket = class extends MockSocket { + constructor(options) { + super({ + write: (chunk, encoding, callback) => { + if (this.socketState !== "passthrough") this.writeBuffer.push([ + chunk, + encoding, + callback + ]); + if (chunk) { + /** + * Forward any writes to the mock socket to the underlying original socket. + * This ensures functional duplex connections, like WebSocket. + * @see https://github.com/mswjs/interceptors/issues/682 + */ + if (this.socketState === "passthrough") this.originalSocket?.write(chunk, encoding, callback); + this.requestParser.execute(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding)); + } + }, + read: (chunk) => { + if (chunk !== null) + /** + * @todo We need to free the parser if the connection has been + * upgraded to a non-HTTP protocol. It won't be able to parse data + * from that point onward anyway. No need to keep it in memory. + */ + this.responseParser.execute(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); + } + }); + this.requestRawHeadersBuffer = []; + this.responseRawHeadersBuffer = []; + this.writeBuffer = []; + this.socketState = "unknown"; + this.onRequestHeaders = (rawHeaders) => { + this.requestRawHeadersBuffer.push(...rawHeaders); + }; + this.onRequestStart = (versionMajor, versionMinor, rawHeaders, _, path, __, ___, ____, shouldKeepAlive) => { + this.shouldKeepAlive = shouldKeepAlive; + const url = new URL(path || "", this.baseUrl); + const method = this.connectionOptions.method?.toUpperCase() || "GET"; + const headers = FetchResponse.parseRawHeaders([...this.requestRawHeadersBuffer, ...rawHeaders || []]); + this.requestRawHeadersBuffer.length = 0; + const canHaveBody = method !== "GET" && method !== "HEAD"; + if (url.username || url.password) { + if (!headers.has("authorization")) headers.set("authorization", `Basic ${url.username}:${url.password}`); + url.username = ""; + url.password = ""; + } + this.requestStream = new Readable({ read: () => { + this.flushWriteBuffer(); + } }); + const requestId = createRequestId(); + this.request = new FetchRequest(url, { + method, + headers, + credentials: "same-origin", + duplex: canHaveBody ? "half" : void 0, + body: canHaveBody ? Readable.toWeb(this.requestStream) : null + }); + Reflect.set(this.request, kRequestId, requestId); + setRawRequest(this.request, Reflect.get(this, "_httpMessage")); + setRawRequestBodyStream(this.request, this.requestStream); + /** + * @fixme Stop relying on the "X-Request-Id" request header + * to figure out if one interceptor has been invoked within another. + * @see https://github.com/mswjs/interceptors/issues/378 + */ + if (this.request.headers.has(INTERNAL_REQUEST_ID_HEADER_NAME)) { + this.passthrough(); + return; + } + this.onRequest({ + requestId, + request: this.request, + socket: this + }); + }; + this.onResponseHeaders = (rawHeaders) => { + this.responseRawHeadersBuffer.push(...rawHeaders); + }; + this.onResponseStart = (versionMajor, versionMinor, rawHeaders, method, url, status, statusText) => { + const headers = FetchResponse.parseRawHeaders([...this.responseRawHeadersBuffer, ...rawHeaders || []]); + this.responseRawHeadersBuffer.length = 0; + const response = new FetchResponse( + /** + * @note The Fetch API response instance exposed to the consumer + * is created over the response stream of the HTTP parser. It is NOT + * related to the Socket instance. This way, you can read response body + * in response listener while the Socket instance delays the emission + * of "end" and other events until those response listeners are finished. + */ + FetchResponse.isResponseWithBody(status) ? Readable.toWeb(this.responseStream = new Readable({ read() {} })) : null, + { + url, + status, + statusText, + headers + } + ); + invariant(this.request, "Failed to handle a response: request does not exist"); + FetchResponse.setUrl(this.request.url, response); + /** + * @fixme Stop relying on the "X-Request-Id" request header + * to figure out if one interceptor has been invoked within another. + * @see https://github.com/mswjs/interceptors/issues/378 + */ + if (this.request.headers.has(INTERNAL_REQUEST_ID_HEADER_NAME)) return; + this.responseListenersPromise = this.onResponse({ + response, + isMockedResponse: this.socketState === "mock", + requestId: Reflect.get(this.request, kRequestId), + request: this.request, + socket: this + }); + }; + this.connectionOptions = options.connectionOptions; + this.createConnection = options.createConnection; + this.onRequest = options.onRequest; + this.onResponse = options.onResponse; + this.baseUrl = baseUrlFromConnectionOptions(this.connectionOptions); + this.requestParser = new HTTPParser(); + this.requestParser.initialize(HTTPParser.REQUEST, {}); + this.requestParser[HTTPParser.kOnHeaders] = this.onRequestHeaders.bind(this); + this.requestParser[HTTPParser.kOnHeadersComplete] = this.onRequestStart.bind(this); + this.requestParser[HTTPParser.kOnBody] = this.onRequestBody.bind(this); + this.requestParser[HTTPParser.kOnMessageComplete] = this.onRequestEnd.bind(this); + this.responseParser = new HTTPParser(); + this.responseParser.initialize(HTTPParser.RESPONSE, {}); + this.responseParser[HTTPParser.kOnHeaders] = this.onResponseHeaders.bind(this); + this.responseParser[HTTPParser.kOnHeadersComplete] = this.onResponseStart.bind(this); + this.responseParser[HTTPParser.kOnBody] = this.onResponseBody.bind(this); + this.responseParser[HTTPParser.kOnMessageComplete] = this.onResponseEnd.bind(this); + this.once("finish", () => freeParser(this.requestParser, this)); + if (this.baseUrl.protocol === "https:") { + Reflect.set(this, "encrypted", true); + Reflect.set(this, "authorized", false); + Reflect.set(this, "getProtocol", () => "TLSv1.3"); + Reflect.set(this, "getSession", () => void 0); + Reflect.set(this, "isSessionReused", () => false); + Reflect.set(this, "getCipher", () => ({ + name: "AES256-SHA", + standardName: "TLS_RSA_WITH_AES_256_CBC_SHA", + version: "TLSv1.3" + })); + } + } + emit(event, ...args) { + const emitEvent = super.emit.bind(this, event, ...args); + if (this.responseListenersPromise) { + this.responseListenersPromise.finally(emitEvent); + return this.listenerCount(event) > 0; + } + return emitEvent(); + } + destroy(error) { + freeParser(this.responseParser, this); + if (error) this.emit("error", error); + return super.destroy(error); + } + /** + * Establish this Socket connection as-is and pipe + * its data/events through this Socket. + */ + passthrough() { + this.socketState = "passthrough"; + if (this.destroyed) return; + const socket = this.createConnection(); + this.originalSocket = socket; + /** + * @note Inherit the original socket's connection handle. + * Without this, each push to the mock socket results in a + * new "connection" listener being added (i.e. buffering pushes). + * @see https://github.com/nodejs/node/blob/b18153598b25485ce4f54d0c5cb830a9457691ee/lib/net.js#L734 + */ + if ("_handle" in socket) Object.defineProperty(this, "_handle", { + value: socket._handle, + enumerable: true, + writable: true + }); + this.once("close", () => { + socket.removeAllListeners(); + if (!socket.destroyed) socket.destroy(); + this.originalSocket = void 0; + }); + this.address = socket.address.bind(socket); + let writeArgs; + let headersWritten = false; + while (writeArgs = this.writeBuffer.shift()) if (writeArgs !== void 0) { + if (!headersWritten) { + const [chunk, encoding, callback] = writeArgs; + const chunkString = chunk.toString(); + const chunkBeforeRequestHeaders = chunkString.slice(0, chunkString.indexOf("\r\n") + 2); + const chunkAfterRequestHeaders = chunkString.slice(chunk.indexOf("\r\n\r\n")); + const headersChunk = `${chunkBeforeRequestHeaders}${getRawFetchHeaders(this.request.headers).filter(([name]) => { + return name.toLowerCase() !== INTERNAL_REQUEST_ID_HEADER_NAME; + }).map(([name, value]) => `${name}: ${value}`).join("\r\n")}${chunkAfterRequestHeaders}`; + socket.write(headersChunk, encoding, callback); + headersWritten = true; + continue; + } + socket.write(...writeArgs); + } + if (Reflect.get(socket, "encrypted")) [ + "encrypted", + "authorized", + "getProtocol", + "getSession", + "isSessionReused", + "getCipher" + ].forEach((propertyName) => { + Object.defineProperty(this, propertyName, { + enumerable: true, + get: () => { + const value = Reflect.get(socket, propertyName); + return typeof value === "function" ? value.bind(socket) : value; + } + }); + }); + socket.on("lookup", (...args) => this.emit("lookup", ...args)).on("connect", () => { + this.connecting = socket.connecting; + this.emit("connect"); + }).on("secureConnect", () => this.emit("secureConnect")).on("secure", () => this.emit("secure")).on("session", (session) => this.emit("session", session)).on("ready", () => this.emit("ready")).on("drain", () => this.emit("drain")).on("data", (chunk) => { + this.push(chunk); + }).on("error", (error) => { + Reflect.set(this, "_hadError", Reflect.get(socket, "_hadError")); + this.emit("error", error); + }).on("resume", () => this.emit("resume")).on("timeout", () => this.emit("timeout")).on("prefinish", () => this.emit("prefinish")).on("finish", () => this.emit("finish")).on("close", (hadError) => this.emit("close", hadError)).on("end", () => this.emit("end")); + } + /** + * Convert the given Fetch API `Response` instance to an + * HTTP message and push it to the socket. + */ + async respondWith(response) { + if (this.destroyed) return; + invariant(this.socketState !== "mock", "[MockHttpSocket] Failed to respond to the \"%s %s\" request with \"%s %s\": the request has already been handled", this.request?.method, this.request?.url, response.status, response.statusText); + if (isPropertyAccessible(response, "type") && response.type === "error") { + this.errorWith(/* @__PURE__ */ new TypeError("Network error")); + return; + } + this.mockConnect(); + this.socketState = "mock"; + this.flushWriteBuffer(); + const serverResponse = new ServerResponse(new IncomingMessage(this)); + /** + * Assign a mock socket instance to the server response to + * spy on the response chunk writes. Push the transformed response chunks + * to this `MockHttpSocket` instance to trigger the "data" event. + * @note Providing the same `MockSocket` instance when creating `ServerResponse` + * does not have the same effect. + * @see https://github.com/nodejs/node/blob/10099bb3f7fd97bb9dd9667188426866b3098e07/test/parallel/test-http-server-response-standalone.js#L32 + */ + serverResponse.assignSocket(new MockSocket({ + write: (chunk, encoding, callback) => { + this.push(chunk, encoding); + callback?.(); + }, + read() {} + })); + /** + * @note Remove the `Connection` and `Date` response headers + * injected by `ServerResponse` by default. Those are required + * from the server but the interceptor is NOT technically a server. + * It's confusing to add response headers that the developer didn't + * specify themselves. They can always add these if they wish. + * @see https://www.rfc-editor.org/rfc/rfc9110#field.date + * @see https://www.rfc-editor.org/rfc/rfc9110#field.connection + */ + serverResponse.removeHeader("connection"); + serverResponse.removeHeader("date"); + const rawResponseHeaders = getRawFetchHeaders(response.headers); + /** + * @note Call `.writeHead` in order to set the raw response headers + * in the same case as they were provided by the developer. Using + * `.setHeader()`/`.appendHeader()` normalizes header names. + */ + serverResponse.writeHead(response.status, response.statusText || STATUS_CODES[response.status], rawResponseHeaders); + this.once("error", () => { + serverResponse.destroy(); + }); + if (response.body) try { + const reader = response.body.getReader(); + while (true) { + const { done, value } = await reader.read(); + if (done) { + serverResponse.end(); + break; + } + serverResponse.write(value); + } + } catch (error) { + if (error instanceof Error) { + serverResponse.destroy(); + /** + * @note Destroy the request socket gracefully. + * Response stream errors do NOT produce request errors. + */ + this.destroy(); + return; + } + serverResponse.destroy(); + throw error; + } + else serverResponse.end(); + if (!this.shouldKeepAlive) { + this.emit("readable"); + /** + * @todo @fixme This is likely a hack. + * Since we push null to the socket, it never propagates to the + * parser, and the parser never calls "onResponseEnd" to close + * the response stream. We are closing the stream here manually + * but that shouldn't be the case. + */ + this.responseStream?.push(null); + this.push(null); + } + } + /** + * Close this socket connection with the given error. + */ + errorWith(error) { + this.destroy(error); + } + mockConnect() { + this.connecting = false; + const isIPv6 = net.isIPv6(this.connectionOptions.hostname) || this.connectionOptions.family === 6; + const addressInfo = { + address: isIPv6 ? "::1" : "127.0.0.1", + family: isIPv6 ? "IPv6" : "IPv4", + port: this.connectionOptions.port + }; + this.address = () => addressInfo; + this.emit("lookup", null, addressInfo.address, addressInfo.family === "IPv6" ? 6 : 4, this.connectionOptions.host); + this.emit("connect"); + this.emit("ready"); + if (this.baseUrl.protocol === "https:") { + this.emit("secure"); + this.emit("secureConnect"); + this.emit("session", this.connectionOptions.session || Buffer.from("mock-session-renegotiate")); + this.emit("session", Buffer.from("mock-session-resume")); + } + } + flushWriteBuffer() { + for (const writeCall of this.writeBuffer) if (typeof writeCall[2] === "function") { + writeCall[2](); + /** + * @note Remove the callback from the write call + * so it doesn't get called twice on passthrough + * if `request.end()` was called within `request.write()`. + * @see https://github.com/mswjs/interceptors/issues/684 + */ + writeCall[2] = void 0; + } + } + onRequestBody(chunk) { + invariant(this.requestStream, "Failed to write to a request stream: stream does not exist"); + this.requestStream.push(chunk); + } + onRequestEnd() { + if (this.requestStream) this.requestStream.push(null); + } + onResponseBody(chunk) { + invariant(this.responseStream, "Failed to write to a response stream: stream does not exist"); + this.responseStream.push(chunk); + } + onResponseEnd() { + if (this.responseStream) this.responseStream.push(null); + } +}; + +//#endregion +//#region src/interceptors/ClientRequest/agents.ts +var MockAgent = class extends http.Agent { + constructor(options) { + super(); + this.customAgent = options.customAgent; + this.onRequest = options.onRequest; + this.onResponse = options.onResponse; + } + createConnection(options, callback) { + const createConnection = this.customAgent instanceof http.Agent ? this.customAgent.createConnection : super.createConnection; + const createConnectionOptions = this.customAgent instanceof http.Agent ? { + ...options, + ...this.customAgent.options + } : options; + return new MockHttpSocket({ + connectionOptions: options, + createConnection: createConnection.bind(this.customAgent || this, createConnectionOptions, callback), + onRequest: this.onRequest.bind(this), + onResponse: this.onResponse.bind(this) + }); + } +}; +var MockHttpsAgent = class extends https.Agent { + constructor(options) { + super(); + this.customAgent = options.customAgent; + this.onRequest = options.onRequest; + this.onResponse = options.onResponse; + } + createConnection(options, callback) { + const createConnection = this.customAgent instanceof http.Agent ? this.customAgent.createConnection : super.createConnection; + const createConnectionOptions = this.customAgent instanceof http.Agent ? { + ...options, + ...this.customAgent.options + } : options; + return new MockHttpSocket({ + connectionOptions: options, + createConnection: createConnection.bind(this.customAgent || this, createConnectionOptions, callback), + onRequest: this.onRequest.bind(this), + onResponse: this.onResponse.bind(this) + }); + } +}; + +//#endregion +//#region src/utils/getUrlByRequestOptions.ts +const logger$2 = new Logger("utils getUrlByRequestOptions"); +const DEFAULT_PATH = "/"; +const DEFAULT_PROTOCOL = "http:"; +const DEFAULT_HOSTNAME = "localhost"; +const SSL_PORT = 443; +function getAgent(options) { + return options.agent instanceof Agent ? options.agent : void 0; +} +function getProtocolByRequestOptions(options) { + if (options.protocol) return options.protocol; + const agentProtocol = getAgent(options)?.protocol; + if (agentProtocol) return agentProtocol; + const port = getPortByRequestOptions(options); + return options.cert || port === SSL_PORT ? "https:" : options.uri?.protocol || DEFAULT_PROTOCOL; +} +function getPortByRequestOptions(options) { + if (options.port) return Number(options.port); + const agent = getAgent(options); + if (agent?.options.port) return Number(agent.options.port); + if (agent?.defaultPort) return Number(agent.defaultPort); +} +function getAuthByRequestOptions(options) { + if (options.auth) { + const [username, password] = options.auth.split(":"); + return { + username, + password + }; + } +} +/** +* Returns true if host looks like an IPv6 address without surrounding brackets +* It assumes any host containing `:` is definitely not IPv4 and probably IPv6, +* but note that this could include invalid IPv6 addresses as well. +*/ +function isRawIPv6Address(host) { + return host.includes(":") && !host.startsWith("[") && !host.endsWith("]"); +} +function getHostname(options) { + let host = options.hostname || options.host; + if (host) { + if (isRawIPv6Address(host)) host = `[${host}]`; + return new URL(`http://${host}`).hostname; + } + return DEFAULT_HOSTNAME; +} +/** +* Creates a `URL` instance from a given `RequestOptions` object. +*/ +function getUrlByRequestOptions(options) { + logger$2.info("request options", options); + if (options.uri) { + logger$2.info("constructing url from explicitly provided \"options.uri\": %s", options.uri); + return new URL(options.uri.href); + } + logger$2.info("figuring out url from request options..."); + const protocol = getProtocolByRequestOptions(options); + logger$2.info("protocol", protocol); + const port = getPortByRequestOptions(options); + logger$2.info("port", port); + const hostname = getHostname(options); + logger$2.info("hostname", hostname); + const path = options.path || DEFAULT_PATH; + logger$2.info("path", path); + const credentials = getAuthByRequestOptions(options); + logger$2.info("credentials", credentials); + const authString = credentials ? `${credentials.username}:${credentials.password}@` : ""; + logger$2.info("auth string:", authString); + const portString = typeof port !== "undefined" ? `:${port}` : ""; + const url = new URL(`${protocol}//${hostname}${portString}${path}`); + url.username = credentials?.username || ""; + url.password = credentials?.password || ""; + logger$2.info("created url:", url); + return url; +} + +//#endregion +//#region src/utils/cloneObject.ts +const logger$1 = new Logger("cloneObject"); +function isPlainObject(obj) { + logger$1.info("is plain object?", obj); + if (obj == null || !obj.constructor?.name) { + logger$1.info("given object is undefined, not a plain object..."); + return false; + } + logger$1.info("checking the object constructor:", obj.constructor.name); + return obj.constructor.name === "Object"; +} +function cloneObject(obj) { + logger$1.info("cloning object:", obj); + const enumerableProperties = Object.entries(obj).reduce((acc, [key, value]) => { + logger$1.info("analyzing key-value pair:", key, value); + acc[key] = isPlainObject(value) ? cloneObject(value) : value; + return acc; + }, {}); + return isPlainObject(obj) ? enumerableProperties : Object.assign(Object.getPrototypeOf(obj), enumerableProperties); +} + +//#endregion +//#region src/interceptors/ClientRequest/utils/normalizeClientRequestArgs.ts +const logger = new Logger("http normalizeClientRequestArgs"); +function resolveRequestOptions(args, url) { + if (typeof args[1] === "undefined" || typeof args[1] === "function") { + logger.info("request options not provided, deriving from the url", url); + return urlToHttpOptions(url); + } + if (args[1]) { + logger.info("has custom RequestOptions!", args[1]); + const requestOptionsFromUrl = urlToHttpOptions(url); + logger.info("derived RequestOptions from the URL:", requestOptionsFromUrl); + /** + * Clone the request options to lock their state + * at the moment they are provided to `ClientRequest`. + * @see https://github.com/mswjs/interceptors/issues/86 + */ + logger.info("cloning RequestOptions..."); + const clonedRequestOptions = cloneObject(args[1]); + logger.info("successfully cloned RequestOptions!", clonedRequestOptions); + return { + ...requestOptionsFromUrl, + ...clonedRequestOptions + }; + } + logger.info("using an empty object as request options"); + return {}; +} +/** +* Overrides the given `URL` instance with the explicit properties provided +* on the `RequestOptions` object. The options object takes precedence, +* and will replace URL properties like "host", "path", and "port", if specified. +*/ +function overrideUrlByRequestOptions(url, options) { + url.host = options.host || url.host; + url.hostname = options.hostname || url.hostname; + url.port = options.port ? options.port.toString() : url.port; + if (options.path) { + const parsedOptionsPath = parse(options.path, false); + url.pathname = parsedOptionsPath.pathname || ""; + url.search = parsedOptionsPath.search || ""; + } + return url; +} +function resolveCallback(args) { + return typeof args[1] === "function" ? args[1] : args[2]; +} +/** +* Normalizes parameters given to a `http.request` call +* so it always has a `URL` and `RequestOptions`. +*/ +function normalizeClientRequestArgs(defaultProtocol, args) { + let url; + let options; + let callback; + logger.info("arguments", args); + logger.info("using default protocol:", defaultProtocol); + if (args.length === 0) { + const url$1 = new URL$1("http://localhost"); + return [url$1, resolveRequestOptions(args, url$1)]; + } + if (typeof args[0] === "string") { + logger.info("first argument is a location string:", args[0]); + url = new URL$1(args[0]); + logger.info("created a url:", url); + const requestOptionsFromUrl = urlToHttpOptions(url); + logger.info("request options from url:", requestOptionsFromUrl); + options = resolveRequestOptions(args, url); + logger.info("resolved request options:", options); + callback = resolveCallback(args); + } else if (args[0] instanceof URL$1) { + url = args[0]; + logger.info("first argument is a URL:", url); + if (typeof args[1] !== "undefined" && isObject(args[1])) url = overrideUrlByRequestOptions(url, args[1]); + options = resolveRequestOptions(args, url); + logger.info("derived request options:", options); + callback = resolveCallback(args); + } else if ("hash" in args[0] && !("method" in args[0])) { + const [legacyUrl] = args; + logger.info("first argument is a legacy URL:", legacyUrl); + if (legacyUrl.hostname === null) { + /** + * We are dealing with a relative url, so use the path as an "option" and + * merge in any existing options, giving priority to existing options -- i.e. a path in any + * existing options will take precedence over the one contained in the url. This is consistent + * with the behaviour in ClientRequest. + * @see https://github.com/nodejs/node/blob/d84f1312915fe45fe0febe888db692c74894c382/lib/_http_client.js#L122 + */ + logger.info("given legacy URL is relative (no hostname)"); + return isObject(args[1]) ? normalizeClientRequestArgs(defaultProtocol, [{ + path: legacyUrl.path, + ...args[1] + }, args[2]]) : normalizeClientRequestArgs(defaultProtocol, [{ path: legacyUrl.path }, args[1]]); + } + logger.info("given legacy url is absolute"); + const resolvedUrl = new URL$1(legacyUrl.href); + return args[1] === void 0 ? normalizeClientRequestArgs(defaultProtocol, [resolvedUrl]) : typeof args[1] === "function" ? normalizeClientRequestArgs(defaultProtocol, [resolvedUrl, args[1]]) : normalizeClientRequestArgs(defaultProtocol, [ + resolvedUrl, + args[1], + args[2] + ]); + } else if (isObject(args[0])) { + options = { ...args[0] }; + logger.info("first argument is RequestOptions:", options); + options.protocol = options.protocol || defaultProtocol; + logger.info("normalized request options:", options); + url = getUrlByRequestOptions(options); + logger.info("created a URL from RequestOptions:", url.href); + callback = resolveCallback(args); + } else throw new Error(`Failed to construct ClientRequest with these parameters: ${args}`); + options.protocol = options.protocol || url.protocol; + options.method = options.method || "GET"; + /** + * Ensure that the default Agent is always set. + * This prevents the protocol mismatch for requests with { agent: false }, + * where the global Agent is inferred. + * @see https://github.com/mswjs/msw/issues/1150 + * @see https://github.com/nodejs/node/blob/418ff70b810f0e7112d48baaa72932a56cfa213b/lib/_http_client.js#L130 + * @see https://github.com/nodejs/node/blob/418ff70b810f0e7112d48baaa72932a56cfa213b/lib/_http_client.js#L157-L159 + */ + if (!options._defaultAgent) { + logger.info("has no default agent, setting the default agent for \"%s\"", options.protocol); + options._defaultAgent = options.protocol === "https:" ? globalAgent$1 : globalAgent; + } + logger.info("successfully resolved url:", url.href); + logger.info("successfully resolved options:", options); + logger.info("successfully resolved callback:", callback); + /** + * @note If the user-provided URL is not a valid URL in Node.js, + * (e.g. the one provided by the JSDOM polyfills), case it to + * string. Otherwise, this throws on Node.js incompatibility + * (`ERR_INVALID_ARG_TYPE` on the connection listener) + * @see https://github.com/node-fetch/node-fetch/issues/1376#issuecomment-966435555 + */ + if (!(url instanceof URL$1)) url = url.toString(); + return [ + url, + options, + callback + ]; +} + +//#endregion +//#region src/interceptors/ClientRequest/index.ts +var ClientRequestInterceptor = class ClientRequestInterceptor extends Interceptor { + static { + this.symbol = Symbol.for("client-request-interceptor"); + } + constructor() { + super(ClientRequestInterceptor.symbol); + this.onRequest = async ({ request, socket }) => { + const controller = new RequestController(request, { + passthrough() { + socket.passthrough(); + }, + async respondWith(response) { + await socket.respondWith(response); + }, + errorWith(reason) { + if (reason instanceof Error) socket.errorWith(reason); + } + }); + await handleRequest({ + request, + requestId: Reflect.get(request, kRequestId), + controller, + emitter: this.emitter + }); + }; + this.onResponse = async ({ requestId, request, response, isMockedResponse }) => { + return emitAsync(this.emitter, "response", { + requestId, + request, + response, + isMockedResponse + }); + }; + } + setup() { + const { ClientRequest: OriginalClientRequest, get: originalGet, request: originalRequest } = http; + const { get: originalHttpsGet, request: originalHttpsRequest } = https; + const onRequest = this.onRequest.bind(this); + const onResponse = this.onResponse.bind(this); + http.ClientRequest = new Proxy(http.ClientRequest, { construct: (target, args) => { + const [url, options, callback] = normalizeClientRequestArgs("http:", args); + options.agent = new (options.protocol === "https:" ? MockHttpsAgent : MockAgent)({ + customAgent: options.agent, + onRequest, + onResponse + }); + return Reflect.construct(target, [ + url, + options, + callback + ]); + } }); + http.request = new Proxy(http.request, { apply: (target, thisArg, args) => { + const [url, options, callback] = normalizeClientRequestArgs("http:", args); + options.agent = new MockAgent({ + customAgent: options.agent, + onRequest, + onResponse + }); + return Reflect.apply(target, thisArg, [ + url, + options, + callback + ]); + } }); + http.get = new Proxy(http.get, { apply: (target, thisArg, args) => { + const [url, options, callback] = normalizeClientRequestArgs("http:", args); + options.agent = new MockAgent({ + customAgent: options.agent, + onRequest, + onResponse + }); + return Reflect.apply(target, thisArg, [ + url, + options, + callback + ]); + } }); + https.request = new Proxy(https.request, { apply: (target, thisArg, args) => { + const [url, options, callback] = normalizeClientRequestArgs("https:", args); + options.agent = new MockHttpsAgent({ + customAgent: options.agent, + onRequest, + onResponse + }); + return Reflect.apply(target, thisArg, [ + url, + options, + callback + ]); + } }); + https.get = new Proxy(https.get, { apply: (target, thisArg, args) => { + const [url, options, callback] = normalizeClientRequestArgs("https:", args); + options.agent = new MockHttpsAgent({ + customAgent: options.agent, + onRequest, + onResponse + }); + return Reflect.apply(target, thisArg, [ + url, + options, + callback + ]); + } }); + recordRawFetchHeaders(); + this.subscriptions.push(() => { + http.ClientRequest = OriginalClientRequest; + http.get = originalGet; + http.request = originalRequest; + https.get = originalHttpsGet; + https.request = originalHttpsRequest; + restoreHeadersPrototype(); + }); + } +}; + +//#endregion +export { ClientRequestInterceptor as t }; +//# sourceMappingURL=ClientRequest-DGhBX21V.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/ClientRequest-DGhBX21V.mjs.map b/node_modules/@mswjs/interceptors/lib/node/ClientRequest-DGhBX21V.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..91fd05bf5b3bb16beb6df13b1259939efbb40ae1 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/ClientRequest-DGhBX21V.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"ClientRequest-DGhBX21V.mjs","names":["normalized: NormalizedSocketWriteArgs","options: MockSocketOptions","headers","inferredRawHeaders: RawHeaders","writeArgs: NormalizedSocketWriteArgs | undefined","logger","logger","parseUrl","url: URL","options: ResolvedRequestOptions","callback: HttpRequestCallback | undefined","url","URL","httpsGlobalAgent","httpGlobalAgent"],"sources":["../../src/interceptors/Socket/utils/normalizeSocketWriteArgs.ts","../../src/interceptors/Socket/MockSocket.ts","../../src/interceptors/Socket/utils/baseUrlFromConnectionOptions.ts","../../src/interceptors/ClientRequest/utils/recordRawHeaders.ts","../../src/interceptors/ClientRequest/utils/parserUtils.ts","../../src/interceptors/ClientRequest/MockHttpSocket.ts","../../src/interceptors/ClientRequest/agents.ts","../../src/utils/getUrlByRequestOptions.ts","../../src/utils/cloneObject.ts","../../src/interceptors/ClientRequest/utils/normalizeClientRequestArgs.ts","../../src/interceptors/ClientRequest/index.ts"],"sourcesContent":["export type WriteCallback = (error?: Error | null) => void\n\nexport type WriteArgs =\n | [chunk: unknown, callback?: WriteCallback]\n | [chunk: unknown, encoding: BufferEncoding, callback?: WriteCallback]\n\nexport type NormalizedSocketWriteArgs = [\n chunk: any,\n encoding?: BufferEncoding,\n callback?: WriteCallback,\n]\n\n/**\n * Normalizes the arguments provided to the `Writable.prototype.write()`\n * and `Writable.prototype.end()`.\n */\nexport function normalizeSocketWriteArgs(\n args: WriteArgs\n): NormalizedSocketWriteArgs {\n const normalized: NormalizedSocketWriteArgs = [args[0], undefined, undefined]\n\n if (typeof args[1] === 'string') {\n normalized[1] = args[1]\n } else if (typeof args[1] === 'function') {\n normalized[2] = args[1]\n }\n\n if (typeof args[2] === 'function') {\n normalized[2] = args[2]\n }\n\n return normalized\n}\n","import net from 'node:net'\nimport {\n normalizeSocketWriteArgs,\n type WriteArgs,\n type WriteCallback,\n} from './utils/normalizeSocketWriteArgs'\n\nexport interface MockSocketOptions {\n write: (\n chunk: Buffer | string,\n encoding: BufferEncoding | undefined,\n callback?: WriteCallback\n ) => void\n\n read: (chunk: Buffer, encoding: BufferEncoding | undefined) => void\n}\n\nexport class MockSocket extends net.Socket {\n public connecting: boolean\n\n constructor(protected readonly options: MockSocketOptions) {\n super()\n this.connecting = false\n this.connect()\n\n this._final = (callback) => {\n callback(null)\n }\n }\n\n public connect() {\n // The connection will remain pending until\n // the consumer decides to handle it.\n this.connecting = true\n return this\n }\n\n public write(...args: Array): boolean {\n const [chunk, encoding, callback] = normalizeSocketWriteArgs(\n args as WriteArgs\n )\n this.options.write(chunk, encoding, callback)\n return true\n }\n\n public end(...args: Array) {\n const [chunk, encoding, callback] = normalizeSocketWriteArgs(\n args as WriteArgs\n )\n this.options.write(chunk, encoding, callback)\n return super.end.apply(this, args as any)\n }\n\n public push(chunk: any, encoding?: BufferEncoding): boolean {\n this.options.read(chunk, encoding)\n return super.push(chunk, encoding)\n }\n}\n","export function baseUrlFromConnectionOptions(options: any): URL {\n if ('href' in options) {\n return new URL(options.href)\n }\n\n const protocol = options.port === 443 ? 'https:' : 'http:'\n const host = options.host\n\n const url = new URL(`${protocol}//${host}`)\n\n if (options.port) {\n url.port = options.port.toString()\n }\n\n if (options.path) {\n url.pathname = options.path\n }\n\n if (options.auth) {\n const [username, password] = options.auth.split(':')\n url.username = username\n url.password = password\n }\n\n return url\n}\n","import { FetchRequest, FetchResponse } from '../../../utils/fetchUtils'\n\ntype HeaderTuple = [string, string]\ntype RawHeaders = Array\ntype SetHeaderBehavior = 'set' | 'append'\n\nconst kRawHeaders = Symbol('kRawHeaders')\nconst kRestorePatches = Symbol('kRestorePatches')\n\nfunction recordRawHeader(\n headers: Headers,\n args: HeaderTuple,\n behavior: SetHeaderBehavior\n) {\n ensureRawHeadersSymbol(headers, [])\n const rawHeaders = Reflect.get(headers, kRawHeaders) as RawHeaders\n\n if (behavior === 'set') {\n // When recording a set header, ensure we remove any matching existing headers.\n for (let index = rawHeaders.length - 1; index >= 0; index--) {\n if (rawHeaders[index][0].toLowerCase() === args[0].toLowerCase()) {\n rawHeaders.splice(index, 1)\n }\n }\n }\n\n rawHeaders.push(args)\n}\n\n/**\n * Define the raw headers symbol on the given `Headers` instance.\n * If the symbol already exists, this function does nothing.\n */\nfunction ensureRawHeadersSymbol(\n headers: Headers,\n rawHeaders: RawHeaders\n): void {\n if (Reflect.has(headers, kRawHeaders)) {\n return\n }\n\n defineRawHeadersSymbol(headers, rawHeaders)\n}\n\n/**\n * Define the raw headers symbol on the given `Headers` instance.\n * If the symbol already exists, it gets overridden.\n */\nfunction defineRawHeadersSymbol(headers: Headers, rawHeaders: RawHeaders) {\n Object.defineProperty(headers, kRawHeaders, {\n value: rawHeaders,\n enumerable: false,\n // Mark the symbol as configurable so its value can be overridden.\n // Overrides happen when merging raw headers from multiple sources.\n // E.g. new Request(new Request(url, { headers }), { headers })\n configurable: true,\n })\n}\n\n/**\n * Patch the global `Headers` class to store raw headers.\n * This is for compatibility with `IncomingMessage.prototype.rawHeaders`.\n *\n * @note Node.js has their own raw headers symbol but it\n * only records the first header name in case of multi-value headers.\n * Any other headers are normalized before comparing. This makes it\n * incompatible with the `rawHeaders` format.\n *\n * let h = new Headers()\n * h.append('X-Custom', 'one')\n * h.append('x-custom', 'two')\n * h[Symbol('headers map')] // Map { 'X-Custom' => 'one, two' }\n */\nexport function recordRawFetchHeaders() {\n // Prevent patching the Headers prototype multiple times.\n if (Reflect.get(Headers, kRestorePatches)) {\n return Reflect.get(Headers, kRestorePatches)\n }\n\n const {\n Headers: OriginalHeaders,\n Request: OriginalRequest,\n Response: OriginalResponse,\n } = globalThis\n const { set, append, delete: headersDeleteMethod } = Headers.prototype\n\n Object.defineProperty(Headers, kRestorePatches, {\n value: () => {\n Headers.prototype.set = set\n Headers.prototype.append = append\n Headers.prototype.delete = headersDeleteMethod\n globalThis.Headers = OriginalHeaders\n\n globalThis.Request = OriginalRequest\n globalThis.Response = OriginalResponse\n\n Object.setPrototypeOf(FetchRequest, OriginalRequest)\n Object.setPrototypeOf(FetchRequest.prototype, OriginalRequest.prototype)\n Object.setPrototypeOf(FetchResponse, OriginalResponse)\n Object.setPrototypeOf(FetchResponse.prototype, OriginalResponse.prototype)\n\n Reflect.deleteProperty(Headers, kRestorePatches)\n },\n enumerable: false,\n /**\n * @note Mark this property as configurable\n * so we can delete it using `Reflect.delete` during cleanup.\n */\n configurable: true,\n })\n\n Object.defineProperty(globalThis, 'Headers', {\n enumerable: true,\n writable: true,\n value: new Proxy(Headers, {\n construct(target, args, newTarget) {\n const headersInit = args[0] || []\n\n if (\n headersInit instanceof Headers &&\n Reflect.has(headersInit, kRawHeaders)\n ) {\n // Ensure each header tuple has exactly 2 elements (name, value).\n // Node.js 24+ may have stored tuples with extra internal arguments.\n const rawHeadersFromInit = Reflect.get(\n headersInit,\n kRawHeaders\n ) as RawHeaders\n const sanitizedHeaders = rawHeadersFromInit.map(\n (tuple): HeaderTuple => [tuple[0], tuple[1]]\n )\n const headers = Reflect.construct(\n target,\n [sanitizedHeaders],\n newTarget\n )\n ensureRawHeadersSymbol(headers, [\n /**\n * @note Spread the retrieved headers to clone them.\n * This prevents multiple Headers instances from pointing\n * at the same internal \"rawHeaders\" array.\n */\n ...sanitizedHeaders,\n ])\n return headers\n }\n\n const headers = Reflect.construct(target, args, newTarget)\n\n // Request/Response constructors will set the symbol\n // upon creating a new instance, using the raw developer\n // input as the raw headers. Skip the symbol altogether\n // in those cases because the input to Headers will be normalized.\n if (!Reflect.has(headers, kRawHeaders)) {\n const rawHeadersInit = Array.isArray(headersInit)\n ? headersInit\n : Object.entries(headersInit)\n ensureRawHeadersSymbol(headers, rawHeadersInit)\n }\n\n return headers\n },\n }),\n })\n\n Headers.prototype.set = new Proxy(Headers.prototype.set, {\n apply(target, thisArg, args: HeaderTuple) {\n // Use only the first two arguments (name, value) to record raw headers.\n // Node.js 24+ may pass additional internal arguments that should not\n // be included in the raw headers array.\n recordRawHeader(thisArg, [args[0], args[1]], 'set')\n return Reflect.apply(target, thisArg, args)\n },\n })\n\n Headers.prototype.append = new Proxy(Headers.prototype.append, {\n apply(target, thisArg, args: HeaderTuple) {\n // Use only the first two arguments (name, value) to record raw headers.\n // Node.js 24+ may pass additional internal arguments that should not\n // be included in the raw headers array.\n recordRawHeader(thisArg, [args[0], args[1]], 'append')\n return Reflect.apply(target, thisArg, args)\n },\n })\n\n Headers.prototype.delete = new Proxy(Headers.prototype.delete, {\n apply(target, thisArg, args: [string]) {\n const rawHeaders = Reflect.get(thisArg, kRawHeaders) as RawHeaders\n\n if (rawHeaders) {\n for (let index = rawHeaders.length - 1; index >= 0; index--) {\n if (rawHeaders[index][0].toLowerCase() === args[0].toLowerCase()) {\n rawHeaders.splice(index, 1)\n }\n }\n }\n\n return Reflect.apply(target, thisArg, args)\n },\n })\n\n Object.defineProperty(globalThis, 'Request', {\n enumerable: true,\n writable: true,\n value: new Proxy(Request, {\n construct(target, args, newTarget) {\n const request = Reflect.construct(target, args, newTarget)\n const inferredRawHeaders: RawHeaders = []\n\n // Infer raw headers from a `Request` instance used as init.\n if (typeof args[0] === 'object' && args[0].headers != null) {\n inferredRawHeaders.push(...inferRawHeaders(args[0].headers))\n }\n\n // Infer raw headers from the \"headers\" init argument.\n if (typeof args[1] === 'object' && args[1].headers != null) {\n inferredRawHeaders.push(...inferRawHeaders(args[1].headers))\n }\n\n if (inferredRawHeaders.length > 0) {\n ensureRawHeadersSymbol(request.headers, inferredRawHeaders)\n }\n\n return request\n },\n }),\n })\n\n Object.defineProperty(globalThis, 'Response', {\n enumerable: true,\n writable: true,\n value: new Proxy(Response, {\n construct(target, args, newTarget) {\n const response = Reflect.construct(target, args, newTarget)\n\n if (typeof args[1] === 'object' && args[1].headers != null) {\n ensureRawHeadersSymbol(\n response.headers,\n inferRawHeaders(args[1].headers)\n )\n }\n\n return response\n },\n }),\n })\n\n /**\n * Re-parent FetchRequest/FetchResponse so their `super()` calls go\n * through the proxied globalThis.Request/Response above. Without this,\n * FetchRequest extends the statically-captured (original) Request,\n * bypassing the construct proxy that records raw headers.\n */\n Object.setPrototypeOf(FetchRequest, globalThis.Request)\n Object.setPrototypeOf(FetchRequest.prototype, globalThis.Request.prototype)\n Object.setPrototypeOf(FetchResponse, globalThis.Response)\n Object.setPrototypeOf(FetchResponse.prototype, globalThis.Response.prototype)\n}\n\nexport function restoreHeadersPrototype() {\n if (!Reflect.get(Headers, kRestorePatches)) {\n return\n }\n\n Reflect.get(Headers, kRestorePatches)()\n}\n\nexport function getRawFetchHeaders(headers: Headers): RawHeaders {\n // If the raw headers recording failed for some reason,\n // use the normalized header entries instead.\n if (!Reflect.has(headers, kRawHeaders)) {\n return Array.from(headers.entries())\n }\n\n const rawHeaders = Reflect.get(headers, kRawHeaders) as RawHeaders\n return rawHeaders.length > 0 ? rawHeaders : Array.from(headers.entries())\n}\n\n/**\n * Infers the raw headers from the given `HeadersInit` provided\n * to the Request/Response constructor.\n *\n * If the `init.headers` is a Headers instance, use it directly.\n * That means the headers were created standalone and already have\n * the raw headers stored.\n * If the `init.headers` is a HeadersInit, create a new Headers\n * instance out of it.\n */\nfunction inferRawHeaders(headers: HeadersInit): RawHeaders {\n if (headers instanceof Headers) {\n return Reflect.get(headers, kRawHeaders) || []\n }\n\n return Reflect.get(new Headers(headers), kRawHeaders)\n}\n","import type { Socket } from 'node:net'\nimport { HTTPParser } from '_http_common'\n\n/**\n * @see https://github.com/nodejs/node/blob/f3adc11e37b8bfaaa026ea85c1cf22e3a0e29ae9/lib/_http_common.js#L180\n */\nexport function freeParser(parser: HTTPParser, socket?: Socket): void {\n if (parser._consumed) {\n parser.unconsume()\n }\n\n parser._headers = []\n parser._url = ''\n parser.socket = null\n parser.incoming = null\n parser.outgoing = null\n parser.maxHeaderPairs = 2000\n parser._consumed = false\n parser.onIncoming = null\n\n parser[HTTPParser.kOnHeaders] = null\n parser[HTTPParser.kOnHeadersComplete] = null\n parser[HTTPParser.kOnMessageBegin] = null\n parser[HTTPParser.kOnMessageComplete] = null\n parser[HTTPParser.kOnBody] = null\n parser[HTTPParser.kOnExecute] = null\n parser[HTTPParser.kOnTimeout] = null\n\n parser.remove()\n parser.free()\n\n if (socket) {\n /**\n * @note Unassigning the socket's parser will fail this assertion\n * if there's still some data being processed on the socket:\n * @see https://github.com/nodejs/node/blob/4e1f39b678b37017ac9baa0971e3aeecd3b67b51/lib/_http_client.js#L613\n */\n if (socket.destroyed) {\n // @ts-expect-error Node.js internals.\n socket.parser = null\n } else {\n socket.once('end', () => {\n // @ts-expect-error Node.js internals.\n socket.parser = null\n })\n }\n }\n}\n","import net from 'node:net'\nimport {\n type HeadersCallback,\n HTTPParser,\n type RequestHeadersCompleteCallback,\n type ResponseHeadersCompleteCallback,\n} from '_http_common'\nimport { STATUS_CODES, IncomingMessage, ServerResponse } from 'node:http'\nimport { Readable } from 'node:stream'\nimport { invariant } from 'outvariant'\nimport { INTERNAL_REQUEST_ID_HEADER_NAME } from '../../Interceptor'\nimport { MockSocket } from '../Socket/MockSocket'\nimport type { NormalizedSocketWriteArgs } from '../Socket/utils/normalizeSocketWriteArgs'\nimport { isPropertyAccessible } from '../../utils/isPropertyAccessible'\nimport { baseUrlFromConnectionOptions } from '../Socket/utils/baseUrlFromConnectionOptions'\nimport { createRequestId } from '../../createRequestId'\nimport { getRawFetchHeaders } from './utils/recordRawHeaders'\nimport { FetchRequest, FetchResponse } from '../../utils/fetchUtils'\nimport { setRawRequest } from '../../getRawRequest'\nimport { setRawRequestBodyStream } from '../../utils/node'\nimport { freeParser } from './utils/parserUtils'\n\ntype HttpConnectionOptions = any\n\nexport type MockHttpSocketRequestCallback = (args: {\n requestId: string\n request: Request\n socket: MockHttpSocket\n}) => void\n\nexport type MockHttpSocketResponseCallback = (args: {\n requestId: string\n request: Request\n response: Response\n isMockedResponse: boolean\n socket: MockHttpSocket\n}) => Promise\n\ninterface MockHttpSocketOptions {\n connectionOptions: HttpConnectionOptions\n createConnection: () => net.Socket\n onRequest: MockHttpSocketRequestCallback\n onResponse: MockHttpSocketResponseCallback\n}\n\nexport const kRequestId = Symbol('kRequestId')\n\nexport class MockHttpSocket extends MockSocket {\n private connectionOptions: HttpConnectionOptions\n private createConnection: () => net.Socket\n private baseUrl: URL\n\n private onRequest: MockHttpSocketRequestCallback\n private onResponse: MockHttpSocketResponseCallback\n private responseListenersPromise?: Promise\n\n private requestRawHeadersBuffer: Array = []\n private responseRawHeadersBuffer: Array = []\n private writeBuffer: Array = []\n private request?: Request\n private requestParser: HTTPParser<0>\n private requestStream?: Readable\n private shouldKeepAlive?: boolean\n\n private socketState: 'unknown' | 'mock' | 'passthrough' = 'unknown'\n private responseParser: HTTPParser<1>\n private responseStream?: Readable\n private originalSocket?: net.Socket\n\n constructor(options: MockHttpSocketOptions) {\n super({\n write: (chunk, encoding, callback) => {\n // Buffer the writes so they can be flushed in case of the original connection\n // and when reading the request body in the interceptor. If the connection has\n // been established, no need to buffer the chunks anymore, they will be forwarded.\n if (this.socketState !== 'passthrough') {\n this.writeBuffer.push([chunk, encoding, callback])\n }\n\n if (chunk) {\n /**\n * Forward any writes to the mock socket to the underlying original socket.\n * This ensures functional duplex connections, like WebSocket.\n * @see https://github.com/mswjs/interceptors/issues/682\n */\n if (this.socketState === 'passthrough') {\n this.originalSocket?.write(chunk, encoding, callback)\n }\n\n this.requestParser.execute(\n Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding)\n )\n }\n },\n read: (chunk) => {\n if (chunk !== null) {\n /**\n * @todo We need to free the parser if the connection has been\n * upgraded to a non-HTTP protocol. It won't be able to parse data\n * from that point onward anyway. No need to keep it in memory.\n */\n this.responseParser.execute(\n Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)\n )\n }\n },\n })\n\n this.connectionOptions = options.connectionOptions\n this.createConnection = options.createConnection\n this.onRequest = options.onRequest\n this.onResponse = options.onResponse\n\n this.baseUrl = baseUrlFromConnectionOptions(this.connectionOptions)\n\n // Request parser.\n this.requestParser = new HTTPParser()\n this.requestParser.initialize(HTTPParser.REQUEST, {})\n this.requestParser[HTTPParser.kOnHeaders] = this.onRequestHeaders.bind(this)\n this.requestParser[HTTPParser.kOnHeadersComplete] =\n this.onRequestStart.bind(this)\n this.requestParser[HTTPParser.kOnBody] = this.onRequestBody.bind(this)\n this.requestParser[HTTPParser.kOnMessageComplete] =\n this.onRequestEnd.bind(this)\n\n // Response parser.\n this.responseParser = new HTTPParser()\n this.responseParser.initialize(HTTPParser.RESPONSE, {})\n this.responseParser[HTTPParser.kOnHeaders] =\n this.onResponseHeaders.bind(this)\n this.responseParser[HTTPParser.kOnHeadersComplete] =\n this.onResponseStart.bind(this)\n this.responseParser[HTTPParser.kOnBody] = this.onResponseBody.bind(this)\n this.responseParser[HTTPParser.kOnMessageComplete] =\n this.onResponseEnd.bind(this)\n\n // Once the socket is finished, nothing can write to it\n // anymore. It has also flushed any buffered chunks.\n this.once('finish', () => freeParser(this.requestParser, this))\n\n if (this.baseUrl.protocol === 'https:') {\n Reflect.set(this, 'encrypted', true)\n // The server certificate is not the same as a CA\n // passed to the TLS socket connection options.\n Reflect.set(this, 'authorized', false)\n Reflect.set(this, 'getProtocol', () => 'TLSv1.3')\n Reflect.set(this, 'getSession', () => undefined)\n Reflect.set(this, 'isSessionReused', () => false)\n Reflect.set(this, 'getCipher', () => ({\n name: 'AES256-SHA',\n standardName: 'TLS_RSA_WITH_AES_256_CBC_SHA',\n version: 'TLSv1.3',\n }))\n }\n }\n\n public emit(event: string | symbol, ...args: any[]): boolean {\n const emitEvent = super.emit.bind(this, event as any, ...args)\n\n if (this.responseListenersPromise) {\n this.responseListenersPromise.finally(emitEvent)\n return this.listenerCount(event) > 0\n }\n\n return emitEvent()\n }\n\n public destroy(error?: Error | undefined): this {\n // Destroy the response parser when the socket gets destroyed.\n // Normally, we should listen to the \"close\" event but it\n // can be suppressed by using the \"emitClose: false\" option.\n freeParser(this.responseParser, this)\n\n if (error) {\n this.emit('error', error)\n }\n\n return super.destroy(error)\n }\n\n /**\n * Establish this Socket connection as-is and pipe\n * its data/events through this Socket.\n */\n public passthrough(): void {\n this.socketState = 'passthrough'\n\n if (this.destroyed) {\n return\n }\n\n const socket = this.createConnection()\n this.originalSocket = socket\n\n /**\n * @note Inherit the original socket's connection handle.\n * Without this, each push to the mock socket results in a\n * new \"connection\" listener being added (i.e. buffering pushes).\n * @see https://github.com/nodejs/node/blob/b18153598b25485ce4f54d0c5cb830a9457691ee/lib/net.js#L734\n */\n if ('_handle' in socket) {\n Object.defineProperty(this, '_handle', {\n value: socket._handle,\n enumerable: true,\n writable: true,\n })\n }\n\n // The client-facing socket can be destroyed in two ways:\n // 1. The developer destroys the socket.\n // 2. The passthrough socket \"close\" is forwarded to the socket.\n this.once('close', () => {\n socket.removeAllListeners()\n\n // If the closure didn't originate from the passthrough socket, destroy it.\n if (!socket.destroyed) {\n socket.destroy()\n }\n\n this.originalSocket = undefined\n })\n\n this.address = socket.address.bind(socket)\n\n // Flush the buffered \"socket.write()\" calls onto\n // the original socket instance (i.e. write request body).\n // Exhaust the \"requestBuffer\" in case this Socket\n // gets reused for different requests.\n let writeArgs: NormalizedSocketWriteArgs | undefined\n let headersWritten = false\n\n while ((writeArgs = this.writeBuffer.shift())) {\n if (writeArgs !== undefined) {\n if (!headersWritten) {\n const [chunk, encoding, callback] = writeArgs\n const chunkString = chunk.toString()\n const chunkBeforeRequestHeaders = chunkString.slice(\n 0,\n chunkString.indexOf('\\r\\n') + 2\n )\n const chunkAfterRequestHeaders = chunkString.slice(\n chunk.indexOf('\\r\\n\\r\\n')\n )\n const rawRequestHeaders = getRawFetchHeaders(this.request!.headers)\n const requestHeadersString = rawRequestHeaders\n // Skip the internal request ID deduplication header.\n .filter(([name]) => {\n return name.toLowerCase() !== INTERNAL_REQUEST_ID_HEADER_NAME\n })\n .map(([name, value]) => `${name}: ${value}`)\n .join('\\r\\n')\n\n // Modify the HTTP request message headers\n // to reflect any changes to the request headers\n // from the \"request\" event listener.\n const headersChunk = `${chunkBeforeRequestHeaders}${requestHeadersString}${chunkAfterRequestHeaders}`\n socket.write(headersChunk, encoding, callback)\n headersWritten = true\n continue\n }\n\n socket.write(...writeArgs)\n }\n }\n\n // Forward TLS Socket properties onto this Socket instance\n // in the case of a TLS/SSL connection.\n if (Reflect.get(socket, 'encrypted')) {\n const tlsProperties = [\n 'encrypted',\n 'authorized',\n 'getProtocol',\n 'getSession',\n 'isSessionReused',\n 'getCipher',\n ]\n\n tlsProperties.forEach((propertyName) => {\n Object.defineProperty(this, propertyName, {\n enumerable: true,\n get: () => {\n const value = Reflect.get(socket, propertyName)\n return typeof value === 'function' ? value.bind(socket) : value\n },\n })\n })\n }\n\n socket\n .on('lookup', (...args) => this.emit('lookup', ...args))\n .on('connect', () => {\n this.connecting = socket.connecting\n this.emit('connect')\n })\n .on('secureConnect', () => this.emit('secureConnect'))\n .on('secure', () => this.emit('secure'))\n .on('session', (session) => this.emit('session', session))\n .on('ready', () => this.emit('ready'))\n .on('drain', () => this.emit('drain'))\n .on('data', (chunk) => {\n // Push the original response to this socket\n // so it triggers the HTTP response parser. This unifies\n // the handling pipeline for original and mocked response.\n this.push(chunk)\n })\n .on('error', (error) => {\n Reflect.set(this, '_hadError', Reflect.get(socket, '_hadError'))\n this.emit('error', error)\n })\n .on('resume', () => this.emit('resume'))\n .on('timeout', () => this.emit('timeout'))\n .on('prefinish', () => this.emit('prefinish'))\n .on('finish', () => this.emit('finish'))\n .on('close', (hadError) => this.emit('close', hadError))\n .on('end', () => this.emit('end'))\n }\n\n /**\n * Convert the given Fetch API `Response` instance to an\n * HTTP message and push it to the socket.\n */\n public async respondWith(response: Response): Promise {\n // Ignore the mocked response if the socket has been destroyed\n // (e.g. aborted or timed out),\n if (this.destroyed) {\n return\n }\n\n // Prevent recursive calls.\n invariant(\n this.socketState !== 'mock',\n '[MockHttpSocket] Failed to respond to the \"%s %s\" request with \"%s %s\": the request has already been handled',\n this.request?.method,\n this.request?.url,\n response.status,\n response.statusText\n )\n\n // Handle \"type: error\" responses.\n if (isPropertyAccessible(response, 'type') && response.type === 'error') {\n this.errorWith(new TypeError('Network error'))\n return\n }\n\n // First, emit all the connection events\n // to emulate a successful connection.\n this.mockConnect()\n this.socketState = 'mock'\n\n // Flush the write buffer to trigger write callbacks\n // if it hasn't been flushed already (e.g. someone started reading request stream).\n this.flushWriteBuffer()\n\n // Create a `ServerResponse` instance to delegate HTTP message parsing,\n // Transfer-Encoding, and other things to Node.js internals.\n const serverResponse = new ServerResponse(new IncomingMessage(this))\n\n /**\n * Assign a mock socket instance to the server response to\n * spy on the response chunk writes. Push the transformed response chunks\n * to this `MockHttpSocket` instance to trigger the \"data\" event.\n * @note Providing the same `MockSocket` instance when creating `ServerResponse`\n * does not have the same effect.\n * @see https://github.com/nodejs/node/blob/10099bb3f7fd97bb9dd9667188426866b3098e07/test/parallel/test-http-server-response-standalone.js#L32\n */\n serverResponse.assignSocket(\n new MockSocket({\n write: (chunk, encoding, callback) => {\n this.push(chunk, encoding)\n callback?.()\n },\n read() {},\n })\n )\n\n /**\n * @note Remove the `Connection` and `Date` response headers\n * injected by `ServerResponse` by default. Those are required\n * from the server but the interceptor is NOT technically a server.\n * It's confusing to add response headers that the developer didn't\n * specify themselves. They can always add these if they wish.\n * @see https://www.rfc-editor.org/rfc/rfc9110#field.date\n * @see https://www.rfc-editor.org/rfc/rfc9110#field.connection\n */\n serverResponse.removeHeader('connection')\n serverResponse.removeHeader('date')\n\n const rawResponseHeaders = getRawFetchHeaders(response.headers)\n\n /**\n * @note Call `.writeHead` in order to set the raw response headers\n * in the same case as they were provided by the developer. Using\n * `.setHeader()`/`.appendHeader()` normalizes header names.\n */\n serverResponse.writeHead(\n response.status,\n response.statusText || STATUS_CODES[response.status],\n rawResponseHeaders\n )\n\n // If the developer destroy the socket, gracefully destroy the response.\n this.once('error', () => {\n serverResponse.destroy()\n })\n\n if (response.body) {\n try {\n const reader = response.body.getReader()\n\n while (true) {\n const { done, value } = await reader.read()\n\n if (done) {\n serverResponse.end()\n break\n }\n\n serverResponse.write(value)\n }\n } catch (error) {\n if (error instanceof Error) {\n serverResponse.destroy()\n /**\n * @note Destroy the request socket gracefully.\n * Response stream errors do NOT produce request errors.\n */\n this.destroy()\n return\n }\n\n serverResponse.destroy()\n throw error\n }\n } else {\n serverResponse.end()\n }\n\n // Close the socket if the connection wasn't marked as keep-alive.\n if (!this.shouldKeepAlive) {\n this.emit('readable')\n\n /**\n * @todo @fixme This is likely a hack.\n * Since we push null to the socket, it never propagates to the\n * parser, and the parser never calls \"onResponseEnd\" to close\n * the response stream. We are closing the stream here manually\n * but that shouldn't be the case.\n */\n this.responseStream?.push(null)\n this.push(null)\n }\n }\n\n /**\n * Close this socket connection with the given error.\n */\n public errorWith(error?: Error): void {\n this.destroy(error)\n }\n\n private mockConnect(): void {\n // Calling this method immediately puts the socket\n // into the connected state.\n this.connecting = false\n\n const isIPv6 =\n net.isIPv6(this.connectionOptions.hostname) ||\n this.connectionOptions.family === 6\n const addressInfo = {\n address: isIPv6 ? '::1' : '127.0.0.1',\n family: isIPv6 ? 'IPv6' : 'IPv4',\n port: this.connectionOptions.port,\n }\n // Return fake address information for the socket.\n this.address = () => addressInfo\n this.emit(\n 'lookup',\n null,\n addressInfo.address,\n addressInfo.family === 'IPv6' ? 6 : 4,\n this.connectionOptions.host\n )\n this.emit('connect')\n this.emit('ready')\n\n if (this.baseUrl.protocol === 'https:') {\n this.emit('secure')\n this.emit('secureConnect')\n\n // A single TLS connection is represented by two \"session\" events.\n this.emit(\n 'session',\n this.connectionOptions.session ||\n Buffer.from('mock-session-renegotiate')\n )\n this.emit('session', Buffer.from('mock-session-resume'))\n }\n }\n\n private flushWriteBuffer(): void {\n for (const writeCall of this.writeBuffer) {\n if (typeof writeCall[2] === 'function') {\n writeCall[2]()\n /**\n * @note Remove the callback from the write call\n * so it doesn't get called twice on passthrough\n * if `request.end()` was called within `request.write()`.\n * @see https://github.com/mswjs/interceptors/issues/684\n */\n writeCall[2] = undefined\n }\n }\n }\n\n /**\n * This callback might be called when the request is \"slow\":\n * - Request headers were fragmented across multiple TCP packages;\n * - Request headers were too large to be processed in a single run\n * (e.g. more than 30 request headers).\n * @note This is called before request start.\n */\n private onRequestHeaders: HeadersCallback = (rawHeaders) => {\n this.requestRawHeadersBuffer.push(...rawHeaders)\n }\n\n private onRequestStart: RequestHeadersCompleteCallback = (\n versionMajor,\n versionMinor,\n rawHeaders,\n _,\n path,\n __,\n ___,\n ____,\n shouldKeepAlive\n ) => {\n this.shouldKeepAlive = shouldKeepAlive\n\n const url = new URL(path || '', this.baseUrl)\n const method = this.connectionOptions.method?.toUpperCase() || 'GET'\n const headers = FetchResponse.parseRawHeaders([\n ...this.requestRawHeadersBuffer,\n ...(rawHeaders || []),\n ])\n this.requestRawHeadersBuffer.length = 0\n\n const canHaveBody = method !== 'GET' && method !== 'HEAD'\n\n // Translate the basic authorization in the URL to the request header.\n // Constructing a Request instance with a URL containing auth is no-op.\n if (url.username || url.password) {\n if (!headers.has('authorization')) {\n headers.set('authorization', `Basic ${url.username}:${url.password}`)\n }\n url.username = ''\n url.password = ''\n }\n\n // Create a new stream for each request.\n // If this Socket is reused for multiple requests,\n // this ensures that each request gets its own stream.\n // One Socket instance can only handle one request at a time.\n this.requestStream = new Readable({\n /**\n * @note Provide the `read()` method so a `Readable` could be\n * used as the actual request body (the stream calls \"read()\").\n * We control the queue in the onRequestBody/End functions.\n */\n read: () => {\n // If the user attempts to read the request body,\n // flush the write buffer to trigger the callbacks.\n // This way, if the request stream ends in the write callback,\n // it will indeed end correctly.\n this.flushWriteBuffer()\n },\n })\n\n const requestId = createRequestId()\n this.request = new FetchRequest(url, {\n method,\n headers,\n credentials: 'same-origin',\n // @ts-expect-error Undocumented Fetch property.\n duplex: canHaveBody ? 'half' : undefined,\n body: canHaveBody ? (Readable.toWeb(this.requestStream!) as any) : null,\n })\n\n Reflect.set(this.request, kRequestId, requestId)\n\n // Set the raw `http.ClientRequest` instance on the request instance.\n // This is useful for cases like getting the raw headers of the request.\n setRawRequest(this.request, Reflect.get(this, '_httpMessage'))\n\n // Create a copy of the request body stream and store it on the request.\n // This is only needed for the consumers who wish to read the request body stream\n // of requests that cannot have a body per Fetch API specification (i.e. GET, HEAD).\n setRawRequestBodyStream(this.request, this.requestStream)\n\n // Skip handling the request that's already being handled\n // by another (parent) interceptor. For example, XMLHttpRequest\n // is often implemented via ClientRequest in Node.js (e.g. JSDOM).\n // In that case, XHR interceptor will bubble down to the ClientRequest\n // interceptor. No need to try to handle that request again.\n /**\n * @fixme Stop relying on the \"X-Request-Id\" request header\n * to figure out if one interceptor has been invoked within another.\n * @see https://github.com/mswjs/interceptors/issues/378\n */\n if (this.request.headers.has(INTERNAL_REQUEST_ID_HEADER_NAME)) {\n this.passthrough()\n return\n }\n\n this.onRequest({\n requestId,\n request: this.request,\n socket: this,\n })\n }\n\n private onRequestBody(chunk: Buffer): void {\n invariant(\n this.requestStream,\n 'Failed to write to a request stream: stream does not exist'\n )\n\n this.requestStream.push(chunk)\n }\n\n private onRequestEnd(): void {\n // Request end can be called for requests without body.\n if (this.requestStream) {\n this.requestStream.push(null)\n }\n }\n\n /**\n * This callback might be called when the response is \"slow\":\n * - Response headers were fragmented across multiple TCP packages;\n * - Response headers were too large to be processed in a single run\n * (e.g. more than 30 response headers).\n * @note This is called before response start.\n */\n private onResponseHeaders: HeadersCallback = (rawHeaders) => {\n this.responseRawHeadersBuffer.push(...rawHeaders)\n }\n\n private onResponseStart: ResponseHeadersCompleteCallback = (\n versionMajor,\n versionMinor,\n rawHeaders,\n method,\n url,\n status,\n statusText\n ) => {\n const headers = FetchResponse.parseRawHeaders([\n ...this.responseRawHeadersBuffer,\n ...(rawHeaders || []),\n ])\n this.responseRawHeadersBuffer.length = 0\n\n const response = new FetchResponse(\n /**\n * @note The Fetch API response instance exposed to the consumer\n * is created over the response stream of the HTTP parser. It is NOT\n * related to the Socket instance. This way, you can read response body\n * in response listener while the Socket instance delays the emission\n * of \"end\" and other events until those response listeners are finished.\n */\n FetchResponse.isResponseWithBody(status)\n ? (Readable.toWeb(\n (this.responseStream = new Readable({ read() {} }))\n ) as any)\n : null,\n {\n url,\n status,\n statusText,\n headers,\n }\n )\n\n invariant(\n this.request,\n 'Failed to handle a response: request does not exist'\n )\n\n FetchResponse.setUrl(this.request.url, response)\n\n /**\n * @fixme Stop relying on the \"X-Request-Id\" request header\n * to figure out if one interceptor has been invoked within another.\n * @see https://github.com/mswjs/interceptors/issues/378\n */\n if (this.request.headers.has(INTERNAL_REQUEST_ID_HEADER_NAME)) {\n return\n }\n\n this.responseListenersPromise = this.onResponse({\n response,\n isMockedResponse: this.socketState === 'mock',\n requestId: Reflect.get(this.request, kRequestId),\n request: this.request,\n socket: this,\n })\n }\n\n private onResponseBody(chunk: Buffer) {\n invariant(\n this.responseStream,\n 'Failed to write to a response stream: stream does not exist'\n )\n\n this.responseStream.push(chunk)\n }\n\n private onResponseEnd(): void {\n // Response end can be called for responses without body.\n if (this.responseStream) {\n this.responseStream.push(null)\n }\n }\n}\n","/**\n * Here's how requests are handled in Node.js:\n *\n * 1. http.ClientRequest instance calls `agent.addRequest(request, options, cb)`.\n * 2. Agent creates a new socket: `agent.createSocket(options, cb)`.\n * 3. Agent creates a new connection: `agent.createConnection(options, cb)`.\n */\nimport net from 'node:net'\nimport http from 'node:http'\nimport https from 'node:https'\nimport {\n MockHttpSocket,\n type MockHttpSocketRequestCallback,\n type MockHttpSocketResponseCallback,\n} from './MockHttpSocket'\n\ndeclare module 'node:http' {\n interface Agent {\n options?: http.AgentOptions\n createConnection(options: any, callback: any): net.Socket\n }\n}\n\ninterface MockAgentOptions {\n customAgent?: http.RequestOptions['agent']\n onRequest: MockHttpSocketRequestCallback\n onResponse: MockHttpSocketResponseCallback\n}\n\nexport class MockAgent extends http.Agent {\n private customAgent?: http.RequestOptions['agent']\n private onRequest: MockHttpSocketRequestCallback\n private onResponse: MockHttpSocketResponseCallback\n\n constructor(options: MockAgentOptions) {\n super()\n this.customAgent = options.customAgent\n this.onRequest = options.onRequest\n this.onResponse = options.onResponse\n }\n\n public createConnection(options: any, callback: any): net.Socket {\n const createConnection =\n this.customAgent instanceof http.Agent\n ? this.customAgent.createConnection\n : super.createConnection\n\n const createConnectionOptions =\n this.customAgent instanceof http.Agent\n ? {\n ...options,\n ...this.customAgent.options,\n }\n : options\n\n const socket = new MockHttpSocket({\n connectionOptions: options,\n createConnection: createConnection.bind(\n this.customAgent || this,\n createConnectionOptions,\n callback\n ),\n onRequest: this.onRequest.bind(this),\n onResponse: this.onResponse.bind(this),\n })\n\n return socket\n }\n}\n\nexport class MockHttpsAgent extends https.Agent {\n private customAgent?: https.RequestOptions['agent']\n private onRequest: MockHttpSocketRequestCallback\n private onResponse: MockHttpSocketResponseCallback\n\n constructor(options: MockAgentOptions) {\n super()\n this.customAgent = options.customAgent\n this.onRequest = options.onRequest\n this.onResponse = options.onResponse\n }\n\n public createConnection(options: any, callback: any): net.Socket {\n const createConnection =\n this.customAgent instanceof http.Agent\n ? this.customAgent.createConnection\n : super.createConnection\n\n const createConnectionOptions =\n this.customAgent instanceof http.Agent\n ? {\n ...options,\n ...this.customAgent.options,\n }\n : options\n\n const socket = new MockHttpSocket({\n connectionOptions: options,\n createConnection: createConnection.bind(\n this.customAgent || this,\n createConnectionOptions,\n callback\n ),\n onRequest: this.onRequest.bind(this),\n onResponse: this.onResponse.bind(this),\n })\n\n return socket\n }\n}\n","import { Agent } from 'http'\nimport { RequestOptions, Agent as HttpsAgent } from 'https'\nimport { Logger } from '@open-draft/logger'\n\nconst logger = new Logger('utils getUrlByRequestOptions')\n\n// Request instance constructed by the \"request\" library\n// has a \"self\" property that has a \"uri\" field. This is\n// reproducible by performing a \"XMLHttpRequest\" request in JSDOM.\nexport interface RequestSelf {\n uri?: URL\n}\n\nexport type ResolvedRequestOptions = RequestOptions & RequestSelf\n\nexport const DEFAULT_PATH = '/'\nconst DEFAULT_PROTOCOL = 'http:'\nconst DEFAULT_HOSTNAME = 'localhost'\nconst SSL_PORT = 443\n\nfunction getAgent(\n options: ResolvedRequestOptions\n): Agent | HttpsAgent | undefined {\n return options.agent instanceof Agent ? options.agent : undefined\n}\n\nfunction getProtocolByRequestOptions(options: ResolvedRequestOptions): string {\n if (options.protocol) {\n return options.protocol\n }\n\n const agent = getAgent(options)\n const agentProtocol = (agent as RequestOptions)?.protocol\n\n if (agentProtocol) {\n return agentProtocol\n }\n\n const port = getPortByRequestOptions(options)\n const isSecureRequest = options.cert || port === SSL_PORT\n\n return isSecureRequest ? 'https:' : options.uri?.protocol || DEFAULT_PROTOCOL\n}\n\nfunction getPortByRequestOptions(\n options: ResolvedRequestOptions\n): number | undefined {\n // Use the explicitly provided port.\n if (options.port) {\n return Number(options.port)\n }\n\n // Otherwise, try to resolve port from the agent.\n const agent = getAgent(options)\n\n if ((agent as HttpsAgent)?.options.port) {\n return Number((agent as HttpsAgent).options.port)\n }\n\n if ((agent as RequestOptions)?.defaultPort) {\n return Number((agent as RequestOptions).defaultPort)\n }\n\n // Lastly, return undefined indicating that the port\n // must inferred from the protocol. Do not infer it here.\n return undefined\n}\n\ninterface RequestAuth {\n username: string\n password: string\n}\n\nfunction getAuthByRequestOptions(\n options: ResolvedRequestOptions\n): RequestAuth | undefined {\n if (options.auth) {\n const [username, password] = options.auth.split(':')\n return { username, password }\n }\n}\n\n/**\n * Returns true if host looks like an IPv6 address without surrounding brackets\n * It assumes any host containing `:` is definitely not IPv4 and probably IPv6,\n * but note that this could include invalid IPv6 addresses as well.\n */\nfunction isRawIPv6Address(host: string): boolean {\n return host.includes(':') && !host.startsWith('[') && !host.endsWith(']')\n}\n\nfunction getHostname(options: ResolvedRequestOptions): string | undefined {\n let host = options.hostname || options.host\n\n if (host) {\n if (isRawIPv6Address(host)) {\n host = `[${host}]`\n }\n\n // Check the presence of the port, and if it's present,\n // remove it from the host, returning a hostname.\n return new URL(`http://${host}`).hostname\n }\n\n return DEFAULT_HOSTNAME\n}\n\n/**\n * Creates a `URL` instance from a given `RequestOptions` object.\n */\nexport function getUrlByRequestOptions(options: ResolvedRequestOptions): URL {\n logger.info('request options', options)\n\n if (options.uri) {\n logger.info(\n 'constructing url from explicitly provided \"options.uri\": %s',\n options.uri\n )\n return new URL(options.uri.href)\n }\n\n logger.info('figuring out url from request options...')\n\n const protocol = getProtocolByRequestOptions(options)\n logger.info('protocol', protocol)\n\n const port = getPortByRequestOptions(options)\n logger.info('port', port)\n\n const hostname = getHostname(options)\n logger.info('hostname', hostname)\n\n const path = options.path || DEFAULT_PATH\n logger.info('path', path)\n\n const credentials = getAuthByRequestOptions(options)\n logger.info('credentials', credentials)\n\n const authString = credentials\n ? `${credentials.username}:${credentials.password}@`\n : ''\n logger.info('auth string:', authString)\n\n const portString = typeof port !== 'undefined' ? `:${port}` : ''\n const url = new URL(`${protocol}//${hostname}${portString}${path}`)\n url.username = credentials?.username || ''\n url.password = credentials?.password || ''\n\n logger.info('created url:', url)\n\n return url\n}\n","import { Logger } from '@open-draft/logger'\n\nconst logger = new Logger('cloneObject')\n\nfunction isPlainObject(obj?: Record): boolean {\n logger.info('is plain object?', obj)\n\n if (obj == null || !obj.constructor?.name) {\n logger.info('given object is undefined, not a plain object...')\n return false\n }\n\n logger.info('checking the object constructor:', obj.constructor.name)\n return obj.constructor.name === 'Object'\n}\n\nexport function cloneObject>(\n obj: ObjectType\n): ObjectType {\n logger.info('cloning object:', obj)\n\n const enumerableProperties = Object.entries(obj).reduce>(\n (acc, [key, value]) => {\n logger.info('analyzing key-value pair:', key, value)\n\n // Recursively clone only plain objects, omitting class instances.\n acc[key] = isPlainObject(value) ? cloneObject(value) : value\n return acc\n },\n {}\n )\n\n return isPlainObject(obj)\n ? enumerableProperties\n : Object.assign(Object.getPrototypeOf(obj), enumerableProperties)\n}\n","import { urlToHttpOptions } from 'node:url'\nimport {\n Agent as HttpAgent,\n globalAgent as httpGlobalAgent,\n IncomingMessage,\n} from 'node:http'\nimport {\n RequestOptions,\n Agent as HttpsAgent,\n globalAgent as httpsGlobalAgent,\n} from 'node:https'\nimport {\n /**\n * @note Use the Node.js URL instead of the global URL\n * because environments like JSDOM may override the global,\n * breaking the compatibility with Node.js.\n * @see https://github.com/node-fetch/node-fetch/issues/1376#issuecomment-966435555\n */\n URL,\n Url as LegacyURL,\n parse as parseUrl,\n} from 'node:url'\nimport { Logger } from '@open-draft/logger'\nimport {\n ResolvedRequestOptions,\n getUrlByRequestOptions,\n} from '../../../utils/getUrlByRequestOptions'\nimport { cloneObject } from '../../../utils/cloneObject'\nimport { isObject } from '../../../utils/isObject'\n\nconst logger = new Logger('http normalizeClientRequestArgs')\n\nexport type HttpRequestCallback = (response: IncomingMessage) => void\n\nexport type ClientRequestArgs =\n // Request without any arguments is also possible.\n | []\n | [string | URL | LegacyURL, HttpRequestCallback?]\n | [string | URL | LegacyURL, RequestOptions, HttpRequestCallback?]\n | [RequestOptions, HttpRequestCallback?]\n\nfunction resolveRequestOptions(\n args: ClientRequestArgs,\n url: URL\n): RequestOptions {\n // Calling `fetch` provides only URL to `ClientRequest`\n // without any `RequestOptions` or callback.\n if (typeof args[1] === 'undefined' || typeof args[1] === 'function') {\n logger.info('request options not provided, deriving from the url', url)\n return urlToHttpOptions(url)\n }\n\n if (args[1]) {\n logger.info('has custom RequestOptions!', args[1])\n const requestOptionsFromUrl = urlToHttpOptions(url)\n\n logger.info('derived RequestOptions from the URL:', requestOptionsFromUrl)\n\n /**\n * Clone the request options to lock their state\n * at the moment they are provided to `ClientRequest`.\n * @see https://github.com/mswjs/interceptors/issues/86\n */\n logger.info('cloning RequestOptions...')\n const clonedRequestOptions = cloneObject(args[1])\n logger.info('successfully cloned RequestOptions!', clonedRequestOptions)\n\n return {\n ...requestOptionsFromUrl,\n ...clonedRequestOptions,\n }\n }\n\n logger.info('using an empty object as request options')\n return {} as RequestOptions\n}\n\n/**\n * Overrides the given `URL` instance with the explicit properties provided\n * on the `RequestOptions` object. The options object takes precedence,\n * and will replace URL properties like \"host\", \"path\", and \"port\", if specified.\n */\nfunction overrideUrlByRequestOptions(url: URL, options: RequestOptions): URL {\n url.host = options.host || url.host\n url.hostname = options.hostname || url.hostname\n url.port = options.port ? options.port.toString() : url.port\n\n if (options.path) {\n const parsedOptionsPath = parseUrl(options.path, false)\n url.pathname = parsedOptionsPath.pathname || ''\n url.search = parsedOptionsPath.search || ''\n }\n\n return url\n}\n\nfunction resolveCallback(\n args: ClientRequestArgs\n): HttpRequestCallback | undefined {\n return typeof args[1] === 'function' ? args[1] : args[2]\n}\n\nexport type NormalizedClientRequestArgs = [\n url: URL,\n options: ResolvedRequestOptions,\n callback?: HttpRequestCallback\n]\n\n/**\n * Normalizes parameters given to a `http.request` call\n * so it always has a `URL` and `RequestOptions`.\n */\nexport function normalizeClientRequestArgs(\n defaultProtocol: string,\n args: ClientRequestArgs\n): NormalizedClientRequestArgs {\n let url: URL\n let options: ResolvedRequestOptions\n let callback: HttpRequestCallback | undefined\n\n logger.info('arguments', args)\n logger.info('using default protocol:', defaultProtocol)\n\n // Support \"http.request()\" calls without any arguments.\n // That call results in a \"GET http://localhost\" request.\n if (args.length === 0) {\n const url = new URL('http://localhost')\n const options = resolveRequestOptions(args, url)\n return [url, options]\n }\n\n // Convert a url string into a URL instance\n // and derive request options from it.\n if (typeof args[0] === 'string') {\n logger.info('first argument is a location string:', args[0])\n\n url = new URL(args[0])\n logger.info('created a url:', url)\n\n const requestOptionsFromUrl = urlToHttpOptions(url)\n logger.info('request options from url:', requestOptionsFromUrl)\n\n options = resolveRequestOptions(args, url)\n logger.info('resolved request options:', options)\n\n callback = resolveCallback(args)\n }\n // Handle a given URL instance as-is\n // and derive request options from it.\n else if (args[0] instanceof URL) {\n url = args[0]\n logger.info('first argument is a URL:', url)\n\n // Check if the second provided argument is RequestOptions.\n // If it is, check if \"options.path\" was set and rewrite it\n // on the input URL.\n // Do this before resolving options from the URL below\n // to prevent query string from being duplicated in the path.\n if (typeof args[1] !== 'undefined' && isObject(args[1])) {\n url = overrideUrlByRequestOptions(url, args[1])\n }\n\n options = resolveRequestOptions(args, url)\n logger.info('derived request options:', options)\n\n callback = resolveCallback(args)\n }\n // Handle a legacy URL instance and re-normalize from either a RequestOptions object\n // or a WHATWG URL.\n else if ('hash' in args[0] && !('method' in args[0])) {\n const [legacyUrl] = args\n logger.info('first argument is a legacy URL:', legacyUrl)\n\n if (legacyUrl.hostname === null) {\n /**\n * We are dealing with a relative url, so use the path as an \"option\" and\n * merge in any existing options, giving priority to existing options -- i.e. a path in any\n * existing options will take precedence over the one contained in the url. This is consistent\n * with the behaviour in ClientRequest.\n * @see https://github.com/nodejs/node/blob/d84f1312915fe45fe0febe888db692c74894c382/lib/_http_client.js#L122\n */\n logger.info('given legacy URL is relative (no hostname)')\n\n return isObject(args[1])\n ? normalizeClientRequestArgs(defaultProtocol, [\n { path: legacyUrl.path, ...args[1] },\n args[2],\n ])\n : normalizeClientRequestArgs(defaultProtocol, [\n { path: legacyUrl.path },\n args[1] as HttpRequestCallback,\n ])\n }\n\n logger.info('given legacy url is absolute')\n\n // We are dealing with an absolute URL, so convert to WHATWG and try again.\n const resolvedUrl = new URL(legacyUrl.href)\n\n return args[1] === undefined\n ? normalizeClientRequestArgs(defaultProtocol, [resolvedUrl])\n : typeof args[1] === 'function'\n ? normalizeClientRequestArgs(defaultProtocol, [resolvedUrl, args[1]])\n : normalizeClientRequestArgs(defaultProtocol, [\n resolvedUrl,\n args[1],\n args[2],\n ])\n }\n // Handle a given \"RequestOptions\" object as-is\n // and derive the URL instance from it.\n else if (isObject(args[0])) {\n options = { ...(args[0] as any) }\n logger.info('first argument is RequestOptions:', options)\n\n // When handling a \"RequestOptions\" object without an explicit \"protocol\",\n // infer the protocol from the request issuing module (http/https).\n options.protocol = options.protocol || defaultProtocol\n logger.info('normalized request options:', options)\n\n url = getUrlByRequestOptions(options)\n logger.info('created a URL from RequestOptions:', url.href)\n\n callback = resolveCallback(args)\n } else {\n throw new Error(\n `Failed to construct ClientRequest with these parameters: ${args}`\n )\n }\n\n options.protocol = options.protocol || url.protocol\n options.method = options.method || 'GET'\n\n /**\n * Ensure that the default Agent is always set.\n * This prevents the protocol mismatch for requests with { agent: false },\n * where the global Agent is inferred.\n * @see https://github.com/mswjs/msw/issues/1150\n * @see https://github.com/nodejs/node/blob/418ff70b810f0e7112d48baaa72932a56cfa213b/lib/_http_client.js#L130\n * @see https://github.com/nodejs/node/blob/418ff70b810f0e7112d48baaa72932a56cfa213b/lib/_http_client.js#L157-L159\n */\n if (!options._defaultAgent) {\n logger.info(\n 'has no default agent, setting the default agent for \"%s\"',\n options.protocol\n )\n\n options._defaultAgent =\n options.protocol === 'https:' ? httpsGlobalAgent : httpGlobalAgent\n }\n\n logger.info('successfully resolved url:', url.href)\n logger.info('successfully resolved options:', options)\n logger.info('successfully resolved callback:', callback)\n\n /**\n * @note If the user-provided URL is not a valid URL in Node.js,\n * (e.g. the one provided by the JSDOM polyfills), case it to\n * string. Otherwise, this throws on Node.js incompatibility\n * (`ERR_INVALID_ARG_TYPE` on the connection listener)\n * @see https://github.com/node-fetch/node-fetch/issues/1376#issuecomment-966435555\n */\n if (!(url instanceof URL)) {\n url = (url as any).toString()\n }\n\n return [url, options, callback]\n}\n","import http from 'node:http'\nimport https from 'node:https'\nimport { Interceptor } from '../../Interceptor'\nimport type { HttpRequestEventMap } from '../../glossary'\nimport {\n kRequestId,\n MockHttpSocketRequestCallback,\n MockHttpSocketResponseCallback,\n} from './MockHttpSocket'\nimport { MockAgent, MockHttpsAgent } from './agents'\nimport { RequestController } from '../../RequestController'\nimport { emitAsync } from '../../utils/emitAsync'\nimport { normalizeClientRequestArgs } from './utils/normalizeClientRequestArgs'\nimport { handleRequest } from '../../utils/handleRequest'\nimport {\n recordRawFetchHeaders,\n restoreHeadersPrototype,\n} from './utils/recordRawHeaders'\n\nexport class ClientRequestInterceptor extends Interceptor {\n static symbol = Symbol.for('client-request-interceptor')\n\n constructor() {\n super(ClientRequestInterceptor.symbol)\n }\n\n protected setup(): void {\n const {\n ClientRequest: OriginalClientRequest,\n get: originalGet,\n request: originalRequest,\n } = http\n const { get: originalHttpsGet, request: originalHttpsRequest } = https\n\n const onRequest = this.onRequest.bind(this)\n const onResponse = this.onResponse.bind(this)\n\n // Support requests performed via the `ClientRequest` constructor directly.\n http.ClientRequest = new Proxy(http.ClientRequest, {\n construct: (target, args: Parameters) => {\n const [url, options, callback] = normalizeClientRequestArgs(\n 'http:',\n args\n )\n\n // Create a mock agent instance appropriate for the request protocol.\n const Agent = options.protocol === 'https:' ? MockHttpsAgent : MockAgent\n const mockAgent = new Agent({\n customAgent: options.agent,\n onRequest,\n onResponse,\n })\n options.agent = mockAgent\n\n return Reflect.construct(target, [url, options, callback])\n },\n })\n\n http.request = new Proxy(http.request, {\n apply: (target, thisArg, args: Parameters) => {\n const [url, options, callback] = normalizeClientRequestArgs(\n 'http:',\n args\n )\n const mockAgent = new MockAgent({\n customAgent: options.agent,\n onRequest,\n onResponse,\n })\n options.agent = mockAgent\n\n return Reflect.apply(target, thisArg, [url, options, callback])\n },\n })\n\n http.get = new Proxy(http.get, {\n apply: (target, thisArg, args: Parameters) => {\n const [url, options, callback] = normalizeClientRequestArgs(\n 'http:',\n args\n )\n\n const mockAgent = new MockAgent({\n customAgent: options.agent,\n onRequest,\n onResponse,\n })\n options.agent = mockAgent\n\n return Reflect.apply(target, thisArg, [url, options, callback])\n },\n })\n\n //\n // HTTPS.\n //\n\n https.request = new Proxy(https.request, {\n apply: (target, thisArg, args: Parameters) => {\n const [url, options, callback] = normalizeClientRequestArgs(\n 'https:',\n args\n )\n\n const mockAgent = new MockHttpsAgent({\n customAgent: options.agent,\n onRequest,\n onResponse,\n })\n options.agent = mockAgent\n\n return Reflect.apply(target, thisArg, [url, options, callback])\n },\n })\n\n https.get = new Proxy(https.get, {\n apply: (target, thisArg, args: Parameters) => {\n const [url, options, callback] = normalizeClientRequestArgs(\n 'https:',\n args\n )\n\n const mockAgent = new MockHttpsAgent({\n customAgent: options.agent,\n onRequest,\n onResponse,\n })\n options.agent = mockAgent\n\n return Reflect.apply(target, thisArg, [url, options, callback])\n },\n })\n\n // Spy on `Header.prototype.set` and `Header.prototype.append` calls\n // and record the raw header names provided. This is to support\n // `IncomingMessage.prototype.rawHeaders`.\n recordRawFetchHeaders()\n\n this.subscriptions.push(() => {\n http.ClientRequest = OriginalClientRequest\n\n http.get = originalGet\n http.request = originalRequest\n\n https.get = originalHttpsGet\n https.request = originalHttpsRequest\n\n restoreHeadersPrototype()\n })\n }\n\n private onRequest: MockHttpSocketRequestCallback = async ({\n request,\n socket,\n }) => {\n const controller = new RequestController(request, {\n passthrough() {\n socket.passthrough()\n },\n async respondWith(response) {\n await socket.respondWith(response)\n },\n errorWith(reason) {\n if (reason instanceof Error) {\n socket.errorWith(reason)\n }\n },\n })\n\n await handleRequest({\n request,\n requestId: Reflect.get(request, kRequestId),\n controller,\n emitter: this.emitter,\n })\n }\n\n public onResponse: MockHttpSocketResponseCallback = async ({\n requestId,\n request,\n response,\n isMockedResponse,\n }) => {\n // Return the promise to when all the response event listeners\n // are finished.\n return emitAsync(this.emitter, 'response', {\n requestId,\n request,\n response,\n isMockedResponse,\n })\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAgBA,SAAgB,yBACd,MAC2B;CAC3B,MAAMA,aAAwC;EAAC,KAAK;EAAI;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AM,UAAU;AAEhB,4BAAyB;IACzB"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/Interceptor-BsZ21ue0.d.cts b/node_modules/@mswjs/interceptors/lib/node/Interceptor-BsZ21ue0.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..0d85408f3c462fdc5ae0dce1c504b7914ab0c88d --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/Interceptor-BsZ21ue0.d.cts @@ -0,0 +1,132 @@ +import { Logger } from "@open-draft/logger"; +import { Emitter, Listener } from "strict-event-emitter"; + +//#region src/RequestController.d.ts +interface RequestControllerSource { + passthrough(): void; + respondWith(response: Response): void; + errorWith(reason?: unknown): void; +} +declare class RequestController { + #private; + protected readonly request: Request; + protected readonly source: RequestControllerSource; + static PENDING: 0; + static PASSTHROUGH: 1; + static RESPONSE: 2; + static ERROR: 3; + readyState: number; + /** + * A Promise that resolves when this controller handles a request. + * See `controller.readyState` for more information on the handling result. + */ + handled: Promise; + constructor(request: Request, source: RequestControllerSource); + /** + * Perform this request as-is. + */ + passthrough(): Promise; + /** + * Respond to this request with the given `Response` instance. + * + * @example + * controller.respondWith(new Response()) + * controller.respondWith(Response.json({ id })) + * controller.respondWith(Response.error()) + */ + respondWith(response: Response): void; + /** + * Error this request with the given reason. + * + * @example + * controller.errorWith() + * controller.errorWith(new Error('Oops!')) + * controller.errorWith({ message: 'Oops!'}) + */ + errorWith(reason?: unknown): void; +} +//#endregion +//#region src/glossary.d.ts +type RequestCredentials = 'omit' | 'include' | 'same-origin'; +type HttpRequestEventMap = { + request: [args: { + request: Request; + requestId: string; + controller: RequestController; + }]; + response: [args: { + response: Response; + isMockedResponse: boolean; + request: Request; + requestId: string; + }]; + unhandledException: [args: { + error: unknown; + request: Request; + requestId: string; + controller: RequestController; + }]; +}; +//#endregion +//#region src/Interceptor.d.ts +type InterceptorEventMap = Record; +type InterceptorSubscription = () => void; +/** + * Request header name to detect when a single request + * is being handled by nested interceptors (XHR -> ClientRequest). + * Obscure by design to prevent collisions with user-defined headers. + * Ideally, come up with the Interceptor-level mechanism for this. + * @see https://github.com/mswjs/interceptors/issues/378 + */ +declare const INTERNAL_REQUEST_ID_HEADER_NAME = "x-interceptors-internal-request-id"; +declare function getGlobalSymbol(symbol: Symbol): V | undefined; +declare function deleteGlobalSymbol(symbol: Symbol): void; +declare enum InterceptorReadyState { + INACTIVE = "INACTIVE", + APPLYING = "APPLYING", + APPLIED = "APPLIED", + DISPOSING = "DISPOSING", + DISPOSED = "DISPOSED", +} +type ExtractEventNames> = Events extends Record ? EventName : never; +declare class Interceptor { + private readonly symbol; + protected emitter: Emitter; + protected subscriptions: Array; + protected logger: Logger; + readyState: InterceptorReadyState; + constructor(symbol: symbol); + /** + * Determine if this interceptor can be applied + * in the current environment. + */ + protected checkEnvironment(): boolean; + /** + * Apply this interceptor to the current process. + * Returns an already running interceptor instance if it's present. + */ + apply(): void; + /** + * Setup the module augments and stubs necessary for this interceptor. + * This method is not run if there's a running interceptor instance + * to prevent instantiating an interceptor multiple times. + */ + protected setup(): void; + /** + * Listen to the interceptor's public events. + */ + on>(event: EventName, listener: Listener): this; + once>(event: EventName, listener: Listener): this; + off>(event: EventName, listener: Listener): this; + removeAllListeners>(event?: EventName): this; + /** + * Disposes of any side-effects this interceptor has introduced. + */ + dispose(): void; + private getInstance; + private setInstance; + private clearInstance; +} +//#endregion +export { InterceptorReadyState as a, getGlobalSymbol as c, RequestController as d, RequestControllerSource as f, InterceptorEventMap as i, HttpRequestEventMap as l, INTERNAL_REQUEST_ID_HEADER_NAME as n, InterceptorSubscription as o, Interceptor as r, deleteGlobalSymbol as s, ExtractEventNames as t, RequestCredentials as u }; +//# sourceMappingURL=Interceptor-BsZ21ue0.d.cts.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/Interceptor-soD-WpQO.d.mts b/node_modules/@mswjs/interceptors/lib/node/Interceptor-soD-WpQO.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..fc5a303509ce5f6ccf9f34f518d70360ff25e572 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/Interceptor-soD-WpQO.d.mts @@ -0,0 +1,132 @@ +import { Logger } from "@open-draft/logger"; +import { Emitter, Listener } from "strict-event-emitter"; + +//#region src/RequestController.d.ts +interface RequestControllerSource { + passthrough(): void; + respondWith(response: Response): void; + errorWith(reason?: unknown): void; +} +declare class RequestController { + #private; + protected readonly request: Request; + protected readonly source: RequestControllerSource; + static PENDING: 0; + static PASSTHROUGH: 1; + static RESPONSE: 2; + static ERROR: 3; + readyState: number; + /** + * A Promise that resolves when this controller handles a request. + * See `controller.readyState` for more information on the handling result. + */ + handled: Promise; + constructor(request: Request, source: RequestControllerSource); + /** + * Perform this request as-is. + */ + passthrough(): Promise; + /** + * Respond to this request with the given `Response` instance. + * + * @example + * controller.respondWith(new Response()) + * controller.respondWith(Response.json({ id })) + * controller.respondWith(Response.error()) + */ + respondWith(response: Response): void; + /** + * Error this request with the given reason. + * + * @example + * controller.errorWith() + * controller.errorWith(new Error('Oops!')) + * controller.errorWith({ message: 'Oops!'}) + */ + errorWith(reason?: unknown): void; +} +//#endregion +//#region src/glossary.d.ts +type RequestCredentials = 'omit' | 'include' | 'same-origin'; +type HttpRequestEventMap = { + request: [args: { + request: Request; + requestId: string; + controller: RequestController; + }]; + response: [args: { + response: Response; + isMockedResponse: boolean; + request: Request; + requestId: string; + }]; + unhandledException: [args: { + error: unknown; + request: Request; + requestId: string; + controller: RequestController; + }]; +}; +//#endregion +//#region src/Interceptor.d.ts +type InterceptorEventMap = Record; +type InterceptorSubscription = () => void; +/** + * Request header name to detect when a single request + * is being handled by nested interceptors (XHR -> ClientRequest). + * Obscure by design to prevent collisions with user-defined headers. + * Ideally, come up with the Interceptor-level mechanism for this. + * @see https://github.com/mswjs/interceptors/issues/378 + */ +declare const INTERNAL_REQUEST_ID_HEADER_NAME = "x-interceptors-internal-request-id"; +declare function getGlobalSymbol(symbol: Symbol): V | undefined; +declare function deleteGlobalSymbol(symbol: Symbol): void; +declare enum InterceptorReadyState { + INACTIVE = "INACTIVE", + APPLYING = "APPLYING", + APPLIED = "APPLIED", + DISPOSING = "DISPOSING", + DISPOSED = "DISPOSED", +} +type ExtractEventNames> = Events extends Record ? EventName : never; +declare class Interceptor { + private readonly symbol; + protected emitter: Emitter; + protected subscriptions: Array; + protected logger: Logger; + readyState: InterceptorReadyState; + constructor(symbol: symbol); + /** + * Determine if this interceptor can be applied + * in the current environment. + */ + protected checkEnvironment(): boolean; + /** + * Apply this interceptor to the current process. + * Returns an already running interceptor instance if it's present. + */ + apply(): void; + /** + * Setup the module augments and stubs necessary for this interceptor. + * This method is not run if there's a running interceptor instance + * to prevent instantiating an interceptor multiple times. + */ + protected setup(): void; + /** + * Listen to the interceptor's public events. + */ + on>(event: EventName, listener: Listener): this; + once>(event: EventName, listener: Listener): this; + off>(event: EventName, listener: Listener): this; + removeAllListeners>(event?: EventName): this; + /** + * Disposes of any side-effects this interceptor has introduced. + */ + dispose(): void; + private getInstance; + private setInstance; + private clearInstance; +} +//#endregion +export { InterceptorReadyState as a, getGlobalSymbol as c, RequestController as d, RequestControllerSource as f, InterceptorEventMap as i, HttpRequestEventMap as l, INTERNAL_REQUEST_ID_HEADER_NAME as n, InterceptorSubscription as o, Interceptor as r, deleteGlobalSymbol as s, ExtractEventNames as t, RequestCredentials as u }; +//# sourceMappingURL=Interceptor-soD-WpQO.d.mts.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/RemoteHttpInterceptor.cjs b/node_modules/@mswjs/interceptors/lib/node/RemoteHttpInterceptor.cjs new file mode 100644 index 0000000000000000000000000000000000000000..473f5b43938bad491be965b440da867a8947f0e5 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/RemoteHttpInterceptor.cjs @@ -0,0 +1,155 @@ +const require_fetchUtils = require('./fetchUtils-umV5xXBy.cjs'); +const require_BatchInterceptor = require('./BatchInterceptor-BGhH8z1z.cjs'); +require('./bufferUtils-S5_-2eN4.cjs'); +const require_ClientRequest = require('./ClientRequest-2loAH7xM.cjs'); +const require_handleRequest = require('./handleRequest-C-cKYjIh.cjs'); +require('./node-DIKcnzhK.cjs'); +const require_XMLHttpRequest = require('./XMLHttpRequest-BtDNZipW.cjs'); +require('./hasConfigurableGlobal-MjY06_Ok.cjs'); +const require_fetch = require('./fetch-D2ClLNN-.cjs'); + +//#region src/RemoteHttpInterceptor.ts +var RemoteHttpInterceptor = class extends require_BatchInterceptor.BatchInterceptor { + constructor() { + super({ + name: "remote-interceptor", + interceptors: [ + new require_ClientRequest.ClientRequestInterceptor(), + new require_XMLHttpRequest.XMLHttpRequestInterceptor(), + new require_fetch.FetchInterceptor() + ] + }); + } + setup() { + super.setup(); + let handleParentMessage; + this.on("request", async ({ request, requestId, controller }) => { + const serializedRequest = JSON.stringify({ + id: requestId, + method: request.method, + url: request.url, + headers: Array.from(request.headers.entries()), + credentials: request.credentials, + body: ["GET", "HEAD"].includes(request.method) ? null : await request.text() + }); + this.logger.info("sent serialized request to the child:", serializedRequest); + process.send?.(`request:${serializedRequest}`); + const responsePromise = new Promise((resolve) => { + handleParentMessage = (message) => { + if (typeof message !== "string") return resolve(); + if (message.startsWith(`response:${requestId}`)) { + const [, serializedResponse] = message.match(/^response:.+?:(.+)$/) || []; + if (!serializedResponse) return resolve(); + const responseInit = JSON.parse(serializedResponse); + const mockedResponse = new require_fetchUtils.FetchResponse(responseInit.body, { + url: request.url, + status: responseInit.status, + statusText: responseInit.statusText, + headers: responseInit.headers + }); + /** + * @todo Support "errorWith" as well. + * This response handling from the child is incomplete. + */ + controller.respondWith(mockedResponse); + return resolve(); + } + }; + }); + this.logger.info("add \"message\" listener to the parent process", handleParentMessage); + process.addListener("message", handleParentMessage); + return responsePromise; + }); + this.subscriptions.push(() => { + process.removeListener("message", handleParentMessage); + }); + } +}; +function requestReviver(key, value) { + switch (key) { + case "url": return new URL(value); + case "headers": return new Headers(value); + default: return value; + } +} +var RemoteHttpResolver = class RemoteHttpResolver extends require_fetchUtils.Interceptor { + static { + this.symbol = Symbol.for("remote-resolver"); + } + constructor(options) { + super(RemoteHttpResolver.symbol); + this.process = options.process; + } + setup() { + const logger = this.logger.extend("setup"); + const handleChildMessage = async (message) => { + logger.info("received message from child!", message); + if (typeof message !== "string" || !message.startsWith("request:")) { + logger.info("unknown message, ignoring..."); + return; + } + const [, serializedRequest] = message.match(/^request:(.+)$/) || []; + if (!serializedRequest) return; + const requestJson = JSON.parse(serializedRequest, requestReviver); + logger.info("parsed intercepted request", requestJson); + const request = new require_fetchUtils.FetchRequest(requestJson.url, { + method: requestJson.method, + headers: new Headers(requestJson.headers), + credentials: requestJson.credentials, + body: requestJson.body + }); + const controller = new require_fetchUtils.RequestController(request, { + passthrough: () => {}, + respondWith: async (response) => { + if (require_handleRequest.isResponseError(response)) { + this.logger.info("received a network error!", { response }); + throw new Error("Not implemented"); + } + this.logger.info("received mocked response!", { response }); + const responseClone = require_fetchUtils.FetchResponse.clone(response); + const responseText = await responseClone.text(); + const serializedResponse = JSON.stringify({ + status: response.status, + statusText: response.statusText, + headers: Array.from(response.headers.entries()), + body: responseText + }); + this.process.send(`response:${requestJson.id}:${serializedResponse}`, (error) => { + if (error) return; + this.emitter.emit("response", { + request, + requestId: requestJson.id, + response: responseClone, + isMockedResponse: true + }); + }); + logger.info("sent serialized mocked response to the parent:", serializedResponse); + }, + errorWith: (reason) => { + this.logger.info("request has errored!", { error: reason }); + throw new Error("Not implemented"); + } + }); + await require_handleRequest.handleRequest({ + request, + requestId: requestJson.id, + controller, + emitter: this.emitter + }); + }; + this.subscriptions.push(() => { + this.process.removeListener("message", handleChildMessage); + logger.info("removed the \"message\" listener from the child process!"); + }); + logger.info("adding a \"message\" listener to the child process"); + this.process.addListener("message", handleChildMessage); + this.process.once("error", () => this.dispose()); + this.process.once("exit", () => this.dispose()); + } +}; + +//#endregion +exports.RemoteHttpInterceptor = RemoteHttpInterceptor; +exports.RemoteHttpResolver = RemoteHttpResolver; +exports.requestReviver = requestReviver; +//# sourceMappingURL=RemoteHttpInterceptor.cjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/RemoteHttpInterceptor.cjs.map b/node_modules/@mswjs/interceptors/lib/node/RemoteHttpInterceptor.cjs.map new file mode 100644 index 0000000000000000000000000000000000000000..6f81e22262972678124d6fc2f011671f039917c6 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/RemoteHttpInterceptor.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"RemoteHttpInterceptor.cjs","names":["BatchInterceptor","ClientRequestInterceptor","XMLHttpRequestInterceptor","FetchInterceptor","handleParentMessage: NodeJS.MessageListener","FetchResponse","Interceptor","handleChildMessage: NodeJS.MessageListener","FetchRequest","RequestController","isResponseError","handleRequest"],"sources":["../../src/RemoteHttpInterceptor.ts"],"sourcesContent":["import { ChildProcess } from 'child_process'\nimport { HttpRequestEventMap } from './glossary'\nimport { Interceptor } from './Interceptor'\nimport { BatchInterceptor } from './BatchInterceptor'\nimport { ClientRequestInterceptor } from './interceptors/ClientRequest'\nimport { XMLHttpRequestInterceptor } from './interceptors/XMLHttpRequest'\nimport { FetchInterceptor } from './interceptors/fetch'\nimport { handleRequest } from './utils/handleRequest'\nimport { RequestController } from './RequestController'\nimport { FetchRequest, FetchResponse } from './utils/fetchUtils'\nimport { isResponseError } from './utils/responseUtils'\n\nexport interface SerializedRequest {\n id: string\n url: string\n method: string\n headers: Array<[string, string]>\n credentials: RequestCredentials\n body: string\n}\n\ninterface RevivedRequest extends Omit {\n url: URL\n headers: Headers\n}\n\nexport interface SerializedResponse {\n status: number\n statusText: string\n headers: Array<[string, string]>\n body: string\n}\n\nexport class RemoteHttpInterceptor extends BatchInterceptor<\n [ClientRequestInterceptor, XMLHttpRequestInterceptor, FetchInterceptor]\n> {\n constructor() {\n super({\n name: 'remote-interceptor',\n interceptors: [\n new ClientRequestInterceptor(),\n new XMLHttpRequestInterceptor(),\n new FetchInterceptor(),\n ],\n })\n }\n\n protected setup() {\n super.setup()\n\n let handleParentMessage: NodeJS.MessageListener\n\n this.on('request', async ({ request, requestId, controller }) => {\n // Send the stringified intercepted request to\n // the parent process where the remote resolver is established.\n const serializedRequest = JSON.stringify({\n id: requestId,\n method: request.method,\n url: request.url,\n headers: Array.from(request.headers.entries()),\n credentials: request.credentials,\n body: ['GET', 'HEAD'].includes(request.method)\n ? null\n : await request.text(),\n } as SerializedRequest)\n\n this.logger.info(\n 'sent serialized request to the child:',\n serializedRequest\n )\n\n process.send?.(`request:${serializedRequest}`)\n\n const responsePromise = new Promise((resolve) => {\n handleParentMessage = (message) => {\n if (typeof message !== 'string') {\n return resolve()\n }\n\n if (message.startsWith(`response:${requestId}`)) {\n const [, serializedResponse] =\n message.match(/^response:.+?:(.+)$/) || []\n\n if (!serializedResponse) {\n return resolve()\n }\n\n const responseInit = JSON.parse(\n serializedResponse\n ) as SerializedResponse\n\n const mockedResponse = new FetchResponse(responseInit.body, {\n url: request.url,\n status: responseInit.status,\n statusText: responseInit.statusText,\n headers: responseInit.headers,\n })\n\n /**\n * @todo Support \"errorWith\" as well.\n * This response handling from the child is incomplete.\n */\n\n controller.respondWith(mockedResponse)\n return resolve()\n }\n }\n })\n\n // Listen for the mocked response message from the parent.\n this.logger.info(\n 'add \"message\" listener to the parent process',\n handleParentMessage\n )\n process.addListener('message', handleParentMessage)\n\n return responsePromise\n })\n\n this.subscriptions.push(() => {\n process.removeListener('message', handleParentMessage)\n })\n }\n}\n\nexport function requestReviver(key: string, value: any) {\n switch (key) {\n case 'url':\n return new URL(value)\n\n case 'headers':\n return new Headers(value)\n\n default:\n return value\n }\n}\n\nexport interface RemoveResolverOptions {\n process: ChildProcess\n}\n\nexport class RemoteHttpResolver extends Interceptor {\n static symbol = Symbol.for('remote-resolver')\n private process: ChildProcess\n\n constructor(options: RemoveResolverOptions) {\n super(RemoteHttpResolver.symbol)\n this.process = options.process\n }\n\n protected setup() {\n const logger = this.logger.extend('setup')\n\n const handleChildMessage: NodeJS.MessageListener = async (message) => {\n logger.info('received message from child!', message)\n\n if (typeof message !== 'string' || !message.startsWith('request:')) {\n logger.info('unknown message, ignoring...')\n return\n }\n\n const [, serializedRequest] = message.match(/^request:(.+)$/) || []\n if (!serializedRequest) {\n return\n }\n\n const requestJson = JSON.parse(\n serializedRequest,\n requestReviver\n ) as RevivedRequest\n\n logger.info('parsed intercepted request', requestJson)\n\n const request = new FetchRequest(requestJson.url, {\n method: requestJson.method,\n headers: new Headers(requestJson.headers),\n credentials: requestJson.credentials,\n body: requestJson.body,\n })\n\n const controller = new RequestController(request, {\n passthrough: () => {},\n respondWith: async (response) => {\n if (isResponseError(response)) {\n this.logger.info('received a network error!', { response })\n throw new Error('Not implemented')\n }\n\n this.logger.info('received mocked response!', { response })\n\n const responseClone = FetchResponse.clone(response)\n const responseText = await responseClone.text()\n\n // // Send the mocked response to the child process.\n const serializedResponse = JSON.stringify({\n status: response.status,\n statusText: response.statusText,\n headers: Array.from(response.headers.entries()),\n body: responseText,\n } as SerializedResponse)\n\n this.process.send(\n `response:${requestJson.id}:${serializedResponse}`,\n (error) => {\n if (error) {\n return\n }\n\n // Emit an optimistic \"response\" event at this point,\n // not to rely on the back-and-forth signaling for the sake of the event.\n this.emitter.emit('response', {\n request,\n requestId: requestJson.id,\n response: responseClone,\n isMockedResponse: true,\n })\n }\n )\n\n logger.info(\n 'sent serialized mocked response to the parent:',\n serializedResponse\n )\n },\n errorWith: (reason) => {\n this.logger.info('request has errored!', { error: reason })\n throw new Error('Not implemented')\n },\n })\n\n await handleRequest({\n request,\n requestId: requestJson.id,\n controller,\n emitter: this.emitter,\n })\n }\n\n this.subscriptions.push(() => {\n this.process.removeListener('message', handleChildMessage)\n logger.info('removed the \"message\" listener from the child process!')\n })\n\n logger.info('adding a \"message\" listener to the child process')\n this.process.addListener('message', handleChildMessage)\n\n this.process.once('error', () => this.dispose())\n this.process.once('exit', () => this.dispose())\n }\n}\n"],"mappings":";;;;;;;;;;;AAiCA,IAAa,wBAAb,c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AK,SAAS,QAAQ,SAAS,CAAC;MAC/C,MAAM;MACP,CAAuB;AAExB,UAAK,QAAQ,KACX,YAAY,YAAY,GAAG,GAAG,uBAC7B,UAAU;AACT,UAAI,MACF;AAKF,WAAK,QAAQ,KAAK,YAAY;OAC5B;OACA,WAAW,YAAY;OACvB,UAAU;OACV,kBAAkB;OACnB,CAAC;OAEL;AAED,YAAO,KACL,kDACA,mBACD;;IAEH,YAAY,WAAW;AACrB,UAAK,OAAO,KAAK,wBAAwB,EAAE,OAAO,QAAQ,CAAC;AAC3D,WAAM,IAAI,MAAM,kBAAkB;;IAErC,CAAC;AAEF,SAAMM,oCAAc;IAClB;IACA,WAAW,YAAY;IACvB;IACA,SAAS,KAAK;IACf,CAAC;;AAGJ,OAAK,cAAc,WAAW;AAC5B,QAAK,QAAQ,eAAe,WAAW,mBAAmB;AAC1D,UAAO,KAAK,2DAAyD;IACrE;AAEF,SAAO,KAAK,qDAAmD;AAC/D,OAAK,QAAQ,YAAY,WAAW,mBAAmB;AAEvD,OAAK,QAAQ,KAAK,eAAe,KAAK,SAAS,CAAC;AAChD,OAAK,QAAQ,KAAK,cAAc,KAAK,SAAS,CAAC"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/RemoteHttpInterceptor.d.cts b/node_modules/@mswjs/interceptors/lib/node/RemoteHttpInterceptor.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..b5dc1a102e6f250c4a17b410561baa75757cbd5f --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/RemoteHttpInterceptor.d.cts @@ -0,0 +1,39 @@ +import { l as HttpRequestEventMap, r as Interceptor } from "./Interceptor-BsZ21ue0.cjs"; +import { t as BatchInterceptor } from "./BatchInterceptor-KKF8Q47I.cjs"; +import { t as ClientRequestInterceptor } from "./index-BJ5E5aW-.cjs"; +import { XMLHttpRequestInterceptor } from "./interceptors/XMLHttpRequest/index.cjs"; +import { FetchInterceptor } from "./interceptors/fetch/index.cjs"; +import { ChildProcess } from "child_process"; + +//#region src/RemoteHttpInterceptor.d.ts +interface SerializedRequest { + id: string; + url: string; + method: string; + headers: Array<[string, string]>; + credentials: RequestCredentials; + body: string; +} +interface SerializedResponse { + status: number; + statusText: string; + headers: Array<[string, string]>; + body: string; +} +declare class RemoteHttpInterceptor extends BatchInterceptor<[ClientRequestInterceptor, XMLHttpRequestInterceptor, FetchInterceptor]> { + constructor(); + protected setup(): void; +} +declare function requestReviver(key: string, value: any): any; +interface RemoveResolverOptions { + process: ChildProcess; +} +declare class RemoteHttpResolver extends Interceptor { + static symbol: symbol; + private process; + constructor(options: RemoveResolverOptions); + protected setup(): void; +} +//#endregion +export { RemoteHttpInterceptor, RemoteHttpResolver, RemoveResolverOptions, SerializedRequest, SerializedResponse, requestReviver }; +//# sourceMappingURL=RemoteHttpInterceptor.d.cts.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/RemoteHttpInterceptor.d.mts b/node_modules/@mswjs/interceptors/lib/node/RemoteHttpInterceptor.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..f91173ddb83b537771ef232ce79c3914072f10cf --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/RemoteHttpInterceptor.d.mts @@ -0,0 +1,39 @@ +import { l as HttpRequestEventMap, r as Interceptor } from "./Interceptor-soD-WpQO.mjs"; +import { t as BatchInterceptor } from "./BatchInterceptor-rSr-NH_H.mjs"; +import { t as ClientRequestInterceptor } from "./index-DfoF45ih.mjs"; +import { XMLHttpRequestInterceptor } from "./interceptors/XMLHttpRequest/index.mjs"; +import { FetchInterceptor } from "./interceptors/fetch/index.mjs"; +import { ChildProcess } from "child_process"; + +//#region src/RemoteHttpInterceptor.d.ts +interface SerializedRequest { + id: string; + url: string; + method: string; + headers: Array<[string, string]>; + credentials: RequestCredentials; + body: string; +} +interface SerializedResponse { + status: number; + statusText: string; + headers: Array<[string, string]>; + body: string; +} +declare class RemoteHttpInterceptor extends BatchInterceptor<[ClientRequestInterceptor, XMLHttpRequestInterceptor, FetchInterceptor]> { + constructor(); + protected setup(): void; +} +declare function requestReviver(key: string, value: any): any; +interface RemoveResolverOptions { + process: ChildProcess; +} +declare class RemoteHttpResolver extends Interceptor { + static symbol: symbol; + private process; + constructor(options: RemoveResolverOptions); + protected setup(): void; +} +//#endregion +export { RemoteHttpInterceptor, RemoteHttpResolver, RemoveResolverOptions, SerializedRequest, SerializedResponse, requestReviver }; +//# sourceMappingURL=RemoteHttpInterceptor.d.mts.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/RemoteHttpInterceptor.mjs b/node_modules/@mswjs/interceptors/lib/node/RemoteHttpInterceptor.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ac0764a61f2118469e7089abe46696bd7a01a043 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/RemoteHttpInterceptor.mjs @@ -0,0 +1,153 @@ +import { a as RequestController, c as Interceptor, n as FetchResponse, t as FetchRequest } from "./fetchUtils-BKJ1XmiO.mjs"; +import { t as BatchInterceptor } from "./BatchInterceptor-C4-RX5rg.mjs"; +import "./bufferUtils-DxPxwff_.mjs"; +import { t as ClientRequestInterceptor } from "./ClientRequest-DGhBX21V.mjs"; +import { n as isResponseError, t as handleRequest } from "./handleRequest-FIQv5pwH.mjs"; +import "./node-lsdNwZEW.mjs"; +import { t as XMLHttpRequestInterceptor } from "./XMLHttpRequest-Dw6Wm-UU.mjs"; +import "./hasConfigurableGlobal-BiTmog1u.mjs"; +import { t as FetchInterceptor } from "./fetch-CaC3rGEu.mjs"; + +//#region src/RemoteHttpInterceptor.ts +var RemoteHttpInterceptor = class extends BatchInterceptor { + constructor() { + super({ + name: "remote-interceptor", + interceptors: [ + new ClientRequestInterceptor(), + new XMLHttpRequestInterceptor(), + new FetchInterceptor() + ] + }); + } + setup() { + super.setup(); + let handleParentMessage; + this.on("request", async ({ request, requestId, controller }) => { + const serializedRequest = JSON.stringify({ + id: requestId, + method: request.method, + url: request.url, + headers: Array.from(request.headers.entries()), + credentials: request.credentials, + body: ["GET", "HEAD"].includes(request.method) ? null : await request.text() + }); + this.logger.info("sent serialized request to the child:", serializedRequest); + process.send?.(`request:${serializedRequest}`); + const responsePromise = new Promise((resolve) => { + handleParentMessage = (message) => { + if (typeof message !== "string") return resolve(); + if (message.startsWith(`response:${requestId}`)) { + const [, serializedResponse] = message.match(/^response:.+?:(.+)$/) || []; + if (!serializedResponse) return resolve(); + const responseInit = JSON.parse(serializedResponse); + const mockedResponse = new FetchResponse(responseInit.body, { + url: request.url, + status: responseInit.status, + statusText: responseInit.statusText, + headers: responseInit.headers + }); + /** + * @todo Support "errorWith" as well. + * This response handling from the child is incomplete. + */ + controller.respondWith(mockedResponse); + return resolve(); + } + }; + }); + this.logger.info("add \"message\" listener to the parent process", handleParentMessage); + process.addListener("message", handleParentMessage); + return responsePromise; + }); + this.subscriptions.push(() => { + process.removeListener("message", handleParentMessage); + }); + } +}; +function requestReviver(key, value) { + switch (key) { + case "url": return new URL(value); + case "headers": return new Headers(value); + default: return value; + } +} +var RemoteHttpResolver = class RemoteHttpResolver extends Interceptor { + static { + this.symbol = Symbol.for("remote-resolver"); + } + constructor(options) { + super(RemoteHttpResolver.symbol); + this.process = options.process; + } + setup() { + const logger = this.logger.extend("setup"); + const handleChildMessage = async (message) => { + logger.info("received message from child!", message); + if (typeof message !== "string" || !message.startsWith("request:")) { + logger.info("unknown message, ignoring..."); + return; + } + const [, serializedRequest] = message.match(/^request:(.+)$/) || []; + if (!serializedRequest) return; + const requestJson = JSON.parse(serializedRequest, requestReviver); + logger.info("parsed intercepted request", requestJson); + const request = new FetchRequest(requestJson.url, { + method: requestJson.method, + headers: new Headers(requestJson.headers), + credentials: requestJson.credentials, + body: requestJson.body + }); + const controller = new RequestController(request, { + passthrough: () => {}, + respondWith: async (response) => { + if (isResponseError(response)) { + this.logger.info("received a network error!", { response }); + throw new Error("Not implemented"); + } + this.logger.info("received mocked response!", { response }); + const responseClone = FetchResponse.clone(response); + const responseText = await responseClone.text(); + const serializedResponse = JSON.stringify({ + status: response.status, + statusText: response.statusText, + headers: Array.from(response.headers.entries()), + body: responseText + }); + this.process.send(`response:${requestJson.id}:${serializedResponse}`, (error) => { + if (error) return; + this.emitter.emit("response", { + request, + requestId: requestJson.id, + response: responseClone, + isMockedResponse: true + }); + }); + logger.info("sent serialized mocked response to the parent:", serializedResponse); + }, + errorWith: (reason) => { + this.logger.info("request has errored!", { error: reason }); + throw new Error("Not implemented"); + } + }); + await handleRequest({ + request, + requestId: requestJson.id, + controller, + emitter: this.emitter + }); + }; + this.subscriptions.push(() => { + this.process.removeListener("message", handleChildMessage); + logger.info("removed the \"message\" listener from the child process!"); + }); + logger.info("adding a \"message\" listener to the child process"); + this.process.addListener("message", handleChildMessage); + this.process.once("error", () => this.dispose()); + this.process.once("exit", () => this.dispose()); + } +}; + +//#endregion +export { RemoteHttpInterceptor, RemoteHttpResolver, requestReviver }; +//# sourceMappingURL=RemoteHttpInterceptor.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/RemoteHttpInterceptor.mjs.map b/node_modules/@mswjs/interceptors/lib/node/RemoteHttpInterceptor.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..39cbf35b3edf431f514fb73071d22f5726884da6 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/RemoteHttpInterceptor.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"RemoteHttpInterceptor.mjs","names":["handleParentMessage: NodeJS.MessageListener","handleChildMessage: NodeJS.MessageListener"],"sources":["../../src/RemoteHttpInterceptor.ts"],"sourcesContent":["import { ChildProcess } from 'child_process'\nimport { HttpRequestEventMap } from './glossary'\nimport { Interceptor } from './Interceptor'\nimport { BatchInterceptor } from './BatchInterceptor'\nimport { ClientRequestInterceptor } from './interceptors/ClientRequest'\nimport { XMLHttpRequestInterceptor } from './interceptors/XMLHttpRequest'\nimport { FetchInterceptor } from './interceptors/fetch'\nimport { handleRequest } from './utils/handleRequest'\nimport { RequestController } from './RequestController'\nimport { FetchRequest, FetchResponse } from './utils/fetchUtils'\nimport { isResponseError } from './utils/responseUtils'\n\nexport interface SerializedRequest {\n id: string\n url: string\n method: string\n headers: Array<[string, string]>\n credentials: RequestCredentials\n body: string\n}\n\ninterface RevivedRequest extends Omit {\n url: URL\n headers: Headers\n}\n\nexport interface SerializedResponse {\n status: number\n statusText: string\n headers: Array<[string, string]>\n body: string\n}\n\nexport class RemoteHttpInterceptor extends BatchInterceptor<\n [ClientRequestInterceptor, XMLHttpRequestInterceptor, FetchInterceptor]\n> {\n constructor() {\n super({\n name: 'remote-interceptor',\n interceptors: [\n new ClientRequestInterceptor(),\n new XMLHttpRequestInterceptor(),\n new FetchInterceptor(),\n ],\n })\n }\n\n protected setup() {\n super.setup()\n\n let handleParentMessage: NodeJS.MessageListener\n\n this.on('request', async ({ request, requestId, controller }) => {\n // Send the stringified intercepted request to\n // the parent process where the remote resolver is established.\n const serializedRequest = JSON.stringify({\n id: requestId,\n method: request.method,\n url: request.url,\n headers: Array.from(request.headers.entries()),\n credentials: request.credentials,\n body: ['GET', 'HEAD'].includes(request.method)\n ? null\n : await request.text(),\n } as SerializedRequest)\n\n this.logger.info(\n 'sent serialized request to the child:',\n serializedRequest\n )\n\n process.send?.(`request:${serializedRequest}`)\n\n const responsePromise = new Promise((resolve) => {\n handleParentMessage = (message) => {\n if (typeof message !== 'string') {\n return resolve()\n }\n\n if (message.startsWith(`response:${requestId}`)) {\n const [, serializedResponse] =\n message.match(/^response:.+?:(.+)$/) || []\n\n if (!serializedResponse) {\n return resolve()\n }\n\n const responseInit = JSON.parse(\n serializedResponse\n ) as SerializedResponse\n\n const mockedResponse = new FetchResponse(responseInit.body, {\n url: request.url,\n status: responseInit.status,\n statusText: responseInit.statusText,\n headers: responseInit.headers,\n })\n\n /**\n * @todo Support \"errorWith\" as well.\n * This response handling from the child is incomplete.\n */\n\n controller.respondWith(mockedResponse)\n return resolve()\n }\n }\n })\n\n // Listen for the mocked response message from the parent.\n this.logger.info(\n 'add \"message\" listener to the parent process',\n handleParentMessage\n )\n process.addListener('message', handleParentMessage)\n\n return responsePromise\n })\n\n this.subscriptions.push(() => {\n process.removeListener('message', handleParentMessage)\n })\n }\n}\n\nexport function requestReviver(key: string, value: any) {\n switch (key) {\n case 'url':\n return new URL(value)\n\n case 'headers':\n return new Headers(value)\n\n default:\n return value\n }\n}\n\nexport interface RemoveResolverOptions {\n process: ChildProcess\n}\n\nexport class RemoteHttpResolver extends Interceptor {\n static symbol = Symbol.for('remote-resolver')\n private process: ChildProcess\n\n constructor(options: RemoveResolverOptions) {\n super(RemoteHttpResolver.symbol)\n this.process = options.process\n }\n\n protected setup() {\n const logger = this.logger.extend('setup')\n\n const handleChildMessage: NodeJS.MessageListener = async (message) => {\n logger.info('received message from child!', message)\n\n if (typeof message !== 'string' || !message.startsWith('request:')) {\n logger.info('unknown message, ignoring...')\n return\n }\n\n const [, serializedRequest] = message.match(/^request:(.+)$/) || []\n if (!serializedRequest) {\n return\n }\n\n const requestJson = JSON.parse(\n serializedRequest,\n requestReviver\n ) as RevivedRequest\n\n logger.info('parsed intercepted request', requestJson)\n\n const request = new FetchRequest(requestJson.url, {\n method: requestJson.method,\n headers: new Headers(requestJson.headers),\n credentials: requestJson.credentials,\n body: requestJson.body,\n })\n\n const controller = new RequestController(request, {\n passthrough: () => {},\n respondWith: async (response) => {\n if (isResponseError(response)) {\n this.logger.info('received a network error!', { response })\n throw new Error('Not implemented')\n }\n\n this.logger.info('received mocked response!', { response })\n\n const responseClone = FetchResponse.clone(response)\n const responseText = await responseClone.text()\n\n // // Send the mocked response to the child process.\n const serializedResponse = JSON.stringify({\n status: response.status,\n statusText: response.statusText,\n headers: Array.from(response.headers.entries()),\n body: responseText,\n } as SerializedResponse)\n\n this.process.send(\n `response:${requestJson.id}:${serializedResponse}`,\n (error) => {\n if (error) {\n return\n }\n\n // Emit an optimistic \"response\" event at this point,\n // not to rely on the back-and-forth signaling for the sake of the event.\n this.emitter.emit('response', {\n request,\n requestId: requestJson.id,\n response: responseClone,\n isMockedResponse: true,\n })\n }\n )\n\n logger.info(\n 'sent serialized mocked response to the parent:',\n serializedResponse\n )\n },\n errorWith: (reason) => {\n this.logger.info('request has errored!', { error: reason })\n throw new Error('Not implemented')\n },\n })\n\n await handleRequest({\n request,\n requestId: requestJson.id,\n controller,\n emitter: this.emitter,\n })\n }\n\n this.subscriptions.push(() => {\n this.process.removeListener('message', handleChildMessage)\n logger.info('removed the \"message\" listener from the child process!')\n })\n\n logger.info('adding a \"message\" listener to the child process')\n this.process.addListener('message', handleChildMessage)\n\n this.process.once('error', () => this.dispose())\n this.process.once('exit', () => this.dispose())\n }\n}\n"],"mappings":";;;;;;;;;;;AAiCA,IAAa,wBAAb,cAA2C,iBAEzC;CACA,cAAc;AACZ,QAAM;GACJ,MAAM;GACN,cAAc;IACZ,IAAI,0BAA0B;IAC9B,IAAI,2BAA2B;IAC/B,IAAI,kBAAkB;IACvB;GACF,CAAC;;CAGJ,AAAU,QAAQ;AAChB,QAAM,OAAO;EAEb,IAAIA;AAEJ,OAAK,GAAG,WAAW,OAAO,EAAE,SAAS,WAAW,iBAAiB;GAG/D,MAAM,oBAAoB,KAAK,UAAU;IACvC,IAAI;IACJ,QAAQ,QAAQ;IAChB,KAAK,QAAQ;IACb,SAAS,MAAM,KAAK,QAAQ,QAAQ,SAAS,CAAC;IAC9C,aAAa,QAAQ;IACrB,MAAM,CAAC,OAAO,OAAO,CAAC,SAAS,QAAQ,OAAO,GAC1C,OACA,MAAM,QAAQ,MAAM;IACzB,CAAsB;AAEvB,QAAK,OAAO,KACV,yCACA,kBACD;AAED,WAAQ,OAAO,WAAW,oBAAoB;GAE9C,MAAM,kBAAkB,IAAI,SAAe,YAAY;AACrD,2BAAuB,YAAY;AACjC,SAAI,OAAO,YAAY,SACrB,QAAO,SAAS;AAGlB,SAAI,QAAQ,WAAW,YAAY,YAAY,EAAE;MAC/C,MAAM,GAAG,sBACP,QAAQ,MAAM,sBAAsB,IAAI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.cjs b/node_modules/@mswjs/interceptors/lib/node/XMLHttpRequest-BtDNZipW.cjs new file mode 100644 index 0000000000000000000000000000000000000000..b02cda6492a982a85bb08e6149554c4b27bb11a8 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/XMLHttpRequest-BtDNZipW.cjs @@ -0,0 +1,752 @@ +const require_chunk = require('./chunk-CbDLau6x.cjs'); +const require_fetchUtils = require('./fetchUtils-umV5xXBy.cjs'); +const require_bufferUtils = require('./bufferUtils-S5_-2eN4.cjs'); +const require_getRawRequest = require('./getRawRequest-B6znU6il.cjs'); +const require_handleRequest = require('./handleRequest-C-cKYjIh.cjs'); +const require_hasConfigurableGlobal = require('./hasConfigurableGlobal-MjY06_Ok.cjs'); +let outvariant = require("outvariant"); +let is_node_process = require("is-node-process"); + +//#region src/interceptors/XMLHttpRequest/utils/concatArrayBuffer.ts +/** +* Concatenate two `Uint8Array` buffers. +*/ +function concatArrayBuffer(left, right) { + const result = new Uint8Array(left.byteLength + right.byteLength); + result.set(left, 0); + result.set(right, left.byteLength); + return result; +} + +//#endregion +//#region src/interceptors/XMLHttpRequest/polyfills/EventPolyfill.ts +var EventPolyfill = class { + constructor(type, options) { + this.NONE = 0; + this.CAPTURING_PHASE = 1; + this.AT_TARGET = 2; + this.BUBBLING_PHASE = 3; + this.type = ""; + this.srcElement = null; + this.currentTarget = null; + this.eventPhase = 0; + this.isTrusted = true; + this.composed = false; + this.cancelable = true; + this.defaultPrevented = false; + this.bubbles = true; + this.lengthComputable = true; + this.loaded = 0; + this.total = 0; + this.cancelBubble = false; + this.returnValue = true; + this.type = type; + this.target = options?.target || null; + this.currentTarget = options?.currentTarget || null; + this.timeStamp = Date.now(); + } + composedPath() { + return []; + } + initEvent(type, bubbles, cancelable) { + this.type = type; + this.bubbles = !!bubbles; + this.cancelable = !!cancelable; + } + preventDefault() { + this.defaultPrevented = true; + } + stopPropagation() {} + stopImmediatePropagation() {} +}; + +//#endregion +//#region src/interceptors/XMLHttpRequest/polyfills/ProgressEventPolyfill.ts +var ProgressEventPolyfill = class extends EventPolyfill { + constructor(type, init) { + super(type); + this.lengthComputable = init?.lengthComputable || false; + this.composed = init?.composed || false; + this.loaded = init?.loaded || 0; + this.total = init?.total || 0; + } +}; + +//#endregion +//#region src/interceptors/XMLHttpRequest/utils/createEvent.ts +const SUPPORTS_PROGRESS_EVENT = typeof ProgressEvent !== "undefined"; +function createEvent(target, type, init) { + const progressEvents = [ + "error", + "progress", + "loadstart", + "loadend", + "load", + "timeout", + "abort" + ]; + /** + * `ProgressEvent` is not supported in React Native. + * @see https://github.com/mswjs/interceptors/issues/40 + */ + const ProgressEventClass = SUPPORTS_PROGRESS_EVENT ? ProgressEvent : ProgressEventPolyfill; + return progressEvents.includes(type) ? new ProgressEventClass(type, { + lengthComputable: true, + loaded: init?.loaded || 0, + total: init?.total || 0 + }) : new EventPolyfill(type, { + target, + currentTarget: target + }); +} + +//#endregion +//#region src/utils/findPropertySource.ts +/** +* Returns the source object of the given property on the target object +* (the target itself, any parent in its prototype, or null). +*/ +function findPropertySource(target, propertyName) { + if (!(propertyName in target)) return null; + if (Object.prototype.hasOwnProperty.call(target, propertyName)) return target; + const prototype = Reflect.getPrototypeOf(target); + return prototype ? findPropertySource(prototype, propertyName) : null; +} + +//#endregion +//#region src/utils/createProxy.ts +function createProxy(target, options) { + return new Proxy(target, optionsToProxyHandler(options)); +} +function optionsToProxyHandler(options) { + const { constructorCall, methodCall, getProperty, setProperty } = options; + const handler = {}; + if (typeof constructorCall !== "undefined") handler.construct = function(target, args, newTarget) { + const next = Reflect.construct.bind(null, target, args, newTarget); + return constructorCall.call(newTarget, args, next); + }; + handler.set = function(target, propertyName, nextValue) { + const next = () => { + const propertySource = findPropertySource(target, propertyName) || target; + const ownDescriptors = Reflect.getOwnPropertyDescriptor(propertySource, propertyName); + if (typeof ownDescriptors?.set !== "undefined") { + ownDescriptors.set.apply(target, [nextValue]); + return true; + } + return Reflect.defineProperty(propertySource, propertyName, { + writable: true, + enumerable: true, + configurable: true, + value: nextValue + }); + }; + if (typeof setProperty !== "undefined") return setProperty.call(target, [propertyName, nextValue], next); + return next(); + }; + handler.get = function(target, propertyName, receiver) { + /** + * @note Using `Reflect.get()` here causes "TypeError: Illegal invocation". + */ + const next = () => target[propertyName]; + const value = typeof getProperty !== "undefined" ? getProperty.call(target, [propertyName, receiver], next) : next(); + if (typeof value === "function") return (...args) => { + const next$1 = value.bind(target, ...args); + if (typeof methodCall !== "undefined") return methodCall.call(target, [propertyName, args], next$1); + return next$1(); + }; + return value; + }; + return handler; +} + +//#endregion +//#region src/interceptors/XMLHttpRequest/utils/isDomParserSupportedType.ts +function isDomParserSupportedType(type) { + return [ + "application/xhtml+xml", + "application/xml", + "image/svg+xml", + "text/html", + "text/xml" + ].some((supportedType) => { + return type.startsWith(supportedType); + }); +} + +//#endregion +//#region src/utils/parseJson.ts +/** +* Parses a given string into JSON. +* Gracefully handles invalid JSON by returning `null`. +*/ +function parseJson(data) { + try { + return JSON.parse(data); + } catch (_) { + return null; + } +} + +//#endregion +//#region src/interceptors/XMLHttpRequest/utils/createResponse.ts +/** +* Creates a Fetch API `Response` instance from the given +* `XMLHttpRequest` instance and a response body. +*/ +function createResponse(request, body) { + return new require_fetchUtils.FetchResponse(require_fetchUtils.FetchResponse.isResponseWithBody(request.status) ? body : null, { + url: request.responseURL, + status: request.status, + statusText: request.statusText, + headers: createHeadersFromXMLHttpRequestHeaders(request.getAllResponseHeaders()) + }); +} +function createHeadersFromXMLHttpRequestHeaders(headersString) { + const headers = new Headers(); + const lines = headersString.split(/[\r\n]+/); + for (const line of lines) { + if (line.trim() === "") continue; + const [name, ...parts] = line.split(": "); + const value = parts.join(": "); + headers.append(name, value); + } + return headers; +} + +//#endregion +//#region src/interceptors/XMLHttpRequest/utils/getBodyByteLength.ts +/** +* Return a total byte length of the given request/response body. +* If the `Content-Length` header is present, it will be used as the byte length. +*/ +async function getBodyByteLength(input) { + const explicitContentLength = input.headers.get("content-length"); + if (explicitContentLength != null && explicitContentLength !== "") return Number(explicitContentLength); + return (await input.arrayBuffer()).byteLength; +} + +//#endregion +//#region src/interceptors/XMLHttpRequest/XMLHttpRequestController.ts +const kIsRequestHandled = Symbol("kIsRequestHandled"); +const IS_NODE = (0, is_node_process.isNodeProcess)(); +const kFetchRequest = Symbol("kFetchRequest"); +/** +* An `XMLHttpRequest` instance controller that allows us +* to handle any given request instance (e.g. responding to it). +*/ +var XMLHttpRequestController = class { + constructor(initialRequest, logger) { + this.initialRequest = initialRequest; + this.logger = logger; + this.method = "GET"; + this.url = null; + this[kIsRequestHandled] = false; + this.events = /* @__PURE__ */ new Map(); + this.uploadEvents = /* @__PURE__ */ new Map(); + this.requestId = require_fetchUtils.createRequestId(); + this.requestHeaders = new Headers(); + this.responseBuffer = new Uint8Array(); + this.request = createProxy(initialRequest, { + setProperty: ([propertyName, nextValue], invoke) => { + switch (propertyName) { + case "ontimeout": { + const eventName = propertyName.slice(2); + /** + * @note Proxy callbacks to event listeners because JSDOM has trouble + * translating these properties to callbacks. It seemed to be operating + * on events exclusively. + */ + this.request.addEventListener(eventName, nextValue); + return invoke(); + } + default: return invoke(); + } + }, + methodCall: ([methodName, args], invoke) => { + switch (methodName) { + case "open": { + const [method, url] = args; + if (typeof url === "undefined") { + this.method = "GET"; + this.url = toAbsoluteUrl(method); + } else { + this.method = method; + this.url = toAbsoluteUrl(url); + } + this.logger = this.logger.extend(`${this.method} ${this.url.href}`); + this.logger.info("open", this.method, this.url.href); + return invoke(); + } + case "addEventListener": { + const [eventName, listener] = args; + this.registerEvent(eventName, listener); + this.logger.info("addEventListener", eventName, listener); + return invoke(); + } + case "setRequestHeader": { + const [name, value] = args; + this.requestHeaders.set(name, value); + this.logger.info("setRequestHeader", name, value); + return invoke(); + } + case "send": { + const [body] = args; + this.request.addEventListener("load", () => { + if (typeof this.onResponse !== "undefined") { + const fetchResponse = createResponse( + this.request, + /** + * The `response` property is the right way to read + * the ambiguous response body, as the request's "responseType" may differ. + * @see https://xhr.spec.whatwg.org/#the-response-attribute + */ + this.request.response + ); + this.onResponse.call(this, { + response: fetchResponse, + isMockedResponse: this[kIsRequestHandled], + request: fetchRequest, + requestId: this.requestId + }); + } + }); + const requestBody = typeof body === "string" ? require_bufferUtils.encodeBuffer(body) : body; + const fetchRequest = this.toFetchApiRequest(requestBody); + this[kFetchRequest] = fetchRequest.clone(); + /** + * @note Start request handling on the next tick so that the user + * could add event listeners for "loadend" before the interceptor fires it. + */ + queueMicrotask(() => { + (this.onRequest?.call(this, { + request: fetchRequest, + requestId: this.requestId + }) || Promise.resolve()).finally(() => { + if (!this[kIsRequestHandled]) { + this.logger.info("request callback settled but request has not been handled (readystate %d), performing as-is...", this.request.readyState); + /** + * @note Set the intercepted request ID on the original request in Node.js + * so that if it triggers any other interceptors, they don't attempt + * to process it once again. + * + * For instance, XMLHttpRequest is often implemented via "http.ClientRequest" + * and we don't want for both XHR and ClientRequest interceptors to + * handle the same request at the same time (e.g. emit the "response" event twice). + */ + if (IS_NODE) this.request.setRequestHeader(require_fetchUtils.INTERNAL_REQUEST_ID_HEADER_NAME, this.requestId); + return invoke(); + } + }); + }); + break; + } + default: return invoke(); + } + } + }); + /** + * Proxy the `.upload` property to gather the event listeners/callbacks. + */ + define(this.request, "upload", createProxy(this.request.upload, { + setProperty: ([propertyName, nextValue], invoke) => { + switch (propertyName) { + case "onloadstart": + case "onprogress": + case "onaboart": + case "onerror": + case "onload": + case "ontimeout": + case "onloadend": { + const eventName = propertyName.slice(2); + this.registerUploadEvent(eventName, nextValue); + } + } + return invoke(); + }, + methodCall: ([methodName, args], invoke) => { + switch (methodName) { + case "addEventListener": { + const [eventName, listener] = args; + this.registerUploadEvent(eventName, listener); + this.logger.info("upload.addEventListener", eventName, listener); + return invoke(); + } + } + } + })); + } + registerEvent(eventName, listener) { + const nextEvents = (this.events.get(eventName) || []).concat(listener); + this.events.set(eventName, nextEvents); + this.logger.info("registered event \"%s\"", eventName, listener); + } + registerUploadEvent(eventName, listener) { + const nextEvents = (this.uploadEvents.get(eventName) || []).concat(listener); + this.uploadEvents.set(eventName, nextEvents); + this.logger.info("registered upload event \"%s\"", eventName, listener); + } + /** + * Responds to the current request with the given + * Fetch API `Response` instance. + */ + async respondWith(response) { + /** + * @note Since `XMLHttpRequestController` delegates the handling of the responses + * to the "load" event listener that doesn't distinguish between the mocked and original + * responses, mark the request that had a mocked response with a corresponding symbol. + * + * Mark this request as having a mocked response immediately since + * calculating request/response total body length is asynchronous. + */ + this[kIsRequestHandled] = true; + /** + * Dispatch request upload events for requests with a body. + * @see https://github.com/mswjs/interceptors/issues/573 + */ + if (this[kFetchRequest]) { + const totalRequestBodyLength = await getBodyByteLength(this[kFetchRequest]); + this.trigger("loadstart", this.request.upload, { + loaded: 0, + total: totalRequestBodyLength + }); + this.trigger("progress", this.request.upload, { + loaded: totalRequestBodyLength, + total: totalRequestBodyLength + }); + this.trigger("load", this.request.upload, { + loaded: totalRequestBodyLength, + total: totalRequestBodyLength + }); + this.trigger("loadend", this.request.upload, { + loaded: totalRequestBodyLength, + total: totalRequestBodyLength + }); + } + this.logger.info("responding with a mocked response: %d %s", response.status, response.statusText); + define(this.request, "status", response.status); + define(this.request, "statusText", response.statusText); + define(this.request, "responseURL", this.url.href); + this.request.getResponseHeader = new Proxy(this.request.getResponseHeader, { apply: (_, __, args) => { + this.logger.info("getResponseHeader", args[0]); + if (this.request.readyState < this.request.HEADERS_RECEIVED) { + this.logger.info("headers not received yet, returning null"); + return null; + } + const headerValue = response.headers.get(args[0]); + this.logger.info("resolved response header \"%s\" to", args[0], headerValue); + return headerValue; + } }); + this.request.getAllResponseHeaders = new Proxy(this.request.getAllResponseHeaders, { apply: () => { + this.logger.info("getAllResponseHeaders"); + if (this.request.readyState < this.request.HEADERS_RECEIVED) { + this.logger.info("headers not received yet, returning empty string"); + return ""; + } + const allHeaders = Array.from(response.headers.entries()).map(([headerName, headerValue]) => { + return `${headerName}: ${headerValue}`; + }).join("\r\n"); + this.logger.info("resolved all response headers to", allHeaders); + return allHeaders; + } }); + Object.defineProperties(this.request, { + response: { + enumerable: true, + configurable: false, + get: () => this.response + }, + responseText: { + enumerable: true, + configurable: false, + get: () => this.responseText + }, + responseXML: { + enumerable: true, + configurable: false, + get: () => this.responseXML + } + }); + const totalResponseBodyLength = await getBodyByteLength(response.clone()); + this.logger.info("calculated response body length", totalResponseBodyLength); + this.trigger("loadstart", this.request, { + loaded: 0, + total: totalResponseBodyLength + }); + this.setReadyState(this.request.HEADERS_RECEIVED); + this.setReadyState(this.request.LOADING); + const finalizeResponse = () => { + this.logger.info("finalizing the mocked response..."); + this.setReadyState(this.request.DONE); + this.trigger("load", this.request, { + loaded: this.responseBuffer.byteLength, + total: totalResponseBodyLength + }); + this.trigger("loadend", this.request, { + loaded: this.responseBuffer.byteLength, + total: totalResponseBodyLength + }); + }; + if (response.body) { + this.logger.info("mocked response has body, streaming..."); + const reader = response.body.getReader(); + const readNextResponseBodyChunk = async () => { + const { value, done } = await reader.read(); + if (done) { + this.logger.info("response body stream done!"); + finalizeResponse(); + return; + } + if (value) { + this.logger.info("read response body chunk:", value); + this.responseBuffer = concatArrayBuffer(this.responseBuffer, value); + this.trigger("progress", this.request, { + loaded: this.responseBuffer.byteLength, + total: totalResponseBodyLength + }); + } + readNextResponseBodyChunk(); + }; + readNextResponseBodyChunk(); + } else finalizeResponse(); + } + responseBufferToText() { + return require_bufferUtils.decodeBuffer(this.responseBuffer); + } + get response() { + this.logger.info("getResponse (responseType: %s)", this.request.responseType); + if (this.request.readyState !== this.request.DONE) return null; + switch (this.request.responseType) { + case "json": { + const responseJson = parseJson(this.responseBufferToText()); + this.logger.info("resolved response JSON", responseJson); + return responseJson; + } + case "arraybuffer": { + const arrayBuffer = require_bufferUtils.toArrayBuffer(this.responseBuffer); + this.logger.info("resolved response ArrayBuffer", arrayBuffer); + return arrayBuffer; + } + case "blob": { + const mimeType = this.request.getResponseHeader("Content-Type") || "text/plain"; + const responseBlob = new Blob([this.responseBufferToText()], { type: mimeType }); + this.logger.info("resolved response Blob (mime type: %s)", responseBlob, mimeType); + return responseBlob; + } + default: { + const responseText = this.responseBufferToText(); + this.logger.info("resolving \"%s\" response type as text", this.request.responseType, responseText); + return responseText; + } + } + } + get responseText() { + /** + * Throw when trying to read the response body as text when the + * "responseType" doesn't expect text. This just respects the spec better. + * @see https://xhr.spec.whatwg.org/#the-responsetext-attribute + */ + (0, outvariant.invariant)(this.request.responseType === "" || this.request.responseType === "text", "InvalidStateError: The object is in invalid state."); + if (this.request.readyState !== this.request.LOADING && this.request.readyState !== this.request.DONE) return ""; + const responseText = this.responseBufferToText(); + this.logger.info("getResponseText: \"%s\"", responseText); + return responseText; + } + get responseXML() { + (0, outvariant.invariant)(this.request.responseType === "" || this.request.responseType === "document", "InvalidStateError: The object is in invalid state."); + if (this.request.readyState !== this.request.DONE) return null; + const contentType = this.request.getResponseHeader("Content-Type") || ""; + if (typeof DOMParser === "undefined") { + console.warn("Cannot retrieve XMLHttpRequest response body as XML: DOMParser is not defined. You are likely using an environment that is not browser or does not polyfill browser globals correctly."); + return null; + } + if (isDomParserSupportedType(contentType)) return new DOMParser().parseFromString(this.responseBufferToText(), contentType); + return null; + } + errorWith(error) { + /** + * @note Mark this request as handled even if it received a mock error. + * This prevents the controller from trying to perform this request as-is. + */ + this[kIsRequestHandled] = true; + this.logger.info("responding with an error"); + this.setReadyState(this.request.DONE); + this.trigger("error", this.request); + this.trigger("loadend", this.request); + } + /** + * Transitions this request's `readyState` to the given one. + */ + setReadyState(nextReadyState) { + this.logger.info("setReadyState: %d -> %d", this.request.readyState, nextReadyState); + if (this.request.readyState === nextReadyState) { + this.logger.info("ready state identical, skipping transition..."); + return; + } + define(this.request, "readyState", nextReadyState); + this.logger.info("set readyState to: %d", nextReadyState); + if (nextReadyState !== this.request.UNSENT) { + this.logger.info("triggering \"readystatechange\" event..."); + this.trigger("readystatechange", this.request); + } + } + /** + * Triggers given event on the `XMLHttpRequest` instance. + */ + trigger(eventName, target, options) { + const callback = target[`on${eventName}`]; + const event = createEvent(target, eventName, options); + this.logger.info("trigger \"%s\"", eventName, options || ""); + if (typeof callback === "function") { + this.logger.info("found a direct \"%s\" callback, calling...", eventName); + callback.call(target, event); + } + const events = target instanceof XMLHttpRequestUpload ? this.uploadEvents : this.events; + for (const [registeredEventName, listeners] of events) if (registeredEventName === eventName) { + this.logger.info("found %d listener(s) for \"%s\" event, calling...", listeners.length, eventName); + listeners.forEach((listener) => listener.call(target, event)); + } + } + /** + * Converts this `XMLHttpRequest` instance into a Fetch API `Request` instance. + */ + toFetchApiRequest(body) { + this.logger.info("converting request to a Fetch API Request..."); + const resolvedBody = body instanceof Document ? body.documentElement.innerText : body; + const fetchRequest = new require_fetchUtils.FetchRequest(this.url.href, { + method: this.method, + headers: this.requestHeaders, + credentials: this.request.withCredentials ? "include" : "same-origin", + body: ["GET", "HEAD"].includes(this.method.toUpperCase()) ? null : resolvedBody + }); + define(fetchRequest, "headers", createProxy(fetchRequest.headers, { methodCall: ([methodName, args], invoke) => { + switch (methodName) { + case "append": + case "set": { + const [headerName, headerValue] = args; + this.request.setRequestHeader(headerName, headerValue); + break; + } + case "delete": { + const [headerName] = args; + console.warn(`XMLHttpRequest: Cannot remove a "${headerName}" header from the Fetch API representation of the "${fetchRequest.method} ${fetchRequest.url}" request. XMLHttpRequest headers cannot be removed.`); + break; + } + } + return invoke(); + } })); + require_getRawRequest.setRawRequest(fetchRequest, this.request); + this.logger.info("converted request to a Fetch API Request!", fetchRequest); + return fetchRequest; + } +}; +function toAbsoluteUrl(url) { + /** + * @note XMLHttpRequest interceptor may run in environments + * that implement XMLHttpRequest but don't implement "location" + * (for example, React Native). If that's the case, return the + * input URL as-is (nothing to be relative to). + * @see https://github.com/mswjs/msw/issues/1777 + */ + if (typeof location === "undefined") return new URL(url); + return new URL(url.toString(), location.href); +} +function define(target, property, value) { + Reflect.defineProperty(target, property, { + writable: true, + enumerable: true, + value + }); +} + +//#endregion +//#region src/interceptors/XMLHttpRequest/XMLHttpRequestProxy.ts +/** +* Create a proxied `XMLHttpRequest` class. +* The proxied class establishes spies on certain methods, +* allowing us to intercept requests and respond to them. +*/ +function createXMLHttpRequestProxy({ emitter, logger }) { + return new Proxy(globalThis.XMLHttpRequest, { construct(target, args, newTarget) { + logger.info("constructed new XMLHttpRequest"); + const originalRequest = Reflect.construct(target, args, newTarget); + /** + * @note Forward prototype descriptors onto the proxied object. + * XMLHttpRequest is implemented in JSDOM in a way that assigns + * a bunch of descriptors, like "set responseType()" on the prototype. + * With this propagation, we make sure that those descriptors trigger + * when the user operates with the proxied request instance. + */ + const prototypeDescriptors = Object.getOwnPropertyDescriptors(target.prototype); + for (const propertyName in prototypeDescriptors) Reflect.defineProperty(originalRequest, propertyName, prototypeDescriptors[propertyName]); + const xhrRequestController = new XMLHttpRequestController(originalRequest, logger); + xhrRequestController.onRequest = async function({ request, requestId }) { + const controller = new require_fetchUtils.RequestController(request, { + passthrough: () => { + this.logger.info("no mocked response received, performing request as-is..."); + }, + respondWith: async (response) => { + if (require_handleRequest.isResponseError(response)) { + this.errorWith(/* @__PURE__ */ new TypeError("Network error")); + return; + } + await this.respondWith(response); + }, + errorWith: (reason) => { + this.logger.info("request errored!", { error: reason }); + if (reason instanceof Error) this.errorWith(reason); + } + }); + this.logger.info("awaiting mocked response..."); + this.logger.info("emitting the \"request\" event for %s listener(s)...", emitter.listenerCount("request")); + await require_handleRequest.handleRequest({ + request, + requestId, + controller, + emitter + }); + }; + xhrRequestController.onResponse = async function({ response, isMockedResponse, request, requestId }) { + this.logger.info("emitting the \"response\" event for %s listener(s)...", emitter.listenerCount("response")); + emitter.emit("response", { + response, + isMockedResponse, + request, + requestId + }); + }; + return xhrRequestController.request; + } }); +} + +//#endregion +//#region src/interceptors/XMLHttpRequest/index.ts +var XMLHttpRequestInterceptor = class XMLHttpRequestInterceptor extends require_fetchUtils.Interceptor { + static { + this.symbol = Symbol.for("xhr-interceptor"); + } + constructor() { + super(XMLHttpRequestInterceptor.symbol); + } + checkEnvironment() { + return require_hasConfigurableGlobal.hasConfigurableGlobal("XMLHttpRequest"); + } + setup() { + const logger = this.logger.extend("setup"); + logger.info("patching global XMLHttpRequest..."); + this.subscriptions.push(require_hasConfigurableGlobal.patchesRegistry.applyPatch(globalThis, "XMLHttpRequest", () => { + return createXMLHttpRequestProxy({ + emitter: this.emitter, + logger: this.logger + }); + })); + logger.info("global XMLHttpRequest patched!", globalThis.XMLHttpRequest.name); + } +}; + +//#endregion +Object.defineProperty(exports, 'XMLHttpRequestInterceptor', { + enumerable: true, + get: function () { + return XMLHttpRequestInterceptor; + } +}); +//# sourceMappingURL=XMLHttpRequest-BtDNZipW.cjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/XMLHttpRequest-BtDNZipW.cjs.map b/node_modules/@mswjs/interceptors/lib/node/XMLHttpRequest-BtDNZipW.cjs.map new file mode 100644 index 0000000000000000000000000000000000000000..7c951482cc217aba38fbfa7193ac643fab6ca75a --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/XMLHttpRequest-BtDNZipW.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"XMLHttpRequest-BtDNZipW.cjs","names":["handler: ProxyHandler","next","FetchResponse","initialRequest: XMLHttpRequest","logger: Logger","createRequestId","encodeBuffer","INTERNAL_REQUEST_ID_HEADER_NAME","decodeBuffer","toArrayBuffer","FetchRequest","RequestController","isResponseError","handleRequest","Interceptor","hasConfigurableGlobal","patchesRegistry"],"sources":["../../src/interceptors/XMLHttpRequest/utils/concatArrayBuffer.ts","../../src/interceptors/XMLHttpRequest/polyfills/EventPolyfill.ts","../../src/interceptors/XMLHttpRequest/polyfills/ProgressEventPolyfill.ts","../../src/interceptors/XMLHttpRequest/utils/createEvent.ts","../../src/utils/findPropertySource.ts","../../src/utils/createProxy.ts","../../src/interceptors/XMLHttpRequest/utils/isDomParserSupportedType.ts","../../src/utils/parseJson.ts","../../src/interceptors/XMLHttpRequest/utils/createResponse.ts","../../src/interceptors/XMLHttpRequest/utils/getBodyByteLength.ts","../../src/interceptors/XMLHttpRequest/XMLHttpRequestController.ts","../../src/interceptors/XMLHttpRequest/XMLHttpRequestProxy.ts","../../src/interceptors/XMLHttpRequest/index.ts"],"sourcesContent":["/**\n * Concatenate two `Uint8Array` buffers.\n */\nexport function concatArrayBuffer(\n left: Uint8Array,\n right: Uint8Array\n): Uint8Array {\n const result = new Uint8Array(left.byteLength + right.byteLength)\n result.set(left, 0)\n result.set(right, left.byteLength)\n return result\n}\n","export class EventPolyfill implements Event {\n readonly NONE = 0\n readonly CAPTURING_PHASE = 1\n readonly AT_TARGET = 2\n readonly BUBBLING_PHASE = 3\n\n public type: string = ''\n public srcElement: EventTarget | null = null\n public target: EventTarget | null\n public currentTarget: EventTarget | null = null\n public eventPhase: number = 0\n public timeStamp: number\n public isTrusted: boolean = true\n public composed: boolean = false\n public cancelable: boolean = true\n public defaultPrevented: boolean = false\n public bubbles: boolean = true\n public lengthComputable: boolean = true\n public loaded: number = 0\n public total: number = 0\n\n cancelBubble: boolean = false\n returnValue: boolean = true\n\n constructor(\n type: string,\n options?: { target: EventTarget; currentTarget: EventTarget }\n ) {\n this.type = type\n this.target = options?.target || null\n this.currentTarget = options?.currentTarget || null\n this.timeStamp = Date.now()\n }\n\n public composedPath(): EventTarget[] {\n return []\n }\n\n public initEvent(type: string, bubbles?: boolean, cancelable?: boolean) {\n this.type = type\n this.bubbles = !!bubbles\n this.cancelable = !!cancelable\n }\n\n public preventDefault() {\n this.defaultPrevented = true\n }\n\n public stopPropagation() {}\n public stopImmediatePropagation() {}\n}\n","import { EventPolyfill } from './EventPolyfill'\n\nexport class ProgressEventPolyfill extends EventPolyfill {\n readonly lengthComputable: boolean\n readonly composed: boolean\n readonly loaded: number\n readonly total: number\n\n constructor(type: string, init?: ProgressEventInit) {\n super(type)\n\n this.lengthComputable = init?.lengthComputable || false\n this.composed = init?.composed || false\n this.loaded = init?.loaded || 0\n this.total = init?.total || 0\n }\n}\n","import { EventPolyfill } from '../polyfills/EventPolyfill'\nimport { ProgressEventPolyfill } from '../polyfills/ProgressEventPolyfill'\n\nconst SUPPORTS_PROGRESS_EVENT = typeof ProgressEvent !== 'undefined'\n\nexport function createEvent(\n target: XMLHttpRequest | XMLHttpRequestUpload,\n type: string,\n init?: ProgressEventInit\n): EventPolyfill | ProgressEvent {\n const progressEvents = [\n 'error',\n 'progress',\n 'loadstart',\n 'loadend',\n 'load',\n 'timeout',\n 'abort',\n ]\n\n /**\n * `ProgressEvent` is not supported in React Native.\n * @see https://github.com/mswjs/interceptors/issues/40\n */\n const ProgressEventClass = SUPPORTS_PROGRESS_EVENT\n ? ProgressEvent\n : ProgressEventPolyfill\n\n const event = progressEvents.includes(type)\n ? new ProgressEventClass(type, {\n lengthComputable: true,\n loaded: init?.loaded || 0,\n total: init?.total || 0,\n })\n : new EventPolyfill(type, {\n target,\n currentTarget: target,\n })\n\n return event\n}\n","/**\n * Returns the source object of the given property on the target object\n * (the target itself, any parent in its prototype, or null).\n */\nexport function findPropertySource(\n target: object,\n propertyName: string | symbol\n): object | null {\n if (!(propertyName in target)) {\n return null\n }\n\n const hasProperty = Object.prototype.hasOwnProperty.call(target, propertyName)\n if (hasProperty) {\n return target\n }\n\n const prototype = Reflect.getPrototypeOf(target)\n return prototype ? findPropertySource(prototype, propertyName) : null\n}\n","import { findPropertySource } from './findPropertySource'\n\nexport interface ProxyOptions> {\n constructorCall?(args: Array, next: NextFunction): Target\n\n methodCall?(\n this: Target,\n data: [methodName: F, args: Array],\n next: NextFunction\n ): void\n\n setProperty?(\n data: [propertyName: string | symbol, nextValue: unknown],\n next: NextFunction\n ): boolean\n\n getProperty?(\n data: [propertyName: string | symbol, receiver: Target],\n next: NextFunction\n ): void\n}\n\nexport type NextFunction = () => ReturnType\n\nexport function createProxy(\n target: Target,\n options: ProxyOptions\n): Target {\n const proxy = new Proxy(target, optionsToProxyHandler(options))\n\n return proxy\n}\n\nfunction optionsToProxyHandler>(\n options: ProxyOptions\n): ProxyHandler {\n const { constructorCall, methodCall, getProperty, setProperty } = options\n const handler: ProxyHandler = {}\n\n if (typeof constructorCall !== 'undefined') {\n handler.construct = function (target, args, newTarget) {\n const next = Reflect.construct.bind(null, target as any, args, newTarget)\n return constructorCall.call(newTarget, args, next)\n }\n }\n\n handler.set = function (target, propertyName, nextValue) {\n const next = () => {\n const propertySource = findPropertySource(target, propertyName) || target\n const ownDescriptors = Reflect.getOwnPropertyDescriptor(\n propertySource,\n propertyName\n )\n\n // Respect any custom setters present for this property.\n if (typeof ownDescriptors?.set !== 'undefined') {\n ownDescriptors.set.apply(target, [nextValue])\n return true\n }\n\n // Otherwise, set the property on the source.\n return Reflect.defineProperty(propertySource, propertyName, {\n writable: true,\n enumerable: true,\n configurable: true,\n value: nextValue,\n })\n }\n\n if (typeof setProperty !== 'undefined') {\n return setProperty.call(target, [propertyName, nextValue], next)\n }\n\n return next()\n }\n\n handler.get = function (target, propertyName, receiver) {\n /**\n * @note Using `Reflect.get()` here causes \"TypeError: Illegal invocation\".\n */\n const next = () => target[propertyName as any]\n\n const value =\n typeof getProperty !== 'undefined'\n ? getProperty.call(target, [propertyName, receiver], next)\n : next()\n\n if (typeof value === 'function') {\n return (...args: Array) => {\n const next = value.bind(target, ...args)\n\n if (typeof methodCall !== 'undefined') {\n return methodCall.call(target, [propertyName as any, args], next)\n }\n\n return next()\n }\n }\n\n return value\n }\n\n return handler\n}\n","export function isDomParserSupportedType(\n type: string\n): type is DOMParserSupportedType {\n const supportedTypes: Array = [\n 'application/xhtml+xml',\n 'application/xml',\n 'image/svg+xml',\n 'text/html',\n 'text/xml',\n ]\n return supportedTypes.some((supportedType) => {\n return type.startsWith(supportedType)\n })\n}\n","/**\n * Parses a given string into JSON.\n * Gracefully handles invalid JSON by returning `null`.\n */\nexport function parseJson(data: string): Record | null {\n try {\n const json = JSON.parse(data)\n return json\n } catch (_) {\n return null\n }\n}\n","import { FetchResponse } from '../../../utils/fetchUtils'\n\n/**\n * Creates a Fetch API `Response` instance from the given\n * `XMLHttpRequest` instance and a response body.\n */\nexport function createResponse(\n request: XMLHttpRequest,\n body: BodyInit | null\n): Response {\n /**\n * Handle XMLHttpRequest responses that must have null as the\n * response body when represented using Fetch API Response.\n * XMLHttpRequest response will always have an empty string\n * as the \"request.response\" in those cases, resulting in an error\n * when constructing a Response instance.\n * @see https://github.com/mswjs/interceptors/issues/379\n */\n const responseBodyOrNull = FetchResponse.isResponseWithBody(request.status)\n ? body\n : null\n\n return new FetchResponse(responseBodyOrNull, {\n url: request.responseURL,\n status: request.status,\n statusText: request.statusText,\n headers: createHeadersFromXMLHttpRequestHeaders(\n request.getAllResponseHeaders()\n ),\n })\n}\n\nfunction createHeadersFromXMLHttpRequestHeaders(headersString: string): Headers {\n const headers = new Headers()\n\n const lines = headersString.split(/[\\r\\n]+/)\n for (const line of lines) {\n if (line.trim() === '') {\n continue\n }\n\n const [name, ...parts] = line.split(': ')\n const value = parts.join(': ')\n\n headers.append(name, value)\n }\n\n return headers\n}\n","/**\n * Return a total byte length of the given request/response body.\n * If the `Content-Length` header is present, it will be used as the byte length.\n */\nexport async function getBodyByteLength(\n input: Request | Response\n): Promise {\n const explicitContentLength = input.headers.get('content-length')\n\n if (explicitContentLength != null && explicitContentLength !== '') {\n return Number(explicitContentLength)\n }\n\n const buffer = await input.arrayBuffer()\n return buffer.byteLength\n}\n","import { invariant } from 'outvariant'\nimport { isNodeProcess } from 'is-node-process'\nimport type { Logger } from '@open-draft/logger'\nimport { concatArrayBuffer } from './utils/concatArrayBuffer'\nimport { createEvent } from './utils/createEvent'\nimport {\n decodeBuffer,\n encodeBuffer,\n toArrayBuffer,\n} from '../../utils/bufferUtils'\nimport { createProxy } from '../../utils/createProxy'\nimport { isDomParserSupportedType } from './utils/isDomParserSupportedType'\nimport { parseJson } from '../../utils/parseJson'\nimport { createResponse } from './utils/createResponse'\nimport { INTERNAL_REQUEST_ID_HEADER_NAME } from '../../Interceptor'\nimport { createRequestId } from '../../createRequestId'\nimport { getBodyByteLength } from './utils/getBodyByteLength'\nimport { setRawRequest } from '../../getRawRequest'\nimport { FetchRequest } from '../../utils/fetchUtils'\n\nconst kIsRequestHandled = Symbol('kIsRequestHandled')\nconst IS_NODE = isNodeProcess()\nconst kFetchRequest = Symbol('kFetchRequest')\n\n/**\n * An `XMLHttpRequest` instance controller that allows us\n * to handle any given request instance (e.g. responding to it).\n */\nexport class XMLHttpRequestController {\n public request: XMLHttpRequest\n public requestId: string\n public onRequest?: (\n this: XMLHttpRequestController,\n args: {\n request: Request\n requestId: string\n }\n ) => Promise\n public onResponse?: (\n this: XMLHttpRequestController,\n args: {\n response: Response\n isMockedResponse: boolean\n request: Request\n requestId: string\n }\n ) => void;\n\n [kIsRequestHandled]: boolean;\n [kFetchRequest]?: Request\n private method: string = 'GET'\n private url: URL = null as any\n private requestHeaders: Headers\n private responseBuffer: Uint8Array\n private events: Map>\n private uploadEvents: Map<\n keyof XMLHttpRequestEventTargetEventMap,\n Array\n >\n\n constructor(\n readonly initialRequest: XMLHttpRequest,\n public logger: Logger\n ) {\n this[kIsRequestHandled] = false\n\n this.events = new Map()\n this.uploadEvents = new Map()\n this.requestId = createRequestId()\n this.requestHeaders = new Headers()\n this.responseBuffer = new Uint8Array()\n\n this.request = createProxy(initialRequest, {\n setProperty: ([propertyName, nextValue], invoke) => {\n switch (propertyName) {\n case 'ontimeout': {\n const eventName = propertyName.slice(\n 2\n ) as keyof XMLHttpRequestEventTargetEventMap\n\n /**\n * @note Proxy callbacks to event listeners because JSDOM has trouble\n * translating these properties to callbacks. It seemed to be operating\n * on events exclusively.\n */\n this.request.addEventListener(eventName, nextValue as any)\n\n return invoke()\n }\n\n default: {\n return invoke()\n }\n }\n },\n methodCall: ([methodName, args], invoke) => {\n switch (methodName) {\n case 'open': {\n const [method, url] = args as [string, string | undefined]\n\n if (typeof url === 'undefined') {\n this.method = 'GET'\n this.url = toAbsoluteUrl(method)\n } else {\n this.method = method\n this.url = toAbsoluteUrl(url)\n }\n\n this.logger = this.logger.extend(`${this.method} ${this.url.href}`)\n this.logger.info('open', this.method, this.url.href)\n\n return invoke()\n }\n\n case 'addEventListener': {\n const [eventName, listener] = args as [\n keyof XMLHttpRequestEventTargetEventMap,\n Function,\n ]\n\n this.registerEvent(eventName, listener)\n this.logger.info('addEventListener', eventName, listener)\n\n return invoke()\n }\n\n case 'setRequestHeader': {\n const [name, value] = args as [string, string]\n this.requestHeaders.set(name, value)\n\n this.logger.info('setRequestHeader', name, value)\n\n return invoke()\n }\n\n case 'send': {\n const [body] = args as [\n body?: XMLHttpRequestBodyInit | Document | null,\n ]\n\n this.request.addEventListener('load', () => {\n if (typeof this.onResponse !== 'undefined') {\n // Create a Fetch API Response representation of whichever\n // response this XMLHttpRequest received. Note those may\n // be either a mocked and the original response.\n const fetchResponse = createResponse(\n this.request,\n /**\n * The `response` property is the right way to read\n * the ambiguous response body, as the request's \"responseType\" may differ.\n * @see https://xhr.spec.whatwg.org/#the-response-attribute\n */\n this.request.response\n )\n\n // Notify the consumer about the response.\n this.onResponse.call(this, {\n response: fetchResponse,\n isMockedResponse: this[kIsRequestHandled],\n request: fetchRequest,\n requestId: this.requestId!,\n })\n }\n })\n\n const requestBody =\n typeof body === 'string' ? encodeBuffer(body) : body\n\n // Delegate request handling to the consumer.\n const fetchRequest = this.toFetchApiRequest(requestBody)\n this[kFetchRequest] = fetchRequest.clone()\n\n /**\n * @note Start request handling on the next tick so that the user\n * could add event listeners for \"loadend\" before the interceptor fires it.\n */\n queueMicrotask(() => {\n const onceRequestSettled =\n this.onRequest?.call(this, {\n request: fetchRequest,\n requestId: this.requestId!,\n }) || Promise.resolve()\n\n onceRequestSettled.finally(() => {\n // If the consumer didn't handle the request (called `.respondWith()`) perform it as-is.\n if (!this[kIsRequestHandled]) {\n this.logger.info(\n 'request callback settled but request has not been handled (readystate %d), performing as-is...',\n this.request.readyState\n )\n\n /**\n * @note Set the intercepted request ID on the original request in Node.js\n * so that if it triggers any other interceptors, they don't attempt\n * to process it once again.\n *\n * For instance, XMLHttpRequest is often implemented via \"http.ClientRequest\"\n * and we don't want for both XHR and ClientRequest interceptors to\n * handle the same request at the same time (e.g. emit the \"response\" event twice).\n */\n if (IS_NODE) {\n this.request.setRequestHeader(\n INTERNAL_REQUEST_ID_HEADER_NAME,\n this.requestId!\n )\n }\n\n return invoke()\n }\n })\n })\n\n break\n }\n\n default: {\n return invoke()\n }\n }\n },\n })\n\n /**\n * Proxy the `.upload` property to gather the event listeners/callbacks.\n */\n define(\n this.request,\n 'upload',\n createProxy(this.request.upload, {\n setProperty: ([propertyName, nextValue], invoke) => {\n switch (propertyName) {\n case 'onloadstart':\n case 'onprogress':\n case 'onaboart':\n case 'onerror':\n case 'onload':\n case 'ontimeout':\n case 'onloadend': {\n const eventName = propertyName.slice(\n 2\n ) as keyof XMLHttpRequestEventTargetEventMap\n\n this.registerUploadEvent(eventName, nextValue as Function)\n }\n }\n\n return invoke()\n },\n methodCall: ([methodName, args], invoke) => {\n switch (methodName) {\n case 'addEventListener': {\n const [eventName, listener] = args as [\n keyof XMLHttpRequestEventTargetEventMap,\n Function,\n ]\n this.registerUploadEvent(eventName, listener)\n this.logger.info('upload.addEventListener', eventName, listener)\n\n return invoke()\n }\n }\n },\n })\n )\n }\n\n private registerEvent(\n eventName: keyof XMLHttpRequestEventTargetEventMap,\n listener: Function\n ): void {\n const prevEvents = this.events.get(eventName) || []\n const nextEvents = prevEvents.concat(listener)\n this.events.set(eventName, nextEvents)\n\n this.logger.info('registered event \"%s\"', eventName, listener)\n }\n\n private registerUploadEvent(\n eventName: keyof XMLHttpRequestEventTargetEventMap,\n listener: Function\n ): void {\n const prevEvents = this.uploadEvents.get(eventName) || []\n const nextEvents = prevEvents.concat(listener)\n this.uploadEvents.set(eventName, nextEvents)\n\n this.logger.info('registered upload event \"%s\"', eventName, listener)\n }\n\n /**\n * Responds to the current request with the given\n * Fetch API `Response` instance.\n */\n public async respondWith(response: Response): Promise {\n /**\n * @note Since `XMLHttpRequestController` delegates the handling of the responses\n * to the \"load\" event listener that doesn't distinguish between the mocked and original\n * responses, mark the request that had a mocked response with a corresponding symbol.\n *\n * Mark this request as having a mocked response immediately since\n * calculating request/response total body length is asynchronous.\n */\n this[kIsRequestHandled] = true\n\n /**\n * Dispatch request upload events for requests with a body.\n * @see https://github.com/mswjs/interceptors/issues/573\n */\n if (this[kFetchRequest]) {\n const totalRequestBodyLength = await getBodyByteLength(\n this[kFetchRequest]\n )\n\n this.trigger('loadstart', this.request.upload, {\n loaded: 0,\n total: totalRequestBodyLength,\n })\n this.trigger('progress', this.request.upload, {\n loaded: totalRequestBodyLength,\n total: totalRequestBodyLength,\n })\n this.trigger('load', this.request.upload, {\n loaded: totalRequestBodyLength,\n total: totalRequestBodyLength,\n })\n\n this.trigger('loadend', this.request.upload, {\n loaded: totalRequestBodyLength,\n total: totalRequestBodyLength,\n })\n }\n\n this.logger.info(\n 'responding with a mocked response: %d %s',\n response.status,\n response.statusText\n )\n\n define(this.request, 'status', response.status)\n define(this.request, 'statusText', response.statusText)\n define(this.request, 'responseURL', this.url.href)\n\n this.request.getResponseHeader = new Proxy(this.request.getResponseHeader, {\n apply: (_, __, args: [name: string]) => {\n this.logger.info('getResponseHeader', args[0])\n\n if (this.request.readyState < this.request.HEADERS_RECEIVED) {\n this.logger.info('headers not received yet, returning null')\n\n // Headers not received yet, nothing to return.\n return null\n }\n\n const headerValue = response.headers.get(args[0])\n this.logger.info(\n 'resolved response header \"%s\" to',\n args[0],\n headerValue\n )\n\n return headerValue\n },\n })\n\n this.request.getAllResponseHeaders = new Proxy(\n this.request.getAllResponseHeaders,\n {\n apply: () => {\n this.logger.info('getAllResponseHeaders')\n\n if (this.request.readyState < this.request.HEADERS_RECEIVED) {\n this.logger.info('headers not received yet, returning empty string')\n\n // Headers not received yet, nothing to return.\n return ''\n }\n\n const headersList = Array.from(response.headers.entries())\n const allHeaders = headersList\n .map(([headerName, headerValue]) => {\n return `${headerName}: ${headerValue}`\n })\n .join('\\r\\n')\n\n this.logger.info('resolved all response headers to', allHeaders)\n\n return allHeaders\n },\n }\n )\n\n // Update the response getters to resolve against the mocked response.\n Object.defineProperties(this.request, {\n response: {\n enumerable: true,\n configurable: false,\n get: () => this.response,\n },\n responseText: {\n enumerable: true,\n configurable: false,\n get: () => this.responseText,\n },\n responseXML: {\n enumerable: true,\n configurable: false,\n get: () => this.responseXML,\n },\n })\n\n const totalResponseBodyLength = await getBodyByteLength(response.clone())\n\n this.logger.info('calculated response body length', totalResponseBodyLength)\n\n this.trigger('loadstart', this.request, {\n loaded: 0,\n total: totalResponseBodyLength,\n })\n\n this.setReadyState(this.request.HEADERS_RECEIVED)\n this.setReadyState(this.request.LOADING)\n\n const finalizeResponse = () => {\n this.logger.info('finalizing the mocked response...')\n\n this.setReadyState(this.request.DONE)\n\n this.trigger('load', this.request, {\n loaded: this.responseBuffer.byteLength,\n total: totalResponseBodyLength,\n })\n\n this.trigger('loadend', this.request, {\n loaded: this.responseBuffer.byteLength,\n total: totalResponseBodyLength,\n })\n }\n\n if (response.body) {\n this.logger.info('mocked response has body, streaming...')\n\n const reader = response.body.getReader()\n\n const readNextResponseBodyChunk = async () => {\n const { value, done } = await reader.read()\n\n if (done) {\n this.logger.info('response body stream done!')\n finalizeResponse()\n return\n }\n\n if (value) {\n this.logger.info('read response body chunk:', value)\n this.responseBuffer = concatArrayBuffer(this.responseBuffer, value)\n\n this.trigger('progress', this.request, {\n loaded: this.responseBuffer.byteLength,\n total: totalResponseBodyLength,\n })\n }\n\n readNextResponseBodyChunk()\n }\n\n readNextResponseBodyChunk()\n } else {\n finalizeResponse()\n }\n }\n\n private responseBufferToText(): string {\n return decodeBuffer(this.responseBuffer)\n }\n\n get response(): unknown {\n this.logger.info(\n 'getResponse (responseType: %s)',\n this.request.responseType\n )\n\n if (this.request.readyState !== this.request.DONE) {\n return null\n }\n\n switch (this.request.responseType) {\n case 'json': {\n const responseJson = parseJson(this.responseBufferToText())\n this.logger.info('resolved response JSON', responseJson)\n\n return responseJson\n }\n\n case 'arraybuffer': {\n const arrayBuffer = toArrayBuffer(this.responseBuffer)\n this.logger.info('resolved response ArrayBuffer', arrayBuffer)\n\n return arrayBuffer\n }\n\n case 'blob': {\n const mimeType =\n this.request.getResponseHeader('Content-Type') || 'text/plain'\n const responseBlob = new Blob([this.responseBufferToText()], {\n type: mimeType,\n })\n\n this.logger.info(\n 'resolved response Blob (mime type: %s)',\n responseBlob,\n mimeType\n )\n\n return responseBlob\n }\n\n default: {\n const responseText = this.responseBufferToText()\n this.logger.info(\n 'resolving \"%s\" response type as text',\n this.request.responseType,\n responseText\n )\n\n return responseText\n }\n }\n }\n\n get responseText(): string {\n /**\n * Throw when trying to read the response body as text when the\n * \"responseType\" doesn't expect text. This just respects the spec better.\n * @see https://xhr.spec.whatwg.org/#the-responsetext-attribute\n */\n invariant(\n this.request.responseType === '' || this.request.responseType === 'text',\n 'InvalidStateError: The object is in invalid state.'\n )\n\n if (\n this.request.readyState !== this.request.LOADING &&\n this.request.readyState !== this.request.DONE\n ) {\n return ''\n }\n\n const responseText = this.responseBufferToText()\n this.logger.info('getResponseText: \"%s\"', responseText)\n\n return responseText\n }\n\n get responseXML(): Document | null {\n invariant(\n this.request.responseType === '' ||\n this.request.responseType === 'document',\n 'InvalidStateError: The object is in invalid state.'\n )\n\n if (this.request.readyState !== this.request.DONE) {\n return null\n }\n\n const contentType = this.request.getResponseHeader('Content-Type') || ''\n\n if (typeof DOMParser === 'undefined') {\n console.warn(\n 'Cannot retrieve XMLHttpRequest response body as XML: DOMParser is not defined. You are likely using an environment that is not browser or does not polyfill browser globals correctly.'\n )\n return null\n }\n\n if (isDomParserSupportedType(contentType)) {\n return new DOMParser().parseFromString(\n this.responseBufferToText(),\n contentType\n )\n }\n\n return null\n }\n\n public errorWith(error?: Error): void {\n /**\n * @note Mark this request as handled even if it received a mock error.\n * This prevents the controller from trying to perform this request as-is.\n */\n this[kIsRequestHandled] = true\n this.logger.info('responding with an error')\n\n this.setReadyState(this.request.DONE)\n this.trigger('error', this.request)\n this.trigger('loadend', this.request)\n }\n\n /**\n * Transitions this request's `readyState` to the given one.\n */\n private setReadyState(nextReadyState: number): void {\n this.logger.info(\n 'setReadyState: %d -> %d',\n this.request.readyState,\n nextReadyState\n )\n\n if (this.request.readyState === nextReadyState) {\n this.logger.info('ready state identical, skipping transition...')\n return\n }\n\n define(this.request, 'readyState', nextReadyState)\n\n this.logger.info('set readyState to: %d', nextReadyState)\n\n if (nextReadyState !== this.request.UNSENT) {\n this.logger.info('triggering \"readystatechange\" event...')\n\n this.trigger('readystatechange', this.request)\n }\n }\n\n /**\n * Triggers given event on the `XMLHttpRequest` instance.\n */\n private trigger<\n EventName extends keyof (XMLHttpRequestEventTargetEventMap & {\n readystatechange: ProgressEvent\n }),\n >(\n eventName: EventName,\n target: XMLHttpRequest | XMLHttpRequestUpload,\n options?: ProgressEventInit\n ): void {\n const callback = (target as XMLHttpRequest)[`on${eventName}`]\n const event = createEvent(target, eventName, options)\n\n this.logger.info('trigger \"%s\"', eventName, options || '')\n\n // Invoke direct callbacks.\n if (typeof callback === 'function') {\n this.logger.info('found a direct \"%s\" callback, calling...', eventName)\n callback.call(target as XMLHttpRequest, event)\n }\n\n // Invoke event listeners.\n const events =\n target instanceof XMLHttpRequestUpload ? this.uploadEvents : this.events\n\n for (const [registeredEventName, listeners] of events) {\n if (registeredEventName === eventName) {\n this.logger.info(\n 'found %d listener(s) for \"%s\" event, calling...',\n listeners.length,\n eventName\n )\n\n listeners.forEach((listener) => listener.call(target, event))\n }\n }\n }\n\n /**\n * Converts this `XMLHttpRequest` instance into a Fetch API `Request` instance.\n */\n private toFetchApiRequest(\n body: XMLHttpRequestBodyInit | Document | null | undefined\n ): Request {\n this.logger.info('converting request to a Fetch API Request...')\n\n // If the `Document` is used as the body of this XMLHttpRequest,\n // set its inner text as the Fetch API Request body.\n const resolvedBody =\n body instanceof Document ? body.documentElement.innerText : body\n\n const fetchRequest = new FetchRequest(this.url.href, {\n method: this.method,\n headers: this.requestHeaders,\n /**\n * @see https://xhr.spec.whatwg.org/#cross-origin-credentials\n */\n credentials: this.request.withCredentials ? 'include' : 'same-origin',\n body: ['GET', 'HEAD'].includes(this.method.toUpperCase())\n ? null\n : resolvedBody,\n })\n\n const proxyHeaders = createProxy(fetchRequest.headers, {\n methodCall: ([methodName, args], invoke) => {\n // Forward the latest state of the internal request headers\n // because the interceptor might have modified them\n // without responding to the request.\n switch (methodName) {\n case 'append':\n case 'set': {\n const [headerName, headerValue] = args as [string, string]\n this.request.setRequestHeader(headerName, headerValue)\n break\n }\n\n case 'delete': {\n const [headerName] = args as [string]\n console.warn(\n `XMLHttpRequest: Cannot remove a \"${headerName}\" header from the Fetch API representation of the \"${fetchRequest.method} ${fetchRequest.url}\" request. XMLHttpRequest headers cannot be removed.`\n )\n break\n }\n }\n\n return invoke()\n },\n })\n define(fetchRequest, 'headers', proxyHeaders)\n setRawRequest(fetchRequest, this.request)\n\n this.logger.info('converted request to a Fetch API Request!', fetchRequest)\n\n return fetchRequest\n }\n}\n\nfunction toAbsoluteUrl(url: string | URL): URL {\n /**\n * @note XMLHttpRequest interceptor may run in environments\n * that implement XMLHttpRequest but don't implement \"location\"\n * (for example, React Native). If that's the case, return the\n * input URL as-is (nothing to be relative to).\n * @see https://github.com/mswjs/msw/issues/1777\n */\n if (typeof location === 'undefined') {\n return new URL(url)\n }\n\n return new URL(url.toString(), location.href)\n}\n\nfunction define(\n target: object,\n property: string | symbol,\n value: unknown\n): void {\n Reflect.defineProperty(target, property, {\n // Ensure writable properties to allow redefining readonly properties.\n writable: true,\n enumerable: true,\n value,\n })\n}\n","import type { Logger } from '@open-draft/logger'\nimport { XMLHttpRequestEmitter } from '.'\nimport { RequestController } from '../../RequestController'\nimport { XMLHttpRequestController } from './XMLHttpRequestController'\nimport { handleRequest } from '../../utils/handleRequest'\nimport { isResponseError } from '../../utils/responseUtils'\n\nexport interface XMLHttpRequestProxyOptions {\n emitter: XMLHttpRequestEmitter\n logger: Logger\n}\n\n/**\n * Create a proxied `XMLHttpRequest` class.\n * The proxied class establishes spies on certain methods,\n * allowing us to intercept requests and respond to them.\n */\nexport function createXMLHttpRequestProxy({\n emitter,\n logger,\n}: XMLHttpRequestProxyOptions) {\n const XMLHttpRequestProxy = new Proxy(globalThis.XMLHttpRequest, {\n construct(target, args, newTarget) {\n logger.info('constructed new XMLHttpRequest')\n\n const originalRequest = Reflect.construct(\n target,\n args,\n newTarget\n ) as XMLHttpRequest\n\n /**\n * @note Forward prototype descriptors onto the proxied object.\n * XMLHttpRequest is implemented in JSDOM in a way that assigns\n * a bunch of descriptors, like \"set responseType()\" on the prototype.\n * With this propagation, we make sure that those descriptors trigger\n * when the user operates with the proxied request instance.\n */\n const prototypeDescriptors = Object.getOwnPropertyDescriptors(\n target.prototype\n )\n for (const propertyName in prototypeDescriptors) {\n Reflect.defineProperty(\n originalRequest,\n propertyName,\n prototypeDescriptors[propertyName]\n )\n }\n\n const xhrRequestController = new XMLHttpRequestController(\n originalRequest,\n logger\n )\n\n xhrRequestController.onRequest = async function ({ request, requestId }) {\n const controller = new RequestController(request, {\n passthrough: () => {\n this.logger.info(\n 'no mocked response received, performing request as-is...'\n )\n },\n respondWith: async (response) => {\n if (isResponseError(response)) {\n this.errorWith(new TypeError('Network error'))\n return\n }\n\n await this.respondWith(response)\n },\n errorWith: (reason) => {\n this.logger.info('request errored!', { error: reason })\n\n if (reason instanceof Error) {\n this.errorWith(reason)\n }\n },\n })\n\n this.logger.info('awaiting mocked response...')\n\n this.logger.info(\n 'emitting the \"request\" event for %s listener(s)...',\n emitter.listenerCount('request')\n )\n\n await handleRequest({\n request,\n requestId,\n controller,\n emitter,\n })\n }\n\n xhrRequestController.onResponse = async function ({\n response,\n isMockedResponse,\n request,\n requestId,\n }) {\n this.logger.info(\n 'emitting the \"response\" event for %s listener(s)...',\n emitter.listenerCount('response')\n )\n\n emitter.emit('response', {\n response,\n isMockedResponse,\n request,\n requestId,\n })\n }\n\n // Return the proxied request from the controller\n // so that the controller can react to the consumer's interactions\n // with this request (opening/sending/etc).\n return xhrRequestController.request\n },\n })\n\n return XMLHttpRequestProxy\n}\n","import { Emitter } from 'strict-event-emitter'\nimport { HttpRequestEventMap } from '../../glossary'\nimport { Interceptor } from '../../Interceptor'\nimport { createXMLHttpRequestProxy } from './XMLHttpRequestProxy'\nimport { hasConfigurableGlobal } from '../../utils/hasConfigurableGlobal'\nimport { patchesRegistry } from '../../utils/patchesRegistry'\n\nexport type XMLHttpRequestEmitter = Emitter\n\nexport class XMLHttpRequestInterceptor extends Interceptor {\n static symbol = Symbol.for('xhr-interceptor')\n\n constructor() {\n super(XMLHttpRequestInterceptor.symbol)\n }\n\n protected checkEnvironment() {\n return hasConfigurableGlobal('XMLHttpRequest')\n }\n\n protected setup() {\n const logger = this.logger.extend('setup')\n\n logger.info('patching global XMLHttpRequest...')\n\n this.subscriptions.push(\n patchesRegistry.applyPatch(globalThis, 'XMLHttpRequest', () => {\n return createXMLHttpRequestProxy({\n emitter: this.emitter,\n logger: this.logger,\n })\n })\n )\n\n logger.info(\n 'global XMLHttpRequest patched!',\n globalThis.XMLHttpRequest.name\n )\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAGA,SAAgB,kBACd,MACA,OACY;CACZ,MAAM,SAAS,IAAI,WAAW,KAAK,aAAa,MAAM,WAAW;AACjE,QAAO,IAAI,MAAM,EAAE;AACnB,QAAO,IAAI,OAAO,KAAK,WAAW;AAClC,QAAO;;;;;ACVT,IAAa,gBAAb,MAA4C;CAwB1C,YACE,MACA,SACA;cA1Bc;yBACW;mBACN;wBACK;cAEJ;oBACkB;uBAEG;oBACf;mBAEA;kBACD;oBACE;0BACM;iBACT;0BACS;gBACX;eACD;sBAEC;qBACD;AAMrB,OAAK,OAAO;AACZ,OAAK,SAAS,SAAS,UAAU;AACjC,OAAK,gBAAgB,SAAS,iBAAiB;AAC/C,OAAK,YAAY,KAAK,KAAK;;CAG7B,AAAO,eAA8B;AACnC,SAAO,EAAE;;CA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zC,AAAU,mBAAmB;AAC3B,SAAOC,oDAAsB,iBAAiB;;CAGhD,AAAU,QAAQ;EAChB,MAAM,SAAS,KAAK,OAAO,OAAO,QAAQ;AAE1C,SAAO,KAAK,oCAAoC;AAEhD,OAAK,cAAc,KACjBC,8CAAgB,WAAW,YAAY,wBAAwB;AAC7D,UAAO,0BAA0B;IAC/B,SAAS,KAAK;IACd,QAAQ,KAAK;IACd,CAAC;IACF,CACH;AAED,SAAO,KACL,kCACA,WAAW,eAAe,KAC3B"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/XMLHttpRequest-Dw6Wm-UU.mjs b/node_modules/@mswjs/interceptors/lib/node/XMLHttpRequest-Dw6Wm-UU.mjs new file mode 100644 index 0000000000000000000000000000000000000000..8449081ccece8ac2229ecaad5f7c315fbe882b00 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/XMLHttpRequest-Dw6Wm-UU.mjs @@ -0,0 +1,746 @@ +import { a as RequestController, c as Interceptor, i as createRequestId, n as FetchResponse, s as INTERNAL_REQUEST_ID_HEADER_NAME, t as FetchRequest } from "./fetchUtils-BKJ1XmiO.mjs"; +import { n as encodeBuffer, r as toArrayBuffer, t as decodeBuffer } from "./bufferUtils-DxPxwff_.mjs"; +import { n as setRawRequest } from "./getRawRequest-C2-1urzA.mjs"; +import { n as isResponseError, t as handleRequest } from "./handleRequest-FIQv5pwH.mjs"; +import { n as patchesRegistry, t as hasConfigurableGlobal } from "./hasConfigurableGlobal-BiTmog1u.mjs"; +import { invariant } from "outvariant"; +import { isNodeProcess } from "is-node-process"; + +//#region src/interceptors/XMLHttpRequest/utils/concatArrayBuffer.ts +/** +* Concatenate two `Uint8Array` buffers. +*/ +function concatArrayBuffer(left, right) { + const result = new Uint8Array(left.byteLength + right.byteLength); + result.set(left, 0); + result.set(right, left.byteLength); + return result; +} + +//#endregion +//#region src/interceptors/XMLHttpRequest/polyfills/EventPolyfill.ts +var EventPolyfill = class { + constructor(type, options) { + this.NONE = 0; + this.CAPTURING_PHASE = 1; + this.AT_TARGET = 2; + this.BUBBLING_PHASE = 3; + this.type = ""; + this.srcElement = null; + this.currentTarget = null; + this.eventPhase = 0; + this.isTrusted = true; + this.composed = false; + this.cancelable = true; + this.defaultPrevented = false; + this.bubbles = true; + this.lengthComputable = true; + this.loaded = 0; + this.total = 0; + this.cancelBubble = false; + this.returnValue = true; + this.type = type; + this.target = options?.target || null; + this.currentTarget = options?.currentTarget || null; + this.timeStamp = Date.now(); + } + composedPath() { + return []; + } + initEvent(type, bubbles, cancelable) { + this.type = type; + this.bubbles = !!bubbles; + this.cancelable = !!cancelable; + } + preventDefault() { + this.defaultPrevented = true; + } + stopPropagation() {} + stopImmediatePropagation() {} +}; + +//#endregion +//#region src/interceptors/XMLHttpRequest/polyfills/ProgressEventPolyfill.ts +var ProgressEventPolyfill = class extends EventPolyfill { + constructor(type, init) { + super(type); + this.lengthComputable = init?.lengthComputable || false; + this.composed = init?.composed || false; + this.loaded = init?.loaded || 0; + this.total = init?.total || 0; + } +}; + +//#endregion +//#region src/interceptors/XMLHttpRequest/utils/createEvent.ts +const SUPPORTS_PROGRESS_EVENT = typeof ProgressEvent !== "undefined"; +function createEvent(target, type, init) { + const progressEvents = [ + "error", + "progress", + "loadstart", + "loadend", + "load", + "timeout", + "abort" + ]; + /** + * `ProgressEvent` is not supported in React Native. + * @see https://github.com/mswjs/interceptors/issues/40 + */ + const ProgressEventClass = SUPPORTS_PROGRESS_EVENT ? ProgressEvent : ProgressEventPolyfill; + return progressEvents.includes(type) ? new ProgressEventClass(type, { + lengthComputable: true, + loaded: init?.loaded || 0, + total: init?.total || 0 + }) : new EventPolyfill(type, { + target, + currentTarget: target + }); +} + +//#endregion +//#region src/utils/findPropertySource.ts +/** +* Returns the source object of the given property on the target object +* (the target itself, any parent in its prototype, or null). +*/ +function findPropertySource(target, propertyName) { + if (!(propertyName in target)) return null; + if (Object.prototype.hasOwnProperty.call(target, propertyName)) return target; + const prototype = Reflect.getPrototypeOf(target); + return prototype ? findPropertySource(prototype, propertyName) : null; +} + +//#endregion +//#region src/utils/createProxy.ts +function createProxy(target, options) { + return new Proxy(target, optionsToProxyHandler(options)); +} +function optionsToProxyHandler(options) { + const { constructorCall, methodCall, getProperty, setProperty } = options; + const handler = {}; + if (typeof constructorCall !== "undefined") handler.construct = function(target, args, newTarget) { + const next = Reflect.construct.bind(null, target, args, newTarget); + return constructorCall.call(newTarget, args, next); + }; + handler.set = function(target, propertyName, nextValue) { + const next = () => { + const propertySource = findPropertySource(target, propertyName) || target; + const ownDescriptors = Reflect.getOwnPropertyDescriptor(propertySource, propertyName); + if (typeof ownDescriptors?.set !== "undefined") { + ownDescriptors.set.apply(target, [nextValue]); + return true; + } + return Reflect.defineProperty(propertySource, propertyName, { + writable: true, + enumerable: true, + configurable: true, + value: nextValue + }); + }; + if (typeof setProperty !== "undefined") return setProperty.call(target, [propertyName, nextValue], next); + return next(); + }; + handler.get = function(target, propertyName, receiver) { + /** + * @note Using `Reflect.get()` here causes "TypeError: Illegal invocation". + */ + const next = () => target[propertyName]; + const value = typeof getProperty !== "undefined" ? getProperty.call(target, [propertyName, receiver], next) : next(); + if (typeof value === "function") return (...args) => { + const next$1 = value.bind(target, ...args); + if (typeof methodCall !== "undefined") return methodCall.call(target, [propertyName, args], next$1); + return next$1(); + }; + return value; + }; + return handler; +} + +//#endregion +//#region src/interceptors/XMLHttpRequest/utils/isDomParserSupportedType.ts +function isDomParserSupportedType(type) { + return [ + "application/xhtml+xml", + "application/xml", + "image/svg+xml", + "text/html", + "text/xml" + ].some((supportedType) => { + return type.startsWith(supportedType); + }); +} + +//#endregion +//#region src/utils/parseJson.ts +/** +* Parses a given string into JSON. +* Gracefully handles invalid JSON by returning `null`. +*/ +function parseJson(data) { + try { + return JSON.parse(data); + } catch (_) { + return null; + } +} + +//#endregion +//#region src/interceptors/XMLHttpRequest/utils/createResponse.ts +/** +* Creates a Fetch API `Response` instance from the given +* `XMLHttpRequest` instance and a response body. +*/ +function createResponse(request, body) { + return new FetchResponse(FetchResponse.isResponseWithBody(request.status) ? body : null, { + url: request.responseURL, + status: request.status, + statusText: request.statusText, + headers: createHeadersFromXMLHttpRequestHeaders(request.getAllResponseHeaders()) + }); +} +function createHeadersFromXMLHttpRequestHeaders(headersString) { + const headers = new Headers(); + const lines = headersString.split(/[\r\n]+/); + for (const line of lines) { + if (line.trim() === "") continue; + const [name, ...parts] = line.split(": "); + const value = parts.join(": "); + headers.append(name, value); + } + return headers; +} + +//#endregion +//#region src/interceptors/XMLHttpRequest/utils/getBodyByteLength.ts +/** +* Return a total byte length of the given request/response body. +* If the `Content-Length` header is present, it will be used as the byte length. +*/ +async function getBodyByteLength(input) { + const explicitContentLength = input.headers.get("content-length"); + if (explicitContentLength != null && explicitContentLength !== "") return Number(explicitContentLength); + return (await input.arrayBuffer()).byteLength; +} + +//#endregion +//#region src/interceptors/XMLHttpRequest/XMLHttpRequestController.ts +const kIsRequestHandled = Symbol("kIsRequestHandled"); +const IS_NODE = isNodeProcess(); +const kFetchRequest = Symbol("kFetchRequest"); +/** +* An `XMLHttpRequest` instance controller that allows us +* to handle any given request instance (e.g. responding to it). +*/ +var XMLHttpRequestController = class { + constructor(initialRequest, logger) { + this.initialRequest = initialRequest; + this.logger = logger; + this.method = "GET"; + this.url = null; + this[kIsRequestHandled] = false; + this.events = /* @__PURE__ */ new Map(); + this.uploadEvents = /* @__PURE__ */ new Map(); + this.requestId = createRequestId(); + this.requestHeaders = new Headers(); + this.responseBuffer = new Uint8Array(); + this.request = createProxy(initialRequest, { + setProperty: ([propertyName, nextValue], invoke) => { + switch (propertyName) { + case "ontimeout": { + const eventName = propertyName.slice(2); + /** + * @note Proxy callbacks to event listeners because JSDOM has trouble + * translating these properties to callbacks. It seemed to be operating + * on events exclusively. + */ + this.request.addEventListener(eventName, nextValue); + return invoke(); + } + default: return invoke(); + } + }, + methodCall: ([methodName, args], invoke) => { + switch (methodName) { + case "open": { + const [method, url] = args; + if (typeof url === "undefined") { + this.method = "GET"; + this.url = toAbsoluteUrl(method); + } else { + this.method = method; + this.url = toAbsoluteUrl(url); + } + this.logger = this.logger.extend(`${this.method} ${this.url.href}`); + this.logger.info("open", this.method, this.url.href); + return invoke(); + } + case "addEventListener": { + const [eventName, listener] = args; + this.registerEvent(eventName, listener); + this.logger.info("addEventListener", eventName, listener); + return invoke(); + } + case "setRequestHeader": { + const [name, value] = args; + this.requestHeaders.set(name, value); + this.logger.info("setRequestHeader", name, value); + return invoke(); + } + case "send": { + const [body] = args; + this.request.addEventListener("load", () => { + if (typeof this.onResponse !== "undefined") { + const fetchResponse = createResponse( + this.request, + /** + * The `response` property is the right way to read + * the ambiguous response body, as the request's "responseType" may differ. + * @see https://xhr.spec.whatwg.org/#the-response-attribute + */ + this.request.response + ); + this.onResponse.call(this, { + response: fetchResponse, + isMockedResponse: this[kIsRequestHandled], + request: fetchRequest, + requestId: this.requestId + }); + } + }); + const requestBody = typeof body === "string" ? encodeBuffer(body) : body; + const fetchRequest = this.toFetchApiRequest(requestBody); + this[kFetchRequest] = fetchRequest.clone(); + /** + * @note Start request handling on the next tick so that the user + * could add event listeners for "loadend" before the interceptor fires it. + */ + queueMicrotask(() => { + (this.onRequest?.call(this, { + request: fetchRequest, + requestId: this.requestId + }) || Promise.resolve()).finally(() => { + if (!this[kIsRequestHandled]) { + this.logger.info("request callback settled but request has not been handled (readystate %d), performing as-is...", this.request.readyState); + /** + * @note Set the intercepted request ID on the original request in Node.js + * so that if it triggers any other interceptors, they don't attempt + * to process it once again. + * + * For instance, XMLHttpRequest is often implemented via "http.ClientRequest" + * and we don't want for both XHR and ClientRequest interceptors to + * handle the same request at the same time (e.g. emit the "response" event twice). + */ + if (IS_NODE) this.request.setRequestHeader(INTERNAL_REQUEST_ID_HEADER_NAME, this.requestId); + return invoke(); + } + }); + }); + break; + } + default: return invoke(); + } + } + }); + /** + * Proxy the `.upload` property to gather the event listeners/callbacks. + */ + define(this.request, "upload", createProxy(this.request.upload, { + setProperty: ([propertyName, nextValue], invoke) => { + switch (propertyName) { + case "onloadstart": + case "onprogress": + case "onaboart": + case "onerror": + case "onload": + case "ontimeout": + case "onloadend": { + const eventName = propertyName.slice(2); + this.registerUploadEvent(eventName, nextValue); + } + } + return invoke(); + }, + methodCall: ([methodName, args], invoke) => { + switch (methodName) { + case "addEventListener": { + const [eventName, listener] = args; + this.registerUploadEvent(eventName, listener); + this.logger.info("upload.addEventListener", eventName, listener); + return invoke(); + } + } + } + })); + } + registerEvent(eventName, listener) { + const nextEvents = (this.events.get(eventName) || []).concat(listener); + this.events.set(eventName, nextEvents); + this.logger.info("registered event \"%s\"", eventName, listener); + } + registerUploadEvent(eventName, listener) { + const nextEvents = (this.uploadEvents.get(eventName) || []).concat(listener); + this.uploadEvents.set(eventName, nextEvents); + this.logger.info("registered upload event \"%s\"", eventName, listener); + } + /** + * Responds to the current request with the given + * Fetch API `Response` instance. + */ + async respondWith(response) { + /** + * @note Since `XMLHttpRequestController` delegates the handling of the responses + * to the "load" event listener that doesn't distinguish between the mocked and original + * responses, mark the request that had a mocked response with a corresponding symbol. + * + * Mark this request as having a mocked response immediately since + * calculating request/response total body length is asynchronous. + */ + this[kIsRequestHandled] = true; + /** + * Dispatch request upload events for requests with a body. + * @see https://github.com/mswjs/interceptors/issues/573 + */ + if (this[kFetchRequest]) { + const totalRequestBodyLength = await getBodyByteLength(this[kFetchRequest]); + this.trigger("loadstart", this.request.upload, { + loaded: 0, + total: totalRequestBodyLength + }); + this.trigger("progress", this.request.upload, { + loaded: totalRequestBodyLength, + total: totalRequestBodyLength + }); + this.trigger("load", this.request.upload, { + loaded: totalRequestBodyLength, + total: totalRequestBodyLength + }); + this.trigger("loadend", this.request.upload, { + loaded: totalRequestBodyLength, + total: totalRequestBodyLength + }); + } + this.logger.info("responding with a mocked response: %d %s", response.status, response.statusText); + define(this.request, "status", response.status); + define(this.request, "statusText", response.statusText); + define(this.request, "responseURL", this.url.href); + this.request.getResponseHeader = new Proxy(this.request.getResponseHeader, { apply: (_, __, args) => { + this.logger.info("getResponseHeader", args[0]); + if (this.request.readyState < this.request.HEADERS_RECEIVED) { + this.logger.info("headers not received yet, returning null"); + return null; + } + const headerValue = response.headers.get(args[0]); + this.logger.info("resolved response header \"%s\" to", args[0], headerValue); + return headerValue; + } }); + this.request.getAllResponseHeaders = new Proxy(this.request.getAllResponseHeaders, { apply: () => { + this.logger.info("getAllResponseHeaders"); + if (this.request.readyState < this.request.HEADERS_RECEIVED) { + this.logger.info("headers not received yet, returning empty string"); + return ""; + } + const allHeaders = Array.from(response.headers.entries()).map(([headerName, headerValue]) => { + return `${headerName}: ${headerValue}`; + }).join("\r\n"); + this.logger.info("resolved all response headers to", allHeaders); + return allHeaders; + } }); + Object.defineProperties(this.request, { + response: { + enumerable: true, + configurable: false, + get: () => this.response + }, + responseText: { + enumerable: true, + configurable: false, + get: () => this.responseText + }, + responseXML: { + enumerable: true, + configurable: false, + get: () => this.responseXML + } + }); + const totalResponseBodyLength = await getBodyByteLength(response.clone()); + this.logger.info("calculated response body length", totalResponseBodyLength); + this.trigger("loadstart", this.request, { + loaded: 0, + total: totalResponseBodyLength + }); + this.setReadyState(this.request.HEADERS_RECEIVED); + this.setReadyState(this.request.LOADING); + const finalizeResponse = () => { + this.logger.info("finalizing the mocked response..."); + this.setReadyState(this.request.DONE); + this.trigger("load", this.request, { + loaded: this.responseBuffer.byteLength, + total: totalResponseBodyLength + }); + this.trigger("loadend", this.request, { + loaded: this.responseBuffer.byteLength, + total: totalResponseBodyLength + }); + }; + if (response.body) { + this.logger.info("mocked response has body, streaming..."); + const reader = response.body.getReader(); + const readNextResponseBodyChunk = async () => { + const { value, done } = await reader.read(); + if (done) { + this.logger.info("response body stream done!"); + finalizeResponse(); + return; + } + if (value) { + this.logger.info("read response body chunk:", value); + this.responseBuffer = concatArrayBuffer(this.responseBuffer, value); + this.trigger("progress", this.request, { + loaded: this.responseBuffer.byteLength, + total: totalResponseBodyLength + }); + } + readNextResponseBodyChunk(); + }; + readNextResponseBodyChunk(); + } else finalizeResponse(); + } + responseBufferToText() { + return decodeBuffer(this.responseBuffer); + } + get response() { + this.logger.info("getResponse (responseType: %s)", this.request.responseType); + if (this.request.readyState !== this.request.DONE) return null; + switch (this.request.responseType) { + case "json": { + const responseJson = parseJson(this.responseBufferToText()); + this.logger.info("resolved response JSON", responseJson); + return responseJson; + } + case "arraybuffer": { + const arrayBuffer = toArrayBuffer(this.responseBuffer); + this.logger.info("resolved response ArrayBuffer", arrayBuffer); + return arrayBuffer; + } + case "blob": { + const mimeType = this.request.getResponseHeader("Content-Type") || "text/plain"; + const responseBlob = new Blob([this.responseBufferToText()], { type: mimeType }); + this.logger.info("resolved response Blob (mime type: %s)", responseBlob, mimeType); + return responseBlob; + } + default: { + const responseText = this.responseBufferToText(); + this.logger.info("resolving \"%s\" response type as text", this.request.responseType, responseText); + return responseText; + } + } + } + get responseText() { + /** + * Throw when trying to read the response body as text when the + * "responseType" doesn't expect text. This just respects the spec better. + * @see https://xhr.spec.whatwg.org/#the-responsetext-attribute + */ + invariant(this.request.responseType === "" || this.request.responseType === "text", "InvalidStateError: The object is in invalid state."); + if (this.request.readyState !== this.request.LOADING && this.request.readyState !== this.request.DONE) return ""; + const responseText = this.responseBufferToText(); + this.logger.info("getResponseText: \"%s\"", responseText); + return responseText; + } + get responseXML() { + invariant(this.request.responseType === "" || this.request.responseType === "document", "InvalidStateError: The object is in invalid state."); + if (this.request.readyState !== this.request.DONE) return null; + const contentType = this.request.getResponseHeader("Content-Type") || ""; + if (typeof DOMParser === "undefined") { + console.warn("Cannot retrieve XMLHttpRequest response body as XML: DOMParser is not defined. You are likely using an environment that is not browser or does not polyfill browser globals correctly."); + return null; + } + if (isDomParserSupportedType(contentType)) return new DOMParser().parseFromString(this.responseBufferToText(), contentType); + return null; + } + errorWith(error) { + /** + * @note Mark this request as handled even if it received a mock error. + * This prevents the controller from trying to perform this request as-is. + */ + this[kIsRequestHandled] = true; + this.logger.info("responding with an error"); + this.setReadyState(this.request.DONE); + this.trigger("error", this.request); + this.trigger("loadend", this.request); + } + /** + * Transitions this request's `readyState` to the given one. + */ + setReadyState(nextReadyState) { + this.logger.info("setReadyState: %d -> %d", this.request.readyState, nextReadyState); + if (this.request.readyState === nextReadyState) { + this.logger.info("ready state identical, skipping transition..."); + return; + } + define(this.request, "readyState", nextReadyState); + this.logger.info("set readyState to: %d", nextReadyState); + if (nextReadyState !== this.request.UNSENT) { + this.logger.info("triggering \"readystatechange\" event..."); + this.trigger("readystatechange", this.request); + } + } + /** + * Triggers given event on the `XMLHttpRequest` instance. + */ + trigger(eventName, target, options) { + const callback = target[`on${eventName}`]; + const event = createEvent(target, eventName, options); + this.logger.info("trigger \"%s\"", eventName, options || ""); + if (typeof callback === "function") { + this.logger.info("found a direct \"%s\" callback, calling...", eventName); + callback.call(target, event); + } + const events = target instanceof XMLHttpRequestUpload ? this.uploadEvents : this.events; + for (const [registeredEventName, listeners] of events) if (registeredEventName === eventName) { + this.logger.info("found %d listener(s) for \"%s\" event, calling...", listeners.length, eventName); + listeners.forEach((listener) => listener.call(target, event)); + } + } + /** + * Converts this `XMLHttpRequest` instance into a Fetch API `Request` instance. + */ + toFetchApiRequest(body) { + this.logger.info("converting request to a Fetch API Request..."); + const resolvedBody = body instanceof Document ? body.documentElement.innerText : body; + const fetchRequest = new FetchRequest(this.url.href, { + method: this.method, + headers: this.requestHeaders, + credentials: this.request.withCredentials ? "include" : "same-origin", + body: ["GET", "HEAD"].includes(this.method.toUpperCase()) ? null : resolvedBody + }); + define(fetchRequest, "headers", createProxy(fetchRequest.headers, { methodCall: ([methodName, args], invoke) => { + switch (methodName) { + case "append": + case "set": { + const [headerName, headerValue] = args; + this.request.setRequestHeader(headerName, headerValue); + break; + } + case "delete": { + const [headerName] = args; + console.warn(`XMLHttpRequest: Cannot remove a "${headerName}" header from the Fetch API representation of the "${fetchRequest.method} ${fetchRequest.url}" request. XMLHttpRequest headers cannot be removed.`); + break; + } + } + return invoke(); + } })); + setRawRequest(fetchRequest, this.request); + this.logger.info("converted request to a Fetch API Request!", fetchRequest); + return fetchRequest; + } +}; +function toAbsoluteUrl(url) { + /** + * @note XMLHttpRequest interceptor may run in environments + * that implement XMLHttpRequest but don't implement "location" + * (for example, React Native). If that's the case, return the + * input URL as-is (nothing to be relative to). + * @see https://github.com/mswjs/msw/issues/1777 + */ + if (typeof location === "undefined") return new URL(url); + return new URL(url.toString(), location.href); +} +function define(target, property, value) { + Reflect.defineProperty(target, property, { + writable: true, + enumerable: true, + value + }); +} + +//#endregion +//#region src/interceptors/XMLHttpRequest/XMLHttpRequestProxy.ts +/** +* Create a proxied `XMLHttpRequest` class. +* The proxied class establishes spies on certain methods, +* allowing us to intercept requests and respond to them. +*/ +function createXMLHttpRequestProxy({ emitter, logger }) { + return new Proxy(globalThis.XMLHttpRequest, { construct(target, args, newTarget) { + logger.info("constructed new XMLHttpRequest"); + const originalRequest = Reflect.construct(target, args, newTarget); + /** + * @note Forward prototype descriptors onto the proxied object. + * XMLHttpRequest is implemented in JSDOM in a way that assigns + * a bunch of descriptors, like "set responseType()" on the prototype. + * With this propagation, we make sure that those descriptors trigger + * when the user operates with the proxied request instance. + */ + const prototypeDescriptors = Object.getOwnPropertyDescriptors(target.prototype); + for (const propertyName in prototypeDescriptors) Reflect.defineProperty(originalRequest, propertyName, prototypeDescriptors[propertyName]); + const xhrRequestController = new XMLHttpRequestController(originalRequest, logger); + xhrRequestController.onRequest = async function({ request, requestId }) { + const controller = new RequestController(request, { + passthrough: () => { + this.logger.info("no mocked response received, performing request as-is..."); + }, + respondWith: async (response) => { + if (isResponseError(response)) { + this.errorWith(/* @__PURE__ */ new TypeError("Network error")); + return; + } + await this.respondWith(response); + }, + errorWith: (reason) => { + this.logger.info("request errored!", { error: reason }); + if (reason instanceof Error) this.errorWith(reason); + } + }); + this.logger.info("awaiting mocked response..."); + this.logger.info("emitting the \"request\" event for %s listener(s)...", emitter.listenerCount("request")); + await handleRequest({ + request, + requestId, + controller, + emitter + }); + }; + xhrRequestController.onResponse = async function({ response, isMockedResponse, request, requestId }) { + this.logger.info("emitting the \"response\" event for %s listener(s)...", emitter.listenerCount("response")); + emitter.emit("response", { + response, + isMockedResponse, + request, + requestId + }); + }; + return xhrRequestController.request; + } }); +} + +//#endregion +//#region src/interceptors/XMLHttpRequest/index.ts +var XMLHttpRequestInterceptor = class XMLHttpRequestInterceptor extends Interceptor { + static { + this.symbol = Symbol.for("xhr-interceptor"); + } + constructor() { + super(XMLHttpRequestInterceptor.symbol); + } + checkEnvironment() { + return hasConfigurableGlobal("XMLHttpRequest"); + } + setup() { + const logger = this.logger.extend("setup"); + logger.info("patching global XMLHttpRequest..."); + this.subscriptions.push(patchesRegistry.applyPatch(globalThis, "XMLHttpRequest", () => { + return createXMLHttpRequestProxy({ + emitter: this.emitter, + logger: this.logger + }); + })); + logger.info("global XMLHttpRequest patched!", globalThis.XMLHttpRequest.name); + } +}; + +//#endregion +export { XMLHttpRequestInterceptor as t }; +//# sourceMappingURL=XMLHttpRequest-Dw6Wm-UU.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/XMLHttpRequest-Dw6Wm-UU.mjs.map b/node_modules/@mswjs/interceptors/lib/node/XMLHttpRequest-Dw6Wm-UU.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..24c5d9851152521e8f6bb394767a4b6b73518f38 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/XMLHttpRequest-Dw6Wm-UU.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"XMLHttpRequest-Dw6Wm-UU.mjs","names":["handler: ProxyHandler","next","initialRequest: XMLHttpRequest","logger: Logger"],"sources":["../../src/interceptors/XMLHttpRequest/utils/concatArrayBuffer.ts","../../src/interceptors/XMLHttpRequest/polyfills/EventPolyfill.ts","../../src/interceptors/XMLHttpRequest/polyfills/ProgressEventPolyfill.ts","../../src/interceptors/XMLHttpRequest/utils/createEvent.ts","../../src/utils/findPropertySource.ts","../../src/utils/createProxy.ts","../../src/interceptors/XMLHttpRequest/utils/isDomParserSupportedType.ts","../../src/utils/parseJson.ts","../../src/interceptors/XMLHttpRequest/utils/createResponse.ts","../../src/interceptors/XMLHttpRequest/utils/getBodyByteLength.ts","../../src/interceptors/XMLHttpRequest/XMLHttpRequestController.ts","../../src/interceptors/XMLHttpRequest/XMLHttpRequestProxy.ts","../../src/interceptors/XMLHttpRequest/index.ts"],"sourcesContent":["/**\n * Concatenate two `Uint8Array` buffers.\n */\nexport function concatArrayBuffer(\n left: Uint8Array,\n right: Uint8Array\n): Uint8Array {\n const result = new Uint8Array(left.byteLength + right.byteLength)\n result.set(left, 0)\n result.set(right, left.byteLength)\n return result\n}\n","export class EventPolyfill implements Event {\n readonly NONE = 0\n readonly CAPTURING_PHASE = 1\n readonly AT_TARGET = 2\n readonly BUBBLING_PHASE = 3\n\n public type: string = ''\n public srcElement: EventTarget | null = null\n public target: EventTarget | null\n public currentTarget: EventTarget | null = null\n public eventPhase: number = 0\n public timeStamp: number\n public isTrusted: boolean = true\n public composed: boolean = false\n public cancelable: boolean = true\n public defaultPrevented: boolean = false\n public bubbles: boolean = true\n public lengthComputable: boolean = true\n public loaded: number = 0\n public total: number = 0\n\n cancelBubble: boolean = false\n returnValue: boolean = true\n\n constructor(\n type: string,\n options?: { target: EventTarget; currentTarget: EventTarget }\n ) {\n this.type = type\n this.target = options?.target || null\n this.currentTarget = options?.currentTarget || null\n this.timeStamp = Date.now()\n }\n\n public composedPath(): EventTarget[] {\n return []\n }\n\n public initEvent(type: string, bubbles?: boolean, cancelable?: boolean) {\n this.type = type\n this.bubbles = !!bubbles\n this.cancelable = !!cancelable\n }\n\n public preventDefault() {\n this.defaultPrevented = true\n }\n\n public stopPropagation() {}\n public stopImmediatePropagation() {}\n}\n","import { EventPolyfill } from './EventPolyfill'\n\nexport class ProgressEventPolyfill extends EventPolyfill {\n readonly lengthComputable: boolean\n readonly composed: boolean\n readonly loaded: number\n readonly total: number\n\n constructor(type: string, init?: ProgressEventInit) {\n super(type)\n\n this.lengthComputable = init?.lengthComputable || false\n this.composed = init?.composed || false\n this.loaded = init?.loaded || 0\n this.total = init?.total || 0\n }\n}\n","import { EventPolyfill } from '../polyfills/EventPolyfill'\nimport { ProgressEventPolyfill } from '../polyfills/ProgressEventPolyfill'\n\nconst SUPPORTS_PROGRESS_EVENT = typeof ProgressEvent !== 'undefined'\n\nexport function createEvent(\n target: XMLHttpRequest | XMLHttpRequestUpload,\n type: string,\n init?: ProgressEventInit\n): EventPolyfill | ProgressEvent {\n const progressEvents = [\n 'error',\n 'progress',\n 'loadstart',\n 'loadend',\n 'load',\n 'timeout',\n 'abort',\n ]\n\n /**\n * `ProgressEvent` is not supported in React Native.\n * @see https://github.com/mswjs/interceptors/issues/40\n */\n const ProgressEventClass = SUPPORTS_PROGRESS_EVENT\n ? ProgressEvent\n : ProgressEventPolyfill\n\n const event = progressEvents.includes(type)\n ? new ProgressEventClass(type, {\n lengthComputable: true,\n loaded: init?.loaded || 0,\n total: init?.total || 0,\n })\n : new EventPolyfill(type, {\n target,\n currentTarget: target,\n })\n\n return event\n}\n","/**\n * Returns the source object of the given property on the target object\n * (the target itself, any parent in its prototype, or null).\n */\nexport function findPropertySource(\n target: object,\n propertyName: string | symbol\n): object | null {\n if (!(propertyName in target)) {\n return null\n }\n\n const hasProperty = Object.prototype.hasOwnProperty.call(target, propertyName)\n if (hasProperty) {\n return target\n }\n\n const prototype = Reflect.getPrototypeOf(target)\n return prototype ? findPropertySource(prototype, propertyName) : null\n}\n","import { findPropertySource } from './findPropertySource'\n\nexport interface ProxyOptions> {\n constructorCall?(args: Array, next: NextFunction): Target\n\n methodCall?(\n this: Target,\n data: [methodName: F, args: Array],\n next: NextFunction\n ): void\n\n setProperty?(\n data: [propertyName: string | symbol, nextValue: unknown],\n next: NextFunction\n ): boolean\n\n getProperty?(\n data: [propertyName: string | symbol, receiver: Target],\n next: NextFunction\n ): void\n}\n\nexport type NextFunction = () => ReturnType\n\nexport function createProxy(\n target: Target,\n options: ProxyOptions\n): Target {\n const proxy = new Proxy(target, optionsToProxyHandler(options))\n\n return proxy\n}\n\nfunction optionsToProxyHandler>(\n options: ProxyOptions\n): ProxyHandler {\n const { constructorCall, methodCall, getProperty, setProperty } = options\n const handler: ProxyHandler = {}\n\n if (typeof constructorCall !== 'undefined') {\n handler.construct = function (target, args, newTarget) {\n const next = Reflect.construct.bind(null, target as any, args, newTarget)\n return constructorCall.call(newTarget, args, next)\n }\n }\n\n handler.set = function (target, propertyName, nextValue) {\n const next = () => {\n const propertySource = findPropertySource(target, propertyName) || target\n const ownDescriptors = Reflect.getOwnPropertyDescriptor(\n propertySource,\n propertyName\n )\n\n // Respect any custom setters present for this property.\n if (typeof ownDescriptors?.set !== 'undefined') {\n ownDescriptors.set.apply(target, [nextValue])\n return true\n }\n\n // Otherwise, set the property on the source.\n return Reflect.defineProperty(propertySource, propertyName, {\n writable: true,\n enumerable: true,\n configurable: true,\n value: nextValue,\n })\n }\n\n if (typeof setProperty !== 'undefined') {\n return setProperty.call(target, [propertyName, nextValue], next)\n }\n\n return next()\n }\n\n handler.get = function (target, propertyName, receiver) {\n /**\n * @note Using `Reflect.get()` here causes \"TypeError: Illegal invocation\".\n */\n const next = () => target[propertyName as any]\n\n const value =\n typeof getProperty !== 'undefined'\n ? getProperty.call(target, [propertyName, receiver], next)\n : next()\n\n if (typeof value === 'function') {\n return (...args: Array) => {\n const next = value.bind(target, ...args)\n\n if (typeof methodCall !== 'undefined') {\n return methodCall.call(target, [propertyName as any, args], next)\n }\n\n return next()\n }\n }\n\n return value\n }\n\n return handler\n}\n","export function isDomParserSupportedType(\n type: string\n): type is DOMParserSupportedType {\n const supportedTypes: Array = [\n 'application/xhtml+xml',\n 'application/xml',\n 'image/svg+xml',\n 'text/html',\n 'text/xml',\n ]\n return supportedTypes.some((supportedType) => {\n return type.startsWith(supportedType)\n })\n}\n","/**\n * Parses a given string into JSON.\n * Gracefully handles invalid JSON by returning `null`.\n */\nexport function parseJson(data: string): Record | null {\n try {\n const json = JSON.parse(data)\n return json\n } catch (_) {\n return null\n }\n}\n","import { FetchResponse } from '../../../utils/fetchUtils'\n\n/**\n * Creates a Fetch API `Response` instance from the given\n * `XMLHttpRequest` instance and a response body.\n */\nexport function createResponse(\n request: XMLHttpRequest,\n body: BodyInit | null\n): Response {\n /**\n * Handle XMLHttpRequest responses that must have null as the\n * response body when represented using Fetch API Response.\n * XMLHttpRequest response will always have an empty string\n * as the \"request.response\" in those cases, resulting in an error\n * when constructing a Response instance.\n * @see https://github.com/mswjs/interceptors/issues/379\n */\n const responseBodyOrNull = FetchResponse.isResponseWithBody(request.status)\n ? body\n : null\n\n return new FetchResponse(responseBodyOrNull, {\n url: request.responseURL,\n status: request.status,\n statusText: request.statusText,\n headers: createHeadersFromXMLHttpRequestHeaders(\n request.getAllResponseHeaders()\n ),\n })\n}\n\nfunction createHeadersFromXMLHttpRequestHeaders(headersString: string): Headers {\n const headers = new Headers()\n\n const lines = headersString.split(/[\\r\\n]+/)\n for (const line of lines) {\n if (line.trim() === '') {\n continue\n }\n\n const [name, ...parts] = line.split(': ')\n const value = parts.join(': ')\n\n headers.append(name, value)\n }\n\n return headers\n}\n","/**\n * Return a total byte length of the given request/response body.\n * If the `Content-Length` header is present, it will be used as the byte length.\n */\nexport async function getBodyByteLength(\n input: Request | Response\n): Promise {\n const explicitContentLength = input.headers.get('content-length')\n\n if (explicitContentLength != null && explicitContentLength !== '') {\n return Number(explicitContentLength)\n }\n\n const buffer = await input.arrayBuffer()\n return buffer.byteLength\n}\n","import { invariant } from 'outvariant'\nimport { isNodeProcess } from 'is-node-process'\nimport type { Logger } from '@open-draft/logger'\nimport { concatArrayBuffer } from './utils/concatArrayBuffer'\nimport { createEvent } from './utils/createEvent'\nimport {\n decodeBuffer,\n encodeBuffer,\n toArrayBuffer,\n} from '../../utils/bufferUtils'\nimport { createProxy } from '../../utils/createProxy'\nimport { isDomParserSupportedType } from './utils/isDomParserSupportedType'\nimport { parseJson } from '../../utils/parseJson'\nimport { createResponse } from './utils/createResponse'\nimport { INTERNAL_REQUEST_ID_HEADER_NAME } from '../../Interceptor'\nimport { createRequestId } from '../../createRequestId'\nimport { getBodyByteLength } from './utils/getBodyByteLength'\nimport { setRawRequest } from '../../getRawRequest'\nimport { FetchRequest } from '../../utils/fetchUtils'\n\nconst kIsRequestHandled = Symbol('kIsRequestHandled')\nconst IS_NODE = isNodeProcess()\nconst kFetchRequest = Symbol('kFetchRequest')\n\n/**\n * An `XMLHttpRequest` instance controller that allows us\n * to handle any given request instance (e.g. responding to it).\n */\nexport class XMLHttpRequestController {\n public request: XMLHttpRequest\n public requestId: string\n public onRequest?: (\n this: XMLHttpRequestController,\n args: {\n request: Request\n requestId: string\n }\n ) => Promise\n public onResponse?: (\n this: XMLHttpRequestController,\n args: {\n response: Response\n isMockedResponse: boolean\n request: Request\n requestId: string\n }\n ) => void;\n\n [kIsRequestHandled]: boolean;\n [kFetchRequest]?: Request\n private method: string = 'GET'\n private url: URL = null as any\n private requestHeaders: Headers\n private responseBuffer: Uint8Array\n private events: Map>\n private uploadEvents: Map<\n keyof XMLHttpRequestEventTargetEventMap,\n Array\n >\n\n constructor(\n readonly initialRequest: XMLHttpRequest,\n public logger: Logger\n ) {\n this[kIsRequestHandled] = false\n\n this.events = new Map()\n this.uploadEvents = new Map()\n this.requestId = createRequestId()\n this.requestHeaders = new Headers()\n this.responseBuffer = new Uint8Array()\n\n this.request = createProxy(initialRequest, {\n setProperty: ([propertyName, nextValue], invoke) => {\n switch (propertyName) {\n case 'ontimeout': {\n const eventName = propertyName.slice(\n 2\n ) as keyof XMLHttpRequestEventTargetEventMap\n\n /**\n * @note Proxy callbacks to event listeners because JSDOM has trouble\n * translating these properties to callbacks. It seemed to be operating\n * on events exclusively.\n */\n this.request.addEventListener(eventName, nextValue as any)\n\n return invoke()\n }\n\n default: {\n return invoke()\n }\n }\n },\n methodCall: ([methodName, args], invoke) => {\n switch (methodName) {\n case 'open': {\n const [method, url] = args as [string, string | undefined]\n\n if (typeof url === 'undefined') {\n this.method = 'GET'\n this.url = toAbsoluteUrl(method)\n } else {\n this.method = method\n this.url = toAbsoluteUrl(url)\n }\n\n this.logger = this.logger.extend(`${this.method} ${this.url.href}`)\n this.logger.info('open', this.method, this.url.href)\n\n return invoke()\n }\n\n case 'addEventListener': {\n const [eventName, listener] = args as [\n keyof XMLHttpRequestEventTargetEventMap,\n Function,\n ]\n\n this.registerEvent(eventName, listener)\n this.logger.info('addEventListener', eventName, listener)\n\n return invoke()\n }\n\n case 'setRequestHeader': {\n const [name, value] = args as [string, string]\n this.requestHeaders.set(name, value)\n\n this.logger.info('setRequestHeader', name, value)\n\n return invoke()\n }\n\n case 'send': {\n const [body] = args as [\n body?: XMLHttpRequestBodyInit | Document | null,\n ]\n\n this.request.addEventListener('load', () => {\n if (typeof this.onResponse !== 'undefined') {\n // Create a Fetch API Response representation of whichever\n // response this XMLHttpRequest received. Note those may\n // be either a mocked and the original response.\n const fetchResponse = createResponse(\n this.request,\n /**\n * The `response` property is the right way to read\n * the ambiguous response body, as the request's \"responseType\" may differ.\n * @see https://xhr.spec.whatwg.org/#the-response-attribute\n */\n this.request.response\n )\n\n // Notify the consumer about the response.\n this.onResponse.call(this, {\n response: fetchResponse,\n isMockedResponse: this[kIsRequestHandled],\n request: fetchRequest,\n requestId: this.requestId!,\n })\n }\n })\n\n const requestBody =\n typeof body === 'string' ? encodeBuffer(body) : body\n\n // Delegate request handling to the consumer.\n const fetchRequest = this.toFetchApiRequest(requestBody)\n this[kFetchRequest] = fetchRequest.clone()\n\n /**\n * @note Start request handling on the next tick so that the user\n * could add event listeners for \"loadend\" before the interceptor fires it.\n */\n queueMicrotask(() => {\n const onceRequestSettled =\n this.onRequest?.call(this, {\n request: fetchRequest,\n requestId: this.requestId!,\n }) || Promise.resolve()\n\n onceRequestSettled.finally(() => {\n // If the consumer didn't handle the request (called `.respondWith()`) perform it as-is.\n if (!this[kIsRequestHandled]) {\n this.logger.info(\n 'request callback settled but request has not been handled (readystate %d), performing as-is...',\n this.request.readyState\n )\n\n /**\n * @note Set the intercepted request ID on the original request in Node.js\n * so that if it triggers any other interceptors, they don't attempt\n * to process it once again.\n *\n * For instance, XMLHttpRequest is often implemented via \"http.ClientRequest\"\n * and we don't want for both XHR and ClientRequest interceptors to\n * handle the same request at the same time (e.g. emit the \"response\" event twice).\n */\n if (IS_NODE) {\n this.request.setRequestHeader(\n INTERNAL_REQUEST_ID_HEADER_NAME,\n this.requestId!\n )\n }\n\n return invoke()\n }\n })\n })\n\n break\n }\n\n default: {\n return invoke()\n }\n }\n },\n })\n\n /**\n * Proxy the `.upload` property to gather the event listeners/callbacks.\n */\n define(\n this.request,\n 'upload',\n createProxy(this.request.upload, {\n setProperty: ([propertyName, nextValue], invoke) => {\n switch (propertyName) {\n case 'onloadstart':\n case 'onprogress':\n case 'onaboart':\n case 'onerror':\n case 'onload':\n case 'ontimeout':\n case 'onloadend': {\n const eventName = propertyName.slice(\n 2\n ) as keyof XMLHttpRequestEventTargetEventMap\n\n this.registerUploadEvent(eventName, nextValue as Function)\n }\n }\n\n return invoke()\n },\n methodCall: ([methodName, args], invoke) => {\n switch (methodName) {\n case 'addEventListener': {\n const [eventName, listener] = args as [\n keyof XMLHttpRequestEventTargetEventMap,\n Function,\n ]\n this.registerUploadEvent(eventName, listener)\n this.logger.info('upload.addEventListener', eventName, listener)\n\n return invoke()\n }\n }\n },\n })\n )\n }\n\n private registerEvent(\n eventName: keyof XMLHttpRequestEventTargetEventMap,\n listener: Function\n ): void {\n const prevEvents = this.events.get(eventName) || []\n const nextEvents = prevEvents.concat(listener)\n this.events.set(eventName, nextEvents)\n\n this.logger.info('registered event \"%s\"', eventName, listener)\n }\n\n private registerUploadEvent(\n eventName: keyof XMLHttpRequestEventTargetEventMap,\n listener: Function\n ): void {\n const prevEvents = this.uploadEvents.get(eventName) || []\n const nextEvents = prevEvents.concat(listener)\n this.uploadEvents.set(eventName, nextEvents)\n\n this.logger.info('registered upload event \"%s\"', eventName, listener)\n }\n\n /**\n * Responds to the current request with the given\n * Fetch API `Response` instance.\n */\n public async respondWith(response: Response): Promise {\n /**\n * @note Since `XMLHttpRequestController` delegates the handling of the responses\n * to the \"load\" event listener that doesn't distinguish between the mocked and original\n * responses, mark the request that had a mocked response with a corresponding symbol.\n *\n * Mark this request as having a mocked response immediately since\n * calculating request/response total body length is asynchronous.\n */\n this[kIsRequestHandled] = true\n\n /**\n * Dispatch request upload events for requests with a body.\n * @see https://github.com/mswjs/interceptors/issues/573\n */\n if (this[kFetchRequest]) {\n const totalRequestBodyLength = await getBodyByteLength(\n this[kFetchRequest]\n )\n\n this.trigger('loadstart', this.request.upload, {\n loaded: 0,\n total: totalRequestBodyLength,\n })\n this.trigger('progress', this.request.upload, {\n loaded: totalRequestBodyLength,\n total: totalRequestBodyLength,\n })\n this.trigger('load', this.request.upload, {\n loaded: totalRequestBodyLength,\n total: totalRequestBodyLength,\n })\n\n this.trigger('loadend', this.request.upload, {\n loaded: totalRequestBodyLength,\n total: totalRequestBodyLength,\n })\n }\n\n this.logger.info(\n 'responding with a mocked response: %d %s',\n response.status,\n response.statusText\n )\n\n define(this.request, 'status', response.status)\n define(this.request, 'statusText', response.statusText)\n define(this.request, 'responseURL', this.url.href)\n\n this.request.getResponseHeader = new Proxy(this.request.getResponseHeader, {\n apply: (_, __, args: [name: string]) => {\n this.logger.info('getResponseHeader', args[0])\n\n if (this.request.readyState < this.request.HEADERS_RECEIVED) {\n this.logger.info('headers not received yet, returning null')\n\n // Headers not received yet, nothing to return.\n return null\n }\n\n const headerValue = response.headers.get(args[0])\n this.logger.info(\n 'resolved response header \"%s\" to',\n args[0],\n headerValue\n )\n\n return headerValue\n },\n })\n\n this.request.getAllResponseHeaders = new Proxy(\n this.request.getAllResponseHeaders,\n {\n apply: () => {\n this.logger.info('getAllResponseHeaders')\n\n if (this.request.readyState < this.request.HEADERS_RECEIVED) {\n this.logger.info('headers not received yet, returning empty string')\n\n // Headers not received yet, nothing to return.\n return ''\n }\n\n const headersList = Array.from(response.headers.entries())\n const allHeaders = headersList\n .map(([headerName, headerValue]) => {\n return `${headerName}: ${headerValue}`\n })\n .join('\\r\\n')\n\n this.logger.info('resolved all response headers to', allHeaders)\n\n return allHeaders\n },\n }\n )\n\n // Update the response getters to resolve against the mocked response.\n Object.defineProperties(this.request, {\n response: {\n enumerable: true,\n configurable: false,\n get: () => this.response,\n },\n responseText: {\n enumerable: true,\n configurable: false,\n get: () => this.responseText,\n },\n responseXML: {\n enumerable: true,\n configurable: false,\n get: () => this.responseXML,\n },\n })\n\n const totalResponseBodyLength = await getBodyByteLength(response.clone())\n\n this.logger.info('calculated response body length', totalResponseBodyLength)\n\n this.trigger('loadstart', this.request, {\n loaded: 0,\n total: totalResponseBodyLength,\n })\n\n this.setReadyState(this.request.HEADERS_RECEIVED)\n this.setReadyState(this.request.LOADING)\n\n const finalizeResponse = () => {\n this.logger.info('finalizing the mocked response...')\n\n this.setReadyState(this.request.DONE)\n\n this.trigger('load', this.request, {\n loaded: this.responseBuffer.byteLength,\n total: totalResponseBodyLength,\n })\n\n this.trigger('loadend', this.request, {\n loaded: this.responseBuffer.byteLength,\n total: totalResponseBodyLength,\n })\n }\n\n if (response.body) {\n this.logger.info('mocked response has body, streaming...')\n\n const reader = response.body.getReader()\n\n const readNextResponseBodyChunk = async () => {\n const { value, done } = await reader.read()\n\n if (done) {\n this.logger.info('response body stream done!')\n finalizeResponse()\n return\n }\n\n if (value) {\n this.logger.info('read response body chunk:', value)\n this.responseBuffer = concatArrayBuffer(this.responseBuffer, value)\n\n this.trigger('progress', this.request, {\n loaded: this.responseBuffer.byteLength,\n total: totalResponseBodyLength,\n })\n }\n\n readNextResponseBodyChunk()\n }\n\n readNextResponseBodyChunk()\n } else {\n finalizeResponse()\n }\n }\n\n private responseBufferToText(): string {\n return decodeBuffer(this.responseBuffer)\n }\n\n get response(): unknown {\n this.logger.info(\n 'getResponse (responseType: %s)',\n this.request.responseType\n )\n\n if (this.request.readyState !== this.request.DONE) {\n return null\n }\n\n switch (this.request.responseType) {\n case 'json': {\n const responseJson = parseJson(this.responseBufferToText())\n this.logger.info('resolved response JSON', responseJson)\n\n return responseJson\n }\n\n case 'arraybuffer': {\n const arrayBuffer = toArrayBuffer(this.responseBuffer)\n this.logger.info('resolved response ArrayBuffer', arrayBuffer)\n\n return arrayBuffer\n }\n\n case 'blob': {\n const mimeType =\n this.request.getResponseHeader('Content-Type') || 'text/plain'\n const responseBlob = new Blob([this.responseBufferToText()], {\n type: mimeType,\n })\n\n this.logger.info(\n 'resolved response Blob (mime type: %s)',\n responseBlob,\n mimeType\n )\n\n return responseBlob\n }\n\n default: {\n const responseText = this.responseBufferToText()\n this.logger.info(\n 'resolving \"%s\" response type as text',\n this.request.responseType,\n responseText\n )\n\n return responseText\n }\n }\n }\n\n get responseText(): string {\n /**\n * Throw when trying to read the response body as text when the\n * \"responseType\" doesn't expect text. This just respects the spec better.\n * @see https://xhr.spec.whatwg.org/#the-responsetext-attribute\n */\n invariant(\n this.request.responseType === '' || this.request.responseType === 'text',\n 'InvalidStateError: The object is in invalid state.'\n )\n\n if (\n this.request.readyState !== this.request.LOADING &&\n this.request.readyState !== this.request.DONE\n ) {\n return ''\n }\n\n const responseText = this.responseBufferToText()\n this.logger.info('getResponseText: \"%s\"', responseText)\n\n return responseText\n }\n\n get responseXML(): Document | null {\n invariant(\n this.request.responseType === '' ||\n this.request.responseType === 'document',\n 'InvalidStateError: The object is in invalid state.'\n )\n\n if (this.request.readyState !== this.request.DONE) {\n return null\n }\n\n const contentType = this.request.getResponseHeader('Content-Type') || ''\n\n if (typeof DOMParser === 'undefined') {\n console.warn(\n 'Cannot retrieve XMLHttpRequest response body as XML: DOMParser is not defined. You are likely using an environment that is not browser or does not polyfill browser globals correctly.'\n )\n return null\n }\n\n if (isDomParserSupportedType(contentType)) {\n return new DOMParser().parseFromString(\n this.responseBufferToText(),\n contentType\n )\n }\n\n return null\n }\n\n public errorWith(error?: Error): void {\n /**\n * @note Mark this request as handled even if it received a mock error.\n * This prevents the controller from trying to perform this request as-is.\n */\n this[kIsRequestHandled] = true\n this.logger.info('responding with an error')\n\n this.setReadyState(this.request.DONE)\n this.trigger('error', this.request)\n this.trigger('loadend', this.request)\n }\n\n /**\n * Transitions this request's `readyState` to the given one.\n */\n private setReadyState(nextReadyState: number): void {\n this.logger.info(\n 'setReadyState: %d -> %d',\n this.request.readyState,\n nextReadyState\n )\n\n if (this.request.readyState === nextReadyState) {\n this.logger.info('ready state identical, skipping transition...')\n return\n }\n\n define(this.request, 'readyState', nextReadyState)\n\n this.logger.info('set readyState to: %d', nextReadyState)\n\n if (nextReadyState !== this.request.UNSENT) {\n this.logger.info('triggering \"readystatechange\" event...')\n\n this.trigger('readystatechange', this.request)\n }\n }\n\n /**\n * Triggers given event on the `XMLHttpRequest` instance.\n */\n private trigger<\n EventName extends keyof (XMLHttpRequestEventTargetEventMap & {\n readystatechange: ProgressEvent\n }),\n >(\n eventName: EventName,\n target: XMLHttpRequest | XMLHttpRequestUpload,\n options?: ProgressEventInit\n ): void {\n const callback = (target as XMLHttpRequest)[`on${eventName}`]\n const event = createEvent(target, eventName, options)\n\n this.logger.info('trigger \"%s\"', eventName, options || '')\n\n // Invoke direct callbacks.\n if (typeof callback === 'function') {\n this.logger.info('found a direct \"%s\" callback, calling...', eventName)\n callback.call(target as XMLHttpRequest, event)\n }\n\n // Invoke event listeners.\n const events =\n target instanceof XMLHttpRequestUpload ? this.uploadEvents : this.events\n\n for (const [registeredEventName, listeners] of events) {\n if (registeredEventName === eventName) {\n this.logger.info(\n 'found %d listener(s) for \"%s\" event, calling...',\n listeners.length,\n eventName\n )\n\n listeners.forEach((listener) => listener.call(target, event))\n }\n }\n }\n\n /**\n * Converts this `XMLHttpRequest` instance into a Fetch API `Request` instance.\n */\n private toFetchApiRequest(\n body: XMLHttpRequestBodyInit | Document | null | undefined\n ): Request {\n this.logger.info('converting request to a Fetch API Request...')\n\n // If the `Document` is used as the body of this XMLHttpRequest,\n // set its inner text as the Fetch API Request body.\n const resolvedBody =\n body instanceof Document ? body.documentElement.innerText : body\n\n const fetchRequest = new FetchRequest(this.url.href, {\n method: this.method,\n headers: this.requestHeaders,\n /**\n * @see https://xhr.spec.whatwg.org/#cross-origin-credentials\n */\n credentials: this.request.withCredentials ? 'include' : 'same-origin',\n body: ['GET', 'HEAD'].includes(this.method.toUpperCase())\n ? null\n : resolvedBody,\n })\n\n const proxyHeaders = createProxy(fetchRequest.headers, {\n methodCall: ([methodName, args], invoke) => {\n // Forward the latest state of the internal request headers\n // because the interceptor might have modified them\n // without responding to the request.\n switch (methodName) {\n case 'append':\n case 'set': {\n const [headerName, headerValue] = args as [string, string]\n this.request.setRequestHeader(headerName, headerValue)\n break\n }\n\n case 'delete': {\n const [headerName] = args as [string]\n console.warn(\n `XMLHttpRequest: Cannot remove a \"${headerName}\" header from the Fetch API representation of the \"${fetchRequest.method} ${fetchRequest.url}\" request. XMLHttpRequest headers cannot be removed.`\n )\n break\n }\n }\n\n return invoke()\n },\n })\n define(fetchRequest, 'headers', proxyHeaders)\n setRawRequest(fetchRequest, this.request)\n\n this.logger.info('converted request to a Fetch API Request!', fetchRequest)\n\n return fetchRequest\n }\n}\n\nfunction toAbsoluteUrl(url: string | URL): URL {\n /**\n * @note XMLHttpRequest interceptor may run in environments\n * that implement XMLHttpRequest but don't implement \"location\"\n * (for example, React Native). If that's the case, return the\n * input URL as-is (nothing to be relative to).\n * @see https://github.com/mswjs/msw/issues/1777\n */\n if (typeof location === 'undefined') {\n return new URL(url)\n }\n\n return new URL(url.toString(), location.href)\n}\n\nfunction define(\n target: object,\n property: string | symbol,\n value: unknown\n): void {\n Reflect.defineProperty(target, property, {\n // Ensure writable properties to allow redefining readonly properties.\n writable: true,\n enumerable: true,\n value,\n })\n}\n","import type { Logger } from '@open-draft/logger'\nimport { XMLHttpRequestEmitter } from '.'\nimport { RequestController } from '../../RequestController'\nimport { XMLHttpRequestController } from './XMLHttpRequestController'\nimport { handleRequest } from '../../utils/handleRequest'\nimport { isResponseError } from '../../utils/responseUtils'\n\nexport interface XMLHttpRequestProxyOptions {\n emitter: XMLHttpRequestEmitter\n logger: Logger\n}\n\n/**\n * Create a proxied `XMLHttpRequest` class.\n * The proxied class establishes spies on certain methods,\n * allowing us to intercept requests and respond to them.\n */\nexport function createXMLHttpRequestProxy({\n emitter,\n logger,\n}: XMLHttpRequestProxyOptions) {\n const XMLHttpRequestProxy = new Proxy(globalThis.XMLHttpRequest, {\n construct(target, args, newTarget) {\n logger.info('constructed new XMLHttpRequest')\n\n const originalRequest = Reflect.construct(\n target,\n args,\n newTarget\n ) as XMLHttpRequest\n\n /**\n * @note Forward prototype descriptors onto the proxied object.\n * XMLHttpRequest is implemented in JSDOM in a way that assigns\n * a bunch of descriptors, like \"set responseType()\" on the prototype.\n * With this propagation, we make sure that those descriptors trigger\n * when the user operates with the proxied request instance.\n */\n const prototypeDescriptors = Object.getOwnPropertyDescriptors(\n target.prototype\n )\n for (const propertyName in prototypeDescriptors) {\n Reflect.defineProperty(\n originalRequest,\n propertyName,\n prototypeDescriptors[propertyName]\n )\n }\n\n const xhrRequestController = new XMLHttpRequestController(\n originalRequest,\n logger\n )\n\n xhrRequestController.onRequest = async function ({ request, requestId }) {\n const controller = new RequestController(request, {\n passthrough: () => {\n this.logger.info(\n 'no mocked response received, performing request as-is...'\n )\n },\n respondWith: async (response) => {\n if (isResponseError(response)) {\n this.errorWith(new TypeError('Network error'))\n return\n }\n\n await this.respondWith(response)\n },\n errorWith: (reason) => {\n this.logger.info('request errored!', { error: reason })\n\n if (reason instanceof Error) {\n this.errorWith(reason)\n }\n },\n })\n\n this.logger.info('awaiting mocked response...')\n\n this.logger.info(\n 'emitting the \"request\" event for %s listener(s)...',\n emitter.listenerCount('request')\n )\n\n await handleRequest({\n request,\n requestId,\n controller,\n emitter,\n })\n }\n\n xhrRequestController.onResponse = async function ({\n response,\n isMockedResponse,\n request,\n requestId,\n }) {\n this.logger.info(\n 'emitting the \"response\" event for %s listener(s)...',\n emitter.listenerCount('response')\n )\n\n emitter.emit('response', {\n response,\n isMockedResponse,\n request,\n requestId,\n })\n }\n\n // Return the proxied request from the controller\n // so that the controller can react to the consumer's interactions\n // with this request (opening/sending/etc).\n return xhrRequestController.request\n },\n })\n\n return XMLHttpRequestProxy\n}\n","import { Emitter } from 'strict-event-emitter'\nimport { HttpRequestEventMap } from '../../glossary'\nimport { Interceptor } from '../../Interceptor'\nimport { createXMLHttpRequestProxy } from './XMLHttpRequestProxy'\nimport { hasConfigurableGlobal } from '../../utils/hasConfigurableGlobal'\nimport { patchesRegistry } from '../../utils/patchesRegistry'\n\nexport type XMLHttpRequestEmitter = Emitter\n\nexport class XMLHttpRequestInterceptor extends Interceptor {\n static symbol = Symbol.for('xhr-interceptor')\n\n constructor() {\n super(XMLHttpRequestInterceptor.symbol)\n }\n\n protected checkEnvironment() {\n return hasConfigurableGlobal('XMLHttpRequest')\n }\n\n protected setup() {\n const logger = this.logger.extend('setup')\n\n logger.info('patching global XMLHttpRequest...')\n\n this.subscriptions.push(\n patchesRegistry.applyPatch(globalThis, 'XMLHttpRequest', () => {\n return createXMLHttpRequestProxy({\n emitter: this.emitter,\n logger: this.logger,\n })\n })\n )\n\n logger.info(\n 'global XMLHttpRequest patched!',\n globalThis.XMLHttpRequest.name\n )\n }\n}\n"],"mappings":";;;;;;;;;;;;AAGA,SAAgB,kBACd,MACA,OACY;CACZ,MAAM,SAAS,IAAI,WAAW,KAAK,aAAa,MAAM,WAAW;AACjE,QAAO,IAAI,MAAM,EAAE;AACnB,QAAO,IAAI,OAAO,KAAK,WAAW;AAClC,QAAO;;;;;ACVT,IAAa,gBAAb,MAA4C;CAwB1C,YACE,MACA,SACA;cA1Bc;yBACW;mBACN;wBACK;cAEJ;oBACkB;uBAEG;oBACf;mBAEA;kBACD;oBACE;0BACM;iBACT;0BACS;gBACX;eACD;sBAEC;qBACD;AAMrB,OAAK,OAAO;AACZ,OAAK,SAAS,SAAS,UAAU;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kC,YAAiC;;gBAC9D,OAAO,IAAI,kBAAkB;;CAE7C,cAAc;AACZ,QAAM,0BAA0B,OAAO;;CAGzC,AAAU,mBAAmB;AAC3B,SAAO,sBAAsB,iBAAiB;;CAGhD,AAAU,QAAQ;EAChB,MAAM,SAAS,KAAK,OAAO,OAAO,QAAQ;AAE1C,SAAO,KAAK,oCAAoC;AAEhD,OAAK,cAAc,KACjB,gBAAgB,WAAW,YAAY,wBAAwB;AAC7D,UAAO,0BAA0B;IAC/B,SAAS,KAAK;IACd,QAAQ,KAAK;IACd,CAAC;IACF,CACH;AAED,SAAO,KACL,kCACA,WAAW,eAAe,KAC3B"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/bufferUtils-DxPxwff_.mjs b/node_modules/@mswjs/interceptors/lib/node/bufferUtils-DxPxwff_.mjs new file mode 100644 index 0000000000000000000000000000000000000000..17dbf5d05e0b959acaed1fad5524e42b2886b167 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/bufferUtils-DxPxwff_.mjs @@ -0,0 +1,20 @@ +//#region src/utils/bufferUtils.ts +const encoder = new TextEncoder(); +function encodeBuffer(text) { + return encoder.encode(text); +} +function decodeBuffer(buffer, encoding) { + return new TextDecoder(encoding).decode(buffer); +} +/** +* Create an `ArrayBuffer` from the given `Uint8Array`. +* Takes the byte offset into account to produce the right buffer +* in the case when the buffer is bigger than the data view. +*/ +function toArrayBuffer(array) { + return array.buffer.slice(array.byteOffset, array.byteOffset + array.byteLength); +} + +//#endregion +export { encodeBuffer as n, toArrayBuffer as r, decodeBuffer as t }; +//# sourceMappingURL=bufferUtils-DxPxwff_.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/bufferUtils-DxPxwff_.mjs.map b/node_modules/@mswjs/interceptors/lib/node/bufferUtils-DxPxwff_.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..555e880a70e788ee6a38b39aeadcb9101cc01105 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/bufferUtils-DxPxwff_.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"bufferUtils-DxPxwff_.mjs","names":[],"sources":["../../src/utils/bufferUtils.ts"],"sourcesContent":["const encoder = new TextEncoder()\n\nexport function encodeBuffer(text: string): Uint8Array {\n return encoder.encode(text)\n}\n\nexport function decodeBuffer(buffer: ArrayBuffer, encoding?: string): string {\n const decoder = new TextDecoder(encoding)\n return decoder.decode(buffer)\n}\n\n/**\n * Create an `ArrayBuffer` from the given `Uint8Array`.\n * Takes the byte offset into account to produce the right buffer\n * in the case when the buffer is bigger than the data view.\n */\nexport function toArrayBuffer(array: Uint8Array): ArrayBuffer {\n return array.buffer.slice(\n array.byteOffset,\n array.byteOffset + array.byteLength\n )\n}\n"],"mappings":";AAAA,MAAM,UAAU,IAAI,aAAa;AAEjC,SAAgB,aAAa,MAA0B;AACrD,QAAO,QAAQ,OAAO,KAAK;;AAG7B,SAAgB,aAAa,QAAqB,UAA2B;AAE3E,QADgB,IAAI,YAAY,SAAS,CAC1B,OAAO,OAAO;;;;;;;AAQ/B,SAAgB,cAAc,OAAgC;AAC5D,QAAO,MAAM,OAAO,MAClB,MAAM,YACN,MAAM,aAAa,MAAM,WAC1B"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/bufferUtils-S5_-2eN4.cjs b/node_modules/@mswjs/interceptors/lib/node/bufferUtils-S5_-2eN4.cjs new file mode 100644 index 0000000000000000000000000000000000000000..2274cfda714d8879e7f8a930863d5061f4b33c4d --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/bufferUtils-S5_-2eN4.cjs @@ -0,0 +1,38 @@ + +//#region src/utils/bufferUtils.ts +const encoder = new TextEncoder(); +function encodeBuffer(text) { + return encoder.encode(text); +} +function decodeBuffer(buffer, encoding) { + return new TextDecoder(encoding).decode(buffer); +} +/** +* Create an `ArrayBuffer` from the given `Uint8Array`. +* Takes the byte offset into account to produce the right buffer +* in the case when the buffer is bigger than the data view. +*/ +function toArrayBuffer(array) { + return array.buffer.slice(array.byteOffset, array.byteOffset + array.byteLength); +} + +//#endregion +Object.defineProperty(exports, 'decodeBuffer', { + enumerable: true, + get: function () { + return decodeBuffer; + } +}); +Object.defineProperty(exports, 'encodeBuffer', { + enumerable: true, + get: function () { + return encodeBuffer; + } +}); +Object.defineProperty(exports, 'toArrayBuffer', { + enumerable: true, + get: function () { + return toArrayBuffer; + } +}); +//# sourceMappingURL=bufferUtils-S5_-2eN4.cjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/bufferUtils-S5_-2eN4.cjs.map b/node_modules/@mswjs/interceptors/lib/node/bufferUtils-S5_-2eN4.cjs.map new file mode 100644 index 0000000000000000000000000000000000000000..9008745d383aad635c91567b1dee795e9dd8003e --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/bufferUtils-S5_-2eN4.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"bufferUtils-S5_-2eN4.cjs","names":[],"sources":["../../src/utils/bufferUtils.ts"],"sourcesContent":["const encoder = new TextEncoder()\n\nexport function encodeBuffer(text: string): Uint8Array {\n return encoder.encode(text)\n}\n\nexport function decodeBuffer(buffer: ArrayBuffer, encoding?: string): string {\n const decoder = new TextDecoder(encoding)\n return decoder.decode(buffer)\n}\n\n/**\n * Create an `ArrayBuffer` from the given `Uint8Array`.\n * Takes the byte offset into account to produce the right buffer\n * in the case when the buffer is bigger than the data view.\n */\nexport function toArrayBuffer(array: Uint8Array): ArrayBuffer {\n return array.buffer.slice(\n array.byteOffset,\n array.byteOffset + array.byteLength\n )\n}\n"],"mappings":";;AAAA,MAAM,UAAU,IAAI,aAAa;AAEjC,SAAgB,aAAa,MAA0B;AACrD,QAAO,QAAQ,OAAO,KAAK;;AAG7B,SAAgB,aAAa,QAAqB,UAA2B;AAE3E,QADgB,IAAI,YAAY,SAAS,CAC1B,OAAO,OAAO;;;;;;;AAQ/B,SAAgB,cAAc,OAAgC;AAC5D,QAAO,MAAM,OAAO,MAClB,MAAM,YACN,MAAM,aAAa,MAAM,WAC1B"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/chunk-CbDLau6x.cjs b/node_modules/@mswjs/interceptors/lib/node/chunk-CbDLau6x.cjs new file mode 100644 index 0000000000000000000000000000000000000000..55d74269c25286a3aa87b234965b7a0b2853019f --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/chunk-CbDLau6x.cjs @@ -0,0 +1,34 @@ +//#region rolldown:runtime +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) { + key = keys[i]; + if (!__hasOwnProp.call(to, key) && key !== except) { + __defProp(to, key, { + get: ((k) => from[k]).bind(null, key), + enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable + }); + } + } + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { + value: mod, + enumerable: true +}) : target, mod)); + +//#endregion + +Object.defineProperty(exports, '__toESM', { + enumerable: true, + get: function () { + return __toESM; + } +}); \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/fetch-CaC3rGEu.mjs b/node_modules/@mswjs/interceptors/lib/node/fetch-CaC3rGEu.mjs new file mode 100644 index 0000000000000000000000000000000000000000..db226083505c8c33959a285e289bbb6eb9c346c9 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/fetch-CaC3rGEu.mjs @@ -0,0 +1,252 @@ +import { a as RequestController, c as Interceptor, i as createRequestId, n as FetchResponse, r as canParseUrl, t as FetchRequest } from "./fetchUtils-BKJ1XmiO.mjs"; +import { n as setRawRequest } from "./getRawRequest-C2-1urzA.mjs"; +import { i as emitAsync, n as isResponseError, t as handleRequest } from "./handleRequest-FIQv5pwH.mjs"; +import { n as patchesRegistry, t as hasConfigurableGlobal } from "./hasConfigurableGlobal-BiTmog1u.mjs"; +import { DeferredPromise } from "@open-draft/deferred-promise"; +import { until } from "@open-draft/until"; +import zlib from "node:zlib"; + +//#region src/interceptors/fetch/utils/createNetworkError.ts +function createNetworkError(cause) { + return Object.assign(/* @__PURE__ */ new TypeError("Failed to fetch"), { cause }); +} + +//#endregion +//#region src/interceptors/fetch/utils/followRedirect.ts +const REQUEST_BODY_HEADERS = [ + "content-encoding", + "content-language", + "content-location", + "content-type", + "content-length" +]; +const kRedirectCount = Symbol("kRedirectCount"); +/** +* @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1210 +*/ +async function followFetchRedirect(request, response) { + if (response.status !== 303 && request.body != null) return Promise.reject(createNetworkError()); + const requestUrl = new URL(request.url); + let locationUrl; + try { + locationUrl = new URL(response.headers.get("location"), request.url); + } catch (error) { + return Promise.reject(createNetworkError(error)); + } + if (!(locationUrl.protocol === "http:" || locationUrl.protocol === "https:")) return Promise.reject(createNetworkError("URL scheme must be a HTTP(S) scheme")); + if (Reflect.get(request, kRedirectCount) > 20) return Promise.reject(createNetworkError("redirect count exceeded")); + Object.defineProperty(request, kRedirectCount, { value: (Reflect.get(request, kRedirectCount) || 0) + 1 }); + if (request.mode === "cors" && (locationUrl.username || locationUrl.password) && !sameOrigin(requestUrl, locationUrl)) return Promise.reject(createNetworkError("cross origin not allowed for request mode \"cors\"")); + const requestInit = {}; + if ([301, 302].includes(response.status) && request.method === "POST" || response.status === 303 && !["HEAD", "GET"].includes(request.method)) { + requestInit.method = "GET"; + requestInit.body = null; + REQUEST_BODY_HEADERS.forEach((headerName) => { + request.headers.delete(headerName); + }); + } + if (!sameOrigin(requestUrl, locationUrl)) { + request.headers.delete("authorization"); + request.headers.delete("proxy-authorization"); + request.headers.delete("cookie"); + request.headers.delete("host"); + } + /** + * @note Undici "safely" extracts the request body. + * I suspect we cannot dispatch this request again + * since its body has been read and the stream is locked. + */ + requestInit.headers = request.headers; + const finalResponse = await fetch(new Request(locationUrl, requestInit)); + Object.defineProperty(finalResponse, "redirected", { + value: true, + configurable: true + }); + return finalResponse; +} +/** +* @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/util.js#L761 +*/ +function sameOrigin(left, right) { + if (left.origin === right.origin && left.origin === "null") return true; + if (left.protocol === right.protocol && left.hostname === right.hostname && left.port === right.port) return true; + return false; +} + +//#endregion +//#region src/interceptors/fetch/utils/brotli-decompress.ts +var BrotliDecompressionStream = class extends TransformStream { + constructor() { + const decompress = zlib.createBrotliDecompress({ + flush: zlib.constants.BROTLI_OPERATION_FLUSH, + finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH + }); + super({ async transform(chunk, controller) { + const buffer = Buffer.from(chunk); + const decompressed = await new Promise((resolve, reject) => { + decompress.write(buffer, (error) => { + if (error) reject(error); + }); + decompress.flush(); + decompress.once("data", (data) => resolve(data)); + decompress.once("error", (error) => reject(error)); + decompress.once("end", () => controller.terminate()); + }).catch((error) => { + controller.error(error); + }); + controller.enqueue(decompressed); + } }); + } +}; + +//#endregion +//#region src/interceptors/fetch/utils/decompression.ts +var PipelineStream = class extends TransformStream { + constructor(transformStreams, ...strategies) { + super({}, ...strategies); + const readable = [super.readable, ...transformStreams].reduce((readable$1, transform) => readable$1.pipeThrough(transform)); + Object.defineProperty(this, "readable", { get() { + return readable; + } }); + } +}; +function parseContentEncoding(contentEncoding) { + return contentEncoding.toLowerCase().split(",").map((coding) => coding.trim()); +} +function createDecompressionStream(contentEncoding) { + if (contentEncoding === "") return null; + const codings = parseContentEncoding(contentEncoding); + if (codings.length === 0) return null; + return new PipelineStream(codings.reduceRight((transformers, coding) => { + if (coding === "gzip" || coding === "x-gzip") return transformers.concat(new DecompressionStream("gzip")); + else if (coding === "deflate") return transformers.concat(new DecompressionStream("deflate")); + else if (coding === "br") return transformers.concat(new BrotliDecompressionStream()); + else transformers.length = 0; + return transformers; + }, [])); +} +function decompressResponse(response) { + if (response.body === null) return null; + const decompressionStream = createDecompressionStream(response.headers.get("content-encoding") || ""); + if (!decompressionStream) return null; + response.body.pipeTo(decompressionStream.writable); + return decompressionStream.readable; +} + +//#endregion +//#region src/interceptors/fetch/index.ts +var FetchInterceptor = class FetchInterceptor extends Interceptor { + static { + this.symbol = Symbol.for("fetch-interceptor"); + } + constructor() { + super(FetchInterceptor.symbol); + } + checkEnvironment() { + return hasConfigurableGlobal("fetch"); + } + async setup() { + const logger = this.logger.extend("setup"); + const pureFetch = globalThis.fetch; + const fetchProxy = async (input, init) => { + const requestId = createRequestId(); + const request = new FetchRequest(typeof input === "string" && typeof location !== "undefined" && !canParseUrl(input) ? new URL(input, location.href) : input, init); + /** + * @note Set the raw request only if a Request instance was provided to fetch. + */ + if (input instanceof Request) setRawRequest(request, input); + const responsePromise = new DeferredPromise(); + const controller = new RequestController(request, { + passthrough: async () => { + this.logger.info("request has not been handled, passthrough..."); + /** + * @note Clone the request instance right before performing it. + * This preserves any modifications made to the intercepted request + * in the "request" listener. This also allows the user to read the + * request body in the "response" listener (otherwise "unusable"). + */ + const requestCloneForResponseEvent = request.clone(); + const { error: responseError, data: originalResponse } = await until(() => pureFetch(request)); + if (responseError) return responsePromise.reject(responseError); + this.logger.info("original fetch performed", originalResponse); + if (this.emitter.listenerCount("response") > 0) { + this.logger.info("emitting the \"response\" event..."); + const responseClone = FetchResponse.clone(originalResponse); + await emitAsync(this.emitter, "response", { + response: responseClone, + isMockedResponse: false, + request: requestCloneForResponseEvent, + requestId + }); + } + responsePromise.resolve(originalResponse); + }, + respondWith: async (rawResponse) => { + if (isResponseError(rawResponse)) { + this.logger.info("request has errored!", { response: rawResponse }); + responsePromise.reject(createNetworkError(rawResponse)); + return; + } + this.logger.info("received mocked response!", { rawResponse }); + const response = new FetchResponse(decompressResponse(rawResponse) || rawResponse.body, { + url: request.url, + status: rawResponse.status, + statusText: rawResponse.statusText, + headers: rawResponse.headers + }); + /** + * Undici's handling of following redirect responses. + * Treat the "manual" redirect mode as a regular mocked response. + * This way, the client can manually follow the redirect it receives. + * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1173 + */ + if (FetchResponse.isRedirectResponse(response.status)) { + if (request.redirect === "error") { + responsePromise.reject(createNetworkError("unexpected redirect")); + return; + } + if (request.redirect === "follow") { + followFetchRedirect(request, response).then((response$1) => { + responsePromise.resolve(response$1); + }, (reason) => { + responsePromise.reject(reason); + }); + return; + } + } + if (this.emitter.listenerCount("response") > 0) { + this.logger.info("emitting the \"response\" event..."); + await emitAsync(this.emitter, "response", { + response: FetchResponse.clone(response), + isMockedResponse: true, + request, + requestId + }); + } + responsePromise.resolve(response); + }, + errorWith: (reason) => { + this.logger.info("request has been aborted!", { reason }); + responsePromise.reject(reason); + } + }); + this.logger.info("[%s] %s", request.method, request.url); + this.logger.info("awaiting for the mocked response..."); + this.logger.info("emitting the \"request\" event for %s listener(s)...", this.emitter.listenerCount("request")); + await handleRequest({ + request, + requestId, + emitter: this.emitter, + controller + }); + return responsePromise; + }; + logger.info("patching global fetch..."); + this.subscriptions.push(patchesRegistry.applyPatch(globalThis, "fetch", () => fetchProxy)); + logger.info("global fetch patched!", globalThis.fetch.name); + } +}; + +//#endregion +export { FetchInterceptor as t }; +//# sourceMappingURL=fetch-CaC3rGEu.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/fetch-CaC3rGEu.mjs.map b/node_modules/@mswjs/interceptors/lib/node/fetch-CaC3rGEu.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..15bab8529c5c48a705321d403e169eef254f5ca6 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/fetch-CaC3rGEu.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"fetch-CaC3rGEu.mjs","names":["locationUrl: URL","requestInit: RequestInit","readable","fetchProxy: typeof fetch","response"],"sources":["../../src/interceptors/fetch/utils/createNetworkError.ts","../../src/interceptors/fetch/utils/followRedirect.ts","../../src/interceptors/fetch/utils/brotli-decompress.ts","../../src/interceptors/fetch/utils/decompression.ts","../../src/interceptors/fetch/index.ts"],"sourcesContent":["export function createNetworkError(cause?: unknown) {\n return Object.assign(new TypeError('Failed to fetch'), {\n cause,\n })\n}\n","import { createNetworkError } from './createNetworkError'\n\nconst REQUEST_BODY_HEADERS = [\n 'content-encoding',\n 'content-language',\n 'content-location',\n 'content-type',\n 'content-length',\n]\n\nconst kRedirectCount = Symbol('kRedirectCount')\n\n/**\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1210\n */\nexport async function followFetchRedirect(\n request: Request,\n response: Response\n): Promise {\n if (response.status !== 303 && request.body != null) {\n return Promise.reject(createNetworkError())\n }\n\n const requestUrl = new URL(request.url)\n\n let locationUrl: URL\n try {\n // If the location is a relative URL, use the request URL as the base URL.\n locationUrl = new URL(response.headers.get('location')!, request.url) \n } catch (error) {\n return Promise.reject(createNetworkError(error))\n }\n\n if (\n !(locationUrl.protocol === 'http:' || locationUrl.protocol === 'https:')\n ) {\n return Promise.reject(\n createNetworkError('URL scheme must be a HTTP(S) scheme')\n )\n }\n\n if (Reflect.get(request, kRedirectCount) > 20) {\n return Promise.reject(createNetworkError('redirect count exceeded'))\n }\n\n Object.defineProperty(request, kRedirectCount, {\n value: (Reflect.get(request, kRedirectCount) || 0) + 1,\n })\n\n if (\n request.mode === 'cors' &&\n (locationUrl.username || locationUrl.password) &&\n !sameOrigin(requestUrl, locationUrl)\n ) {\n return Promise.reject(\n createNetworkError('cross origin not allowed for request mode \"cors\"')\n )\n }\n\n const requestInit: RequestInit = {}\n\n if (\n ([301, 302].includes(response.status) && request.method === 'POST') ||\n (response.status === 303 && !['HEAD', 'GET'].includes(request.method))\n ) {\n requestInit.method = 'GET'\n requestInit.body = null\n\n REQUEST_BODY_HEADERS.forEach((headerName) => {\n request.headers.delete(headerName)\n })\n }\n\n if (!sameOrigin(requestUrl, locationUrl)) {\n request.headers.delete('authorization')\n request.headers.delete('proxy-authorization')\n request.headers.delete('cookie')\n request.headers.delete('host')\n }\n\n /**\n * @note Undici \"safely\" extracts the request body.\n * I suspect we cannot dispatch this request again\n * since its body has been read and the stream is locked.\n */\n\n requestInit.headers = request.headers\n const finalResponse = await fetch(new Request(locationUrl, requestInit))\n Object.defineProperty(finalResponse, 'redirected', {\n value: true,\n configurable: true,\n })\n\n return finalResponse\n}\n\n/**\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/util.js#L761\n */\nfunction sameOrigin(left: URL, right: URL): boolean {\n if (left.origin === right.origin && left.origin === 'null') {\n return true\n }\n\n if (\n left.protocol === right.protocol &&\n left.hostname === right.hostname &&\n left.port === right.port\n ) {\n return true\n }\n\n return false\n}\n","import zlib from 'node:zlib'\n\nexport class BrotliDecompressionStream extends TransformStream {\n constructor() {\n const decompress = zlib.createBrotliDecompress({\n flush: zlib.constants.BROTLI_OPERATION_FLUSH,\n finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH,\n })\n\n super({\n async transform(chunk, controller) {\n const buffer = Buffer.from(chunk)\n\n const decompressed = await new Promise((resolve, reject) => {\n decompress.write(buffer, (error) => {\n if (error) reject(error)\n })\n\n decompress.flush()\n decompress.once('data', (data) => resolve(data))\n decompress.once('error', (error) => reject(error))\n decompress.once('end', () => controller.terminate())\n }).catch((error) => {\n controller.error(error)\n })\n\n controller.enqueue(decompressed)\n },\n })\n }\n}\n","// Import from an internal alias that resolves to different modules\n// depending on the environment. This way, we can keep the fetch interceptor\n// intact while using different strategies for Brotli decompression.\nimport { BrotliDecompressionStream } from 'internal:brotli-decompress'\n\nclass PipelineStream extends TransformStream {\n constructor(\n transformStreams: Array,\n ...strategies: Array\n ) {\n super({}, ...strategies)\n\n const readable = [super.readable as any, ...transformStreams].reduce(\n (readable, transform) => readable.pipeThrough(transform)\n )\n\n Object.defineProperty(this, 'readable', {\n get() {\n return readable\n },\n })\n }\n}\n\nexport function parseContentEncoding(contentEncoding: string): Array {\n return contentEncoding\n .toLowerCase()\n .split(',')\n .map((coding) => coding.trim())\n}\n\nfunction createDecompressionStream(\n contentEncoding: string\n): TransformStream | null {\n if (contentEncoding === '') {\n return null\n }\n\n const codings = parseContentEncoding(contentEncoding)\n\n if (codings.length === 0) {\n return null\n }\n\n const transformers = codings.reduceRight>(\n (transformers, coding) => {\n if (coding === 'gzip' || coding === 'x-gzip') {\n return transformers.concat(new DecompressionStream('gzip'))\n } else if (coding === 'deflate') {\n return transformers.concat(new DecompressionStream('deflate'))\n } else if (coding === 'br') {\n return transformers.concat(new BrotliDecompressionStream())\n } else {\n transformers.length = 0\n }\n\n return transformers\n },\n []\n )\n\n return new PipelineStream(transformers)\n}\n\nexport function decompressResponse(\n response: Response\n): ReadableStream | null {\n if (response.body === null) {\n return null\n }\n\n const decompressionStream = createDecompressionStream(\n response.headers.get('content-encoding') || ''\n )\n\n if (!decompressionStream) {\n return null\n }\n\n // Use `pipeTo` and return the decompression stream's readable\n // instead of `pipeThrough` because that will lock the original\n // response stream, making it unusable as the input to Response.\n response.body.pipeTo(decompressionStream.writable)\n return decompressionStream.readable\n}\n","import { until } from '@open-draft/until'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { HttpRequestEventMap } from '../../glossary'\nimport { Interceptor } from '../../Interceptor'\nimport { RequestController } from '../../RequestController'\nimport { emitAsync } from '../../utils/emitAsync'\nimport { handleRequest } from '../../utils/handleRequest'\nimport { canParseUrl } from '../../utils/canParseUrl'\nimport { createRequestId } from '../../createRequestId'\nimport { createNetworkError } from './utils/createNetworkError'\nimport { followFetchRedirect } from './utils/followRedirect'\nimport { decompressResponse } from './utils/decompression'\nimport { hasConfigurableGlobal } from '../../utils/hasConfigurableGlobal'\nimport { FetchRequest, FetchResponse } from '../../utils/fetchUtils'\nimport { setRawRequest } from '../../getRawRequest'\nimport { isResponseError } from '../../utils/responseUtils'\nimport { patchesRegistry } from '../../utils/patchesRegistry'\n\nexport class FetchInterceptor extends Interceptor {\n static symbol = Symbol.for('fetch-interceptor')\n\n constructor() {\n super(FetchInterceptor.symbol)\n }\n\n protected checkEnvironment() {\n return hasConfigurableGlobal('fetch')\n }\n\n protected async setup() {\n const logger = this.logger.extend('setup')\n\n const pureFetch = globalThis.fetch\n\n const fetchProxy: typeof fetch = async (input, init) => {\n const requestId = createRequestId()\n\n /**\n * @note Resolve potentially relative request URL\n * against the present `location`. This is mainly\n * for native `fetch` in JSDOM.\n * @see https://github.com/mswjs/msw/issues/1625\n */\n const resolvedInput =\n typeof input === 'string' &&\n typeof location !== 'undefined' &&\n !canParseUrl(input)\n ? new URL(input, location.href)\n : input\n\n const request = new FetchRequest(resolvedInput, init)\n\n /**\n * @note Set the raw request only if a Request instance was provided to fetch.\n */\n if (input instanceof Request) {\n setRawRequest(request, input)\n }\n\n const responsePromise = new DeferredPromise()\n\n const controller = new RequestController(request, {\n passthrough: async () => {\n this.logger.info('request has not been handled, passthrough...')\n\n /**\n * @note Clone the request instance right before performing it.\n * This preserves any modifications made to the intercepted request\n * in the \"request\" listener. This also allows the user to read the\n * request body in the \"response\" listener (otherwise \"unusable\").\n */\n const requestCloneForResponseEvent = request.clone()\n\n // Perform the intercepted request as-is.\n const { error: responseError, data: originalResponse } = await until(\n () => pureFetch(request)\n )\n\n if (responseError) {\n return responsePromise.reject(responseError)\n }\n\n this.logger.info('original fetch performed', originalResponse)\n\n if (this.emitter.listenerCount('response') > 0) {\n this.logger.info('emitting the \"response\" event...')\n\n const responseClone = FetchResponse.clone(originalResponse)\n await emitAsync(this.emitter, 'response', {\n response: responseClone,\n isMockedResponse: false,\n request: requestCloneForResponseEvent,\n requestId,\n })\n }\n\n // Resolve the response promise with the original response\n // since the `fetch()` return this internal promise.\n responsePromise.resolve(originalResponse)\n },\n respondWith: async (rawResponse) => {\n // Handle mocked `Response.error()` (i.e. request errors).\n if (isResponseError(rawResponse)) {\n this.logger.info('request has errored!', { response: rawResponse })\n responsePromise.reject(createNetworkError(rawResponse))\n return\n }\n\n this.logger.info('received mocked response!', {\n rawResponse,\n })\n\n // Decompress the mocked response body, if applicable.\n const decompressedStream = decompressResponse(rawResponse)\n const response = new FetchResponse(\n decompressedStream || rawResponse.body,\n {\n url: request.url,\n status: rawResponse.status,\n statusText: rawResponse.statusText,\n headers: rawResponse.headers,\n }\n )\n\n /**\n * Undici's handling of following redirect responses.\n * Treat the \"manual\" redirect mode as a regular mocked response.\n * This way, the client can manually follow the redirect it receives.\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1173\n */\n if (FetchResponse.isRedirectResponse(response.status)) {\n // Reject the request promise if its `redirect` is set to `error`\n // and it receives a mocked redirect response.\n if (request.redirect === 'error') {\n responsePromise.reject(createNetworkError('unexpected redirect'))\n return\n }\n\n if (request.redirect === 'follow') {\n followFetchRedirect(request, response).then(\n (response) => {\n responsePromise.resolve(response)\n },\n (reason) => {\n responsePromise.reject(reason)\n }\n )\n return\n }\n }\n\n if (this.emitter.listenerCount('response') > 0) {\n this.logger.info('emitting the \"response\" event...')\n\n // Await the response listeners to finish before resolving\n // the response promise. This ensures all your logic finishes\n // before the interceptor resolves the pending response.\n await emitAsync(this.emitter, 'response', {\n // Clone the mocked response for the \"response\" event listener.\n // This way, the listener can read the response and not lock its body\n // for the actual fetch consumer.\n response: FetchResponse.clone(response),\n isMockedResponse: true,\n request,\n requestId,\n })\n }\n\n responsePromise.resolve(response)\n },\n errorWith: (reason) => {\n this.logger.info('request has been aborted!', { reason })\n responsePromise.reject(reason)\n },\n })\n\n this.logger.info('[%s] %s', request.method, request.url)\n this.logger.info('awaiting for the mocked response...')\n\n this.logger.info(\n 'emitting the \"request\" event for %s listener(s)...',\n this.emitter.listenerCount('request')\n )\n\n await handleRequest({\n request,\n requestId,\n emitter: this.emitter,\n controller,\n })\n\n return responsePromise\n }\n\n logger.info('patching global fetch...')\n\n this.subscriptions.push(\n patchesRegistry.applyPatch(globalThis, 'fetch', () => fetchProxy)\n )\n\n logger.info('global fetch patched!', globalThis.fetch.name)\n }\n}\n"],"mappings":";;;;;;;;;AAAA,SAAgB,mBAAmB,OAAiB;AAClD,QAAO,OAAO,uBAAO,IAAI,UAAU,kBAAkB,EAAE,EACrD,OACD,CAAC;;;;;ACDJ,MAAM,uBAAuB;CAC3B;CACA;CACA;CACA;CACA;CACD;AAED,MAAM,iBAAiB,OAAO,iBAAiB;;;;AAK/C,eAAsB,oBACpB,SACA,UACmB;AACnB,KAAI,SAAS,WAAW,OAAO,QAAQ,QAAQ,KAC7C,QAAO,QAAQ,OAAO,oBAAoB,CAAC;CAG7C,MAAM,aAAa,IAAI,IAAI,QAAQ,IAAI;CAEvC,IAAIA;AACJ,KAAI;AAEF,gBAAc,IAAI,IAAI,SAAS,QAAQ,IAAI,WAAW,EAAG,QAAQ,IAAI;UAC9D,OAAO;AACd,SAAO,QAAQ,OAAO,mBAAmB,MAAM,CAAC;;AAGlD,KACE,EAAE,YAAY,aAAa,WAAW,YAAY,aAAa,UAE/D,QAAO,QAAQ,OACb,mBAAmB,sCAAsC,CAC1D;AAGH,KAAI,QAAQ,IAAI,SAAS,eAAe,GAAG,GACzC,QAAO,QAAQ,OAAO,mBAAmB,0BAA0B,CAAC;AAGtE,QAAO,eAAe,SAAS,gBAAgB,EAC7C,QAAQ,QAAQ,IAAI,SAAS,eAAe,IAAI,KAAK,GACtD,CAAC;AAEF,KACE,QAAQ,SAAS,WAChB,YAAY,YAAY,YAAY,aACrC,CAAC,WAAW,YAAY,YAAY,CAEpC,QAAO,QAAQ,OACb,mBAAmB,qDAAmD,CACvE;CAGH,MAAMC,cAA2B,EAAE;AAEnC,KACG,CAAC,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-.cjs b/node_modules/@mswjs/interceptors/lib/node/fetch-D2ClLNN-.cjs new file mode 100644 index 0000000000000000000000000000000000000000..4743c60bc43bbb9d8157c8c5e2b7ad6453eb34b6 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/fetch-D2ClLNN-.cjs @@ -0,0 +1,259 @@ +const require_chunk = require('./chunk-CbDLau6x.cjs'); +const require_fetchUtils = require('./fetchUtils-umV5xXBy.cjs'); +const require_getRawRequest = require('./getRawRequest-B6znU6il.cjs'); +const require_handleRequest = require('./handleRequest-C-cKYjIh.cjs'); +const require_hasConfigurableGlobal = require('./hasConfigurableGlobal-MjY06_Ok.cjs'); +let _open_draft_deferred_promise = require("@open-draft/deferred-promise"); +let _open_draft_until = require("@open-draft/until"); +let node_zlib = require("node:zlib"); +node_zlib = require_chunk.__toESM(node_zlib); + +//#region src/interceptors/fetch/utils/createNetworkError.ts +function createNetworkError(cause) { + return Object.assign(/* @__PURE__ */ new TypeError("Failed to fetch"), { cause }); +} + +//#endregion +//#region src/interceptors/fetch/utils/followRedirect.ts +const REQUEST_BODY_HEADERS = [ + "content-encoding", + "content-language", + "content-location", + "content-type", + "content-length" +]; +const kRedirectCount = Symbol("kRedirectCount"); +/** +* @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1210 +*/ +async function followFetchRedirect(request, response) { + if (response.status !== 303 && request.body != null) return Promise.reject(createNetworkError()); + const requestUrl = new URL(request.url); + let locationUrl; + try { + locationUrl = new URL(response.headers.get("location"), request.url); + } catch (error) { + return Promise.reject(createNetworkError(error)); + } + if (!(locationUrl.protocol === "http:" || locationUrl.protocol === "https:")) return Promise.reject(createNetworkError("URL scheme must be a HTTP(S) scheme")); + if (Reflect.get(request, kRedirectCount) > 20) return Promise.reject(createNetworkError("redirect count exceeded")); + Object.defineProperty(request, kRedirectCount, { value: (Reflect.get(request, kRedirectCount) || 0) + 1 }); + if (request.mode === "cors" && (locationUrl.username || locationUrl.password) && !sameOrigin(requestUrl, locationUrl)) return Promise.reject(createNetworkError("cross origin not allowed for request mode \"cors\"")); + const requestInit = {}; + if ([301, 302].includes(response.status) && request.method === "POST" || response.status === 303 && !["HEAD", "GET"].includes(request.method)) { + requestInit.method = "GET"; + requestInit.body = null; + REQUEST_BODY_HEADERS.forEach((headerName) => { + request.headers.delete(headerName); + }); + } + if (!sameOrigin(requestUrl, locationUrl)) { + request.headers.delete("authorization"); + request.headers.delete("proxy-authorization"); + request.headers.delete("cookie"); + request.headers.delete("host"); + } + /** + * @note Undici "safely" extracts the request body. + * I suspect we cannot dispatch this request again + * since its body has been read and the stream is locked. + */ + requestInit.headers = request.headers; + const finalResponse = await fetch(new Request(locationUrl, requestInit)); + Object.defineProperty(finalResponse, "redirected", { + value: true, + configurable: true + }); + return finalResponse; +} +/** +* @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/util.js#L761 +*/ +function sameOrigin(left, right) { + if (left.origin === right.origin && left.origin === "null") return true; + if (left.protocol === right.protocol && left.hostname === right.hostname && left.port === right.port) return true; + return false; +} + +//#endregion +//#region src/interceptors/fetch/utils/brotli-decompress.ts +var BrotliDecompressionStream = class extends TransformStream { + constructor() { + const decompress = node_zlib.default.createBrotliDecompress({ + flush: node_zlib.default.constants.BROTLI_OPERATION_FLUSH, + finishFlush: node_zlib.default.constants.BROTLI_OPERATION_FLUSH + }); + super({ async transform(chunk, controller) { + const buffer = Buffer.from(chunk); + const decompressed = await new Promise((resolve, reject) => { + decompress.write(buffer, (error) => { + if (error) reject(error); + }); + decompress.flush(); + decompress.once("data", (data) => resolve(data)); + decompress.once("error", (error) => reject(error)); + decompress.once("end", () => controller.terminate()); + }).catch((error) => { + controller.error(error); + }); + controller.enqueue(decompressed); + } }); + } +}; + +//#endregion +//#region src/interceptors/fetch/utils/decompression.ts +var PipelineStream = class extends TransformStream { + constructor(transformStreams, ...strategies) { + super({}, ...strategies); + const readable = [super.readable, ...transformStreams].reduce((readable$1, transform) => readable$1.pipeThrough(transform)); + Object.defineProperty(this, "readable", { get() { + return readable; + } }); + } +}; +function parseContentEncoding(contentEncoding) { + return contentEncoding.toLowerCase().split(",").map((coding) => coding.trim()); +} +function createDecompressionStream(contentEncoding) { + if (contentEncoding === "") return null; + const codings = parseContentEncoding(contentEncoding); + if (codings.length === 0) return null; + return new PipelineStream(codings.reduceRight((transformers, coding) => { + if (coding === "gzip" || coding === "x-gzip") return transformers.concat(new DecompressionStream("gzip")); + else if (coding === "deflate") return transformers.concat(new DecompressionStream("deflate")); + else if (coding === "br") return transformers.concat(new BrotliDecompressionStream()); + else transformers.length = 0; + return transformers; + }, [])); +} +function decompressResponse(response) { + if (response.body === null) return null; + const decompressionStream = createDecompressionStream(response.headers.get("content-encoding") || ""); + if (!decompressionStream) return null; + response.body.pipeTo(decompressionStream.writable); + return decompressionStream.readable; +} + +//#endregion +//#region src/interceptors/fetch/index.ts +var FetchInterceptor = class FetchInterceptor extends require_fetchUtils.Interceptor { + static { + this.symbol = Symbol.for("fetch-interceptor"); + } + constructor() { + super(FetchInterceptor.symbol); + } + checkEnvironment() { + return require_hasConfigurableGlobal.hasConfigurableGlobal("fetch"); + } + async setup() { + const logger = this.logger.extend("setup"); + const pureFetch = globalThis.fetch; + const fetchProxy = async (input, init) => { + const requestId = require_fetchUtils.createRequestId(); + const request = new require_fetchUtils.FetchRequest(typeof input === "string" && typeof location !== "undefined" && !require_fetchUtils.canParseUrl(input) ? new URL(input, location.href) : input, init); + /** + * @note Set the raw request only if a Request instance was provided to fetch. + */ + if (input instanceof Request) require_getRawRequest.setRawRequest(request, input); + const responsePromise = new _open_draft_deferred_promise.DeferredPromise(); + const controller = new require_fetchUtils.RequestController(request, { + passthrough: async () => { + this.logger.info("request has not been handled, passthrough..."); + /** + * @note Clone the request instance right before performing it. + * This preserves any modifications made to the intercepted request + * in the "request" listener. This also allows the user to read the + * request body in the "response" listener (otherwise "unusable"). + */ + const requestCloneForResponseEvent = request.clone(); + const { error: responseError, data: originalResponse } = await (0, _open_draft_until.until)(() => pureFetch(request)); + if (responseError) return responsePromise.reject(responseError); + this.logger.info("original fetch performed", originalResponse); + if (this.emitter.listenerCount("response") > 0) { + this.logger.info("emitting the \"response\" event..."); + const responseClone = require_fetchUtils.FetchResponse.clone(originalResponse); + await require_handleRequest.emitAsync(this.emitter, "response", { + response: responseClone, + isMockedResponse: false, + request: requestCloneForResponseEvent, + requestId + }); + } + responsePromise.resolve(originalResponse); + }, + respondWith: async (rawResponse) => { + if (require_handleRequest.isResponseError(rawResponse)) { + this.logger.info("request has errored!", { response: rawResponse }); + responsePromise.reject(createNetworkError(rawResponse)); + return; + } + this.logger.info("received mocked response!", { rawResponse }); + const response = new require_fetchUtils.FetchResponse(decompressResponse(rawResponse) || rawResponse.body, { + url: request.url, + status: rawResponse.status, + statusText: rawResponse.statusText, + headers: rawResponse.headers + }); + /** + * Undici's handling of following redirect responses. + * Treat the "manual" redirect mode as a regular mocked response. + * This way, the client can manually follow the redirect it receives. + * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1173 + */ + if (require_fetchUtils.FetchResponse.isRedirectResponse(response.status)) { + if (request.redirect === "error") { + responsePromise.reject(createNetworkError("unexpected redirect")); + return; + } + if (request.redirect === "follow") { + followFetchRedirect(request, response).then((response$1) => { + responsePromise.resolve(response$1); + }, (reason) => { + responsePromise.reject(reason); + }); + return; + } + } + if (this.emitter.listenerCount("response") > 0) { + this.logger.info("emitting the \"response\" event..."); + await require_handleRequest.emitAsync(this.emitter, "response", { + response: require_fetchUtils.FetchResponse.clone(response), + isMockedResponse: true, + request, + requestId + }); + } + responsePromise.resolve(response); + }, + errorWith: (reason) => { + this.logger.info("request has been aborted!", { reason }); + responsePromise.reject(reason); + } + }); + this.logger.info("[%s] %s", request.method, request.url); + this.logger.info("awaiting for the mocked response..."); + this.logger.info("emitting the \"request\" event for %s listener(s)...", this.emitter.listenerCount("request")); + await require_handleRequest.handleRequest({ + request, + requestId, + emitter: this.emitter, + controller + }); + return responsePromise; + }; + logger.info("patching global fetch..."); + this.subscriptions.push(require_hasConfigurableGlobal.patchesRegistry.applyPatch(globalThis, "fetch", () => fetchProxy)); + logger.info("global fetch patched!", globalThis.fetch.name); + } +}; + +//#endregion +Object.defineProperty(exports, 'FetchInterceptor', { + enumerable: true, + get: function () { + return FetchInterceptor; + } +}); +//# sourceMappingURL=fetch-D2ClLNN-.cjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/fetch-D2ClLNN-.cjs.map b/node_modules/@mswjs/interceptors/lib/node/fetch-D2ClLNN-.cjs.map new file mode 100644 index 0000000000000000000000000000000000000000..732a026f37abd229f07eb38cf9c995794fd50fa4 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/fetch-D2ClLNN-.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"fetch-D2ClLNN-.cjs","names":["locationUrl: URL","requestInit: RequestInit","zlib","readable","Interceptor","hasConfigurableGlobal","fetchProxy: typeof fetch","createRequestId","FetchRequest","canParseUrl","DeferredPromise","RequestController","FetchResponse","emitAsync","isResponseError","response","handleRequest","patchesRegistry"],"sources":["../../src/interceptors/fetch/utils/createNetworkError.ts","../../src/interceptors/fetch/utils/followRedirect.ts","../../src/interceptors/fetch/utils/brotli-decompress.ts","../../src/interceptors/fetch/utils/decompression.ts","../../src/interceptors/fetch/index.ts"],"sourcesContent":["export function createNetworkError(cause?: unknown) {\n return Object.assign(new TypeError('Failed to fetch'), {\n cause,\n })\n}\n","import { createNetworkError } from './createNetworkError'\n\nconst REQUEST_BODY_HEADERS = [\n 'content-encoding',\n 'content-language',\n 'content-location',\n 'content-type',\n 'content-length',\n]\n\nconst kRedirectCount = Symbol('kRedirectCount')\n\n/**\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1210\n */\nexport async function followFetchRedirect(\n request: Request,\n response: Response\n): Promise {\n if (response.status !== 303 && request.body != null) {\n return Promise.reject(createNetworkError())\n }\n\n const requestUrl = new URL(request.url)\n\n let locationUrl: URL\n try {\n // If the location is a relative URL, use the request URL as the base URL.\n locationUrl = new URL(response.headers.get('location')!, request.url) \n } catch (error) {\n return Promise.reject(createNetworkError(error))\n }\n\n if (\n !(locationUrl.protocol === 'http:' || locationUrl.protocol === 'https:')\n ) {\n return Promise.reject(\n createNetworkError('URL scheme must be a HTTP(S) scheme')\n )\n }\n\n if (Reflect.get(request, kRedirectCount) > 20) {\n return Promise.reject(createNetworkError('redirect count exceeded'))\n }\n\n Object.defineProperty(request, kRedirectCount, {\n value: (Reflect.get(request, kRedirectCount) || 0) + 1,\n })\n\n if (\n request.mode === 'cors' &&\n (locationUrl.username || locationUrl.password) &&\n !sameOrigin(requestUrl, locationUrl)\n ) {\n return Promise.reject(\n createNetworkError('cross origin not allowed for request mode \"cors\"')\n )\n }\n\n const requestInit: RequestInit = {}\n\n if (\n ([301, 302].includes(response.status) && request.method === 'POST') ||\n (response.status === 303 && !['HEAD', 'GET'].includes(request.method))\n ) {\n requestInit.method = 'GET'\n requestInit.body = null\n\n REQUEST_BODY_HEADERS.forEach((headerName) => {\n request.headers.delete(headerName)\n })\n }\n\n if (!sameOrigin(requestUrl, locationUrl)) {\n request.headers.delete('authorization')\n request.headers.delete('proxy-authorization')\n request.headers.delete('cookie')\n request.headers.delete('host')\n }\n\n /**\n * @note Undici \"safely\" extracts the request body.\n * I suspect we cannot dispatch this request again\n * since its body has been read and the stream is locked.\n */\n\n requestInit.headers = request.headers\n const finalResponse = await fetch(new Request(locationUrl, requestInit))\n Object.defineProperty(finalResponse, 'redirected', {\n value: true,\n configurable: true,\n })\n\n return finalResponse\n}\n\n/**\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/util.js#L761\n */\nfunction sameOrigin(left: URL, right: URL): boolean {\n if (left.origin === right.origin && left.origin === 'null') {\n return true\n }\n\n if (\n left.protocol === right.protocol &&\n left.hostname === right.hostname &&\n left.port === right.port\n ) {\n return true\n }\n\n return false\n}\n","import zlib from 'node:zlib'\n\nexport class BrotliDecompressionStream extends TransformStream {\n constructor() {\n const decompress = zlib.createBrotliDecompress({\n flush: zlib.constants.BROTLI_OPERATION_FLUSH,\n finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH,\n })\n\n super({\n async transform(chunk, controller) {\n const buffer = Buffer.from(chunk)\n\n const decompressed = await new Promise((resolve, reject) => {\n decompress.write(buffer, (error) => {\n if (error) reject(error)\n })\n\n decompress.flush()\n decompress.once('data', (data) => resolve(data))\n decompress.once('error', (error) => reject(error))\n decompress.once('end', () => controller.terminate())\n }).catch((error) => {\n controller.error(error)\n })\n\n controller.enqueue(decompressed)\n },\n })\n }\n}\n","// Import from an internal alias that resolves to different modules\n// depending on the environment. This way, we can keep the fetch interceptor\n// intact while using different strategies for Brotli decompression.\nimport { BrotliDecompressionStream } from 'internal:brotli-decompress'\n\nclass PipelineStream extends TransformStream {\n constructor(\n transformStreams: Array,\n ...strategies: Array\n ) {\n super({}, ...strategies)\n\n const readable = [super.readable as any, ...transformStreams].reduce(\n (readable, transform) => readable.pipeThrough(transform)\n )\n\n Object.defineProperty(this, 'readable', {\n get() {\n return readable\n },\n })\n }\n}\n\nexport function parseContentEncoding(contentEncoding: string): Array {\n return contentEncoding\n .toLowerCase()\n .split(',')\n .map((coding) => coding.trim())\n}\n\nfunction createDecompressionStream(\n contentEncoding: string\n): TransformStream | null {\n if (contentEncoding === '') {\n return null\n }\n\n const codings = parseContentEncoding(contentEncoding)\n\n if (codings.length === 0) {\n return null\n }\n\n const transformers = codings.reduceRight>(\n (transformers, coding) => {\n if (coding === 'gzip' || coding === 'x-gzip') {\n return transformers.concat(new DecompressionStream('gzip'))\n } else if (coding === 'deflate') {\n return transformers.concat(new DecompressionStream('deflate'))\n } else if (coding === 'br') {\n return transformers.concat(new BrotliDecompressionStream())\n } else {\n transformers.length = 0\n }\n\n return transformers\n },\n []\n )\n\n return new PipelineStream(transformers)\n}\n\nexport function decompressResponse(\n response: Response\n): ReadableStream | null {\n if (response.body === null) {\n return null\n }\n\n const decompressionStream = createDecompressionStream(\n response.headers.get('content-encoding') || ''\n )\n\n if (!decompressionStream) {\n return null\n }\n\n // Use `pipeTo` and return the decompression stream's readable\n // instead of `pipeThrough` because that will lock the original\n // response stream, making it unusable as the input to Response.\n response.body.pipeTo(decompressionStream.writable)\n return decompressionStream.readable\n}\n","import { until } from '@open-draft/until'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { HttpRequestEventMap } from '../../glossary'\nimport { Interceptor } from '../../Interceptor'\nimport { RequestController } from '../../RequestController'\nimport { emitAsync } from '../../utils/emitAsync'\nimport { handleRequest } from '../../utils/handleRequest'\nimport { canParseUrl } from '../../utils/canParseUrl'\nimport { createRequestId } from '../../createRequestId'\nimport { createNetworkError } from './utils/createNetworkError'\nimport { followFetchRedirect } from './utils/followRedirect'\nimport { decompressResponse } from './utils/decompression'\nimport { hasConfigurableGlobal } from '../../utils/hasConfigurableGlobal'\nimport { FetchRequest, FetchResponse } from '../../utils/fetchUtils'\nimport { setRawRequest } from '../../getRawRequest'\nimport { isResponseError } from '../../utils/responseUtils'\nimport { patchesRegistry } from '../../utils/patchesRegistry'\n\nexport class FetchInterceptor extends Interceptor {\n static symbol = Symbol.for('fetch-interceptor')\n\n constructor() {\n super(FetchInterceptor.symbol)\n }\n\n protected checkEnvironment() {\n return hasConfigurableGlobal('fetch')\n }\n\n protected async setup() {\n const logger = this.logger.extend('setup')\n\n const pureFetch = globalThis.fetch\n\n const fetchProxy: typeof fetch = async (input, init) => {\n const requestId = createRequestId()\n\n /**\n * @note Resolve potentially relative request URL\n * against the present `location`. This is mainly\n * for native `fetch` in JSDOM.\n * @see https://github.com/mswjs/msw/issues/1625\n */\n const resolvedInput =\n typeof input === 'string' &&\n typeof location !== 'undefined' &&\n !canParseUrl(input)\n ? new URL(input, location.href)\n : input\n\n const request = new FetchRequest(resolvedInput, init)\n\n /**\n * @note Set the raw request only if a Request instance was provided to fetch.\n */\n if (input instanceof Request) {\n setRawRequest(request, input)\n }\n\n const responsePromise = new DeferredPromise()\n\n const controller = new RequestController(request, {\n passthrough: async () => {\n this.logger.info('request has not been handled, passthrough...')\n\n /**\n * @note Clone the request instance right before performing it.\n * This preserves any modifications made to the intercepted request\n * in the \"request\" listener. This also allows the user to read the\n * request body in the \"response\" listener (otherwise \"unusable\").\n */\n const requestCloneForResponseEvent = request.clone()\n\n // Perform the intercepted request as-is.\n const { error: responseError, data: originalResponse } = await until(\n () => pureFetch(request)\n )\n\n if (responseError) {\n return responsePromise.reject(responseError)\n }\n\n this.logger.info('original fetch performed', originalResponse)\n\n if (this.emitter.listenerCount('response') > 0) {\n this.logger.info('emitting the \"response\" event...')\n\n const responseClone = FetchResponse.clone(originalResponse)\n await emitAsync(this.emitter, 'response', {\n response: responseClone,\n isMockedResponse: false,\n request: requestCloneForResponseEvent,\n requestId,\n })\n }\n\n // Resolve the response promise with the original response\n // since the `fetch()` return this internal promise.\n responsePromise.resolve(originalResponse)\n },\n respondWith: async (rawResponse) => {\n // Handle mocked `Response.error()` (i.e. request errors).\n if (isResponseError(rawResponse)) {\n this.logger.info('request has errored!', { response: rawResponse })\n responsePromise.reject(createNetworkError(rawResponse))\n return\n }\n\n this.logger.info('received mocked response!', {\n rawResponse,\n })\n\n // Decompress the mocked response body, if applicable.\n const decompressedStream = decompressResponse(rawResponse)\n const response = new FetchResponse(\n decompressedStream || rawResponse.body,\n {\n url: request.url,\n status: rawResponse.status,\n statusText: rawResponse.statusText,\n headers: rawResponse.headers,\n }\n )\n\n /**\n * Undici's handling of following redirect responses.\n * Treat the \"manual\" redirect mode as a regular mocked response.\n * This way, the client can manually follow the redirect it receives.\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1173\n */\n if (FetchResponse.isRedirectResponse(response.status)) {\n // Reject the request promise if its `redirect` is set to `error`\n // and it receives a mocked redirect response.\n if (request.redirect === 'error') {\n responsePromise.reject(createNetworkError('unexpected redirect'))\n return\n }\n\n if (request.redirect === 'follow') {\n followFetchRedirect(request, response).then(\n (response) => {\n responsePromise.resolve(response)\n },\n (reason) => {\n responsePromise.reject(reason)\n }\n )\n return\n }\n }\n\n if (this.emitter.listenerCount('response') > 0) {\n this.logger.info('emitting the \"response\" event...')\n\n // Await the response listeners to finish before resolving\n // the response promise. This ensures all your logic finishes\n // before the interceptor resolves the pending response.\n await emitAsync(this.emitter, 'response', {\n // Clone the mocked response for the \"response\" event listener.\n // This way, the listener can read the response and not lock its body\n // for the actual fetch consumer.\n response: FetchResponse.clone(response),\n isMockedResponse: true,\n request,\n requestId,\n })\n }\n\n responsePromise.resolve(response)\n },\n errorWith: (reason) => {\n this.logger.info('request has been aborted!', { reason })\n responsePromise.reject(reason)\n },\n })\n\n this.logger.info('[%s] %s', request.method, request.url)\n this.logger.info('awaiting for the mocked response...')\n\n this.logger.info(\n 'emitting the \"request\" event for %s listener(s)...',\n this.emitter.listenerCount('request')\n )\n\n await handleRequest({\n request,\n requestId,\n emitter: this.emitter,\n controller,\n })\n\n return responsePromise\n }\n\n logger.info('patching global fetch...')\n\n this.subscriptions.push(\n patchesRegistry.applyPatch(globalThis, 'fetch', () => fetchProxy)\n )\n\n logger.info('global fetch patched!', globalThis.fetch.name)\n }\n}\n"],"mappings":";;;;;;;;;;;AAAA,SAAgB,mBAAmB,OAAiB;AAClD,QAAO,OAAO,uBAAO,IAAI,UAAU,kBAAkB,EAAE,EACrD,OACD,CAAC;;;;;ACDJ,MAAM,uBAAuB;CAC3B;CACA;CACA;CACA;CACA;CACD;AAED,MAAM,iBAAiB,OAAO,iBAAiB;;;;AAK/C,eAAsB,oBACpB,SACA,UACmB;AACnB,KAAI,SAAS,WAAW,OAAO,QAAQ,QAAQ,KAC7C,QAAO,QAAQ,OAAO,oBAAoB,C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K,OAAO,KAAK,qCAAmC;AAKpD,YAAMF,gCAAU,KAAK,SAAS,YAAY;OAIxC,UAAUD,iCAAc,MAAM,SAAS;OACvC,kBAAkB;OAClB;OACA;OACD,CAAC;;AAGJ,qBAAgB,QAAQ,SAAS;;IAEnC,YAAY,WAAW;AACrB,UAAK,OAAO,KAAK,6BAA6B,EAAE,QAAQ,CAAC;AACzD,qBAAgB,OAAO,OAAO;;IAEjC,CAAC;AAEF,QAAK,OAAO,KAAK,WAAW,QAAQ,QAAQ,QAAQ,IAAI;AACxD,QAAK,OAAO,KAAK,sCAAsC;AAEvD,QAAK,OAAO,KACV,wDACA,KAAK,QAAQ,cAAc,UAAU,CACtC;AAED,SAAMI,oCAAc;IAClB;IACA;IACA,SAAS,KAAK;IACd;IACD,CAAC;AAEF,UAAO;;AAGT,SAAO,KAAK,2BAA2B;AAEvC,OAAK,cAAc,KACjBC,8CAAgB,WAAW,YAAY,eAAe,WAAW,CAClE;AAED,SAAO,KAAK,yBAAyB,WAAW,MAAM,KAAK"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/fetchUtils-BKJ1XmiO.mjs b/node_modules/@mswjs/interceptors/lib/node/fetchUtils-BKJ1XmiO.mjs new file mode 100644 index 0000000000000000000000000000000000000000..796fd83e5d01f09d201d3983ff5f3f67e41b0edf --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/fetchUtils-BKJ1XmiO.mjs @@ -0,0 +1,480 @@ +import { Logger } from "@open-draft/logger"; +import { Emitter } from "strict-event-emitter"; +import { DeferredPromise } from "@open-draft/deferred-promise"; +import { invariant } from "outvariant"; + +//#region src/Interceptor.ts +/** +* Request header name to detect when a single request +* is being handled by nested interceptors (XHR -> ClientRequest). +* Obscure by design to prevent collisions with user-defined headers. +* Ideally, come up with the Interceptor-level mechanism for this. +* @see https://github.com/mswjs/interceptors/issues/378 +*/ +const INTERNAL_REQUEST_ID_HEADER_NAME = "x-interceptors-internal-request-id"; +function getGlobalSymbol(symbol) { + return globalThis[symbol] || void 0; +} +function setGlobalSymbol(symbol, value) { + globalThis[symbol] = value; +} +function deleteGlobalSymbol(symbol) { + delete globalThis[symbol]; +} +let InterceptorReadyState = /* @__PURE__ */ function(InterceptorReadyState$1) { + InterceptorReadyState$1["INACTIVE"] = "INACTIVE"; + InterceptorReadyState$1["APPLYING"] = "APPLYING"; + InterceptorReadyState$1["APPLIED"] = "APPLIED"; + InterceptorReadyState$1["DISPOSING"] = "DISPOSING"; + InterceptorReadyState$1["DISPOSED"] = "DISPOSED"; + return InterceptorReadyState$1; +}({}); +var Interceptor = class { + constructor(symbol) { + this.symbol = symbol; + this.readyState = InterceptorReadyState.INACTIVE; + this.emitter = new Emitter(); + this.subscriptions = []; + this.logger = new Logger(symbol.description); + this.emitter.setMaxListeners(0); + this.logger.info("constructing the interceptor..."); + } + /** + * Determine if this interceptor can be applied + * in the current environment. + */ + checkEnvironment() { + return true; + } + /** + * Apply this interceptor to the current process. + * Returns an already running interceptor instance if it's present. + */ + apply() { + const logger = this.logger.extend("apply"); + logger.info("applying the interceptor..."); + if (this.readyState === InterceptorReadyState.APPLIED) { + logger.info("intercepted already applied!"); + return; + } + if (!this.checkEnvironment()) { + logger.info("the interceptor cannot be applied in this environment!"); + return; + } + this.readyState = InterceptorReadyState.APPLYING; + const runningInstance = this.getInstance(); + if (runningInstance) { + logger.info("found a running instance, reusing..."); + this.on = (event, listener) => { + logger.info("proxying the \"%s\" listener", event); + runningInstance.emitter.addListener(event, listener); + this.subscriptions.push(() => { + runningInstance.emitter.removeListener(event, listener); + logger.info("removed proxied \"%s\" listener!", event); + }); + return this; + }; + this.readyState = InterceptorReadyState.APPLIED; + return; + } + logger.info("no running instance found, setting up a new instance..."); + this.setup(); + this.setInstance(); + this.readyState = InterceptorReadyState.APPLIED; + } + /** + * Setup the module augments and stubs necessary for this interceptor. + * This method is not run if there's a running interceptor instance + * to prevent instantiating an interceptor multiple times. + */ + setup() {} + /** + * Listen to the interceptor's public events. + */ + on(event, listener) { + const logger = this.logger.extend("on"); + if (this.readyState === InterceptorReadyState.DISPOSING || this.readyState === InterceptorReadyState.DISPOSED) { + logger.info("cannot listen to events, already disposed!"); + return this; + } + logger.info("adding \"%s\" event listener:", event, listener); + this.emitter.on(event, listener); + return this; + } + once(event, listener) { + this.emitter.once(event, listener); + return this; + } + off(event, listener) { + this.emitter.off(event, listener); + return this; + } + removeAllListeners(event) { + this.emitter.removeAllListeners(event); + return this; + } + /** + * Disposes of any side-effects this interceptor has introduced. + */ + dispose() { + const logger = this.logger.extend("dispose"); + if (this.readyState === InterceptorReadyState.DISPOSED) { + logger.info("cannot dispose, already disposed!"); + return; + } + logger.info("disposing the interceptor..."); + this.readyState = InterceptorReadyState.DISPOSING; + if (!this.getInstance()) { + logger.info("no interceptors running, skipping dispose..."); + return; + } + this.clearInstance(); + logger.info("global symbol deleted:", getGlobalSymbol(this.symbol)); + if (this.subscriptions.length > 0) { + logger.info("disposing of %d subscriptions...", this.subscriptions.length); + for (const dispose of this.subscriptions) dispose(); + this.subscriptions = []; + logger.info("disposed of all subscriptions!", this.subscriptions.length); + } + this.emitter.removeAllListeners(); + logger.info("destroyed the listener!"); + this.readyState = InterceptorReadyState.DISPOSED; + } + getInstance() { + const instance = getGlobalSymbol(this.symbol); + this.logger.info("retrieved global instance:", instance?.constructor?.name); + return instance; + } + setInstance() { + setGlobalSymbol(this.symbol, this); + this.logger.info("set global instance!", this.symbol.description); + } + clearInstance() { + deleteGlobalSymbol(this.symbol); + this.logger.info("cleared global instance!", this.symbol.description); + } +}; + +//#endregion +//#region src/InterceptorError.ts +var InterceptorError = class InterceptorError extends Error { + constructor(message) { + super(message); + this.name = "InterceptorError"; + Object.setPrototypeOf(this, InterceptorError.prototype); + } +}; + +//#endregion +//#region src/RequestController.ts +var RequestController = class RequestController { + static { + this.PENDING = 0; + } + static { + this.PASSTHROUGH = 1; + } + static { + this.RESPONSE = 2; + } + static { + this.ERROR = 3; + } + constructor(request, source) { + this.request = request; + this.source = source; + this.readyState = RequestController.PENDING; + this.handled = new DeferredPromise(); + } + get #handled() { + return this.handled; + } + /** + * Perform this request as-is. + */ + async passthrough() { + invariant.as(InterceptorError, this.readyState === RequestController.PENDING, "Failed to passthrough the \"%s %s\" request: the request has already been handled", this.request.method, this.request.url); + this.readyState = RequestController.PASSTHROUGH; + await this.source.passthrough(); + this.#handled.resolve(); + } + /** + * Respond to this request with the given `Response` instance. + * + * @example + * controller.respondWith(new Response()) + * controller.respondWith(Response.json({ id })) + * controller.respondWith(Response.error()) + */ + respondWith(response) { + invariant.as(InterceptorError, this.readyState === RequestController.PENDING, "Failed to respond to the \"%s %s\" request with \"%d %s\": the request has already been handled (%d)", this.request.method, this.request.url, response.status, response.statusText || "OK", this.readyState); + this.readyState = RequestController.RESPONSE; + this.#handled.resolve(); + /** + * @note Although `source.respondWith()` is potentially asynchronous, + * do NOT await it for backward-compatibility. Awaiting it will short-circuit + * the request listener invocation as soon as a listener responds to a request. + * Ideally, that's what we want, but that's not what we promise the user. + */ + this.source.respondWith(response); + } + /** + * Error this request with the given reason. + * + * @example + * controller.errorWith() + * controller.errorWith(new Error('Oops!')) + * controller.errorWith({ message: 'Oops!'}) + */ + errorWith(reason) { + invariant.as(InterceptorError, this.readyState === RequestController.PENDING, "Failed to error the \"%s %s\" request with \"%s\": the request has already been handled (%d)", this.request.method, this.request.url, reason?.toString(), this.readyState); + this.readyState = RequestController.ERROR; + this.source.errorWith(reason); + this.#handled.resolve(); + } +}; + +//#endregion +//#region src/createRequestId.ts +/** +* Generate a random ID string to represent a request. +* @example +* createRequestId() +* // "f774b6c9c600f" +*/ +function createRequestId() { + return Math.random().toString(16).slice(2); +} + +//#endregion +//#region src/utils/canParseUrl.ts +/** +* Returns a boolean indicating whether the given URL string +* can be parsed into a `URL` instance. +* A substitute for `URL.canParse()` for Node.js 18. +*/ +function canParseUrl(url) { + try { + new URL(url); + return true; + } catch (_error) { + return false; + } +} + +//#endregion +//#region src/utils/getValueBySymbol.ts +/** +* Returns the value behind the symbol with the given name. +*/ +function getValueBySymbol(symbolName, source) { + const symbol = Object.getOwnPropertySymbols(source).find((symbol$1) => { + return symbol$1.description === symbolName; + }); + if (symbol) return Reflect.get(source, symbol); +} + +//#endregion +//#region src/utils/fetchUtils.ts +var FetchRequest = class FetchRequest extends Request { + static #resolveProperty(input, init = {}, key) { + return init[key] ?? (input instanceof Request ? input[key] : void 0); + } + /** + * Check if the given request method is configurable. + * @see https://fetch.spec.whatwg.org/#methods + */ + static isConfigurableMethod(method) { + return method !== "CONNECT" && method !== "TRACE" && method !== "TRACK"; + } + static isMethodWithBody(method) { + return method !== "HEAD" && method !== "GET" && FetchRequest.isConfigurableMethod(method); + } + /** + * Check if the given request `mode` is configurable. + * @see https://fetch.spec.whatwg.org/#concept-request-mode + */ + static isConfigurableMode(mode) { + return mode !== "navigate" && mode !== "websocket" && mode !== "webtransport"; + } + constructor(input, init) { + const method = FetchRequest.#resolveProperty(input, init, "method") || "GET"; + const safeMethod = FetchRequest.isConfigurableMethod(method) ? method : "GET"; + const hasExplicitBody = init != null && "body" in init; + /** + * Only include `body` in the super init when it needs to be overridden. + * When `input` is a Request and no explicit body is in `init`, let the + * Request constructor handle body transfer naturally so it properly + * marks the original request's body as consumed (bodyUsed = true). + */ + const bodyInit = !FetchRequest.isMethodWithBody(method) ? { body: void 0 } : hasExplicitBody ? { body: init.body } : {}; + const mode = FetchRequest.#resolveProperty(input, init, "mode") ?? void 0; + const safeMode = FetchRequest.isConfigurableMode(mode) ? mode : void 0; + super(input, { + ...init || {}, + method: safeMethod, + mode: safeMode, + duplex: init?.duplex ?? (FetchRequest.isMethodWithBody(method) ? "half" : void 0), + ...bodyInit + }); + if (method !== safeMethod) this.#setInternalProperty("method", method); + if (method === "CONNECT") { + const url = new URL(input instanceof Request ? input.url : input); + let authority; + /** + * @note Node.js has a bug parsing raw CONNECT requests URLs like + * "http://127.0.0.1:1337/localhost:80". It would treat "localhost:" as a protocol. + */ + if (url.protocol === "localhost:") authority = url.href; + else authority = url.pathname.replace(/^\/+/, ""); + /** + * @note Define "url" as a getter because Undici uses their own + * logic to resolve the "request.url" property. Simply reassigning + * its value doesn't do anything. This is a destructive action + * but it's safe because "CONNECT" requests are forbidden per fetch. + */ + Object.defineProperty(this, "url", { + get: () => authority, + enumerable: true, + configurable: true + }); + } + if (mode != null && mode !== safeMode) this.#setInternalProperty("mode", mode); + } + #setInternalProperty(key, value) { + const internalState = getValueBySymbol("state", this); + if (internalState) Reflect.set(internalState, key, value); + else Object.defineProperty(this, key, { + value, + enumerable: true, + configurable: true, + writable: false + }); + } +}; +const kStatus = Symbol("kStatus"); +const kUrl = Symbol("kUrl"); +var FetchResponse = class FetchResponse extends Response { + static { + this.STATUS_CODES_WITHOUT_BODY = [ + 101, + 103, + 204, + 205, + 304 + ]; + } + static { + this.STATUS_CODES_WITH_REDIRECT = [ + 301, + 302, + 303, + 307, + 308 + ]; + } + static isConfigurableStatusCode(status) { + return status >= 200 && status <= 599; + } + static isRedirectResponse(status) { + return FetchResponse.STATUS_CODES_WITH_REDIRECT.includes(status); + } + /** + * Returns a boolean indicating whether the given response status + * code represents a response that can have a body. + */ + static isResponseWithBody(status) { + return !FetchResponse.STATUS_CODES_WITHOUT_BODY.includes(status); + } + static setStatus(status, response) { + /** + * @note Undici keeps an internal "Symbol(state)" that holds + * the actual value of response status. Update that in Node.js. + */ + const internalState = getValueBySymbol("state", response); + if (internalState) internalState.status = status; + else Object.defineProperty(response, "status", { + value: status, + enumerable: true, + configurable: true, + writable: false + }); + Object.defineProperty(response, kStatus, { + value: status, + enumerable: false + }); + } + static setUrl(url, response) { + if (!url || url === "about:" || !canParseUrl(url)) return; + const state = getValueBySymbol("state", response); + if (state) state.urlList.push(new URL(url)); + else Object.defineProperty(response, "url", { + value: url, + enumerable: true, + configurable: true, + writable: false + }); + Object.defineProperty(response, kUrl, { + value: url, + enumerable: false + }); + } + /** + * Parses the given raw HTTP headers into a Fetch API `Headers` instance. + */ + static parseRawHeaders(rawHeaders) { + const headers = new Headers(); + for (let line = 0; line < rawHeaders.length; line += 2) headers.append(rawHeaders[line], rawHeaders[line + 1]); + return headers; + } + /** + * Safely clones the given `Response`. + * Coerces response clone exceptions into 500 mocked responses. + * Handy in the environments that introduce arbitrary response + * cloning restrictions, like "101 Switching Protocols" cloning + * in "miniflare". + */ + static clone(response) { + try { + return response.clone(); + } catch (error) { + return Response.json(error instanceof Error ? { + name: error.name, + message: error.message, + stack: error.stack + } : {}, { + status: 500, + statusText: "Unclonable Response" + }); + } + } + constructor(body, init = {}) { + const status = init.status ?? 200; + const safeStatus = FetchResponse.isConfigurableStatusCode(status) ? status : 200; + const finalBody = FetchResponse.isResponseWithBody(status) ? body : null; + super(finalBody, { + status: safeStatus, + statusText: init.statusText, + headers: init.headers + }); + /** + * Since Node.js v24, Undici stores the Response state in an inaccessible field "#state". + * Forward the modified status/URL to the cloned response manually. + * @see https://github.com/nodejs/undici/blob/f734c87280e626c75f59aad55b65eb6a89cef392/lib/web/fetch/response.js#L242 + */ + if (status !== safeStatus) FetchResponse.setStatus(status, this); + FetchResponse.setUrl(init.url, this); + } + clone() { + const clonedResponse = super.clone(); + const customStatus = Reflect.get(this, kStatus); + if (customStatus) FetchResponse.setStatus(customStatus, clonedResponse); + const customUrl = Reflect.get(this, kUrl); + if (customUrl) FetchResponse.setUrl(customUrl, clonedResponse); + return clonedResponse; + } +}; + +//#endregion +export { RequestController as a, Interceptor as c, getGlobalSymbol as d, createRequestId as i, InterceptorReadyState as l, FetchResponse as n, InterceptorError as o, canParseUrl as r, INTERNAL_REQUEST_ID_HEADER_NAME as s, FetchRequest as t, deleteGlobalSymbol as u }; +//# sourceMappingURL=fetchUtils-BKJ1XmiO.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/fetchUtils-BKJ1XmiO.mjs.map b/node_modules/@mswjs/interceptors/lib/node/fetchUtils-BKJ1XmiO.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..e8c52de75d5e90fa4bf5974ddd740d02ceec8514 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/fetchUtils-BKJ1XmiO.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"fetchUtils-BKJ1XmiO.mjs","names":["symbol: symbol","request: Request","source: RequestControllerSource","#handled","symbol","#resolveProperty","bodyInit: { body?: BodyInit | null }","#setInternalProperty","authority: string"],"sources":["../../src/Interceptor.ts","../../src/InterceptorError.ts","../../src/RequestController.ts","../../src/createRequestId.ts","../../src/utils/canParseUrl.ts","../../src/utils/getValueBySymbol.ts","../../src/utils/fetchUtils.ts"],"sourcesContent":["import { Logger } from '@open-draft/logger'\nimport { Emitter, Listener } from 'strict-event-emitter'\n\nexport type InterceptorEventMap = Record\nexport type InterceptorSubscription = () => void\n\n/**\n * Request header name to detect when a single request\n * is being handled by nested interceptors (XHR -> ClientRequest).\n * Obscure by design to prevent collisions with user-defined headers.\n * Ideally, come up with the Interceptor-level mechanism for this.\n * @see https://github.com/mswjs/interceptors/issues/378\n */\nexport const INTERNAL_REQUEST_ID_HEADER_NAME =\n 'x-interceptors-internal-request-id'\n\nexport function getGlobalSymbol(symbol: Symbol): V | undefined {\n return (\n // @ts-ignore https://github.com/Microsoft/TypeScript/issues/24587\n globalThis[symbol] || undefined\n )\n}\n\nfunction setGlobalSymbol(symbol: Symbol, value: any): void {\n // @ts-ignore\n globalThis[symbol] = value\n}\n\nexport function deleteGlobalSymbol(symbol: Symbol): void {\n // @ts-ignore\n delete globalThis[symbol]\n}\n\nexport enum InterceptorReadyState {\n INACTIVE = 'INACTIVE',\n APPLYING = 'APPLYING',\n APPLIED = 'APPLIED',\n DISPOSING = 'DISPOSING',\n DISPOSED = 'DISPOSED',\n}\n\nexport type ExtractEventNames> =\n Events extends Record ? EventName : never\n\nexport class Interceptor {\n protected emitter: Emitter\n protected subscriptions: Array\n protected logger: Logger\n\n public readyState: InterceptorReadyState\n\n constructor(private readonly symbol: symbol) {\n this.readyState = InterceptorReadyState.INACTIVE\n\n this.emitter = new Emitter()\n this.subscriptions = []\n this.logger = new Logger(symbol.description!)\n\n // Do not limit the maximum number of listeners\n // so not to limit the maximum amount of parallel events emitted.\n this.emitter.setMaxListeners(0)\n\n this.logger.info('constructing the interceptor...')\n }\n\n /**\n * Determine if this interceptor can be applied\n * in the current environment.\n */\n protected checkEnvironment(): boolean {\n return true\n }\n\n /**\n * Apply this interceptor to the current process.\n * Returns an already running interceptor instance if it's present.\n */\n public apply(): void {\n const logger = this.logger.extend('apply')\n logger.info('applying the interceptor...')\n\n if (this.readyState === InterceptorReadyState.APPLIED) {\n logger.info('intercepted already applied!')\n return\n }\n\n const shouldApply = this.checkEnvironment()\n\n if (!shouldApply) {\n logger.info('the interceptor cannot be applied in this environment!')\n return\n }\n\n this.readyState = InterceptorReadyState.APPLYING\n\n // Whenever applying a new interceptor, check if it hasn't been applied already.\n // This enables to apply the same interceptor multiple times, for example from a different\n // interceptor, only proxying events but keeping the stubs in a single place.\n const runningInstance = this.getInstance()\n\n if (runningInstance) {\n logger.info('found a running instance, reusing...')\n\n // Proxy any listeners you set on this instance to the running instance.\n this.on = (event, listener) => {\n logger.info('proxying the \"%s\" listener', event)\n\n // Add listeners to the running instance so they appear\n // at the top of the event listeners list and are executed first.\n runningInstance.emitter.addListener(event, listener)\n\n // Ensure that once this interceptor instance is disposed,\n // it removes all listeners it has appended to the running interceptor instance.\n this.subscriptions.push(() => {\n runningInstance.emitter.removeListener(event, listener)\n logger.info('removed proxied \"%s\" listener!', event)\n })\n\n return this\n }\n\n this.readyState = InterceptorReadyState.APPLIED\n\n return\n }\n\n logger.info('no running instance found, setting up a new instance...')\n\n // Setup the interceptor.\n this.setup()\n\n // Store the newly applied interceptor instance globally.\n this.setInstance()\n\n this.readyState = InterceptorReadyState.APPLIED\n }\n\n /**\n * Setup the module augments and stubs necessary for this interceptor.\n * This method is not run if there's a running interceptor instance\n * to prevent instantiating an interceptor multiple times.\n */\n protected setup(): void {}\n\n /**\n * Listen to the interceptor's public events.\n */\n public on>(\n event: EventName,\n listener: Listener\n ): this {\n const logger = this.logger.extend('on')\n\n if (\n this.readyState === InterceptorReadyState.DISPOSING ||\n this.readyState === InterceptorReadyState.DISPOSED\n ) {\n logger.info('cannot listen to events, already disposed!')\n return this\n }\n\n logger.info('adding \"%s\" event listener:', event, listener)\n\n this.emitter.on(event, listener)\n return this\n }\n\n public once>(\n event: EventName,\n listener: Listener\n ): this {\n this.emitter.once(event, listener)\n return this\n }\n\n public off>(\n event: EventName,\n listener: Listener\n ): this {\n this.emitter.off(event, listener)\n return this\n }\n\n public removeAllListeners>(\n event?: EventName\n ): this {\n this.emitter.removeAllListeners(event)\n return this\n }\n\n /**\n * Disposes of any side-effects this interceptor has introduced.\n */\n public dispose(): void {\n const logger = this.logger.extend('dispose')\n\n if (this.readyState === InterceptorReadyState.DISPOSED) {\n logger.info('cannot dispose, already disposed!')\n return\n }\n\n logger.info('disposing the interceptor...')\n this.readyState = InterceptorReadyState.DISPOSING\n\n if (!this.getInstance()) {\n logger.info('no interceptors running, skipping dispose...')\n return\n }\n\n // Delete the global symbol as soon as possible,\n // indicating that the interceptor is no longer running.\n this.clearInstance()\n\n logger.info('global symbol deleted:', getGlobalSymbol(this.symbol))\n\n if (this.subscriptions.length > 0) {\n logger.info('disposing of %d subscriptions...', this.subscriptions.length)\n\n for (const dispose of this.subscriptions) {\n dispose()\n }\n\n this.subscriptions = []\n\n logger.info('disposed of all subscriptions!', this.subscriptions.length)\n }\n\n this.emitter.removeAllListeners()\n logger.info('destroyed the listener!')\n\n this.readyState = InterceptorReadyState.DISPOSED\n }\n\n private getInstance(): this | undefined {\n const instance = getGlobalSymbol(this.symbol)\n this.logger.info('retrieved global instance:', instance?.constructor?.name)\n return instance\n }\n\n private setInstance(): void {\n setGlobalSymbol(this.symbol, this)\n this.logger.info('set global instance!', this.symbol.description)\n }\n\n private clearInstance(): void {\n deleteGlobalSymbol(this.symbol)\n this.logger.info('cleared global instance!', this.symbol.description)\n }\n}\n","export class InterceptorError extends Error {\n constructor(message?: string) {\n super(message)\n this.name = 'InterceptorError'\n Object.setPrototypeOf(this, InterceptorError.prototype)\n }\n}\n","import { DeferredPromise } from '@open-draft/deferred-promise'\nimport { invariant } from 'outvariant'\nimport { InterceptorError } from './InterceptorError'\n\nexport interface RequestControllerSource {\n passthrough(): void\n respondWith(response: Response): void\n errorWith(reason?: unknown): void\n}\n\nexport class RequestController {\n static PENDING = 0 as const\n static PASSTHROUGH = 1 as const\n static RESPONSE = 2 as const\n static ERROR = 3 as const\n\n public readyState: number\n\n /**\n * A Promise that resolves when this controller handles a request.\n * See `controller.readyState` for more information on the handling result.\n */\n public handled: Promise\n\n constructor(\n protected readonly request: Request,\n protected readonly source: RequestControllerSource\n ) {\n this.readyState = RequestController.PENDING\n this.handled = new DeferredPromise()\n }\n\n get #handled() {\n return this.handled as DeferredPromise\n }\n\n /**\n * Perform this request as-is.\n */\n public async passthrough(): Promise {\n invariant.as(\n InterceptorError,\n this.readyState === RequestController.PENDING,\n 'Failed to passthrough the \"%s %s\" request: the request has already been handled',\n this.request.method,\n this.request.url\n )\n\n this.readyState = RequestController.PASSTHROUGH\n await this.source.passthrough()\n this.#handled.resolve()\n }\n\n /**\n * Respond to this request with the given `Response` instance.\n *\n * @example\n * controller.respondWith(new Response())\n * controller.respondWith(Response.json({ id }))\n * controller.respondWith(Response.error())\n */\n public respondWith(response: Response): void {\n invariant.as(\n InterceptorError,\n this.readyState === RequestController.PENDING,\n 'Failed to respond to the \"%s %s\" request with \"%d %s\": the request has already been handled (%d)',\n this.request.method,\n this.request.url,\n response.status,\n response.statusText || 'OK',\n this.readyState\n )\n\n this.readyState = RequestController.RESPONSE\n this.#handled.resolve()\n\n /**\n * @note Although `source.respondWith()` is potentially asynchronous,\n * do NOT await it for backward-compatibility. Awaiting it will short-circuit\n * the request listener invocation as soon as a listener responds to a request.\n * Ideally, that's what we want, but that's not what we promise the user.\n */\n this.source.respondWith(response)\n }\n\n /**\n * Error this request with the given reason.\n *\n * @example\n * controller.errorWith()\n * controller.errorWith(new Error('Oops!'))\n * controller.errorWith({ message: 'Oops!'})\n */\n public errorWith(reason?: unknown): void {\n invariant.as(\n InterceptorError,\n this.readyState === RequestController.PENDING,\n 'Failed to error the \"%s %s\" request with \"%s\": the request has already been handled (%d)',\n this.request.method,\n this.request.url,\n reason?.toString(),\n this.readyState\n )\n\n this.readyState = RequestController.ERROR\n this.source.errorWith(reason)\n this.#handled.resolve()\n }\n}\n","/**\n * Generate a random ID string to represent a request.\n * @example\n * createRequestId()\n * // \"f774b6c9c600f\"\n */\nexport function createRequestId(): string {\n return Math.random().toString(16).slice(2)\n}\n","/**\n * Returns a boolean indicating whether the given URL string\n * can be parsed into a `URL` instance.\n * A substitute for `URL.canParse()` for Node.js 18.\n */\nexport function canParseUrl(url: string): boolean {\n try {\n new URL(url)\n return true\n } catch (_error) {\n return false\n }\n}\n","/**\n * Returns the value behind the symbol with the given name.\n */\nexport function getValueBySymbol(\n symbolName: string,\n source: object\n): T | undefined {\n const ownSymbols = Object.getOwnPropertySymbols(source)\n\n const symbol = ownSymbols.find((symbol) => {\n return symbol.description === symbolName\n })\n\n if (symbol) {\n return Reflect.get(source, symbol)\n }\n\n return\n}\n","import { canParseUrl } from './canParseUrl'\nimport { getValueBySymbol } from './getValueBySymbol'\n\ninterface UndiciRequestState extends RequestInit {}\n\ninterface FetchRequestInit extends Omit {\n mode?: RequestMode | 'websocket' | 'webtransport'\n duplex?: 'half' | 'full'\n}\n\nexport class FetchRequest extends Request {\n static #resolveProperty(\n input: RequestInfo | URL,\n init: FetchRequestInit = {},\n key: T\n ): FetchRequestInit[T] {\n return init[key] ?? (input instanceof Request ? input[key] : undefined)\n }\n\n /**\n * Check if the given request method is configurable.\n * @see https://fetch.spec.whatwg.org/#methods\n */\n static isConfigurableMethod(method: string): boolean {\n return method !== 'CONNECT' && method !== 'TRACE' && method !== 'TRACK'\n }\n\n static isMethodWithBody(method: string): boolean {\n return (\n method !== 'HEAD' &&\n method !== 'GET' &&\n FetchRequest.isConfigurableMethod(method)\n )\n }\n\n /**\n * Check if the given request `mode` is configurable.\n * @see https://fetch.spec.whatwg.org/#concept-request-mode\n */\n static isConfigurableMode(mode: string): boolean {\n return (\n mode !== 'navigate' && mode !== 'websocket' && mode !== 'webtransport'\n )\n }\n\n constructor(input: URL | RequestInfo, init?: FetchRequestInit) {\n const method = FetchRequest.#resolveProperty(input, init, 'method') || 'GET'\n const safeMethod = FetchRequest.isConfigurableMethod(method)\n ? method\n : 'GET'\n\n const hasExplicitBody = init != null && 'body' in init\n\n /**\n * Only include `body` in the super init when it needs to be overridden.\n * When `input` is a Request and no explicit body is in `init`, let the\n * Request constructor handle body transfer naturally so it properly\n * marks the original request's body as consumed (bodyUsed = true).\n */\n const bodyInit: { body?: BodyInit | null } = !FetchRequest.isMethodWithBody(\n method\n )\n ? { body: undefined }\n : hasExplicitBody\n ? { body: init.body }\n : {}\n\n const mode =\n (FetchRequest.#resolveProperty(input, init, 'mode') as RequestMode) ??\n undefined\n const safeMode = FetchRequest.isConfigurableMode(mode) ? mode : undefined\n\n super(input, {\n ...(init || {}),\n method: safeMethod,\n mode: safeMode,\n // @ts-expect-error Untyped Node.js property.\n duplex:\n init?.duplex ??\n (FetchRequest.isMethodWithBody(method) ? 'half' : undefined),\n ...bodyInit,\n })\n\n if (method !== safeMethod) {\n this.#setInternalProperty('method', method)\n }\n\n if (method === 'CONNECT') {\n const url = new URL(input instanceof Request ? input.url : input)\n\n let authority: string\n\n /**\n * @note Node.js has a bug parsing raw CONNECT requests URLs like\n * \"http://127.0.0.1:1337/localhost:80\". It would treat \"localhost:\" as a protocol.\n */\n if (url.protocol === 'localhost:') {\n authority = url.href\n } else {\n authority = url.pathname.replace(/^\\/+/, '')\n }\n\n /**\n * @note Define \"url\" as a getter because Undici uses their own\n * logic to resolve the \"request.url\" property. Simply reassigning\n * its value doesn't do anything. This is a destructive action\n * but it's safe because \"CONNECT\" requests are forbidden per fetch.\n */\n Object.defineProperty(this, 'url', {\n get: () => authority,\n enumerable: true,\n configurable: true,\n })\n }\n\n if (mode != null && mode !== safeMode) {\n this.#setInternalProperty('mode', mode)\n }\n }\n\n #setInternalProperty(\n key: T,\n value: Request[T]\n ): void {\n const internalState = getValueBySymbol('state', this)\n\n if (internalState) {\n Reflect.set(internalState, key, value)\n } else {\n Object.defineProperty(this, key, {\n value,\n enumerable: true,\n configurable: true,\n writable: false,\n })\n }\n }\n}\n\nexport interface FetchResponseInit extends ResponseInit {\n url?: string\n}\n\ninterface UndiciResponseState {\n aborted: boolean\n rangeRequested: boolean\n timingAllowPassed: boolean\n requestIncludesCredentials: boolean\n type: ResponseType\n status: number\n statusText: string\n timingInfo: unknown\n cacheState: unknown\n headersList: Record>\n urlList: Array\n body?: {\n stream: ReadableStream\n source: unknown\n length: number\n }\n}\n\nconst kStatus = Symbol('kStatus')\nconst kUrl = Symbol('kUrl')\n\nexport class FetchResponse extends Response {\n /**\n * Response status codes for responses that cannot have body.\n * @see https://fetch.spec.whatwg.org/#statuses\n */\n static readonly STATUS_CODES_WITHOUT_BODY = [101, 103, 204, 205, 304]\n\n static readonly STATUS_CODES_WITH_REDIRECT = [301, 302, 303, 307, 308]\n\n static isConfigurableStatusCode(status: number): boolean {\n return status >= 200 && status <= 599\n }\n\n static isRedirectResponse(status: number): boolean {\n return FetchResponse.STATUS_CODES_WITH_REDIRECT.includes(status)\n }\n\n /**\n * Returns a boolean indicating whether the given response status\n * code represents a response that can have a body.\n */\n static isResponseWithBody(status: number): boolean {\n return !FetchResponse.STATUS_CODES_WITHOUT_BODY.includes(status)\n }\n\n static setStatus(status: number, response: Response): void {\n /**\n * @note Undici keeps an internal \"Symbol(state)\" that holds\n * the actual value of response status. Update that in Node.js.\n */\n const internalState = getValueBySymbol(\n 'state',\n response\n )\n\n if (internalState) {\n internalState.status = status\n } else {\n Object.defineProperty(response, 'status', {\n value: status,\n enumerable: true,\n configurable: true,\n writable: false,\n })\n }\n\n Object.defineProperty(response, kStatus, {\n value: status,\n enumerable: false,\n })\n }\n\n static setUrl(url: string | undefined, response: Response): void {\n if (!url || url === 'about:' || !canParseUrl(url)) {\n return\n }\n\n const state = getValueBySymbol('state', response)\n\n if (state) {\n // In Undici, push the URL to the internal list of URLs.\n // This will respect the `response.url` getter logic correctly.\n state.urlList.push(new URL(url))\n } else {\n // In other libraries, redefine the `url` property directly.\n Object.defineProperty(response, 'url', {\n value: url,\n enumerable: true,\n configurable: true,\n writable: false,\n })\n }\n\n Object.defineProperty(response, kUrl, {\n value: url,\n enumerable: false,\n })\n }\n\n /**\n * Parses the given raw HTTP headers into a Fetch API `Headers` instance.\n */\n static parseRawHeaders(rawHeaders: Array): Headers {\n const headers = new Headers()\n\n for (let line = 0; line < rawHeaders.length; line += 2) {\n headers.append(rawHeaders[line], rawHeaders[line + 1])\n }\n\n return headers\n }\n\n /**\n * Safely clones the given `Response`.\n * Coerces response clone exceptions into 500 mocked responses.\n * Handy in the environments that introduce arbitrary response\n * cloning restrictions, like \"101 Switching Protocols\" cloning\n * in \"miniflare\".\n */\n static clone(response: Response): Response {\n try {\n const clone = response.clone()\n return clone\n } catch (error) {\n return Response.json(\n error instanceof Error\n ? {\n name: error.name,\n message: error.message,\n stack: error.stack,\n }\n : {},\n {\n status: 500,\n statusText: 'Unclonable Response',\n }\n )\n }\n }\n\n constructor(body?: BodyInit | null, init: FetchResponseInit = {}) {\n const status = init.status ?? 200\n const safeStatus = FetchResponse.isConfigurableStatusCode(status)\n ? status\n : 200\n const finalBody = FetchResponse.isResponseWithBody(status) ? body : null\n\n super(finalBody, {\n status: safeStatus,\n statusText: init.statusText,\n headers: init.headers,\n })\n\n /**\n * Since Node.js v24, Undici stores the Response state in an inaccessible field \"#state\".\n * Forward the modified status/URL to the cloned response manually.\n * @see https://github.com/nodejs/undici/blob/f734c87280e626c75f59aad55b65eb6a89cef392/lib/web/fetch/response.js#L242\n */\n if (status !== safeStatus) {\n FetchResponse.setStatus(status, this)\n }\n\n FetchResponse.setUrl(init.url, this)\n }\n\n public clone() {\n const clonedResponse = super.clone()\n\n const customStatus = Reflect.get(this, kStatus) as number | undefined\n\n if (customStatus) {\n FetchResponse.setStatus(customStatus, clonedResponse)\n }\n\n const customUrl = Reflect.get(this, kUrl) as string | undefined\n\n if (customUrl) {\n FetchResponse.setUrl(customUrl, clonedResponse)\n }\n\n return clonedResponse\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAaA,MAAa,kCACX;AAEF,SAAgB,gBAAmB,QAA+B;AAChE,QAEE,WAAW,WAAW;;AAI1B,SAAS,gBAAgB,QAAgB,OAAkB;AAEzD,YAAW,UAAU;;AAGvB,SAAgB,mBAAmB,QAAsB;AAEvD,QAAO,WAAW;;AAGpB,IAAY,0EAAL;AACL;AACA;AACA;AACA;AACA;;;AAMF,IAAa,cAAb,MAA6D;CAO3D,YAAY,AAAiBA,QAAgB;EAAhB;AAC3B,OAAK,aAAa,sBAAsB;AAExC,OAAK,UAAU,IAAI,SAAS;AAC5B,OAAK,gBAAgB,EAAE;AACvB,OAAK,SAAS,IAAI,OAAO,OAAO,YAAa;AAI7C,OAAK,QAAQ,gBAAgB,EAAE;AAE/B,OAAK,OAAO,KAAK,kCAAkC;;;;;;CAOrD,AAAU,mBAA4B;AACpC,SAAO;;;;;;CAOT,AAAO,QAAc;EACnB,MAAM,SAAS,KAAK,OAAO,OAAO,QAAQ;AAC1C,SAAO,KAAK,8BAA8B;AAE1C,MAAI,KAAK,eAAe,sBAAsB,SAAS;AACrD,UAAO,KAAK,+BAA+B;AAC3C;;AAKF,MAAI,CAFgB,KAAK,kBAAkB,EAEzB;AAChB,UAAO,KAAK,yDAAyD;AACrE;;AAGF,OAAK,aAAa,sBAAsB;EAKxC,MAAM,kBAAkB,KAAK,aAAa;AAE1C,MAAI,iBAAiB;AACnB,UAAO,KAAK,uCAAuC;AAGnD,QAAK,MAAM,OAAO,aAAa;AAC7B,WAAO,KAAK,gCAA8B,MAAM;AAIhD,oBAAgB,QAAQ,YAAY,OAA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,EAAE,EAAE;EAChE,MAAM,SAAS,KAAK,UAAU;EAC9B,MAAM,aAAa,cAAc,yBAAyB,OAAO,GAC7D,SACA;EACJ,MAAM,YAAY,cAAc,mBAAmB,OAAO,GAAG,OAAO;AAEpE,QAAM,WAAW;GACf,QAAQ;GACR,YAAY,KAAK;GACjB,SAAS,KAAK;GACf,CAAC;;;;;;AAOF,MAAI,WAAW,WACb,eAAc,UAAU,QAAQ,KAAK;AAGvC,gBAAc,OAAO,KAAK,KAAK,KAAK;;CAGtC,AAAO,QAAQ;EACb,MAAM,iBAAiB,MAAM,OAAO;EAEpC,MAAM,eAAe,QAAQ,IAAI,MAAM,QAAQ;AAE/C,MAAI,aACF,eAAc,UAAU,cAAc,eAAe;EAGvD,MAAM,YAAY,QAAQ,IAAI,MAAM,KAAK;AAEzC,MAAI,UACF,eAAc,OAAO,WAAW,eAAe;AAGjD,SAAO"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/fetchUtils-umV5xXBy.cjs b/node_modules/@mswjs/interceptors/lib/node/fetchUtils-umV5xXBy.cjs new file mode 100644 index 0000000000000000000000000000000000000000..08675a27102d00d015a1ca1730a4e69ce40a9001 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/fetchUtils-umV5xXBy.cjs @@ -0,0 +1,546 @@ +const require_chunk = require('./chunk-CbDLau6x.cjs'); +let _open_draft_logger = require("@open-draft/logger"); +let strict_event_emitter = require("strict-event-emitter"); +let _open_draft_deferred_promise = require("@open-draft/deferred-promise"); +let outvariant = require("outvariant"); + +//#region src/Interceptor.ts +/** +* Request header name to detect when a single request +* is being handled by nested interceptors (XHR -> ClientRequest). +* Obscure by design to prevent collisions with user-defined headers. +* Ideally, come up with the Interceptor-level mechanism for this. +* @see https://github.com/mswjs/interceptors/issues/378 +*/ +const INTERNAL_REQUEST_ID_HEADER_NAME = "x-interceptors-internal-request-id"; +function getGlobalSymbol(symbol) { + return globalThis[symbol] || void 0; +} +function setGlobalSymbol(symbol, value) { + globalThis[symbol] = value; +} +function deleteGlobalSymbol(symbol) { + delete globalThis[symbol]; +} +let InterceptorReadyState = /* @__PURE__ */ function(InterceptorReadyState$1) { + InterceptorReadyState$1["INACTIVE"] = "INACTIVE"; + InterceptorReadyState$1["APPLYING"] = "APPLYING"; + InterceptorReadyState$1["APPLIED"] = "APPLIED"; + InterceptorReadyState$1["DISPOSING"] = "DISPOSING"; + InterceptorReadyState$1["DISPOSED"] = "DISPOSED"; + return InterceptorReadyState$1; +}({}); +var Interceptor = class { + constructor(symbol) { + this.symbol = symbol; + this.readyState = InterceptorReadyState.INACTIVE; + this.emitter = new strict_event_emitter.Emitter(); + this.subscriptions = []; + this.logger = new _open_draft_logger.Logger(symbol.description); + this.emitter.setMaxListeners(0); + this.logger.info("constructing the interceptor..."); + } + /** + * Determine if this interceptor can be applied + * in the current environment. + */ + checkEnvironment() { + return true; + } + /** + * Apply this interceptor to the current process. + * Returns an already running interceptor instance if it's present. + */ + apply() { + const logger = this.logger.extend("apply"); + logger.info("applying the interceptor..."); + if (this.readyState === InterceptorReadyState.APPLIED) { + logger.info("intercepted already applied!"); + return; + } + if (!this.checkEnvironment()) { + logger.info("the interceptor cannot be applied in this environment!"); + return; + } + this.readyState = InterceptorReadyState.APPLYING; + const runningInstance = this.getInstance(); + if (runningInstance) { + logger.info("found a running instance, reusing..."); + this.on = (event, listener) => { + logger.info("proxying the \"%s\" listener", event); + runningInstance.emitter.addListener(event, listener); + this.subscriptions.push(() => { + runningInstance.emitter.removeListener(event, listener); + logger.info("removed proxied \"%s\" listener!", event); + }); + return this; + }; + this.readyState = InterceptorReadyState.APPLIED; + return; + } + logger.info("no running instance found, setting up a new instance..."); + this.setup(); + this.setInstance(); + this.readyState = InterceptorReadyState.APPLIED; + } + /** + * Setup the module augments and stubs necessary for this interceptor. + * This method is not run if there's a running interceptor instance + * to prevent instantiating an interceptor multiple times. + */ + setup() {} + /** + * Listen to the interceptor's public events. + */ + on(event, listener) { + const logger = this.logger.extend("on"); + if (this.readyState === InterceptorReadyState.DISPOSING || this.readyState === InterceptorReadyState.DISPOSED) { + logger.info("cannot listen to events, already disposed!"); + return this; + } + logger.info("adding \"%s\" event listener:", event, listener); + this.emitter.on(event, listener); + return this; + } + once(event, listener) { + this.emitter.once(event, listener); + return this; + } + off(event, listener) { + this.emitter.off(event, listener); + return this; + } + removeAllListeners(event) { + this.emitter.removeAllListeners(event); + return this; + } + /** + * Disposes of any side-effects this interceptor has introduced. + */ + dispose() { + const logger = this.logger.extend("dispose"); + if (this.readyState === InterceptorReadyState.DISPOSED) { + logger.info("cannot dispose, already disposed!"); + return; + } + logger.info("disposing the interceptor..."); + this.readyState = InterceptorReadyState.DISPOSING; + if (!this.getInstance()) { + logger.info("no interceptors running, skipping dispose..."); + return; + } + this.clearInstance(); + logger.info("global symbol deleted:", getGlobalSymbol(this.symbol)); + if (this.subscriptions.length > 0) { + logger.info("disposing of %d subscriptions...", this.subscriptions.length); + for (const dispose of this.subscriptions) dispose(); + this.subscriptions = []; + logger.info("disposed of all subscriptions!", this.subscriptions.length); + } + this.emitter.removeAllListeners(); + logger.info("destroyed the listener!"); + this.readyState = InterceptorReadyState.DISPOSED; + } + getInstance() { + const instance = getGlobalSymbol(this.symbol); + this.logger.info("retrieved global instance:", instance?.constructor?.name); + return instance; + } + setInstance() { + setGlobalSymbol(this.symbol, this); + this.logger.info("set global instance!", this.symbol.description); + } + clearInstance() { + deleteGlobalSymbol(this.symbol); + this.logger.info("cleared global instance!", this.symbol.description); + } +}; + +//#endregion +//#region src/InterceptorError.ts +var InterceptorError = class InterceptorError extends Error { + constructor(message) { + super(message); + this.name = "InterceptorError"; + Object.setPrototypeOf(this, InterceptorError.prototype); + } +}; + +//#endregion +//#region src/RequestController.ts +var RequestController = class RequestController { + static { + this.PENDING = 0; + } + static { + this.PASSTHROUGH = 1; + } + static { + this.RESPONSE = 2; + } + static { + this.ERROR = 3; + } + constructor(request, source) { + this.request = request; + this.source = source; + this.readyState = RequestController.PENDING; + this.handled = new _open_draft_deferred_promise.DeferredPromise(); + } + get #handled() { + return this.handled; + } + /** + * Perform this request as-is. + */ + async passthrough() { + outvariant.invariant.as(InterceptorError, this.readyState === RequestController.PENDING, "Failed to passthrough the \"%s %s\" request: the request has already been handled", this.request.method, this.request.url); + this.readyState = RequestController.PASSTHROUGH; + await this.source.passthrough(); + this.#handled.resolve(); + } + /** + * Respond to this request with the given `Response` instance. + * + * @example + * controller.respondWith(new Response()) + * controller.respondWith(Response.json({ id })) + * controller.respondWith(Response.error()) + */ + respondWith(response) { + outvariant.invariant.as(InterceptorError, this.readyState === RequestController.PENDING, "Failed to respond to the \"%s %s\" request with \"%d %s\": the request has already been handled (%d)", this.request.method, this.request.url, response.status, response.statusText || "OK", this.readyState); + this.readyState = RequestController.RESPONSE; + this.#handled.resolve(); + /** + * @note Although `source.respondWith()` is potentially asynchronous, + * do NOT await it for backward-compatibility. Awaiting it will short-circuit + * the request listener invocation as soon as a listener responds to a request. + * Ideally, that's what we want, but that's not what we promise the user. + */ + this.source.respondWith(response); + } + /** + * Error this request with the given reason. + * + * @example + * controller.errorWith() + * controller.errorWith(new Error('Oops!')) + * controller.errorWith({ message: 'Oops!'}) + */ + errorWith(reason) { + outvariant.invariant.as(InterceptorError, this.readyState === RequestController.PENDING, "Failed to error the \"%s %s\" request with \"%s\": the request has already been handled (%d)", this.request.method, this.request.url, reason?.toString(), this.readyState); + this.readyState = RequestController.ERROR; + this.source.errorWith(reason); + this.#handled.resolve(); + } +}; + +//#endregion +//#region src/createRequestId.ts +/** +* Generate a random ID string to represent a request. +* @example +* createRequestId() +* // "f774b6c9c600f" +*/ +function createRequestId() { + return Math.random().toString(16).slice(2); +} + +//#endregion +//#region src/utils/canParseUrl.ts +/** +* Returns a boolean indicating whether the given URL string +* can be parsed into a `URL` instance. +* A substitute for `URL.canParse()` for Node.js 18. +*/ +function canParseUrl(url) { + try { + new URL(url); + return true; + } catch (_error) { + return false; + } +} + +//#endregion +//#region src/utils/getValueBySymbol.ts +/** +* Returns the value behind the symbol with the given name. +*/ +function getValueBySymbol(symbolName, source) { + const symbol = Object.getOwnPropertySymbols(source).find((symbol$1) => { + return symbol$1.description === symbolName; + }); + if (symbol) return Reflect.get(source, symbol); +} + +//#endregion +//#region src/utils/fetchUtils.ts +var FetchRequest = class FetchRequest extends Request { + static #resolveProperty(input, init = {}, key) { + return init[key] ?? (input instanceof Request ? input[key] : void 0); + } + /** + * Check if the given request method is configurable. + * @see https://fetch.spec.whatwg.org/#methods + */ + static isConfigurableMethod(method) { + return method !== "CONNECT" && method !== "TRACE" && method !== "TRACK"; + } + static isMethodWithBody(method) { + return method !== "HEAD" && method !== "GET" && FetchRequest.isConfigurableMethod(method); + } + /** + * Check if the given request `mode` is configurable. + * @see https://fetch.spec.whatwg.org/#concept-request-mode + */ + static isConfigurableMode(mode) { + return mode !== "navigate" && mode !== "websocket" && mode !== "webtransport"; + } + constructor(input, init) { + const method = FetchRequest.#resolveProperty(input, init, "method") || "GET"; + const safeMethod = FetchRequest.isConfigurableMethod(method) ? method : "GET"; + const hasExplicitBody = init != null && "body" in init; + /** + * Only include `body` in the super init when it needs to be overridden. + * When `input` is a Request and no explicit body is in `init`, let the + * Request constructor handle body transfer naturally so it properly + * marks the original request's body as consumed (bodyUsed = true). + */ + const bodyInit = !FetchRequest.isMethodWithBody(method) ? { body: void 0 } : hasExplicitBody ? { body: init.body } : {}; + const mode = FetchRequest.#resolveProperty(input, init, "mode") ?? void 0; + const safeMode = FetchRequest.isConfigurableMode(mode) ? mode : void 0; + super(input, { + ...init || {}, + method: safeMethod, + mode: safeMode, + duplex: init?.duplex ?? (FetchRequest.isMethodWithBody(method) ? "half" : void 0), + ...bodyInit + }); + if (method !== safeMethod) this.#setInternalProperty("method", method); + if (method === "CONNECT") { + const url = new URL(input instanceof Request ? input.url : input); + let authority; + /** + * @note Node.js has a bug parsing raw CONNECT requests URLs like + * "http://127.0.0.1:1337/localhost:80". It would treat "localhost:" as a protocol. + */ + if (url.protocol === "localhost:") authority = url.href; + else authority = url.pathname.replace(/^\/+/, ""); + /** + * @note Define "url" as a getter because Undici uses their own + * logic to resolve the "request.url" property. Simply reassigning + * its value doesn't do anything. This is a destructive action + * but it's safe because "CONNECT" requests are forbidden per fetch. + */ + Object.defineProperty(this, "url", { + get: () => authority, + enumerable: true, + configurable: true + }); + } + if (mode != null && mode !== safeMode) this.#setInternalProperty("mode", mode); + } + #setInternalProperty(key, value) { + const internalState = getValueBySymbol("state", this); + if (internalState) Reflect.set(internalState, key, value); + else Object.defineProperty(this, key, { + value, + enumerable: true, + configurable: true, + writable: false + }); + } +}; +const kStatus = Symbol("kStatus"); +const kUrl = Symbol("kUrl"); +var FetchResponse = class FetchResponse extends Response { + static { + this.STATUS_CODES_WITHOUT_BODY = [ + 101, + 103, + 204, + 205, + 304 + ]; + } + static { + this.STATUS_CODES_WITH_REDIRECT = [ + 301, + 302, + 303, + 307, + 308 + ]; + } + static isConfigurableStatusCode(status) { + return status >= 200 && status <= 599; + } + static isRedirectResponse(status) { + return FetchResponse.STATUS_CODES_WITH_REDIRECT.includes(status); + } + /** + * Returns a boolean indicating whether the given response status + * code represents a response that can have a body. + */ + static isResponseWithBody(status) { + return !FetchResponse.STATUS_CODES_WITHOUT_BODY.includes(status); + } + static setStatus(status, response) { + /** + * @note Undici keeps an internal "Symbol(state)" that holds + * the actual value of response status. Update that in Node.js. + */ + const internalState = getValueBySymbol("state", response); + if (internalState) internalState.status = status; + else Object.defineProperty(response, "status", { + value: status, + enumerable: true, + configurable: true, + writable: false + }); + Object.defineProperty(response, kStatus, { + value: status, + enumerable: false + }); + } + static setUrl(url, response) { + if (!url || url === "about:" || !canParseUrl(url)) return; + const state = getValueBySymbol("state", response); + if (state) state.urlList.push(new URL(url)); + else Object.defineProperty(response, "url", { + value: url, + enumerable: true, + configurable: true, + writable: false + }); + Object.defineProperty(response, kUrl, { + value: url, + enumerable: false + }); + } + /** + * Parses the given raw HTTP headers into a Fetch API `Headers` instance. + */ + static parseRawHeaders(rawHeaders) { + const headers = new Headers(); + for (let line = 0; line < rawHeaders.length; line += 2) headers.append(rawHeaders[line], rawHeaders[line + 1]); + return headers; + } + /** + * Safely clones the given `Response`. + * Coerces response clone exceptions into 500 mocked responses. + * Handy in the environments that introduce arbitrary response + * cloning restrictions, like "101 Switching Protocols" cloning + * in "miniflare". + */ + static clone(response) { + try { + return response.clone(); + } catch (error) { + return Response.json(error instanceof Error ? { + name: error.name, + message: error.message, + stack: error.stack + } : {}, { + status: 500, + statusText: "Unclonable Response" + }); + } + } + constructor(body, init = {}) { + const status = init.status ?? 200; + const safeStatus = FetchResponse.isConfigurableStatusCode(status) ? status : 200; + const finalBody = FetchResponse.isResponseWithBody(status) ? body : null; + super(finalBody, { + status: safeStatus, + statusText: init.statusText, + headers: init.headers + }); + /** + * Since Node.js v24, Undici stores the Response state in an inaccessible field "#state". + * Forward the modified status/URL to the cloned response manually. + * @see https://github.com/nodejs/undici/blob/f734c87280e626c75f59aad55b65eb6a89cef392/lib/web/fetch/response.js#L242 + */ + if (status !== safeStatus) FetchResponse.setStatus(status, this); + FetchResponse.setUrl(init.url, this); + } + clone() { + const clonedResponse = super.clone(); + const customStatus = Reflect.get(this, kStatus); + if (customStatus) FetchResponse.setStatus(customStatus, clonedResponse); + const customUrl = Reflect.get(this, kUrl); + if (customUrl) FetchResponse.setUrl(customUrl, clonedResponse); + return clonedResponse; + } +}; + +//#endregion +Object.defineProperty(exports, 'FetchRequest', { + enumerable: true, + get: function () { + return FetchRequest; + } +}); +Object.defineProperty(exports, 'FetchResponse', { + enumerable: true, + get: function () { + return FetchResponse; + } +}); +Object.defineProperty(exports, 'INTERNAL_REQUEST_ID_HEADER_NAME', { + enumerable: true, + get: function () { + return INTERNAL_REQUEST_ID_HEADER_NAME; + } +}); +Object.defineProperty(exports, 'Interceptor', { + enumerable: true, + get: function () { + return Interceptor; + } +}); +Object.defineProperty(exports, 'InterceptorError', { + enumerable: true, + get: function () { + return InterceptorError; + } +}); +Object.defineProperty(exports, 'InterceptorReadyState', { + enumerable: true, + get: function () { + return InterceptorReadyState; + } +}); +Object.defineProperty(exports, 'RequestController', { + enumerable: true, + get: function () { + return RequestController; + } +}); +Object.defineProperty(exports, 'canParseUrl', { + enumerable: true, + get: function () { + return canParseUrl; + } +}); +Object.defineProperty(exports, 'createRequestId', { + enumerable: true, + get: function () { + return createRequestId; + } +}); +Object.defineProperty(exports, 'deleteGlobalSymbol', { + enumerable: true, + get: function () { + return deleteGlobalSymbol; + } +}); +Object.defineProperty(exports, 'getGlobalSymbol', { + enumerable: true, + get: function () { + return getGlobalSymbol; + } +}); +//# sourceMappingURL=fetchUtils-umV5xXBy.cjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/fetchUtils-umV5xXBy.cjs.map b/node_modules/@mswjs/interceptors/lib/node/fetchUtils-umV5xXBy.cjs.map new file mode 100644 index 0000000000000000000000000000000000000000..7ac0b333f88dc9b4acf5b5cd11b0158ead47d8b0 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/fetchUtils-umV5xXBy.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"fetchUtils-umV5xXBy.cjs","names":["symbol: symbol","Emitter","Logger","request: Request","source: RequestControllerSource","DeferredPromise","#handled","symbol","#resolveProperty","bodyInit: { body?: BodyInit | null }","#setInternalProperty","authority: string"],"sources":["../../src/Interceptor.ts","../../src/InterceptorError.ts","../../src/RequestController.ts","../../src/createRequestId.ts","../../src/utils/canParseUrl.ts","../../src/utils/getValueBySymbol.ts","../../src/utils/fetchUtils.ts"],"sourcesContent":["import { Logger } from '@open-draft/logger'\nimport { Emitter, Listener } from 'strict-event-emitter'\n\nexport type InterceptorEventMap = Record\nexport type InterceptorSubscription = () => void\n\n/**\n * Request header name to detect when a single request\n * is being handled by nested interceptors (XHR -> ClientRequest).\n * Obscure by design to prevent collisions with user-defined headers.\n * Ideally, come up with the Interceptor-level mechanism for this.\n * @see https://github.com/mswjs/interceptors/issues/378\n */\nexport const INTERNAL_REQUEST_ID_HEADER_NAME =\n 'x-interceptors-internal-request-id'\n\nexport function getGlobalSymbol(symbol: Symbol): V | undefined {\n return (\n // @ts-ignore https://github.com/Microsoft/TypeScript/issues/24587\n globalThis[symbol] || undefined\n )\n}\n\nfunction setGlobalSymbol(symbol: Symbol, value: any): void {\n // @ts-ignore\n globalThis[symbol] = value\n}\n\nexport function deleteGlobalSymbol(symbol: Symbol): void {\n // @ts-ignore\n delete globalThis[symbol]\n}\n\nexport enum InterceptorReadyState {\n INACTIVE = 'INACTIVE',\n APPLYING = 'APPLYING',\n APPLIED = 'APPLIED',\n DISPOSING = 'DISPOSING',\n DISPOSED = 'DISPOSED',\n}\n\nexport type ExtractEventNames> =\n Events extends Record ? EventName : never\n\nexport class Interceptor {\n protected emitter: Emitter\n protected subscriptions: Array\n protected logger: Logger\n\n public readyState: InterceptorReadyState\n\n constructor(private readonly symbol: symbol) {\n this.readyState = InterceptorReadyState.INACTIVE\n\n this.emitter = new Emitter()\n this.subscriptions = []\n this.logger = new Logger(symbol.description!)\n\n // Do not limit the maximum number of listeners\n // so not to limit the maximum amount of parallel events emitted.\n this.emitter.setMaxListeners(0)\n\n this.logger.info('constructing the interceptor...')\n }\n\n /**\n * Determine if this interceptor can be applied\n * in the current environment.\n */\n protected checkEnvironment(): boolean {\n return true\n }\n\n /**\n * Apply this interceptor to the current process.\n * Returns an already running interceptor instance if it's present.\n */\n public apply(): void {\n const logger = this.logger.extend('apply')\n logger.info('applying the interceptor...')\n\n if (this.readyState === InterceptorReadyState.APPLIED) {\n logger.info('intercepted already applied!')\n return\n }\n\n const shouldApply = this.checkEnvironment()\n\n if (!shouldApply) {\n logger.info('the interceptor cannot be applied in this environment!')\n return\n }\n\n this.readyState = InterceptorReadyState.APPLYING\n\n // Whenever applying a new interceptor, check if it hasn't been applied already.\n // This enables to apply the same interceptor multiple times, for example from a different\n // interceptor, only proxying events but keeping the stubs in a single place.\n const runningInstance = this.getInstance()\n\n if (runningInstance) {\n logger.info('found a running instance, reusing...')\n\n // Proxy any listeners you set on this instance to the running instance.\n this.on = (event, listener) => {\n logger.info('proxying the \"%s\" listener', event)\n\n // Add listeners to the running instance so they appear\n // at the top of the event listeners list and are executed first.\n runningInstance.emitter.addListener(event, listener)\n\n // Ensure that once this interceptor instance is disposed,\n // it removes all listeners it has appended to the running interceptor instance.\n this.subscriptions.push(() => {\n runningInstance.emitter.removeListener(event, listener)\n logger.info('removed proxied \"%s\" listener!', event)\n })\n\n return this\n }\n\n this.readyState = InterceptorReadyState.APPLIED\n\n return\n }\n\n logger.info('no running instance found, setting up a new instance...')\n\n // Setup the interceptor.\n this.setup()\n\n // Store the newly applied interceptor instance globally.\n this.setInstance()\n\n this.readyState = InterceptorReadyState.APPLIED\n }\n\n /**\n * Setup the module augments and stubs necessary for this interceptor.\n * This method is not run if there's a running interceptor instance\n * to prevent instantiating an interceptor multiple times.\n */\n protected setup(): void {}\n\n /**\n * Listen to the interceptor's public events.\n */\n public on>(\n event: EventName,\n listener: Listener\n ): this {\n const logger = this.logger.extend('on')\n\n if (\n this.readyState === InterceptorReadyState.DISPOSING ||\n this.readyState === InterceptorReadyState.DISPOSED\n ) {\n logger.info('cannot listen to events, already disposed!')\n return this\n }\n\n logger.info('adding \"%s\" event listener:', event, listener)\n\n this.emitter.on(event, listener)\n return this\n }\n\n public once>(\n event: EventName,\n listener: Listener\n ): this {\n this.emitter.once(event, listener)\n return this\n }\n\n public off>(\n event: EventName,\n listener: Listener\n ): this {\n this.emitter.off(event, listener)\n return this\n }\n\n public removeAllListeners>(\n event?: EventName\n ): this {\n this.emitter.removeAllListeners(event)\n return this\n }\n\n /**\n * Disposes of any side-effects this interceptor has introduced.\n */\n public dispose(): void {\n const logger = this.logger.extend('dispose')\n\n if (this.readyState === InterceptorReadyState.DISPOSED) {\n logger.info('cannot dispose, already disposed!')\n return\n }\n\n logger.info('disposing the interceptor...')\n this.readyState = InterceptorReadyState.DISPOSING\n\n if (!this.getInstance()) {\n logger.info('no interceptors running, skipping dispose...')\n return\n }\n\n // Delete the global symbol as soon as possible,\n // indicating that the interceptor is no longer running.\n this.clearInstance()\n\n logger.info('global symbol deleted:', getGlobalSymbol(this.symbol))\n\n if (this.subscriptions.length > 0) {\n logger.info('disposing of %d subscriptions...', this.subscriptions.length)\n\n for (const dispose of this.subscriptions) {\n dispose()\n }\n\n this.subscriptions = []\n\n logger.info('disposed of all subscriptions!', this.subscriptions.length)\n }\n\n this.emitter.removeAllListeners()\n logger.info('destroyed the listener!')\n\n this.readyState = InterceptorReadyState.DISPOSED\n }\n\n private getInstance(): this | undefined {\n const instance = getGlobalSymbol(this.symbol)\n this.logger.info('retrieved global instance:', instance?.constructor?.name)\n return instance\n }\n\n private setInstance(): void {\n setGlobalSymbol(this.symbol, this)\n this.logger.info('set global instance!', this.symbol.description)\n }\n\n private clearInstance(): void {\n deleteGlobalSymbol(this.symbol)\n this.logger.info('cleared global instance!', this.symbol.description)\n }\n}\n","export class InterceptorError extends Error {\n constructor(message?: string) {\n super(message)\n this.name = 'InterceptorError'\n Object.setPrototypeOf(this, InterceptorError.prototype)\n }\n}\n","import { DeferredPromise } from '@open-draft/deferred-promise'\nimport { invariant } from 'outvariant'\nimport { InterceptorError } from './InterceptorError'\n\nexport interface RequestControllerSource {\n passthrough(): void\n respondWith(response: Response): void\n errorWith(reason?: unknown): void\n}\n\nexport class RequestController {\n static PENDING = 0 as const\n static PASSTHROUGH = 1 as const\n static RESPONSE = 2 as const\n static ERROR = 3 as const\n\n public readyState: number\n\n /**\n * A Promise that resolves when this controller handles a request.\n * See `controller.readyState` for more information on the handling result.\n */\n public handled: Promise\n\n constructor(\n protected readonly request: Request,\n protected readonly source: RequestControllerSource\n ) {\n this.readyState = RequestController.PENDING\n this.handled = new DeferredPromise()\n }\n\n get #handled() {\n return this.handled as DeferredPromise\n }\n\n /**\n * Perform this request as-is.\n */\n public async passthrough(): Promise {\n invariant.as(\n InterceptorError,\n this.readyState === RequestController.PENDING,\n 'Failed to passthrough the \"%s %s\" request: the request has already been handled',\n this.request.method,\n this.request.url\n )\n\n this.readyState = RequestController.PASSTHROUGH\n await this.source.passthrough()\n this.#handled.resolve()\n }\n\n /**\n * Respond to this request with the given `Response` instance.\n *\n * @example\n * controller.respondWith(new Response())\n * controller.respondWith(Response.json({ id }))\n * controller.respondWith(Response.error())\n */\n public respondWith(response: Response): void {\n invariant.as(\n InterceptorError,\n this.readyState === RequestController.PENDING,\n 'Failed to respond to the \"%s %s\" request with \"%d %s\": the request has already been handled (%d)',\n this.request.method,\n this.request.url,\n response.status,\n response.statusText || 'OK',\n this.readyState\n )\n\n this.readyState = RequestController.RESPONSE\n this.#handled.resolve()\n\n /**\n * @note Although `source.respondWith()` is potentially asynchronous,\n * do NOT await it for backward-compatibility. Awaiting it will short-circuit\n * the request listener invocation as soon as a listener responds to a request.\n * Ideally, that's what we want, but that's not what we promise the user.\n */\n this.source.respondWith(response)\n }\n\n /**\n * Error this request with the given reason.\n *\n * @example\n * controller.errorWith()\n * controller.errorWith(new Error('Oops!'))\n * controller.errorWith({ message: 'Oops!'})\n */\n public errorWith(reason?: unknown): void {\n invariant.as(\n InterceptorError,\n this.readyState === RequestController.PENDING,\n 'Failed to error the \"%s %s\" request with \"%s\": the request has already been handled (%d)',\n this.request.method,\n this.request.url,\n reason?.toString(),\n this.readyState\n )\n\n this.readyState = RequestController.ERROR\n this.source.errorWith(reason)\n this.#handled.resolve()\n }\n}\n","/**\n * Generate a random ID string to represent a request.\n * @example\n * createRequestId()\n * // \"f774b6c9c600f\"\n */\nexport function createRequestId(): string {\n return Math.random().toString(16).slice(2)\n}\n","/**\n * Returns a boolean indicating whether the given URL string\n * can be parsed into a `URL` instance.\n * A substitute for `URL.canParse()` for Node.js 18.\n */\nexport function canParseUrl(url: string): boolean {\n try {\n new URL(url)\n return true\n } catch (_error) {\n return false\n }\n}\n","/**\n * Returns the value behind the symbol with the given name.\n */\nexport function getValueBySymbol(\n symbolName: string,\n source: object\n): T | undefined {\n const ownSymbols = Object.getOwnPropertySymbols(source)\n\n const symbol = ownSymbols.find((symbol) => {\n return symbol.description === symbolName\n })\n\n if (symbol) {\n return Reflect.get(source, symbol)\n }\n\n return\n}\n","import { canParseUrl } from './canParseUrl'\nimport { getValueBySymbol } from './getValueBySymbol'\n\ninterface UndiciRequestState extends RequestInit {}\n\ninterface FetchRequestInit extends Omit {\n mode?: RequestMode | 'websocket' | 'webtransport'\n duplex?: 'half' | 'full'\n}\n\nexport class FetchRequest extends Request {\n static #resolveProperty(\n input: RequestInfo | URL,\n init: FetchRequestInit = {},\n key: T\n ): FetchRequestInit[T] {\n return init[key] ?? (input instanceof Request ? input[key] : undefined)\n }\n\n /**\n * Check if the given request method is configurable.\n * @see https://fetch.spec.whatwg.org/#methods\n */\n static isConfigurableMethod(method: string): boolean {\n return method !== 'CONNECT' && method !== 'TRACE' && method !== 'TRACK'\n }\n\n static isMethodWithBody(method: string): boolean {\n return (\n method !== 'HEAD' &&\n method !== 'GET' &&\n FetchRequest.isConfigurableMethod(method)\n )\n }\n\n /**\n * Check if the given request `mode` is configurable.\n * @see https://fetch.spec.whatwg.org/#concept-request-mode\n */\n static isConfigurableMode(mode: string): boolean {\n return (\n mode !== 'navigate' && mode !== 'websocket' && mode !== 'webtransport'\n )\n }\n\n constructor(input: URL | RequestInfo, init?: FetchRequestInit) {\n const method = FetchRequest.#resolveProperty(input, init, 'method') || 'GET'\n const safeMethod = FetchRequest.isConfigurableMethod(method)\n ? method\n : 'GET'\n\n const hasExplicitBody = init != null && 'body' in init\n\n /**\n * Only include `body` in the super init when it needs to be overridden.\n * When `input` is a Request and no explicit body is in `init`, let the\n * Request constructor handle body transfer naturally so it properly\n * marks the original request's body as consumed (bodyUsed = true).\n */\n const bodyInit: { body?: BodyInit | null } = !FetchRequest.isMethodWithBody(\n method\n )\n ? { body: undefined }\n : hasExplicitBody\n ? { body: init.body }\n : {}\n\n const mode =\n (FetchRequest.#resolveProperty(input, init, 'mode') as RequestMode) ??\n undefined\n const safeMode = FetchRequest.isConfigurableMode(mode) ? mode : undefined\n\n super(input, {\n ...(init || {}),\n method: safeMethod,\n mode: safeMode,\n // @ts-expect-error Untyped Node.js property.\n duplex:\n init?.duplex ??\n (FetchRequest.isMethodWithBody(method) ? 'half' : undefined),\n ...bodyInit,\n })\n\n if (method !== safeMethod) {\n this.#setInternalProperty('method', method)\n }\n\n if (method === 'CONNECT') {\n const url = new URL(input instanceof Request ? input.url : input)\n\n let authority: string\n\n /**\n * @note Node.js has a bug parsing raw CONNECT requests URLs like\n * \"http://127.0.0.1:1337/localhost:80\". It would treat \"localhost:\" as a protocol.\n */\n if (url.protocol === 'localhost:') {\n authority = url.href\n } else {\n authority = url.pathname.replace(/^\\/+/, '')\n }\n\n /**\n * @note Define \"url\" as a getter because Undici uses their own\n * logic to resolve the \"request.url\" property. Simply reassigning\n * its value doesn't do anything. This is a destructive action\n * but it's safe because \"CONNECT\" requests are forbidden per fetch.\n */\n Object.defineProperty(this, 'url', {\n get: () => authority,\n enumerable: true,\n configurable: true,\n })\n }\n\n if (mode != null && mode !== safeMode) {\n this.#setInternalProperty('mode', mode)\n }\n }\n\n #setInternalProperty(\n key: T,\n value: Request[T]\n ): void {\n const internalState = getValueBySymbol('state', this)\n\n if (internalState) {\n Reflect.set(internalState, key, value)\n } else {\n Object.defineProperty(this, key, {\n value,\n enumerable: true,\n configurable: true,\n writable: false,\n })\n }\n }\n}\n\nexport interface FetchResponseInit extends ResponseInit {\n url?: string\n}\n\ninterface UndiciResponseState {\n aborted: boolean\n rangeRequested: boolean\n timingAllowPassed: boolean\n requestIncludesCredentials: boolean\n type: ResponseType\n status: number\n statusText: string\n timingInfo: unknown\n cacheState: unknown\n headersList: Record>\n urlList: Array\n body?: {\n stream: ReadableStream\n source: unknown\n length: number\n }\n}\n\nconst kStatus = Symbol('kStatus')\nconst kUrl = Symbol('kUrl')\n\nexport class FetchResponse extends Response {\n /**\n * Response status codes for responses that cannot have body.\n * @see https://fetch.spec.whatwg.org/#statuses\n */\n static readonly STATUS_CODES_WITHOUT_BODY = [101, 103, 204, 205, 304]\n\n static readonly STATUS_CODES_WITH_REDIRECT = [301, 302, 303, 307, 308]\n\n static isConfigurableStatusCode(status: number): boolean {\n return status >= 200 && status <= 599\n }\n\n static isRedirectResponse(status: number): boolean {\n return FetchResponse.STATUS_CODES_WITH_REDIRECT.includes(status)\n }\n\n /**\n * Returns a boolean indicating whether the given response status\n * code represents a response that can have a body.\n */\n static isResponseWithBody(status: number): boolean {\n return !FetchResponse.STATUS_CODES_WITHOUT_BODY.includes(status)\n }\n\n static setStatus(status: number, response: Response): void {\n /**\n * @note Undici keeps an internal \"Symbol(state)\" that holds\n * the actual value of response status. Update that in Node.js.\n */\n const internalState = getValueBySymbol(\n 'state',\n response\n )\n\n if (internalState) {\n internalState.status = status\n } else {\n Object.defineProperty(response, 'status', {\n value: status,\n enumerable: true,\n configurable: true,\n writable: false,\n })\n }\n\n Object.defineProperty(response, kStatus, {\n value: status,\n enumerable: false,\n })\n }\n\n static setUrl(url: string | undefined, response: Response): void {\n if (!url || url === 'about:' || !canParseUrl(url)) {\n return\n }\n\n const state = getValueBySymbol('state', response)\n\n if (state) {\n // In Undici, push the URL to the internal list of URLs.\n // This will respect the `response.url` getter logic correctly.\n state.urlList.push(new URL(url))\n } else {\n // In other libraries, redefine the `url` property directly.\n Object.defineProperty(response, 'url', {\n value: url,\n enumerable: true,\n configurable: true,\n writable: false,\n })\n }\n\n Object.defineProperty(response, kUrl, {\n value: url,\n enumerable: false,\n })\n }\n\n /**\n * Parses the given raw HTTP headers into a Fetch API `Headers` instance.\n */\n static parseRawHeaders(rawHeaders: Array): Headers {\n const headers = new Headers()\n\n for (let line = 0; line < rawHeaders.length; line += 2) {\n headers.append(rawHeaders[line], rawHeaders[line + 1])\n }\n\n return headers\n }\n\n /**\n * Safely clones the given `Response`.\n * Coerces response clone exceptions into 500 mocked responses.\n * Handy in the environments that introduce arbitrary response\n * cloning restrictions, like \"101 Switching Protocols\" cloning\n * in \"miniflare\".\n */\n static clone(response: Response): Response {\n try {\n const clone = response.clone()\n return clone\n } catch (error) {\n return Response.json(\n error instanceof Error\n ? {\n name: error.name,\n message: error.message,\n stack: error.stack,\n }\n : {},\n {\n status: 500,\n statusText: 'Unclonable Response',\n }\n )\n }\n }\n\n constructor(body?: BodyInit | null, init: FetchResponseInit = {}) {\n const status = init.status ?? 200\n const safeStatus = FetchResponse.isConfigurableStatusCode(status)\n ? status\n : 200\n const finalBody = FetchResponse.isResponseWithBody(status) ? body : null\n\n super(finalBody, {\n status: safeStatus,\n statusText: init.statusText,\n headers: init.headers,\n })\n\n /**\n * Since Node.js v24, Undici stores the Response state in an inaccessible field \"#state\".\n * Forward the modified status/URL to the cloned response manually.\n * @see https://github.com/nodejs/undici/blob/f734c87280e626c75f59aad55b65eb6a89cef392/lib/web/fetch/response.js#L242\n */\n if (status !== safeStatus) {\n FetchResponse.setStatus(status, this)\n }\n\n FetchResponse.setUrl(init.url, this)\n }\n\n public clone() {\n const clonedResponse = super.clone()\n\n const customStatus = Reflect.get(this, kStatus) as number | undefined\n\n if (customStatus) {\n FetchResponse.setStatus(customStatus, clonedResponse)\n }\n\n const customUrl = Reflect.get(this, kUrl) as string | undefined\n\n if (customUrl) {\n FetchResponse.setUrl(customUrl, clonedResponse)\n }\n\n return clonedResponse\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAaA,MAAa,kCACX;AAEF,SAAgB,gBAAmB,QAA+B;AAChE,QAEE,WAAW,WAAW;;AAI1B,SAAS,gBAAgB,QAAgB,OAAkB;AAEzD,YAAW,UAAU;;AAGvB,SAAgB,mBAAmB,QAAsB;AAEvD,QAAO,WAAW;;AAGpB,IAAY,0EAAL;AACL;AACA;AACA;AACA;AACA;;;AAMF,IAAa,cAAb,MAA6D;CAO3D,YAAY,AAAiBA,QAAgB;EAAhB;AAC3B,OAAK,aAAa,sBAAsB;AAExC,OAAK,UAAU,IAAIC,8BAAS;AAC5B,OAAK,gBAAgB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cjs b/node_modules/@mswjs/interceptors/lib/node/getRawRequest-B6znU6il.cjs new file mode 100644 index 0000000000000000000000000000000000000000..63b4d67f9390681ca92fddbc71c01ae23c2785c8 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/getRawRequest-B6znU6il.cjs @@ -0,0 +1,36 @@ + +//#region src/getRawRequest.ts +const kRawRequest = Symbol("kRawRequest"); +/** +* Returns a raw request instance associated with this request. +* +* @example +* interceptor.on('request', ({ request }) => { +* const rawRequest = getRawRequest(request) +* +* if (rawRequest instanceof http.ClientRequest) { +* console.log(rawRequest.rawHeaders) +* } +* }) +*/ +function getRawRequest(request) { + return Reflect.get(request, kRawRequest); +} +function setRawRequest(request, rawRequest) { + Reflect.set(request, kRawRequest, rawRequest); +} + +//#endregion +Object.defineProperty(exports, 'getRawRequest', { + enumerable: true, + get: function () { + return getRawRequest; + } +}); +Object.defineProperty(exports, 'setRawRequest', { + enumerable: true, + get: function () { + return setRawRequest; + } +}); +//# sourceMappingURL=getRawRequest-B6znU6il.cjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/getRawRequest-B6znU6il.cjs.map b/node_modules/@mswjs/interceptors/lib/node/getRawRequest-B6znU6il.cjs.map new file mode 100644 index 0000000000000000000000000000000000000000..35eaad2aab336842f9d3e9d5ae22c3aae364492a --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/getRawRequest-B6znU6il.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"getRawRequest-B6znU6il.cjs","names":[],"sources":["../../src/getRawRequest.ts"],"sourcesContent":["const kRawRequest = Symbol('kRawRequest')\n\n/**\n * Returns a raw request instance associated with this request.\n *\n * @example\n * interceptor.on('request', ({ request }) => {\n * const rawRequest = getRawRequest(request)\n *\n * if (rawRequest instanceof http.ClientRequest) {\n * console.log(rawRequest.rawHeaders)\n * }\n * })\n */\nexport function getRawRequest(request: Request): unknown | undefined {\n return Reflect.get(request, kRawRequest)\n}\n\nexport function setRawRequest(request: Request, rawRequest: unknown): void {\n Reflect.set(request, kRawRequest, rawRequest)\n}\n"],"mappings":";;AAAA,MAAM,cAAc,OAAO,cAAc;;;;;;;;;;;;;AAczC,SAAgB,cAAc,SAAuC;AACnE,QAAO,QAAQ,IAAI,SAAS,YAAY;;AAG1C,SAAgB,cAAc,SAAkB,YAA2B;AACzE,SAAQ,IAAI,SAAS,aAAa,WAAW"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/getRawRequest-C2-1urzA.mjs b/node_modules/@mswjs/interceptors/lib/node/getRawRequest-C2-1urzA.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b1b62e1dc749f9222613fcfc82621117b75c6a48 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/getRawRequest-C2-1urzA.mjs @@ -0,0 +1,24 @@ +//#region src/getRawRequest.ts +const kRawRequest = Symbol("kRawRequest"); +/** +* Returns a raw request instance associated with this request. +* +* @example +* interceptor.on('request', ({ request }) => { +* const rawRequest = getRawRequest(request) +* +* if (rawRequest instanceof http.ClientRequest) { +* console.log(rawRequest.rawHeaders) +* } +* }) +*/ +function getRawRequest(request) { + return Reflect.get(request, kRawRequest); +} +function setRawRequest(request, rawRequest) { + Reflect.set(request, kRawRequest, rawRequest); +} + +//#endregion +export { setRawRequest as n, getRawRequest as t }; +//# sourceMappingURL=getRawRequest-C2-1urzA.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/getRawRequest-C2-1urzA.mjs.map b/node_modules/@mswjs/interceptors/lib/node/getRawRequest-C2-1urzA.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..e02c08d35e80964237093ce0ade1c5e32141c520 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/getRawRequest-C2-1urzA.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"getRawRequest-C2-1urzA.mjs","names":[],"sources":["../../src/getRawRequest.ts"],"sourcesContent":["const kRawRequest = Symbol('kRawRequest')\n\n/**\n * Returns a raw request instance associated with this request.\n *\n * @example\n * interceptor.on('request', ({ request }) => {\n * const rawRequest = getRawRequest(request)\n *\n * if (rawRequest instanceof http.ClientRequest) {\n * console.log(rawRequest.rawHeaders)\n * }\n * })\n */\nexport function getRawRequest(request: Request): unknown | undefined {\n return Reflect.get(request, kRawRequest)\n}\n\nexport function setRawRequest(request: Request, rawRequest: unknown): void {\n Reflect.set(request, kRawRequest, rawRequest)\n}\n"],"mappings":";AAAA,MAAM,cAAc,OAAO,cAAc;;;;;;;;;;;;;AAczC,SAAgB,cAAc,SAAuC;AACnE,QAAO,QAAQ,IAAI,SAAS,YAAY;;AAG1C,SAAgB,cAAc,SAAkB,YAA2B;AACzE,SAAQ,IAAI,SAAS,aAAa,WAAW"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/handleRequest-C-cKYjIh.cjs b/node_modules/@mswjs/interceptors/lib/node/handleRequest-C-cKYjIh.cjs new file mode 100644 index 0000000000000000000000000000000000000000..1d0d400a7c77fed502043d57a4375da3d2ba4b97 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/handleRequest-C-cKYjIh.cjs @@ -0,0 +1,222 @@ +const require_chunk = require('./chunk-CbDLau6x.cjs'); +const require_fetchUtils = require('./fetchUtils-umV5xXBy.cjs'); +let _open_draft_deferred_promise = require("@open-draft/deferred-promise"); +let _open_draft_until = require("@open-draft/until"); + +//#region src/utils/isPropertyAccessible.ts +/** +* A function that validates if property access is possible on an object +* without throwing. It returns `true` if the property access is possible +* and `false` otherwise. +* +* Environments like miniflare will throw on property access on certain objects +* like Request and Response, for unimplemented properties. +*/ +function isPropertyAccessible(obj, key) { + try { + obj[key]; + return true; + } catch { + return false; + } +} + +//#endregion +//#region src/utils/emitAsync.ts +/** +* Emits an event on the given emitter but executes +* the listeners sequentially. This accounts for asynchronous +* listeners (e.g. those having "sleep" and handling the request). +*/ +async function emitAsync(emitter, eventName, ...data) { + const listeners = emitter.listeners(eventName); + if (listeners.length === 0) return; + for (const listener of listeners) await listener.apply(emitter, data); +} + +//#endregion +//#region src/utils/isObject.ts +/** +* Determines if a given value is an instance of object. +*/ +function isObject(value, loose = false) { + return loose ? Object.prototype.toString.call(value).startsWith("[object ") : Object.prototype.toString.call(value) === "[object Object]"; +} + +//#endregion +//#region src/utils/responseUtils.ts +/** +* Creates a generic 500 Unhandled Exception response. +*/ +function createServerErrorResponse(body) { + return new Response(JSON.stringify(body instanceof Error ? { + name: body.name, + message: body.message, + stack: body.stack + } : body), { + status: 500, + statusText: "Unhandled Exception", + headers: { "Content-Type": "application/json" } + }); +} +/** +* Check if the given response is a `Response.error()`. +* +* @note Some environments, like Miniflare (Cloudflare) do not +* implement the "Response.type" property and throw on its access. +* Safely check if we can access "type" on "Response" before continuing. +* @see https://github.com/mswjs/msw/issues/1834 +*/ +function isResponseError(response) { + return response != null && response instanceof Response && isPropertyAccessible(response, "type") && response.type === "error"; +} +/** +* Check if the given value is a `Response` or a Response-like object. +* This is different from `value instanceof Response` because it supports +* custom `Response` constructors, like the one when using Undici directly. +*/ +function isResponseLike(value) { + return isObject(value, true) && isPropertyAccessible(value, "status") && isPropertyAccessible(value, "statusText") && isPropertyAccessible(value, "bodyUsed"); +} + +//#endregion +//#region src/utils/isNodeLikeError.ts +function isNodeLikeError(error) { + if (error == null) return false; + if (!(error instanceof Error)) return false; + return "code" in error && "errno" in error; +} + +//#endregion +//#region src/utils/handleRequest.ts +async function handleRequest(options) { + const handleResponse = async (response) => { + if (response instanceof Error) { + await options.controller.errorWith(response); + return true; + } + if (isResponseError(response)) { + await options.controller.respondWith(response); + return true; + } + /** + * Handle normal responses or response-like objects. + * @note This must come before the arbitrary object check + * since Response instances are, in fact, objects. + */ + if (isResponseLike(response)) { + await options.controller.respondWith(response); + return true; + } + if (isObject(response)) { + await options.controller.errorWith(response); + return true; + } + return false; + }; + const handleResponseError = async (error) => { + if (error instanceof require_fetchUtils.InterceptorError) throw result.error; + if (isNodeLikeError(error)) { + await options.controller.errorWith(error); + return true; + } + if (error instanceof Response) return await handleResponse(error); + return false; + }; + const requestAbortPromise = new _open_draft_deferred_promise.DeferredPromise(); + const onAbort = () => { + requestAbortPromise.reject(options.request.signal?.reason); + }; + /** + * @note `signal` is not always defined in React Native. + */ + if (options.request.signal) { + if (options.request.signal.aborted) { + await options.controller.errorWith(options.request.signal.reason); + return; + } + options.request.signal.addEventListener("abort", onAbort, { once: true }); + } + const result = await (0, _open_draft_until.until)(async () => { + const requestListenersPromise = emitAsync(options.emitter, "request", { + requestId: options.requestId, + request: options.request, + controller: options.controller + }); + await Promise.race([ + requestAbortPromise, + requestListenersPromise, + options.controller.handled + ]); + }); + options.request.signal?.removeEventListener("abort", onAbort); + if (requestAbortPromise.state === "rejected") { + await options.controller.errorWith(requestAbortPromise.rejectionReason); + return; + } + if (result.error) { + if (await handleResponseError(result.error)) return; + if (options.emitter.listenerCount("unhandledException") > 0) { + const unhandledExceptionController = new require_fetchUtils.RequestController(options.request, { + passthrough() {}, + async respondWith(response) { + await handleResponse(response); + }, + async errorWith(reason) { + /** + * @note Handle the result of the unhandled controller + * in the same way as the original request controller. + * The exception here is that thrown errors within the + * "unhandledException" event do NOT result in another + * emit of the same event. They are forwarded as-is. + */ + await options.controller.errorWith(reason); + } + }); + await emitAsync(options.emitter, "unhandledException", { + error: result.error, + request: options.request, + requestId: options.requestId, + controller: unhandledExceptionController + }); + if (unhandledExceptionController.readyState !== require_fetchUtils.RequestController.PENDING) return; + } + await options.controller.respondWith(createServerErrorResponse(result.error)); + return; + } + if (options.controller.readyState === require_fetchUtils.RequestController.PENDING) return await options.controller.passthrough(); + return options.controller.handled; +} + +//#endregion +Object.defineProperty(exports, 'emitAsync', { + enumerable: true, + get: function () { + return emitAsync; + } +}); +Object.defineProperty(exports, 'handleRequest', { + enumerable: true, + get: function () { + return handleRequest; + } +}); +Object.defineProperty(exports, 'isObject', { + enumerable: true, + get: function () { + return isObject; + } +}); +Object.defineProperty(exports, 'isPropertyAccessible', { + enumerable: true, + get: function () { + return isPropertyAccessible; + } +}); +Object.defineProperty(exports, 'isResponseError', { + enumerable: true, + get: function () { + return isResponseError; + } +}); +//# sourceMappingURL=handleRequest-C-cKYjIh.cjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/handleRequest-C-cKYjIh.cjs.map b/node_modules/@mswjs/interceptors/lib/node/handleRequest-C-cKYjIh.cjs.map new file mode 100644 index 0000000000000000000000000000000000000000..0fde2945823f926454737f74c201fed7085a6151 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/handleRequest-C-cKYjIh.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"handleRequest-C-cKYjIh.cjs","names":["InterceptorError","DeferredPromise","RequestController"],"sources":["../../src/utils/isPropertyAccessible.ts","../../src/utils/emitAsync.ts","../../src/utils/isObject.ts","../../src/utils/responseUtils.ts","../../src/utils/isNodeLikeError.ts","../../src/utils/handleRequest.ts"],"sourcesContent":["/**\n * A function that validates if property access is possible on an object\n * without throwing. It returns `true` if the property access is possible\n * and `false` otherwise.\n *\n * Environments like miniflare will throw on property access on certain objects\n * like Request and Response, for unimplemented properties.\n */\nexport function isPropertyAccessible>(\n obj: Obj,\n key: keyof Obj\n) {\n try {\n obj[key]\n return true\n } catch {\n return false\n }\n}\n","import { Emitter, EventMap } from 'strict-event-emitter'\n\n/**\n * Emits an event on the given emitter but executes\n * the listeners sequentially. This accounts for asynchronous\n * listeners (e.g. those having \"sleep\" and handling the request).\n */\nexport async function emitAsync<\n Events extends EventMap,\n EventName extends keyof Events\n>(\n emitter: Emitter,\n eventName: EventName,\n ...data: Events[EventName]\n): Promise {\n const listeners = emitter.listeners(eventName)\n\n if (listeners.length === 0) {\n return\n }\n\n for (const listener of listeners) {\n await listener.apply(emitter, data)\n }\n}\n","/**\n * Determines if a given value is an instance of object.\n */\nexport function isObject(value: any, loose = false): value is T {\n return loose\n ? Object.prototype.toString.call(value).startsWith('[object ')\n : Object.prototype.toString.call(value) === '[object Object]'\n}\n","import { isObject } from './isObject'\nimport { isPropertyAccessible } from './isPropertyAccessible'\n\n/**\n * Creates a generic 500 Unhandled Exception response.\n */\nexport function createServerErrorResponse(body: unknown): Response {\n return new Response(\n JSON.stringify(\n body instanceof Error\n ? {\n name: body.name,\n message: body.message,\n stack: body.stack,\n }\n : body\n ),\n {\n status: 500,\n statusText: 'Unhandled Exception',\n headers: {\n 'Content-Type': 'application/json',\n },\n }\n )\n}\n\nexport type ResponseError = Response & { type: 'error' }\n\n/**\n * Check if the given response is a `Response.error()`.\n *\n * @note Some environments, like Miniflare (Cloudflare) do not\n * implement the \"Response.type\" property and throw on its access.\n * Safely check if we can access \"type\" on \"Response\" before continuing.\n * @see https://github.com/mswjs/msw/issues/1834\n */\nexport function isResponseError(response: unknown): response is ResponseError {\n return (\n response != null &&\n response instanceof Response &&\n isPropertyAccessible(response, 'type') &&\n response.type === 'error'\n )\n}\n\n/**\n * Check if the given value is a `Response` or a Response-like object.\n * This is different from `value instanceof Response` because it supports\n * custom `Response` constructors, like the one when using Undici directly.\n */\nexport function isResponseLike(value: unknown): value is Response {\n return (\n isObject>(value, true) &&\n isPropertyAccessible(value, 'status') &&\n isPropertyAccessible(value, 'statusText') &&\n isPropertyAccessible(value, 'bodyUsed')\n )\n}\n","export function isNodeLikeError(\n error: unknown\n): error is NodeJS.ErrnoException {\n if (error == null) {\n return false\n }\n\n if (!(error instanceof Error)) {\n return false\n }\n\n return 'code' in error && 'errno' in error\n}\n","import type { Emitter } from 'strict-event-emitter'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { until } from '@open-draft/until'\nimport type { HttpRequestEventMap } from '../glossary'\nimport { emitAsync } from './emitAsync'\nimport { RequestController } from '../RequestController'\nimport {\n createServerErrorResponse,\n isResponseError,\n isResponseLike,\n} from './responseUtils'\nimport { InterceptorError } from '../InterceptorError'\nimport { isNodeLikeError } from './isNodeLikeError'\nimport { isObject } from './isObject'\n\ninterface HandleRequestOptions {\n requestId: string\n request: Request\n emitter: Emitter\n controller: RequestController\n}\n\nexport async function handleRequest(\n options: HandleRequestOptions\n): Promise {\n const handleResponse = async (\n response: Response | Error | Record\n ) => {\n if (response instanceof Error) {\n await options.controller.errorWith(response)\n return true\n }\n\n // Handle \"Response.error()\" instances.\n if (isResponseError(response)) {\n await options.controller.respondWith(response)\n return true\n }\n\n /**\n * Handle normal responses or response-like objects.\n * @note This must come before the arbitrary object check\n * since Response instances are, in fact, objects.\n */\n if (isResponseLike(response)) {\n await options.controller.respondWith(response)\n return true\n }\n\n // Handle arbitrary objects provided to `.errorWith(reason)`.\n if (isObject(response)) {\n await options.controller.errorWith(response)\n return true\n }\n\n return false\n }\n\n const handleResponseError = async (error: unknown): Promise => {\n // Forward the special interceptor error instances\n // to the developer. These must not be handled in any way.\n if (error instanceof InterceptorError) {\n throw result.error\n }\n\n // Support mocking Node.js-like errors.\n if (isNodeLikeError(error)) {\n await options.controller.errorWith(error)\n return true\n }\n\n // Handle thrown responses.\n if (error instanceof Response) {\n return await handleResponse(error)\n }\n\n return false\n }\n\n // Add the last \"request\" listener to check if the request\n // has been handled in any way. If it hasn't, resolve the\n // response promise with undefined.\n // options.emitter.once('request', async ({ requestId: pendingRequestId }) => {\n // if (\n // pendingRequestId === options.requestId &&\n // options.controller.readyState === RequestController.PENDING\n // ) {\n // await options.controller.passthrough()\n // }\n // })\n\n const requestAbortPromise = new DeferredPromise()\n const onAbort = () => {\n requestAbortPromise.reject(options.request.signal?.reason)\n }\n\n /**\n * @note `signal` is not always defined in React Native.\n */\n if (options.request.signal) {\n if (options.request.signal.aborted) {\n await options.controller.errorWith(options.request.signal.reason)\n return\n }\n\n options.request.signal.addEventListener('abort', onAbort, { once: true })\n }\n\n const result = await until(async () => {\n // Emit the \"request\" event and wait until all the listeners\n // for that event are finished (e.g. async listeners awaited).\n // By the end of this promise, the developer cannot affect the\n // request anymore.\n const requestListenersPromise = emitAsync(options.emitter, 'request', {\n requestId: options.requestId,\n request: options.request,\n controller: options.controller,\n })\n\n await Promise.race([\n // Short-circuit the request handling promise if the request gets aborted.\n requestAbortPromise,\n requestListenersPromise,\n options.controller.handled,\n ])\n })\n\n options.request.signal?.removeEventListener('abort', onAbort)\n\n // Handle the request being aborted while waiting for the request listeners.\n if (requestAbortPromise.state === 'rejected') {\n await options.controller.errorWith(requestAbortPromise.rejectionReason)\n return\n }\n\n if (result.error) {\n // Handle the error during the request listener execution.\n // These can be thrown responses or request errors.\n if (await handleResponseError(result.error)) {\n return\n }\n\n // If the developer has added \"unhandledException\" listeners,\n // allow them to handle the error. They can translate it to a\n // mocked response, network error, or forward it as-is.\n if (options.emitter.listenerCount('unhandledException') > 0) {\n // Create a new request controller just for the unhandled exception case.\n // This is needed because the original controller might have been already\n // interacted with (e.g. \"respondWith\" or \"errorWith\" called on it).\n const unhandledExceptionController = new RequestController(\n options.request,\n {\n /**\n * @note Intentionally empty passthrough handle.\n * This controller is created within another controller and we only need\n * to know if `unhandledException` listeners handled the request.\n */\n passthrough() {},\n async respondWith(response) {\n await handleResponse(response)\n },\n async errorWith(reason) {\n /**\n * @note Handle the result of the unhandled controller\n * in the same way as the original request controller.\n * The exception here is that thrown errors within the\n * \"unhandledException\" event do NOT result in another\n * emit of the same event. They are forwarded as-is.\n */\n await options.controller.errorWith(reason)\n },\n }\n )\n\n await emitAsync(options.emitter, 'unhandledException', {\n error: result.error,\n request: options.request,\n requestId: options.requestId,\n controller: unhandledExceptionController,\n })\n\n // If all the \"unhandledException\" listeners have finished\n // but have not handled the request in any way, passthrough.\n if (\n unhandledExceptionController.readyState !== RequestController.PENDING\n ) {\n return\n }\n }\n\n // Otherwise, coerce unhandled exceptions to a 500 Internal Server Error response.\n await options.controller.respondWith(\n createServerErrorResponse(result.error)\n )\n return\n }\n\n // If the request hasn't been handled by this point, passthrough.\n if (options.controller.readyState === RequestController.PENDING) {\n return await options.controller.passthrough()\n }\n\n return options.controller.handled\n}\n"],"mappings":";;;;;;;;;;;;;;AAQA,SAAgB,qBACd,KACA,KACA;AACA,KAAI;AACF,MAA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ACR;IAME,cAAc;IACd,MAAM,YAAY,UAAU;AAC1B,WAAM,eAAe,SAAS;;IAEhC,MAAM,UAAU,QAAQ;;;;;;;;AAQtB,WAAM,QAAQ,WAAW,UAAU,OAAO;;IAE7C,CACF;AAED,SAAM,UAAU,QAAQ,SAAS,sBAAsB;IACrD,OAAO,OAAO;IACd,SAAS,QAAQ;IACjB,WAAW,QAAQ;IACnB,YAAY;IACb,CAAC;AAIF,OACE,6BAA6B,eAAeA,qCAAkB,QAE9D;;AAKJ,QAAM,QAAQ,WAAW,YACvB,0BAA0B,OAAO,MAAM,CACxC;AACD;;AAIF,KAAI,QAAQ,WAAW,eAAeA,qCAAkB,QACtD,QAAO,MAAM,QAAQ,WAAW,aAAa;AAG/C,QAAO,QAAQ,WAAW"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/handleRequest-FIQv5pwH.mjs b/node_modules/@mswjs/interceptors/lib/node/handleRequest-FIQv5pwH.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a1676184e5878032d05ba88b0e6d308fcf497812 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/handleRequest-FIQv5pwH.mjs @@ -0,0 +1,192 @@ +import { a as RequestController, o as InterceptorError } from "./fetchUtils-BKJ1XmiO.mjs"; +import { DeferredPromise } from "@open-draft/deferred-promise"; +import { until } from "@open-draft/until"; + +//#region src/utils/isPropertyAccessible.ts +/** +* A function that validates if property access is possible on an object +* without throwing. It returns `true` if the property access is possible +* and `false` otherwise. +* +* Environments like miniflare will throw on property access on certain objects +* like Request and Response, for unimplemented properties. +*/ +function isPropertyAccessible(obj, key) { + try { + obj[key]; + return true; + } catch { + return false; + } +} + +//#endregion +//#region src/utils/emitAsync.ts +/** +* Emits an event on the given emitter but executes +* the listeners sequentially. This accounts for asynchronous +* listeners (e.g. those having "sleep" and handling the request). +*/ +async function emitAsync(emitter, eventName, ...data) { + const listeners = emitter.listeners(eventName); + if (listeners.length === 0) return; + for (const listener of listeners) await listener.apply(emitter, data); +} + +//#endregion +//#region src/utils/isObject.ts +/** +* Determines if a given value is an instance of object. +*/ +function isObject(value, loose = false) { + return loose ? Object.prototype.toString.call(value).startsWith("[object ") : Object.prototype.toString.call(value) === "[object Object]"; +} + +//#endregion +//#region src/utils/responseUtils.ts +/** +* Creates a generic 500 Unhandled Exception response. +*/ +function createServerErrorResponse(body) { + return new Response(JSON.stringify(body instanceof Error ? { + name: body.name, + message: body.message, + stack: body.stack + } : body), { + status: 500, + statusText: "Unhandled Exception", + headers: { "Content-Type": "application/json" } + }); +} +/** +* Check if the given response is a `Response.error()`. +* +* @note Some environments, like Miniflare (Cloudflare) do not +* implement the "Response.type" property and throw on its access. +* Safely check if we can access "type" on "Response" before continuing. +* @see https://github.com/mswjs/msw/issues/1834 +*/ +function isResponseError(response) { + return response != null && response instanceof Response && isPropertyAccessible(response, "type") && response.type === "error"; +} +/** +* Check if the given value is a `Response` or a Response-like object. +* This is different from `value instanceof Response` because it supports +* custom `Response` constructors, like the one when using Undici directly. +*/ +function isResponseLike(value) { + return isObject(value, true) && isPropertyAccessible(value, "status") && isPropertyAccessible(value, "statusText") && isPropertyAccessible(value, "bodyUsed"); +} + +//#endregion +//#region src/utils/isNodeLikeError.ts +function isNodeLikeError(error) { + if (error == null) return false; + if (!(error instanceof Error)) return false; + return "code" in error && "errno" in error; +} + +//#endregion +//#region src/utils/handleRequest.ts +async function handleRequest(options) { + const handleResponse = async (response) => { + if (response instanceof Error) { + await options.controller.errorWith(response); + return true; + } + if (isResponseError(response)) { + await options.controller.respondWith(response); + return true; + } + /** + * Handle normal responses or response-like objects. + * @note This must come before the arbitrary object check + * since Response instances are, in fact, objects. + */ + if (isResponseLike(response)) { + await options.controller.respondWith(response); + return true; + } + if (isObject(response)) { + await options.controller.errorWith(response); + return true; + } + return false; + }; + const handleResponseError = async (error) => { + if (error instanceof InterceptorError) throw result.error; + if (isNodeLikeError(error)) { + await options.controller.errorWith(error); + return true; + } + if (error instanceof Response) return await handleResponse(error); + return false; + }; + const requestAbortPromise = new DeferredPromise(); + const onAbort = () => { + requestAbortPromise.reject(options.request.signal?.reason); + }; + /** + * @note `signal` is not always defined in React Native. + */ + if (options.request.signal) { + if (options.request.signal.aborted) { + await options.controller.errorWith(options.request.signal.reason); + return; + } + options.request.signal.addEventListener("abort", onAbort, { once: true }); + } + const result = await until(async () => { + const requestListenersPromise = emitAsync(options.emitter, "request", { + requestId: options.requestId, + request: options.request, + controller: options.controller + }); + await Promise.race([ + requestAbortPromise, + requestListenersPromise, + options.controller.handled + ]); + }); + options.request.signal?.removeEventListener("abort", onAbort); + if (requestAbortPromise.state === "rejected") { + await options.controller.errorWith(requestAbortPromise.rejectionReason); + return; + } + if (result.error) { + if (await handleResponseError(result.error)) return; + if (options.emitter.listenerCount("unhandledException") > 0) { + const unhandledExceptionController = new RequestController(options.request, { + passthrough() {}, + async respondWith(response) { + await handleResponse(response); + }, + async errorWith(reason) { + /** + * @note Handle the result of the unhandled controller + * in the same way as the original request controller. + * The exception here is that thrown errors within the + * "unhandledException" event do NOT result in another + * emit of the same event. They are forwarded as-is. + */ + await options.controller.errorWith(reason); + } + }); + await emitAsync(options.emitter, "unhandledException", { + error: result.error, + request: options.request, + requestId: options.requestId, + controller: unhandledExceptionController + }); + if (unhandledExceptionController.readyState !== RequestController.PENDING) return; + } + await options.controller.respondWith(createServerErrorResponse(result.error)); + return; + } + if (options.controller.readyState === RequestController.PENDING) return await options.controller.passthrough(); + return options.controller.handled; +} + +//#endregion +export { isPropertyAccessible as a, emitAsync as i, isResponseError as n, isObject as r, handleRequest as t }; +//# sourceMappingURL=handleRequest-FIQv5pwH.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/handleRequest-FIQv5pwH.mjs.map b/node_modules/@mswjs/interceptors/lib/node/handleRequest-FIQv5pwH.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..00a47836c7b838020ae369d6e72b52342c82a0d5 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/handleRequest-FIQv5pwH.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"handleRequest-FIQv5pwH.mjs","names":[],"sources":["../../src/utils/isPropertyAccessible.ts","../../src/utils/emitAsync.ts","../../src/utils/isObject.ts","../../src/utils/responseUtils.ts","../../src/utils/isNodeLikeError.ts","../../src/utils/handleRequest.ts"],"sourcesContent":["/**\n * A function that validates if property access is possible on an object\n * without throwing. It returns `true` if the property access is possible\n * and `false` otherwise.\n *\n * Environments like miniflare will throw on property access on certain objects\n * like Request and Response, for unimplemented properties.\n */\nexport function isPropertyAccessible>(\n obj: Obj,\n key: keyof Obj\n) {\n try {\n obj[key]\n return true\n } catch {\n return false\n }\n}\n","import { Emitter, EventMap } from 'strict-event-emitter'\n\n/**\n * Emits an event on the given emitter but executes\n * the listeners sequentially. This accounts for asynchronous\n * listeners (e.g. those having \"sleep\" and handling the request).\n */\nexport async function emitAsync<\n Events extends EventMap,\n EventName extends keyof Events\n>(\n emitter: Emitter,\n eventName: EventName,\n ...data: Events[EventName]\n): Promise {\n const listeners = emitter.listeners(eventName)\n\n if (listeners.length === 0) {\n return\n }\n\n for (const listener of listeners) {\n await listener.apply(emitter, data)\n }\n}\n","/**\n * Determines if a given value is an instance of object.\n */\nexport function isObject(value: any, loose = false): value is T {\n return loose\n ? Object.prototype.toString.call(value).startsWith('[object ')\n : Object.prototype.toString.call(value) === '[object Object]'\n}\n","import { isObject } from './isObject'\nimport { isPropertyAccessible } from './isPropertyAccessible'\n\n/**\n * Creates a generic 500 Unhandled Exception response.\n */\nexport function createServerErrorResponse(body: unknown): Response {\n return new Response(\n JSON.stringify(\n body instanceof Error\n ? {\n name: body.name,\n message: body.message,\n stack: body.stack,\n }\n : body\n ),\n {\n status: 500,\n statusText: 'Unhandled Exception',\n headers: {\n 'Content-Type': 'application/json',\n },\n }\n )\n}\n\nexport type ResponseError = Response & { type: 'error' }\n\n/**\n * Check if the given response is a `Response.error()`.\n *\n * @note Some environments, like Miniflare (Cloudflare) do not\n * implement the \"Response.type\" property and throw on its access.\n * Safely check if we can access \"type\" on \"Response\" before continuing.\n * @see https://github.com/mswjs/msw/issues/1834\n */\nexport function isResponseError(response: unknown): response is ResponseError {\n return (\n response != null &&\n response instanceof Response &&\n isPropertyAccessible(response, 'type') &&\n response.type === 'error'\n )\n}\n\n/**\n * Check if the given value is a `Response` or a Response-like object.\n * This is different from `value instanceof Response` because it supports\n * custom `Response` constructors, like the one when using Undici directly.\n */\nexport function isResponseLike(value: unknown): value is Response {\n return (\n isObject>(value, true) &&\n isPropertyAccessible(value, 'status') &&\n isPropertyAccessible(value, 'statusText') &&\n isPropertyAccessible(value, 'bodyUsed')\n )\n}\n","export function isNodeLikeError(\n error: unknown\n): error is NodeJS.ErrnoException {\n if (error == null) {\n return false\n }\n\n if (!(error instanceof Error)) {\n return false\n }\n\n return 'code' in error && 'errno' in error\n}\n","import type { Emitter } from 'strict-event-emitter'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { until } from '@open-draft/until'\nimport type { HttpRequestEventMap } from '../glossary'\nimport { emitAsync } from './emitAsync'\nimport { RequestController } from '../RequestController'\nimport {\n createServerErrorResponse,\n isResponseError,\n isResponseLike,\n} from './responseUtils'\nimport { InterceptorError } from '../InterceptorError'\nimport { isNodeLikeError } from './isNodeLikeError'\nimport { isObject } from './isObject'\n\ninterface HandleRequestOptions {\n requestId: string\n request: Request\n emitter: Emitter\n controller: RequestController\n}\n\nexport async function handleRequest(\n options: HandleRequestOptions\n): Promise {\n const handleResponse = async (\n response: Response | Error | Record\n ) => {\n if (response instanceof Error) {\n await options.controller.errorWith(response)\n return true\n }\n\n // Handle \"Response.error()\" instances.\n if (isResponseError(response)) {\n await options.controller.respondWith(response)\n return true\n }\n\n /**\n * Handle normal responses or response-like objects.\n * @note This must come before the arbitrary object check\n * since Response instances are, in fact, objects.\n */\n if (isResponseLike(response)) {\n await options.controller.respondWith(response)\n return true\n }\n\n // Handle arbitrary objects provided to `.errorWith(reason)`.\n if (isObject(response)) {\n await options.controller.errorWith(response)\n return true\n }\n\n return false\n }\n\n const handleResponseError = async (error: unknown): Promise => {\n // Forward the special interceptor error instances\n // to the developer. These must not be handled in any way.\n if (error instanceof InterceptorError) {\n throw result.error\n }\n\n // Support mocking Node.js-like errors.\n if (isNodeLikeError(error)) {\n await options.controller.errorWith(error)\n return true\n }\n\n // Handle thrown responses.\n if (error instanceof Response) {\n return await handleResponse(error)\n }\n\n return false\n }\n\n // Add the last \"request\" listener to check if the request\n // has been handled in any way. If it hasn't, resolve the\n // response promise with undefined.\n // options.emitter.once('request', async ({ requestId: pendingRequestId }) => {\n // if (\n // pendingRequestId === options.requestId &&\n // options.controller.readyState === RequestController.PENDING\n // ) {\n // await options.controller.passthrough()\n // }\n // })\n\n const requestAbortPromise = new DeferredPromise()\n const onAbort = () => {\n requestAbortPromise.reject(options.request.signal?.reason)\n }\n\n /**\n * @note `signal` is not always defined in React Native.\n */\n if (options.request.signal) {\n if (options.request.signal.aborted) {\n await options.controller.errorWith(options.request.signal.reason)\n return\n }\n\n options.request.signal.addEventListener('abort', onAbort, { once: true })\n }\n\n const result = await until(async () => {\n // Emit the \"request\" event and wait until all the listeners\n // for that event are finished (e.g. async listeners awaited).\n // By the end of this promise, the developer cannot affect the\n // request anymore.\n const requestListenersPromise = emitAsync(options.emitter, 'request', {\n requestId: options.requestId,\n request: options.request,\n controller: options.controller,\n })\n\n await Promise.race([\n // Short-circuit the request handling promise if the request gets aborted.\n requestAbortPromise,\n requestListenersPromise,\n options.controller.handled,\n ])\n })\n\n options.request.signal?.removeEventListener('abort', onAbort)\n\n // Handle the request being aborted while waiting for the request listeners.\n if (requestAbortPromise.state === 'rejected') {\n await options.controller.errorWith(requestAbortPromise.rejectionReason)\n return\n }\n\n if (result.error) {\n // Handle the error during the request listener execution.\n // These can be thrown responses or request errors.\n if (await handleResponseError(result.error)) {\n return\n }\n\n // If the developer has added \"unhandledException\" listeners,\n // allow them to handle the error. They can translate it to a\n // mocked response, network error, or forward it as-is.\n if (options.emitter.listenerCount('unhandledException') > 0) {\n // Create a new request controller just for the unhandled exception case.\n // This is needed because the original controller might have been already\n // interacted with (e.g. \"respondWith\" or \"errorWith\" called on it).\n const unhandledExceptionController = new RequestController(\n options.request,\n {\n /**\n * @note Intentionally empty passthrough handle.\n * This controller is created within another controller and we only need\n * to know if `unhandledException` listeners handled the request.\n */\n passthrough() {},\n async respondWith(response) {\n await handleResponse(response)\n },\n async errorWith(reason) {\n /**\n * @note Handle the result of the unhandled controller\n * in the same way as the original request controller.\n * The exception here is that thrown errors within the\n * \"unhandledException\" event do NOT result in another\n * emit of the same event. They are forwarded as-is.\n */\n await options.controller.errorWith(reason)\n },\n }\n )\n\n await emitAsync(options.emitter, 'unhandledException', {\n error: result.error,\n request: options.request,\n requestId: options.requestId,\n controller: unhandledExceptionController,\n })\n\n // If all the \"unhandledException\" listeners have finished\n // but have not handled the request in any way, passthrough.\n if (\n unhandledExceptionController.readyState !== RequestController.PENDING\n ) {\n return\n }\n }\n\n // Otherwise, coerce unhandled exceptions to a 500 Internal Server Error response.\n await options.controller.respondWith(\n createServerErrorResponse(result.error)\n )\n return\n }\n\n // If the request hasn't been handled by this point, passthrough.\n if (options.controller.readyState === RequestController.PENDING) {\n return await options.controller.passthrough()\n }\n\n return options.controller.handled\n}\n"],"mappings":";;;;;;;;;;;;;AAQA,SAAgB,qBACd,KACA,KACA;AACA,KAAI;AACF,MAAI;AACJ,SAAO;SACD;AACN,SAAO;;;;;;;;;;;ACTX,eAAsB,UAIpB,SACA,WACA,GAAG,MACY;CACf,MAAM,YAAY,QAAQ,UAAU,UAAU;AAE9C,KAAI,UAAU,WAAW,EACvB;AAGF,MAAK,MAAM,YAAY,UACrB,OAAM,SAAS,MAAM,SAAS,KAAK;;;;;;;;ACnBvC,SAAgB,SAAY,OAAY,QAAQ,OAAmB;AACjE,QAAO,QACH,OAAO,UAAU,SAAS,KAAK,MAAM,CAAC,WAAW,WAAW,GAC5D,OAAO,UAAU,SAA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B,OAAO,MAAM,CACxC;AACD;;AAIF,KAAI,QAAQ,WAAW,eAAe,kBAAkB,QACtD,QAAO,MAAM,QAAQ,WAAW,aAAa;AAG/C,QAAO,QAAQ,WAAW"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/hasConfigurableGlobal-BiTmog1u.mjs b/node_modules/@mswjs/interceptors/lib/node/hasConfigurableGlobal-BiTmog1u.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e05169c2b8021905ac084604bca2d3834a8507a3 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/hasConfigurableGlobal-BiTmog1u.mjs @@ -0,0 +1,96 @@ +import { invariant } from "outvariant"; + +//#region src/utils/patchesRegistry.ts +var PatchesRegistry = class { + #replacements = /* @__PURE__ */ new Map(); + applyPatch(owner, key, getNextValue) { + const ownerReplacements = this.#replacements.get(owner); + invariant(!ownerReplacements?.has(key), `Failed to replace a global value at "${String(key)}": already replaced.`); + const match = getDeepPropertyDescriptor(owner, key); + if (typeof match === "undefined") { + console.warn(`Failed to replace a global value at "${String(key)}": not a global value.`); + return () => {}; + } + if (match.descriptor.configurable) Object.defineProperty(owner, key, { + value: getNextValue(owner[key]), + enumerable: true, + configurable: true + }); + else if (match.descriptor.writable) owner[key] = getNextValue(owner[key]); + else throw new Error(`Failed to patch a non-configurable non-writable property "${key.toString()}"`); + const restorePatch = () => { + const currentReplacements = this.#replacements.get(owner); + if (!currentReplacements?.has(key)) return; + if (match.owner === owner) + /** + * @note Restoring non-configurable properties works as long as "writable: true" + * and none of the other descriptor properties except for "value" have changed. + */ + Object.defineProperty(match.owner, key, match.descriptor); + else + /** + * @todo Delete the proxy property set by the registry. + * If the match's owner isn't the original owner, the property is likely nested in the prototype. + * The registry does not meddle with those, they are left intact. + */ + Reflect.deleteProperty(owner, key); + currentReplacements.delete(key); + if (currentReplacements.size === 0) this.#replacements.delete(owner); + }; + if (ownerReplacements) ownerReplacements.set(key, restorePatch); + else this.#replacements.set(owner, new Map([[key, restorePatch]])); + return restorePatch; + } + restoreAllPatches() { + const errors = []; + for (const [, ownerReplacements] of this.#replacements) for (const [, restorePatch] of ownerReplacements) try { + restorePatch(); + } catch (error) { + if (error instanceof Error) errors.push(error); + else throw error; + } + if (errors.length > 0) throw new AggregateError(errors, "FOO!"); + } +}; +const patchesRegistry = new PatchesRegistry(); +/** +* Returns a property descriptor for the given property on the owner. +* Walks down the prototype chain if the property does not exist on the owner. +* Handy for getting a global property descriptor where `globalThis` is +* replaced with a controlled class (e.g. ServiceWorkerGlobalScope). +*/ +function getDeepPropertyDescriptor(owner, key) { + let currentOwner = owner; + let descriptor; + while (currentOwner) { + descriptor = Object.getOwnPropertyDescriptor(currentOwner, key); + if (descriptor) return { + owner: currentOwner, + descriptor + }; + currentOwner = Object.getPrototypeOf(currentOwner); + } +} + +//#endregion +//#region src/utils/hasConfigurableGlobal.ts +/** +* Returns a boolean indicating whether the given global property +* is defined and is configurable. +*/ +function hasConfigurableGlobal(propertyName) { + const match = getDeepPropertyDescriptor(globalThis, propertyName); + if (typeof match === "undefined") return false; + const { descriptor } = match; + if (typeof descriptor.get === "function" && typeof descriptor.get() === "undefined") return false; + if (typeof descriptor.get === "undefined" && descriptor.value == null) return false; + if (typeof descriptor.set === "undefined" && !descriptor.configurable) { + console.error(`[MSW] Failed to apply interceptor: the global \`${propertyName}\` property is non-configurable. This is likely an issue with your environment. If you are using a framework, please open an issue about this in their repository.`); + return false; + } + return true; +} + +//#endregion +export { patchesRegistry as n, hasConfigurableGlobal as t }; +//# sourceMappingURL=hasConfigurableGlobal-BiTmog1u.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/hasConfigurableGlobal-BiTmog1u.mjs.map b/node_modules/@mswjs/interceptors/lib/node/hasConfigurableGlobal-BiTmog1u.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..ca658f5c98f59eebd52ea7e4ca0aa7e110e943fe --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/hasConfigurableGlobal-BiTmog1u.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"hasConfigurableGlobal-BiTmog1u.mjs","names":["#replacements","errors: Array","currentOwner: Owner | null","descriptor: PropertyDescriptor | undefined"],"sources":["../../src/utils/patchesRegistry.ts","../../src/utils/hasConfigurableGlobal.ts"],"sourcesContent":["import { invariant } from 'outvariant'\n\nclass PatchesRegistry {\n #replacements = new Map void>>()\n\n public applyPatch(\n owner: Owner,\n key: K,\n getNextValue: (realValue: Owner[K]) => Owner[K]\n ): () => void {\n const ownerReplacements = this.#replacements.get(owner)\n\n invariant(\n !ownerReplacements?.has(key),\n `Failed to replace a global value at \"${String(key)}\": already replaced.`\n )\n\n const match = getDeepPropertyDescriptor(owner, key)\n\n if (typeof match === 'undefined') {\n console.warn(\n `Failed to replace a global value at \"${String(key)}\": not a global value.`\n )\n return () => {}\n }\n\n if (match.descriptor.configurable) {\n Object.defineProperty(owner, key, {\n value: getNextValue(owner[key]),\n enumerable: true,\n configurable: true,\n })\n } else if (match.descriptor.writable) {\n owner[key] = getNextValue(owner[key])\n } else {\n throw new Error(\n `Failed to patch a non-configurable non-writable property \"${key.toString()}\"`\n )\n }\n\n const restorePatch = () => {\n const currentReplacements = this.#replacements.get(owner)\n\n if (!currentReplacements?.has(key)) {\n return\n }\n\n if (match.owner === owner) {\n /**\n * @note Restoring non-configurable properties works as long as \"writable: true\"\n * and none of the other descriptor properties except for \"value\" have changed.\n */\n Object.defineProperty(match.owner, key, match.descriptor)\n } else {\n /**\n * @todo Delete the proxy property set by the registry.\n * If the match's owner isn't the original owner, the property is likely nested in the prototype.\n * The registry does not meddle with those, they are left intact.\n */\n Reflect.deleteProperty(owner, key)\n }\n\n currentReplacements.delete(key)\n\n if (currentReplacements.size === 0) {\n this.#replacements.delete(owner)\n }\n }\n\n if (ownerReplacements) {\n ownerReplacements.set(key, restorePatch)\n } else {\n this.#replacements.set(owner, new Map([[key, restorePatch]]))\n }\n\n return restorePatch\n }\n\n public restoreAllPatches(): void {\n const errors: Array = []\n\n for (const [, ownerReplacements] of this.#replacements) {\n for (const [, restorePatch] of ownerReplacements) {\n try {\n restorePatch()\n } catch (error) {\n if (error instanceof Error) {\n errors.push(error)\n } else {\n throw error\n }\n }\n }\n }\n\n if (errors.length > 0) {\n throw new AggregateError(errors, 'FOO!')\n }\n }\n}\n\nexport const patchesRegistry = new PatchesRegistry()\n\ninterface DeepDescriptorMatch {\n owner: object\n descriptor: PropertyDescriptor\n}\n\n/**\n * Returns a property descriptor for the given property on the owner.\n * Walks down the prototype chain if the property does not exist on the owner.\n * Handy for getting a global property descriptor where `globalThis` is\n * replaced with a controlled class (e.g. ServiceWorkerGlobalScope).\n */\nexport function getDeepPropertyDescriptor(\n owner: Owner,\n key: keyof Owner\n): DeepDescriptorMatch | undefined {\n let currentOwner: Owner | null = owner\n let descriptor: PropertyDescriptor | undefined\n\n while (currentOwner) {\n descriptor = Object.getOwnPropertyDescriptor(currentOwner, key)\n\n if (descriptor) {\n return {\n owner: currentOwner,\n descriptor,\n }\n }\n\n currentOwner = Object.getPrototypeOf(currentOwner)\n }\n}\n","import { getDeepPropertyDescriptor } from './patchesRegistry'\n\n/**\n * Returns a boolean indicating whether the given global property\n * is defined and is configurable.\n */\nexport function hasConfigurableGlobal(\n propertyName: keyof typeof globalThis\n): boolean {\n const match = getDeepPropertyDescriptor(globalThis, propertyName)\n\n // The property is not set at all.\n if (typeof match === 'undefined') {\n return false\n }\n\n const { descriptor } = match\n\n // The property is set to a getter that returns undefined.\n if (\n typeof descriptor.get === 'function' &&\n typeof descriptor.get() === 'undefined'\n ) {\n return false\n }\n\n // The property is set to a value equal to undefined.\n if (typeof descriptor.get === 'undefined' && descriptor.value == null) {\n return false\n }\n\n if (typeof descriptor.set === 'undefined' && !descriptor.configurable) {\n console.error(\n `[MSW] Failed to apply interceptor: the global \\`${propertyName}\\` property is non-configurable. This is likely an issue with your environment. If you are using a framework, please open an issue about this in their repository.`\n )\n return false\n }\n\n return true\n}\n"],"m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,QAAO,KAAK,MAAM;OAElB,OAAM;;AAMd,MAAI,OAAO,SAAS,EAClB,OAAM,IAAI,eAAe,QAAQ,OAAO;;;AAK9C,MAAa,kBAAkB,IAAI,iBAAiB;;;;;;;AAapD,SAAgB,0BACd,OACA,KACiC;CACjC,IAAIE,eAA6B;CACjC,IAAIC;AAEJ,QAAO,cAAc;AACnB,eAAa,OAAO,yBAAyB,cAAc,IAAI;AAE/D,MAAI,WACF,QAAO;GACL,OAAO;GACP;GACD;AAGH,iBAAe,OAAO,eAAe,aAAa;;;;;;;;;;AC7HtD,SAAgB,sBACd,cACS;CACT,MAAM,QAAQ,0BAA0B,YAAY,aAAa;AAGjE,KAAI,OAAO,UAAU,YACnB,QAAO;CAGT,MAAM,EAAE,eAAe;AAGvB,KACE,OAAO,WAAW,QAAQ,cAC1B,OAAO,WAAW,KAAK,KAAK,YAE5B,QAAO;AAIT,KAAI,OAAO,WAAW,QAAQ,eAAe,WAAW,SAAS,KAC/D,QAAO;AAGT,KAAI,OAAO,WAAW,QAAQ,eAAe,CAAC,WAAW,cAAc;AACrE,UAAQ,MACN,mDAAmD,aAAa,oKACjE;AACD,SAAO;;AAGT,QAAO"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/hasConfigurableGlobal-MjY06_Ok.cjs b/node_modules/@mswjs/interceptors/lib/node/hasConfigurableGlobal-MjY06_Ok.cjs new file mode 100644 index 0000000000000000000000000000000000000000..8ee56429f22b42ff8e001e66bef32a1188d269d5 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/hasConfigurableGlobal-MjY06_Ok.cjs @@ -0,0 +1,108 @@ +const require_chunk = require('./chunk-CbDLau6x.cjs'); +let outvariant = require("outvariant"); + +//#region src/utils/patchesRegistry.ts +var PatchesRegistry = class { + #replacements = /* @__PURE__ */ new Map(); + applyPatch(owner, key, getNextValue) { + const ownerReplacements = this.#replacements.get(owner); + (0, outvariant.invariant)(!ownerReplacements?.has(key), `Failed to replace a global value at "${String(key)}": already replaced.`); + const match = getDeepPropertyDescriptor(owner, key); + if (typeof match === "undefined") { + console.warn(`Failed to replace a global value at "${String(key)}": not a global value.`); + return () => {}; + } + if (match.descriptor.configurable) Object.defineProperty(owner, key, { + value: getNextValue(owner[key]), + enumerable: true, + configurable: true + }); + else if (match.descriptor.writable) owner[key] = getNextValue(owner[key]); + else throw new Error(`Failed to patch a non-configurable non-writable property "${key.toString()}"`); + const restorePatch = () => { + const currentReplacements = this.#replacements.get(owner); + if (!currentReplacements?.has(key)) return; + if (match.owner === owner) + /** + * @note Restoring non-configurable properties works as long as "writable: true" + * and none of the other descriptor properties except for "value" have changed. + */ + Object.defineProperty(match.owner, key, match.descriptor); + else + /** + * @todo Delete the proxy property set by the registry. + * If the match's owner isn't the original owner, the property is likely nested in the prototype. + * The registry does not meddle with those, they are left intact. + */ + Reflect.deleteProperty(owner, key); + currentReplacements.delete(key); + if (currentReplacements.size === 0) this.#replacements.delete(owner); + }; + if (ownerReplacements) ownerReplacements.set(key, restorePatch); + else this.#replacements.set(owner, new Map([[key, restorePatch]])); + return restorePatch; + } + restoreAllPatches() { + const errors = []; + for (const [, ownerReplacements] of this.#replacements) for (const [, restorePatch] of ownerReplacements) try { + restorePatch(); + } catch (error) { + if (error instanceof Error) errors.push(error); + else throw error; + } + if (errors.length > 0) throw new AggregateError(errors, "FOO!"); + } +}; +const patchesRegistry = new PatchesRegistry(); +/** +* Returns a property descriptor for the given property on the owner. +* Walks down the prototype chain if the property does not exist on the owner. +* Handy for getting a global property descriptor where `globalThis` is +* replaced with a controlled class (e.g. ServiceWorkerGlobalScope). +*/ +function getDeepPropertyDescriptor(owner, key) { + let currentOwner = owner; + let descriptor; + while (currentOwner) { + descriptor = Object.getOwnPropertyDescriptor(currentOwner, key); + if (descriptor) return { + owner: currentOwner, + descriptor + }; + currentOwner = Object.getPrototypeOf(currentOwner); + } +} + +//#endregion +//#region src/utils/hasConfigurableGlobal.ts +/** +* Returns a boolean indicating whether the given global property +* is defined and is configurable. +*/ +function hasConfigurableGlobal(propertyName) { + const match = getDeepPropertyDescriptor(globalThis, propertyName); + if (typeof match === "undefined") return false; + const { descriptor } = match; + if (typeof descriptor.get === "function" && typeof descriptor.get() === "undefined") return false; + if (typeof descriptor.get === "undefined" && descriptor.value == null) return false; + if (typeof descriptor.set === "undefined" && !descriptor.configurable) { + console.error(`[MSW] Failed to apply interceptor: the global \`${propertyName}\` property is non-configurable. This is likely an issue with your environment. If you are using a framework, please open an issue about this in their repository.`); + return false; + } + return true; +} + +//#endregion +Object.defineProperty(exports, 'hasConfigurableGlobal', { + enumerable: true, + get: function () { + return hasConfigurableGlobal; + } +}); +Object.defineProperty(exports, 'patchesRegistry', { + enumerable: true, + get: function () { + return patchesRegistry; + } +}); +//# sourceMappingURL=hasConfigurableGlobal-MjY06_Ok.cjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/hasConfigurableGlobal-MjY06_Ok.cjs.map b/node_modules/@mswjs/interceptors/lib/node/hasConfigurableGlobal-MjY06_Ok.cjs.map new file mode 100644 index 0000000000000000000000000000000000000000..5cf6f1a8a82569ab6014b9e1b449b0f94082aa3a --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/hasConfigurableGlobal-MjY06_Ok.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"hasConfigurableGlobal-MjY06_Ok.cjs","names":["#replacements","errors: Array","currentOwner: Owner | null","descriptor: PropertyDescriptor | undefined"],"sources":["../../src/utils/patchesRegistry.ts","../../src/utils/hasConfigurableGlobal.ts"],"sourcesContent":["import { invariant } from 'outvariant'\n\nclass PatchesRegistry {\n #replacements = new Map void>>()\n\n public applyPatch(\n owner: Owner,\n key: K,\n getNextValue: (realValue: Owner[K]) => Owner[K]\n ): () => void {\n const ownerReplacements = this.#replacements.get(owner)\n\n invariant(\n !ownerReplacements?.has(key),\n `Failed to replace a global value at \"${String(key)}\": already replaced.`\n )\n\n const match = getDeepPropertyDescriptor(owner, key)\n\n if (typeof match === 'undefined') {\n console.warn(\n `Failed to replace a global value at \"${String(key)}\": not a global value.`\n )\n return () => {}\n }\n\n if (match.descriptor.configurable) {\n Object.defineProperty(owner, key, {\n value: getNextValue(owner[key]),\n enumerable: true,\n configurable: true,\n })\n } else if (match.descriptor.writable) {\n owner[key] = getNextValue(owner[key])\n } else {\n throw new Error(\n `Failed to patch a non-configurable non-writable property \"${key.toString()}\"`\n )\n }\n\n const restorePatch = () => {\n const currentReplacements = this.#replacements.get(owner)\n\n if (!currentReplacements?.has(key)) {\n return\n }\n\n if (match.owner === owner) {\n /**\n * @note Restoring non-configurable properties works as long as \"writable: true\"\n * and none of the other descriptor properties except for \"value\" have changed.\n */\n Object.defineProperty(match.owner, key, match.descriptor)\n } else {\n /**\n * @todo Delete the proxy property set by the registry.\n * If the match's owner isn't the original owner, the property is likely nested in the prototype.\n * The registry does not meddle with those, they are left intact.\n */\n Reflect.deleteProperty(owner, key)\n }\n\n currentReplacements.delete(key)\n\n if (currentReplacements.size === 0) {\n this.#replacements.delete(owner)\n }\n }\n\n if (ownerReplacements) {\n ownerReplacements.set(key, restorePatch)\n } else {\n this.#replacements.set(owner, new Map([[key, restorePatch]]))\n }\n\n return restorePatch\n }\n\n public restoreAllPatches(): void {\n const errors: Array = []\n\n for (const [, ownerReplacements] of this.#replacements) {\n for (const [, restorePatch] of ownerReplacements) {\n try {\n restorePatch()\n } catch (error) {\n if (error instanceof Error) {\n errors.push(error)\n } else {\n throw error\n }\n }\n }\n }\n\n if (errors.length > 0) {\n throw new AggregateError(errors, 'FOO!')\n }\n }\n}\n\nexport const patchesRegistry = new PatchesRegistry()\n\ninterface DeepDescriptorMatch {\n owner: object\n descriptor: PropertyDescriptor\n}\n\n/**\n * Returns a property descriptor for the given property on the owner.\n * Walks down the prototype chain if the property does not exist on the owner.\n * Handy for getting a global property descriptor where `globalThis` is\n * replaced with a controlled class (e.g. ServiceWorkerGlobalScope).\n */\nexport function getDeepPropertyDescriptor(\n owner: Owner,\n key: keyof Owner\n): DeepDescriptorMatch | undefined {\n let currentOwner: Owner | null = owner\n let descriptor: PropertyDescriptor | undefined\n\n while (currentOwner) {\n descriptor = Object.getOwnPropertyDescriptor(currentOwner, key)\n\n if (descriptor) {\n return {\n owner: currentOwner,\n descriptor,\n }\n }\n\n currentOwner = Object.getPrototypeOf(currentOwner)\n }\n}\n","import { getDeepPropertyDescriptor } from './patchesRegistry'\n\n/**\n * Returns a boolean indicating whether the given global property\n * is defined and is configurable.\n */\nexport function hasConfigurableGlobal(\n propertyName: keyof typeof globalThis\n): boolean {\n const match = getDeepPropertyDescriptor(globalThis, propertyName)\n\n // The property is not set at all.\n if (typeof match === 'undefined') {\n return false\n }\n\n const { descriptor } = match\n\n // The property is set to a getter that returns undefined.\n if (\n typeof descriptor.get === 'function' &&\n typeof descriptor.get() === 'undefined'\n ) {\n return false\n }\n\n // The property is set to a value equal to undefined.\n if (typeof descriptor.get === 'undefined' && descriptor.value == null) {\n return false\n }\n\n if (typeof descriptor.set === 'undefined' && !descriptor.configurable) {\n console.error(\n `[MSW] Failed to apply interceptor: the global \\`${propertyName}\\` property is non-configurable. This is likely an issue with your environment. If you are using a framework, please open an issue about this in their repository.`\n )\n return false\n }\n\n return true\n}\n"],"mappings":";;;;AAEA,IAAM,kBAAN,MAAsB;CACpB,gCAAgB,IAAI,KAA2C;CAE/D,AAAO,WACL,OACA,KACA,cACY;EACZ,MAAM,oBAAoB,MAAKA,aAAc,IAAI,MAAM;AAEvD,4BACE,CAAC,mBAAmB,IAAI,IAAI,EAC5B,wCAAwC,OAAO,IAAI,CAAC,sBACrD;EAED,MAAM,QAAQ,0BAA0B,OAAO,IAAI;AAEnD,MAAI,OAAO,UAAU,aAAa;AAChC,WAAQ,KACN,wCAAwC,OAAO,IAAI,CAAC,wBACrD;AACD,gBAAa;;AAGf,MAAI,MAAM,WAAW,aACnB,QAAO,eAAe,OAAO,KAAK;GAChC,OAAO,aAAa,MAAM,KAAK;GAC/B,YAAY;GACZ,cAAc;GACf,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eAAe;AAGvB,KACE,OAAO,WAAW,QAAQ,cAC1B,OAAO,WAAW,KAAK,KAAK,YAE5B,QAAO;AAIT,KAAI,OAAO,WAAW,QAAQ,eAAe,WAAW,SAAS,KAC/D,QAAO;AAGT,KAAI,OAAO,WAAW,QAAQ,eAAe,CAAC,WAAW,cAAc;AACrE,UAAQ,MACN,mDAAmD,aAAa,oKACjE;AACD,SAAO;;AAGT,QAAO"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/index-BJ5E5aW-.d.cts b/node_modules/@mswjs/interceptors/lib/node/index-BJ5E5aW-.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..f3bb73a14e597b9f6d18df4ad7d2c1fdfe66ce92 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/index-BJ5E5aW-.d.cts @@ -0,0 +1,113 @@ +import { l as HttpRequestEventMap, r as Interceptor } from "./Interceptor-BsZ21ue0.cjs"; +import net from "node:net"; + +//#region src/interceptors/Socket/utils/normalizeSocketWriteArgs.d.ts +type WriteCallback = (error?: Error | null) => void; +//#endregion +//#region src/interceptors/Socket/MockSocket.d.ts +interface MockSocketOptions { + write: (chunk: Buffer | string, encoding: BufferEncoding | undefined, callback?: WriteCallback) => void; + read: (chunk: Buffer, encoding: BufferEncoding | undefined) => void; +} +declare class MockSocket extends net.Socket { + protected readonly options: MockSocketOptions; + connecting: boolean; + constructor(options: MockSocketOptions); + connect(): this; + write(...args: Array): boolean; + end(...args: Array): this; + push(chunk: any, encoding?: BufferEncoding): boolean; +} +//#endregion +//#region src/interceptors/ClientRequest/MockHttpSocket.d.ts +type HttpConnectionOptions = any; +type MockHttpSocketRequestCallback = (args: { + requestId: string; + request: Request; + socket: MockHttpSocket; +}) => void; +type MockHttpSocketResponseCallback = (args: { + requestId: string; + request: Request; + response: Response; + isMockedResponse: boolean; + socket: MockHttpSocket; +}) => Promise; +interface MockHttpSocketOptions { + connectionOptions: HttpConnectionOptions; + createConnection: () => net.Socket; + onRequest: MockHttpSocketRequestCallback; + onResponse: MockHttpSocketResponseCallback; +} +declare class MockHttpSocket extends MockSocket { + private connectionOptions; + private createConnection; + private baseUrl; + private onRequest; + private onResponse; + private responseListenersPromise?; + private requestRawHeadersBuffer; + private responseRawHeadersBuffer; + private writeBuffer; + private request?; + private requestParser; + private requestStream?; + private shouldKeepAlive?; + private socketState; + private responseParser; + private responseStream?; + private originalSocket?; + constructor(options: MockHttpSocketOptions); + emit(event: string | symbol, ...args: any[]): boolean; + destroy(error?: Error | undefined): this; + /** + * Establish this Socket connection as-is and pipe + * its data/events through this Socket. + */ + passthrough(): void; + /** + * Convert the given Fetch API `Response` instance to an + * HTTP message and push it to the socket. + */ + respondWith(response: Response): Promise; + /** + * Close this socket connection with the given error. + */ + errorWith(error?: Error): void; + private mockConnect; + private flushWriteBuffer; + /** + * This callback might be called when the request is "slow": + * - Request headers were fragmented across multiple TCP packages; + * - Request headers were too large to be processed in a single run + * (e.g. more than 30 request headers). + * @note This is called before request start. + */ + private onRequestHeaders; + private onRequestStart; + private onRequestBody; + private onRequestEnd; + /** + * This callback might be called when the response is "slow": + * - Response headers were fragmented across multiple TCP packages; + * - Response headers were too large to be processed in a single run + * (e.g. more than 30 response headers). + * @note This is called before response start. + */ + private onResponseHeaders; + private onResponseStart; + private onResponseBody; + private onResponseEnd; +} +//#endregion +//#region src/interceptors/ClientRequest/index.d.ts +declare class ClientRequestInterceptor extends Interceptor { + static symbol: symbol; + constructor(); + protected setup(): void; + private onRequest; + onResponse: MockHttpSocketResponseCallback; +} +//#endregion +export { ClientRequestInterceptor as t }; +//# sourceMappingURL=index-BJ5E5aW-.d.cts.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/index-DfoF45ih.d.mts b/node_modules/@mswjs/interceptors/lib/node/index-DfoF45ih.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..37e7daf7e5200ded62afa824ba829efbf24f9fc0 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/index-DfoF45ih.d.mts @@ -0,0 +1,113 @@ +import { l as HttpRequestEventMap, r as Interceptor } from "./Interceptor-soD-WpQO.mjs"; +import net from "node:net"; + +//#region src/interceptors/Socket/utils/normalizeSocketWriteArgs.d.ts +type WriteCallback = (error?: Error | null) => void; +//#endregion +//#region src/interceptors/Socket/MockSocket.d.ts +interface MockSocketOptions { + write: (chunk: Buffer | string, encoding: BufferEncoding | undefined, callback?: WriteCallback) => void; + read: (chunk: Buffer, encoding: BufferEncoding | undefined) => void; +} +declare class MockSocket extends net.Socket { + protected readonly options: MockSocketOptions; + connecting: boolean; + constructor(options: MockSocketOptions); + connect(): this; + write(...args: Array): boolean; + end(...args: Array): this; + push(chunk: any, encoding?: BufferEncoding): boolean; +} +//#endregion +//#region src/interceptors/ClientRequest/MockHttpSocket.d.ts +type HttpConnectionOptions = any; +type MockHttpSocketRequestCallback = (args: { + requestId: string; + request: Request; + socket: MockHttpSocket; +}) => void; +type MockHttpSocketResponseCallback = (args: { + requestId: string; + request: Request; + response: Response; + isMockedResponse: boolean; + socket: MockHttpSocket; +}) => Promise; +interface MockHttpSocketOptions { + connectionOptions: HttpConnectionOptions; + createConnection: () => net.Socket; + onRequest: MockHttpSocketRequestCallback; + onResponse: MockHttpSocketResponseCallback; +} +declare class MockHttpSocket extends MockSocket { + private connectionOptions; + private createConnection; + private baseUrl; + private onRequest; + private onResponse; + private responseListenersPromise?; + private requestRawHeadersBuffer; + private responseRawHeadersBuffer; + private writeBuffer; + private request?; + private requestParser; + private requestStream?; + private shouldKeepAlive?; + private socketState; + private responseParser; + private responseStream?; + private originalSocket?; + constructor(options: MockHttpSocketOptions); + emit(event: string | symbol, ...args: any[]): boolean; + destroy(error?: Error | undefined): this; + /** + * Establish this Socket connection as-is and pipe + * its data/events through this Socket. + */ + passthrough(): void; + /** + * Convert the given Fetch API `Response` instance to an + * HTTP message and push it to the socket. + */ + respondWith(response: Response): Promise; + /** + * Close this socket connection with the given error. + */ + errorWith(error?: Error): void; + private mockConnect; + private flushWriteBuffer; + /** + * This callback might be called when the request is "slow": + * - Request headers were fragmented across multiple TCP packages; + * - Request headers were too large to be processed in a single run + * (e.g. more than 30 request headers). + * @note This is called before request start. + */ + private onRequestHeaders; + private onRequestStart; + private onRequestBody; + private onRequestEnd; + /** + * This callback might be called when the response is "slow": + * - Response headers were fragmented across multiple TCP packages; + * - Response headers were too large to be processed in a single run + * (e.g. more than 30 response headers). + * @note This is called before response start. + */ + private onResponseHeaders; + private onResponseStart; + private onResponseBody; + private onResponseEnd; +} +//#endregion +//#region src/interceptors/ClientRequest/index.d.ts +declare class ClientRequestInterceptor extends Interceptor { + static symbol: symbol; + constructor(); + protected setup(): void; + private onRequest; + onResponse: MockHttpSocketResponseCallback; +} +//#endregion +export { ClientRequestInterceptor as t }; +//# sourceMappingURL=index-DfoF45ih.d.mts.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/index.cjs b/node_modules/@mswjs/interceptors/lib/node/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..f84b5faaa2cecfd33f25a490e21fc234490cee8f --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/index.cjs @@ -0,0 +1,53 @@ +const require_fetchUtils = require('./fetchUtils-umV5xXBy.cjs'); +const require_BatchInterceptor = require('./BatchInterceptor-BGhH8z1z.cjs'); +const require_bufferUtils = require('./bufferUtils-S5_-2eN4.cjs'); +const require_getRawRequest = require('./getRawRequest-B6znU6il.cjs'); + +//#region src/utils/getCleanUrl.ts +/** +* Removes query parameters and hashes from a given URL. +*/ +function getCleanUrl(url, isAbsolute = true) { + return [isAbsolute && url.origin, url.pathname].filter(Boolean).join(""); +} + +//#endregion +//#region src/utils/resolveWebSocketUrl.ts +/** +* Resolve potentially relative WebSocket URLs the same way +* the browser does (replace the protocol, use the origin, etc). +* +* @see https://websockets.spec.whatwg.org//#dom-websocket-websocket +*/ +function resolveWebSocketUrl(url) { + if (typeof url === "string") return resolveWebSocketUrl(new URL(url, typeof location !== "undefined" ? location.href : void 0)); + if (url.protocol === "http:") url.protocol = "ws:"; + else if (url.protocol === "https:") url.protocol = "wss:"; + if (url.protocol !== "ws:" && url.protocol !== "wss:") + /** + * @note These errors are modeled after the browser errors. + * The exact error messages aren't provided in the specification. + * Node.js uses more obscure error messages that I don't wish to replicate. + */ + throw new SyntaxError(`Failed to construct 'WebSocket': The URL's scheme must be either 'http', 'https', 'ws', or 'wss'. '${url.protocol}' is not allowed.`); + if (url.hash !== "") throw new SyntaxError(`Failed to construct 'WebSocket': The URL contains a fragment identifier ('${url.hash}'). Fragment identifiers are not allowed in WebSocket URLs.`); + return url.href; +} + +//#endregion +exports.BatchInterceptor = require_BatchInterceptor.BatchInterceptor; +exports.FetchRequest = require_fetchUtils.FetchRequest; +exports.FetchResponse = require_fetchUtils.FetchResponse; +exports.INTERNAL_REQUEST_ID_HEADER_NAME = require_fetchUtils.INTERNAL_REQUEST_ID_HEADER_NAME; +exports.Interceptor = require_fetchUtils.Interceptor; +exports.InterceptorReadyState = require_fetchUtils.InterceptorReadyState; +exports.RequestController = require_fetchUtils.RequestController; +exports.createRequestId = require_fetchUtils.createRequestId; +exports.decodeBuffer = require_bufferUtils.decodeBuffer; +exports.deleteGlobalSymbol = require_fetchUtils.deleteGlobalSymbol; +exports.encodeBuffer = require_bufferUtils.encodeBuffer; +exports.getCleanUrl = getCleanUrl; +exports.getGlobalSymbol = require_fetchUtils.getGlobalSymbol; +exports.getRawRequest = require_getRawRequest.getRawRequest; +exports.resolveWebSocketUrl = resolveWebSocketUrl; +//# sourceMappingURL=index.cjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/index.cjs.map b/node_modules/@mswjs/interceptors/lib/node/index.cjs.map new file mode 100644 index 0000000000000000000000000000000000000000..1dcafa3e9c017bfe5e47bbc43c7ad488ee4c7092 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/index.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.cjs","names":[],"sources":["../../src/utils/getCleanUrl.ts","../../src/utils/resolveWebSocketUrl.ts"],"sourcesContent":["/**\n * Removes query parameters and hashes from a given URL.\n */\nexport function getCleanUrl(url: URL, isAbsolute: boolean = true): string {\n return [isAbsolute && url.origin, url.pathname].filter(Boolean).join('')\n}\n","/**\n * Resolve potentially relative WebSocket URLs the same way\n * the browser does (replace the protocol, use the origin, etc).\n *\n * @see https://websockets.spec.whatwg.org//#dom-websocket-websocket\n */\nexport function resolveWebSocketUrl(url: string | URL): string {\n if (typeof url === 'string') {\n /**\n * @note Cast the string to a URL first so the parsing errors\n * are thrown as a part of the WebSocket constructor, not consumers.\n */\n const urlRecord = new URL(\n url,\n typeof location !== 'undefined' ? location.href : undefined\n )\n\n return resolveWebSocketUrl(urlRecord)\n }\n\n if (url.protocol === 'http:') {\n url.protocol = 'ws:'\n } else if (url.protocol === 'https:') {\n url.protocol = 'wss:'\n }\n\n if (url.protocol !== 'ws:' && url.protocol !== 'wss:') {\n /**\n * @note These errors are modeled after the browser errors.\n * The exact error messages aren't provided in the specification.\n * Node.js uses more obscure error messages that I don't wish to replicate.\n */\n throw new SyntaxError(\n `Failed to construct 'WebSocket': The URL's scheme must be either 'http', 'https', 'ws', or 'wss'. '${url.protocol}' is not allowed.`\n )\n }\n\n if (url.hash !== '') {\n throw new SyntaxError(\n `Failed to construct 'WebSocket': The URL contains a fragment identifier ('${url.hash}'). Fragment identifiers are not allowed in WebSocket URLs.`\n )\n }\n\n return url.href\n}\n"],"mappings":";;;;;;;;;AAGA,SAAgB,YAAY,KAAU,aAAsB,MAAc;AACxE,QAAO,CAAC,cAAc,IAAI,QAAQ,IAAI,SAAS,CAAC,OAAO,QAAQ,CAAC,KAAK,GAAG;;;;;;;;;;;ACE1E,SAAgB,oBAAoB,KAA2B;AAC7D,KAAI,OAAO,QAAQ,SAUjB,QAAO,oBALW,IAAI,IACpB,KACA,OAAO,aAAa,cAAc,SAAS,OAAO,OACnD,CAEoC;AAGvC,KAAI,IAAI,aAAa,QACnB,KAAI,WAAW;UACN,IAAI,aAAa,SAC1B,KAAI,WAAW;AAGjB,KAAI,IAAI,aAAa,SAAS,IAAI,aAAa;;;;;;AAM7C,OAAM,IAAI,YACR,sGAAsG,IAAI,SAAS,mBACpH;AAGH,KAAI,IAAI,SAAS,GACf,OAAM,IAAI,YACR,6EAA6E,IAAI,KAAK,6DACvF;AAGH,QAAO,IAAI"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/index.d.cts b/node_modules/@mswjs/interceptors/lib/node/index.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..934e88d89af07543baf607c4a709d19ca6d69b5c --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/index.d.cts @@ -0,0 +1,104 @@ +import { a as InterceptorReadyState, c as getGlobalSymbol, d as RequestController, f as RequestControllerSource, i as InterceptorEventMap, l as HttpRequestEventMap, n as INTERNAL_REQUEST_ID_HEADER_NAME, o as InterceptorSubscription, r as Interceptor, s as deleteGlobalSymbol, t as ExtractEventNames, u as RequestCredentials } from "./Interceptor-BsZ21ue0.cjs"; +import { n as BatchInterceptorOptions, r as ExtractEventMapType, t as BatchInterceptor } from "./BatchInterceptor-KKF8Q47I.cjs"; + +//#region src/createRequestId.d.ts + +/** + * Generate a random ID string to represent a request. + * @example + * createRequestId() + * // "f774b6c9c600f" + */ +declare function createRequestId(): string; +//#endregion +//#region src/utils/getCleanUrl.d.ts +/** + * Removes query parameters and hashes from a given URL. + */ +declare function getCleanUrl(url: URL, isAbsolute?: boolean): string; +//#endregion +//#region src/utils/bufferUtils.d.ts +declare function encodeBuffer(text: string): Uint8Array; +declare function decodeBuffer(buffer: ArrayBuffer, encoding?: string): string; +//#endregion +//#region src/utils/fetchUtils.d.ts +interface FetchRequestInit extends Omit { + mode?: RequestMode | 'websocket' | 'webtransport'; + duplex?: 'half' | 'full'; +} +declare class FetchRequest extends Request { + #private; + /** + * Check if the given request method is configurable. + * @see https://fetch.spec.whatwg.org/#methods + */ + static isConfigurableMethod(method: string): boolean; + static isMethodWithBody(method: string): boolean; + /** + * Check if the given request `mode` is configurable. + * @see https://fetch.spec.whatwg.org/#concept-request-mode + */ + static isConfigurableMode(mode: string): boolean; + constructor(input: URL | RequestInfo, init?: FetchRequestInit); +} +interface FetchResponseInit extends ResponseInit { + url?: string; +} +declare class FetchResponse extends Response { + /** + * Response status codes for responses that cannot have body. + * @see https://fetch.spec.whatwg.org/#statuses + */ + static readonly STATUS_CODES_WITHOUT_BODY: number[]; + static readonly STATUS_CODES_WITH_REDIRECT: number[]; + static isConfigurableStatusCode(status: number): boolean; + static isRedirectResponse(status: number): boolean; + /** + * Returns a boolean indicating whether the given response status + * code represents a response that can have a body. + */ + static isResponseWithBody(status: number): boolean; + static setStatus(status: number, response: Response): void; + static setUrl(url: string | undefined, response: Response): void; + /** + * Parses the given raw HTTP headers into a Fetch API `Headers` instance. + */ + static parseRawHeaders(rawHeaders: Array): Headers; + /** + * Safely clones the given `Response`. + * Coerces response clone exceptions into 500 mocked responses. + * Handy in the environments that introduce arbitrary response + * cloning restrictions, like "101 Switching Protocols" cloning + * in "miniflare". + */ + static clone(response: Response): Response; + constructor(body?: BodyInit | null, init?: FetchResponseInit); + clone(): Response; +} +//#endregion +//#region src/getRawRequest.d.ts +/** + * Returns a raw request instance associated with this request. + * + * @example + * interceptor.on('request', ({ request }) => { + * const rawRequest = getRawRequest(request) + * + * if (rawRequest instanceof http.ClientRequest) { + * console.log(rawRequest.rawHeaders) + * } + * }) + */ +declare function getRawRequest(request: Request): unknown | undefined; +//#endregion +//#region src/utils/resolveWebSocketUrl.d.ts +/** + * Resolve potentially relative WebSocket URLs the same way + * the browser does (replace the protocol, use the origin, etc). + * + * @see https://websockets.spec.whatwg.org//#dom-websocket-websocket + */ +declare function resolveWebSocketUrl(url: string | URL): string; +//#endregion +export { BatchInterceptor, BatchInterceptorOptions, ExtractEventMapType, ExtractEventNames, FetchRequest, FetchResponse, HttpRequestEventMap, INTERNAL_REQUEST_ID_HEADER_NAME, Interceptor, InterceptorEventMap, InterceptorReadyState, InterceptorSubscription, RequestController, type RequestControllerSource, RequestCredentials, createRequestId, decodeBuffer, deleteGlobalSymbol, encodeBuffer, getCleanUrl, getGlobalSymbol, getRawRequest, resolveWebSocketUrl }; +//# sourceMappingURL=index.d.cts.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/index.d.mts b/node_modules/@mswjs/interceptors/lib/node/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..4b1973c53f00a4bf139cf66a55d521a9280c1061 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/index.d.mts @@ -0,0 +1,104 @@ +import { a as InterceptorReadyState, c as getGlobalSymbol, d as RequestController, f as RequestControllerSource, i as InterceptorEventMap, l as HttpRequestEventMap, n as INTERNAL_REQUEST_ID_HEADER_NAME, o as InterceptorSubscription, r as Interceptor, s as deleteGlobalSymbol, t as ExtractEventNames, u as RequestCredentials } from "./Interceptor-soD-WpQO.mjs"; +import { n as BatchInterceptorOptions, r as ExtractEventMapType, t as BatchInterceptor } from "./BatchInterceptor-rSr-NH_H.mjs"; + +//#region src/createRequestId.d.ts + +/** + * Generate a random ID string to represent a request. + * @example + * createRequestId() + * // "f774b6c9c600f" + */ +declare function createRequestId(): string; +//#endregion +//#region src/utils/getCleanUrl.d.ts +/** + * Removes query parameters and hashes from a given URL. + */ +declare function getCleanUrl(url: URL, isAbsolute?: boolean): string; +//#endregion +//#region src/utils/bufferUtils.d.ts +declare function encodeBuffer(text: string): Uint8Array; +declare function decodeBuffer(buffer: ArrayBuffer, encoding?: string): string; +//#endregion +//#region src/utils/fetchUtils.d.ts +interface FetchRequestInit extends Omit { + mode?: RequestMode | 'websocket' | 'webtransport'; + duplex?: 'half' | 'full'; +} +declare class FetchRequest extends Request { + #private; + /** + * Check if the given request method is configurable. + * @see https://fetch.spec.whatwg.org/#methods + */ + static isConfigurableMethod(method: string): boolean; + static isMethodWithBody(method: string): boolean; + /** + * Check if the given request `mode` is configurable. + * @see https://fetch.spec.whatwg.org/#concept-request-mode + */ + static isConfigurableMode(mode: string): boolean; + constructor(input: URL | RequestInfo, init?: FetchRequestInit); +} +interface FetchResponseInit extends ResponseInit { + url?: string; +} +declare class FetchResponse extends Response { + /** + * Response status codes for responses that cannot have body. + * @see https://fetch.spec.whatwg.org/#statuses + */ + static readonly STATUS_CODES_WITHOUT_BODY: number[]; + static readonly STATUS_CODES_WITH_REDIRECT: number[]; + static isConfigurableStatusCode(status: number): boolean; + static isRedirectResponse(status: number): boolean; + /** + * Returns a boolean indicating whether the given response status + * code represents a response that can have a body. + */ + static isResponseWithBody(status: number): boolean; + static setStatus(status: number, response: Response): void; + static setUrl(url: string | undefined, response: Response): void; + /** + * Parses the given raw HTTP headers into a Fetch API `Headers` instance. + */ + static parseRawHeaders(rawHeaders: Array): Headers; + /** + * Safely clones the given `Response`. + * Coerces response clone exceptions into 500 mocked responses. + * Handy in the environments that introduce arbitrary response + * cloning restrictions, like "101 Switching Protocols" cloning + * in "miniflare". + */ + static clone(response: Response): Response; + constructor(body?: BodyInit | null, init?: FetchResponseInit); + clone(): Response; +} +//#endregion +//#region src/getRawRequest.d.ts +/** + * Returns a raw request instance associated with this request. + * + * @example + * interceptor.on('request', ({ request }) => { + * const rawRequest = getRawRequest(request) + * + * if (rawRequest instanceof http.ClientRequest) { + * console.log(rawRequest.rawHeaders) + * } + * }) + */ +declare function getRawRequest(request: Request): unknown | undefined; +//#endregion +//#region src/utils/resolveWebSocketUrl.d.ts +/** + * Resolve potentially relative WebSocket URLs the same way + * the browser does (replace the protocol, use the origin, etc). + * + * @see https://websockets.spec.whatwg.org//#dom-websocket-websocket + */ +declare function resolveWebSocketUrl(url: string | URL): string; +//#endregion +export { BatchInterceptor, BatchInterceptorOptions, ExtractEventMapType, ExtractEventNames, FetchRequest, FetchResponse, HttpRequestEventMap, INTERNAL_REQUEST_ID_HEADER_NAME, Interceptor, InterceptorEventMap, InterceptorReadyState, InterceptorSubscription, RequestController, type RequestControllerSource, RequestCredentials, createRequestId, decodeBuffer, deleteGlobalSymbol, encodeBuffer, getCleanUrl, getGlobalSymbol, getRawRequest, resolveWebSocketUrl }; +//# sourceMappingURL=index.d.mts.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/index.mjs b/node_modules/@mswjs/interceptors/lib/node/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..989f1f54b85fa77e621374ddbd8f3333644365c2 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/index.mjs @@ -0,0 +1,39 @@ +import { a as RequestController, c as Interceptor, d as getGlobalSymbol, i as createRequestId, l as InterceptorReadyState, n as FetchResponse, s as INTERNAL_REQUEST_ID_HEADER_NAME, t as FetchRequest, u as deleteGlobalSymbol } from "./fetchUtils-BKJ1XmiO.mjs"; +import { t as BatchInterceptor } from "./BatchInterceptor-C4-RX5rg.mjs"; +import { n as encodeBuffer, t as decodeBuffer } from "./bufferUtils-DxPxwff_.mjs"; +import { t as getRawRequest } from "./getRawRequest-C2-1urzA.mjs"; + +//#region src/utils/getCleanUrl.ts +/** +* Removes query parameters and hashes from a given URL. +*/ +function getCleanUrl(url, isAbsolute = true) { + return [isAbsolute && url.origin, url.pathname].filter(Boolean).join(""); +} + +//#endregion +//#region src/utils/resolveWebSocketUrl.ts +/** +* Resolve potentially relative WebSocket URLs the same way +* the browser does (replace the protocol, use the origin, etc). +* +* @see https://websockets.spec.whatwg.org//#dom-websocket-websocket +*/ +function resolveWebSocketUrl(url) { + if (typeof url === "string") return resolveWebSocketUrl(new URL(url, typeof location !== "undefined" ? location.href : void 0)); + if (url.protocol === "http:") url.protocol = "ws:"; + else if (url.protocol === "https:") url.protocol = "wss:"; + if (url.protocol !== "ws:" && url.protocol !== "wss:") + /** + * @note These errors are modeled after the browser errors. + * The exact error messages aren't provided in the specification. + * Node.js uses more obscure error messages that I don't wish to replicate. + */ + throw new SyntaxError(`Failed to construct 'WebSocket': The URL's scheme must be either 'http', 'https', 'ws', or 'wss'. '${url.protocol}' is not allowed.`); + if (url.hash !== "") throw new SyntaxError(`Failed to construct 'WebSocket': The URL contains a fragment identifier ('${url.hash}'). Fragment identifiers are not allowed in WebSocket URLs.`); + return url.href; +} + +//#endregion +export { BatchInterceptor, FetchRequest, FetchResponse, INTERNAL_REQUEST_ID_HEADER_NAME, Interceptor, InterceptorReadyState, RequestController, createRequestId, decodeBuffer, deleteGlobalSymbol, encodeBuffer, getCleanUrl, getGlobalSymbol, getRawRequest, resolveWebSocketUrl }; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/index.mjs.map b/node_modules/@mswjs/interceptors/lib/node/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..cfa93b41e4f0835549105b7915a42b8c719b0af3 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.mjs","names":[],"sources":["../../src/utils/getCleanUrl.ts","../../src/utils/resolveWebSocketUrl.ts"],"sourcesContent":["/**\n * Removes query parameters and hashes from a given URL.\n */\nexport function getCleanUrl(url: URL, isAbsolute: boolean = true): string {\n return [isAbsolute && url.origin, url.pathname].filter(Boolean).join('')\n}\n","/**\n * Resolve potentially relative WebSocket URLs the same way\n * the browser does (replace the protocol, use the origin, etc).\n *\n * @see https://websockets.spec.whatwg.org//#dom-websocket-websocket\n */\nexport function resolveWebSocketUrl(url: string | URL): string {\n if (typeof url === 'string') {\n /**\n * @note Cast the string to a URL first so the parsing errors\n * are thrown as a part of the WebSocket constructor, not consumers.\n */\n const urlRecord = new URL(\n url,\n typeof location !== 'undefined' ? location.href : undefined\n )\n\n return resolveWebSocketUrl(urlRecord)\n }\n\n if (url.protocol === 'http:') {\n url.protocol = 'ws:'\n } else if (url.protocol === 'https:') {\n url.protocol = 'wss:'\n }\n\n if (url.protocol !== 'ws:' && url.protocol !== 'wss:') {\n /**\n * @note These errors are modeled after the browser errors.\n * The exact error messages aren't provided in the specification.\n * Node.js uses more obscure error messages that I don't wish to replicate.\n */\n throw new SyntaxError(\n `Failed to construct 'WebSocket': The URL's scheme must be either 'http', 'https', 'ws', or 'wss'. '${url.protocol}' is not allowed.`\n )\n }\n\n if (url.hash !== '') {\n throw new SyntaxError(\n `Failed to construct 'WebSocket': The URL contains a fragment identifier ('${url.hash}'). Fragment identifiers are not allowed in WebSocket URLs.`\n )\n }\n\n return url.href\n}\n"],"mappings":";;;;;;;;;AAGA,SAAgB,YAAY,KAAU,aAAsB,MAAc;AACxE,QAAO,CAAC,cAAc,IAAI,QAAQ,IAAI,SAAS,CAAC,OAAO,QAAQ,CAAC,KAAK,GAAG;;;;;;;;;;;ACE1E,SAAgB,oBAAoB,KAA2B;AAC7D,KAAI,OAAO,QAAQ,SAUjB,QAAO,oBALW,IAAI,IACpB,KACA,OAAO,aAAa,cAAc,SAAS,OAAO,OACnD,CAEoC;AAGvC,KAAI,IAAI,aAAa,QACnB,KAAI,WAAW;UACN,IAAI,aAAa,SAC1B,KAAI,WAAW;AAGjB,KAAI,IAAI,aAAa,SAAS,IAAI,aAAa;;;;;;AAM7C,OAAM,IAAI,YACR,sGAAsG,IAAI,SAAS,mBACpH;AAGH,KAAI,IAAI,SAAS,GACf,OAAM,IAAI,YACR,6EAA6E,IAAI,KAAK,6DACvF;AAGH,QAAO,IAAI"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/interceptors/ClientRequest/index.cjs b/node_modules/@mswjs/interceptors/lib/node/interceptors/ClientRequest/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..ad500582eba9a289dacfe45143b80569a222496b --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/interceptors/ClientRequest/index.cjs @@ -0,0 +1,6 @@ +require('../../fetchUtils-umV5xXBy.cjs'); +const require_ClientRequest = require('../../ClientRequest-2loAH7xM.cjs'); +require('../../handleRequest-C-cKYjIh.cjs'); +require('../../node-DIKcnzhK.cjs'); + +exports.ClientRequestInterceptor = require_ClientRequest.ClientRequestInterceptor; \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/interceptors/ClientRequest/index.d.cts b/node_modules/@mswjs/interceptors/lib/node/interceptors/ClientRequest/index.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..5c9fa72734056d1fccfa34aa64c6add8779a6881 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/interceptors/ClientRequest/index.d.cts @@ -0,0 +1,2 @@ +import { t as ClientRequestInterceptor } from "../../index-BJ5E5aW-.cjs"; +export { ClientRequestInterceptor }; \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/interceptors/ClientRequest/index.d.mts b/node_modules/@mswjs/interceptors/lib/node/interceptors/ClientRequest/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..eede001dfc8330134228b05d7705068aa3e5519d --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/interceptors/ClientRequest/index.d.mts @@ -0,0 +1,3 @@ +import "../../Interceptor-soD-WpQO.mjs"; +import { t as ClientRequestInterceptor } from "../../index-DfoF45ih.mjs"; +export { ClientRequestInterceptor }; \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/interceptors/ClientRequest/index.mjs b/node_modules/@mswjs/interceptors/lib/node/interceptors/ClientRequest/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..11decc167bbadce56a7d91932e3036df8d145ebd --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/interceptors/ClientRequest/index.mjs @@ -0,0 +1,6 @@ +import "../../fetchUtils-BKJ1XmiO.mjs"; +import { t as ClientRequestInterceptor } from "../../ClientRequest-DGhBX21V.mjs"; +import "../../handleRequest-FIQv5pwH.mjs"; +import "../../node-lsdNwZEW.mjs"; + +export { ClientRequestInterceptor }; \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/interceptors/XMLHttpRequest/index.cjs b/node_modules/@mswjs/interceptors/lib/node/interceptors/XMLHttpRequest/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..3fb16f5618c6d43b2a30a474efe5e6e692b1fe6a --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/interceptors/XMLHttpRequest/index.cjs @@ -0,0 +1,7 @@ +require('../../fetchUtils-umV5xXBy.cjs'); +require('../../bufferUtils-S5_-2eN4.cjs'); +require('../../handleRequest-C-cKYjIh.cjs'); +const require_XMLHttpRequest = require('../../XMLHttpRequest-BtDNZipW.cjs'); +require('../../hasConfigurableGlobal-MjY06_Ok.cjs'); + +exports.XMLHttpRequestInterceptor = require_XMLHttpRequest.XMLHttpRequestInterceptor; \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/interceptors/XMLHttpRequest/index.d.cts b/node_modules/@mswjs/interceptors/lib/node/interceptors/XMLHttpRequest/index.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..b15fccea6f4032926218b784ad3eb19cbe462246 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/interceptors/XMLHttpRequest/index.d.cts @@ -0,0 +1,14 @@ +import { l as HttpRequestEventMap, r as Interceptor } from "../../Interceptor-BsZ21ue0.cjs"; +import { Emitter } from "strict-event-emitter"; + +//#region src/interceptors/XMLHttpRequest/index.d.ts +type XMLHttpRequestEmitter = Emitter; +declare class XMLHttpRequestInterceptor extends Interceptor { + static symbol: symbol; + constructor(); + protected checkEnvironment(): boolean; + protected setup(): void; +} +//#endregion +export { XMLHttpRequestEmitter, XMLHttpRequestInterceptor }; +//# sourceMappingURL=index.d.cts.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/interceptors/XMLHttpRequest/index.d.mts b/node_modules/@mswjs/interceptors/lib/node/interceptors/XMLHttpRequest/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..0fbec47a7e7f3b6aab884eacce5784f4d8162202 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/interceptors/XMLHttpRequest/index.d.mts @@ -0,0 +1,14 @@ +import { l as HttpRequestEventMap, r as Interceptor } from "../../Interceptor-soD-WpQO.mjs"; +import { Emitter } from "strict-event-emitter"; + +//#region src/interceptors/XMLHttpRequest/index.d.ts +type XMLHttpRequestEmitter = Emitter; +declare class XMLHttpRequestInterceptor extends Interceptor { + static symbol: symbol; + constructor(); + protected checkEnvironment(): boolean; + protected setup(): void; +} +//#endregion +export { XMLHttpRequestEmitter, XMLHttpRequestInterceptor }; +//# sourceMappingURL=index.d.mts.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/interceptors/XMLHttpRequest/index.mjs b/node_modules/@mswjs/interceptors/lib/node/interceptors/XMLHttpRequest/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..4d4567cf6fe349eb1dec7ea14b58dace0971d7c1 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/interceptors/XMLHttpRequest/index.mjs @@ -0,0 +1,7 @@ +import "../../fetchUtils-BKJ1XmiO.mjs"; +import "../../bufferUtils-DxPxwff_.mjs"; +import "../../handleRequest-FIQv5pwH.mjs"; +import { t as XMLHttpRequestInterceptor } from "../../XMLHttpRequest-Dw6Wm-UU.mjs"; +import "../../hasConfigurableGlobal-BiTmog1u.mjs"; + +export { XMLHttpRequestInterceptor }; \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/interceptors/fetch/index.cjs b/node_modules/@mswjs/interceptors/lib/node/interceptors/fetch/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..ffe1bba87ee205595987014333f5bdb2cdb3145c --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/interceptors/fetch/index.cjs @@ -0,0 +1,6 @@ +require('../../fetchUtils-umV5xXBy.cjs'); +require('../../handleRequest-C-cKYjIh.cjs'); +require('../../hasConfigurableGlobal-MjY06_Ok.cjs'); +const require_fetch = require('../../fetch-D2ClLNN-.cjs'); + +exports.FetchInterceptor = require_fetch.FetchInterceptor; \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/interceptors/fetch/index.d.cts b/node_modules/@mswjs/interceptors/lib/node/interceptors/fetch/index.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..feffc4c881483beeac25bfd965a6c7145103f703 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/interceptors/fetch/index.d.cts @@ -0,0 +1,12 @@ +import { l as HttpRequestEventMap, r as Interceptor } from "../../Interceptor-BsZ21ue0.cjs"; + +//#region src/interceptors/fetch/index.d.ts +declare class FetchInterceptor extends Interceptor { + static symbol: symbol; + constructor(); + protected checkEnvironment(): boolean; + protected setup(): Promise; +} +//#endregion +export { FetchInterceptor }; +//# sourceMappingURL=index.d.cts.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/interceptors/fetch/index.d.mts b/node_modules/@mswjs/interceptors/lib/node/interceptors/fetch/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..cf39d783769127926568f08af63f0b31f3e1dc12 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/interceptors/fetch/index.d.mts @@ -0,0 +1,12 @@ +import { l as HttpRequestEventMap, r as Interceptor } from "../../Interceptor-soD-WpQO.mjs"; + +//#region src/interceptors/fetch/index.d.ts +declare class FetchInterceptor extends Interceptor { + static symbol: symbol; + constructor(); + protected checkEnvironment(): boolean; + protected setup(): Promise; +} +//#endregion +export { FetchInterceptor }; +//# sourceMappingURL=index.d.mts.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/interceptors/fetch/index.mjs b/node_modules/@mswjs/interceptors/lib/node/interceptors/fetch/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..636366cd5770f96088b9c3e0bd8e9039402536d3 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/interceptors/fetch/index.mjs @@ -0,0 +1,6 @@ +import "../../fetchUtils-BKJ1XmiO.mjs"; +import "../../handleRequest-FIQv5pwH.mjs"; +import "../../hasConfigurableGlobal-BiTmog1u.mjs"; +import { t as FetchInterceptor } from "../../fetch-CaC3rGEu.mjs"; + +export { FetchInterceptor }; \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/node-DIKcnzhK.cjs b/node_modules/@mswjs/interceptors/lib/node/node-DIKcnzhK.cjs new file mode 100644 index 0000000000000000000000000000000000000000..e1564b9349e6011e30f86acc152ed38cf6c73736 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/node-DIKcnzhK.cjs @@ -0,0 +1,39 @@ +const require_chunk = require('./chunk-CbDLau6x.cjs'); +const require_getRawRequest = require('./getRawRequest-B6znU6il.cjs'); +let outvariant = require("outvariant"); +let node_http = require("node:http"); +let node_stream = require("node:stream"); + +//#region src/utils/node/index.ts +const kRawRequestBodyStream = Symbol("kRawRequestBodyStream"); +/** +* Returns the request body stream of the given request. +* @note This is only relevant in the context of `http.ClientRequest`. +* This function will throw if the given `request` wasn't created based on +* the `http.ClientRequest` instance. +* You must rely on the web stream consumers for other request clients. +*/ +function getClientRequestBodyStream(request) { + (0, outvariant.invariant)(require_getRawRequest.getRawRequest(request) instanceof node_http.ClientRequest, `Failed to retrieve raw request body stream: request is not an instance of "http.ClientRequest". Note that you can only use the "getClientRequestBodyStream" function with the requests issued by "http.clientRequest".`); + const requestBodyStream = Reflect.get(request, kRawRequestBodyStream); + (0, outvariant.invariant)(requestBodyStream instanceof node_stream.Readable, "Failed to retrieve raw request body stream: corrupted stream (%s)", typeof requestBodyStream); + return requestBodyStream; +} +function setRawRequestBodyStream(request, stream) { + Reflect.set(request, kRawRequestBodyStream, stream); +} + +//#endregion +Object.defineProperty(exports, 'getClientRequestBodyStream', { + enumerable: true, + get: function () { + return getClientRequestBodyStream; + } +}); +Object.defineProperty(exports, 'setRawRequestBodyStream', { + enumerable: true, + get: function () { + return setRawRequestBodyStream; + } +}); +//# sourceMappingURL=node-DIKcnzhK.cjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/node-DIKcnzhK.cjs.map b/node_modules/@mswjs/interceptors/lib/node/node-DIKcnzhK.cjs.map new file mode 100644 index 0000000000000000000000000000000000000000..06c39c3c8fcbf89d98af3a48d49713f0159c374e --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/node-DIKcnzhK.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"node-DIKcnzhK.cjs","names":["getRawRequest","ClientRequest","Readable"],"sources":["../../src/utils/node/index.ts"],"sourcesContent":["import { ClientRequest } from 'node:http'\nimport { Readable } from 'node:stream'\nimport { invariant } from 'outvariant'\nimport { getRawRequest } from '../../getRawRequest'\n\nconst kRawRequestBodyStream = Symbol('kRawRequestBodyStream')\n\n/**\n * Returns the request body stream of the given request.\n * @note This is only relevant in the context of `http.ClientRequest`.\n * This function will throw if the given `request` wasn't created based on\n * the `http.ClientRequest` instance.\n * You must rely on the web stream consumers for other request clients.\n */\nexport function getClientRequestBodyStream(request: Request): Readable {\n const rawRequest = getRawRequest(request)\n\n invariant(\n rawRequest instanceof ClientRequest,\n `Failed to retrieve raw request body stream: request is not an instance of \"http.ClientRequest\". Note that you can only use the \"getClientRequestBodyStream\" function with the requests issued by \"http.clientRequest\".`\n )\n\n const requestBodyStream = Reflect.get(request, kRawRequestBodyStream)\n\n invariant(\n requestBodyStream instanceof Readable,\n 'Failed to retrieve raw request body stream: corrupted stream (%s)',\n typeof requestBodyStream\n )\n\n return requestBodyStream\n}\n\nexport function setRawRequestBodyStream(\n request: Request,\n stream: Readable\n): void {\n Reflect.set(request, kRawRequestBodyStream, stream)\n}\n"],"mappings":";;;;;;;AAKA,MAAM,wBAAwB,OAAO,wBAAwB;;;;;;;;AAS7D,SAAgB,2BAA2B,SAA4B;AAGrE,2BAFmBA,oCAAc,QAAQ,YAGjBC,yBACtB,yNACD;CAED,MAAM,oBAAoB,QAAQ,IAAI,SAAS,sBAAsB;AAErE,2BACE,6BAA6BC,sBAC7B,qEACA,OAAO,kBACR;AAED,QAAO;;AAGT,SAAgB,wBACd,SACA,QACM;AACN,SAAQ,IAAI,SAAS,uBAAuB,OAAO"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/node-lsdNwZEW.mjs b/node_modules/@mswjs/interceptors/lib/node/node-lsdNwZEW.mjs new file mode 100644 index 0000000000000000000000000000000000000000..2fe4dcdbaff0342584dfc4fcc3f6fdd7ef005c5a --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/node-lsdNwZEW.mjs @@ -0,0 +1,27 @@ +import { t as getRawRequest } from "./getRawRequest-C2-1urzA.mjs"; +import { invariant } from "outvariant"; +import { ClientRequest } from "node:http"; +import { Readable } from "node:stream"; + +//#region src/utils/node/index.ts +const kRawRequestBodyStream = Symbol("kRawRequestBodyStream"); +/** +* Returns the request body stream of the given request. +* @note This is only relevant in the context of `http.ClientRequest`. +* This function will throw if the given `request` wasn't created based on +* the `http.ClientRequest` instance. +* You must rely on the web stream consumers for other request clients. +*/ +function getClientRequestBodyStream(request) { + invariant(getRawRequest(request) instanceof ClientRequest, `Failed to retrieve raw request body stream: request is not an instance of "http.ClientRequest". Note that you can only use the "getClientRequestBodyStream" function with the requests issued by "http.clientRequest".`); + const requestBodyStream = Reflect.get(request, kRawRequestBodyStream); + invariant(requestBodyStream instanceof Readable, "Failed to retrieve raw request body stream: corrupted stream (%s)", typeof requestBodyStream); + return requestBodyStream; +} +function setRawRequestBodyStream(request, stream) { + Reflect.set(request, kRawRequestBodyStream, stream); +} + +//#endregion +export { setRawRequestBodyStream as n, getClientRequestBodyStream as t }; +//# sourceMappingURL=node-lsdNwZEW.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/node-lsdNwZEW.mjs.map b/node_modules/@mswjs/interceptors/lib/node/node-lsdNwZEW.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..f7a108a3c4cdc01fcd61e363d7850950c0adf0b8 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/node-lsdNwZEW.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"node-lsdNwZEW.mjs","names":[],"sources":["../../src/utils/node/index.ts"],"sourcesContent":["import { ClientRequest } from 'node:http'\nimport { Readable } from 'node:stream'\nimport { invariant } from 'outvariant'\nimport { getRawRequest } from '../../getRawRequest'\n\nconst kRawRequestBodyStream = Symbol('kRawRequestBodyStream')\n\n/**\n * Returns the request body stream of the given request.\n * @note This is only relevant in the context of `http.ClientRequest`.\n * This function will throw if the given `request` wasn't created based on\n * the `http.ClientRequest` instance.\n * You must rely on the web stream consumers for other request clients.\n */\nexport function getClientRequestBodyStream(request: Request): Readable {\n const rawRequest = getRawRequest(request)\n\n invariant(\n rawRequest instanceof ClientRequest,\n `Failed to retrieve raw request body stream: request is not an instance of \"http.ClientRequest\". Note that you can only use the \"getClientRequestBodyStream\" function with the requests issued by \"http.clientRequest\".`\n )\n\n const requestBodyStream = Reflect.get(request, kRawRequestBodyStream)\n\n invariant(\n requestBodyStream instanceof Readable,\n 'Failed to retrieve raw request body stream: corrupted stream (%s)',\n typeof requestBodyStream\n )\n\n return requestBodyStream\n}\n\nexport function setRawRequestBodyStream(\n request: Request,\n stream: Readable\n): void {\n Reflect.set(request, kRawRequestBodyStream, stream)\n}\n"],"mappings":";;;;;;AAKA,MAAM,wBAAwB,OAAO,wBAAwB;;;;;;;;AAS7D,SAAgB,2BAA2B,SAA4B;AAGrE,WAFmB,cAAc,QAAQ,YAGjB,eACtB,yNACD;CAED,MAAM,oBAAoB,QAAQ,IAAI,SAAS,sBAAsB;AAErE,WACE,6BAA6B,UAC7B,qEACA,OAAO,kBACR;AAED,QAAO;;AAGT,SAAgB,wBACd,SACA,QACM;AACN,SAAQ,IAAI,SAAS,uBAAuB,OAAO"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/presets/node.cjs b/node_modules/@mswjs/interceptors/lib/node/presets/node.cjs new file mode 100644 index 0000000000000000000000000000000000000000..10803f823d444f82bc8f7c22ae8c583b24e5e199 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/presets/node.cjs @@ -0,0 +1,23 @@ +require('../fetchUtils-umV5xXBy.cjs'); +require('../bufferUtils-S5_-2eN4.cjs'); +const require_ClientRequest = require('../ClientRequest-2loAH7xM.cjs'); +require('../handleRequest-C-cKYjIh.cjs'); +require('../node-DIKcnzhK.cjs'); +const require_XMLHttpRequest = require('../XMLHttpRequest-BtDNZipW.cjs'); +require('../hasConfigurableGlobal-MjY06_Ok.cjs'); +const require_fetch = require('../fetch-D2ClLNN-.cjs'); + +//#region src/presets/node.ts +/** +* The default preset provisions the interception of requests +* regardless of their type (http/https/XMLHttpRequest). +*/ +var node_default = [ + new require_ClientRequest.ClientRequestInterceptor(), + new require_XMLHttpRequest.XMLHttpRequestInterceptor(), + new require_fetch.FetchInterceptor() +]; + +//#endregion +module.exports = node_default; +//# sourceMappingURL=node.cjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/presets/node.cjs.map b/node_modules/@mswjs/interceptors/lib/node/presets/node.cjs.map new file mode 100644 index 0000000000000000000000000000000000000000..f437a8ecaaeb98a27055d9ae29d52e82a1a8c216 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/presets/node.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"node.cjs","names":["ClientRequestInterceptor","XMLHttpRequestInterceptor","FetchInterceptor"],"sources":["../../../src/presets/node.ts"],"sourcesContent":["import { ClientRequestInterceptor } from '../interceptors/ClientRequest'\nimport { XMLHttpRequestInterceptor } from '../interceptors/XMLHttpRequest'\nimport { FetchInterceptor } from '../interceptors/fetch'\n\n/**\n * The default preset provisions the interception of requests\n * regardless of their type (http/https/XMLHttpRequest).\n */\nexport default [\n new ClientRequestInterceptor(),\n new XMLHttpRequestInterceptor(),\n new FetchInterceptor(),\n] as const\n"],"mappings":";;;;;;;;;;;;;;AAQA,mBAAe;CACb,IAAIA,gDAA0B;CAC9B,IAAIC,kDAA2B;CAC/B,IAAIC,gCAAkB;CACvB"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/presets/node.d.cts b/node_modules/@mswjs/interceptors/lib/node/presets/node.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..e29131aab0de3c2c7c59aecc241dc134c6dbfeda --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/presets/node.d.cts @@ -0,0 +1,13 @@ +import { t as ClientRequestInterceptor } from "../index-BJ5E5aW-.cjs"; +import { XMLHttpRequestInterceptor } from "../interceptors/XMLHttpRequest/index.cjs"; +import { FetchInterceptor } from "../interceptors/fetch/index.cjs"; + +//#region src/presets/node.d.ts + +/** + * The default preset provisions the interception of requests + * regardless of their type (http/https/XMLHttpRequest). + */ +declare const _default: readonly [ClientRequestInterceptor, XMLHttpRequestInterceptor, FetchInterceptor]; +export = _default; +//# sourceMappingURL=node.d.cts.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/presets/node.d.mts b/node_modules/@mswjs/interceptors/lib/node/presets/node.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..0d094bd5e33cedffff243b0ceff072b2c77442c0 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/presets/node.d.mts @@ -0,0 +1,15 @@ +import "../Interceptor-soD-WpQO.mjs"; +import { t as ClientRequestInterceptor } from "../index-DfoF45ih.mjs"; +import { XMLHttpRequestInterceptor } from "../interceptors/XMLHttpRequest/index.mjs"; +import { FetchInterceptor } from "../interceptors/fetch/index.mjs"; + +//#region src/presets/node.d.ts + +/** + * The default preset provisions the interception of requests + * regardless of their type (http/https/XMLHttpRequest). + */ +declare const _default: readonly [ClientRequestInterceptor, XMLHttpRequestInterceptor, FetchInterceptor]; +//#endregion +export { _default as default }; +//# sourceMappingURL=node.d.mts.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/presets/node.mjs b/node_modules/@mswjs/interceptors/lib/node/presets/node.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ec7750ad50503b582f098f4a5dd708d44ee5010a --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/presets/node.mjs @@ -0,0 +1,23 @@ +import "../fetchUtils-BKJ1XmiO.mjs"; +import "../bufferUtils-DxPxwff_.mjs"; +import { t as ClientRequestInterceptor } from "../ClientRequest-DGhBX21V.mjs"; +import "../handleRequest-FIQv5pwH.mjs"; +import "../node-lsdNwZEW.mjs"; +import { t as XMLHttpRequestInterceptor } from "../XMLHttpRequest-Dw6Wm-UU.mjs"; +import "../hasConfigurableGlobal-BiTmog1u.mjs"; +import { t as FetchInterceptor } from "../fetch-CaC3rGEu.mjs"; + +//#region src/presets/node.ts +/** +* The default preset provisions the interception of requests +* regardless of their type (http/https/XMLHttpRequest). +*/ +var node_default = [ + new ClientRequestInterceptor(), + new XMLHttpRequestInterceptor(), + new FetchInterceptor() +]; + +//#endregion +export { node_default as default }; +//# sourceMappingURL=node.mjs.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/presets/node.mjs.map b/node_modules/@mswjs/interceptors/lib/node/presets/node.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..e3e775873e51768f3e7d6cea3aa954bcd65ec273 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/presets/node.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"node.mjs","names":[],"sources":["../../../src/presets/node.ts"],"sourcesContent":["import { ClientRequestInterceptor } from '../interceptors/ClientRequest'\nimport { XMLHttpRequestInterceptor } from '../interceptors/XMLHttpRequest'\nimport { FetchInterceptor } from '../interceptors/fetch'\n\n/**\n * The default preset provisions the interception of requests\n * regardless of their type (http/https/XMLHttpRequest).\n */\nexport default [\n new ClientRequestInterceptor(),\n new XMLHttpRequestInterceptor(),\n new FetchInterceptor(),\n] as const\n"],"mappings":";;;;;;;;;;;;;;AAQA,mBAAe;CACb,IAAI,0BAA0B;CAC9B,IAAI,2BAA2B;CAC/B,IAAI,kBAAkB;CACvB"} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/utils/node/index.cjs b/node_modules/@mswjs/interceptors/lib/node/utils/node/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..ac3e108b8975f73421ac4d15df3d18dd7eb30b8c --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/utils/node/index.cjs @@ -0,0 +1,4 @@ +const require_node = require('../../node-DIKcnzhK.cjs'); + +exports.getClientRequestBodyStream = require_node.getClientRequestBodyStream; +exports.setRawRequestBodyStream = require_node.setRawRequestBodyStream; \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/utils/node/index.d.cts b/node_modules/@mswjs/interceptors/lib/node/utils/node/index.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..2990c2c7451f827aae24234da36cb1824d33cbfa --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/utils/node/index.d.cts @@ -0,0 +1,16 @@ +import { Readable } from "node:stream"; + +//#region src/utils/node/index.d.ts + +/** + * Returns the request body stream of the given request. + * @note This is only relevant in the context of `http.ClientRequest`. + * This function will throw if the given `request` wasn't created based on + * the `http.ClientRequest` instance. + * You must rely on the web stream consumers for other request clients. + */ +declare function getClientRequestBodyStream(request: Request): Readable; +declare function setRawRequestBodyStream(request: Request, stream: Readable): void; +//#endregion +export { getClientRequestBodyStream, setRawRequestBodyStream }; +//# sourceMappingURL=index.d.cts.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/utils/node/index.d.mts b/node_modules/@mswjs/interceptors/lib/node/utils/node/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..5f6714f8c62c28a2eef9c4b674d96e41a566df9e --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/utils/node/index.d.mts @@ -0,0 +1,16 @@ +import { Readable } from "node:stream"; + +//#region src/utils/node/index.d.ts + +/** + * Returns the request body stream of the given request. + * @note This is only relevant in the context of `http.ClientRequest`. + * This function will throw if the given `request` wasn't created based on + * the `http.ClientRequest` instance. + * You must rely on the web stream consumers for other request clients. + */ +declare function getClientRequestBodyStream(request: Request): Readable; +declare function setRawRequestBodyStream(request: Request, stream: Readable): void; +//#endregion +export { getClientRequestBodyStream, setRawRequestBodyStream }; +//# sourceMappingURL=index.d.mts.map \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/lib/node/utils/node/index.mjs b/node_modules/@mswjs/interceptors/lib/node/utils/node/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6a7ce1e10abf8fa1e4bcedc7f27d3e16f151e227 --- /dev/null +++ b/node_modules/@mswjs/interceptors/lib/node/utils/node/index.mjs @@ -0,0 +1,3 @@ +import { n as setRawRequestBodyStream, t as getClientRequestBodyStream } from "../../node-lsdNwZEW.mjs"; + +export { getClientRequestBodyStream, setRawRequestBodyStream }; \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/package.json b/node_modules/@mswjs/interceptors/package.json new file mode 100644 index 0000000000000000000000000000000000000000..0530c80a03558a49b8a6855a0f452236ffe389df --- /dev/null +++ b/node_modules/@mswjs/interceptors/package.json @@ -0,0 +1,186 @@ +{ + "type": "commonjs", + "name": "@mswjs/interceptors", + "description": "Low-level HTTP/HTTPS/XHR/fetch request interception library.", + "version": "0.41.9", + "main": "./lib/node/index.cjs", + "module": "./lib/node/index.mjs", + "types": "./lib/node/index.d.cts", + "exports": { + ".": { + "browser": { + "import": "./lib/browser/index.mjs", + "default": "./lib/browser/index.cjs" + }, + "import": "./lib/node/index.mjs", + "default": "./lib/node/index.cjs" + }, + "./ClientRequest": { + "node": { + "require": "./lib/node/interceptors/ClientRequest/index.cjs", + "import": "./lib/node/interceptors/ClientRequest/index.mjs" + }, + "browser": null, + "require": "./lib/node/interceptors/ClientRequest/index.cjs", + "import": "./lib/node/interceptors/ClientRequest/index.mjs", + "default": "./lib/node/interceptors/ClientRequest/index.cjs" + }, + "./XMLHttpRequest": { + "browser": "./lib/browser/interceptors/XMLHttpRequest/index.mjs", + "require": "./lib/node/interceptors/XMLHttpRequest/index.cjs", + "import": "./lib/node/interceptors/XMLHttpRequest/index.mjs", + "default": "./lib/node/interceptors/XMLHttpRequest/index.cjs" + }, + "./fetch": { + "browser": "./lib/browser/interceptors/fetch/index.mjs", + "require": "./lib/node/interceptors/fetch/index.cjs", + "import": "./lib/node/interceptors/fetch/index.mjs", + "default": "./lib/node/interceptors/fetch/index.cjs" + }, + "./WebSocket": { + "require": "./lib/browser/interceptors/WebSocket/index.cjs", + "import": "./lib/browser/interceptors/WebSocket/index.mjs", + "default": "./lib/browser/interceptors/WebSocket/index.cjs" + }, + "./RemoteHttpInterceptor": { + "node": { + "require": "./lib/node/RemoteHttpInterceptor.cjs", + "import": "./lib/node/RemoteHttpInterceptor.mjs" + }, + "browser": null, + "require": "./lib/node/RemoteHttpInterceptor.cjs", + "import": "./lib/node/RemoteHttpInterceptor.mjs", + "default": "./lib/node/RemoteHttpInterceptor.cjs" + }, + "./presets/node": { + "node": { + "require": "./lib/node/presets/node.cjs", + "import": "./lib/node/presets/node.mjs" + }, + "browser": null, + "require": "./lib/node/presets/node.cjs", + "import": "./lib/node/presets/node.mjs", + "default": "./lib/node/presets/node.cjs" + }, + "./presets/browser": { + "browser": "./lib/browser/presets/browser.mjs", + "node": null + }, + "./utils/node": { + "node": { + "require": "./lib/node/utils/node/index.cjs", + "import": "./lib/node/utils/node/index.mjs" + }, + "browser": null, + "require": "./lib/node/utils/node/index.cjs", + "import": "./lib/node/utils/node/index.mjs", + "default": "./lib/node/utils/node/index.cjs" + } + }, + "author": "Artem Zakharchenko", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "files": [ + "lib", + "README.md", + "src", + "ClientRequest", + "fetch", + "RemoteHttpInterceptor", + "XMLHttpRequest", + "WebSocket", + "presets" + ], + "repository": { + "url": "https://github.com/mswjs/interceptors" + }, + "devDependencies": { + "@commitlint/cli": "^19.7.1", + "@commitlint/config-conventional": "^19.7.1", + "@open-draft/test-server": "^0.5.1", + "@ossjs/release": "^0.10.1", + "@playwright/test": "^1.51.0", + "@types/cors": "^2.8.12", + "@types/express": "^5.0.0", + "@types/express-fileupload": "^1.5.0", + "@types/follow-redirects": "^1.14.1", + "@types/node": "^22.13.9", + "@types/node-fetch": "2.6.12", + "@types/superagent": "^8.1.9", + "@types/supertest": "^6.0.2", + "@types/ws": "^8.18.0", + "axios": "^1.8.2", + "body-parser": "^1.19.0", + "commitizen": "^4.2.4", + "cors": "^2.8.5", + "cross-env": "^7.0.3", + "cz-conventional-changelog": "3.3.0", + "engine.io-parser": "^5.2.1", + "express": "^4.21.2", + "express-fileupload": "^1.5.1", + "express-rate-limit": "^7.5.0", + "follow-redirects": "^1.15.1", + "got": "^14.4.6", + "happy-dom": "^17.3.0", + "jsdom": "^26.1.0", + "node-fetch": "3.3.2", + "simple-git-hooks": "^2.7.0", + "socket.io": "^4.7.4", + "socket.io-client": "^4.7.4", + "socket.io-parser": "^4.2.4", + "superagent": "^10.1.1", + "supertest": "^7.0.0", + "tsdown": "^0.18.1", + "typescript": "^5.8.2", + "undici": "^7.4.0", + "vitest": "^3.0.8", + "vitest-environment-miniflare": "^2.14.1", + "wait-for-expect": "^3.0.2", + "web-encoding": "^1.1.5", + "webpack": "^5.105.0", + "webpack-http-server": "^0.5.0", + "ws": "^8.18.1" + }, + "dependencies": { + "@open-draft/deferred-promise": "^2.2.0", + "@open-draft/logger": "^0.3.0", + "@open-draft/until": "^2.0.0", + "is-node-process": "^1.2.0", + "outvariant": "^1.4.3", + "strict-event-emitter": "^0.5.1" + }, + "resolutions": { + "memfs": "^3.4.13" + }, + "keywords": [ + "request", + "intercept", + "http", + "https", + "xmlhttprequest", + "xhr", + "fetch", + "low-level", + "mock", + "spy", + "testing" + ], + "config": { + "commitizen": { + "path": "./node_modules/cz-conventional-changelog" + } + }, + "scripts": { + "start": "tsdown --watch", + "test": "pnpm test:unit && pnpm test:integration", + "test:unit": "vitest", + "test:integration": "pnpm test:node && pnpm test:browser", + "test:node": "vitest -c test/vitest.config.js", + "test:browser": "pnpm playwright test -c test/playwright.config.ts", + "test:nock": "./test/third-party/nock.sh", + "build": "tsdown", + "release": "release publish" + } +} \ No newline at end of file diff --git a/node_modules/@mswjs/interceptors/presets/browser/package.json b/node_modules/@mswjs/interceptors/presets/browser/package.json new file mode 100644 index 0000000000000000000000000000000000000000..52583a49b35cd0dd40b9ce88142fa5392fe1d5ae --- /dev/null +++ b/node_modules/@mswjs/interceptors/presets/browser/package.json @@ -0,0 +1,5 @@ +{ + "main": "../../lib/browser/presets/browser.mjs", + "module": "../../lib/browser/presets/browser.mjs", + "browser": "../../lib/browser/presets/browser.mjs" +} diff --git a/node_modules/@mswjs/interceptors/presets/node/package.json b/node_modules/@mswjs/interceptors/presets/node/package.json new file mode 100644 index 0000000000000000000000000000000000000000..9e8b05b9f1139d6ffd7ad1a0c1960b5f327ab26b --- /dev/null +++ b/node_modules/@mswjs/interceptors/presets/node/package.json @@ -0,0 +1,11 @@ +{ + "main": "../../lib/node/presets/node.cjs", + "module": "../../lib/node/presets/node.mjs", + "browser": null, + "exports": { + ".": { + "import": "./../lib/node/presets/node.mjs", + "default": "./../lib/node/presets/node.cjs" + } + } +} diff --git a/node_modules/@mswjs/interceptors/src/BatchInterceptor.test.ts b/node_modules/@mswjs/interceptors/src/BatchInterceptor.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..5891d626718a75d0c3ea2b3a98833f77a2885f0c --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/BatchInterceptor.test.ts @@ -0,0 +1,255 @@ +import { vi, it, expect, afterEach } from 'vitest' +import { Interceptor } from './Interceptor' +import { BatchInterceptor } from './BatchInterceptor' + +afterEach(() => { + vi.resetAllMocks() +}) + +it('applies child interceptors', () => { + class PrimaryInterceptor extends Interceptor { + constructor() { + super(Symbol('primary')) + } + } + + class SecondaryInterceptor extends Interceptor { + constructor() { + super(Symbol('secondary')) + } + } + + const instances = { + primary: new PrimaryInterceptor(), + secondary: new SecondaryInterceptor(), + } + + const interceptor = new BatchInterceptor({ + name: 'batch-apply', + interceptors: [instances.primary, instances.secondary], + }) + + const primaryApplySpy = vi.spyOn(instances.primary, 'apply') + const secondaryApplySpy = vi.spyOn(instances.secondary, 'apply') + + interceptor.apply() + + expect(primaryApplySpy).toHaveBeenCalledTimes(1) + expect(secondaryApplySpy).toHaveBeenCalledTimes(1) +}) + +it('proxies event listeners to the interceptors', () => { + class PrimaryInterceptor extends Interceptor<{ hello: [string] }> { + constructor() { + super(Symbol('primary')) + } + } + + class SecondaryInterceptor extends Interceptor<{ + goodbye: [string] + }> { + constructor() { + super(Symbol('secondary')) + } + } + + const instances = { + primary: new PrimaryInterceptor(), + secondary: new SecondaryInterceptor(), + } + + const interceptor = new BatchInterceptor({ + name: 'batch-proxy', + interceptors: [instances.primary, instances.secondary], + }) + + const helloListener = vi.fn() + interceptor.on('hello', helloListener) + + const goodbyeListener = vi.fn() + interceptor.on('goodbye', goodbyeListener) + + // Emulate the child interceptor emitting events. + instances.primary['emitter'].emit('hello', 'John') + instances.secondary['emitter'].emit('goodbye', 'Kate') + + // Must call the batch interceptor listener. + expect(helloListener).toHaveBeenCalledTimes(1) + expect(helloListener).toHaveBeenCalledWith('John') + expect(goodbyeListener).toHaveBeenCalledTimes(1) + expect(goodbyeListener).toHaveBeenCalledWith('Kate') +}) + +it('disposes of child interceptors', async () => { + class PrimaryInterceptor extends Interceptor { + constructor() { + super(Symbol('primary')) + } + } + + class SecondaryInterceptor extends Interceptor { + constructor() { + super(Symbol('secondary')) + } + } + + const instances = { + primary: new PrimaryInterceptor(), + secondary: new SecondaryInterceptor(), + } + + const interceptor = new BatchInterceptor({ + name: 'batch-dispose', + interceptors: [instances.primary, instances.secondary], + }) + + const primaryDisposeSpy = vi.spyOn(instances.primary, 'dispose') + const secondaryDisposeSpy = vi.spyOn(instances.secondary, 'dispose') + + interceptor.apply() + interceptor.dispose() + + expect(primaryDisposeSpy).toHaveBeenCalledTimes(1) + expect(secondaryDisposeSpy).toHaveBeenCalledTimes(1) +}) + +it('forwards listeners added via "on()"', () => { + class FirstInterceptor extends Interceptor { + constructor() { + super(Symbol('first')) + } + } + class SecondaryInterceptor extends Interceptor { + constructor() { + super(Symbol('second')) + } + } + + const firstInterceptor = new FirstInterceptor() + const secondInterceptor = new SecondaryInterceptor() + + const interceptor = new BatchInterceptor({ + name: 'batch', + interceptors: [firstInterceptor, secondInterceptor], + }) + + const listener = vi.fn() + interceptor.on('foo', listener) + + expect(firstInterceptor['emitter'].listenerCount('foo')).toBe(1) + expect(secondInterceptor['emitter'].listenerCount('foo')).toBe(1) + expect(interceptor['emitter'].listenerCount('foo')).toBe(0) +}) + +it('forwards listeners removal via "off()"', () => { + type Events = { + foo: [] + } + + class FirstInterceptor extends Interceptor { + constructor() { + super(Symbol('first')) + } + } + class SecondaryInterceptor extends Interceptor { + constructor() { + super(Symbol('second')) + } + } + + const firstInterceptor = new FirstInterceptor() + const secondInterceptor = new SecondaryInterceptor() + + const interceptor = new BatchInterceptor({ + name: 'batch', + interceptors: [firstInterceptor, secondInterceptor], + }) + + const listener = vi.fn() + interceptor.on('foo', listener) + interceptor.off('foo', listener) + + expect(firstInterceptor['emitter'].listenerCount('foo')).toBe(0) + expect(secondInterceptor['emitter'].listenerCount('foo')).toBe(0) +}) + +it('forwards removal of all listeners by name via ".removeAllListeners()"', () => { + type Events = { + foo: [] + bar: [] + } + + class FirstInterceptor extends Interceptor { + constructor() { + super(Symbol('first')) + } + } + class SecondaryInterceptor extends Interceptor { + constructor() { + super(Symbol('second')) + } + } + + const firstInterceptor = new FirstInterceptor() + const secondInterceptor = new SecondaryInterceptor() + + const interceptor = new BatchInterceptor({ + name: 'batch', + interceptors: [firstInterceptor, secondInterceptor], + }) + + const listener = vi.fn() + interceptor.on('foo', listener) + interceptor.on('foo', listener) + interceptor.on('bar', listener) + + expect(firstInterceptor['emitter'].listenerCount('foo')).toBe(2) + expect(secondInterceptor['emitter'].listenerCount('foo')).toBe(2) + expect(firstInterceptor['emitter'].listenerCount('bar')).toBe(1) + expect(secondInterceptor['emitter'].listenerCount('bar')).toBe(1) + + interceptor.removeAllListeners('foo') + + expect(firstInterceptor['emitter'].listenerCount('foo')).toBe(0) + expect(secondInterceptor['emitter'].listenerCount('foo')).toBe(0) + expect(firstInterceptor['emitter'].listenerCount('bar')).toBe(1) + expect(secondInterceptor['emitter'].listenerCount('bar')).toBe(1) +}) + +it('forwards removal of all listeners via ".removeAllListeners()"', () => { + class FirstInterceptor extends Interceptor { + constructor() { + super(Symbol('first')) + } + } + class SecondaryInterceptor extends Interceptor { + constructor() { + super(Symbol('second')) + } + } + + const firstInterceptor = new FirstInterceptor() + const secondInterceptor = new SecondaryInterceptor() + + const interceptor = new BatchInterceptor({ + name: 'batch', + interceptors: [firstInterceptor, secondInterceptor], + }) + + const listener = vi.fn() + interceptor.on('foo', listener) + interceptor.on('foo', listener) + interceptor.on('bar', listener) + + expect(firstInterceptor['emitter'].listenerCount('foo')).toBe(2) + expect(secondInterceptor['emitter'].listenerCount('foo')).toBe(2) + expect(firstInterceptor['emitter'].listenerCount('bar')).toBe(1) + expect(secondInterceptor['emitter'].listenerCount('bar')).toBe(1) + + interceptor.removeAllListeners() + + expect(firstInterceptor['emitter'].listenerCount('foo')).toBe(0) + expect(secondInterceptor['emitter'].listenerCount('foo')).toBe(0) + expect(firstInterceptor['emitter'].listenerCount('bar')).toBe(0) + expect(secondInterceptor['emitter'].listenerCount('bar')).toBe(0) +}) diff --git a/node_modules/@mswjs/interceptors/src/BatchInterceptor.ts b/node_modules/@mswjs/interceptors/src/BatchInterceptor.ts new file mode 100644 index 0000000000000000000000000000000000000000..ecfba33176eff8d12a413b93035a340f92da41c8 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/BatchInterceptor.ts @@ -0,0 +1,96 @@ +import { EventMap, Listener } from 'strict-event-emitter' +import { Interceptor, ExtractEventNames } from './Interceptor' + +export interface BatchInterceptorOptions< + InterceptorList extends ReadonlyArray>, +> { + name: string + interceptors: InterceptorList +} + +export type ExtractEventMapType< + InterceptorList extends ReadonlyArray>, +> = + InterceptorList extends ReadonlyArray + ? InterceptorType extends Interceptor + ? EventMap + : never + : never + +/** + * A batch interceptor that exposes a single interface + * to apply and operate with multiple interceptors at once. + */ +export class BatchInterceptor< + InterceptorList extends ReadonlyArray>, + Events extends EventMap = ExtractEventMapType, +> extends Interceptor { + static symbol: symbol + + private interceptors: InterceptorList + + constructor(options: BatchInterceptorOptions) { + BatchInterceptor.symbol = Symbol.for(options.name) + super(BatchInterceptor.symbol) + this.interceptors = options.interceptors + } + + protected setup() { + const logger = this.logger.extend('setup') + + logger.info('applying all %d interceptors...', this.interceptors.length) + + for (const interceptor of this.interceptors) { + logger.info('applying "%s" interceptor...', interceptor.constructor.name) + interceptor.apply() + + logger.info('adding interceptor dispose subscription') + this.subscriptions.push(() => interceptor.dispose()) + } + } + + public on>( + event: EventName, + listener: Listener + ): this { + // Instead of adding a listener to the batch interceptor, + // propagate the listener to each of the individual interceptors. + for (const interceptor of this.interceptors) { + interceptor.on(event, listener) + } + + return this + } + + public once>( + event: EventName, + listener: Listener + ): this { + for (const interceptor of this.interceptors) { + interceptor.once(event, listener) + } + + return this + } + + public off>( + event: EventName, + listener: Listener + ): this { + for (const interceptor of this.interceptors) { + interceptor.off(event, listener) + } + + return this + } + + public removeAllListeners>( + event?: EventName | undefined + ): this { + for (const interceptors of this.interceptors) { + interceptors.removeAllListeners(event) + } + + return this + } +} diff --git a/node_modules/@mswjs/interceptors/src/Interceptor.test.ts b/node_modules/@mswjs/interceptors/src/Interceptor.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..e8d78f8a3609f101a1271a5062d120e4eacb4d22 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/Interceptor.test.ts @@ -0,0 +1,205 @@ +import { describe, vi, it, expect, afterEach } from 'vitest' +import { + Interceptor, + getGlobalSymbol, + deleteGlobalSymbol, + InterceptorReadyState, +} from './Interceptor' +import { nextTickAsync } from './utils/nextTick' + +const symbol = Symbol('test') + +afterEach(() => { + deleteGlobalSymbol(symbol) +}) + +it('does not set a maximum listeners limit', () => { + const interceptor = new Interceptor(symbol) + expect(interceptor['emitter'].getMaxListeners()).toBe(0) +}) + +describe('on()', () => { + it('adds a new listener using "on()"', () => { + const interceptor = new Interceptor(symbol) + expect(interceptor['emitter'].listenerCount('event')).toBe(0) + + const listener = vi.fn() + interceptor.on('event', listener) + expect(interceptor['emitter'].listenerCount('event')).toBe(1) + }) +}) + +describe('once()', () => { + it('calls the listener only once', () => { + const interceptor = new Interceptor(symbol) + const listener = vi.fn() + + interceptor.once('foo', listener) + expect(listener).not.toHaveBeenCalled() + + interceptor['emitter'].emit('foo', 'bar') + + expect(listener).toHaveBeenCalledTimes(1) + expect(listener).toHaveBeenCalledWith('bar') + + listener.mockReset() + + interceptor['emitter'].emit('foo', 'baz') + interceptor['emitter'].emit('foo', 'xyz') + expect(listener).toHaveBeenCalledTimes(0) + }) +}) + +describe('off()', () => { + it('removes a listener using "off()"', () => { + const interceptor = new Interceptor(symbol) + expect(interceptor['emitter'].listenerCount('event')).toBe(0) + + const listener = vi.fn() + interceptor.on('event', listener) + expect(interceptor['emitter'].listenerCount('event')).toBe(1) + + interceptor.off('event', listener) + expect(interceptor['emitter'].listenerCount('event')).toBe(0) + }) +}) + +describe('persistence', () => { + it('stores global reference to the applied interceptor', () => { + const interceptor = new Interceptor(symbol) + interceptor.apply() + + expect(getGlobalSymbol(symbol)).toEqual(interceptor) + }) + + it('deletes global reference when the interceptor is disposed', () => { + const interceptor = new Interceptor(symbol) + + interceptor.apply() + interceptor.dispose() + + expect(getGlobalSymbol(symbol)).toBeUndefined() + }) +}) + +describe('readyState', () => { + it('sets the state to "INACTIVE" when the interceptor is created', () => { + const interceptor = new Interceptor(symbol) + expect(interceptor.readyState).toBe(InterceptorReadyState.INACTIVE) + }) + + it('leaves state as "INACTIVE" if the interceptor failed the environment check', async () => { + class MyInterceptor extends Interceptor { + protected checkEnvironment(): boolean { + return false + } + } + const interceptor = new MyInterceptor(symbol) + interceptor.apply() + + expect(interceptor.readyState).toBe(InterceptorReadyState.INACTIVE) + }) + + it('performs state transition when the interceptor is applying', async () => { + const interceptor = new Interceptor(symbol) + interceptor.apply() + + // The interceptor's state transitions to APPLIED immediately. + // The only exception is if something throws during the setup. + expect(interceptor.readyState).toBe(InterceptorReadyState.APPLIED) + }) + + it('performs state transition when disposing of the interceptor', async () => { + const interceptor = new Interceptor(symbol) + interceptor.apply() + interceptor.dispose() + + // The interceptor's state transitions to DISPOSED immediately. + // The only exception is if something throws during the teardown. + expect(interceptor.readyState).toBe(InterceptorReadyState.DISPOSED) + }) +}) + +describe('apply', () => { + it('does not apply the same interceptor multiple times', () => { + const interceptor = new Interceptor(symbol) + const setupSpy = vi.spyOn( + interceptor, + // @ts-expect-error Protected property spy. + 'setup' + ) + + // Intentionally apply the same interceptor multiple times. + interceptor.apply() + interceptor.apply() + interceptor.apply() + + // The "setup" must not be called repeatedly. + expect(setupSpy).toHaveBeenCalledTimes(1) + + expect(getGlobalSymbol(symbol)).toEqual(interceptor) + }) + + it('does not call "apply" if the interceptor fails environment check', () => { + class MyInterceptor extends Interceptor<{}> { + checkEnvironment() { + return false + } + } + + const interceptor = new MyInterceptor(Symbol('test')) + const setupSpy = vi.spyOn( + interceptor, + // @ts-expect-error Protected property spy. + 'setup' + ) + interceptor.apply() + + expect(setupSpy).not.toHaveBeenCalled() + }) + + it('proxies listeners from new interceptor to already running interceptor', () => { + const firstInterceptor = new Interceptor(symbol) + const secondInterceptor = new Interceptor(symbol) + + firstInterceptor.apply() + const firstListener = vi.fn() + firstInterceptor.on('test', firstListener) + + secondInterceptor.apply() + const secondListener = vi.fn() + secondInterceptor.on('test', secondListener) + + // Emitting event in the first interceptor will bubble to the second one. + firstInterceptor['emitter'].emit('test', 'hello world') + + expect(firstListener).toHaveBeenCalledTimes(1) + expect(firstListener).toHaveBeenCalledWith('hello world') + + expect(secondListener).toHaveBeenCalledTimes(1) + expect(secondListener).toHaveBeenCalledWith('hello world') + + expect(secondInterceptor['emitter'].listenerCount('test')).toBe(0) + }) +}) + +describe('dispose', () => { + it('removes all listeners when the interceptor is disposed', async () => { + const interceptor = new Interceptor(symbol) + + interceptor.apply() + const listener = vi.fn() + interceptor.on('test', listener) + interceptor.dispose() + + // Even after emitting an event, the listener must not get called. + interceptor['emitter'].emit('test') + expect(listener).not.toHaveBeenCalled() + + // The listener must not be called on the next tick either. + await nextTickAsync(() => { + interceptor['emitter'].emit('test') + expect(listener).not.toHaveBeenCalled() + }) + }) +}) diff --git a/node_modules/@mswjs/interceptors/src/Interceptor.ts b/node_modules/@mswjs/interceptors/src/Interceptor.ts new file mode 100644 index 0000000000000000000000000000000000000000..b33e74fdfb29d523e63711dae56e056a12dd8864 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/Interceptor.ts @@ -0,0 +1,249 @@ +import { Logger } from '@open-draft/logger' +import { Emitter, Listener } from 'strict-event-emitter' + +export type InterceptorEventMap = Record +export type InterceptorSubscription = () => void + +/** + * Request header name to detect when a single request + * is being handled by nested interceptors (XHR -> ClientRequest). + * Obscure by design to prevent collisions with user-defined headers. + * Ideally, come up with the Interceptor-level mechanism for this. + * @see https://github.com/mswjs/interceptors/issues/378 + */ +export const INTERNAL_REQUEST_ID_HEADER_NAME = + 'x-interceptors-internal-request-id' + +export function getGlobalSymbol(symbol: Symbol): V | undefined { + return ( + // @ts-ignore https://github.com/Microsoft/TypeScript/issues/24587 + globalThis[symbol] || undefined + ) +} + +function setGlobalSymbol(symbol: Symbol, value: any): void { + // @ts-ignore + globalThis[symbol] = value +} + +export function deleteGlobalSymbol(symbol: Symbol): void { + // @ts-ignore + delete globalThis[symbol] +} + +export enum InterceptorReadyState { + INACTIVE = 'INACTIVE', + APPLYING = 'APPLYING', + APPLIED = 'APPLIED', + DISPOSING = 'DISPOSING', + DISPOSED = 'DISPOSED', +} + +export type ExtractEventNames> = + Events extends Record ? EventName : never + +export class Interceptor { + protected emitter: Emitter + protected subscriptions: Array + protected logger: Logger + + public readyState: InterceptorReadyState + + constructor(private readonly symbol: symbol) { + this.readyState = InterceptorReadyState.INACTIVE + + this.emitter = new Emitter() + this.subscriptions = [] + this.logger = new Logger(symbol.description!) + + // Do not limit the maximum number of listeners + // so not to limit the maximum amount of parallel events emitted. + this.emitter.setMaxListeners(0) + + this.logger.info('constructing the interceptor...') + } + + /** + * Determine if this interceptor can be applied + * in the current environment. + */ + protected checkEnvironment(): boolean { + return true + } + + /** + * Apply this interceptor to the current process. + * Returns an already running interceptor instance if it's present. + */ + public apply(): void { + const logger = this.logger.extend('apply') + logger.info('applying the interceptor...') + + if (this.readyState === InterceptorReadyState.APPLIED) { + logger.info('intercepted already applied!') + return + } + + const shouldApply = this.checkEnvironment() + + if (!shouldApply) { + logger.info('the interceptor cannot be applied in this environment!') + return + } + + this.readyState = InterceptorReadyState.APPLYING + + // Whenever applying a new interceptor, check if it hasn't been applied already. + // This enables to apply the same interceptor multiple times, for example from a different + // interceptor, only proxying events but keeping the stubs in a single place. + const runningInstance = this.getInstance() + + if (runningInstance) { + logger.info('found a running instance, reusing...') + + // Proxy any listeners you set on this instance to the running instance. + this.on = (event, listener) => { + logger.info('proxying the "%s" listener', event) + + // Add listeners to the running instance so they appear + // at the top of the event listeners list and are executed first. + runningInstance.emitter.addListener(event, listener) + + // Ensure that once this interceptor instance is disposed, + // it removes all listeners it has appended to the running interceptor instance. + this.subscriptions.push(() => { + runningInstance.emitter.removeListener(event, listener) + logger.info('removed proxied "%s" listener!', event) + }) + + return this + } + + this.readyState = InterceptorReadyState.APPLIED + + return + } + + logger.info('no running instance found, setting up a new instance...') + + // Setup the interceptor. + this.setup() + + // Store the newly applied interceptor instance globally. + this.setInstance() + + this.readyState = InterceptorReadyState.APPLIED + } + + /** + * Setup the module augments and stubs necessary for this interceptor. + * This method is not run if there's a running interceptor instance + * to prevent instantiating an interceptor multiple times. + */ + protected setup(): void {} + + /** + * Listen to the interceptor's public events. + */ + public on>( + event: EventName, + listener: Listener + ): this { + const logger = this.logger.extend('on') + + if ( + this.readyState === InterceptorReadyState.DISPOSING || + this.readyState === InterceptorReadyState.DISPOSED + ) { + logger.info('cannot listen to events, already disposed!') + return this + } + + logger.info('adding "%s" event listener:', event, listener) + + this.emitter.on(event, listener) + return this + } + + public once>( + event: EventName, + listener: Listener + ): this { + this.emitter.once(event, listener) + return this + } + + public off>( + event: EventName, + listener: Listener + ): this { + this.emitter.off(event, listener) + return this + } + + public removeAllListeners>( + event?: EventName + ): this { + this.emitter.removeAllListeners(event) + return this + } + + /** + * Disposes of any side-effects this interceptor has introduced. + */ + public dispose(): void { + const logger = this.logger.extend('dispose') + + if (this.readyState === InterceptorReadyState.DISPOSED) { + logger.info('cannot dispose, already disposed!') + return + } + + logger.info('disposing the interceptor...') + this.readyState = InterceptorReadyState.DISPOSING + + if (!this.getInstance()) { + logger.info('no interceptors running, skipping dispose...') + return + } + + // Delete the global symbol as soon as possible, + // indicating that the interceptor is no longer running. + this.clearInstance() + + logger.info('global symbol deleted:', getGlobalSymbol(this.symbol)) + + if (this.subscriptions.length > 0) { + logger.info('disposing of %d subscriptions...', this.subscriptions.length) + + for (const dispose of this.subscriptions) { + dispose() + } + + this.subscriptions = [] + + logger.info('disposed of all subscriptions!', this.subscriptions.length) + } + + this.emitter.removeAllListeners() + logger.info('destroyed the listener!') + + this.readyState = InterceptorReadyState.DISPOSED + } + + private getInstance(): this | undefined { + const instance = getGlobalSymbol(this.symbol) + this.logger.info('retrieved global instance:', instance?.constructor?.name) + return instance + } + + private setInstance(): void { + setGlobalSymbol(this.symbol, this) + this.logger.info('set global instance!', this.symbol.description) + } + + private clearInstance(): void { + deleteGlobalSymbol(this.symbol) + this.logger.info('cleared global instance!', this.symbol.description) + } +} diff --git a/node_modules/@mswjs/interceptors/src/InterceptorError.ts b/node_modules/@mswjs/interceptors/src/InterceptorError.ts new file mode 100644 index 0000000000000000000000000000000000000000..882848befd5b77cca56749572437482942d001bb --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/InterceptorError.ts @@ -0,0 +1,7 @@ +export class InterceptorError extends Error { + constructor(message?: string) { + super(message) + this.name = 'InterceptorError' + Object.setPrototypeOf(this, InterceptorError.prototype) + } +} diff --git a/node_modules/@mswjs/interceptors/src/RemoteHttpInterceptor.ts b/node_modules/@mswjs/interceptors/src/RemoteHttpInterceptor.ts new file mode 100644 index 0000000000000000000000000000000000000000..a35765ee4edf0072821b314d2683808caddb804a --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/RemoteHttpInterceptor.ts @@ -0,0 +1,251 @@ +import { ChildProcess } from 'child_process' +import { HttpRequestEventMap } from './glossary' +import { Interceptor } from './Interceptor' +import { BatchInterceptor } from './BatchInterceptor' +import { ClientRequestInterceptor } from './interceptors/ClientRequest' +import { XMLHttpRequestInterceptor } from './interceptors/XMLHttpRequest' +import { FetchInterceptor } from './interceptors/fetch' +import { handleRequest } from './utils/handleRequest' +import { RequestController } from './RequestController' +import { FetchRequest, FetchResponse } from './utils/fetchUtils' +import { isResponseError } from './utils/responseUtils' + +export interface SerializedRequest { + id: string + url: string + method: string + headers: Array<[string, string]> + credentials: RequestCredentials + body: string +} + +interface RevivedRequest extends Omit { + url: URL + headers: Headers +} + +export interface SerializedResponse { + status: number + statusText: string + headers: Array<[string, string]> + body: string +} + +export class RemoteHttpInterceptor extends BatchInterceptor< + [ClientRequestInterceptor, XMLHttpRequestInterceptor, FetchInterceptor] +> { + constructor() { + super({ + name: 'remote-interceptor', + interceptors: [ + new ClientRequestInterceptor(), + new XMLHttpRequestInterceptor(), + new FetchInterceptor(), + ], + }) + } + + protected setup() { + super.setup() + + let handleParentMessage: NodeJS.MessageListener + + this.on('request', async ({ request, requestId, controller }) => { + // Send the stringified intercepted request to + // the parent process where the remote resolver is established. + const serializedRequest = JSON.stringify({ + id: requestId, + method: request.method, + url: request.url, + headers: Array.from(request.headers.entries()), + credentials: request.credentials, + body: ['GET', 'HEAD'].includes(request.method) + ? null + : await request.text(), + } as SerializedRequest) + + this.logger.info( + 'sent serialized request to the child:', + serializedRequest + ) + + process.send?.(`request:${serializedRequest}`) + + const responsePromise = new Promise((resolve) => { + handleParentMessage = (message) => { + if (typeof message !== 'string') { + return resolve() + } + + if (message.startsWith(`response:${requestId}`)) { + const [, serializedResponse] = + message.match(/^response:.+?:(.+)$/) || [] + + if (!serializedResponse) { + return resolve() + } + + const responseInit = JSON.parse( + serializedResponse + ) as SerializedResponse + + const mockedResponse = new FetchResponse(responseInit.body, { + url: request.url, + status: responseInit.status, + statusText: responseInit.statusText, + headers: responseInit.headers, + }) + + /** + * @todo Support "errorWith" as well. + * This response handling from the child is incomplete. + */ + + controller.respondWith(mockedResponse) + return resolve() + } + } + }) + + // Listen for the mocked response message from the parent. + this.logger.info( + 'add "message" listener to the parent process', + handleParentMessage + ) + process.addListener('message', handleParentMessage) + + return responsePromise + }) + + this.subscriptions.push(() => { + process.removeListener('message', handleParentMessage) + }) + } +} + +export function requestReviver(key: string, value: any) { + switch (key) { + case 'url': + return new URL(value) + + case 'headers': + return new Headers(value) + + default: + return value + } +} + +export interface RemoveResolverOptions { + process: ChildProcess +} + +export class RemoteHttpResolver extends Interceptor { + static symbol = Symbol.for('remote-resolver') + private process: ChildProcess + + constructor(options: RemoveResolverOptions) { + super(RemoteHttpResolver.symbol) + this.process = options.process + } + + protected setup() { + const logger = this.logger.extend('setup') + + const handleChildMessage: NodeJS.MessageListener = async (message) => { + logger.info('received message from child!', message) + + if (typeof message !== 'string' || !message.startsWith('request:')) { + logger.info('unknown message, ignoring...') + return + } + + const [, serializedRequest] = message.match(/^request:(.+)$/) || [] + if (!serializedRequest) { + return + } + + const requestJson = JSON.parse( + serializedRequest, + requestReviver + ) as RevivedRequest + + logger.info('parsed intercepted request', requestJson) + + const request = new FetchRequest(requestJson.url, { + method: requestJson.method, + headers: new Headers(requestJson.headers), + credentials: requestJson.credentials, + body: requestJson.body, + }) + + const controller = new RequestController(request, { + passthrough: () => {}, + respondWith: async (response) => { + if (isResponseError(response)) { + this.logger.info('received a network error!', { response }) + throw new Error('Not implemented') + } + + this.logger.info('received mocked response!', { response }) + + const responseClone = FetchResponse.clone(response) + const responseText = await responseClone.text() + + // // Send the mocked response to the child process. + const serializedResponse = JSON.stringify({ + status: response.status, + statusText: response.statusText, + headers: Array.from(response.headers.entries()), + body: responseText, + } as SerializedResponse) + + this.process.send( + `response:${requestJson.id}:${serializedResponse}`, + (error) => { + if (error) { + return + } + + // Emit an optimistic "response" event at this point, + // not to rely on the back-and-forth signaling for the sake of the event. + this.emitter.emit('response', { + request, + requestId: requestJson.id, + response: responseClone, + isMockedResponse: true, + }) + } + ) + + logger.info( + 'sent serialized mocked response to the parent:', + serializedResponse + ) + }, + errorWith: (reason) => { + this.logger.info('request has errored!', { error: reason }) + throw new Error('Not implemented') + }, + }) + + await handleRequest({ + request, + requestId: requestJson.id, + controller, + emitter: this.emitter, + }) + } + + this.subscriptions.push(() => { + this.process.removeListener('message', handleChildMessage) + logger.info('removed the "message" listener from the child process!') + }) + + logger.info('adding a "message" listener to the child process') + this.process.addListener('message', handleChildMessage) + + this.process.once('error', () => this.dispose()) + this.process.once('exit', () => this.dispose()) + } +} diff --git a/node_modules/@mswjs/interceptors/src/RequestController.test.ts b/node_modules/@mswjs/interceptors/src/RequestController.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..eeed75f0a70eedab9f6fe262ba76b4ebd37f0801 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/RequestController.test.ts @@ -0,0 +1,104 @@ +import { vi, it, expect } from 'vitest' +import { + RequestController, + type RequestControllerSource, +} from './RequestController' +import { InterceptorError } from './InterceptorError' + +const defaultSource = { + passthrough() {}, + respondWith() {}, + errorWith() {}, +} satisfies RequestControllerSource + +it('has a pending state upon construction', () => { + const controller = new RequestController( + new Request('http://localhost'), + defaultSource + ) + + expect(controller.handled).toBeInstanceOf(Promise) + expect(controller.readyState).toBe(RequestController.PENDING) +}) + +it('handles a request when calling ".respondWith()" with a mocked response', async () => { + const respondWith = vi.fn() + const controller = new RequestController(new Request('http://localhost'), { + ...defaultSource, + respondWith, + }) + + await controller.respondWith(new Response('hello world')) + + expect(controller.readyState).toBe(RequestController.RESPONSE) + await expect(controller.handled).resolves.toBeUndefined() + + expect(respondWith).toHaveBeenCalledOnce() + const [response] = respondWith.mock.calls[0] + + expect(response).toBeInstanceOf(Response) + expect(response.status).toBe(200) + await expect(response.text()).resolves.toBe('hello world') +}) + +it('handles the request when calling ".errorWith()" with an error', async () => { + const errorWith = vi.fn() + const controller = new RequestController(new Request('http://localhost'), { + ...defaultSource, + errorWith, + }) + + const error = new Error('Oops!') + await controller.errorWith(error) + + expect(controller.readyState).toBe(RequestController.ERROR) + await expect(controller.handled).resolves.toBeUndefined() + + expect(errorWith).toHaveBeenCalledOnce() + expect(errorWith).toHaveBeenCalledWith(error) +}) + +it('handles the request when calling ".errorWith()" with an arbitrary object', async () => { + const errorWith = vi.fn() + const controller = new RequestController(new Request('http://localhost'), { + ...defaultSource, + errorWith, + }) + + const error = { message: 'Oops!' } + await controller.errorWith(error) + + expect(controller.readyState).toBe(RequestController.ERROR) + await expect(controller.handled).resolves.toBeUndefined() + + expect(errorWith).toHaveBeenCalledOnce() + expect(errorWith).toHaveBeenCalledWith(error) +}) + +it('throws when calling "respondWith" multiple times', async () => { + const controller = new RequestController( + new Request('http://localhost'), + defaultSource + ) + controller.respondWith(new Response('hello world')) + + expect(() => controller.respondWith(new Response('second response'))).toThrow( + new InterceptorError( + 'Failed to respond to the "GET http://localhost/" request with "200 OK": the request has already been handled (2)' + ) + ) +}) + +it('throws when calling "errorWith" multiple times', async () => { + const controller = new RequestController( + new Request('http://localhost'), + defaultSource + ) + controller.errorWith(new Error('Oops!')) + + expect(() => controller.errorWith(new Error('second error'))).toThrow( + new InterceptorError( + 'Failed to error the "GET http://localhost/" request with "Error: second error": the request has already been handled (3)' + ) + ) +}) diff --git a/node_modules/@mswjs/interceptors/src/RequestController.ts b/node_modules/@mswjs/interceptors/src/RequestController.ts new file mode 100644 index 0000000000000000000000000000000000000000..57486d84807639c83de13d4320234474252768ce --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/RequestController.ts @@ -0,0 +1,109 @@ +import { DeferredPromise } from '@open-draft/deferred-promise' +import { invariant } from 'outvariant' +import { InterceptorError } from './InterceptorError' + +export interface RequestControllerSource { + passthrough(): void + respondWith(response: Response): void + errorWith(reason?: unknown): void +} + +export class RequestController { + static PENDING = 0 as const + static PASSTHROUGH = 1 as const + static RESPONSE = 2 as const + static ERROR = 3 as const + + public readyState: number + + /** + * A Promise that resolves when this controller handles a request. + * See `controller.readyState` for more information on the handling result. + */ + public handled: Promise + + constructor( + protected readonly request: Request, + protected readonly source: RequestControllerSource + ) { + this.readyState = RequestController.PENDING + this.handled = new DeferredPromise() + } + + get #handled() { + return this.handled as DeferredPromise + } + + /** + * Perform this request as-is. + */ + public async passthrough(): Promise { + invariant.as( + InterceptorError, + this.readyState === RequestController.PENDING, + 'Failed to passthrough the "%s %s" request: the request has already been handled', + this.request.method, + this.request.url + ) + + this.readyState = RequestController.PASSTHROUGH + await this.source.passthrough() + this.#handled.resolve() + } + + /** + * Respond to this request with the given `Response` instance. + * + * @example + * controller.respondWith(new Response()) + * controller.respondWith(Response.json({ id })) + * controller.respondWith(Response.error()) + */ + public respondWith(response: Response): void { + invariant.as( + InterceptorError, + this.readyState === RequestController.PENDING, + 'Failed to respond to the "%s %s" request with "%d %s": the request has already been handled (%d)', + this.request.method, + this.request.url, + response.status, + response.statusText || 'OK', + this.readyState + ) + + this.readyState = RequestController.RESPONSE + this.#handled.resolve() + + /** + * @note Although `source.respondWith()` is potentially asynchronous, + * do NOT await it for backward-compatibility. Awaiting it will short-circuit + * the request listener invocation as soon as a listener responds to a request. + * Ideally, that's what we want, but that's not what we promise the user. + */ + this.source.respondWith(response) + } + + /** + * Error this request with the given reason. + * + * @example + * controller.errorWith() + * controller.errorWith(new Error('Oops!')) + * controller.errorWith({ message: 'Oops!'}) + */ + public errorWith(reason?: unknown): void { + invariant.as( + InterceptorError, + this.readyState === RequestController.PENDING, + 'Failed to error the "%s %s" request with "%s": the request has already been handled (%d)', + this.request.method, + this.request.url, + reason?.toString(), + this.readyState + ) + + this.readyState = RequestController.ERROR + this.source.errorWith(reason) + this.#handled.resolve() + } +} diff --git a/node_modules/@mswjs/interceptors/src/createRequestId.test.ts b/node_modules/@mswjs/interceptors/src/createRequestId.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..a59b2c049f3b3dfe0bea0524c3ec27ed10e205b1 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/createRequestId.test.ts @@ -0,0 +1,7 @@ +import { it, expect } from 'vitest' +import { createRequestId } from './createRequestId' +import { REQUEST_ID_REGEXP } from '../test/helpers' + +it('returns a request ID', () => { + expect(createRequestId()).toMatch(REQUEST_ID_REGEXP) +}) diff --git a/node_modules/@mswjs/interceptors/src/createRequestId.ts b/node_modules/@mswjs/interceptors/src/createRequestId.ts new file mode 100644 index 0000000000000000000000000000000000000000..318d2eb954d8d4620e6b047d38a6feac8744121a --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/createRequestId.ts @@ -0,0 +1,9 @@ +/** + * Generate a random ID string to represent a request. + * @example + * createRequestId() + * // "f774b6c9c600f" + */ +export function createRequestId(): string { + return Math.random().toString(16).slice(2) +} diff --git a/node_modules/@mswjs/interceptors/src/getRawRequest.ts b/node_modules/@mswjs/interceptors/src/getRawRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..3818711caaafc5e5305c0ca6d228f87b59cb90ce --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/getRawRequest.ts @@ -0,0 +1,21 @@ +const kRawRequest = Symbol('kRawRequest') + +/** + * Returns a raw request instance associated with this request. + * + * @example + * interceptor.on('request', ({ request }) => { + * const rawRequest = getRawRequest(request) + * + * if (rawRequest instanceof http.ClientRequest) { + * console.log(rawRequest.rawHeaders) + * } + * }) + */ +export function getRawRequest(request: Request): unknown | undefined { + return Reflect.get(request, kRawRequest) +} + +export function setRawRequest(request: Request, rawRequest: unknown): void { + Reflect.set(request, kRawRequest, rawRequest) +} diff --git a/node_modules/@mswjs/interceptors/src/glossary.ts b/node_modules/@mswjs/interceptors/src/glossary.ts new file mode 100644 index 0000000000000000000000000000000000000000..816ab75efdb4f26f067d3f861059e9b9b9452708 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/glossary.ts @@ -0,0 +1,35 @@ +import type { RequestController } from './RequestController' + +/** + * @note Export `RequestController` as a type only. + * It's never meant to be created in the userland. + */ +export type { RequestController } + +export type RequestCredentials = 'omit' | 'include' | 'same-origin' + +export type HttpRequestEventMap = { + request: [ + args: { + request: Request + requestId: string + controller: RequestController + }, + ] + response: [ + args: { + response: Response + isMockedResponse: boolean + request: Request + requestId: string + }, + ] + unhandledException: [ + args: { + error: unknown + request: Request + requestId: string + controller: RequestController + }, + ] +} diff --git a/node_modules/@mswjs/interceptors/src/index.ts b/node_modules/@mswjs/interceptors/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..7b1d7870cca67e3e265a08329094886649c58bd5 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/index.ts @@ -0,0 +1,15 @@ +export * from './glossary' +export * from './Interceptor' +export * from './BatchInterceptor' +export { + RequestController, + type RequestControllerSource, +} from './RequestController' + +/* Utils */ +export { createRequestId } from './createRequestId' +export { getCleanUrl } from './utils/getCleanUrl' +export { encodeBuffer, decodeBuffer } from './utils/bufferUtils' +export { FetchRequest, FetchResponse } from './utils/fetchUtils' +export { getRawRequest } from './getRawRequest' +export { resolveWebSocketUrl } from './utils/resolveWebSocketUrl' diff --git a/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/MockHttpSocket.ts b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/MockHttpSocket.ts new file mode 100644 index 0000000000000000000000000000000000000000..4d6a730cf6a01675306d0f25303b59427032a82c --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/MockHttpSocket.ts @@ -0,0 +1,724 @@ +import net from 'node:net' +import { + type HeadersCallback, + HTTPParser, + type RequestHeadersCompleteCallback, + type ResponseHeadersCompleteCallback, +} from '_http_common' +import { STATUS_CODES, IncomingMessage, ServerResponse } from 'node:http' +import { Readable } from 'node:stream' +import { invariant } from 'outvariant' +import { INTERNAL_REQUEST_ID_HEADER_NAME } from '../../Interceptor' +import { MockSocket } from '../Socket/MockSocket' +import type { NormalizedSocketWriteArgs } from '../Socket/utils/normalizeSocketWriteArgs' +import { isPropertyAccessible } from '../../utils/isPropertyAccessible' +import { baseUrlFromConnectionOptions } from '../Socket/utils/baseUrlFromConnectionOptions' +import { createRequestId } from '../../createRequestId' +import { getRawFetchHeaders } from './utils/recordRawHeaders' +import { FetchRequest, FetchResponse } from '../../utils/fetchUtils' +import { setRawRequest } from '../../getRawRequest' +import { setRawRequestBodyStream } from '../../utils/node' +import { freeParser } from './utils/parserUtils' + +type HttpConnectionOptions = any + +export type MockHttpSocketRequestCallback = (args: { + requestId: string + request: Request + socket: MockHttpSocket +}) => void + +export type MockHttpSocketResponseCallback = (args: { + requestId: string + request: Request + response: Response + isMockedResponse: boolean + socket: MockHttpSocket +}) => Promise + +interface MockHttpSocketOptions { + connectionOptions: HttpConnectionOptions + createConnection: () => net.Socket + onRequest: MockHttpSocketRequestCallback + onResponse: MockHttpSocketResponseCallback +} + +export const kRequestId = Symbol('kRequestId') + +export class MockHttpSocket extends MockSocket { + private connectionOptions: HttpConnectionOptions + private createConnection: () => net.Socket + private baseUrl: URL + + private onRequest: MockHttpSocketRequestCallback + private onResponse: MockHttpSocketResponseCallback + private responseListenersPromise?: Promise + + private requestRawHeadersBuffer: Array = [] + private responseRawHeadersBuffer: Array = [] + private writeBuffer: Array = [] + private request?: Request + private requestParser: HTTPParser<0> + private requestStream?: Readable + private shouldKeepAlive?: boolean + + private socketState: 'unknown' | 'mock' | 'passthrough' = 'unknown' + private responseParser: HTTPParser<1> + private responseStream?: Readable + private originalSocket?: net.Socket + + constructor(options: MockHttpSocketOptions) { + super({ + write: (chunk, encoding, callback) => { + // Buffer the writes so they can be flushed in case of the original connection + // and when reading the request body in the interceptor. If the connection has + // been established, no need to buffer the chunks anymore, they will be forwarded. + if (this.socketState !== 'passthrough') { + this.writeBuffer.push([chunk, encoding, callback]) + } + + if (chunk) { + /** + * Forward any writes to the mock socket to the underlying original socket. + * This ensures functional duplex connections, like WebSocket. + * @see https://github.com/mswjs/interceptors/issues/682 + */ + if (this.socketState === 'passthrough') { + this.originalSocket?.write(chunk, encoding, callback) + } + + this.requestParser.execute( + Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding) + ) + } + }, + read: (chunk) => { + if (chunk !== null) { + /** + * @todo We need to free the parser if the connection has been + * upgraded to a non-HTTP protocol. It won't be able to parse data + * from that point onward anyway. No need to keep it in memory. + */ + this.responseParser.execute( + Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk) + ) + } + }, + }) + + this.connectionOptions = options.connectionOptions + this.createConnection = options.createConnection + this.onRequest = options.onRequest + this.onResponse = options.onResponse + + this.baseUrl = baseUrlFromConnectionOptions(this.connectionOptions) + + // Request parser. + this.requestParser = new HTTPParser() + this.requestParser.initialize(HTTPParser.REQUEST, {}) + this.requestParser[HTTPParser.kOnHeaders] = this.onRequestHeaders.bind(this) + this.requestParser[HTTPParser.kOnHeadersComplete] = + this.onRequestStart.bind(this) + this.requestParser[HTTPParser.kOnBody] = this.onRequestBody.bind(this) + this.requestParser[HTTPParser.kOnMessageComplete] = + this.onRequestEnd.bind(this) + + // Response parser. + this.responseParser = new HTTPParser() + this.responseParser.initialize(HTTPParser.RESPONSE, {}) + this.responseParser[HTTPParser.kOnHeaders] = + this.onResponseHeaders.bind(this) + this.responseParser[HTTPParser.kOnHeadersComplete] = + this.onResponseStart.bind(this) + this.responseParser[HTTPParser.kOnBody] = this.onResponseBody.bind(this) + this.responseParser[HTTPParser.kOnMessageComplete] = + this.onResponseEnd.bind(this) + + // Once the socket is finished, nothing can write to it + // anymore. It has also flushed any buffered chunks. + this.once('finish', () => freeParser(this.requestParser, this)) + + if (this.baseUrl.protocol === 'https:') { + Reflect.set(this, 'encrypted', true) + // The server certificate is not the same as a CA + // passed to the TLS socket connection options. + Reflect.set(this, 'authorized', false) + Reflect.set(this, 'getProtocol', () => 'TLSv1.3') + Reflect.set(this, 'getSession', () => undefined) + Reflect.set(this, 'isSessionReused', () => false) + Reflect.set(this, 'getCipher', () => ({ + name: 'AES256-SHA', + standardName: 'TLS_RSA_WITH_AES_256_CBC_SHA', + version: 'TLSv1.3', + })) + } + } + + public emit(event: string | symbol, ...args: any[]): boolean { + const emitEvent = super.emit.bind(this, event as any, ...args) + + if (this.responseListenersPromise) { + this.responseListenersPromise.finally(emitEvent) + return this.listenerCount(event) > 0 + } + + return emitEvent() + } + + public destroy(error?: Error | undefined): this { + // Destroy the response parser when the socket gets destroyed. + // Normally, we should listen to the "close" event but it + // can be suppressed by using the "emitClose: false" option. + freeParser(this.responseParser, this) + + if (error) { + this.emit('error', error) + } + + return super.destroy(error) + } + + /** + * Establish this Socket connection as-is and pipe + * its data/events through this Socket. + */ + public passthrough(): void { + this.socketState = 'passthrough' + + if (this.destroyed) { + return + } + + const socket = this.createConnection() + this.originalSocket = socket + + /** + * @note Inherit the original socket's connection handle. + * Without this, each push to the mock socket results in a + * new "connection" listener being added (i.e. buffering pushes). + * @see https://github.com/nodejs/node/blob/b18153598b25485ce4f54d0c5cb830a9457691ee/lib/net.js#L734 + */ + if ('_handle' in socket) { + Object.defineProperty(this, '_handle', { + value: socket._handle, + enumerable: true, + writable: true, + }) + } + + // The client-facing socket can be destroyed in two ways: + // 1. The developer destroys the socket. + // 2. The passthrough socket "close" is forwarded to the socket. + this.once('close', () => { + socket.removeAllListeners() + + // If the closure didn't originate from the passthrough socket, destroy it. + if (!socket.destroyed) { + socket.destroy() + } + + this.originalSocket = undefined + }) + + this.address = socket.address.bind(socket) + + // Flush the buffered "socket.write()" calls onto + // the original socket instance (i.e. write request body). + // Exhaust the "requestBuffer" in case this Socket + // gets reused for different requests. + let writeArgs: NormalizedSocketWriteArgs | undefined + let headersWritten = false + + while ((writeArgs = this.writeBuffer.shift())) { + if (writeArgs !== undefined) { + if (!headersWritten) { + const [chunk, encoding, callback] = writeArgs + const chunkString = chunk.toString() + const chunkBeforeRequestHeaders = chunkString.slice( + 0, + chunkString.indexOf('\r\n') + 2 + ) + const chunkAfterRequestHeaders = chunkString.slice( + chunk.indexOf('\r\n\r\n') + ) + const rawRequestHeaders = getRawFetchHeaders(this.request!.headers) + const requestHeadersString = rawRequestHeaders + // Skip the internal request ID deduplication header. + .filter(([name]) => { + return name.toLowerCase() !== INTERNAL_REQUEST_ID_HEADER_NAME + }) + .map(([name, value]) => `${name}: ${value}`) + .join('\r\n') + + // Modify the HTTP request message headers + // to reflect any changes to the request headers + // from the "request" event listener. + const headersChunk = `${chunkBeforeRequestHeaders}${requestHeadersString}${chunkAfterRequestHeaders}` + socket.write(headersChunk, encoding, callback) + headersWritten = true + continue + } + + socket.write(...writeArgs) + } + } + + // Forward TLS Socket properties onto this Socket instance + // in the case of a TLS/SSL connection. + if (Reflect.get(socket, 'encrypted')) { + const tlsProperties = [ + 'encrypted', + 'authorized', + 'getProtocol', + 'getSession', + 'isSessionReused', + 'getCipher', + ] + + tlsProperties.forEach((propertyName) => { + Object.defineProperty(this, propertyName, { + enumerable: true, + get: () => { + const value = Reflect.get(socket, propertyName) + return typeof value === 'function' ? value.bind(socket) : value + }, + }) + }) + } + + socket + .on('lookup', (...args) => this.emit('lookup', ...args)) + .on('connect', () => { + this.connecting = socket.connecting + this.emit('connect') + }) + .on('secureConnect', () => this.emit('secureConnect')) + .on('secure', () => this.emit('secure')) + .on('session', (session) => this.emit('session', session)) + .on('ready', () => this.emit('ready')) + .on('drain', () => this.emit('drain')) + .on('data', (chunk) => { + // Push the original response to this socket + // so it triggers the HTTP response parser. This unifies + // the handling pipeline for original and mocked response. + this.push(chunk) + }) + .on('error', (error) => { + Reflect.set(this, '_hadError', Reflect.get(socket, '_hadError')) + this.emit('error', error) + }) + .on('resume', () => this.emit('resume')) + .on('timeout', () => this.emit('timeout')) + .on('prefinish', () => this.emit('prefinish')) + .on('finish', () => this.emit('finish')) + .on('close', (hadError) => this.emit('close', hadError)) + .on('end', () => this.emit('end')) + } + + /** + * Convert the given Fetch API `Response` instance to an + * HTTP message and push it to the socket. + */ + public async respondWith(response: Response): Promise { + // Ignore the mocked response if the socket has been destroyed + // (e.g. aborted or timed out), + if (this.destroyed) { + return + } + + // Prevent recursive calls. + invariant( + this.socketState !== 'mock', + '[MockHttpSocket] Failed to respond to the "%s %s" request with "%s %s": the request has already been handled', + this.request?.method, + this.request?.url, + response.status, + response.statusText + ) + + // Handle "type: error" responses. + if (isPropertyAccessible(response, 'type') && response.type === 'error') { + this.errorWith(new TypeError('Network error')) + return + } + + // First, emit all the connection events + // to emulate a successful connection. + this.mockConnect() + this.socketState = 'mock' + + // Flush the write buffer to trigger write callbacks + // if it hasn't been flushed already (e.g. someone started reading request stream). + this.flushWriteBuffer() + + // Create a `ServerResponse` instance to delegate HTTP message parsing, + // Transfer-Encoding, and other things to Node.js internals. + const serverResponse = new ServerResponse(new IncomingMessage(this)) + + /** + * Assign a mock socket instance to the server response to + * spy on the response chunk writes. Push the transformed response chunks + * to this `MockHttpSocket` instance to trigger the "data" event. + * @note Providing the same `MockSocket` instance when creating `ServerResponse` + * does not have the same effect. + * @see https://github.com/nodejs/node/blob/10099bb3f7fd97bb9dd9667188426866b3098e07/test/parallel/test-http-server-response-standalone.js#L32 + */ + serverResponse.assignSocket( + new MockSocket({ + write: (chunk, encoding, callback) => { + this.push(chunk, encoding) + callback?.() + }, + read() {}, + }) + ) + + /** + * @note Remove the `Connection` and `Date` response headers + * injected by `ServerResponse` by default. Those are required + * from the server but the interceptor is NOT technically a server. + * It's confusing to add response headers that the developer didn't + * specify themselves. They can always add these if they wish. + * @see https://www.rfc-editor.org/rfc/rfc9110#field.date + * @see https://www.rfc-editor.org/rfc/rfc9110#field.connection + */ + serverResponse.removeHeader('connection') + serverResponse.removeHeader('date') + + const rawResponseHeaders = getRawFetchHeaders(response.headers) + + /** + * @note Call `.writeHead` in order to set the raw response headers + * in the same case as they were provided by the developer. Using + * `.setHeader()`/`.appendHeader()` normalizes header names. + */ + serverResponse.writeHead( + response.status, + response.statusText || STATUS_CODES[response.status], + rawResponseHeaders + ) + + // If the developer destroy the socket, gracefully destroy the response. + this.once('error', () => { + serverResponse.destroy() + }) + + if (response.body) { + try { + const reader = response.body.getReader() + + while (true) { + const { done, value } = await reader.read() + + if (done) { + serverResponse.end() + break + } + + serverResponse.write(value) + } + } catch (error) { + if (error instanceof Error) { + serverResponse.destroy() + /** + * @note Destroy the request socket gracefully. + * Response stream errors do NOT produce request errors. + */ + this.destroy() + return + } + + serverResponse.destroy() + throw error + } + } else { + serverResponse.end() + } + + // Close the socket if the connection wasn't marked as keep-alive. + if (!this.shouldKeepAlive) { + this.emit('readable') + + /** + * @todo @fixme This is likely a hack. + * Since we push null to the socket, it never propagates to the + * parser, and the parser never calls "onResponseEnd" to close + * the response stream. We are closing the stream here manually + * but that shouldn't be the case. + */ + this.responseStream?.push(null) + this.push(null) + } + } + + /** + * Close this socket connection with the given error. + */ + public errorWith(error?: Error): void { + this.destroy(error) + } + + private mockConnect(): void { + // Calling this method immediately puts the socket + // into the connected state. + this.connecting = false + + const isIPv6 = + net.isIPv6(this.connectionOptions.hostname) || + this.connectionOptions.family === 6 + const addressInfo = { + address: isIPv6 ? '::1' : '127.0.0.1', + family: isIPv6 ? 'IPv6' : 'IPv4', + port: this.connectionOptions.port, + } + // Return fake address information for the socket. + this.address = () => addressInfo + this.emit( + 'lookup', + null, + addressInfo.address, + addressInfo.family === 'IPv6' ? 6 : 4, + this.connectionOptions.host + ) + this.emit('connect') + this.emit('ready') + + if (this.baseUrl.protocol === 'https:') { + this.emit('secure') + this.emit('secureConnect') + + // A single TLS connection is represented by two "session" events. + this.emit( + 'session', + this.connectionOptions.session || + Buffer.from('mock-session-renegotiate') + ) + this.emit('session', Buffer.from('mock-session-resume')) + } + } + + private flushWriteBuffer(): void { + for (const writeCall of this.writeBuffer) { + if (typeof writeCall[2] === 'function') { + writeCall[2]() + /** + * @note Remove the callback from the write call + * so it doesn't get called twice on passthrough + * if `request.end()` was called within `request.write()`. + * @see https://github.com/mswjs/interceptors/issues/684 + */ + writeCall[2] = undefined + } + } + } + + /** + * This callback might be called when the request is "slow": + * - Request headers were fragmented across multiple TCP packages; + * - Request headers were too large to be processed in a single run + * (e.g. more than 30 request headers). + * @note This is called before request start. + */ + private onRequestHeaders: HeadersCallback = (rawHeaders) => { + this.requestRawHeadersBuffer.push(...rawHeaders) + } + + private onRequestStart: RequestHeadersCompleteCallback = ( + versionMajor, + versionMinor, + rawHeaders, + _, + path, + __, + ___, + ____, + shouldKeepAlive + ) => { + this.shouldKeepAlive = shouldKeepAlive + + const url = new URL(path || '', this.baseUrl) + const method = this.connectionOptions.method?.toUpperCase() || 'GET' + const headers = FetchResponse.parseRawHeaders([ + ...this.requestRawHeadersBuffer, + ...(rawHeaders || []), + ]) + this.requestRawHeadersBuffer.length = 0 + + const canHaveBody = method !== 'GET' && method !== 'HEAD' + + // Translate the basic authorization in the URL to the request header. + // Constructing a Request instance with a URL containing auth is no-op. + if (url.username || url.password) { + if (!headers.has('authorization')) { + headers.set('authorization', `Basic ${url.username}:${url.password}`) + } + url.username = '' + url.password = '' + } + + // Create a new stream for each request. + // If this Socket is reused for multiple requests, + // this ensures that each request gets its own stream. + // One Socket instance can only handle one request at a time. + this.requestStream = new Readable({ + /** + * @note Provide the `read()` method so a `Readable` could be + * used as the actual request body (the stream calls "read()"). + * We control the queue in the onRequestBody/End functions. + */ + read: () => { + // If the user attempts to read the request body, + // flush the write buffer to trigger the callbacks. + // This way, if the request stream ends in the write callback, + // it will indeed end correctly. + this.flushWriteBuffer() + }, + }) + + const requestId = createRequestId() + this.request = new FetchRequest(url, { + method, + headers, + credentials: 'same-origin', + // @ts-expect-error Undocumented Fetch property. + duplex: canHaveBody ? 'half' : undefined, + body: canHaveBody ? (Readable.toWeb(this.requestStream!) as any) : null, + }) + + Reflect.set(this.request, kRequestId, requestId) + + // Set the raw `http.ClientRequest` instance on the request instance. + // This is useful for cases like getting the raw headers of the request. + setRawRequest(this.request, Reflect.get(this, '_httpMessage')) + + // Create a copy of the request body stream and store it on the request. + // This is only needed for the consumers who wish to read the request body stream + // of requests that cannot have a body per Fetch API specification (i.e. GET, HEAD). + setRawRequestBodyStream(this.request, this.requestStream) + + // Skip handling the request that's already being handled + // by another (parent) interceptor. For example, XMLHttpRequest + // is often implemented via ClientRequest in Node.js (e.g. JSDOM). + // In that case, XHR interceptor will bubble down to the ClientRequest + // interceptor. No need to try to handle that request again. + /** + * @fixme Stop relying on the "X-Request-Id" request header + * to figure out if one interceptor has been invoked within another. + * @see https://github.com/mswjs/interceptors/issues/378 + */ + if (this.request.headers.has(INTERNAL_REQUEST_ID_HEADER_NAME)) { + this.passthrough() + return + } + + this.onRequest({ + requestId, + request: this.request, + socket: this, + }) + } + + private onRequestBody(chunk: Buffer): void { + invariant( + this.requestStream, + 'Failed to write to a request stream: stream does not exist' + ) + + this.requestStream.push(chunk) + } + + private onRequestEnd(): void { + // Request end can be called for requests without body. + if (this.requestStream) { + this.requestStream.push(null) + } + } + + /** + * This callback might be called when the response is "slow": + * - Response headers were fragmented across multiple TCP packages; + * - Response headers were too large to be processed in a single run + * (e.g. more than 30 response headers). + * @note This is called before response start. + */ + private onResponseHeaders: HeadersCallback = (rawHeaders) => { + this.responseRawHeadersBuffer.push(...rawHeaders) + } + + private onResponseStart: ResponseHeadersCompleteCallback = ( + versionMajor, + versionMinor, + rawHeaders, + method, + url, + status, + statusText + ) => { + const headers = FetchResponse.parseRawHeaders([ + ...this.responseRawHeadersBuffer, + ...(rawHeaders || []), + ]) + this.responseRawHeadersBuffer.length = 0 + + const response = new FetchResponse( + /** + * @note The Fetch API response instance exposed to the consumer + * is created over the response stream of the HTTP parser. It is NOT + * related to the Socket instance. This way, you can read response body + * in response listener while the Socket instance delays the emission + * of "end" and other events until those response listeners are finished. + */ + FetchResponse.isResponseWithBody(status) + ? (Readable.toWeb( + (this.responseStream = new Readable({ read() {} })) + ) as any) + : null, + { + url, + status, + statusText, + headers, + } + ) + + invariant( + this.request, + 'Failed to handle a response: request does not exist' + ) + + FetchResponse.setUrl(this.request.url, response) + + /** + * @fixme Stop relying on the "X-Request-Id" request header + * to figure out if one interceptor has been invoked within another. + * @see https://github.com/mswjs/interceptors/issues/378 + */ + if (this.request.headers.has(INTERNAL_REQUEST_ID_HEADER_NAME)) { + return + } + + this.responseListenersPromise = this.onResponse({ + response, + isMockedResponse: this.socketState === 'mock', + requestId: Reflect.get(this.request, kRequestId), + request: this.request, + socket: this, + }) + } + + private onResponseBody(chunk: Buffer) { + invariant( + this.responseStream, + 'Failed to write to a response stream: stream does not exist' + ) + + this.responseStream.push(chunk) + } + + private onResponseEnd(): void { + // Response end can be called for responses without body. + if (this.responseStream) { + this.responseStream.push(null) + } + } +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/agents.ts b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/agents.ts new file mode 100644 index 0000000000000000000000000000000000000000..ec8ddd23cbb2a78a411492a9f2b958530b9e2eca --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/agents.ts @@ -0,0 +1,110 @@ +/** + * Here's how requests are handled in Node.js: + * + * 1. http.ClientRequest instance calls `agent.addRequest(request, options, cb)`. + * 2. Agent creates a new socket: `agent.createSocket(options, cb)`. + * 3. Agent creates a new connection: `agent.createConnection(options, cb)`. + */ +import net from 'node:net' +import http from 'node:http' +import https from 'node:https' +import { + MockHttpSocket, + type MockHttpSocketRequestCallback, + type MockHttpSocketResponseCallback, +} from './MockHttpSocket' + +declare module 'node:http' { + interface Agent { + options?: http.AgentOptions + createConnection(options: any, callback: any): net.Socket + } +} + +interface MockAgentOptions { + customAgent?: http.RequestOptions['agent'] + onRequest: MockHttpSocketRequestCallback + onResponse: MockHttpSocketResponseCallback +} + +export class MockAgent extends http.Agent { + private customAgent?: http.RequestOptions['agent'] + private onRequest: MockHttpSocketRequestCallback + private onResponse: MockHttpSocketResponseCallback + + constructor(options: MockAgentOptions) { + super() + this.customAgent = options.customAgent + this.onRequest = options.onRequest + this.onResponse = options.onResponse + } + + public createConnection(options: any, callback: any): net.Socket { + const createConnection = + this.customAgent instanceof http.Agent + ? this.customAgent.createConnection + : super.createConnection + + const createConnectionOptions = + this.customAgent instanceof http.Agent + ? { + ...options, + ...this.customAgent.options, + } + : options + + const socket = new MockHttpSocket({ + connectionOptions: options, + createConnection: createConnection.bind( + this.customAgent || this, + createConnectionOptions, + callback + ), + onRequest: this.onRequest.bind(this), + onResponse: this.onResponse.bind(this), + }) + + return socket + } +} + +export class MockHttpsAgent extends https.Agent { + private customAgent?: https.RequestOptions['agent'] + private onRequest: MockHttpSocketRequestCallback + private onResponse: MockHttpSocketResponseCallback + + constructor(options: MockAgentOptions) { + super() + this.customAgent = options.customAgent + this.onRequest = options.onRequest + this.onResponse = options.onResponse + } + + public createConnection(options: any, callback: any): net.Socket { + const createConnection = + this.customAgent instanceof http.Agent + ? this.customAgent.createConnection + : super.createConnection + + const createConnectionOptions = + this.customAgent instanceof http.Agent + ? { + ...options, + ...this.customAgent.options, + } + : options + + const socket = new MockHttpSocket({ + connectionOptions: options, + createConnection: createConnection.bind( + this.customAgent || this, + createConnectionOptions, + callback + ), + onRequest: this.onRequest.bind(this), + onResponse: this.onResponse.bind(this), + }) + + return socket + } +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/index.test.ts b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/index.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..98539017d01f8e706e501401f16cb8e45dfb1dcc --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/index.test.ts @@ -0,0 +1,75 @@ +import { it, expect, beforeAll, afterEach, afterAll } from 'vitest' +import http from 'node:http' +import { HttpServer } from '@open-draft/test-server/http' +import { DeferredPromise } from '@open-draft/deferred-promise' +import { ClientRequestInterceptor } from '.' +import { sleep, waitForClientRequest } from '../../../test/helpers' + +const httpServer = new HttpServer((app) => { + app.get('/', (_req, res) => { + res.status(200).send('/') + }) + app.get('/get', (_req, res) => { + res.status(200).send('/get') + }) +}) + +const interceptor = new ClientRequestInterceptor() + +beforeAll(async () => { + interceptor.apply() + await httpServer.listen() +}) + +afterEach(() => { + interceptor.removeAllListeners() +}) + +afterAll(async () => { + interceptor.dispose() + await httpServer.close() +}) + +it('abort the request if the abort signal is emitted', async () => { + const requestUrl = httpServer.http.url('/') + + interceptor.on('request', async function delayedResponse({ controller }) { + await sleep(1_000) + controller.respondWith(new Response()) + }) + + const abortController = new AbortController() + const request = http.get(requestUrl, { signal: abortController.signal }) + + abortController.abort() + + const abortErrorPromise = new DeferredPromise() + request.on('error', function (error) { + abortErrorPromise.resolve(error) + }) + + const abortError = await abortErrorPromise + expect(abortError.name).toEqual('AbortError') + + expect(request.destroyed).toBe(true) +}) + +it('patch the Headers object correctly after dispose and reapply', async () => { + interceptor.dispose() + interceptor.apply() + + interceptor.on('request', ({ controller }) => { + const headers = new Headers({ + 'X-CustoM-HeadeR': 'Yes', + }) + controller.respondWith(new Response(null, { headers })) + }) + + const request = http.get(httpServer.http.url('/')) + const { res } = await waitForClientRequest(request) + + expect(res.rawHeaders).toEqual( + expect.arrayContaining(['X-CustoM-HeadeR', 'Yes']) + ) + expect(res.headers['x-custom-header']).toEqual('Yes') +}) diff --git a/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/index.ts b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..de192c32f53e346f278a4bb155160792c70f7bf4 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/index.ts @@ -0,0 +1,193 @@ +import http from 'node:http' +import https from 'node:https' +import { Interceptor } from '../../Interceptor' +import type { HttpRequestEventMap } from '../../glossary' +import { + kRequestId, + MockHttpSocketRequestCallback, + MockHttpSocketResponseCallback, +} from './MockHttpSocket' +import { MockAgent, MockHttpsAgent } from './agents' +import { RequestController } from '../../RequestController' +import { emitAsync } from '../../utils/emitAsync' +import { normalizeClientRequestArgs } from './utils/normalizeClientRequestArgs' +import { handleRequest } from '../../utils/handleRequest' +import { + recordRawFetchHeaders, + restoreHeadersPrototype, +} from './utils/recordRawHeaders' + +export class ClientRequestInterceptor extends Interceptor { + static symbol = Symbol.for('client-request-interceptor') + + constructor() { + super(ClientRequestInterceptor.symbol) + } + + protected setup(): void { + const { + ClientRequest: OriginalClientRequest, + get: originalGet, + request: originalRequest, + } = http + const { get: originalHttpsGet, request: originalHttpsRequest } = https + + const onRequest = this.onRequest.bind(this) + const onResponse = this.onResponse.bind(this) + + // Support requests performed via the `ClientRequest` constructor directly. + http.ClientRequest = new Proxy(http.ClientRequest, { + construct: (target, args: Parameters) => { + const [url, options, callback] = normalizeClientRequestArgs( + 'http:', + args + ) + + // Create a mock agent instance appropriate for the request protocol. + const Agent = options.protocol === 'https:' ? MockHttpsAgent : MockAgent + const mockAgent = new Agent({ + customAgent: options.agent, + onRequest, + onResponse, + }) + options.agent = mockAgent + + return Reflect.construct(target, [url, options, callback]) + }, + }) + + http.request = new Proxy(http.request, { + apply: (target, thisArg, args: Parameters) => { + const [url, options, callback] = normalizeClientRequestArgs( + 'http:', + args + ) + const mockAgent = new MockAgent({ + customAgent: options.agent, + onRequest, + onResponse, + }) + options.agent = mockAgent + + return Reflect.apply(target, thisArg, [url, options, callback]) + }, + }) + + http.get = new Proxy(http.get, { + apply: (target, thisArg, args: Parameters) => { + const [url, options, callback] = normalizeClientRequestArgs( + 'http:', + args + ) + + const mockAgent = new MockAgent({ + customAgent: options.agent, + onRequest, + onResponse, + }) + options.agent = mockAgent + + return Reflect.apply(target, thisArg, [url, options, callback]) + }, + }) + + // + // HTTPS. + // + + https.request = new Proxy(https.request, { + apply: (target, thisArg, args: Parameters) => { + const [url, options, callback] = normalizeClientRequestArgs( + 'https:', + args + ) + + const mockAgent = new MockHttpsAgent({ + customAgent: options.agent, + onRequest, + onResponse, + }) + options.agent = mockAgent + + return Reflect.apply(target, thisArg, [url, options, callback]) + }, + }) + + https.get = new Proxy(https.get, { + apply: (target, thisArg, args: Parameters) => { + const [url, options, callback] = normalizeClientRequestArgs( + 'https:', + args + ) + + const mockAgent = new MockHttpsAgent({ + customAgent: options.agent, + onRequest, + onResponse, + }) + options.agent = mockAgent + + return Reflect.apply(target, thisArg, [url, options, callback]) + }, + }) + + // Spy on `Header.prototype.set` and `Header.prototype.append` calls + // and record the raw header names provided. This is to support + // `IncomingMessage.prototype.rawHeaders`. + recordRawFetchHeaders() + + this.subscriptions.push(() => { + http.ClientRequest = OriginalClientRequest + + http.get = originalGet + http.request = originalRequest + + https.get = originalHttpsGet + https.request = originalHttpsRequest + + restoreHeadersPrototype() + }) + } + + private onRequest: MockHttpSocketRequestCallback = async ({ + request, + socket, + }) => { + const controller = new RequestController(request, { + passthrough() { + socket.passthrough() + }, + async respondWith(response) { + await socket.respondWith(response) + }, + errorWith(reason) { + if (reason instanceof Error) { + socket.errorWith(reason) + } + }, + }) + + await handleRequest({ + request, + requestId: Reflect.get(request, kRequestId), + controller, + emitter: this.emitter, + }) + } + + public onResponse: MockHttpSocketResponseCallback = async ({ + requestId, + request, + response, + isMockedResponse, + }) => { + // Return the promise to when all the response event listeners + // are finished. + return emitAsync(this.emitter, 'response', { + requestId, + request, + response, + isMockedResponse, + }) + } +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/getIncomingMessageBody.test.ts b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/getIncomingMessageBody.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..76d232971e582c18ab2c28fc6cbecf846e91d58c --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/getIncomingMessageBody.test.ts @@ -0,0 +1,54 @@ +import { it, expect } from 'vitest' +import { IncomingMessage } from 'http' +import { Socket } from 'net' +import * as zlib from 'zlib' +import { getIncomingMessageBody } from './getIncomingMessageBody' + +it('returns utf8 string given a utf8 response body', async () => { + const utfBuffer = Buffer.from('one') + const message = new IncomingMessage(new Socket()) + + const pendingResponseBody = getIncomingMessageBody(message) + message.emit('data', utfBuffer) + message.emit('end') + + expect(await pendingResponseBody).toEqual('one') +}) + +it('returns utf8 string given a gzipped response body', async () => { + const utfBuffer = zlib.gzipSync(Buffer.from('two')) + const message = new IncomingMessage(new Socket()) + message.headers = { + 'content-encoding': 'gzip', + } + + const pendingResponseBody = getIncomingMessageBody(message) + message.emit('data', utfBuffer) + message.emit('end') + + expect(await pendingResponseBody).toEqual('two') +}) + +it('returns utf8 string given a gzipped response body with incorrect "content-length"', async () => { + const utfBuffer = zlib.gzipSync(Buffer.from('three')) + const message = new IncomingMessage(new Socket()) + message.headers = { + 'content-encoding': 'gzip', + 'content-length': '500', + } + + const pendingResponseBody = getIncomingMessageBody(message) + message.emit('data', utfBuffer) + message.emit('end') + + expect(await pendingResponseBody).toEqual('three') +}) + +it('returns empty string given an empty body', async () => { + const message = new IncomingMessage(new Socket()) + + const pendingResponseBody = getIncomingMessageBody(message) + message.emit('end') + + expect(await pendingResponseBody).toEqual('') +}) diff --git a/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/getIncomingMessageBody.ts b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/getIncomingMessageBody.ts new file mode 100644 index 0000000000000000000000000000000000000000..563e55259706b93213f1232e8e1165256cb58ca3 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/getIncomingMessageBody.ts @@ -0,0 +1,45 @@ +import { IncomingMessage } from 'http' +import { PassThrough } from 'stream' +import * as zlib from 'zlib' +import { Logger } from '@open-draft/logger' + +const logger = new Logger('http getIncomingMessageBody') + +export function getIncomingMessageBody( + response: IncomingMessage +): Promise { + return new Promise((resolve, reject) => { + logger.info('cloning the original response...') + + // Pipe the original response to support non-clone + // "response" input. No need to clone the response, + // as we always have access to the full "response" input, + // either a clone or an original one (in tests). + const responseClone = response.pipe(new PassThrough()) + const stream = + response.headers['content-encoding'] === 'gzip' + ? responseClone.pipe(zlib.createGunzip()) + : responseClone + + const encoding = response.readableEncoding || 'utf8' + stream.setEncoding(encoding) + logger.info('using encoding:', encoding) + + let body = '' + + stream.on('data', (responseBody) => { + logger.info('response body read:', responseBody) + body += responseBody + }) + + stream.once('end', () => { + logger.info('response body end') + resolve(body) + }) + + stream.once('error', (error) => { + logger.info('error while reading response body:', error) + reject(error) + }) + }) +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/normalizeClientRequestArgs.test.ts b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/normalizeClientRequestArgs.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..ab0e217ee25b20689f564751b8228bb4a6296d82 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/normalizeClientRequestArgs.test.ts @@ -0,0 +1,427 @@ +import { it, expect } from 'vitest' +import { parse } from 'url' +import { globalAgent as httpGlobalAgent, RequestOptions } from 'http' +import { Agent as HttpsAgent, globalAgent as httpsGlobalAgent } from 'https' +import { getUrlByRequestOptions } from '../../../utils/getUrlByRequestOptions' +import { normalizeClientRequestArgs } from './normalizeClientRequestArgs' + +it('handles [string, callback] input', () => { + const [url, options, callback] = normalizeClientRequestArgs('https:', [ + 'https://mswjs.io/resource', + function cb() {}, + ]) + + // URL string must be converted to a URL instance. + expect(url.href).toEqual('https://mswjs.io/resource') + + // Request options must be derived from the URL instance. + expect(options).toHaveProperty('method', 'GET') + expect(options).toHaveProperty('protocol', 'https:') + expect(options).toHaveProperty('hostname', 'mswjs.io') + expect(options).toHaveProperty('path', '/resource') + + // Callback must be preserved. + expect(callback?.name).toEqual('cb') +}) + +it('handles [string, RequestOptions, callback] input', () => { + const initialOptions = { + headers: { + 'Content-Type': 'text/plain', + }, + } + const [url, options, callback] = normalizeClientRequestArgs('https:', [ + 'https://mswjs.io/resource', + initialOptions, + function cb() {}, + ]) + + // URL must be created from the string. + expect(url.href).toEqual('https://mswjs.io/resource') + + // Request options must be preserved. + expect(options).toHaveProperty('headers', initialOptions.headers) + + // Callback must be preserved. + expect(callback?.name).toEqual('cb') +}) + +it('handles [URL, callback] input', () => { + const [url, options, callback] = normalizeClientRequestArgs('https:', [ + new URL('https://mswjs.io/resource'), + function cb() {}, + ]) + + // URL must be preserved. + expect(url.href).toEqual('https://mswjs.io/resource') + + // Request options must be derived from the URL instance. + expect(options.method).toEqual('GET') + expect(options.protocol).toEqual('https:') + expect(options.hostname).toEqual('mswjs.io') + expect(options.path).toEqual('/resource') + + // Callback must be preserved. + expect(callback?.name).toEqual('cb') +}) + +it('handles [Absolute Legacy URL, callback] input', () => { + const [url, options, callback] = normalizeClientRequestArgs('https:', [ + parse('https://cherry:durian@mswjs.io:12345/resource?apple=banana'), + function cb() {}, + ]) + + // URL must be preserved. + expect(url.toJSON()).toEqual( + new URL( + 'https://cherry:durian@mswjs.io:12345/resource?apple=banana' + ).toJSON() + ) + + // Request options must be derived from the URL instance. + expect(options.method).toEqual('GET') + expect(options.protocol).toEqual('https:') + expect(options.hostname).toEqual('mswjs.io') + expect(options.path).toEqual('/resource?apple=banana') + expect(options.port).toEqual(12345) + expect(options.auth).toEqual('cherry:durian') + + // Callback must be preserved. + expect(callback?.name).toEqual('cb') +}) + +it('handles [Relative Legacy URL, RequestOptions without path set, callback] input', () => { + const [url, options, callback] = normalizeClientRequestArgs('http:', [ + parse('/resource?apple=banana'), + { host: 'mswjs.io' }, + function cb() {}, + ]) + + // Correct WHATWG URL generated. + expect(url.toJSON()).toEqual( + new URL('http://mswjs.io/resource?apple=banana').toJSON() + ) + + // No path in request options, so legacy url path is copied-in. + expect(options.protocol).toEqual('http:') + expect(options.host).toEqual('mswjs.io') + expect(options.path).toEqual('/resource?apple=banana') + + // Callback must be preserved. + expect(callback?.name).toEqual('cb') +}) + +it('handles [Relative Legacy URL, RequestOptions with path set, callback] input', () => { + const [url, options, callback] = normalizeClientRequestArgs('http:', [ + parse('/resource?apple=banana'), + { host: 'mswjs.io', path: '/other?cherry=durian' }, + function cb() {}, + ]) + + // Correct WHATWG URL generated. + expect(url.toJSON()).toEqual( + new URL('http://mswjs.io/other?cherry=durian').toJSON() + ) + + // Path in request options, so that path is preferred. + expect(options.protocol).toEqual('http:') + expect(options.host).toEqual('mswjs.io') + expect(options.path).toEqual('/other?cherry=durian') + + // Callback must be preserved. + expect(callback?.name).toEqual('cb') +}) + +it('handles [Relative Legacy URL, callback] input', () => { + const [url, options, callback] = normalizeClientRequestArgs('http:', [ + parse('/resource?apple=banana'), + function cb() {}, + ]) + + // Correct WHATWG URL generated. + expect(url.toJSON()).toMatch( + getUrlByRequestOptions({ path: '/resource?apple=banana' }).toJSON() + ) + + // Check path is in options. + expect(options.protocol).toEqual('http:') + expect(options.path).toEqual('/resource?apple=banana') + + // Callback must be preserved. + expect(callback).toBeTypeOf('function') + expect(callback?.name).toEqual('cb') +}) + +it('handles [Relative Legacy URL] input', () => { + const [url, options, callback] = normalizeClientRequestArgs('http:', [ + parse('/resource?apple=banana'), + ]) + + // Correct WHATWG URL generated. + expect(url.toJSON()).toMatch( + getUrlByRequestOptions({ path: '/resource?apple=banana' }).toJSON() + ) + + // Check path is in options. + expect(options.protocol).toEqual('http:') + expect(options.path).toEqual('/resource?apple=banana') + + // Callback must be preserved. + expect(callback).toBeUndefined() +}) + +it('handles [URL, RequestOptions, callback] input', () => { + const [url, options, callback] = normalizeClientRequestArgs('https:', [ + new URL('https://mswjs.io/resource'), + { + agent: false, + headers: { + 'Content-Type': 'text/plain', + }, + }, + function cb() {}, + ]) + + // URL must be preserved. + expect(url.href).toEqual('https://mswjs.io/resource') + + // Options must be preserved. + // `urlToHttpOptions` from `node:url` generates additional + // ClientRequest options, some of which are not legally allowed. + expect(options).toMatchObject({ + agent: false, + _defaultAgent: httpsGlobalAgent, + protocol: url.protocol, + method: 'GET', + headers: { + 'Content-Type': 'text/plain', + }, + hostname: url.hostname, + path: url.pathname, + }) + + // Callback must be preserved. + expect(callback).toBeTypeOf('function') + expect(callback?.name).toEqual('cb') +}) + +it('handles [URL, RequestOptions] where options have custom "hostname"', () => { + const [url, options] = normalizeClientRequestArgs('http:', [ + new URL('http://example.com/path-from-url'), + { + hostname: 'host-from-options.com', + }, + ]) + expect(url.href).toBe('http://host-from-options.com/path-from-url') + expect(options).toMatchObject({ + hostname: 'host-from-options.com', + path: '/path-from-url', + }) +}) + +it('handles [URL, RequestOptions] where options contain "host" and "path" and "port"', () => { + const [url, options] = normalizeClientRequestArgs('http:', [ + new URL('http://example.com/path-from-url?a=b&c=d'), + { + hostname: 'host-from-options.com', + path: '/path-from-options', + port: 1234, + }, + ]) + // Must remove the query string since it's not specified in "options.path" + expect(url.href).toBe('http://host-from-options.com:1234/path-from-options') + expect(options).toMatchObject({ + hostname: 'host-from-options.com', + path: '/path-from-options', + port: 1234, + }) +}) + +it('handles [URL, RequestOptions] where options contain "path" with query string', () => { + const [url, options] = normalizeClientRequestArgs('http:', [ + new URL('http://example.com/path-from-url?a=b&c=d'), + { + path: '/path-from-options?foo=bar&baz=xyz', + }, + ]) + expect(url.href).toBe('http://example.com/path-from-options?foo=bar&baz=xyz') + expect(options).toMatchObject({ + hostname: 'example.com', + path: '/path-from-options?foo=bar&baz=xyz', + }) +}) + +it('handles [RequestOptions, callback] input', () => { + const initialOptions = { + method: 'POST', + protocol: 'https:', + host: 'mswjs.io', + /** + * @see https://github.com/mswjs/msw/issues/705 + */ + origin: 'https://mswjs.io', + path: '/resource', + headers: { + 'Content-Type': 'text/plain', + }, + } + const [url, options, callback] = normalizeClientRequestArgs('https:', [ + initialOptions, + function cb() {}, + ]) + + // URL must be derived from request options. + expect(url.href).toEqual('https://mswjs.io/resource') + + // Request options must be preserved. + expect(options).toMatchObject(initialOptions) + + // Callback must be preserved. + expect(callback).toBeTypeOf('function') + expect(callback?.name).toEqual('cb') +}) + +it('handles [Empty RequestOptions, callback] input', () => { + const [_, options, callback] = normalizeClientRequestArgs('https:', [ + {}, + function cb() {}, + ]) + + expect(options.protocol).toEqual('https:') + + // Callback must be preserved + expect(callback?.name).toEqual('cb') +}) + +/** + * @see https://github.com/mswjs/interceptors/issues/19 + */ +it('handles [PartialRequestOptions, callback] input', () => { + const initialOptions = { + method: 'GET', + port: '50176', + path: '/resource', + host: '127.0.0.1', + ca: undefined, + key: undefined, + pfx: undefined, + cert: undefined, + passphrase: undefined, + agent: false, + } + const [url, options, callback] = normalizeClientRequestArgs('https:', [ + initialOptions, + function cb() {}, + ]) + + // URL must be derived from request options. + expect(url.toJSON()).toEqual( + new URL('https://127.0.0.1:50176/resource').toJSON() + ) + + // Request options must be preserved. + expect(options).toMatchObject(initialOptions) + + // Options protocol must be inferred from the request issuing module. + expect(options.protocol).toEqual('https:') + + // Callback must be preserved. + expect(callback).toBeTypeOf('function') + expect(callback?.name).toEqual('cb') +}) + +it('sets the default Agent for HTTP request', () => { + const [, options] = normalizeClientRequestArgs('http:', [ + 'http://github.com', + {}, + ]) + + expect(options._defaultAgent).toEqual(httpGlobalAgent) +}) + +it('sets the default Agent for HTTPS request', () => { + const [, options] = normalizeClientRequestArgs('https:', [ + 'https://github.com', + {}, + ]) + + expect(options._defaultAgent).toEqual(httpsGlobalAgent) +}) + +it('preserves a custom default Agent when set', () => { + const [, options] = normalizeClientRequestArgs('https:', [ + 'https://github.com', + { + /** + * @note Intentionally incorrect Agent for HTTPS request. + */ + _defaultAgent: httpGlobalAgent, + }, + ]) + + expect(options._defaultAgent).toEqual(httpGlobalAgent) +}) + +it('merges URL-based RequestOptions with the custom RequestOptions', () => { + const [url, options] = normalizeClientRequestArgs('https:', [ + 'https://github.com/graphql', + { + method: 'GET', + pfx: 'PFX_KEY', + }, + ]) + + expect(url.href).toEqual('https://github.com/graphql') + + // Original request options must be preserved. + expect(options.method).toEqual('GET') + expect(options.pfx).toEqual('PFX_KEY') + + // Other options must be inferred from the URL. + expect(options.protocol).toEqual(url.protocol) + expect(options.hostname).toEqual(url.hostname) + expect(options.path).toEqual(url.pathname) +}) + +it('respects custom "options.path" over URL path', () => { + const [url, options] = normalizeClientRequestArgs('http:', [ + new URL('http://example.com/path-from-url'), + { + path: '/path-from-options', + }, + ]) + + expect(url.href).toBe('http://example.com/path-from-options') + expect(options.protocol).toBe('http:') + expect(options.hostname).toBe('example.com') + expect(options.path).toBe('/path-from-options') +}) + +it('respects custom "options.path" over URL path with query string', () => { + const [url, options] = normalizeClientRequestArgs('http:', [ + new URL('http://example.com/path-from-url?a=b&c=d'), + { + path: '/path-from-options', + }, + ]) + + // Must replace both the path and the query string. + expect(url.href).toBe('http://example.com/path-from-options') + expect(options.protocol).toBe('http:') + expect(options.hostname).toBe('example.com') + expect(options.path).toBe('/path-from-options') +}) + +it('preserves URL query string', () => { + const [url, options] = normalizeClientRequestArgs('http:', [ + new URL('http://example.com:8080/resource?a=b&c=d'), + ]) + + expect(url.href).toBe('http://example.com:8080/resource?a=b&c=d') + expect(options.protocol).toBe('http:') + // expect(options.host).toBe('example.com:8080') + expect(options.hostname).toBe('example.com') + // Query string is a part of the options path. + expect(options.path).toBe('/resource?a=b&c=d') + expect(options.port).toBe(8080) +}) diff --git a/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/normalizeClientRequestArgs.ts b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/normalizeClientRequestArgs.ts new file mode 100644 index 0000000000000000000000000000000000000000..324f865fbcfc3b9f97ec690b8fbc8af85786dcbc --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/normalizeClientRequestArgs.ts @@ -0,0 +1,268 @@ +import { urlToHttpOptions } from 'node:url' +import { + Agent as HttpAgent, + globalAgent as httpGlobalAgent, + IncomingMessage, +} from 'node:http' +import { + RequestOptions, + Agent as HttpsAgent, + globalAgent as httpsGlobalAgent, +} from 'node:https' +import { + /** + * @note Use the Node.js URL instead of the global URL + * because environments like JSDOM may override the global, + * breaking the compatibility with Node.js. + * @see https://github.com/node-fetch/node-fetch/issues/1376#issuecomment-966435555 + */ + URL, + Url as LegacyURL, + parse as parseUrl, +} from 'node:url' +import { Logger } from '@open-draft/logger' +import { + ResolvedRequestOptions, + getUrlByRequestOptions, +} from '../../../utils/getUrlByRequestOptions' +import { cloneObject } from '../../../utils/cloneObject' +import { isObject } from '../../../utils/isObject' + +const logger = new Logger('http normalizeClientRequestArgs') + +export type HttpRequestCallback = (response: IncomingMessage) => void + +export type ClientRequestArgs = + // Request without any arguments is also possible. + | [] + | [string | URL | LegacyURL, HttpRequestCallback?] + | [string | URL | LegacyURL, RequestOptions, HttpRequestCallback?] + | [RequestOptions, HttpRequestCallback?] + +function resolveRequestOptions( + args: ClientRequestArgs, + url: URL +): RequestOptions { + // Calling `fetch` provides only URL to `ClientRequest` + // without any `RequestOptions` or callback. + if (typeof args[1] === 'undefined' || typeof args[1] === 'function') { + logger.info('request options not provided, deriving from the url', url) + return urlToHttpOptions(url) + } + + if (args[1]) { + logger.info('has custom RequestOptions!', args[1]) + const requestOptionsFromUrl = urlToHttpOptions(url) + + logger.info('derived RequestOptions from the URL:', requestOptionsFromUrl) + + /** + * Clone the request options to lock their state + * at the moment they are provided to `ClientRequest`. + * @see https://github.com/mswjs/interceptors/issues/86 + */ + logger.info('cloning RequestOptions...') + const clonedRequestOptions = cloneObject(args[1]) + logger.info('successfully cloned RequestOptions!', clonedRequestOptions) + + return { + ...requestOptionsFromUrl, + ...clonedRequestOptions, + } + } + + logger.info('using an empty object as request options') + return {} as RequestOptions +} + +/** + * Overrides the given `URL` instance with the explicit properties provided + * on the `RequestOptions` object. The options object takes precedence, + * and will replace URL properties like "host", "path", and "port", if specified. + */ +function overrideUrlByRequestOptions(url: URL, options: RequestOptions): URL { + url.host = options.host || url.host + url.hostname = options.hostname || url.hostname + url.port = options.port ? options.port.toString() : url.port + + if (options.path) { + const parsedOptionsPath = parseUrl(options.path, false) + url.pathname = parsedOptionsPath.pathname || '' + url.search = parsedOptionsPath.search || '' + } + + return url +} + +function resolveCallback( + args: ClientRequestArgs +): HttpRequestCallback | undefined { + return typeof args[1] === 'function' ? args[1] : args[2] +} + +export type NormalizedClientRequestArgs = [ + url: URL, + options: ResolvedRequestOptions, + callback?: HttpRequestCallback +] + +/** + * Normalizes parameters given to a `http.request` call + * so it always has a `URL` and `RequestOptions`. + */ +export function normalizeClientRequestArgs( + defaultProtocol: string, + args: ClientRequestArgs +): NormalizedClientRequestArgs { + let url: URL + let options: ResolvedRequestOptions + let callback: HttpRequestCallback | undefined + + logger.info('arguments', args) + logger.info('using default protocol:', defaultProtocol) + + // Support "http.request()" calls without any arguments. + // That call results in a "GET http://localhost" request. + if (args.length === 0) { + const url = new URL('http://localhost') + const options = resolveRequestOptions(args, url) + return [url, options] + } + + // Convert a url string into a URL instance + // and derive request options from it. + if (typeof args[0] === 'string') { + logger.info('first argument is a location string:', args[0]) + + url = new URL(args[0]) + logger.info('created a url:', url) + + const requestOptionsFromUrl = urlToHttpOptions(url) + logger.info('request options from url:', requestOptionsFromUrl) + + options = resolveRequestOptions(args, url) + logger.info('resolved request options:', options) + + callback = resolveCallback(args) + } + // Handle a given URL instance as-is + // and derive request options from it. + else if (args[0] instanceof URL) { + url = args[0] + logger.info('first argument is a URL:', url) + + // Check if the second provided argument is RequestOptions. + // If it is, check if "options.path" was set and rewrite it + // on the input URL. + // Do this before resolving options from the URL below + // to prevent query string from being duplicated in the path. + if (typeof args[1] !== 'undefined' && isObject(args[1])) { + url = overrideUrlByRequestOptions(url, args[1]) + } + + options = resolveRequestOptions(args, url) + logger.info('derived request options:', options) + + callback = resolveCallback(args) + } + // Handle a legacy URL instance and re-normalize from either a RequestOptions object + // or a WHATWG URL. + else if ('hash' in args[0] && !('method' in args[0])) { + const [legacyUrl] = args + logger.info('first argument is a legacy URL:', legacyUrl) + + if (legacyUrl.hostname === null) { + /** + * We are dealing with a relative url, so use the path as an "option" and + * merge in any existing options, giving priority to existing options -- i.e. a path in any + * existing options will take precedence over the one contained in the url. This is consistent + * with the behaviour in ClientRequest. + * @see https://github.com/nodejs/node/blob/d84f1312915fe45fe0febe888db692c74894c382/lib/_http_client.js#L122 + */ + logger.info('given legacy URL is relative (no hostname)') + + return isObject(args[1]) + ? normalizeClientRequestArgs(defaultProtocol, [ + { path: legacyUrl.path, ...args[1] }, + args[2], + ]) + : normalizeClientRequestArgs(defaultProtocol, [ + { path: legacyUrl.path }, + args[1] as HttpRequestCallback, + ]) + } + + logger.info('given legacy url is absolute') + + // We are dealing with an absolute URL, so convert to WHATWG and try again. + const resolvedUrl = new URL(legacyUrl.href) + + return args[1] === undefined + ? normalizeClientRequestArgs(defaultProtocol, [resolvedUrl]) + : typeof args[1] === 'function' + ? normalizeClientRequestArgs(defaultProtocol, [resolvedUrl, args[1]]) + : normalizeClientRequestArgs(defaultProtocol, [ + resolvedUrl, + args[1], + args[2], + ]) + } + // Handle a given "RequestOptions" object as-is + // and derive the URL instance from it. + else if (isObject(args[0])) { + options = { ...(args[0] as any) } + logger.info('first argument is RequestOptions:', options) + + // When handling a "RequestOptions" object without an explicit "protocol", + // infer the protocol from the request issuing module (http/https). + options.protocol = options.protocol || defaultProtocol + logger.info('normalized request options:', options) + + url = getUrlByRequestOptions(options) + logger.info('created a URL from RequestOptions:', url.href) + + callback = resolveCallback(args) + } else { + throw new Error( + `Failed to construct ClientRequest with these parameters: ${args}` + ) + } + + options.protocol = options.protocol || url.protocol + options.method = options.method || 'GET' + + /** + * Ensure that the default Agent is always set. + * This prevents the protocol mismatch for requests with { agent: false }, + * where the global Agent is inferred. + * @see https://github.com/mswjs/msw/issues/1150 + * @see https://github.com/nodejs/node/blob/418ff70b810f0e7112d48baaa72932a56cfa213b/lib/_http_client.js#L130 + * @see https://github.com/nodejs/node/blob/418ff70b810f0e7112d48baaa72932a56cfa213b/lib/_http_client.js#L157-L159 + */ + if (!options._defaultAgent) { + logger.info( + 'has no default agent, setting the default agent for "%s"', + options.protocol + ) + + options._defaultAgent = + options.protocol === 'https:' ? httpsGlobalAgent : httpGlobalAgent + } + + logger.info('successfully resolved url:', url.href) + logger.info('successfully resolved options:', options) + logger.info('successfully resolved callback:', callback) + + /** + * @note If the user-provided URL is not a valid URL in Node.js, + * (e.g. the one provided by the JSDOM polyfills), case it to + * string. Otherwise, this throws on Node.js incompatibility + * (`ERR_INVALID_ARG_TYPE` on the connection listener) + * @see https://github.com/node-fetch/node-fetch/issues/1376#issuecomment-966435555 + */ + if (!(url instanceof URL)) { + url = (url as any).toString() + } + + return [url, options, callback] +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/parserUtils.ts b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/parserUtils.ts new file mode 100644 index 0000000000000000000000000000000000000000..6c9c9585aa4a66581b73c2b4b8207c0398ad9577 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/parserUtils.ts @@ -0,0 +1,48 @@ +import type { Socket } from 'node:net' +import { HTTPParser } from '_http_common' + +/** + * @see https://github.com/nodejs/node/blob/f3adc11e37b8bfaaa026ea85c1cf22e3a0e29ae9/lib/_http_common.js#L180 + */ +export function freeParser(parser: HTTPParser, socket?: Socket): void { + if (parser._consumed) { + parser.unconsume() + } + + parser._headers = [] + parser._url = '' + parser.socket = null + parser.incoming = null + parser.outgoing = null + parser.maxHeaderPairs = 2000 + parser._consumed = false + parser.onIncoming = null + + parser[HTTPParser.kOnHeaders] = null + parser[HTTPParser.kOnHeadersComplete] = null + parser[HTTPParser.kOnMessageBegin] = null + parser[HTTPParser.kOnMessageComplete] = null + parser[HTTPParser.kOnBody] = null + parser[HTTPParser.kOnExecute] = null + parser[HTTPParser.kOnTimeout] = null + + parser.remove() + parser.free() + + if (socket) { + /** + * @note Unassigning the socket's parser will fail this assertion + * if there's still some data being processed on the socket: + * @see https://github.com/nodejs/node/blob/4e1f39b678b37017ac9baa0971e3aeecd3b67b51/lib/_http_client.js#L613 + */ + if (socket.destroyed) { + // @ts-expect-error Node.js internals. + socket.parser = null + } else { + socket.once('end', () => { + // @ts-expect-error Node.js internals. + socket.parser = null + }) + } + } +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/recordRawHeaders.test.ts b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/recordRawHeaders.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..929bb342145c97a1492a710d261f0cf7c1e74870 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/recordRawHeaders.test.ts @@ -0,0 +1,291 @@ +// @vitest-environment node +import { it, expect, afterEach } from 'vitest' +import { + recordRawFetchHeaders, + restoreHeadersPrototype, + getRawFetchHeaders, +} from './recordRawHeaders' + +const url = 'http://localhost' + +afterEach(() => { + restoreHeadersPrototype() +}) + +it('returns an empty list if no headers were set', () => { + expect(getRawFetchHeaders(new Headers())).toEqual([]) + expect(getRawFetchHeaders(new Headers(undefined))).toEqual([]) + expect(getRawFetchHeaders(new Headers({}))).toEqual([]) + expect(getRawFetchHeaders(new Headers([]))).toEqual([]) + expect(getRawFetchHeaders(new Request(url).headers)).toEqual([]) + expect(getRawFetchHeaders(new Response().headers)).toEqual([]) +}) + +it('records raw headers (Headers / object as init)', () => { + recordRawFetchHeaders() + const headers = new Headers({ + 'Content-Type': 'application/json', + 'X-My-Header': '1', + }) + + expect(getRawFetchHeaders(headers)).toEqual([ + ['Content-Type', 'application/json'], + ['X-My-Header', '1'], + ]) + expect(Object.fromEntries(headers)).toEqual({ + 'content-type': 'application/json', + 'x-my-header': '1', + }) +}) + +it('records raw headers (Headers / array as init)', () => { + recordRawFetchHeaders() + const headers = new Headers([['X-My-Header', '1']]) + + expect(getRawFetchHeaders(headers)).toEqual([['X-My-Header', '1']]) + expect(Object.fromEntries(headers)).toEqual({ + 'x-my-header': '1', + }) +}) + +it('records raw headers (Headers / Headers as init', () => { + recordRawFetchHeaders() + const headers = new Headers([['X-My-Header', '1']]) + + expect(getRawFetchHeaders(new Headers(headers))).toEqual([ + ['X-My-Header', '1'], + ]) +}) + +it('records raw headers added via ".set()"', () => { + recordRawFetchHeaders() + const headers = new Headers([['X-My-Header', '1']]) + headers.set('X-Another-Header', '2') + + expect(getRawFetchHeaders(headers)).toEqual([ + ['X-My-Header', '1'], + ['X-Another-Header', '2'], + ]) +}) + +it('records raw headers added via ".append()"', () => { + recordRawFetchHeaders() + const headers = new Headers([['X-My-Header', '1']]) + headers.append('X-My-Header', '2') + + expect(getRawFetchHeaders(headers)).toEqual([ + ['X-My-Header', '1'], + ['X-My-Header', '2'], + ]) +}) + +it('deletes the header when called ".delete()"', () => { + const headers = new Headers([['X-My-Header', '1']]) + headers.delete('X-My-Header') + + expect(getRawFetchHeaders(headers)).toEqual([]) +}) + +it('records raw headers (Request / object as init)', () => { + recordRawFetchHeaders() + const request = new Request(url, { + headers: { + 'Content-Type': 'application/json', + 'X-My-Header': '1', + }, + }) + + expect(getRawFetchHeaders(request.headers)).toEqual([ + ['Content-Type', 'application/json'], + ['X-My-Header', '1'], + ]) +}) + +it('records raw headers (Request / array as init)', () => { + recordRawFetchHeaders() + const request = new Request(url, { + headers: [['X-My-Header', '1']], + }) + + expect(getRawFetchHeaders(request.headers)).toEqual([['X-My-Header', '1']]) +}) + +it('records raw headers (Request / Headers as init)', () => { + recordRawFetchHeaders() + const headers = new Headers([['X-My-Header', '1']]) + const request = new Request(url, { headers }) + + expect(getRawFetchHeaders(request.headers)).toEqual([['X-My-Header', '1']]) +}) + +it('records raw headers (Request / Request as init)', () => { + recordRawFetchHeaders() + const init = new Request(url, { headers: [['X-My-Header', '1']] }) + const request = new Request(init) + + expect(getRawFetchHeaders(request.headers)).toEqual([['X-My-Header', '1']]) +}) + +it('preserves headers instanceof (Request / Request as init)', () => { + recordRawFetchHeaders() + const init = new Request(url, { headers: [['X-My-Header', '1']] }) + new Request(init) + expect(init.headers).toBeInstanceOf(Headers) +}) + +it('preserves headers instanceof (Request / Request with Headers as init)', () => { + recordRawFetchHeaders() + const headers = new Headers([['X-My-Header', '1']]) + const init = new Request(url, { headers }) + new Request(init) + expect(init.headers).toBeInstanceOf(Headers) +}) + +it('preserves headers instanceof (Response / Response with Headers as init)', () => { + recordRawFetchHeaders() + const init = { headers: new Headers([['X-My-Header', '1']]) } + new Response(url, init) + expect(init.headers).toBeInstanceOf(Headers) +}) + +it('records raw headers (Request / Request+Headers as init)', () => { + recordRawFetchHeaders() + const init = new Request(url, { headers: [['X-My-Header', '1']] }) + expect(getRawFetchHeaders(init.headers)).toEqual([['X-My-Header', '1']]) + + const request = new Request(init, { + headers: new Headers([['X-Another-Header', '2']]), + }) + + // Must merge the raw headers from the request init + // and the request instance itself. + expect(getRawFetchHeaders(request.headers)).toEqual([ + ['X-My-Header', '1'], + ['X-Another-Header', '2'], + ]) +}) + +it('records raw headers (Response / object as init)', () => { + recordRawFetchHeaders() + const response = new Response(null, { + headers: { + 'Content-Type': 'application/json', + 'X-My-Header': '1', + }, + }) + + expect(getRawFetchHeaders(response.headers)).toEqual([ + ['Content-Type', 'application/json'], + ['X-My-Header', '1'], + ]) +}) + +it('records raw headers (Response / array as init)', () => { + recordRawFetchHeaders() + const response = new Response(null, { + headers: [['X-My-Header', '1']], + }) + + expect(getRawFetchHeaders(response.headers)).toEqual([['X-My-Header', '1']]) +}) + +it('records raw headers (Response / Headers as init)', () => { + recordRawFetchHeaders() + const headers = new Headers([['X-My-Header', '1']]) + const response = new Response(null, { headers }) + + expect(getRawFetchHeaders(response.headers)).toEqual([['X-My-Header', '1']]) +}) + +it('stops recording once the patches are restored', () => { + restoreHeadersPrototype() + + const headers = new Headers({ 'X-My-Header': '1' }) + // Must return the normalized headers (no access to raw headers). + expect(getRawFetchHeaders(headers)).toEqual([['x-my-header', '1']]) +}) + +it('overrides an existing header when calling ".set()"', () => { + recordRawFetchHeaders() + const headers = new Headers([['a', '1']]) + expect(headers.get('a')).toBe('1') + + headers.set('a', '2') + expect(headers.get('a')).toBe('2') + + const headersClone = new Headers(headers) + expect(headersClone.get('a')).toBe('2') +}) + +it('overrides an existing multi-value header when calling ".set()"', () => { + recordRawFetchHeaders() + const headers = new Headers([ + ['a', '1'], + ['a', '2'], + ]) + expect(headers.get('a')).toBe('1, 2') + + headers.set('a', '3') + expect(headers.get('a')).toBe('3') +}) + +it('does not throw on using Headers before recording', () => { + // If the consumer constructs a Headers instance before + // the interceptor is enabled, it will have no internal symbol set. + const headers = new Headers() + recordRawFetchHeaders() + const request = new Request(url, { headers }) + + expect(getRawFetchHeaders(request.headers)).toEqual([]) + + request.headers.set('X-My-Header', '1') + expect(getRawFetchHeaders(request.headers)).toEqual([['X-My-Header', '1']]) +}) + +/** + * @see https://github.com/mswjs/interceptors/issues/681 + */ +it('isolates headers between different headers instances', async () => { + recordRawFetchHeaders() + const original = new Headers() + const firstClone = new Headers(original) + firstClone.set('Content-Type', 'application/json') + const secondClone = new Headers(original) + + expect(original.get('Content-Type')).toBeNull() + expect(firstClone.get('Content-Type')).toBe('application/json') + expect(secondClone.get('Content-Type')).toBeNull() +}) + +/** + * Node.js 24+ may pass additional internal arguments to Headers.prototype.set + * and Headers.prototype.append. This test ensures we only record the first + * two arguments (name, value) and ignore any additional internal arguments. + * @see https://github.com/mswjs/interceptors/issues/762 + */ +it('ignores extra internal arguments passed to .set() and .append()', () => { + recordRawFetchHeaders() + const headers = new Headers() + + // Simulate Node.js 24+ behavior where internal calls may pass extra arguments + // by calling the prototype methods directly with additional arguments. + Headers.prototype.set.call( + headers, + 'X-Set-Header', + 'set-value', + // @ts-expect-error Internal argument + true + ) + Headers.prototype.append.call( + headers, + 'X-Append-Header', + 'append-value', + // @ts-expect-error Internal argument + true + ) + + expect(getRawFetchHeaders(headers)).toEqual([ + ['X-Set-Header', 'set-value'], + ['X-Append-Header', 'append-value'], + ]) +}) diff --git a/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/recordRawHeaders.ts b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/recordRawHeaders.ts new file mode 100644 index 0000000000000000000000000000000000000000..a596ced108bb74bb0efd15600d66e7ed7b148062 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/utils/recordRawHeaders.ts @@ -0,0 +1,295 @@ +import { FetchRequest, FetchResponse } from '../../../utils/fetchUtils' + +type HeaderTuple = [string, string] +type RawHeaders = Array +type SetHeaderBehavior = 'set' | 'append' + +const kRawHeaders = Symbol('kRawHeaders') +const kRestorePatches = Symbol('kRestorePatches') + +function recordRawHeader( + headers: Headers, + args: HeaderTuple, + behavior: SetHeaderBehavior +) { + ensureRawHeadersSymbol(headers, []) + const rawHeaders = Reflect.get(headers, kRawHeaders) as RawHeaders + + if (behavior === 'set') { + // When recording a set header, ensure we remove any matching existing headers. + for (let index = rawHeaders.length - 1; index >= 0; index--) { + if (rawHeaders[index][0].toLowerCase() === args[0].toLowerCase()) { + rawHeaders.splice(index, 1) + } + } + } + + rawHeaders.push(args) +} + +/** + * Define the raw headers symbol on the given `Headers` instance. + * If the symbol already exists, this function does nothing. + */ +function ensureRawHeadersSymbol( + headers: Headers, + rawHeaders: RawHeaders +): void { + if (Reflect.has(headers, kRawHeaders)) { + return + } + + defineRawHeadersSymbol(headers, rawHeaders) +} + +/** + * Define the raw headers symbol on the given `Headers` instance. + * If the symbol already exists, it gets overridden. + */ +function defineRawHeadersSymbol(headers: Headers, rawHeaders: RawHeaders) { + Object.defineProperty(headers, kRawHeaders, { + value: rawHeaders, + enumerable: false, + // Mark the symbol as configurable so its value can be overridden. + // Overrides happen when merging raw headers from multiple sources. + // E.g. new Request(new Request(url, { headers }), { headers }) + configurable: true, + }) +} + +/** + * Patch the global `Headers` class to store raw headers. + * This is for compatibility with `IncomingMessage.prototype.rawHeaders`. + * + * @note Node.js has their own raw headers symbol but it + * only records the first header name in case of multi-value headers. + * Any other headers are normalized before comparing. This makes it + * incompatible with the `rawHeaders` format. + * + * let h = new Headers() + * h.append('X-Custom', 'one') + * h.append('x-custom', 'two') + * h[Symbol('headers map')] // Map { 'X-Custom' => 'one, two' } + */ +export function recordRawFetchHeaders() { + // Prevent patching the Headers prototype multiple times. + if (Reflect.get(Headers, kRestorePatches)) { + return Reflect.get(Headers, kRestorePatches) + } + + const { + Headers: OriginalHeaders, + Request: OriginalRequest, + Response: OriginalResponse, + } = globalThis + const { set, append, delete: headersDeleteMethod } = Headers.prototype + + Object.defineProperty(Headers, kRestorePatches, { + value: () => { + Headers.prototype.set = set + Headers.prototype.append = append + Headers.prototype.delete = headersDeleteMethod + globalThis.Headers = OriginalHeaders + + globalThis.Request = OriginalRequest + globalThis.Response = OriginalResponse + + Object.setPrototypeOf(FetchRequest, OriginalRequest) + Object.setPrototypeOf(FetchRequest.prototype, OriginalRequest.prototype) + Object.setPrototypeOf(FetchResponse, OriginalResponse) + Object.setPrototypeOf(FetchResponse.prototype, OriginalResponse.prototype) + + Reflect.deleteProperty(Headers, kRestorePatches) + }, + enumerable: false, + /** + * @note Mark this property as configurable + * so we can delete it using `Reflect.delete` during cleanup. + */ + configurable: true, + }) + + Object.defineProperty(globalThis, 'Headers', { + enumerable: true, + writable: true, + value: new Proxy(Headers, { + construct(target, args, newTarget) { + const headersInit = args[0] || [] + + if ( + headersInit instanceof Headers && + Reflect.has(headersInit, kRawHeaders) + ) { + // Ensure each header tuple has exactly 2 elements (name, value). + // Node.js 24+ may have stored tuples with extra internal arguments. + const rawHeadersFromInit = Reflect.get( + headersInit, + kRawHeaders + ) as RawHeaders + const sanitizedHeaders = rawHeadersFromInit.map( + (tuple): HeaderTuple => [tuple[0], tuple[1]] + ) + const headers = Reflect.construct( + target, + [sanitizedHeaders], + newTarget + ) + ensureRawHeadersSymbol(headers, [ + /** + * @note Spread the retrieved headers to clone them. + * This prevents multiple Headers instances from pointing + * at the same internal "rawHeaders" array. + */ + ...sanitizedHeaders, + ]) + return headers + } + + const headers = Reflect.construct(target, args, newTarget) + + // Request/Response constructors will set the symbol + // upon creating a new instance, using the raw developer + // input as the raw headers. Skip the symbol altogether + // in those cases because the input to Headers will be normalized. + if (!Reflect.has(headers, kRawHeaders)) { + const rawHeadersInit = Array.isArray(headersInit) + ? headersInit + : Object.entries(headersInit) + ensureRawHeadersSymbol(headers, rawHeadersInit) + } + + return headers + }, + }), + }) + + Headers.prototype.set = new Proxy(Headers.prototype.set, { + apply(target, thisArg, args: HeaderTuple) { + // Use only the first two arguments (name, value) to record raw headers. + // Node.js 24+ may pass additional internal arguments that should not + // be included in the raw headers array. + recordRawHeader(thisArg, [args[0], args[1]], 'set') + return Reflect.apply(target, thisArg, args) + }, + }) + + Headers.prototype.append = new Proxy(Headers.prototype.append, { + apply(target, thisArg, args: HeaderTuple) { + // Use only the first two arguments (name, value) to record raw headers. + // Node.js 24+ may pass additional internal arguments that should not + // be included in the raw headers array. + recordRawHeader(thisArg, [args[0], args[1]], 'append') + return Reflect.apply(target, thisArg, args) + }, + }) + + Headers.prototype.delete = new Proxy(Headers.prototype.delete, { + apply(target, thisArg, args: [string]) { + const rawHeaders = Reflect.get(thisArg, kRawHeaders) as RawHeaders + + if (rawHeaders) { + for (let index = rawHeaders.length - 1; index >= 0; index--) { + if (rawHeaders[index][0].toLowerCase() === args[0].toLowerCase()) { + rawHeaders.splice(index, 1) + } + } + } + + return Reflect.apply(target, thisArg, args) + }, + }) + + Object.defineProperty(globalThis, 'Request', { + enumerable: true, + writable: true, + value: new Proxy(Request, { + construct(target, args, newTarget) { + const request = Reflect.construct(target, args, newTarget) + const inferredRawHeaders: RawHeaders = [] + + // Infer raw headers from a `Request` instance used as init. + if (typeof args[0] === 'object' && args[0].headers != null) { + inferredRawHeaders.push(...inferRawHeaders(args[0].headers)) + } + + // Infer raw headers from the "headers" init argument. + if (typeof args[1] === 'object' && args[1].headers != null) { + inferredRawHeaders.push(...inferRawHeaders(args[1].headers)) + } + + if (inferredRawHeaders.length > 0) { + ensureRawHeadersSymbol(request.headers, inferredRawHeaders) + } + + return request + }, + }), + }) + + Object.defineProperty(globalThis, 'Response', { + enumerable: true, + writable: true, + value: new Proxy(Response, { + construct(target, args, newTarget) { + const response = Reflect.construct(target, args, newTarget) + + if (typeof args[1] === 'object' && args[1].headers != null) { + ensureRawHeadersSymbol( + response.headers, + inferRawHeaders(args[1].headers) + ) + } + + return response + }, + }), + }) + + /** + * Re-parent FetchRequest/FetchResponse so their `super()` calls go + * through the proxied globalThis.Request/Response above. Without this, + * FetchRequest extends the statically-captured (original) Request, + * bypassing the construct proxy that records raw headers. + */ + Object.setPrototypeOf(FetchRequest, globalThis.Request) + Object.setPrototypeOf(FetchRequest.prototype, globalThis.Request.prototype) + Object.setPrototypeOf(FetchResponse, globalThis.Response) + Object.setPrototypeOf(FetchResponse.prototype, globalThis.Response.prototype) +} + +export function restoreHeadersPrototype() { + if (!Reflect.get(Headers, kRestorePatches)) { + return + } + + Reflect.get(Headers, kRestorePatches)() +} + +export function getRawFetchHeaders(headers: Headers): RawHeaders { + // If the raw headers recording failed for some reason, + // use the normalized header entries instead. + if (!Reflect.has(headers, kRawHeaders)) { + return Array.from(headers.entries()) + } + + const rawHeaders = Reflect.get(headers, kRawHeaders) as RawHeaders + return rawHeaders.length > 0 ? rawHeaders : Array.from(headers.entries()) +} + +/** + * Infers the raw headers from the given `HeadersInit` provided + * to the Request/Response constructor. + * + * If the `init.headers` is a Headers instance, use it directly. + * That means the headers were created standalone and already have + * the raw headers stored. + * If the `init.headers` is a HeadersInit, create a new Headers + * instance out of it. + */ +function inferRawHeaders(headers: HeadersInit): RawHeaders { + if (headers instanceof Headers) { + return Reflect.get(headers, kRawHeaders) || [] + } + + return Reflect.get(new Headers(headers), kRawHeaders) +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/Socket/MockSocket.test.ts b/node_modules/@mswjs/interceptors/src/interceptors/Socket/MockSocket.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..61235cf3633f6c31b4be8e44ff758d9acf882c12 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/Socket/MockSocket.test.ts @@ -0,0 +1,264 @@ +/** + * @vitest-environment node + */ +import { Socket } from 'node:net' +import { vi, it, expect } from 'vitest' +import { MockSocket } from './MockSocket' + +it(`keeps the socket connecting until it's destroyed`, () => { + const socket = new MockSocket({ + write: vi.fn(), + read: vi.fn(), + }) + + expect(socket.connecting).toBe(true) + + socket.destroy() + expect(socket.connecting).toBe(false) +}) + +it('calls the "write" on "socket.write()"', () => { + const writeCallback = vi.fn() + const socket = new MockSocket({ + write: writeCallback, + read: vi.fn(), + }) + + socket.write() + expect(writeCallback).toHaveBeenCalledWith(undefined, undefined, undefined) +}) + +it('calls the "write" on "socket.write(chunk)"', () => { + const writeCallback = vi.fn() + const socket = new MockSocket({ + write: writeCallback, + read: vi.fn(), + }) + + socket.write('hello') + expect(writeCallback).toHaveBeenCalledWith('hello', undefined, undefined) +}) + +it('calls the "write" on "socket.write(chunk, encoding)"', () => { + const writeCallback = vi.fn() + const socket = new MockSocket({ + write: writeCallback, + read: vi.fn(), + }) + + socket.write('hello', 'utf8') + expect(writeCallback).toHaveBeenCalledWith('hello', 'utf8', undefined) +}) + +it('calls the "write" on "socket.write(chunk, encoding, callback)"', () => { + const writeCallback = vi.fn() + const socket = new MockSocket({ + write: writeCallback, + read: vi.fn(), + }) + + const callback = vi.fn() + socket.write('hello', 'utf8', callback) + expect(writeCallback).toHaveBeenCalledWith('hello', 'utf8', callback) +}) + +it('calls the "write" on "socket.end()"', () => { + const writeCallback = vi.fn() + const socket = new MockSocket({ + write: writeCallback, + read: vi.fn(), + }) + + socket.end() + expect(writeCallback).toHaveBeenCalledWith(undefined, undefined, undefined) +}) + +it('calls the "write" on "socket.end(chunk)"', () => { + const writeCallback = vi.fn() + const socket = new MockSocket({ + write: writeCallback, + read: vi.fn(), + }) + + socket.end('final') + expect(writeCallback).toHaveBeenCalledWith('final', undefined, undefined) +}) + +it('calls the "write" on "socket.end(chunk, encoding)"', () => { + const writeCallback = vi.fn() + const socket = new MockSocket({ + write: writeCallback, + read: vi.fn(), + }) + + socket.end('final', 'utf8') + expect(writeCallback).toHaveBeenCalledWith('final', 'utf8', undefined) +}) + +it('calls the "write" on "socket.end(chunk, encoding, callback)"', () => { + const writeCallback = vi.fn() + const socket = new MockSocket({ + write: writeCallback, + read: vi.fn(), + }) + + const callback = vi.fn() + socket.end('final', 'utf8', callback) + expect(writeCallback).toHaveBeenCalledWith('final', 'utf8', callback) +}) + +it('calls the "write" on "socket.end()" without any arguments', () => { + const writeCallback = vi.fn() + const socket = new MockSocket({ + write: writeCallback, + read: vi.fn(), + }) + + socket.end() + expect(writeCallback).toHaveBeenCalledWith(undefined, undefined, undefined) +}) + +it('emits "finished" on .end() without any arguments', async () => { + const finishListener = vi.fn() + const socket = new MockSocket({ + write: vi.fn(), + read: vi.fn(), + }) + socket.on('finish', finishListener) + socket.end() + + await vi.waitFor(() => { + expect(finishListener).toHaveBeenCalledTimes(1) + }) +}) + +it('calls the "read" on "socket.read(chunk)"', () => { + const readCallback = vi.fn() + const socket = new MockSocket({ + write: vi.fn(), + read: readCallback, + }) + + socket.push('hello') + expect(readCallback).toHaveBeenCalledWith('hello', undefined) +}) + +it('calls the "read" on "socket.read(chunk, encoding)"', () => { + const readCallback = vi.fn() + const socket = new MockSocket({ + write: vi.fn(), + read: readCallback, + }) + + socket.push('world', 'utf8') + expect(readCallback).toHaveBeenCalledWith('world', 'utf8') +}) + +it('calls the "read" on "socket.read(null)"', () => { + const readCallback = vi.fn() + const socket = new MockSocket({ + write: vi.fn(), + read: readCallback, + }) + + socket.push(null) + expect(readCallback).toHaveBeenCalledWith(null, undefined) +}) + +it('updates the writable state on "socket.end()"', async () => { + const finishListener = vi.fn() + const endListener = vi.fn() + const socket = new MockSocket({ + write: vi.fn(), + read: vi.fn(), + }) + socket.on('finish', finishListener) + socket.on('end', endListener) + + expect(socket.writable).toBe(true) + expect(socket.writableEnded).toBe(false) + expect(socket.writableFinished).toBe(false) + + socket.write('hello') + // Finish the writable stream. + socket.end() + + expect(socket.writable).toBe(false) + expect(socket.writableEnded).toBe(true) + + // The "finish" event is emitted when writable is done. + // I.e. "socket.end()" is called. + await vi.waitFor(() => { + expect(finishListener).toHaveBeenCalledTimes(1) + }) + expect(socket.writableFinished).toBe(true) +}) + +it('updates the readable state on "socket.push(null)"', async () => { + const endListener = vi.fn() + const socket = new MockSocket({ + write: vi.fn(), + read: vi.fn(), + }) + socket.on('end', endListener) + + expect(socket.readable).toBe(true) + expect(socket.readableEnded).toBe(false) + + socket.push('hello') + socket.push(null) + + expect(socket.readable).toBe(true) + expect(socket.readableEnded).toBe(false) + + // Read the data to free the buffer and + // make Socket emit "end". + socket.read() + + await vi.waitFor(() => { + expect(endListener).toHaveBeenCalledTimes(1) + }) + expect(socket.readable).toBe(false) + expect(socket.readableEnded).toBe(true) +}) + +it('updates the readable/writable state on "socket.destroy()"', async () => { + const finishListener = vi.fn() + const endListener = vi.fn() + const closeListener = vi.fn() + const socket = new MockSocket({ + write: vi.fn(), + read: vi.fn(), + }) + socket.on('finish', finishListener) + socket.on('end', endListener) + socket.on('close', closeListener) + + expect(socket.writable).toBe(true) + expect(socket.writableEnded).toBe(false) + expect(socket.writableFinished).toBe(false) + expect(socket.readable).toBe(true) + + socket.destroy() + + expect(socket.writable).toBe(false) + // The ".end()" wasn't called. + expect(socket.writableEnded).toBe(false) + expect(socket.writableFinished).toBe(false) + expect(socket.readable).toBe(false) + + await vi.waitFor(() => { + expect(closeListener).toHaveBeenCalledTimes(1) + }) + + // Neither "finish" nor "end" events are emitted + // when you destroy the stream. If you want those, + // call ".end()", then destroy the stream. + expect(finishListener).not.toHaveBeenCalled() + expect(endListener).not.toHaveBeenCalled() + expect(socket.writableFinished).toBe(false) + + // The "end" event was never emitted so "readableEnded" + // remains false. + expect(socket.readableEnded).toBe(false) +}) diff --git a/node_modules/@mswjs/interceptors/src/interceptors/Socket/MockSocket.ts b/node_modules/@mswjs/interceptors/src/interceptors/Socket/MockSocket.ts new file mode 100644 index 0000000000000000000000000000000000000000..5bcc42eead874acf99ab72c32755494e378fcc59 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/Socket/MockSocket.ts @@ -0,0 +1,58 @@ +import net from 'node:net' +import { + normalizeSocketWriteArgs, + type WriteArgs, + type WriteCallback, +} from './utils/normalizeSocketWriteArgs' + +export interface MockSocketOptions { + write: ( + chunk: Buffer | string, + encoding: BufferEncoding | undefined, + callback?: WriteCallback + ) => void + + read: (chunk: Buffer, encoding: BufferEncoding | undefined) => void +} + +export class MockSocket extends net.Socket { + public connecting: boolean + + constructor(protected readonly options: MockSocketOptions) { + super() + this.connecting = false + this.connect() + + this._final = (callback) => { + callback(null) + } + } + + public connect() { + // The connection will remain pending until + // the consumer decides to handle it. + this.connecting = true + return this + } + + public write(...args: Array): boolean { + const [chunk, encoding, callback] = normalizeSocketWriteArgs( + args as WriteArgs + ) + this.options.write(chunk, encoding, callback) + return true + } + + public end(...args: Array) { + const [chunk, encoding, callback] = normalizeSocketWriteArgs( + args as WriteArgs + ) + this.options.write(chunk, encoding, callback) + return super.end.apply(this, args as any) + } + + public push(chunk: any, encoding?: BufferEncoding): boolean { + this.options.read(chunk, encoding) + return super.push(chunk, encoding) + } +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/Socket/utils/baseUrlFromConnectionOptions.ts b/node_modules/@mswjs/interceptors/src/interceptors/Socket/utils/baseUrlFromConnectionOptions.ts new file mode 100644 index 0000000000000000000000000000000000000000..6a4f33adbaf45647ebb2123fd9b40a7585e63007 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/Socket/utils/baseUrlFromConnectionOptions.ts @@ -0,0 +1,26 @@ +export function baseUrlFromConnectionOptions(options: any): URL { + if ('href' in options) { + return new URL(options.href) + } + + const protocol = options.port === 443 ? 'https:' : 'http:' + const host = options.host + + const url = new URL(`${protocol}//${host}`) + + if (options.port) { + url.port = options.port.toString() + } + + if (options.path) { + url.pathname = options.path + } + + if (options.auth) { + const [username, password] = options.auth.split(':') + url.username = username + url.password = password + } + + return url +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/Socket/utils/normalizeSocketWriteArgs.test.ts b/node_modules/@mswjs/interceptors/src/interceptors/Socket/utils/normalizeSocketWriteArgs.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..32f2e1d5a87bc30bca4d257d23b15e144e26ac1b --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/Socket/utils/normalizeSocketWriteArgs.test.ts @@ -0,0 +1,52 @@ +/** + * @vitest-environment node + */ +import { it, expect } from 'vitest' +import { normalizeSocketWriteArgs } from './normalizeSocketWriteArgs' + +it('normalizes .write()', () => { + expect(normalizeSocketWriteArgs([undefined])).toEqual([ + undefined, + undefined, + undefined, + ]) + expect(normalizeSocketWriteArgs([null])).toEqual([null, undefined, undefined]) +}) + +it('normalizes .write(chunk)', () => { + expect(normalizeSocketWriteArgs([Buffer.from('hello')])).toEqual([ + Buffer.from('hello'), + undefined, + undefined, + ]) + expect(normalizeSocketWriteArgs(['hello'])).toEqual([ + 'hello', + undefined, + undefined, + ]) + expect(normalizeSocketWriteArgs([null])).toEqual([null, undefined, undefined]) +}) + +it('normalizes .write(chunk, encoding)', () => { + expect(normalizeSocketWriteArgs([Buffer.from('hello'), 'utf8'])).toEqual([ + Buffer.from('hello'), + 'utf8', + undefined, + ]) +}) + +it('normalizes .write(chunk, callback)', () => { + const callback = () => {} + expect(normalizeSocketWriteArgs([Buffer.from('hello'), callback])).toEqual([ + Buffer.from('hello'), + undefined, + callback, + ]) +}) + +it('normalizes .write(chunk, encoding, callback)', () => { + const callback = () => {} + expect( + normalizeSocketWriteArgs([Buffer.from('hello'), 'utf8', callback]) + ).toEqual([Buffer.from('hello'), 'utf8', callback]) +}) diff --git a/node_modules/@mswjs/interceptors/src/interceptors/Socket/utils/normalizeSocketWriteArgs.ts b/node_modules/@mswjs/interceptors/src/interceptors/Socket/utils/normalizeSocketWriteArgs.ts new file mode 100644 index 0000000000000000000000000000000000000000..03a3e9c05473819ecb46c6eeffb0143c24d01ded --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/Socket/utils/normalizeSocketWriteArgs.ts @@ -0,0 +1,33 @@ +export type WriteCallback = (error?: Error | null) => void + +export type WriteArgs = + | [chunk: unknown, callback?: WriteCallback] + | [chunk: unknown, encoding: BufferEncoding, callback?: WriteCallback] + +export type NormalizedSocketWriteArgs = [ + chunk: any, + encoding?: BufferEncoding, + callback?: WriteCallback, +] + +/** + * Normalizes the arguments provided to the `Writable.prototype.write()` + * and `Writable.prototype.end()`. + */ +export function normalizeSocketWriteArgs( + args: WriteArgs +): NormalizedSocketWriteArgs { + const normalized: NormalizedSocketWriteArgs = [args[0], undefined, undefined] + + if (typeof args[1] === 'string') { + normalized[1] = args[1] + } else if (typeof args[1] === 'function') { + normalized[2] = args[1] + } + + if (typeof args[2] === 'function') { + normalized[2] = args[2] + } + + return normalized +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/WebSocketClassTransport.ts b/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/WebSocketClassTransport.ts new file mode 100644 index 0000000000000000000000000000000000000000..70f2166584409bcd9ea78d50af5665c796e4872c --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/WebSocketClassTransport.ts @@ -0,0 +1,116 @@ +import { bindEvent } from './utils/bindEvent' +import { + StrictEventListenerOrEventListenerObject, + WebSocketData, + WebSocketTransport, + WebSocketTransportEventMap, +} from './WebSocketTransport' +import { kOnSend, kClose, WebSocketOverride } from './WebSocketOverride' +import { CancelableMessageEvent, CloseEvent } from './utils/events' + +/** + * Abstraction over the given mock `WebSocket` instance that allows + * for controlling that instance (e.g. sending and receiving messages). + */ +export class WebSocketClassTransport + extends EventTarget + implements WebSocketTransport +{ + constructor(protected readonly socket: WebSocketOverride) { + super() + + // Emit the "close" event on the transport if the close + // originates from the WebSocket client. E.g. the application + // calls "ws.close()", not the interceptor. + this.socket.addEventListener('close', (event) => { + this.dispatchEvent(bindEvent(this.socket, new CloseEvent('close', event))) + }) + + /** + * Emit the "outgoing" event on the transport + * whenever the WebSocket client sends data ("ws.send()"). + */ + this.socket[kOnSend] = (data) => { + this.dispatchEvent( + bindEvent( + this.socket, + // Dispatch this as cancelable because "client" connection + // re-creates this message event (cannot dispatch the same event). + new CancelableMessageEvent('outgoing', { + data, + origin: this.socket.url, + cancelable: true, + }) + ) + ) + } + } + + public addEventListener( + type: EventType, + callback: StrictEventListenerOrEventListenerObject< + WebSocketTransportEventMap[EventType] + > | null, + options?: boolean | AddEventListenerOptions + ): void { + return super.addEventListener(type, callback as EventListener, options) + } + + public dispatchEvent( + event: WebSocketTransportEventMap[EventType] + ): boolean { + return super.dispatchEvent(event) + } + + public send(data: WebSocketData): void { + queueMicrotask(() => { + if ( + this.socket.readyState === this.socket.CLOSING || + this.socket.readyState === this.socket.CLOSED + ) { + return + } + + const dispatchEvent = () => { + this.socket.dispatchEvent( + bindEvent( + /** + * @note Setting this event's "target" to the + * WebSocket override instance is important. + * This way it can tell apart original incoming events + * (must be forwarded to the transport) from the + * mocked message events like the one below + * (must be dispatched on the client instance). + */ + this.socket, + new MessageEvent('message', { + data, + origin: this.socket.url, + }) + ) + ) + } + + if (this.socket.readyState === this.socket.CONNECTING) { + this.socket.addEventListener( + 'open', + () => { + dispatchEvent() + }, + { once: true } + ) + } else { + dispatchEvent() + } + }) + } + + public close(code: number, reason?: string): void { + /** + * @note Call the internal close method directly + * to allow closing the connection with the status codes + * that are non-configurable by the user (> 1000 <= 1015). + */ + this.socket[kClose](code, reason) + } +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/WebSocketClientConnection.ts b/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/WebSocketClientConnection.ts new file mode 100644 index 0000000000000000000000000000000000000000..34eef4c00308113ebcf57bf1d994ec4a2bd182b5 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/WebSocketClientConnection.ts @@ -0,0 +1,152 @@ +import type { WebSocketData, WebSocketTransport } from './WebSocketTransport' +import type { WebSocketEventListener } from './WebSocketOverride' +import { bindEvent } from './utils/bindEvent' +import { CancelableMessageEvent, CloseEvent } from './utils/events' +import { createRequestId } from '../../createRequestId' + +const kEmitter = Symbol('kEmitter') +const kBoundListener = Symbol('kBoundListener') + +export interface WebSocketClientEventMap { + message: MessageEvent + close: CloseEvent +} + +export abstract class WebSocketClientConnectionProtocol { + abstract id: string + abstract url: URL + public abstract send(data: WebSocketData): void + public abstract close(code?: number, reason?: string): void + + public abstract addEventListener< + EventType extends keyof WebSocketClientEventMap, + >( + type: EventType, + listener: WebSocketEventListener, + options?: AddEventListenerOptions | boolean + ): void + + public abstract removeEventListener< + EventType extends keyof WebSocketClientEventMap, + >( + event: EventType, + listener: WebSocketEventListener, + options?: EventListenerOptions | boolean + ): void +} + +/** + * The WebSocket client instance represents an incoming + * client connection. The user can control the connection, + * send and receive events. + */ +export class WebSocketClientConnection implements WebSocketClientConnectionProtocol { + public readonly id: string + public readonly url: URL + + private [kEmitter]: EventTarget + + constructor( + public readonly socket: WebSocket, + private readonly transport: WebSocketTransport + ) { + this.id = createRequestId() + this.url = new URL(socket.url) + this[kEmitter] = new EventTarget() + + // Emit outgoing client data ("ws.send()") as "message" + // events on the "client" connection. + this.transport.addEventListener('outgoing', (event) => { + const message = bindEvent( + this.socket, + new CancelableMessageEvent('message', { + data: event.data, + origin: event.origin, + cancelable: true, + }) + ) + + this[kEmitter].dispatchEvent(message) + + // This is a bit silly but forward the cancellation state + // of the "client" message event to the "outgoing" transport event. + // This way, other agens (like "server" connection) can know + // whether the client listener has pervented the default. + if (message.defaultPrevented) { + event.preventDefault() + } + }) + + /** + * Emit the "close" event on the "client" connection + * whenever the underlying transport is closed. + * @note "client.close()" does NOT dispatch the "close" + * event on the WebSocket because it uses non-configurable + * close status code. Thus, we listen to the transport + * instead of the WebSocket's "close" event. + */ + this.transport.addEventListener('close', (event) => { + this[kEmitter].dispatchEvent( + bindEvent(this.socket, new CloseEvent('close', event)) + ) + }) + } + + /** + * Listen for the outgoing events from the connected WebSocket client. + */ + public addEventListener( + type: EventType, + listener: WebSocketEventListener, + options?: AddEventListenerOptions | boolean + ): void { + if (!Reflect.has(listener, kBoundListener)) { + const boundListener = listener.bind(this.socket) + + // Store the bound listener on the original listener + // so the exact bound function can be accessed in "removeEventListener()". + Object.defineProperty(listener, kBoundListener, { + value: boundListener, + enumerable: false, + configurable: false, + }) + } + + this[kEmitter].addEventListener( + type, + Reflect.get(listener, kBoundListener) as EventListener, + options + ) + } + + /** + * Removes the listener for the given event. + */ + public removeEventListener( + event: EventType, + listener: WebSocketEventListener, + options?: EventListenerOptions | boolean + ): void { + this[kEmitter].removeEventListener( + event, + Reflect.get(listener, kBoundListener) as EventListener, + options + ) + } + + /** + * Send data to the connected client. + */ + public send(data: WebSocketData): void { + this.transport.send(data) + } + + /** + * Close the WebSocket connection. + * @param {number} code A status code (see https://www.rfc-editor.org/rfc/rfc6455#section-7.4.1). + * @param {string} reason A custom connection close reason. + */ + public close(code?: number, reason?: string): void { + this.transport.close(code, reason) + } +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/WebSocketOverride.ts b/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/WebSocketOverride.ts new file mode 100644 index 0000000000000000000000000000000000000000..162418861dab5996b50604b5f31dec2be2d11646 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/WebSocketOverride.ts @@ -0,0 +1,252 @@ +import { invariant } from 'outvariant' +import { DeferredPromise } from '@open-draft/deferred-promise' +import type { WebSocketData } from './WebSocketTransport' +import { bindEvent } from './utils/bindEvent' +import { CloseEvent } from './utils/events' +import { resolveWebSocketUrl } from '../../utils/resolveWebSocketUrl' + +export type WebSocketEventListener< + EventType extends WebSocketEventMap[keyof WebSocketEventMap] = Event, +> = (this: WebSocket, event: EventType) => void + +const WEBSOCKET_CLOSE_CODE_RANGE_ERROR = + 'InvalidAccessError: close code out of user configurable range' + +export const kPassthroughPromise = Symbol('kPassthroughPromise') +export const kOnSend = Symbol('kOnSend') +export const kClose = Symbol('kClose') + +export class WebSocketOverride extends EventTarget implements WebSocket { + static readonly CONNECTING = 0 + static readonly OPEN = 1 + static readonly CLOSING = 2 + static readonly CLOSED = 3 + readonly CONNECTING = 0 + readonly OPEN = 1 + readonly CLOSING = 2 + readonly CLOSED = 3 + + public url: string + public protocol: string + public extensions: string + public binaryType: BinaryType + public readyState: WebSocket['readyState'] + public bufferedAmount: number + + private _onopen: WebSocketEventListener | null = null + private _onmessage: WebSocketEventListener< + MessageEvent + > | null = null + private _onerror: WebSocketEventListener | null = null + private _onclose: WebSocketEventListener | null = null + + private [kPassthroughPromise]: DeferredPromise + private [kOnSend]?: (data: WebSocketData) => void + + constructor(url: string | URL, protocols?: string | Array) { + super() + this.url = resolveWebSocketUrl(url) + this.protocol = '' + this.extensions = '' + this.binaryType = 'blob' + this.readyState = this.CONNECTING + this.bufferedAmount = 0 + + this[kPassthroughPromise] = new DeferredPromise() + + queueMicrotask(async () => { + if (await this[kPassthroughPromise]) { + return + } + + this.protocol = + typeof protocols === 'string' + ? protocols + : Array.isArray(protocols) && protocols.length > 0 + ? protocols[0] + : '' + + /** + * @note Check that nothing has prevented this connection + * (e.g. called `client.close()` in the connection listener). + * If the connection has been prevented, never dispatch the open event,. + */ + if (this.readyState === this.CONNECTING) { + this.readyState = this.OPEN + this.dispatchEvent(bindEvent(this, new Event('open'))) + } + }) + } + + set onopen(listener: WebSocketEventListener | null) { + this.removeEventListener('open', this._onopen) + this._onopen = listener + if (listener !== null) { + this.addEventListener('open', listener) + } + } + get onopen(): WebSocketEventListener | null { + return this._onopen + } + + set onmessage( + listener: WebSocketEventListener> | null + ) { + this.removeEventListener( + 'message', + this._onmessage as WebSocketEventListener + ) + this._onmessage = listener + if (listener !== null) { + this.addEventListener('message', listener) + } + } + get onmessage(): WebSocketEventListener> | null { + return this._onmessage + } + + set onerror(listener: WebSocketEventListener | null) { + this.removeEventListener('error', this._onerror) + this._onerror = listener + if (listener !== null) { + this.addEventListener('error', listener) + } + } + get onerror(): WebSocketEventListener | null { + return this._onerror + } + + set onclose(listener: WebSocketEventListener | null) { + this.removeEventListener('close', this._onclose as WebSocketEventListener) + this._onclose = listener + if (listener !== null) { + this.addEventListener('close', listener) + } + } + get onclose(): WebSocketEventListener | null { + return this._onclose + } + + /** + * @see https://websockets.spec.whatwg.org/#ref-for-dom-websocket-send%E2%91%A0 + */ + public send(data: WebSocketData): void { + if (this.readyState === this.CONNECTING) { + this.close() + throw new DOMException('InvalidStateError') + } + + // Sending when the socket is about to close + // discards the sent data. + if (this.readyState === this.CLOSING || this.readyState === this.CLOSED) { + return + } + + // Buffer the data to send in this even loop + // but send it in the next. + this.bufferedAmount += getDataSize(data) + + queueMicrotask(() => { + // This is a bit optimistic but since no actual data transfer + // is involved, all the data will be "sent" on the next tick. + this.bufferedAmount = 0 + + /** + * @note Notify the parent about outgoing data. + * This notifies the transport and the connection + * listens to the outgoing data to emit the "message" event. + */ + this[kOnSend]?.(data) + }) + } + + public close(code: number = 1000, reason?: string): void { + invariant(code, WEBSOCKET_CLOSE_CODE_RANGE_ERROR) + invariant( + code === 1000 || (code >= 3000 && code <= 4999), + WEBSOCKET_CLOSE_CODE_RANGE_ERROR + ) + + this[kClose](code, reason) + } + + private [kClose]( + code: number = 1000, + reason?: string, + wasClean = true + ): void { + /** + * @note Move this check here so that even internal closures, + * like those triggered by the `server` connection, are not + * performed twice. + */ + if (this.readyState === this.CLOSING || this.readyState === this.CLOSED) { + return + } + + this.readyState = this.CLOSING + + queueMicrotask(() => { + this.readyState = this.CLOSED + + this.dispatchEvent( + bindEvent( + this, + new CloseEvent('close', { + code, + reason, + wasClean, + }) + ) + ) + + // Remove all event listeners once the socket is closed. + this._onopen = null + this._onmessage = null + this._onerror = null + this._onclose = null + }) + } + + public addEventListener( + type: K, + listener: (this: WebSocket, event: WebSocketEventMap[K]) => void, + options?: boolean | AddEventListenerOptions + ): void + public addEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions + ): void + public addEventListener( + type: unknown, + listener: unknown, + options?: unknown + ): void { + return super.addEventListener( + type as string, + listener as EventListener, + options as AddEventListenerOptions + ) + } + + removeEventListener( + type: K, + callback: EventListenerOrEventListenerObject | null, + options?: boolean | EventListenerOptions + ): void { + return super.removeEventListener(type, callback, options) + } +} + +function getDataSize(data: WebSocketData): number { + if (typeof data === 'string') { + return data.length + } + + if (data instanceof Blob) { + return data.size + } + + return data.byteLength +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/WebSocketServerConnection.ts b/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/WebSocketServerConnection.ts new file mode 100644 index 0000000000000000000000000000000000000000..e521ff81f718c8a280c531dee863e3008d52d5f2 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/WebSocketServerConnection.ts @@ -0,0 +1,420 @@ +import { invariant } from 'outvariant' +import { + kClose, + WebSocketEventListener, + WebSocketOverride, +} from './WebSocketOverride' +import type { WebSocketData } from './WebSocketTransport' +import type { WebSocketClassTransport } from './WebSocketClassTransport' +import { bindEvent } from './utils/bindEvent' +import { + CancelableMessageEvent, + CancelableCloseEvent, + CloseEvent, +} from './utils/events' + +const kEmitter = Symbol('kEmitter') +const kBoundListener = Symbol('kBoundListener') +const kSend = Symbol('kSend') + +export interface WebSocketServerEventMap { + open: Event + message: MessageEvent + error: Event + close: CloseEvent +} + +export abstract class WebSocketServerConnectionProtocol { + public abstract connect(): void + public abstract send(data: WebSocketData): void + public abstract close(): void + + public abstract addEventListener< + EventType extends keyof WebSocketServerEventMap, + >( + event: EventType, + listener: WebSocketEventListener, + options?: AddEventListenerOptions | boolean + ): void + + public abstract removeEventListener< + EventType extends keyof WebSocketServerEventMap, + >( + event: EventType, + listener: WebSocketEventListener, + options?: EventListenerOptions | boolean + ): void +} + +/** + * The WebSocket server instance represents the actual production + * WebSocket server connection. It's idle by default but you can + * establish it by calling `server.connect()`. + */ +export class WebSocketServerConnection implements WebSocketServerConnectionProtocol { + /** + * A WebSocket instance connected to the original server. + */ + private realWebSocket?: WebSocket + private mockCloseController: AbortController + private realCloseController: AbortController + private [kEmitter]: EventTarget + + constructor( + private readonly client: WebSocketOverride, + private readonly transport: WebSocketClassTransport, + private readonly createConnection: () => WebSocket + ) { + this[kEmitter] = new EventTarget() + this.mockCloseController = new AbortController() + this.realCloseController = new AbortController() + + // Automatically forward outgoing client events + // to the actual server unless the outgoing message event + // has been prevented. The "outgoing" transport event it + // dispatched by the "client" connection. + this.transport.addEventListener('outgoing', (event) => { + // Ignore client messages if the server connection + // hasn't been established yet. Nowhere to forward. + if (typeof this.realWebSocket === 'undefined') { + return + } + + // Every outgoing client message can prevent this forwarding + // by preventing the default of the outgoing message event. + // This listener will be added before user-defined listeners, + // so execute the logic on the next tick. + queueMicrotask(() => { + if (!event.defaultPrevented) { + /** + * @note Use the internal send mechanism so consumers can tell + * apart direct user calls to `server.send()` and internal calls. + * E.g. MSW has to ignore this internal call to log out messages correctly. + */ + this[kSend](event.data) + } + }) + }) + + this.transport.addEventListener( + 'incoming', + this.handleIncomingMessage.bind(this) + ) + } + + /** + * The `WebSocket` instance connected to the original server. + * Accessing this before calling `server.connect()` will throw. + */ + public get socket(): WebSocket { + invariant( + this.realWebSocket, + 'Cannot access "socket" on the original WebSocket server object: the connection is not open. Did you forget to call `server.connect()`?' + ) + + return this.realWebSocket + } + + /** + * Open connection to the original WebSocket server. + */ + public connect(): void { + invariant( + !this.realWebSocket || this.realWebSocket.readyState !== WebSocket.OPEN, + 'Failed to call "connect()" on the original WebSocket instance: the connection already open' + ) + + const realWebSocket = this.createConnection() + + // Inherit the binary type from the mock WebSocket client. + realWebSocket.binaryType = this.client.binaryType + + // Allow the interceptor to listen to when the server connection + // has been established. This isn't necessary to operate with the connection + // but may be beneficial in some cases (like conditionally adding logging). + realWebSocket.addEventListener( + 'open', + (event) => { + this[kEmitter].dispatchEvent( + bindEvent(this.realWebSocket!, new Event('open', event)) + ) + }, + { once: true } + ) + + realWebSocket.addEventListener('message', (event) => { + // Dispatch the "incoming" transport event instead of + // invoking the internal handler directly. This way, + // anyone can listen to the "incoming" event but this + // class is the one resulting in it. + this.transport.dispatchEvent( + bindEvent( + this.realWebSocket!, + new MessageEvent('incoming', { + data: event.data, + origin: event.origin, + }) + ) + ) + }) + + // Close the original connection when the mock client closes. + // E.g. "client.close()" was called. This is never forwarded anywhere. + this.client.addEventListener( + 'close', + (event) => { + this.handleMockClose(event) + }, + { + signal: this.mockCloseController.signal, + } + ) + + // Forward the "close" event to let the interceptor handle + // closures initiated by the original server. + realWebSocket.addEventListener( + 'close', + (event) => { + this.handleRealClose(event) + }, + { + signal: this.realCloseController.signal, + } + ) + + realWebSocket.addEventListener('error', () => { + const errorEvent = bindEvent( + realWebSocket, + new Event('error', { cancelable: true }) + ) + + // Emit the "error" event on the `server` connection + // to let the interceptor react to original server errors. + this[kEmitter].dispatchEvent(errorEvent) + + // If the error event from the original server hasn't been prevented, + // forward it to the underlying client. + if (!errorEvent.defaultPrevented) { + this.client.dispatchEvent(bindEvent(this.client, new Event('error'))) + } + }) + + this.realWebSocket = realWebSocket + } + + /** + * Listen for the incoming events from the original WebSocket server. + */ + public addEventListener( + event: EventType, + listener: WebSocketEventListener, + options?: AddEventListenerOptions | boolean + ): void { + if (!Reflect.has(listener, kBoundListener)) { + const boundListener = listener.bind(this.client) + + // Store the bound listener on the original listener + // so the exact bound function can be accessed in "removeEventListener()". + Object.defineProperty(listener, kBoundListener, { + value: boundListener, + enumerable: false, + }) + } + + this[kEmitter].addEventListener( + event, + Reflect.get(listener, kBoundListener) as EventListener, + options + ) + } + + /** + * Remove the listener for the given event. + */ + public removeEventListener( + event: EventType, + listener: WebSocketEventListener, + options?: EventListenerOptions | boolean + ): void { + this[kEmitter].removeEventListener( + event, + Reflect.get(listener, kBoundListener) as EventListener, + options + ) + } + + /** + * Send data to the original WebSocket server. + * @example + * server.send('hello') + * server.send(new Blob(['hello'])) + * server.send(new TextEncoder().encode('hello')) + */ + public send(data: WebSocketData): void { + this[kSend](data) + } + + private [kSend](data: WebSocketData): void { + const { realWebSocket } = this + + invariant( + realWebSocket, + 'Failed to call "server.send()" for "%s": the connection is not open. Did you forget to call "server.connect()"?', + this.client.url + ) + + // Silently ignore writes on the closed original WebSocket. + if ( + realWebSocket.readyState === WebSocket.CLOSING || + realWebSocket.readyState === WebSocket.CLOSED + ) { + return + } + + // Delegate the send to when the original connection is open. + // Unlike the mock, connecting to the original server may take time + // so we cannot call this on the next tick. + if (realWebSocket.readyState === WebSocket.CONNECTING) { + realWebSocket.addEventListener( + 'open', + () => { + realWebSocket.send(data) + }, + { once: true } + ) + return + } + + // Send the data to the original WebSocket server. + realWebSocket.send(data) + } + + /** + * Close the actual server connection. + */ + public close(): void { + const { realWebSocket } = this + + invariant( + realWebSocket, + 'Failed to close server connection for "%s": the connection is not open. Did you forget to call "server.connect()"?', + this.client.url + ) + + // Remove the "close" event listener from the server + // so it doesn't close the underlying WebSocket client + // when you call "server.close()". This also prevents the + // `close` event on the `server` connection from being dispatched twice. + this.realCloseController.abort() + + if ( + realWebSocket.readyState === WebSocket.CLOSING || + realWebSocket.readyState === WebSocket.CLOSED + ) { + return + } + + // Close the actual client connection. + realWebSocket.close() + + // Dispatch the "close" event on the `server` connection. + queueMicrotask(() => { + this[kEmitter].dispatchEvent( + bindEvent( + this.realWebSocket, + new CancelableCloseEvent('close', { + /** + * @note `server.close()` in the interceptor + * always results in clean closures. + */ + code: 1000, + cancelable: true, + }) + ) + ) + }) + } + + private handleIncomingMessage(event: MessageEvent): void { + // Clone the event to dispatch it on this class + // once again and prevent the "already being dispatched" + // exception. Clone it here so we can observe this event + // being prevented in the "server.on()" listeners. + const messageEvent = bindEvent( + event.target, + new CancelableMessageEvent('message', { + data: event.data, + origin: event.origin, + cancelable: true, + }) + ) + + /** + * @note Emit "message" event on the server connection + * instance to let the interceptor know about these + * incoming events from the original server. In that listener, + * the interceptor can modify or skip the event forwarding + * to the mock WebSocket instance. + */ + this[kEmitter].dispatchEvent(messageEvent) + + /** + * @note Forward the incoming server events to the client. + * Preventing the default on the message event stops this. + */ + if (!messageEvent.defaultPrevented) { + this.client.dispatchEvent( + bindEvent( + /** + * @note Bind the forwarded original server events + * to the mock WebSocket instance so it would + * dispatch them straight away. + */ + this.client, + // Clone the message event again to prevent + // the "already being dispatched" exception. + new MessageEvent('message', { + data: event.data, + origin: event.origin, + }) + ) + ) + } + } + + private handleMockClose(_event: Event): void { + // Close the original connection if the mock client closes. + if (this.realWebSocket) { + this.realWebSocket.close() + } + } + + private handleRealClose(event: CloseEvent): void { + // For closures originating from the original server, + // remove the "close" listener from the mock client. + // original close -> (?) client[kClose]() --X--> "close" (again). + this.mockCloseController.abort() + + const closeEvent = bindEvent( + this.realWebSocket, + new CancelableCloseEvent('close', { + code: event.code, + reason: event.reason, + wasClean: event.wasClean, + cancelable: true, + }) + ) + + this[kEmitter].dispatchEvent(closeEvent) + + // If the close event from the server hasn't been prevented, + // forward the closure to the mock client. + if (!closeEvent.defaultPrevented) { + // Close the intercepted client forcefully to + // allow non-configurable status codes from the server. + // If the socket has been closed by now, no harm calling + // this again—it will have no effect. + this.client[kClose](event.code, event.reason) + } + } +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/WebSocketTransport.ts b/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/WebSocketTransport.ts new file mode 100644 index 0000000000000000000000000000000000000000..973f511ed983d3dc81ad895a317d66d24460ffe1 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/WebSocketTransport.ts @@ -0,0 +1,39 @@ +import { CloseEvent } from './utils/events' + +export type WebSocketData = string | ArrayBufferLike | Blob | ArrayBufferView + +export type WebSocketTransportEventMap = { + incoming: MessageEvent + outgoing: MessageEvent + close: CloseEvent +} + +export type StrictEventListenerOrEventListenerObject = + | ((this: WebSocket, event: EventType) => void) + | { + handleEvent(this: WebSocket, event: EventType): void + } + +export interface WebSocketTransport { + addEventListener( + event: EventType, + listener: StrictEventListenerOrEventListenerObject< + WebSocketTransportEventMap[EventType] + > | null, + options?: boolean | AddEventListenerOptions + ): void + + dispatchEvent( + event: WebSocketTransportEventMap[EventType] + ): boolean + + /** + * Send the data from the server to this client. + */ + send(data: WebSocketData): void + + /** + * Close the client connection. + */ + close(code?: number, reason?: string): void +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/index.ts b/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..c8b8cd59fdf6ee340224b4b3cf5d103a629485fa --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/index.ts @@ -0,0 +1,184 @@ +import { Interceptor } from '../../Interceptor' +import { + WebSocketClientConnectionProtocol, + WebSocketClientConnection, + type WebSocketClientEventMap, +} from './WebSocketClientConnection' +import { + WebSocketServerConnectionProtocol, + WebSocketServerConnection, + type WebSocketServerEventMap, +} from './WebSocketServerConnection' +import { WebSocketClassTransport } from './WebSocketClassTransport' +import { + kClose, + kPassthroughPromise, + WebSocketOverride, +} from './WebSocketOverride' +import { bindEvent } from './utils/bindEvent' +import { hasConfigurableGlobal } from '../../utils/hasConfigurableGlobal' +import { emitAsync } from '../../utils/emitAsync' +import { patchesRegistry } from '../../utils/patchesRegistry' + +export { + type WebSocketData, + type WebSocketTransport, +} from './WebSocketTransport' +export { + WebSocketClientEventMap, + WebSocketClientConnectionProtocol, + WebSocketClientConnection, + WebSocketServerEventMap, + WebSocketServerConnectionProtocol, + WebSocketServerConnection, +} + +export { + CloseEvent, + CancelableCloseEvent, + CancelableMessageEvent, +} from './utils/events' + +export type WebSocketEventMap = { + connection: [args: WebSocketConnectionData] +} + +export type WebSocketConnectionData = { + /** + * The incoming WebSocket client connection. + */ + client: WebSocketClientConnection + + /** + * The original WebSocket server connection. + */ + server: WebSocketServerConnection + + /** + * The connection information. + */ + info: { + /** + * The protocols supported by the WebSocket client. + */ + protocols: string | Array | undefined + } +} + +/** + * Intercept the outgoing WebSocket connections created using + * the global `WebSocket` class. + */ +export class WebSocketInterceptor extends Interceptor { + static symbol = Symbol.for('websocket-interceptor') + + constructor() { + super(WebSocketInterceptor.symbol) + } + + protected checkEnvironment(): boolean { + return hasConfigurableGlobal('WebSocket') + } + + protected setup(): void { + const logger = this.logger.extend('setup') + + const WebSocketProxy = new Proxy(globalThis.WebSocket, { + construct: ( + target, + args: ConstructorParameters, + newTarget + ) => { + const [url, protocols] = args + + const createConnection = (): WebSocket => { + return Reflect.construct(target, args, newTarget) + } + + // All WebSocket instances are mocked and don't forward + // any events to the original server (no connection established). + // To forward the events, the user must use the "server.send()" API. + const socket = new WebSocketOverride(url, protocols) + const transport = new WebSocketClassTransport(socket) + + // Emit the "connection" event to the interceptor on the next tick + // so the client can modify WebSocket options, like "binaryType" + // while the connection is already pending. + queueMicrotask(async () => { + try { + const server = new WebSocketServerConnection( + socket, + transport, + createConnection + ) + + const hasConnectionListeners = + this.emitter.listenerCount('connection') > 0 + + // The "globalThis.WebSocket" class stands for + // the client-side connection. Assume it's established + // as soon as the WebSocket instance is constructed. + await emitAsync(this.emitter, 'connection', { + client: new WebSocketClientConnection(socket, transport), + server, + info: { + protocols, + }, + }) + + if (hasConnectionListeners) { + socket[kPassthroughPromise].resolve(false) + } else { + socket[kPassthroughPromise].resolve(true) + + server.connect() + + // Forward the "open" event from the original server + // to the mock WebSocket client in the case of a passthrough connection. + server.addEventListener('open', () => { + socket.dispatchEvent(bindEvent(socket, new Event('open'))) + + // Forward the original connection protocol to the + // mock WebSocket client. + if (server['realWebSocket']) { + socket.protocol = server['realWebSocket'].protocol + } + }) + } + } catch (error) { + /** + * @note Translate unhandled exceptions during the connection + * handling (i.e. interceptor exceptions) as WebSocket connection + * closures with error. This prevents from the exceptions occurring + * in `queueMicrotask` from being process-wide and uncatchable. + */ + if (error instanceof Error) { + socket.dispatchEvent(new Event('error')) + + // No need to close the connection if it's already being closed. + // E.g. the interceptor called `client.close()` and then threw an error. + if ( + socket.readyState !== WebSocket.CLOSING && + socket.readyState !== WebSocket.CLOSED + ) { + socket[kClose](1011, error.message, false) + } + + console.error(error) + } + } + }) + + return socket + }, + }) + + logger.info('patching global WebSocket...') + + this.subscriptions.push( + patchesRegistry.applyPatch(globalThis, 'WebSocket', () => WebSocketProxy) + ) + + logger.info('global WebSocket patched!', globalThis.WebSocket.name) + } +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/utils/bindEvent.test.ts b/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/utils/bindEvent.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..7871961f0f24e4665cbddfdd5d2bfe91ee9b7741 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/utils/bindEvent.test.ts @@ -0,0 +1,27 @@ +/** + * @vitest-environment node + */ +import { it, expect } from 'vitest' +import { bindEvent } from './bindEvent' + +it('sets the "target" on the given event', () => { + class Target {} + const target = new Target() + const event = new Event('open') + bindEvent(target, event) + + expect(event.type).toBe('open') + expect(event.target).toEqual(target) +}) + +it('overrides existing "target" on the given event', () => { + class Target {} + const oldTarget = new Target() + const newTarget = new Target() + const event = new Event('open') + bindEvent(oldTarget, event) + bindEvent(newTarget, event) + + expect(event.type).toBe('open') + expect(event.target).toEqual(newTarget) +}) diff --git a/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/utils/bindEvent.ts b/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/utils/bindEvent.ts new file mode 100644 index 0000000000000000000000000000000000000000..8efa6820263a83eb6ff9d892ad92c19ca2074626 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/utils/bindEvent.ts @@ -0,0 +1,21 @@ +type EventWithTarget = E & { target: T } + +export function bindEvent( + target: T, + event: E +): EventWithTarget { + Object.defineProperties(event, { + target: { + value: target, + enumerable: true, + writable: true, + }, + currentTarget: { + value: target, + enumerable: true, + writable: true, + }, + }) + + return event as EventWithTarget +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/utils/events.test.ts b/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/utils/events.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..84a2116335b1ca8a9f11f74e1d52023ec2e7a425 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/utils/events.test.ts @@ -0,0 +1,101 @@ +/** + * @vitest-environment node + */ +import { describe, it, expect } from 'vitest' +import { CancelableMessageEvent, CloseEvent } from './events' + +describe(CancelableMessageEvent, () => { + it('initiates with the right defaults', () => { + const event = new CancelableMessageEvent('message', { + data: 'hello', + }) + + expect(event).toBeInstanceOf(MessageEvent) + expect(event.type).toBe('message') + expect(event.data).toBe('hello') + expect(event.cancelable).toBe(false) + expect(event.defaultPrevented).toBe(false) + }) + + it('initiates a cancelable event', () => { + const event = new CancelableMessageEvent('message', { + data: 'hello', + cancelable: true, + }) + + expect(event).toBeInstanceOf(MessageEvent) + expect(event.type).toBe('message') + expect(event.data).toBe('hello') + expect(event.cancelable).toBe(true) + expect(event.defaultPrevented).toBe(false) + }) + + it('cancels a cancelable event when calling "preventDefault()"', () => { + const event = new CancelableMessageEvent('message', { + data: 'hello', + cancelable: true, + }) + + expect(event.defaultPrevented).toBe(false) + event.preventDefault() + expect(event.defaultPrevented).toBe(true) + }) + + it('does nothing when calling "preventDefault()" on a non-cancelable event', () => { + const event = new CancelableMessageEvent('message', { + data: 'hello', + }) + + expect(event.defaultPrevented).toBe(false) + event.preventDefault() + expect(event.defaultPrevented).toBe(false) + }) + + it('supports setting the "cancelable" value directly', () => { + const event = new CancelableMessageEvent('message', {}) + /** + * @note HappyDOM sets the "cancelable" and "preventDefault" + * event properties directly. That's no-op as far as I know + * but they do it and we have to account for that. + */ + event.cancelable = true + expect(event.cancelable).toBe(true) + }) + + it('supports setting the "defaultPrevented" value directly', () => { + const event = new CancelableMessageEvent('message', {}) + /** + * @note HappyDOM sets the "cancelable" and "preventDefault" + * event properties directly. That's no-op as far as I know + * but they do it and we have to account for that. + */ + event.defaultPrevented = true + expect(event.defaultPrevented).toBe(true) + }) +}) + +describe(CloseEvent, () => { + it('initiates with the right defaults', () => { + const event = new CloseEvent('close') + + expect(event).toBeInstanceOf(Event) + expect(event.type).toBe('close') + expect(event.code).toBe(0) + expect(event.reason).toBe('') + expect(event.wasClean).toBe(false) + }) + + it('initiates with custom values', () => { + const event = new CloseEvent('close', { + code: 1003, + reason: 'close reason', + wasClean: true, + }) + + expect(event).toBeInstanceOf(Event) + expect(event.type).toBe('close') + expect(event.code).toBe(1003) + expect(event.reason).toBe('close reason') + expect(event.wasClean).toBe(true) + }) +}) diff --git a/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/utils/events.ts b/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/utils/events.ts new file mode 100644 index 0000000000000000000000000000000000000000..cb4c059ff630767e207e1ecd69afeaeccd57cf39 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/WebSocket/utils/events.ts @@ -0,0 +1,94 @@ +const kCancelable = Symbol('kCancelable') +const kDefaultPrevented = Symbol('kDefaultPrevented') + +/** + * A `MessageEvent` superset that supports event cancellation + * in Node.js. It's rather non-intrusive so it can be safely + * used in the browser as well. + * + * @see https://github.com/nodejs/node/issues/51767 + */ +export class CancelableMessageEvent extends MessageEvent { + [kCancelable]: boolean; + [kDefaultPrevented]: boolean + + constructor(type: string, init: MessageEventInit) { + super(type, init) + this[kCancelable] = !!init.cancelable + this[kDefaultPrevented] = false + } + + get cancelable() { + return this[kCancelable] + } + + set cancelable(nextCancelable) { + this[kCancelable] = nextCancelable + } + + get defaultPrevented() { + return this[kDefaultPrevented] + } + + set defaultPrevented(nextDefaultPrevented) { + this[kDefaultPrevented] = nextDefaultPrevented + } + + public preventDefault(): void { + if (this.cancelable && !this[kDefaultPrevented]) { + this[kDefaultPrevented] = true + } + } +} + +interface CloseEventInit extends EventInit { + code?: number + reason?: string + wasClean?: boolean +} + +export class CloseEvent extends Event { + public code: number + public reason: string + public wasClean: boolean + + constructor(type: string, init: CloseEventInit = {}) { + super(type, init) + this.code = init.code === undefined ? 0 : init.code + this.reason = init.reason === undefined ? '' : init.reason + this.wasClean = init.wasClean === undefined ? false : init.wasClean + } +} + +export class CancelableCloseEvent extends CloseEvent { + [kCancelable]: boolean; + [kDefaultPrevented]: boolean + + constructor(type: string, init: CloseEventInit = {}) { + super(type, init) + this[kCancelable] = !!init.cancelable + this[kDefaultPrevented] = false + } + + get cancelable() { + return this[kCancelable] + } + + set cancelable(nextCancelable) { + this[kCancelable] = nextCancelable + } + + get defaultPrevented() { + return this[kDefaultPrevented] + } + + set defaultPrevented(nextDefaultPrevented) { + this[kDefaultPrevented] = nextDefaultPrevented + } + + public preventDefault(): void { + if (this.cancelable && !this[kDefaultPrevented]) { + this[kDefaultPrevented] = true + } + } +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/XMLHttpRequestController.ts b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/XMLHttpRequestController.ts new file mode 100644 index 0000000000000000000000000000000000000000..6a47ac896f901d973cedfdb3a1d1876fab731083 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/XMLHttpRequestController.ts @@ -0,0 +1,747 @@ +import { invariant } from 'outvariant' +import { isNodeProcess } from 'is-node-process' +import type { Logger } from '@open-draft/logger' +import { concatArrayBuffer } from './utils/concatArrayBuffer' +import { createEvent } from './utils/createEvent' +import { + decodeBuffer, + encodeBuffer, + toArrayBuffer, +} from '../../utils/bufferUtils' +import { createProxy } from '../../utils/createProxy' +import { isDomParserSupportedType } from './utils/isDomParserSupportedType' +import { parseJson } from '../../utils/parseJson' +import { createResponse } from './utils/createResponse' +import { INTERNAL_REQUEST_ID_HEADER_NAME } from '../../Interceptor' +import { createRequestId } from '../../createRequestId' +import { getBodyByteLength } from './utils/getBodyByteLength' +import { setRawRequest } from '../../getRawRequest' +import { FetchRequest } from '../../utils/fetchUtils' + +const kIsRequestHandled = Symbol('kIsRequestHandled') +const IS_NODE = isNodeProcess() +const kFetchRequest = Symbol('kFetchRequest') + +/** + * An `XMLHttpRequest` instance controller that allows us + * to handle any given request instance (e.g. responding to it). + */ +export class XMLHttpRequestController { + public request: XMLHttpRequest + public requestId: string + public onRequest?: ( + this: XMLHttpRequestController, + args: { + request: Request + requestId: string + } + ) => Promise + public onResponse?: ( + this: XMLHttpRequestController, + args: { + response: Response + isMockedResponse: boolean + request: Request + requestId: string + } + ) => void; + + [kIsRequestHandled]: boolean; + [kFetchRequest]?: Request + private method: string = 'GET' + private url: URL = null as any + private requestHeaders: Headers + private responseBuffer: Uint8Array + private events: Map> + private uploadEvents: Map< + keyof XMLHttpRequestEventTargetEventMap, + Array + > + + constructor( + readonly initialRequest: XMLHttpRequest, + public logger: Logger + ) { + this[kIsRequestHandled] = false + + this.events = new Map() + this.uploadEvents = new Map() + this.requestId = createRequestId() + this.requestHeaders = new Headers() + this.responseBuffer = new Uint8Array() + + this.request = createProxy(initialRequest, { + setProperty: ([propertyName, nextValue], invoke) => { + switch (propertyName) { + case 'ontimeout': { + const eventName = propertyName.slice( + 2 + ) as keyof XMLHttpRequestEventTargetEventMap + + /** + * @note Proxy callbacks to event listeners because JSDOM has trouble + * translating these properties to callbacks. It seemed to be operating + * on events exclusively. + */ + this.request.addEventListener(eventName, nextValue as any) + + return invoke() + } + + default: { + return invoke() + } + } + }, + methodCall: ([methodName, args], invoke) => { + switch (methodName) { + case 'open': { + const [method, url] = args as [string, string | undefined] + + if (typeof url === 'undefined') { + this.method = 'GET' + this.url = toAbsoluteUrl(method) + } else { + this.method = method + this.url = toAbsoluteUrl(url) + } + + this.logger = this.logger.extend(`${this.method} ${this.url.href}`) + this.logger.info('open', this.method, this.url.href) + + return invoke() + } + + case 'addEventListener': { + const [eventName, listener] = args as [ + keyof XMLHttpRequestEventTargetEventMap, + Function, + ] + + this.registerEvent(eventName, listener) + this.logger.info('addEventListener', eventName, listener) + + return invoke() + } + + case 'setRequestHeader': { + const [name, value] = args as [string, string] + this.requestHeaders.set(name, value) + + this.logger.info('setRequestHeader', name, value) + + return invoke() + } + + case 'send': { + const [body] = args as [ + body?: XMLHttpRequestBodyInit | Document | null, + ] + + this.request.addEventListener('load', () => { + if (typeof this.onResponse !== 'undefined') { + // Create a Fetch API Response representation of whichever + // response this XMLHttpRequest received. Note those may + // be either a mocked and the original response. + const fetchResponse = createResponse( + this.request, + /** + * The `response` property is the right way to read + * the ambiguous response body, as the request's "responseType" may differ. + * @see https://xhr.spec.whatwg.org/#the-response-attribute + */ + this.request.response + ) + + // Notify the consumer about the response. + this.onResponse.call(this, { + response: fetchResponse, + isMockedResponse: this[kIsRequestHandled], + request: fetchRequest, + requestId: this.requestId!, + }) + } + }) + + const requestBody = + typeof body === 'string' ? encodeBuffer(body) : body + + // Delegate request handling to the consumer. + const fetchRequest = this.toFetchApiRequest(requestBody) + this[kFetchRequest] = fetchRequest.clone() + + /** + * @note Start request handling on the next tick so that the user + * could add event listeners for "loadend" before the interceptor fires it. + */ + queueMicrotask(() => { + const onceRequestSettled = + this.onRequest?.call(this, { + request: fetchRequest, + requestId: this.requestId!, + }) || Promise.resolve() + + onceRequestSettled.finally(() => { + // If the consumer didn't handle the request (called `.respondWith()`) perform it as-is. + if (!this[kIsRequestHandled]) { + this.logger.info( + 'request callback settled but request has not been handled (readystate %d), performing as-is...', + this.request.readyState + ) + + /** + * @note Set the intercepted request ID on the original request in Node.js + * so that if it triggers any other interceptors, they don't attempt + * to process it once again. + * + * For instance, XMLHttpRequest is often implemented via "http.ClientRequest" + * and we don't want for both XHR and ClientRequest interceptors to + * handle the same request at the same time (e.g. emit the "response" event twice). + */ + if (IS_NODE) { + this.request.setRequestHeader( + INTERNAL_REQUEST_ID_HEADER_NAME, + this.requestId! + ) + } + + return invoke() + } + }) + }) + + break + } + + default: { + return invoke() + } + } + }, + }) + + /** + * Proxy the `.upload` property to gather the event listeners/callbacks. + */ + define( + this.request, + 'upload', + createProxy(this.request.upload, { + setProperty: ([propertyName, nextValue], invoke) => { + switch (propertyName) { + case 'onloadstart': + case 'onprogress': + case 'onaboart': + case 'onerror': + case 'onload': + case 'ontimeout': + case 'onloadend': { + const eventName = propertyName.slice( + 2 + ) as keyof XMLHttpRequestEventTargetEventMap + + this.registerUploadEvent(eventName, nextValue as Function) + } + } + + return invoke() + }, + methodCall: ([methodName, args], invoke) => { + switch (methodName) { + case 'addEventListener': { + const [eventName, listener] = args as [ + keyof XMLHttpRequestEventTargetEventMap, + Function, + ] + this.registerUploadEvent(eventName, listener) + this.logger.info('upload.addEventListener', eventName, listener) + + return invoke() + } + } + }, + }) + ) + } + + private registerEvent( + eventName: keyof XMLHttpRequestEventTargetEventMap, + listener: Function + ): void { + const prevEvents = this.events.get(eventName) || [] + const nextEvents = prevEvents.concat(listener) + this.events.set(eventName, nextEvents) + + this.logger.info('registered event "%s"', eventName, listener) + } + + private registerUploadEvent( + eventName: keyof XMLHttpRequestEventTargetEventMap, + listener: Function + ): void { + const prevEvents = this.uploadEvents.get(eventName) || [] + const nextEvents = prevEvents.concat(listener) + this.uploadEvents.set(eventName, nextEvents) + + this.logger.info('registered upload event "%s"', eventName, listener) + } + + /** + * Responds to the current request with the given + * Fetch API `Response` instance. + */ + public async respondWith(response: Response): Promise { + /** + * @note Since `XMLHttpRequestController` delegates the handling of the responses + * to the "load" event listener that doesn't distinguish between the mocked and original + * responses, mark the request that had a mocked response with a corresponding symbol. + * + * Mark this request as having a mocked response immediately since + * calculating request/response total body length is asynchronous. + */ + this[kIsRequestHandled] = true + + /** + * Dispatch request upload events for requests with a body. + * @see https://github.com/mswjs/interceptors/issues/573 + */ + if (this[kFetchRequest]) { + const totalRequestBodyLength = await getBodyByteLength( + this[kFetchRequest] + ) + + this.trigger('loadstart', this.request.upload, { + loaded: 0, + total: totalRequestBodyLength, + }) + this.trigger('progress', this.request.upload, { + loaded: totalRequestBodyLength, + total: totalRequestBodyLength, + }) + this.trigger('load', this.request.upload, { + loaded: totalRequestBodyLength, + total: totalRequestBodyLength, + }) + + this.trigger('loadend', this.request.upload, { + loaded: totalRequestBodyLength, + total: totalRequestBodyLength, + }) + } + + this.logger.info( + 'responding with a mocked response: %d %s', + response.status, + response.statusText + ) + + define(this.request, 'status', response.status) + define(this.request, 'statusText', response.statusText) + define(this.request, 'responseURL', this.url.href) + + this.request.getResponseHeader = new Proxy(this.request.getResponseHeader, { + apply: (_, __, args: [name: string]) => { + this.logger.info('getResponseHeader', args[0]) + + if (this.request.readyState < this.request.HEADERS_RECEIVED) { + this.logger.info('headers not received yet, returning null') + + // Headers not received yet, nothing to return. + return null + } + + const headerValue = response.headers.get(args[0]) + this.logger.info( + 'resolved response header "%s" to', + args[0], + headerValue + ) + + return headerValue + }, + }) + + this.request.getAllResponseHeaders = new Proxy( + this.request.getAllResponseHeaders, + { + apply: () => { + this.logger.info('getAllResponseHeaders') + + if (this.request.readyState < this.request.HEADERS_RECEIVED) { + this.logger.info('headers not received yet, returning empty string') + + // Headers not received yet, nothing to return. + return '' + } + + const headersList = Array.from(response.headers.entries()) + const allHeaders = headersList + .map(([headerName, headerValue]) => { + return `${headerName}: ${headerValue}` + }) + .join('\r\n') + + this.logger.info('resolved all response headers to', allHeaders) + + return allHeaders + }, + } + ) + + // Update the response getters to resolve against the mocked response. + Object.defineProperties(this.request, { + response: { + enumerable: true, + configurable: false, + get: () => this.response, + }, + responseText: { + enumerable: true, + configurable: false, + get: () => this.responseText, + }, + responseXML: { + enumerable: true, + configurable: false, + get: () => this.responseXML, + }, + }) + + const totalResponseBodyLength = await getBodyByteLength(response.clone()) + + this.logger.info('calculated response body length', totalResponseBodyLength) + + this.trigger('loadstart', this.request, { + loaded: 0, + total: totalResponseBodyLength, + }) + + this.setReadyState(this.request.HEADERS_RECEIVED) + this.setReadyState(this.request.LOADING) + + const finalizeResponse = () => { + this.logger.info('finalizing the mocked response...') + + this.setReadyState(this.request.DONE) + + this.trigger('load', this.request, { + loaded: this.responseBuffer.byteLength, + total: totalResponseBodyLength, + }) + + this.trigger('loadend', this.request, { + loaded: this.responseBuffer.byteLength, + total: totalResponseBodyLength, + }) + } + + if (response.body) { + this.logger.info('mocked response has body, streaming...') + + const reader = response.body.getReader() + + const readNextResponseBodyChunk = async () => { + const { value, done } = await reader.read() + + if (done) { + this.logger.info('response body stream done!') + finalizeResponse() + return + } + + if (value) { + this.logger.info('read response body chunk:', value) + this.responseBuffer = concatArrayBuffer(this.responseBuffer, value) + + this.trigger('progress', this.request, { + loaded: this.responseBuffer.byteLength, + total: totalResponseBodyLength, + }) + } + + readNextResponseBodyChunk() + } + + readNextResponseBodyChunk() + } else { + finalizeResponse() + } + } + + private responseBufferToText(): string { + return decodeBuffer(this.responseBuffer) + } + + get response(): unknown { + this.logger.info( + 'getResponse (responseType: %s)', + this.request.responseType + ) + + if (this.request.readyState !== this.request.DONE) { + return null + } + + switch (this.request.responseType) { + case 'json': { + const responseJson = parseJson(this.responseBufferToText()) + this.logger.info('resolved response JSON', responseJson) + + return responseJson + } + + case 'arraybuffer': { + const arrayBuffer = toArrayBuffer(this.responseBuffer) + this.logger.info('resolved response ArrayBuffer', arrayBuffer) + + return arrayBuffer + } + + case 'blob': { + const mimeType = + this.request.getResponseHeader('Content-Type') || 'text/plain' + const responseBlob = new Blob([this.responseBufferToText()], { + type: mimeType, + }) + + this.logger.info( + 'resolved response Blob (mime type: %s)', + responseBlob, + mimeType + ) + + return responseBlob + } + + default: { + const responseText = this.responseBufferToText() + this.logger.info( + 'resolving "%s" response type as text', + this.request.responseType, + responseText + ) + + return responseText + } + } + } + + get responseText(): string { + /** + * Throw when trying to read the response body as text when the + * "responseType" doesn't expect text. This just respects the spec better. + * @see https://xhr.spec.whatwg.org/#the-responsetext-attribute + */ + invariant( + this.request.responseType === '' || this.request.responseType === 'text', + 'InvalidStateError: The object is in invalid state.' + ) + + if ( + this.request.readyState !== this.request.LOADING && + this.request.readyState !== this.request.DONE + ) { + return '' + } + + const responseText = this.responseBufferToText() + this.logger.info('getResponseText: "%s"', responseText) + + return responseText + } + + get responseXML(): Document | null { + invariant( + this.request.responseType === '' || + this.request.responseType === 'document', + 'InvalidStateError: The object is in invalid state.' + ) + + if (this.request.readyState !== this.request.DONE) { + return null + } + + const contentType = this.request.getResponseHeader('Content-Type') || '' + + if (typeof DOMParser === 'undefined') { + console.warn( + 'Cannot retrieve XMLHttpRequest response body as XML: DOMParser is not defined. You are likely using an environment that is not browser or does not polyfill browser globals correctly.' + ) + return null + } + + if (isDomParserSupportedType(contentType)) { + return new DOMParser().parseFromString( + this.responseBufferToText(), + contentType + ) + } + + return null + } + + public errorWith(error?: Error): void { + /** + * @note Mark this request as handled even if it received a mock error. + * This prevents the controller from trying to perform this request as-is. + */ + this[kIsRequestHandled] = true + this.logger.info('responding with an error') + + this.setReadyState(this.request.DONE) + this.trigger('error', this.request) + this.trigger('loadend', this.request) + } + + /** + * Transitions this request's `readyState` to the given one. + */ + private setReadyState(nextReadyState: number): void { + this.logger.info( + 'setReadyState: %d -> %d', + this.request.readyState, + nextReadyState + ) + + if (this.request.readyState === nextReadyState) { + this.logger.info('ready state identical, skipping transition...') + return + } + + define(this.request, 'readyState', nextReadyState) + + this.logger.info('set readyState to: %d', nextReadyState) + + if (nextReadyState !== this.request.UNSENT) { + this.logger.info('triggering "readystatechange" event...') + + this.trigger('readystatechange', this.request) + } + } + + /** + * Triggers given event on the `XMLHttpRequest` instance. + */ + private trigger< + EventName extends keyof (XMLHttpRequestEventTargetEventMap & { + readystatechange: ProgressEvent + }), + >( + eventName: EventName, + target: XMLHttpRequest | XMLHttpRequestUpload, + options?: ProgressEventInit + ): void { + const callback = (target as XMLHttpRequest)[`on${eventName}`] + const event = createEvent(target, eventName, options) + + this.logger.info('trigger "%s"', eventName, options || '') + + // Invoke direct callbacks. + if (typeof callback === 'function') { + this.logger.info('found a direct "%s" callback, calling...', eventName) + callback.call(target as XMLHttpRequest, event) + } + + // Invoke event listeners. + const events = + target instanceof XMLHttpRequestUpload ? this.uploadEvents : this.events + + for (const [registeredEventName, listeners] of events) { + if (registeredEventName === eventName) { + this.logger.info( + 'found %d listener(s) for "%s" event, calling...', + listeners.length, + eventName + ) + + listeners.forEach((listener) => listener.call(target, event)) + } + } + } + + /** + * Converts this `XMLHttpRequest` instance into a Fetch API `Request` instance. + */ + private toFetchApiRequest( + body: XMLHttpRequestBodyInit | Document | null | undefined + ): Request { + this.logger.info('converting request to a Fetch API Request...') + + // If the `Document` is used as the body of this XMLHttpRequest, + // set its inner text as the Fetch API Request body. + const resolvedBody = + body instanceof Document ? body.documentElement.innerText : body + + const fetchRequest = new FetchRequest(this.url.href, { + method: this.method, + headers: this.requestHeaders, + /** + * @see https://xhr.spec.whatwg.org/#cross-origin-credentials + */ + credentials: this.request.withCredentials ? 'include' : 'same-origin', + body: ['GET', 'HEAD'].includes(this.method.toUpperCase()) + ? null + : resolvedBody, + }) + + const proxyHeaders = createProxy(fetchRequest.headers, { + methodCall: ([methodName, args], invoke) => { + // Forward the latest state of the internal request headers + // because the interceptor might have modified them + // without responding to the request. + switch (methodName) { + case 'append': + case 'set': { + const [headerName, headerValue] = args as [string, string] + this.request.setRequestHeader(headerName, headerValue) + break + } + + case 'delete': { + const [headerName] = args as [string] + console.warn( + `XMLHttpRequest: Cannot remove a "${headerName}" header from the Fetch API representation of the "${fetchRequest.method} ${fetchRequest.url}" request. XMLHttpRequest headers cannot be removed.` + ) + break + } + } + + return invoke() + }, + }) + define(fetchRequest, 'headers', proxyHeaders) + setRawRequest(fetchRequest, this.request) + + this.logger.info('converted request to a Fetch API Request!', fetchRequest) + + return fetchRequest + } +} + +function toAbsoluteUrl(url: string | URL): URL { + /** + * @note XMLHttpRequest interceptor may run in environments + * that implement XMLHttpRequest but don't implement "location" + * (for example, React Native). If that's the case, return the + * input URL as-is (nothing to be relative to). + * @see https://github.com/mswjs/msw/issues/1777 + */ + if (typeof location === 'undefined') { + return new URL(url) + } + + return new URL(url.toString(), location.href) +} + +function define( + target: object, + property: string | symbol, + value: unknown +): void { + Reflect.defineProperty(target, property, { + // Ensure writable properties to allow redefining readonly properties. + writable: true, + enumerable: true, + value, + }) +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/XMLHttpRequestProxy.ts b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/XMLHttpRequestProxy.ts new file mode 100644 index 0000000000000000000000000000000000000000..4cfe8b89b28d3c73d13f98c419b1745ef086de1f --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/XMLHttpRequestProxy.ts @@ -0,0 +1,121 @@ +import type { Logger } from '@open-draft/logger' +import { XMLHttpRequestEmitter } from '.' +import { RequestController } from '../../RequestController' +import { XMLHttpRequestController } from './XMLHttpRequestController' +import { handleRequest } from '../../utils/handleRequest' +import { isResponseError } from '../../utils/responseUtils' + +export interface XMLHttpRequestProxyOptions { + emitter: XMLHttpRequestEmitter + logger: Logger +} + +/** + * Create a proxied `XMLHttpRequest` class. + * The proxied class establishes spies on certain methods, + * allowing us to intercept requests and respond to them. + */ +export function createXMLHttpRequestProxy({ + emitter, + logger, +}: XMLHttpRequestProxyOptions) { + const XMLHttpRequestProxy = new Proxy(globalThis.XMLHttpRequest, { + construct(target, args, newTarget) { + logger.info('constructed new XMLHttpRequest') + + const originalRequest = Reflect.construct( + target, + args, + newTarget + ) as XMLHttpRequest + + /** + * @note Forward prototype descriptors onto the proxied object. + * XMLHttpRequest is implemented in JSDOM in a way that assigns + * a bunch of descriptors, like "set responseType()" on the prototype. + * With this propagation, we make sure that those descriptors trigger + * when the user operates with the proxied request instance. + */ + const prototypeDescriptors = Object.getOwnPropertyDescriptors( + target.prototype + ) + for (const propertyName in prototypeDescriptors) { + Reflect.defineProperty( + originalRequest, + propertyName, + prototypeDescriptors[propertyName] + ) + } + + const xhrRequestController = new XMLHttpRequestController( + originalRequest, + logger + ) + + xhrRequestController.onRequest = async function ({ request, requestId }) { + const controller = new RequestController(request, { + passthrough: () => { + this.logger.info( + 'no mocked response received, performing request as-is...' + ) + }, + respondWith: async (response) => { + if (isResponseError(response)) { + this.errorWith(new TypeError('Network error')) + return + } + + await this.respondWith(response) + }, + errorWith: (reason) => { + this.logger.info('request errored!', { error: reason }) + + if (reason instanceof Error) { + this.errorWith(reason) + } + }, + }) + + this.logger.info('awaiting mocked response...') + + this.logger.info( + 'emitting the "request" event for %s listener(s)...', + emitter.listenerCount('request') + ) + + await handleRequest({ + request, + requestId, + controller, + emitter, + }) + } + + xhrRequestController.onResponse = async function ({ + response, + isMockedResponse, + request, + requestId, + }) { + this.logger.info( + 'emitting the "response" event for %s listener(s)...', + emitter.listenerCount('response') + ) + + emitter.emit('response', { + response, + isMockedResponse, + request, + requestId, + }) + } + + // Return the proxied request from the controller + // so that the controller can react to the consumer's interactions + // with this request (opening/sending/etc). + return xhrRequestController.request + }, + }) + + return XMLHttpRequestProxy +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/index.ts b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..b05f4e28e4cfc2f55ebac7830768a405a843fc74 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/index.ts @@ -0,0 +1,40 @@ +import { Emitter } from 'strict-event-emitter' +import { HttpRequestEventMap } from '../../glossary' +import { Interceptor } from '../../Interceptor' +import { createXMLHttpRequestProxy } from './XMLHttpRequestProxy' +import { hasConfigurableGlobal } from '../../utils/hasConfigurableGlobal' +import { patchesRegistry } from '../../utils/patchesRegistry' + +export type XMLHttpRequestEmitter = Emitter + +export class XMLHttpRequestInterceptor extends Interceptor { + static symbol = Symbol.for('xhr-interceptor') + + constructor() { + super(XMLHttpRequestInterceptor.symbol) + } + + protected checkEnvironment() { + return hasConfigurableGlobal('XMLHttpRequest') + } + + protected setup() { + const logger = this.logger.extend('setup') + + logger.info('patching global XMLHttpRequest...') + + this.subscriptions.push( + patchesRegistry.applyPatch(globalThis, 'XMLHttpRequest', () => { + return createXMLHttpRequestProxy({ + emitter: this.emitter, + logger: this.logger, + }) + }) + ) + + logger.info( + 'global XMLHttpRequest patched!', + globalThis.XMLHttpRequest.name + ) + } +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/polyfills/EventPolyfill.ts b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/polyfills/EventPolyfill.ts new file mode 100644 index 0000000000000000000000000000000000000000..4c44e50956064d9ad94f7800555a662901b292f8 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/polyfills/EventPolyfill.ts @@ -0,0 +1,51 @@ +export class EventPolyfill implements Event { + readonly NONE = 0 + readonly CAPTURING_PHASE = 1 + readonly AT_TARGET = 2 + readonly BUBBLING_PHASE = 3 + + public type: string = '' + public srcElement: EventTarget | null = null + public target: EventTarget | null + public currentTarget: EventTarget | null = null + public eventPhase: number = 0 + public timeStamp: number + public isTrusted: boolean = true + public composed: boolean = false + public cancelable: boolean = true + public defaultPrevented: boolean = false + public bubbles: boolean = true + public lengthComputable: boolean = true + public loaded: number = 0 + public total: number = 0 + + cancelBubble: boolean = false + returnValue: boolean = true + + constructor( + type: string, + options?: { target: EventTarget; currentTarget: EventTarget } + ) { + this.type = type + this.target = options?.target || null + this.currentTarget = options?.currentTarget || null + this.timeStamp = Date.now() + } + + public composedPath(): EventTarget[] { + return [] + } + + public initEvent(type: string, bubbles?: boolean, cancelable?: boolean) { + this.type = type + this.bubbles = !!bubbles + this.cancelable = !!cancelable + } + + public preventDefault() { + this.defaultPrevented = true + } + + public stopPropagation() {} + public stopImmediatePropagation() {} +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/polyfills/ProgressEventPolyfill.ts b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/polyfills/ProgressEventPolyfill.ts new file mode 100644 index 0000000000000000000000000000000000000000..20a318816ab8c5f7976e6f3ab9aa237511bd8d00 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/polyfills/ProgressEventPolyfill.ts @@ -0,0 +1,17 @@ +import { EventPolyfill } from './EventPolyfill' + +export class ProgressEventPolyfill extends EventPolyfill { + readonly lengthComputable: boolean + readonly composed: boolean + readonly loaded: number + readonly total: number + + constructor(type: string, init?: ProgressEventInit) { + super(type) + + this.lengthComputable = init?.lengthComputable || false + this.composed = init?.composed || false + this.loaded = init?.loaded || 0 + this.total = init?.total || 0 + } +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/concatArrayBuffer.ts b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/concatArrayBuffer.ts new file mode 100644 index 0000000000000000000000000000000000000000..e8b9fb46606a36ebf169aaf45b9e0a3864010bb3 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/concatArrayBuffer.ts @@ -0,0 +1,12 @@ +/** + * Concatenate two `Uint8Array` buffers. + */ +export function concatArrayBuffer( + left: Uint8Array, + right: Uint8Array +): Uint8Array { + const result = new Uint8Array(left.byteLength + right.byteLength) + result.set(left, 0) + result.set(right, left.byteLength) + return result +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/concateArrayBuffer.test.ts b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/concateArrayBuffer.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..fab59abd6225d4c8e6671a1a2c208fff88ceba07 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/concateArrayBuffer.test.ts @@ -0,0 +1,12 @@ +import { it, expect } from 'vitest' +import { concatArrayBuffer } from './concatArrayBuffer' + +const encoder = new TextEncoder() + +it('concatenates two Uint8Array buffers', () => { + const result = concatArrayBuffer( + encoder.encode('hello'), + encoder.encode('world') + ) + expect(result).toEqual(encoder.encode('helloworld')) +}) diff --git a/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/createEvent.test.ts b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/createEvent.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..0b23216913ebdc16e6c5749e007da19201aba589 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/createEvent.test.ts @@ -0,0 +1,26 @@ +// @vitest-environment jsdom +import { it, expect } from 'vitest' +import { createEvent } from './createEvent' +import { EventPolyfill } from '../polyfills/EventPolyfill' + +const request = new XMLHttpRequest() +request.open('POST', '/user') + +it('returns an EventPolyfill instance with the given target set', () => { + const event = createEvent(request, 'my-event') + const target = event.target as XMLHttpRequest + + expect(event).toBeInstanceOf(EventPolyfill) + expect(target).toBeInstanceOf(XMLHttpRequest) +}) + +it('returns the ProgressEvent instance', () => { + const event = createEvent(request, 'load', { + loaded: 100, + total: 500, + }) + + expect(event).toBeInstanceOf(ProgressEvent) + expect(event.loaded).toBe(100) + expect(event.total).toBe(500) +}) diff --git a/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/createEvent.ts b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/createEvent.ts new file mode 100644 index 0000000000000000000000000000000000000000..be87b3692760dd3cf814d8852e493c5d591440d9 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/createEvent.ts @@ -0,0 +1,41 @@ +import { EventPolyfill } from '../polyfills/EventPolyfill' +import { ProgressEventPolyfill } from '../polyfills/ProgressEventPolyfill' + +const SUPPORTS_PROGRESS_EVENT = typeof ProgressEvent !== 'undefined' + +export function createEvent( + target: XMLHttpRequest | XMLHttpRequestUpload, + type: string, + init?: ProgressEventInit +): EventPolyfill | ProgressEvent { + const progressEvents = [ + 'error', + 'progress', + 'loadstart', + 'loadend', + 'load', + 'timeout', + 'abort', + ] + + /** + * `ProgressEvent` is not supported in React Native. + * @see https://github.com/mswjs/interceptors/issues/40 + */ + const ProgressEventClass = SUPPORTS_PROGRESS_EVENT + ? ProgressEvent + : ProgressEventPolyfill + + const event = progressEvents.includes(type) + ? new ProgressEventClass(type, { + lengthComputable: true, + loaded: init?.loaded || 0, + total: init?.total || 0, + }) + : new EventPolyfill(type, { + target, + currentTarget: target, + }) + + return event +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/createResponse.ts b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/createResponse.ts new file mode 100644 index 0000000000000000000000000000000000000000..4499433bda80e082b1c45c5f3122f0961948d201 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/createResponse.ts @@ -0,0 +1,49 @@ +import { FetchResponse } from '../../../utils/fetchUtils' + +/** + * Creates a Fetch API `Response` instance from the given + * `XMLHttpRequest` instance and a response body. + */ +export function createResponse( + request: XMLHttpRequest, + body: BodyInit | null +): Response { + /** + * Handle XMLHttpRequest responses that must have null as the + * response body when represented using Fetch API Response. + * XMLHttpRequest response will always have an empty string + * as the "request.response" in those cases, resulting in an error + * when constructing a Response instance. + * @see https://github.com/mswjs/interceptors/issues/379 + */ + const responseBodyOrNull = FetchResponse.isResponseWithBody(request.status) + ? body + : null + + return new FetchResponse(responseBodyOrNull, { + url: request.responseURL, + status: request.status, + statusText: request.statusText, + headers: createHeadersFromXMLHttpRequestHeaders( + request.getAllResponseHeaders() + ), + }) +} + +function createHeadersFromXMLHttpRequestHeaders(headersString: string): Headers { + const headers = new Headers() + + const lines = headersString.split(/[\r\n]+/) + for (const line of lines) { + if (line.trim() === '') { + continue + } + + const [name, ...parts] = line.split(': ') + const value = parts.join(': ') + + headers.append(name, value) + } + + return headers +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/getBodyByteLength.test.ts b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/getBodyByteLength.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..eacebb2a5c2ad35442bcf274d35ef4a529093d3d --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/getBodyByteLength.test.ts @@ -0,0 +1,164 @@ +// @vitest-environment node +import { it, expect } from 'vitest' +import { getBodyByteLength } from './getBodyByteLength' + +const url = 'http://localhost' + +it('returns explicit body length set in the "Content-Length" header', async () => { + await expect( + getBodyByteLength(new Request(url, { headers: { 'Content-Length': '10' } })) + ).resolves.toBe(10) + + await expect( + getBodyByteLength( + new Response('hello', { headers: { 'Content-Length': '5' } }) + ) + ).resolves.toBe(5) +}) + +/** + * Request. + */ + +it('returns 0 for a request with an empty body', async () => { + await expect(getBodyByteLength(new Request(url))).resolves.toBe(0) + await expect( + getBodyByteLength(new Request(url, { method: 'POST', body: null })) + ).resolves.toBe(0) + await expect( + getBodyByteLength(new Request(url, { method: 'POST', body: undefined })) + ).resolves.toBe(0) + await expect( + getBodyByteLength(new Request(url, { method: 'POST', body: '' })) + ).resolves.toBe(0) +}) + +it('calculates body length from the text request body', async () => { + await expect( + getBodyByteLength( + new Request(url, { + method: 'POST', + body: 'hello world', + }) + ) + ).resolves.toBe(11) +}) + +it('calculates body length from the URLSearchParams request body', async () => { + await expect( + getBodyByteLength( + new Request(url, { + method: 'POST', + body: new URLSearchParams([['hello', 'world']]), + }) + ) + ).resolves.toBe(11) +}) + +it('calculates body length from the Blob request body', async () => { + await expect( + getBodyByteLength( + new Request(url, { + method: 'POST', + body: new Blob(['hello world']), + }) + ) + ).resolves.toBe(11) +}) + +it('calculates body length from the ArrayBuffer request body', async () => { + await expect( + getBodyByteLength( + new Request(url, { + method: 'POST', + body: await new Blob(['hello world']).arrayBuffer(), + }) + ) + ).resolves.toBe(11) +}) + +it('calculates body length from the FormData request body', async () => { + const formData = new FormData() + formData.append('hello', 'world') + + await expect( + getBodyByteLength( + new Request(url, { + method: 'POST', + body: formData, + }) + ) + ).resolves.toBe(129) +}) + +it('calculates body length from the ReadableStream request body', async () => { + const stream = new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode('hello world')) + controller.close() + }, + }) + + await expect( + getBodyByteLength( + new Request(url, { + method: 'POST', + body: stream, + // @ts-expect-error Undocumented required Undici property. + duplex: 'half', + }) + ) + ).resolves.toBe(11) +}) + +/** + * Response. + */ +it('returns 0 for a response with an empty body', async () => { + await expect(getBodyByteLength(new Response())).resolves.toBe(0) + await expect(getBodyByteLength(new Response(null))).resolves.toBe(0) + await expect(getBodyByteLength(new Response(undefined))).resolves.toBe(0) + await expect(getBodyByteLength(new Response(''))).resolves.toBe(0) +}) + +it('calculates body length from the text response body', async () => { + await expect(getBodyByteLength(new Response('hello world'))).resolves.toBe(11) +}) + +it('calculates body length from the URLSearchParams response body', async () => { + await expect( + getBodyByteLength(new Response(new URLSearchParams([['hello', 'world']]))) + ).resolves.toBe(11) +}) + +it('calculates body length from the Blob response body', async () => { + await expect( + getBodyByteLength(new Response(new Blob(['hello world']))) + ).resolves.toBe(11) +}) + +it('calculates body length from the ArrayBuffer response body', async () => { + await expect( + getBodyByteLength( + new Response(await new Blob(['hello world']).arrayBuffer()) + ) + ).resolves.toBe(11) +}) + +it('calculates body length from the FormData response body', async () => { + const formData = new FormData() + formData.append('hello', 'world') + + await expect(getBodyByteLength(new Response(formData))).resolves.toBe(129) +}) + +it('calculates body length from the ReadableStream response body', async () => { + const stream = new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode('hello world')) + controller.close() + }, + }) + + await expect(getBodyByteLength(new Response(stream))).resolves.toBe(11) +}) diff --git a/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/getBodyByteLength.ts b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/getBodyByteLength.ts new file mode 100644 index 0000000000000000000000000000000000000000..dd7655ab0ce9134873a071045e51a98aa3ec59f0 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/getBodyByteLength.ts @@ -0,0 +1,16 @@ +/** + * Return a total byte length of the given request/response body. + * If the `Content-Length` header is present, it will be used as the byte length. + */ +export async function getBodyByteLength( + input: Request | Response +): Promise { + const explicitContentLength = input.headers.get('content-length') + + if (explicitContentLength != null && explicitContentLength !== '') { + return Number(explicitContentLength) + } + + const buffer = await input.arrayBuffer() + return buffer.byteLength +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/isDomParserSupportedType.ts b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/isDomParserSupportedType.ts new file mode 100644 index 0000000000000000000000000000000000000000..3cf18b04002ed477d343e4a5a058a66766eebb3c --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/XMLHttpRequest/utils/isDomParserSupportedType.ts @@ -0,0 +1,14 @@ +export function isDomParserSupportedType( + type: string +): type is DOMParserSupportedType { + const supportedTypes: Array = [ + 'application/xhtml+xml', + 'application/xml', + 'image/svg+xml', + 'text/html', + 'text/xml', + ] + return supportedTypes.some((supportedType) => { + return type.startsWith(supportedType) + }) +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/fetch/index.ts b/node_modules/@mswjs/interceptors/src/interceptors/fetch/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..0542d4a1501150152c4db78b421e6c36d46925de --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/fetch/index.ts @@ -0,0 +1,203 @@ +import { until } from '@open-draft/until' +import { DeferredPromise } from '@open-draft/deferred-promise' +import { HttpRequestEventMap } from '../../glossary' +import { Interceptor } from '../../Interceptor' +import { RequestController } from '../../RequestController' +import { emitAsync } from '../../utils/emitAsync' +import { handleRequest } from '../../utils/handleRequest' +import { canParseUrl } from '../../utils/canParseUrl' +import { createRequestId } from '../../createRequestId' +import { createNetworkError } from './utils/createNetworkError' +import { followFetchRedirect } from './utils/followRedirect' +import { decompressResponse } from './utils/decompression' +import { hasConfigurableGlobal } from '../../utils/hasConfigurableGlobal' +import { FetchRequest, FetchResponse } from '../../utils/fetchUtils' +import { setRawRequest } from '../../getRawRequest' +import { isResponseError } from '../../utils/responseUtils' +import { patchesRegistry } from '../../utils/patchesRegistry' + +export class FetchInterceptor extends Interceptor { + static symbol = Symbol.for('fetch-interceptor') + + constructor() { + super(FetchInterceptor.symbol) + } + + protected checkEnvironment() { + return hasConfigurableGlobal('fetch') + } + + protected async setup() { + const logger = this.logger.extend('setup') + + const pureFetch = globalThis.fetch + + const fetchProxy: typeof fetch = async (input, init) => { + const requestId = createRequestId() + + /** + * @note Resolve potentially relative request URL + * against the present `location`. This is mainly + * for native `fetch` in JSDOM. + * @see https://github.com/mswjs/msw/issues/1625 + */ + const resolvedInput = + typeof input === 'string' && + typeof location !== 'undefined' && + !canParseUrl(input) + ? new URL(input, location.href) + : input + + const request = new FetchRequest(resolvedInput, init) + + /** + * @note Set the raw request only if a Request instance was provided to fetch. + */ + if (input instanceof Request) { + setRawRequest(request, input) + } + + const responsePromise = new DeferredPromise() + + const controller = new RequestController(request, { + passthrough: async () => { + this.logger.info('request has not been handled, passthrough...') + + /** + * @note Clone the request instance right before performing it. + * This preserves any modifications made to the intercepted request + * in the "request" listener. This also allows the user to read the + * request body in the "response" listener (otherwise "unusable"). + */ + const requestCloneForResponseEvent = request.clone() + + // Perform the intercepted request as-is. + const { error: responseError, data: originalResponse } = await until( + () => pureFetch(request) + ) + + if (responseError) { + return responsePromise.reject(responseError) + } + + this.logger.info('original fetch performed', originalResponse) + + if (this.emitter.listenerCount('response') > 0) { + this.logger.info('emitting the "response" event...') + + const responseClone = FetchResponse.clone(originalResponse) + await emitAsync(this.emitter, 'response', { + response: responseClone, + isMockedResponse: false, + request: requestCloneForResponseEvent, + requestId, + }) + } + + // Resolve the response promise with the original response + // since the `fetch()` return this internal promise. + responsePromise.resolve(originalResponse) + }, + respondWith: async (rawResponse) => { + // Handle mocked `Response.error()` (i.e. request errors). + if (isResponseError(rawResponse)) { + this.logger.info('request has errored!', { response: rawResponse }) + responsePromise.reject(createNetworkError(rawResponse)) + return + } + + this.logger.info('received mocked response!', { + rawResponse, + }) + + // Decompress the mocked response body, if applicable. + const decompressedStream = decompressResponse(rawResponse) + const response = new FetchResponse( + decompressedStream || rawResponse.body, + { + url: request.url, + status: rawResponse.status, + statusText: rawResponse.statusText, + headers: rawResponse.headers, + } + ) + + /** + * Undici's handling of following redirect responses. + * Treat the "manual" redirect mode as a regular mocked response. + * This way, the client can manually follow the redirect it receives. + * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1173 + */ + if (FetchResponse.isRedirectResponse(response.status)) { + // Reject the request promise if its `redirect` is set to `error` + // and it receives a mocked redirect response. + if (request.redirect === 'error') { + responsePromise.reject(createNetworkError('unexpected redirect')) + return + } + + if (request.redirect === 'follow') { + followFetchRedirect(request, response).then( + (response) => { + responsePromise.resolve(response) + }, + (reason) => { + responsePromise.reject(reason) + } + ) + return + } + } + + if (this.emitter.listenerCount('response') > 0) { + this.logger.info('emitting the "response" event...') + + // Await the response listeners to finish before resolving + // the response promise. This ensures all your logic finishes + // before the interceptor resolves the pending response. + await emitAsync(this.emitter, 'response', { + // Clone the mocked response for the "response" event listener. + // This way, the listener can read the response and not lock its body + // for the actual fetch consumer. + response: FetchResponse.clone(response), + isMockedResponse: true, + request, + requestId, + }) + } + + responsePromise.resolve(response) + }, + errorWith: (reason) => { + this.logger.info('request has been aborted!', { reason }) + responsePromise.reject(reason) + }, + }) + + this.logger.info('[%s] %s', request.method, request.url) + this.logger.info('awaiting for the mocked response...') + + this.logger.info( + 'emitting the "request" event for %s listener(s)...', + this.emitter.listenerCount('request') + ) + + await handleRequest({ + request, + requestId, + emitter: this.emitter, + controller, + }) + + return responsePromise + } + + logger.info('patching global fetch...') + + this.subscriptions.push( + patchesRegistry.applyPatch(globalThis, 'fetch', () => fetchProxy) + ) + + logger.info('global fetch patched!', globalThis.fetch.name) + } +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/fetch/utils/brotli-decompress.browser.ts b/node_modules/@mswjs/interceptors/src/interceptors/fetch/utils/brotli-decompress.browser.ts new file mode 100644 index 0000000000000000000000000000000000000000..d88ca784f93391995cff90456b7ed18fd78fd891 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/fetch/utils/brotli-decompress.browser.ts @@ -0,0 +1,14 @@ +export class BrotliDecompressionStream extends TransformStream { + constructor() { + console.warn( + '[Interceptors]: Brotli decompression of response streams is not supported in the browser' + ) + + super({ + transform(chunk, controller) { + // Keep the stream as passthrough, it does nothing. + controller.enqueue(chunk) + }, + }) + } +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/fetch/utils/brotli-decompress.ts b/node_modules/@mswjs/interceptors/src/interceptors/fetch/utils/brotli-decompress.ts new file mode 100644 index 0000000000000000000000000000000000000000..dbfa622e59ce6a76e882595dcc5bef159028d0c9 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/fetch/utils/brotli-decompress.ts @@ -0,0 +1,31 @@ +import zlib from 'node:zlib' + +export class BrotliDecompressionStream extends TransformStream { + constructor() { + const decompress = zlib.createBrotliDecompress({ + flush: zlib.constants.BROTLI_OPERATION_FLUSH, + finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH, + }) + + super({ + async transform(chunk, controller) { + const buffer = Buffer.from(chunk) + + const decompressed = await new Promise((resolve, reject) => { + decompress.write(buffer, (error) => { + if (error) reject(error) + }) + + decompress.flush() + decompress.once('data', (data) => resolve(data)) + decompress.once('error', (error) => reject(error)) + decompress.once('end', () => controller.terminate()) + }).catch((error) => { + controller.error(error) + }) + + controller.enqueue(decompressed) + }, + }) + } +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/fetch/utils/createNetworkError.ts b/node_modules/@mswjs/interceptors/src/interceptors/fetch/utils/createNetworkError.ts new file mode 100644 index 0000000000000000000000000000000000000000..bf58f070803f4624ad27b7e0b392629cde49908a --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/fetch/utils/createNetworkError.ts @@ -0,0 +1,5 @@ +export function createNetworkError(cause?: unknown) { + return Object.assign(new TypeError('Failed to fetch'), { + cause, + }) +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/fetch/utils/decompression.ts b/node_modules/@mswjs/interceptors/src/interceptors/fetch/utils/decompression.ts new file mode 100644 index 0000000000000000000000000000000000000000..583d4a37edf9d372af8ab4fa07f33b46e506051c --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/fetch/utils/decompression.ts @@ -0,0 +1,85 @@ +// Import from an internal alias that resolves to different modules +// depending on the environment. This way, we can keep the fetch interceptor +// intact while using different strategies for Brotli decompression. +import { BrotliDecompressionStream } from 'internal:brotli-decompress' + +class PipelineStream extends TransformStream { + constructor( + transformStreams: Array, + ...strategies: Array + ) { + super({}, ...strategies) + + const readable = [super.readable as any, ...transformStreams].reduce( + (readable, transform) => readable.pipeThrough(transform) + ) + + Object.defineProperty(this, 'readable', { + get() { + return readable + }, + }) + } +} + +export function parseContentEncoding(contentEncoding: string): Array { + return contentEncoding + .toLowerCase() + .split(',') + .map((coding) => coding.trim()) +} + +function createDecompressionStream( + contentEncoding: string +): TransformStream | null { + if (contentEncoding === '') { + return null + } + + const codings = parseContentEncoding(contentEncoding) + + if (codings.length === 0) { + return null + } + + const transformers = codings.reduceRight>( + (transformers, coding) => { + if (coding === 'gzip' || coding === 'x-gzip') { + return transformers.concat(new DecompressionStream('gzip')) + } else if (coding === 'deflate') { + return transformers.concat(new DecompressionStream('deflate')) + } else if (coding === 'br') { + return transformers.concat(new BrotliDecompressionStream()) + } else { + transformers.length = 0 + } + + return transformers + }, + [] + ) + + return new PipelineStream(transformers) +} + +export function decompressResponse( + response: Response +): ReadableStream | null { + if (response.body === null) { + return null + } + + const decompressionStream = createDecompressionStream( + response.headers.get('content-encoding') || '' + ) + + if (!decompressionStream) { + return null + } + + // Use `pipeTo` and return the decompression stream's readable + // instead of `pipeThrough` because that will lock the original + // response stream, making it unusable as the input to Response. + response.body.pipeTo(decompressionStream.writable) + return decompressionStream.readable +} diff --git a/node_modules/@mswjs/interceptors/src/interceptors/fetch/utils/followRedirect.ts b/node_modules/@mswjs/interceptors/src/interceptors/fetch/utils/followRedirect.ts new file mode 100644 index 0000000000000000000000000000000000000000..6e2decb9f518f254c005a29dc4906d29dca5db53 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/interceptors/fetch/utils/followRedirect.ts @@ -0,0 +1,114 @@ +import { createNetworkError } from './createNetworkError' + +const REQUEST_BODY_HEADERS = [ + 'content-encoding', + 'content-language', + 'content-location', + 'content-type', + 'content-length', +] + +const kRedirectCount = Symbol('kRedirectCount') + +/** + * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1210 + */ +export async function followFetchRedirect( + request: Request, + response: Response +): Promise { + if (response.status !== 303 && request.body != null) { + return Promise.reject(createNetworkError()) + } + + const requestUrl = new URL(request.url) + + let locationUrl: URL + try { + // If the location is a relative URL, use the request URL as the base URL. + locationUrl = new URL(response.headers.get('location')!, request.url) + } catch (error) { + return Promise.reject(createNetworkError(error)) + } + + if ( + !(locationUrl.protocol === 'http:' || locationUrl.protocol === 'https:') + ) { + return Promise.reject( + createNetworkError('URL scheme must be a HTTP(S) scheme') + ) + } + + if (Reflect.get(request, kRedirectCount) > 20) { + return Promise.reject(createNetworkError('redirect count exceeded')) + } + + Object.defineProperty(request, kRedirectCount, { + value: (Reflect.get(request, kRedirectCount) || 0) + 1, + }) + + if ( + request.mode === 'cors' && + (locationUrl.username || locationUrl.password) && + !sameOrigin(requestUrl, locationUrl) + ) { + return Promise.reject( + createNetworkError('cross origin not allowed for request mode "cors"') + ) + } + + const requestInit: RequestInit = {} + + if ( + ([301, 302].includes(response.status) && request.method === 'POST') || + (response.status === 303 && !['HEAD', 'GET'].includes(request.method)) + ) { + requestInit.method = 'GET' + requestInit.body = null + + REQUEST_BODY_HEADERS.forEach((headerName) => { + request.headers.delete(headerName) + }) + } + + if (!sameOrigin(requestUrl, locationUrl)) { + request.headers.delete('authorization') + request.headers.delete('proxy-authorization') + request.headers.delete('cookie') + request.headers.delete('host') + } + + /** + * @note Undici "safely" extracts the request body. + * I suspect we cannot dispatch this request again + * since its body has been read and the stream is locked. + */ + + requestInit.headers = request.headers + const finalResponse = await fetch(new Request(locationUrl, requestInit)) + Object.defineProperty(finalResponse, 'redirected', { + value: true, + configurable: true, + }) + + return finalResponse +} + +/** + * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/util.js#L761 + */ +function sameOrigin(left: URL, right: URL): boolean { + if (left.origin === right.origin && left.origin === 'null') { + return true + } + + if ( + left.protocol === right.protocol && + left.hostname === right.hostname && + left.port === right.port + ) { + return true + } + + return false +} diff --git a/node_modules/@mswjs/interceptors/src/presets/browser.ts b/node_modules/@mswjs/interceptors/src/presets/browser.ts new file mode 100644 index 0000000000000000000000000000000000000000..c609adc5e7dca8993d68109684d12455f468a456 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/presets/browser.ts @@ -0,0 +1,11 @@ +import { FetchInterceptor } from '../interceptors/fetch' +import { XMLHttpRequestInterceptor } from '../interceptors/XMLHttpRequest' + +/** + * The default preset provisions the interception of requests + * regardless of their type (fetch/XMLHttpRequest). + */ +export default [ + new FetchInterceptor(), + new XMLHttpRequestInterceptor(), +] as const diff --git a/node_modules/@mswjs/interceptors/src/presets/node.ts b/node_modules/@mswjs/interceptors/src/presets/node.ts new file mode 100644 index 0000000000000000000000000000000000000000..63fbe0f459e67bdc693121f8cc55903bd18100df --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/presets/node.ts @@ -0,0 +1,13 @@ +import { ClientRequestInterceptor } from '../interceptors/ClientRequest' +import { XMLHttpRequestInterceptor } from '../interceptors/XMLHttpRequest' +import { FetchInterceptor } from '../interceptors/fetch' + +/** + * The default preset provisions the interception of requests + * regardless of their type (http/https/XMLHttpRequest). + */ +export default [ + new ClientRequestInterceptor(), + new XMLHttpRequestInterceptor(), + new FetchInterceptor(), +] as const diff --git a/node_modules/@mswjs/interceptors/src/utils/bufferUtils.test.ts b/node_modules/@mswjs/interceptors/src/utils/bufferUtils.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..7c554556164da88a34dfced42ee641e1a8ed590c --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/bufferUtils.test.ts @@ -0,0 +1,21 @@ +import { it, expect } from 'vitest' +import { decodeBuffer, encodeBuffer } from './bufferUtils' + +it('encodes utf-8 string', () => { + const encoded = encodeBuffer('😁') + expect(new Uint8Array(encoded)).toEqual(new Uint8Array([240, 159, 152, 129])) +}) + +it('decodes utf-8 string', () => { + const array = new Uint8Array([240, 159, 152, 129]) + const decoded = decodeBuffer(array.buffer) + expect(decoded).toEqual('😁') +}) + +it('decodes string with custom encoding', () => { + const array = new Uint8Array([ + 207, 240, 232, 226, 229, 242, 44, 32, 236, 232, 240, 33, + ]) + const decoded = decodeBuffer(array.buffer, 'windows-1251') + expect(decoded).toEqual('Привет, мир!') +}) diff --git a/node_modules/@mswjs/interceptors/src/utils/bufferUtils.ts b/node_modules/@mswjs/interceptors/src/utils/bufferUtils.ts new file mode 100644 index 0000000000000000000000000000000000000000..b4b1c3784d2859669e6e209234d974bb0a2d3784 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/bufferUtils.ts @@ -0,0 +1,22 @@ +const encoder = new TextEncoder() + +export function encodeBuffer(text: string): Uint8Array { + return encoder.encode(text) +} + +export function decodeBuffer(buffer: ArrayBuffer, encoding?: string): string { + const decoder = new TextDecoder(encoding) + return decoder.decode(buffer) +} + +/** + * Create an `ArrayBuffer` from the given `Uint8Array`. + * Takes the byte offset into account to produce the right buffer + * in the case when the buffer is bigger than the data view. + */ +export function toArrayBuffer(array: Uint8Array): ArrayBuffer { + return array.buffer.slice( + array.byteOffset, + array.byteOffset + array.byteLength + ) +} diff --git a/node_modules/@mswjs/interceptors/src/utils/canParseUrl.ts b/node_modules/@mswjs/interceptors/src/utils/canParseUrl.ts new file mode 100644 index 0000000000000000000000000000000000000000..7f814cd5269c9779271770971bba049e7304dd04 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/canParseUrl.ts @@ -0,0 +1,13 @@ +/** + * Returns a boolean indicating whether the given URL string + * can be parsed into a `URL` instance. + * A substitute for `URL.canParse()` for Node.js 18. + */ +export function canParseUrl(url: string): boolean { + try { + new URL(url) + return true + } catch (_error) { + return false + } +} diff --git a/node_modules/@mswjs/interceptors/src/utils/cloneObject.test.ts b/node_modules/@mswjs/interceptors/src/utils/cloneObject.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..85a1dbbb3f32f70005390ab883a93f5553136a5c --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/cloneObject.test.ts @@ -0,0 +1,94 @@ +import { it, expect } from 'vitest' +import { cloneObject } from './cloneObject' + +it('clones a shallow object', () => { + const original = { a: 1, b: 2, c: [1, 2, 3] } + const clone = cloneObject(original) + + expect(clone).toEqual(original) + + clone.a = 5 + clone.b = 6 + clone.c = [5, 6, 7] + + expect(clone).toHaveProperty('a', 5) + expect(clone).toHaveProperty('b', 6) + expect(clone).toHaveProperty('c', [5, 6, 7]) + expect(original).toHaveProperty('a', 1) + expect(original).toHaveProperty('b', 2) + expect(original).toHaveProperty('c', [1, 2, 3]) +}) + +it('clones a nested object', () => { + const original = { a: { b: 1 }, c: { d: { e: 2 } } } + const clone = cloneObject(original) + + expect(clone).toEqual(original) + + clone.a.b = 10 + clone.c.d.e = 20 + + expect(clone).toHaveProperty(['a', 'b'], 10) + expect(clone).toHaveProperty(['c', 'd', 'e'], 20) + expect(original).toHaveProperty(['a', 'b'], 1) + expect(original).toHaveProperty(['c', 'd', 'e'], 2) +}) + +it('clones a class instance', () => { + class Car { + public manufacturer: string + constructor() { + this.manufacturer = 'Audi' + } + getManufacturer() { + return this.manufacturer + } + } + + const car = new Car() + const clone = cloneObject(car) + + expect(clone).toHaveProperty('manufacturer', 'Audi') + expect(clone).toHaveProperty('getManufacturer') + expect(clone.getManufacturer).toBeInstanceOf(Function) + expect(clone.getManufacturer()).toEqual('Audi') +}) + +it('ignores nested class instances', () => { + class Car { + name: string + constructor(name: string) { + this.name = name + } + getName() { + return this.name + } + } + const original = { + a: 1, + car: new Car('Audi'), + } + const clone = cloneObject(original) + + expect(clone).toEqual(original) + expect(clone.car).toBeInstanceOf(Car) + expect(clone.car.getName()).toEqual('Audi') + + clone.car = new Car('BMW') + + expect(clone.car).toBeInstanceOf(Car) + expect(clone.car.getName()).toEqual('BMW') + expect(original.car).toBeInstanceOf(Car) + expect(original.car.getName()).toEqual('Audi') +}) + +it('clones an object with null prototype', () => { + const original = { + key: Object.create(null), + } + const clone = cloneObject(original) + + expect(clone).toEqual({ + key: {}, + }) +}) diff --git a/node_modules/@mswjs/interceptors/src/utils/cloneObject.ts b/node_modules/@mswjs/interceptors/src/utils/cloneObject.ts new file mode 100644 index 0000000000000000000000000000000000000000..521f2ea0032dfae61a1254ce734254303dc1ba89 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/cloneObject.ts @@ -0,0 +1,36 @@ +import { Logger } from '@open-draft/logger' + +const logger = new Logger('cloneObject') + +function isPlainObject(obj?: Record): boolean { + logger.info('is plain object?', obj) + + if (obj == null || !obj.constructor?.name) { + logger.info('given object is undefined, not a plain object...') + return false + } + + logger.info('checking the object constructor:', obj.constructor.name) + return obj.constructor.name === 'Object' +} + +export function cloneObject>( + obj: ObjectType +): ObjectType { + logger.info('cloning object:', obj) + + const enumerableProperties = Object.entries(obj).reduce>( + (acc, [key, value]) => { + logger.info('analyzing key-value pair:', key, value) + + // Recursively clone only plain objects, omitting class instances. + acc[key] = isPlainObject(value) ? cloneObject(value) : value + return acc + }, + {} + ) + + return isPlainObject(obj) + ? enumerableProperties + : Object.assign(Object.getPrototypeOf(obj), enumerableProperties) +} diff --git a/node_modules/@mswjs/interceptors/src/utils/createProxy.test.ts b/node_modules/@mswjs/interceptors/src/utils/createProxy.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..acbd165f5b0c9c008870204f4a4b88a8b1aa695a --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/createProxy.test.ts @@ -0,0 +1,164 @@ +import { vi, it, expect } from 'vitest' +import { createProxy } from './createProxy' + +it('does not interfere with default constructors', () => { + const ProxyClass = createProxy( + class { + constructor(public name: string) {} + }, + {} + ) + + const instance = new ProxyClass('John') + expect(instance.name).toBe('John') +}) + +it('does not interfere with default getters', () => { + const proxy = createProxy({ foo: 'initial' }, {}) + expect(proxy.foo).toBe('initial') +}) + +it('does not interfere with default setters', () => { + const proxy = createProxy({ foo: 'initial' }, {}) + proxy.foo = 'next' + + expect(proxy.foo).toBe('next') +}) + +it('does not interfere with default methods', () => { + const proxy = createProxy({ getValue: () => 'initial' }, {}) + expect(proxy.getValue()).toBe('initial') +}) + +it('does not interfere with existing descriptors', () => { + const target = {} as { foo: string; bar: number } + let internalBar = 0 + + Object.defineProperties(target, { + foo: { + get: () => 'initial', + }, + bar: { + set: (value) => { + internalBar = value + 10 + }, + }, + }) + + const proxy = createProxy(target, { + getProperty(data, next) { + return next() + }, + }) + expect(proxy.foo).toBe('initial') + + proxy.bar = 5 + expect(proxy.bar).toBeUndefined() + expect(internalBar).toBe(15) +}) + +it('infer prototype descriptors', () => { + class Child { + ok: boolean + + set status(nextStatus: number) { + this.ok = nextStatus >= 200 && nextStatus < 300 + } + } + + Object.defineProperties(Child.prototype, { + status: { enumerable: true }, + }) + + const scope = {} as { child: typeof Child } + + Object.defineProperty(scope, 'child', { + enumerable: true, + value: Child, + }) + + const ProxyClass = createProxy(scope.child, {}) + const instance = new ProxyClass() + + instance.status = 201 + expect(instance.ok).toBe(true) +}) + +it('spies on the constructor', () => { + const OriginalClass = class { + constructor(public name: string, public age: number) {} + } + + const constructorCall = vi.fn< + ( + args: ConstructorParameters, + next: () => typeof OriginalClass + ) => typeof OriginalClass + >((args, next) => next()) + + const ProxyClass = createProxy(OriginalClass, { + constructorCall, + }) + + new ProxyClass('John', 32) + + expect(constructorCall).toHaveBeenCalledTimes(1) + expect(constructorCall).toHaveBeenCalledWith( + ['John', 32], + expect.any(Function) + ) +}) + +it('spies on property getters', () => { + const getProperty = vi.fn((args, next) => next()) + const proxy = createProxy({ foo: 'initial' }, { getProperty }) + + proxy.foo + + expect(getProperty).toHaveBeenCalledTimes(1) + expect(getProperty).toHaveBeenCalledWith(['foo', proxy], expect.any(Function)) +}) + +it('spies on property setters', () => { + const setProperty = vi.fn((args, next) => next()) + const proxy = createProxy({ foo: 'initial' }, { setProperty }) + + proxy.foo = 'next' + + expect(setProperty).toHaveBeenCalledTimes(1) + expect(setProperty).toHaveBeenCalledWith( + ['foo', 'next'], + expect.any(Function) + ) +}) + +it('spies on method calls', () => { + const methodCall = vi.fn((args, next) => next()) + const proxy = createProxy( + { + greet: (name: string) => `hello ${name}`, + }, + { methodCall } + ) + + proxy.greet('Clair') + + expect(methodCall).toHaveBeenCalledTimes(1) + expect(methodCall).toHaveBeenCalledWith( + ['greet', ['Clair']], + expect.any(Function) + ) +}) + +it('proxies properties on the prototype level', () => { + const method = vi.fn() + const prototype = { method } + + const proxy = createProxy(Object.create(prototype), {}) + const proxyMethod = vi.fn() + proxy.method = proxyMethod + + prototype.method() + expect(method).toHaveBeenCalledTimes(0) + expect(proxyMethod).toHaveBeenCalledTimes(1) +}) diff --git a/node_modules/@mswjs/interceptors/src/utils/createProxy.ts b/node_modules/@mswjs/interceptors/src/utils/createProxy.ts new file mode 100644 index 0000000000000000000000000000000000000000..054e752437f1059fa43804fb354beaad68393977 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/createProxy.ts @@ -0,0 +1,104 @@ +import { findPropertySource } from './findPropertySource' + +export interface ProxyOptions> { + constructorCall?(args: Array, next: NextFunction): Target + + methodCall?( + this: Target, + data: [methodName: F, args: Array], + next: NextFunction + ): void + + setProperty?( + data: [propertyName: string | symbol, nextValue: unknown], + next: NextFunction + ): boolean + + getProperty?( + data: [propertyName: string | symbol, receiver: Target], + next: NextFunction + ): void +} + +export type NextFunction = () => ReturnType + +export function createProxy( + target: Target, + options: ProxyOptions +): Target { + const proxy = new Proxy(target, optionsToProxyHandler(options)) + + return proxy +} + +function optionsToProxyHandler>( + options: ProxyOptions +): ProxyHandler { + const { constructorCall, methodCall, getProperty, setProperty } = options + const handler: ProxyHandler = {} + + if (typeof constructorCall !== 'undefined') { + handler.construct = function (target, args, newTarget) { + const next = Reflect.construct.bind(null, target as any, args, newTarget) + return constructorCall.call(newTarget, args, next) + } + } + + handler.set = function (target, propertyName, nextValue) { + const next = () => { + const propertySource = findPropertySource(target, propertyName) || target + const ownDescriptors = Reflect.getOwnPropertyDescriptor( + propertySource, + propertyName + ) + + // Respect any custom setters present for this property. + if (typeof ownDescriptors?.set !== 'undefined') { + ownDescriptors.set.apply(target, [nextValue]) + return true + } + + // Otherwise, set the property on the source. + return Reflect.defineProperty(propertySource, propertyName, { + writable: true, + enumerable: true, + configurable: true, + value: nextValue, + }) + } + + if (typeof setProperty !== 'undefined') { + return setProperty.call(target, [propertyName, nextValue], next) + } + + return next() + } + + handler.get = function (target, propertyName, receiver) { + /** + * @note Using `Reflect.get()` here causes "TypeError: Illegal invocation". + */ + const next = () => target[propertyName as any] + + const value = + typeof getProperty !== 'undefined' + ? getProperty.call(target, [propertyName, receiver], next) + : next() + + if (typeof value === 'function') { + return (...args: Array) => { + const next = value.bind(target, ...args) + + if (typeof methodCall !== 'undefined') { + return methodCall.call(target, [propertyName as any, args], next) + } + + return next() + } + } + + return value + } + + return handler +} diff --git a/node_modules/@mswjs/interceptors/src/utils/emitAsync.ts b/node_modules/@mswjs/interceptors/src/utils/emitAsync.ts new file mode 100644 index 0000000000000000000000000000000000000000..2edf1ceeba744a96ec5ac85cde2bb6bb1fabe6b6 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/emitAsync.ts @@ -0,0 +1,25 @@ +import { Emitter, EventMap } from 'strict-event-emitter' + +/** + * Emits an event on the given emitter but executes + * the listeners sequentially. This accounts for asynchronous + * listeners (e.g. those having "sleep" and handling the request). + */ +export async function emitAsync< + Events extends EventMap, + EventName extends keyof Events +>( + emitter: Emitter, + eventName: EventName, + ...data: Events[EventName] +): Promise { + const listeners = emitter.listeners(eventName) + + if (listeners.length === 0) { + return + } + + for (const listener of listeners) { + await listener.apply(emitter, data) + } +} diff --git a/node_modules/@mswjs/interceptors/src/utils/fetchUtils.test.ts b/node_modules/@mswjs/interceptors/src/utils/fetchUtils.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..aefef7bcfca9a20c74377d9afe4d0f93d146eaaf --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/fetchUtils.test.ts @@ -0,0 +1,131 @@ +import { describe, it, expect } from 'vitest' +import { FetchRequest, FetchResponse } from './fetchUtils' + +describe('FetchRequest', () => { + const URL = 'https://example.com/' + + it('passes instanceof check with the regular Request', () => { + expect(new FetchRequest(URL)).toBeInstanceOf(Request) + }) + + it('creates a request with a non-configurable method', () => { + expect + .soft(new FetchRequest(URL, { method: 'CONNECT' })) + .toHaveProperty('method', 'CONNECT') + + expect + .soft(new FetchRequest(URL, { method: 'TRACE' })) + .toHaveProperty('method', 'TRACE') + expect + .soft(new FetchRequest(new FetchRequest(URL, { method: 'TRACE' }))) + .toHaveProperty('method', 'TRACE') + + expect + .soft(new FetchRequest(URL, { method: 'TRACK' })) + .toHaveProperty('method', 'TRACK') + expect + .soft(new FetchRequest(new FetchRequest(URL, { method: 'TRACK' }))) + .toHaveProperty('method', 'TRACK') + }) + + it('creates a request with a non-configurable mode', () => { + expect + .soft(new FetchRequest(URL, { mode: 'navigate' })) + .toHaveProperty('mode', 'navigate') + expect + .soft(new FetchRequest(new FetchRequest(URL, { mode: 'navigate' }))) + .toHaveProperty('mode', 'navigate') + + expect + .soft(new FetchRequest(URL, { mode: 'websocket' })) + .toHaveProperty('mode', 'websocket') + expect + .soft(new FetchRequest(new FetchRequest(URL, { mode: 'websocket' }))) + .toHaveProperty('mode', 'websocket') + + expect + .soft(new FetchRequest(URL, { mode: 'webtransport' })) + .toHaveProperty('mode', 'webtransport') + expect + .soft(new FetchRequest(new FetchRequest(URL, { mode: 'webtransport' }))) + .toHaveProperty('mode', 'webtransport') + }) + + it('ignores body for the requests without a body', () => { + expect + .soft(new FetchRequest(URL, { body: null })) + .toHaveProperty('body', null) + expect + .soft(new FetchRequest(URL, { body: undefined })) + .toHaveProperty('body', null) + expect + .soft(new FetchRequest(URL, { body: 'hello' })) + .toHaveProperty('body', null) + + expect + .soft(new FetchRequest(URL, { method: 'GET', body: 'hello' })) + .toHaveProperty('body', null) + expect + .soft(new FetchRequest(URL, { method: 'HEAD', body: 'hello' })) + .toHaveProperty('body', null) + expect + .soft(new FetchRequest(URL, { method: 'CONNECT', body: 'hello' })) + .toHaveProperty('body', null) + expect + .soft(new FetchRequest(URL, { method: 'TRACE', body: 'hello' })) + .toHaveProperty('body', null) + expect + .soft(new FetchRequest(URL, { method: 'TRACK', body: 'hello' })) + .toHaveProperty('body', null) + + expect + .soft(new FetchRequest(URL, { method: 'POST', body: 'hello' })) + .toHaveProperty('body', expect.any(ReadableStream)) + }) +}) + +describe('FetchResponse', () => { + it('clones a regular response', () => { + const response = new Response('hello world') + expect(FetchResponse.clone(response)).toMatchObject(response) + }) + + it('returns a mocked 500 response if cloning throws', async () => { + const response = new Response('hello world') + const error = new Error('Cannot clone!') + response.clone = function () { + throw error + } + + const clone = FetchResponse.clone(response) + expect.soft(clone.status).toBe(500) + expect.soft(clone.statusText).toBe('Unclonable Response') + await expect.soft(clone.json()).resolves.toEqual({ + name: error.name, + message: error.message, + stack: error.stack, + }) + }) + + it('sets the response URL', () => { + const response = new Response('hello world') + FetchResponse.setUrl('https://example.com/', response) + + expect(response.url).toBe('https://example.com/') + }) + + it('preserves a custom response URL after cloning Response', () => { + const response = new FetchResponse('hello world') + FetchResponse.setUrl('https://example.com/', response) + + expect(response.clone().url).toBe('https://example.com/') + }) + + it('preserves a custom response URL after cloning FetchResponse', () => { + const response = new FetchResponse('hello world', { + url: 'https://example.com/', + }) + + expect(response.clone().url).toBe('https://example.com/') + }) +}) diff --git a/node_modules/@mswjs/interceptors/src/utils/fetchUtils.ts b/node_modules/@mswjs/interceptors/src/utils/fetchUtils.ts new file mode 100644 index 0000000000000000000000000000000000000000..27e127f51dac2a4aa534a3b54c3a7697193389db --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/fetchUtils.ts @@ -0,0 +1,328 @@ +import { canParseUrl } from './canParseUrl' +import { getValueBySymbol } from './getValueBySymbol' + +interface UndiciRequestState extends RequestInit {} + +interface FetchRequestInit extends Omit { + mode?: RequestMode | 'websocket' | 'webtransport' + duplex?: 'half' | 'full' +} + +export class FetchRequest extends Request { + static #resolveProperty( + input: RequestInfo | URL, + init: FetchRequestInit = {}, + key: T + ): FetchRequestInit[T] { + return init[key] ?? (input instanceof Request ? input[key] : undefined) + } + + /** + * Check if the given request method is configurable. + * @see https://fetch.spec.whatwg.org/#methods + */ + static isConfigurableMethod(method: string): boolean { + return method !== 'CONNECT' && method !== 'TRACE' && method !== 'TRACK' + } + + static isMethodWithBody(method: string): boolean { + return ( + method !== 'HEAD' && + method !== 'GET' && + FetchRequest.isConfigurableMethod(method) + ) + } + + /** + * Check if the given request `mode` is configurable. + * @see https://fetch.spec.whatwg.org/#concept-request-mode + */ + static isConfigurableMode(mode: string): boolean { + return ( + mode !== 'navigate' && mode !== 'websocket' && mode !== 'webtransport' + ) + } + + constructor(input: URL | RequestInfo, init?: FetchRequestInit) { + const method = FetchRequest.#resolveProperty(input, init, 'method') || 'GET' + const safeMethod = FetchRequest.isConfigurableMethod(method) + ? method + : 'GET' + + const hasExplicitBody = init != null && 'body' in init + + /** + * Only include `body` in the super init when it needs to be overridden. + * When `input` is a Request and no explicit body is in `init`, let the + * Request constructor handle body transfer naturally so it properly + * marks the original request's body as consumed (bodyUsed = true). + */ + const bodyInit: { body?: BodyInit | null } = !FetchRequest.isMethodWithBody( + method + ) + ? { body: undefined } + : hasExplicitBody + ? { body: init.body } + : {} + + const mode = + (FetchRequest.#resolveProperty(input, init, 'mode') as RequestMode) ?? + undefined + const safeMode = FetchRequest.isConfigurableMode(mode) ? mode : undefined + + super(input, { + ...(init || {}), + method: safeMethod, + mode: safeMode, + // @ts-expect-error Untyped Node.js property. + duplex: + init?.duplex ?? + (FetchRequest.isMethodWithBody(method) ? 'half' : undefined), + ...bodyInit, + }) + + if (method !== safeMethod) { + this.#setInternalProperty('method', method) + } + + if (method === 'CONNECT') { + const url = new URL(input instanceof Request ? input.url : input) + + let authority: string + + /** + * @note Node.js has a bug parsing raw CONNECT requests URLs like + * "http://127.0.0.1:1337/localhost:80". It would treat "localhost:" as a protocol. + */ + if (url.protocol === 'localhost:') { + authority = url.href + } else { + authority = url.pathname.replace(/^\/+/, '') + } + + /** + * @note Define "url" as a getter because Undici uses their own + * logic to resolve the "request.url" property. Simply reassigning + * its value doesn't do anything. This is a destructive action + * but it's safe because "CONNECT" requests are forbidden per fetch. + */ + Object.defineProperty(this, 'url', { + get: () => authority, + enumerable: true, + configurable: true, + }) + } + + if (mode != null && mode !== safeMode) { + this.#setInternalProperty('mode', mode) + } + } + + #setInternalProperty( + key: T, + value: Request[T] + ): void { + const internalState = getValueBySymbol('state', this) + + if (internalState) { + Reflect.set(internalState, key, value) + } else { + Object.defineProperty(this, key, { + value, + enumerable: true, + configurable: true, + writable: false, + }) + } + } +} + +export interface FetchResponseInit extends ResponseInit { + url?: string +} + +interface UndiciResponseState { + aborted: boolean + rangeRequested: boolean + timingAllowPassed: boolean + requestIncludesCredentials: boolean + type: ResponseType + status: number + statusText: string + timingInfo: unknown + cacheState: unknown + headersList: Record> + urlList: Array + body?: { + stream: ReadableStream + source: unknown + length: number + } +} + +const kStatus = Symbol('kStatus') +const kUrl = Symbol('kUrl') + +export class FetchResponse extends Response { + /** + * Response status codes for responses that cannot have body. + * @see https://fetch.spec.whatwg.org/#statuses + */ + static readonly STATUS_CODES_WITHOUT_BODY = [101, 103, 204, 205, 304] + + static readonly STATUS_CODES_WITH_REDIRECT = [301, 302, 303, 307, 308] + + static isConfigurableStatusCode(status: number): boolean { + return status >= 200 && status <= 599 + } + + static isRedirectResponse(status: number): boolean { + return FetchResponse.STATUS_CODES_WITH_REDIRECT.includes(status) + } + + /** + * Returns a boolean indicating whether the given response status + * code represents a response that can have a body. + */ + static isResponseWithBody(status: number): boolean { + return !FetchResponse.STATUS_CODES_WITHOUT_BODY.includes(status) + } + + static setStatus(status: number, response: Response): void { + /** + * @note Undici keeps an internal "Symbol(state)" that holds + * the actual value of response status. Update that in Node.js. + */ + const internalState = getValueBySymbol( + 'state', + response + ) + + if (internalState) { + internalState.status = status + } else { + Object.defineProperty(response, 'status', { + value: status, + enumerable: true, + configurable: true, + writable: false, + }) + } + + Object.defineProperty(response, kStatus, { + value: status, + enumerable: false, + }) + } + + static setUrl(url: string | undefined, response: Response): void { + if (!url || url === 'about:' || !canParseUrl(url)) { + return + } + + const state = getValueBySymbol('state', response) + + if (state) { + // In Undici, push the URL to the internal list of URLs. + // This will respect the `response.url` getter logic correctly. + state.urlList.push(new URL(url)) + } else { + // In other libraries, redefine the `url` property directly. + Object.defineProperty(response, 'url', { + value: url, + enumerable: true, + configurable: true, + writable: false, + }) + } + + Object.defineProperty(response, kUrl, { + value: url, + enumerable: false, + }) + } + + /** + * Parses the given raw HTTP headers into a Fetch API `Headers` instance. + */ + static parseRawHeaders(rawHeaders: Array): Headers { + const headers = new Headers() + + for (let line = 0; line < rawHeaders.length; line += 2) { + headers.append(rawHeaders[line], rawHeaders[line + 1]) + } + + return headers + } + + /** + * Safely clones the given `Response`. + * Coerces response clone exceptions into 500 mocked responses. + * Handy in the environments that introduce arbitrary response + * cloning restrictions, like "101 Switching Protocols" cloning + * in "miniflare". + */ + static clone(response: Response): Response { + try { + const clone = response.clone() + return clone + } catch (error) { + return Response.json( + error instanceof Error + ? { + name: error.name, + message: error.message, + stack: error.stack, + } + : {}, + { + status: 500, + statusText: 'Unclonable Response', + } + ) + } + } + + constructor(body?: BodyInit | null, init: FetchResponseInit = {}) { + const status = init.status ?? 200 + const safeStatus = FetchResponse.isConfigurableStatusCode(status) + ? status + : 200 + const finalBody = FetchResponse.isResponseWithBody(status) ? body : null + + super(finalBody, { + status: safeStatus, + statusText: init.statusText, + headers: init.headers, + }) + + /** + * Since Node.js v24, Undici stores the Response state in an inaccessible field "#state". + * Forward the modified status/URL to the cloned response manually. + * @see https://github.com/nodejs/undici/blob/f734c87280e626c75f59aad55b65eb6a89cef392/lib/web/fetch/response.js#L242 + */ + if (status !== safeStatus) { + FetchResponse.setStatus(status, this) + } + + FetchResponse.setUrl(init.url, this) + } + + public clone() { + const clonedResponse = super.clone() + + const customStatus = Reflect.get(this, kStatus) as number | undefined + + if (customStatus) { + FetchResponse.setStatus(customStatus, clonedResponse) + } + + const customUrl = Reflect.get(this, kUrl) as string | undefined + + if (customUrl) { + FetchResponse.setUrl(customUrl, clonedResponse) + } + + return clonedResponse + } +} diff --git a/node_modules/@mswjs/interceptors/src/utils/findPropertySource.test.ts b/node_modules/@mswjs/interceptors/src/utils/findPropertySource.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..cce02ca9eb099feda1cdde43b0f29e82f715323c --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/findPropertySource.test.ts @@ -0,0 +1,27 @@ +import { it, expect } from 'vitest' +import { findPropertySource } from './findPropertySource' + +it('returns the source for objects without prototypes', () => { + const obj = Object.create(null) + obj.test = undefined + const source = findPropertySource(obj, 'test') + expect(source).toBe(obj) +}) + +it('returns the source for objects with prototypes', () => { + const prototype = Object.create(null) + prototype.test = undefined + + const obj = Object.create(prototype) + + const source = findPropertySource(obj, 'test') + expect(source).toBe(prototype) +}) + +it('returns null if the prototype chain does not contain the property', () => { + const prototype = Object.create(null) + const obj = Object.create(prototype) + + const source = findPropertySource(obj, 'test') + expect(source).toBeNull() +}) diff --git a/node_modules/@mswjs/interceptors/src/utils/findPropertySource.ts b/node_modules/@mswjs/interceptors/src/utils/findPropertySource.ts new file mode 100644 index 0000000000000000000000000000000000000000..26ca44af82e00e5feb046e5ee8dab2339d5fc35d --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/findPropertySource.ts @@ -0,0 +1,20 @@ +/** + * Returns the source object of the given property on the target object + * (the target itself, any parent in its prototype, or null). + */ +export function findPropertySource( + target: object, + propertyName: string | symbol +): object | null { + if (!(propertyName in target)) { + return null + } + + const hasProperty = Object.prototype.hasOwnProperty.call(target, propertyName) + if (hasProperty) { + return target + } + + const prototype = Reflect.getPrototypeOf(target) + return prototype ? findPropertySource(prototype, propertyName) : null +} diff --git a/node_modules/@mswjs/interceptors/src/utils/getCleanUrl.test.ts b/node_modules/@mswjs/interceptors/src/utils/getCleanUrl.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..9f70ca81d5e08954b9e7c6cf3499a9862170fb67 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/getCleanUrl.test.ts @@ -0,0 +1,32 @@ +import { describe, it, expect } from 'vitest' +import { getCleanUrl } from './getCleanUrl' + +describe('getCleanUrl', () => { + describe('given a URL without query parameters', () => { + it('should return url href as-is', () => { + const url = new URL('https://github.com') + expect(getCleanUrl(url)).toEqual('https://github.com/') + }) + }) + + describe('given a URL with query parameters', () => { + it('should return url without parameters', () => { + const url = new URL('https://github.com/mswjs/?userId=abc-123') + expect(getCleanUrl(url)).toEqual('https://github.com/mswjs/') + }) + }) + + describe('given a URL with a hash', () => { + it('should return a url without hash', () => { + const url = new URL('https://github.com/mswjs/#hello-world') + expect(getCleanUrl(url)).toEqual('https://github.com/mswjs/') + }) + }) + + describe('given an absolute URL ', () => { + it('should return a clean relative URL', () => { + const url = new URL('/login?query=value', 'https://github.com') + expect(getCleanUrl(url, false)).toEqual('/login') + }) + }) +}) diff --git a/node_modules/@mswjs/interceptors/src/utils/getCleanUrl.ts b/node_modules/@mswjs/interceptors/src/utils/getCleanUrl.ts new file mode 100644 index 0000000000000000000000000000000000000000..14165674a3dc626a1445e7d117edc639b05e839a --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/getCleanUrl.ts @@ -0,0 +1,6 @@ +/** + * Removes query parameters and hashes from a given URL. + */ +export function getCleanUrl(url: URL, isAbsolute: boolean = true): string { + return [isAbsolute && url.origin, url.pathname].filter(Boolean).join('') +} diff --git a/node_modules/@mswjs/interceptors/src/utils/getUrlByRequestOptions.test.ts b/node_modules/@mswjs/interceptors/src/utils/getUrlByRequestOptions.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..cc9423609d32be0399fb0ace18f5891f461c1f67 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/getUrlByRequestOptions.test.ts @@ -0,0 +1,163 @@ +import { it, expect } from 'vitest' +import { Agent as HttpAgent } from 'http' +import { RequestOptions, Agent as HttpsAgent } from 'https' +import { getUrlByRequestOptions } from './getUrlByRequestOptions' + +it('returns a URL based on the basic RequestOptions', () => { + expect( + getUrlByRequestOptions({ + protocol: 'https:', + host: '127.0.0.1', + path: '/resource', + }).href + ).toBe('https://127.0.0.1/resource') +}) + +it('inherits protocol and port from http.Agent, if set', () => { + expect( + getUrlByRequestOptions({ + host: '127.0.0.1', + path: '/', + agent: new HttpAgent(), + }).href + ).toBe('http://127.0.0.1/') +}) + +it('inherits protocol and port from https.Agent, if set', () => { + expect( + getUrlByRequestOptions({ + host: '127.0.0.1', + path: '/', + agent: new HttpsAgent({ + port: 3080, + }), + }).href + ).toBe('https://127.0.0.1:3080/') +}) + +it('resolves protocol to "http" given no explicit protocol and no certificate', () => { + expect( + getUrlByRequestOptions({ + host: '127.0.0.1', + path: '/', + }).href + ).toBe('http://127.0.0.1/') +}) + +it('resolves protocol to "https" given no explicit protocol, but certificate', () => { + expect( + getUrlByRequestOptions({ + host: '127.0.0.1', + path: '/secure', + cert: '', + }).href + ).toBe('https://127.0.0.1/secure') +}) + +it('resolves protocol to "https" given no explicit protocol, but port is 443', () => { + expect( + getUrlByRequestOptions({ + host: '127.0.0.1', + port: 443, + path: '/resource', + }).href + ).toBe('https://127.0.0.1/resource') +}) + +it('resolves protocol to "https" given no explicit protocol, but agent port is 443', () => { + expect( + getUrlByRequestOptions({ + host: '127.0.0.1', + agent: new HttpsAgent({ + port: 443, + }), + path: '/resource', + }).href + ).toBe('https://127.0.0.1/resource') +}) + +it('respects explicitly provided port', () => { + expect( + getUrlByRequestOptions({ + protocol: 'http:', + host: '127.0.0.1', + port: 4002, + path: '/', + }).href + ).toBe('http://127.0.0.1:4002/') +}) + +it('inherits "username" and "password"', () => { + const url = getUrlByRequestOptions({ + protocol: 'https:', + host: '127.0.0.1', + path: '/user', + auth: 'admin:abc-123', + }) + + expect(url).toBeInstanceOf(URL) + expect(url).toHaveProperty('username', 'admin') + expect(url).toHaveProperty('password', 'abc-123') + expect(url).toHaveProperty('href', 'https://admin:abc-123@127.0.0.1/user') +}) + +it('resolves hostname to localhost if none provided', () => { + expect(getUrlByRequestOptions({}).hostname).toBe('localhost') +}) + +it('resolves host to localhost if none provided', () => { + expect(getUrlByRequestOptions({}).host).toBe('localhost') +}) + +it('supports "hostname" and "port"', () => { + const options: RequestOptions = { + protocol: 'https:', + hostname: '127.0.0.1', + port: 1234, + path: '/resource', + } + + expect(getUrlByRequestOptions(options).href).toBe( + 'https://127.0.0.1:1234/resource' + ) +}) + +it('use "hostname" if both "hostname" and "host" are specified', () => { + const options: RequestOptions = { + protocol: 'https:', + host: 'host', + hostname: 'hostname', + path: '/resource', + } + + expect(getUrlByRequestOptions(options).href).toBe( + 'https://hostname/resource' + ) +}) + +it('parses "host" in IPv6', () => { + expect( + getUrlByRequestOptions({ + host: '::1', + path: '/resource', + }).href + ).toBe('http://[::1]/resource') + + expect( + getUrlByRequestOptions({ + host: '[::1]', + path: '/resource', + }).href + ).toBe('http://[::1]/resource') + +}) + +it('parses "host" and "port" in IPv6', () => { + expect( + getUrlByRequestOptions({ + host: '::1', + port: 3001, + path: '/resource', + }).href + ).toBe('http://[::1]:3001/resource') +}) diff --git a/node_modules/@mswjs/interceptors/src/utils/getUrlByRequestOptions.ts b/node_modules/@mswjs/interceptors/src/utils/getUrlByRequestOptions.ts new file mode 100644 index 0000000000000000000000000000000000000000..0b8a5ef76010de2a957bbdc0b54b783b5cd9b836 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/getUrlByRequestOptions.ts @@ -0,0 +1,152 @@ +import { Agent } from 'http' +import { RequestOptions, Agent as HttpsAgent } from 'https' +import { Logger } from '@open-draft/logger' + +const logger = new Logger('utils getUrlByRequestOptions') + +// Request instance constructed by the "request" library +// has a "self" property that has a "uri" field. This is +// reproducible by performing a "XMLHttpRequest" request in JSDOM. +export interface RequestSelf { + uri?: URL +} + +export type ResolvedRequestOptions = RequestOptions & RequestSelf + +export const DEFAULT_PATH = '/' +const DEFAULT_PROTOCOL = 'http:' +const DEFAULT_HOSTNAME = 'localhost' +const SSL_PORT = 443 + +function getAgent( + options: ResolvedRequestOptions +): Agent | HttpsAgent | undefined { + return options.agent instanceof Agent ? options.agent : undefined +} + +function getProtocolByRequestOptions(options: ResolvedRequestOptions): string { + if (options.protocol) { + return options.protocol + } + + const agent = getAgent(options) + const agentProtocol = (agent as RequestOptions)?.protocol + + if (agentProtocol) { + return agentProtocol + } + + const port = getPortByRequestOptions(options) + const isSecureRequest = options.cert || port === SSL_PORT + + return isSecureRequest ? 'https:' : options.uri?.protocol || DEFAULT_PROTOCOL +} + +function getPortByRequestOptions( + options: ResolvedRequestOptions +): number | undefined { + // Use the explicitly provided port. + if (options.port) { + return Number(options.port) + } + + // Otherwise, try to resolve port from the agent. + const agent = getAgent(options) + + if ((agent as HttpsAgent)?.options.port) { + return Number((agent as HttpsAgent).options.port) + } + + if ((agent as RequestOptions)?.defaultPort) { + return Number((agent as RequestOptions).defaultPort) + } + + // Lastly, return undefined indicating that the port + // must inferred from the protocol. Do not infer it here. + return undefined +} + +interface RequestAuth { + username: string + password: string +} + +function getAuthByRequestOptions( + options: ResolvedRequestOptions +): RequestAuth | undefined { + if (options.auth) { + const [username, password] = options.auth.split(':') + return { username, password } + } +} + +/** + * Returns true if host looks like an IPv6 address without surrounding brackets + * It assumes any host containing `:` is definitely not IPv4 and probably IPv6, + * but note that this could include invalid IPv6 addresses as well. + */ +function isRawIPv6Address(host: string): boolean { + return host.includes(':') && !host.startsWith('[') && !host.endsWith(']') +} + +function getHostname(options: ResolvedRequestOptions): string | undefined { + let host = options.hostname || options.host + + if (host) { + if (isRawIPv6Address(host)) { + host = `[${host}]` + } + + // Check the presence of the port, and if it's present, + // remove it from the host, returning a hostname. + return new URL(`http://${host}`).hostname + } + + return DEFAULT_HOSTNAME +} + +/** + * Creates a `URL` instance from a given `RequestOptions` object. + */ +export function getUrlByRequestOptions(options: ResolvedRequestOptions): URL { + logger.info('request options', options) + + if (options.uri) { + logger.info( + 'constructing url from explicitly provided "options.uri": %s', + options.uri + ) + return new URL(options.uri.href) + } + + logger.info('figuring out url from request options...') + + const protocol = getProtocolByRequestOptions(options) + logger.info('protocol', protocol) + + const port = getPortByRequestOptions(options) + logger.info('port', port) + + const hostname = getHostname(options) + logger.info('hostname', hostname) + + const path = options.path || DEFAULT_PATH + logger.info('path', path) + + const credentials = getAuthByRequestOptions(options) + logger.info('credentials', credentials) + + const authString = credentials + ? `${credentials.username}:${credentials.password}@` + : '' + logger.info('auth string:', authString) + + const portString = typeof port !== 'undefined' ? `:${port}` : '' + const url = new URL(`${protocol}//${hostname}${portString}${path}`) + url.username = credentials?.username || '' + url.password = credentials?.password || '' + + logger.info('created url:', url) + + return url +} diff --git a/node_modules/@mswjs/interceptors/src/utils/getValueBySymbol.test.ts b/node_modules/@mswjs/interceptors/src/utils/getValueBySymbol.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..9e2b21c8ceda848d594162356257be11555811d4 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/getValueBySymbol.test.ts @@ -0,0 +1,14 @@ +import { it, expect } from 'vitest' +import { getValueBySymbol } from './getValueBySymbol' + +it('returns undefined given a non-existing symbol', () => { + expect(getValueBySymbol('non-existing', {})).toBeUndefined() +}) + +it('returns value behind the given symbol', () => { + const symbol = Symbol('kInternal') + + expect(getValueBySymbol('kInternal', { [symbol]: null })).toBe(null) + expect(getValueBySymbol('kInternal', { [symbol]: true })).toBe(true) + expect(getValueBySymbol('kInternal', { [symbol]: 'value' })).toBe('value') +}) diff --git a/node_modules/@mswjs/interceptors/src/utils/getValueBySymbol.ts b/node_modules/@mswjs/interceptors/src/utils/getValueBySymbol.ts new file mode 100644 index 0000000000000000000000000000000000000000..2c2e9541f44094b2e07b35154aeae9a2cc1a813c --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/getValueBySymbol.ts @@ -0,0 +1,19 @@ +/** + * Returns the value behind the symbol with the given name. + */ +export function getValueBySymbol( + symbolName: string, + source: object +): T | undefined { + const ownSymbols = Object.getOwnPropertySymbols(source) + + const symbol = ownSymbols.find((symbol) => { + return symbol.description === symbolName + }) + + if (symbol) { + return Reflect.get(source, symbol) + } + + return +} diff --git a/node_modules/@mswjs/interceptors/src/utils/handleRequest.ts b/node_modules/@mswjs/interceptors/src/utils/handleRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..3ac9d2f0645e7af2749bf8c2ea2d1faafe3b23d7 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/handleRequest.ts @@ -0,0 +1,204 @@ +import type { Emitter } from 'strict-event-emitter' +import { DeferredPromise } from '@open-draft/deferred-promise' +import { until } from '@open-draft/until' +import type { HttpRequestEventMap } from '../glossary' +import { emitAsync } from './emitAsync' +import { RequestController } from '../RequestController' +import { + createServerErrorResponse, + isResponseError, + isResponseLike, +} from './responseUtils' +import { InterceptorError } from '../InterceptorError' +import { isNodeLikeError } from './isNodeLikeError' +import { isObject } from './isObject' + +interface HandleRequestOptions { + requestId: string + request: Request + emitter: Emitter + controller: RequestController +} + +export async function handleRequest( + options: HandleRequestOptions +): Promise { + const handleResponse = async ( + response: Response | Error | Record + ) => { + if (response instanceof Error) { + await options.controller.errorWith(response) + return true + } + + // Handle "Response.error()" instances. + if (isResponseError(response)) { + await options.controller.respondWith(response) + return true + } + + /** + * Handle normal responses or response-like objects. + * @note This must come before the arbitrary object check + * since Response instances are, in fact, objects. + */ + if (isResponseLike(response)) { + await options.controller.respondWith(response) + return true + } + + // Handle arbitrary objects provided to `.errorWith(reason)`. + if (isObject(response)) { + await options.controller.errorWith(response) + return true + } + + return false + } + + const handleResponseError = async (error: unknown): Promise => { + // Forward the special interceptor error instances + // to the developer. These must not be handled in any way. + if (error instanceof InterceptorError) { + throw result.error + } + + // Support mocking Node.js-like errors. + if (isNodeLikeError(error)) { + await options.controller.errorWith(error) + return true + } + + // Handle thrown responses. + if (error instanceof Response) { + return await handleResponse(error) + } + + return false + } + + // Add the last "request" listener to check if the request + // has been handled in any way. If it hasn't, resolve the + // response promise with undefined. + // options.emitter.once('request', async ({ requestId: pendingRequestId }) => { + // if ( + // pendingRequestId === options.requestId && + // options.controller.readyState === RequestController.PENDING + // ) { + // await options.controller.passthrough() + // } + // }) + + const requestAbortPromise = new DeferredPromise() + const onAbort = () => { + requestAbortPromise.reject(options.request.signal?.reason) + } + + /** + * @note `signal` is not always defined in React Native. + */ + if (options.request.signal) { + if (options.request.signal.aborted) { + await options.controller.errorWith(options.request.signal.reason) + return + } + + options.request.signal.addEventListener('abort', onAbort, { once: true }) + } + + const result = await until(async () => { + // Emit the "request" event and wait until all the listeners + // for that event are finished (e.g. async listeners awaited). + // By the end of this promise, the developer cannot affect the + // request anymore. + const requestListenersPromise = emitAsync(options.emitter, 'request', { + requestId: options.requestId, + request: options.request, + controller: options.controller, + }) + + await Promise.race([ + // Short-circuit the request handling promise if the request gets aborted. + requestAbortPromise, + requestListenersPromise, + options.controller.handled, + ]) + }) + + options.request.signal?.removeEventListener('abort', onAbort) + + // Handle the request being aborted while waiting for the request listeners. + if (requestAbortPromise.state === 'rejected') { + await options.controller.errorWith(requestAbortPromise.rejectionReason) + return + } + + if (result.error) { + // Handle the error during the request listener execution. + // These can be thrown responses or request errors. + if (await handleResponseError(result.error)) { + return + } + + // If the developer has added "unhandledException" listeners, + // allow them to handle the error. They can translate it to a + // mocked response, network error, or forward it as-is. + if (options.emitter.listenerCount('unhandledException') > 0) { + // Create a new request controller just for the unhandled exception case. + // This is needed because the original controller might have been already + // interacted with (e.g. "respondWith" or "errorWith" called on it). + const unhandledExceptionController = new RequestController( + options.request, + { + /** + * @note Intentionally empty passthrough handle. + * This controller is created within another controller and we only need + * to know if `unhandledException` listeners handled the request. + */ + passthrough() {}, + async respondWith(response) { + await handleResponse(response) + }, + async errorWith(reason) { + /** + * @note Handle the result of the unhandled controller + * in the same way as the original request controller. + * The exception here is that thrown errors within the + * "unhandledException" event do NOT result in another + * emit of the same event. They are forwarded as-is. + */ + await options.controller.errorWith(reason) + }, + } + ) + + await emitAsync(options.emitter, 'unhandledException', { + error: result.error, + request: options.request, + requestId: options.requestId, + controller: unhandledExceptionController, + }) + + // If all the "unhandledException" listeners have finished + // but have not handled the request in any way, passthrough. + if ( + unhandledExceptionController.readyState !== RequestController.PENDING + ) { + return + } + } + + // Otherwise, coerce unhandled exceptions to a 500 Internal Server Error response. + await options.controller.respondWith( + createServerErrorResponse(result.error) + ) + return + } + + // If the request hasn't been handled by this point, passthrough. + if (options.controller.readyState === RequestController.PENDING) { + return await options.controller.passthrough() + } + + return options.controller.handled +} diff --git a/node_modules/@mswjs/interceptors/src/utils/hasConfigurableGlobal.test.ts b/node_modules/@mswjs/interceptors/src/utils/hasConfigurableGlobal.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..4d643d43722a85d96fee488cd91756a81d8d107b --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/hasConfigurableGlobal.test.ts @@ -0,0 +1,94 @@ +import { vi, beforeAll, afterEach, afterAll, it, expect } from 'vitest' +import { hasConfigurableGlobal } from './hasConfigurableGlobal' + +let originalGlobalPrototype = Object.getPrototypeOf(globalThis) + +beforeAll(() => { + vi.spyOn(console, 'error').mockImplementation(() => {}) +}) + +afterEach(() => { + vi.clearAllMocks() + Object.setPrototypeOf(globalThis, originalGlobalPrototype) +}) + +afterAll(() => { + vi.restoreAllMocks() +}) + +it('returns true if the global property exists and is configurable', () => { + Object.defineProperty(global, '_existsAndConfigurable', { + value: 'something', + configurable: true, + }) + + expect(hasConfigurableGlobal('_existsAndConfigurable')).toBe(true) +}) + +it('returns false if the global property does not exist', () => { + expect(hasConfigurableGlobal('_non-existing')).toBe(false) +}) + +it('returns false for existing global with undefined as a value', () => { + Object.defineProperty(global, '_existsAndUndefined', { + value: undefined, + configurable: true, + }) + expect(hasConfigurableGlobal('_existsAndUndefined')).toBe(false) +}) + +it('returns false for existing global with null as a value', () => { + Object.defineProperty(global, '_existsAndNull', { + value: null, + configurable: true, + }) + expect(hasConfigurableGlobal('_existsAndNull')).toBe(false) +}) + +it('returns false for existing global with a getter that returns undefined', () => { + Object.defineProperty(global, '_existsGetterUndefined', { + get: () => undefined, + configurable: true, + }) + expect(hasConfigurableGlobal('_existsGetterUndefined')).toBe(false) +}) + +it('returns false and prints an error for implicitly non-configurable global property', () => { + Object.defineProperty(global, '_implicitlyNonConfigurable', { + value: 'something', + }) + + expect(hasConfigurableGlobal('_implicitlyNonConfigurable')).toBe(false) + expect(console.error).toHaveBeenCalledWith( + '[MSW] Failed to apply interceptor: the global `_implicitlyNonConfigurable` property is non-configurable. This is likely an issue with your environment. If you are using a framework, please open an issue about this in their repository.' + ) +}) + +it('returns false and prints an error for explicitly non-configurable global property', () => { + Object.defineProperty(global, '_explicitlyNonConfigurable', { + value: 'something', + configurable: false, + }) + + expect(hasConfigurableGlobal('_explicitlyNonConfigurable')).toBe(false) + expect(console.error).toHaveBeenCalledWith( + '[MSW] Failed to apply interceptor: the global `_explicitlyNonConfigurable` property is non-configurable. This is likely an issue with your environment. If you are using a framework, please open an issue about this in their repository.' + ) +}) + +it('returns false and prints an error for global property that only has a getter', () => { + Object.defineProperty(global, '_onlyGetter', { get: () => 'something' }) + + expect(hasConfigurableGlobal('_onlyGetter')).toBe(false) + expect(console.error).toHaveBeenCalledWith( + '[MSW] Failed to apply interceptor: the global `_onlyGetter` property is non-configurable. This is likely an issue with your environment. If you are using a framework, please open an issue about this in their repository.' + ) +}) + +it('returns true for a property on a global prototype', () => { + function FakeGlobalScope() {} + FakeGlobalScope.prototype._prototypeGlobal = 123 + Object.setPrototypeOf(globalThis, FakeGlobalScope.prototype) + + expect(hasConfigurableGlobal('_prototypeGlobal')).toBe(true) +}) diff --git a/node_modules/@mswjs/interceptors/src/utils/hasConfigurableGlobal.ts b/node_modules/@mswjs/interceptors/src/utils/hasConfigurableGlobal.ts new file mode 100644 index 0000000000000000000000000000000000000000..42c13ebb422f77ff916900b18685409a19dd606e --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/hasConfigurableGlobal.ts @@ -0,0 +1,40 @@ +import { getDeepPropertyDescriptor } from './patchesRegistry' + +/** + * Returns a boolean indicating whether the given global property + * is defined and is configurable. + */ +export function hasConfigurableGlobal( + propertyName: keyof typeof globalThis +): boolean { + const match = getDeepPropertyDescriptor(globalThis, propertyName) + + // The property is not set at all. + if (typeof match === 'undefined') { + return false + } + + const { descriptor } = match + + // The property is set to a getter that returns undefined. + if ( + typeof descriptor.get === 'function' && + typeof descriptor.get() === 'undefined' + ) { + return false + } + + // The property is set to a value equal to undefined. + if (typeof descriptor.get === 'undefined' && descriptor.value == null) { + return false + } + + if (typeof descriptor.set === 'undefined' && !descriptor.configurable) { + console.error( + `[MSW] Failed to apply interceptor: the global \`${propertyName}\` property is non-configurable. This is likely an issue with your environment. If you are using a framework, please open an issue about this in their repository.` + ) + return false + } + + return true +} diff --git a/node_modules/@mswjs/interceptors/src/utils/isNodeLikeError.ts b/node_modules/@mswjs/interceptors/src/utils/isNodeLikeError.ts new file mode 100644 index 0000000000000000000000000000000000000000..f74dea789c9fd82fece9a8e57495f5fefc410bc1 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/isNodeLikeError.ts @@ -0,0 +1,13 @@ +export function isNodeLikeError( + error: unknown +): error is NodeJS.ErrnoException { + if (error == null) { + return false + } + + if (!(error instanceof Error)) { + return false + } + + return 'code' in error && 'errno' in error +} diff --git a/node_modules/@mswjs/interceptors/src/utils/isObject.test.ts b/node_modules/@mswjs/interceptors/src/utils/isObject.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..ea4e99d60a605eb74731c51d405e3dee30845ca5 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/isObject.test.ts @@ -0,0 +1,21 @@ +import { it, expect } from 'vitest' +import { isObject } from './isObject' + +it('returns true given an object', () => { + expect(isObject({})).toBe(true) + expect(isObject({ a: 1 })).toBe(true) +}) + +it('returns false given an object-like instance', () => { + expect(isObject([1])).toBe(false) + expect(isObject(function () {})).toBe(false) + expect(isObject(new Response())).toBe(false) +}) + +it('returns false given a non-object instance', () => { + expect(isObject(null)).toBe(false) + expect(isObject(undefined)).toBe(false) + expect(isObject(false)).toBe(false) + expect(isObject(123)).toBe(false) + expect(isObject(Symbol('object Object'))).toBe(false) +}) diff --git a/node_modules/@mswjs/interceptors/src/utils/isObject.ts b/node_modules/@mswjs/interceptors/src/utils/isObject.ts new file mode 100644 index 0000000000000000000000000000000000000000..096e12ea52e8fdefe0819d5717506a8d1a36707a --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/isObject.ts @@ -0,0 +1,8 @@ +/** + * Determines if a given value is an instance of object. + */ +export function isObject(value: any, loose = false): value is T { + return loose + ? Object.prototype.toString.call(value).startsWith('[object ') + : Object.prototype.toString.call(value) === '[object Object]' +} diff --git a/node_modules/@mswjs/interceptors/src/utils/isPropertyAccessible.ts b/node_modules/@mswjs/interceptors/src/utils/isPropertyAccessible.ts new file mode 100644 index 0000000000000000000000000000000000000000..4a80a75bc4b635f6d1e8ea2c8e01756f56da4bb5 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/isPropertyAccessible.ts @@ -0,0 +1,19 @@ +/** + * A function that validates if property access is possible on an object + * without throwing. It returns `true` if the property access is possible + * and `false` otherwise. + * + * Environments like miniflare will throw on property access on certain objects + * like Request and Response, for unimplemented properties. + */ +export function isPropertyAccessible>( + obj: Obj, + key: keyof Obj +) { + try { + obj[key] + return true + } catch { + return false + } +} diff --git a/node_modules/@mswjs/interceptors/src/utils/nextTick.ts b/node_modules/@mswjs/interceptors/src/utils/nextTick.ts new file mode 100644 index 0000000000000000000000000000000000000000..a080ca1e1f34f4a440497765d1509403b55025ed --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/nextTick.ts @@ -0,0 +1,11 @@ +export function nextTick(callback: () => void) { + setTimeout(callback, 0) +} + +export function nextTickAsync(callback: () => void) { + return new Promise((resolve) => { + setTimeout(() => { + resolve(callback()) + }, 0) + }) +} diff --git a/node_modules/@mswjs/interceptors/src/utils/node/index.ts b/node_modules/@mswjs/interceptors/src/utils/node/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..e4f0e72c1f717aeaac73e4ad4eaf0b8fbd513765 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/node/index.ts @@ -0,0 +1,39 @@ +import { ClientRequest } from 'node:http' +import { Readable } from 'node:stream' +import { invariant } from 'outvariant' +import { getRawRequest } from '../../getRawRequest' + +const kRawRequestBodyStream = Symbol('kRawRequestBodyStream') + +/** + * Returns the request body stream of the given request. + * @note This is only relevant in the context of `http.ClientRequest`. + * This function will throw if the given `request` wasn't created based on + * the `http.ClientRequest` instance. + * You must rely on the web stream consumers for other request clients. + */ +export function getClientRequestBodyStream(request: Request): Readable { + const rawRequest = getRawRequest(request) + + invariant( + rawRequest instanceof ClientRequest, + `Failed to retrieve raw request body stream: request is not an instance of "http.ClientRequest". Note that you can only use the "getClientRequestBodyStream" function with the requests issued by "http.clientRequest".` + ) + + const requestBodyStream = Reflect.get(request, kRawRequestBodyStream) + + invariant( + requestBodyStream instanceof Readable, + 'Failed to retrieve raw request body stream: corrupted stream (%s)', + typeof requestBodyStream + ) + + return requestBodyStream +} + +export function setRawRequestBodyStream( + request: Request, + stream: Readable +): void { + Reflect.set(request, kRawRequestBodyStream, stream) +} diff --git a/node_modules/@mswjs/interceptors/src/utils/parseJson.test.ts b/node_modules/@mswjs/interceptors/src/utils/parseJson.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..b0210348163aceceeb7bf077250bb5f7e5143eb2 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/parseJson.test.ts @@ -0,0 +1,10 @@ +import { it, expect } from 'vitest' +import { parseJson } from './parseJson' + +it('parses a given string into JSON', () => { + expect(parseJson('{"id":1}')).toEqual({ id: 1 }) +}) + +it('returns null given invalid JSON string', () => { + expect(parseJson('{"o:2\'')).toBeNull() +}) diff --git a/node_modules/@mswjs/interceptors/src/utils/parseJson.ts b/node_modules/@mswjs/interceptors/src/utils/parseJson.ts new file mode 100644 index 0000000000000000000000000000000000000000..af8d2e6da6e09485911865eba28b239db6fa26b1 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/parseJson.ts @@ -0,0 +1,12 @@ +/** + * Parses a given string into JSON. + * Gracefully handles invalid JSON by returning `null`. + */ +export function parseJson(data: string): Record | null { + try { + const json = JSON.parse(data) + return json + } catch (_) { + return null + } +} diff --git a/node_modules/@mswjs/interceptors/src/utils/patchesRegistry.test.ts b/node_modules/@mswjs/interceptors/src/utils/patchesRegistry.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..c03caf731b7ae9b38c34433b1e61d3bbdfecc9bf --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/patchesRegistry.test.ts @@ -0,0 +1,240 @@ +import { it, beforeEach, afterEach, expect, vi } from 'vitest' +import { patchesRegistry } from './patchesRegistry' + +declare global { + var foo: { original: boolean } +} + +const realGlobalPrototype = Object.getPrototypeOf(global) + +beforeEach(() => { + Object.defineProperty(global, 'foo', { + value: { original: true }, + writable: true, + enumerable: true, + configurable: true, + }) +}) + +afterEach(() => { + Object.setPrototypeOf(global, realGlobalPrototype) + patchesRegistry.restoreAllPatches() +}) + +it('replaces the global', () => { + patchesRegistry.applyPatch(global, 'foo', () => ({ original: false })) + expect(global.foo).toEqual({ original: false }) +}) + +it('exposes the real value to the replacement callback', () => { + patchesRegistry.applyPatch(global, 'foo', (realValue) => { + expect(realValue).toEqual({ original: true }) + return { original: false } + }) + expect(global.foo).toEqual({ original: false }) +}) + +it('replaces the global set on the prototype', () => { + function FakeGlobalScope() {} + FakeGlobalScope.prototype.foo = { prototype: true } + Object.setPrototypeOf(global, FakeGlobalScope.prototype) + Reflect.deleteProperty(global, 'foo') + + expect(global.foo).toEqual({ prototype: true }) + expect(FakeGlobalScope.prototype.foo).toEqual({ prototype: true }) + + patchesRegistry.applyPatch(global, 'foo', () => ({ original: false })) + + expect(global.foo).toEqual({ original: false }) + expect(FakeGlobalScope.prototype.foo, 'Preserves prototype value').toEqual({ + prototype: true, + }) +}) + +it('replaces the global after it was restored', () => { + const restoreGlobal = patchesRegistry.applyPatch(global, 'foo', () => ({ + original: false, + })) + expect(global.foo).toEqual({ original: false }) + + restoreGlobal() + expect(global.foo).toEqual({ original: true }) + + patchesRegistry.applyPatch(global, 'foo', () => ({ original: false })) + expect(global.foo).toEqual({ original: false }) +}) + +it('replaces a property on a custom owner', () => { + const owner = { bar: { original: true } } + const restoreGlobal = patchesRegistry.applyPatch(owner, 'bar', () => ({ + original: false, + })) + + expect(owner.bar).toEqual({ original: false }) + expect(global.foo).toEqual({ original: true }) + + restoreGlobal() + expect(owner.bar).toEqual({ original: true }) +}) + +it('tracks replacements per owner independently', () => { + const ownerA = { shared: 'a-original' } + const ownerB = { shared: 'b-original' } + + const restoreA = patchesRegistry.applyPatch(ownerA, 'shared', () => 'a-next') + const restoreB = patchesRegistry.applyPatch(ownerB, 'shared', () => 'b-next') + + expect(ownerA.shared).toBe('a-next') + expect(ownerB.shared).toBe('b-next') + + restoreA() + expect(ownerA.shared).toBe('a-original') + expect(ownerB.shared).toBe('b-next') + + restoreB() + expect(ownerB.shared).toBe('b-original') +}) + +it('warns on replacing a non-existing global', () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}) + + patchesRegistry.applyPatch( + global, + // @ts-expect-error Intentionally invalid value. + 'NON-EXISTING', + () => ({ original: false }) + ) + expect(console.warn).toHaveBeenCalledExactlyOnceWith( + 'Failed to replace a global value at "NON-EXISTING": not a global value.' + ) +}) + +it('throws if replacing an already replaced global', () => { + patchesRegistry.applyPatch(global, 'foo', () => ({ original: false })) + expect(global.foo).toEqual({ original: false }) + + expect(() => + patchesRegistry.applyPatch(global, 'foo', () => ({ original: false })) + ).toThrow('Failed to replace a global value at "foo": already replaced.') +}) + +it('does nothing if restoring an already restored global', () => { + const restoreGlobal = patchesRegistry.applyPatch(global, 'foo', () => ({ + original: false, + })) + + expect(global.foo).toEqual({ original: false }) + + restoreGlobal() + expect(global.foo).toEqual({ original: true }) + + restoreGlobal() + expect(global.foo).toEqual({ original: true }) +}) + +it('restores the global', () => { + const restoreGlobal = patchesRegistry.applyPatch(global, 'foo', () => ({ + original: false, + })) + expect(global.foo).toEqual({ original: false }) + + restoreGlobal() + expect(global.foo).toEqual({ original: true }) +}) + +it('restores the global set on the prototype', () => { + function FakeGlobalScope() {} + FakeGlobalScope.prototype.foo = { prototype: true } + Object.setPrototypeOf(global, FakeGlobalScope.prototype) + Reflect.deleteProperty(global, 'foo') + + expect(global.foo).toEqual({ prototype: true }) + + const restoreGlobal = patchesRegistry.applyPatch(global, 'foo', () => ({ + original: false, + })) + + expect(global.foo).toEqual({ original: false }) + + restoreGlobal() + expect(global.foo).toEqual({ prototype: true }) +}) + +it('restores global to the original property descriptor', () => { + const descriptor: PropertyDescriptor = { + value: { original: true }, + enumerable: false, + configurable: true, + writable: false, + } + Object.defineProperty(global, 'foo', descriptor) + expect(Object.getOwnPropertyDescriptor(global, 'foo')).toEqual(descriptor) + + const restoreGlobal = patchesRegistry.applyPatch(global, 'foo', () => ({ + original: false, + })) + + expect(global.foo).toEqual({ original: false }) + expect(Object.getOwnPropertyDescriptor(global, 'foo')).toEqual({ + value: { original: false }, + enumerable: true, + configurable: true, + writable: false, + }) + + restoreGlobal() + + expect(global.foo).toEqual({ original: true }) + expect(Object.getOwnPropertyDescriptor(global, 'foo')).toEqual(descriptor) +}) + +it('replaces a non-configurable writable property', () => { + const owner = {} as { foo: { original: boolean } } + const descriptor: PropertyDescriptor = { + value: { original: true }, + enumerable: true, + writable: true, + configurable: false, + } + Object.defineProperty(owner, 'foo', descriptor) + + const restoreGlobal = patchesRegistry.applyPatch(owner, 'foo', () => ({ + original: false, + })) + + expect(owner.foo).toEqual({ original: false }) + expect( + Object.getOwnPropertyDescriptor(owner, 'foo'), + 'Preserves the original descriptor' + ).toEqual({ + value: { original: false }, + enumerable: true, + configurable: false, + writable: true, + }) + + restoreGlobal() + + expect(owner.foo).toEqual({ original: true }) + expect( + Object.getOwnPropertyDescriptor(owner, 'foo'), + 'Restores the original descriptor' + ).toEqual(descriptor) +}) + +it('throws when replacing a non-configurable non-writable property', () => { + let owner = {} as { foo: { original: boolean } } + const descriptor: PropertyDescriptor = { + value: { original: true }, + enumerable: true, + writable: false, + configurable: false, + } + Object.defineProperty(owner, 'foo', descriptor) + + expect(() => + patchesRegistry.applyPatch(owner, 'foo', () => ({ + original: false, + })) + ).toThrow('Failed to patch a non-configurable non-writable property "foo"') +}) diff --git a/node_modules/@mswjs/interceptors/src/utils/patchesRegistry.ts b/node_modules/@mswjs/interceptors/src/utils/patchesRegistry.ts new file mode 100644 index 0000000000000000000000000000000000000000..0c3a594037e7f3bfcbcd7c42f691f493e629d46f --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/patchesRegistry.ts @@ -0,0 +1,134 @@ +import { invariant } from 'outvariant' + +class PatchesRegistry { + #replacements = new Map void>>() + + public applyPatch( + owner: Owner, + key: K, + getNextValue: (realValue: Owner[K]) => Owner[K] + ): () => void { + const ownerReplacements = this.#replacements.get(owner) + + invariant( + !ownerReplacements?.has(key), + `Failed to replace a global value at "${String(key)}": already replaced.` + ) + + const match = getDeepPropertyDescriptor(owner, key) + + if (typeof match === 'undefined') { + console.warn( + `Failed to replace a global value at "${String(key)}": not a global value.` + ) + return () => {} + } + + if (match.descriptor.configurable) { + Object.defineProperty(owner, key, { + value: getNextValue(owner[key]), + enumerable: true, + configurable: true, + }) + } else if (match.descriptor.writable) { + owner[key] = getNextValue(owner[key]) + } else { + throw new Error( + `Failed to patch a non-configurable non-writable property "${key.toString()}"` + ) + } + + const restorePatch = () => { + const currentReplacements = this.#replacements.get(owner) + + if (!currentReplacements?.has(key)) { + return + } + + if (match.owner === owner) { + /** + * @note Restoring non-configurable properties works as long as "writable: true" + * and none of the other descriptor properties except for "value" have changed. + */ + Object.defineProperty(match.owner, key, match.descriptor) + } else { + /** + * @todo Delete the proxy property set by the registry. + * If the match's owner isn't the original owner, the property is likely nested in the prototype. + * The registry does not meddle with those, they are left intact. + */ + Reflect.deleteProperty(owner, key) + } + + currentReplacements.delete(key) + + if (currentReplacements.size === 0) { + this.#replacements.delete(owner) + } + } + + if (ownerReplacements) { + ownerReplacements.set(key, restorePatch) + } else { + this.#replacements.set(owner, new Map([[key, restorePatch]])) + } + + return restorePatch + } + + public restoreAllPatches(): void { + const errors: Array = [] + + for (const [, ownerReplacements] of this.#replacements) { + for (const [, restorePatch] of ownerReplacements) { + try { + restorePatch() + } catch (error) { + if (error instanceof Error) { + errors.push(error) + } else { + throw error + } + } + } + } + + if (errors.length > 0) { + throw new AggregateError(errors, 'FOO!') + } + } +} + +export const patchesRegistry = new PatchesRegistry() + +interface DeepDescriptorMatch { + owner: object + descriptor: PropertyDescriptor +} + +/** + * Returns a property descriptor for the given property on the owner. + * Walks down the prototype chain if the property does not exist on the owner. + * Handy for getting a global property descriptor where `globalThis` is + * replaced with a controlled class (e.g. ServiceWorkerGlobalScope). + */ +export function getDeepPropertyDescriptor( + owner: Owner, + key: keyof Owner +): DeepDescriptorMatch | undefined { + let currentOwner: Owner | null = owner + let descriptor: PropertyDescriptor | undefined + + while (currentOwner) { + descriptor = Object.getOwnPropertyDescriptor(currentOwner, key) + + if (descriptor) { + return { + owner: currentOwner, + descriptor, + } + } + + currentOwner = Object.getPrototypeOf(currentOwner) + } +} diff --git a/node_modules/@mswjs/interceptors/src/utils/resolveWebSocketUrl.ts b/node_modules/@mswjs/interceptors/src/utils/resolveWebSocketUrl.ts new file mode 100644 index 0000000000000000000000000000000000000000..0c15a1e1f8ea82b0bddfd019b5963f51a854bc4b --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/resolveWebSocketUrl.ts @@ -0,0 +1,45 @@ +/** + * Resolve potentially relative WebSocket URLs the same way + * the browser does (replace the protocol, use the origin, etc). + * + * @see https://websockets.spec.whatwg.org//#dom-websocket-websocket + */ +export function resolveWebSocketUrl(url: string | URL): string { + if (typeof url === 'string') { + /** + * @note Cast the string to a URL first so the parsing errors + * are thrown as a part of the WebSocket constructor, not consumers. + */ + const urlRecord = new URL( + url, + typeof location !== 'undefined' ? location.href : undefined + ) + + return resolveWebSocketUrl(urlRecord) + } + + if (url.protocol === 'http:') { + url.protocol = 'ws:' + } else if (url.protocol === 'https:') { + url.protocol = 'wss:' + } + + if (url.protocol !== 'ws:' && url.protocol !== 'wss:') { + /** + * @note These errors are modeled after the browser errors. + * The exact error messages aren't provided in the specification. + * Node.js uses more obscure error messages that I don't wish to replicate. + */ + throw new SyntaxError( + `Failed to construct 'WebSocket': The URL's scheme must be either 'http', 'https', 'ws', or 'wss'. '${url.protocol}' is not allowed.` + ) + } + + if (url.hash !== '') { + throw new SyntaxError( + `Failed to construct 'WebSocket': The URL contains a fragment identifier ('${url.hash}'). Fragment identifiers are not allowed in WebSocket URLs.` + ) + } + + return url.href +} diff --git a/node_modules/@mswjs/interceptors/src/utils/responseUtils.ts b/node_modules/@mswjs/interceptors/src/utils/responseUtils.ts new file mode 100644 index 0000000000000000000000000000000000000000..67c35c4fcadd8a46e8766d1ade6a63898ddfd1b5 --- /dev/null +++ b/node_modules/@mswjs/interceptors/src/utils/responseUtils.ts @@ -0,0 +1,59 @@ +import { isObject } from './isObject' +import { isPropertyAccessible } from './isPropertyAccessible' + +/** + * Creates a generic 500 Unhandled Exception response. + */ +export function createServerErrorResponse(body: unknown): Response { + return new Response( + JSON.stringify( + body instanceof Error + ? { + name: body.name, + message: body.message, + stack: body.stack, + } + : body + ), + { + status: 500, + statusText: 'Unhandled Exception', + headers: { + 'Content-Type': 'application/json', + }, + } + ) +} + +export type ResponseError = Response & { type: 'error' } + +/** + * Check if the given response is a `Response.error()`. + * + * @note Some environments, like Miniflare (Cloudflare) do not + * implement the "Response.type" property and throw on its access. + * Safely check if we can access "type" on "Response" before continuing. + * @see https://github.com/mswjs/msw/issues/1834 + */ +export function isResponseError(response: unknown): response is ResponseError { + return ( + response != null && + response instanceof Response && + isPropertyAccessible(response, 'type') && + response.type === 'error' + ) +} + +/** + * Check if the given value is a `Response` or a Response-like object. + * This is different from `value instanceof Response` because it supports + * custom `Response` constructors, like the one when using Undici directly. + */ +export function isResponseLike(value: unknown): value is Response { + return ( + isObject>(value, true) && + isPropertyAccessible(value, 'status') && + isPropertyAccessible(value, 'statusText') && + isPropertyAccessible(value, 'bodyUsed') + ) +} diff --git a/node_modules/@napi-rs/wasm-runtime/fs-proxy.js b/node_modules/@napi-rs/wasm-runtime/fs-proxy.js new file mode 100644 index 0000000000000000000000000000000000000000..4daf897876396c2e80c605701325e6fef2f1159f --- /dev/null +++ b/node_modules/@napi-rs/wasm-runtime/fs-proxy.js @@ -0,0 +1,316 @@ +// @ts-check + +/** + * @param {unknown} value + */ +const getType = (value) => { + if (value === undefined) return 0 + if (value === null) return 1 + if (isBuffer(value)) return 10 + const t = typeof value + if (t === 'boolean') return 2 + if (t === 'number') return 3 + if (t === 'string') return 4 + if (t === 'object') return 6 + if (t === 'bigint') return 9 + return -1 +} + +/** + * @param {unknown} value + * @returns {value is Uint8Array} + */ +const isBuffer = (value) => { + const BufferCtor = globalThis.Buffer + if (typeof BufferCtor?.isBuffer === 'function') { + return BufferCtor.isBuffer(value) + } + return value instanceof Uint8Array && value.constructor?.name === 'Buffer' +} + +const RESPONSE_HEADER_SIZE = 16 +const RESPONSE_PAYLOAD_SIZE = 10240 +const RESPONSE_BUFFER_SIZE = RESPONSE_HEADER_SIZE + RESPONSE_PAYLOAD_SIZE + +/** + * @param {Int32Array} sab + * @param {Uint8Array} payload + */ +const writeResponsePayload = (sab, payload) => { + if (payload.length > RESPONSE_PAYLOAD_SIZE) { + throw new RangeError('payload overflow') + } + new Uint8Array(sab.buffer).set(payload, RESPONSE_HEADER_SIZE) +} + +/** + * @param {import('memfs').IFs} memfs + * @param {any} value + * @param {ReturnType} type + * @returns {Uint8Array} + */ +const encodeValue = (memfs, value, type) => { + switch (type) { + case 0: + case 1: + return new Uint8Array(0) + case 2: { + const view = new Int32Array(1) + view[0] = value ? 1 : 0 + return new Uint8Array(view.buffer) + } + case 3: { + const view = new Float64Array(1) + view[0] = value + return new Uint8Array(view.buffer) + } + case 4: { + const view = new TextEncoder().encode(value) + return view + } + case 10: + return new Uint8Array(value) + case 6: { + function storeConstructor(obj, memfs, processed = new WeakSet()) { + if (!obj || typeof obj !== 'object') { + return + } + + if (processed.has(obj)) { + return + } + + processed.add(obj) + + const [entry] = + Object.entries(memfs).filter(([_, v]) => v === obj.constructor)[0] ?? + [] + if (entry) { + Object.defineProperty(obj, '__constructor__', { + configurable: true, + writable: true, + enumerable: true, + value: entry, + }) + } + + for (const value of Object.values(obj)) { + storeConstructor(value, memfs, processed) + } + } + + storeConstructor(value, memfs) + + const json = JSON.stringify(value, (_, value) => { + if (typeof value === 'bigint') { + return `BigInt(${String(value)})` + } + if (value instanceof Error) { + return { + ...value, + message: value.message, + stack: value.stack, + __error__: value.constructor.name, + } + } + return value + }) + const view = new TextEncoder().encode(json) + return view + } + case 9: { + return new TextEncoder().encode(String(value)) + } + case -1: + default: + throw new Error('unsupported data') + } +} + +/** + * @param {typeof import('memfs')} memfs + * @param {Uint8Array} payload + * @param {number} type + * @returns {any} + */ +const decodeValue = (memfs, payload, type) => { + if (type === 0) return undefined + if (type === 1) return null + if (type === 2) + return Boolean(new Int32Array(payload.buffer, payload.byteOffset, 1)[0]) + if (type === 3) + return new Float64Array(payload.buffer, payload.byteOffset, 1)[0] + if (type === 4) return new TextDecoder().decode(payload.slice()) + if (type === 10) { + const BufferCtor = globalThis.Buffer + if (typeof BufferCtor?.from === 'function') { + return BufferCtor.from(payload) + } + return payload.slice() + } + if (type === 6) { + const obj = JSON.parse( + new TextDecoder().decode(payload.slice()), + (_key, value) => { + if (typeof value === 'string') { + const matched = value.match(/^BigInt\((-?\d+)\)$/) + if (matched && matched[1]) { + return BigInt(matched[1]) + } + } + return value + }, + ) + + function loadConstructor(obj, memfs, processed = new WeakSet()) { + if (!obj || typeof obj !== 'object') { + return + } + + if (processed.has(obj)) { + return + } + + processed.add(obj) + + if (obj.__constructor__) { + const ctor = obj.__constructor__ + delete obj.__constructor__ + Object.setPrototypeOf(obj, memfs[ctor].prototype) + } + + for (const value of Object.values(obj)) { + loadConstructor(value, memfs, processed) + } + } + + loadConstructor(obj, memfs) + + if (obj.__error__) { + const name = obj.__error__ + const ErrorConstructor = globalThis[name] || Error + delete obj.__error__ + const err = new ErrorConstructor(obj.message) + Object.defineProperty(err, 'stack', { + configurable: true, + enumerable: false, + writable: true, + value: err.stack, + }) + Object.defineProperty(err, Symbol.toStringTag, { + configurable: true, + enumerable: false, + writable: true, + value: name, + }) + for (const [k, v] of Object.entries(obj)) { + if (k === 'message' || k === 'stack') continue + err[k] = v + } + return err + } + return obj + } + if (type === 9) { + return BigInt(new TextDecoder().decode(payload.slice())) + } + throw new Error('unsupported data') +} + +/** + * @param {import('memfs').IFs} fs + * @returns {(e: { data: { __fs__: { sab: Int32Array, type: keyof import('memfs').IFs, payload: any[] } } }) => void} + */ +// oxlint-disable-next-line no-unused-vars -- fixed in an upcoming release +export const createOnMessage = (fs) => + function onMessage(e) { + if (e.data.__fs__) { + /** + * 0..4 status(int32_t): 21(waiting) 0(success) 1(error) + * 5..8 type(napi_valuetype): 0(undefined) 1(null) 2(boolean) 3(number) 4(string) 6(jsonstring) 9(bigint) 10(buffer) -1(unsupported) + * 9..16 payload_size(uint32_t) <= 10240 + * 16..16 + payload_size payload_content + */ + const { sab, type, payload } = e.data.__fs__ + const fn = fs[type] + try { + const ret = fn.apply(fs, payload) + const t = getType(ret) + Atomics.store(sab, 1, t) + const v = encodeValue(fs, ret, t) + Atomics.store(sab, 2, v.length) + writeResponsePayload(sab, v) + Atomics.store(sab, 0, 0) // success + } catch (/** @type {any} */ err) { + let t = getType(err) + let v + try { + if (t === -1) { + throw new Error('unsupported data') + } + v = encodeValue(fs, err, t) + } catch { + const fallback = (() => { + try { + return String(err) + } catch { + return 'Unserializable thrown value' + } + })() + t = getType(fallback) + v = encodeValue(fs, fallback, t) + } + if (v.length > RESPONSE_PAYLOAD_SIZE) { + const overflowErr = new RangeError('payload overflow') + t = getType(overflowErr) + v = encodeValue(fs, overflowErr, t) + } + Atomics.store(sab, 1, t) + Atomics.store(sab, 2, v.length) + writeResponsePayload(sab, v) + Atomics.store(sab, 0, 1) // error + } finally { + Atomics.notify(sab, 0) + } + } + } + +/** + * @param {typeof import('memfs')} memfs + */ +export const createFsProxy = (memfs) => + new Proxy( + {}, + { + get(_target, p, _receiver) { + /** + * @param {any[]} args + */ + return function (...args) { + const sab = new SharedArrayBuffer(RESPONSE_BUFFER_SIZE) + const i32arr = new Int32Array(sab) + Atomics.store(i32arr, 0, 21) + + postMessage({ + __fs__: { + sab: i32arr, + type: p, + payload: args, + }, + }) + + Atomics.wait(i32arr, 0, 21) + + const status = Atomics.load(i32arr, 0) + const type = Atomics.load(i32arr, 1) + const size = Atomics.load(i32arr, 2) + const content = new Uint8Array(sab, RESPONSE_HEADER_SIZE, size) + const value = decodeValue(memfs, content, type) + if (status === 1) { + throw value + } + return value + } + }, + }, + ) diff --git a/node_modules/@napi-rs/wasm-runtime/package.json b/node_modules/@napi-rs/wasm-runtime/package.json new file mode 100644 index 0000000000000000000000000000000000000000..8ba6e5d824d02e98d1a47ef901da0ab77afffc60 --- /dev/null +++ b/node_modules/@napi-rs/wasm-runtime/package.json @@ -0,0 +1,70 @@ +{ + "name": "@napi-rs/wasm-runtime", + "version": "1.1.5", + "type": "module", + "description": "Runtime and polyfill for wasm targets", + "homepage": "https://napi.rs/", + "author": { + "name": "LongYinan", + "url": "https://github.com/Brooooooklyn" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/napi-rs/napi-rs.git", + "directory": "wasm-runtime" + }, + "license": "MIT", + "publishConfig": { + "registry": "https://registry.npmjs.org/", + "access": "public" + }, + "files": [ + "runtime.cjs", + "runtime.js", + "fs-proxy.js", + "dist/*.cjs", + "dist/*.js" + ], + "devDependencies": { + "@rollup/plugin-alias": "^6.0.0", + "@rollup/plugin-commonjs": "^29.0.3", + "@rollup/plugin-inject": "^5.0.5", + "@rollup/plugin-json": "^6.1.0", + "@rollup/plugin-node-resolve": "^16.0.3", + "@rollup/plugin-replace": "^6.0.3", + "buffer": "^6.0.3", + "events": "^3.3.0", + "memfs": "^4.57.6", + "node-inspect-extracted": "^3.3.2", + "path-browserify": "^1.0.1", + "process": "^0.11.10", + "readable-stream": "^4.7.0", + "rollup": "^4.61.1", + "rollup-plugin-polyfill-node": "^0.13.0", + "tslib": "^2.8.1" + }, + "dependencies": { + "@tybys/wasm-util": "^0.10.2" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1", + "@emnapi/runtime": "^1.7.1" + }, + "scripts": { + "build": "rollup -c rollup.config.js", + "test": "node --test" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "exports": { + ".": { + "import": "./runtime.js", + "require": "./runtime.cjs" + }, + "./fs": { + "import": "./dist/fs.js" + } + } +} diff --git a/node_modules/@napi-rs/wasm-runtime/runtime.cjs b/node_modules/@napi-rs/wasm-runtime/runtime.cjs new file mode 100644 index 0000000000000000000000000000000000000000..a22e62a07d667e594c2b16967544d9f1388238fd --- /dev/null +++ b/node_modules/@napi-rs/wasm-runtime/runtime.cjs @@ -0,0 +1,15 @@ +const { MessageHandler, instantiateNapiModuleSync, instantiateNapiModule } = require('@emnapi/core') +const { getDefaultContext } = require('@emnapi/runtime') +const { WASI } = require('@tybys/wasm-util') + +const { createFsProxy, createOnMessage } = require('./dist/fs-proxy.cjs') + +module.exports = { + MessageHandler, + instantiateNapiModule, + instantiateNapiModuleSync, + getDefaultContext, + WASI, + createFsProxy, + createOnMessage, +} diff --git a/node_modules/@napi-rs/wasm-runtime/runtime.js b/node_modules/@napi-rs/wasm-runtime/runtime.js new file mode 100644 index 0000000000000000000000000000000000000000..abbe9e29887db5357257576b94e6aa39c926fd3c --- /dev/null +++ b/node_modules/@napi-rs/wasm-runtime/runtime.js @@ -0,0 +1,8 @@ +export { + instantiateNapiModuleSync, + instantiateNapiModule, + MessageHandler, +} from '@emnapi/core' +export { getDefaultContext } from '@emnapi/runtime' +export * from '@tybys/wasm-util' +export { createOnMessage, createFsProxy } from './fs-proxy.js' diff --git a/node_modules/@nestjs/common/LICENSE b/node_modules/@nestjs/common/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d209764d20a03be35896a1ad8ebf6aba30bc7172 --- /dev/null +++ b/node_modules/@nestjs/common/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2017-present Kamil Mysliwiec + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@nestjs/common/PACKAGE.md b/node_modules/@nestjs/common/PACKAGE.md new file mode 100644 index 0000000000000000000000000000000000000000..2e33978e5d219006030703640f87e2e9d0c9ae2b --- /dev/null +++ b/node_modules/@nestjs/common/PACKAGE.md @@ -0,0 +1 @@ +The common package comes with decorators such as `@Controller()`, `@Injectable()` and so on. diff --git a/node_modules/@nestjs/common/Readme.md b/node_modules/@nestjs/common/Readme.md new file mode 100644 index 0000000000000000000000000000000000000000..d1631aae1b84b50b74ce4464d1c55dc12837e497 --- /dev/null +++ b/node_modules/@nestjs/common/Readme.md @@ -0,0 +1,150 @@ +

+ Nest Logo +

+ +[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456 +[circleci-url]: https://circleci.com/gh/nestjs/nest + +

A progressive Node.js framework for building efficient and scalable server-side applications.

+

+NPM Version +Package License +NPM Downloads +CircleCI +Discord +Backers on Open Collective +Sponsors on Open Collective + + Support us + +

+ + +## Description + +Nest is a framework for building efficient, scalable Node.js server-side applications. It uses modern JavaScript, is built with TypeScript (preserves compatibility with pure JavaScript) and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Reactive Programming). + +

Under the hood, Nest makes use of Express, but also provides compatibility with a wide range of other libraries, like Fastify, allowing for easy use of the myriad of third-party plugins which are available.

+ +## Philosophy + +

In recent years, thanks to Node.js, JavaScript has become the “lingua franca” of the web for both front-end and back-end applications, giving rise to awesome projects like Angular, React, and Vue, which improve developer productivity and enable the construction of fast, testable, and extensible frontend applications. However, on the server-side, while there are a lot of superb libraries, helpers, and tools for Node, none of them effectively solve the main problem - the architecture.

+

Nest aims to provide an application architecture out of the box which allows for effortless creation of highly testable, scalable, and loosely coupled and easily maintainable applications. The architecture is heavily inspired by Angular.

+ +## Getting started + +- To check out the [guide](https://docs.nestjs.com), visit [docs.nestjs.com](https://docs.nestjs.com). :books: +- 要查看中文 [指南](readme_zh.md), 请访问 [docs.nestjs.cn](https://docs.nestjs.cn). :books: +- [가이드](readme_kr.md) 문서는 [docs.nestjs.com](https://docs.nestjs.com)에서 확인하실 수 있습니다. :books: +- [ガイド](readme_jp.md)は [docs.nestjs.com](https://docs.nestjs.com)でご確認ください。 :books: + +## Questions + +For questions and support please use the official [Discord channel](https://discord.gg/G7Qnnhy). The issue list of this repo is **exclusively** for bug reports and feature requests. + +## Issues + +Please make sure to read the [Issue Reporting Checklist](https://github.com/nestjs/nest/blob/master/CONTRIBUTING.md#-submitting-an-issue) before opening an issue. Issues not conforming to the guidelines may be closed immediately. + +## Consulting + +With official support, you can get expert help straight from the Nest core team. We provide dedicated technical support, migration strategies, advice on best practices (and design decisions), PR reviews, and team augmentation. Read more about [support here](https://enterprise.nestjs.com). + +## Support + +Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support from the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support). + +#### Principal Sponsors + + + + + + + + + +
+ +#### Gold Sponsors + + + + + + + + + + + + + +
+ +#### Silver Sponsors + + + + + + + + + + + + + + + +
+ +#### Sponsors + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +## Backers + + + +## Stay in touch + +- Author - [Kamil Myśliwiec](https://x.com/kammysliwiec) +- Website - [https://nestjs.com](https://nestjs.com/) +- X - [@nestframework](https://x.com/nestframework) + +## License + +Nest is [MIT licensed](LICENSE). diff --git a/node_modules/@nestjs/common/constants.d.ts b/node_modules/@nestjs/common/constants.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..246972ace94c9c3f370b7b323e9c43cdf7e674a0 --- /dev/null +++ b/node_modules/@nestjs/common/constants.d.ts @@ -0,0 +1,42 @@ +export declare const MODULE_METADATA: { + IMPORTS: string; + PROVIDERS: string; + CONTROLLERS: string; + EXPORTS: string; +}; +export declare const GLOBAL_MODULE_METADATA = "__module:global__"; +export declare const HOST_METADATA = "host"; +export declare const PATH_METADATA = "path"; +export declare const PARAMTYPES_METADATA = "design:paramtypes"; +export declare const SELF_DECLARED_DEPS_METADATA = "self:paramtypes"; +export declare const OPTIONAL_DEPS_METADATA = "optional:paramtypes"; +export declare const PROPERTY_DEPS_METADATA = "self:properties_metadata"; +export declare const OPTIONAL_PROPERTY_DEPS_METADATA = "optional:properties_metadata"; +export declare const SCOPE_OPTIONS_METADATA = "scope:options"; +export declare const METHOD_METADATA = "method"; +export declare const ROUTE_ARGS_METADATA = "__routeArguments__"; +export declare const CUSTOM_ROUTE_ARGS_METADATA = "__customRouteArgs__"; +export declare const FILTER_CATCH_EXCEPTIONS = "__filterCatchExceptions__"; +export declare const PIPES_METADATA = "__pipes__"; +export declare const GUARDS_METADATA = "__guards__"; +export declare const INTERCEPTORS_METADATA = "__interceptors__"; +export declare const EXCEPTION_FILTERS_METADATA = "__exceptionFilters__"; +export declare const ENHANCER_KEY_TO_SUBTYPE_MAP: { + readonly __guards__: "guard"; + readonly __interceptors__: "interceptor"; + readonly __pipes__: "pipe"; + readonly __exceptionFilters__: "filter"; +}; +export type EnhancerSubtype = (typeof ENHANCER_KEY_TO_SUBTYPE_MAP)[keyof typeof ENHANCER_KEY_TO_SUBTYPE_MAP]; +export declare const RENDER_METADATA = "__renderTemplate__"; +export declare const HTTP_CODE_METADATA = "__httpCode__"; +export declare const MODULE_PATH = "__module_path__"; +export declare const HEADERS_METADATA = "__headers__"; +export declare const REDIRECT_METADATA = "__redirect__"; +export declare const RESPONSE_PASSTHROUGH_METADATA = "__responsePassthrough__"; +export declare const SSE_METADATA = "__sse__"; +export declare const VERSION_METADATA = "__version__"; +export declare const INJECTABLE_WATERMARK = "__injectable__"; +export declare const CONTROLLER_WATERMARK = "__controller__"; +export declare const CATCH_WATERMARK = "__catch__"; +export declare const ENTRY_PROVIDER_WATERMARK = "__entryProvider__"; diff --git a/node_modules/@nestjs/common/constants.js b/node_modules/@nestjs/common/constants.js new file mode 100644 index 0000000000000000000000000000000000000000..33476343d19b1efa3a9af3eea2abee5edaa4f41d --- /dev/null +++ b/node_modules/@nestjs/common/constants.js @@ -0,0 +1,44 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ENTRY_PROVIDER_WATERMARK = exports.CATCH_WATERMARK = exports.CONTROLLER_WATERMARK = exports.INJECTABLE_WATERMARK = exports.VERSION_METADATA = exports.SSE_METADATA = exports.RESPONSE_PASSTHROUGH_METADATA = exports.REDIRECT_METADATA = exports.HEADERS_METADATA = exports.MODULE_PATH = exports.HTTP_CODE_METADATA = exports.RENDER_METADATA = exports.ENHANCER_KEY_TO_SUBTYPE_MAP = exports.EXCEPTION_FILTERS_METADATA = exports.INTERCEPTORS_METADATA = exports.GUARDS_METADATA = exports.PIPES_METADATA = exports.FILTER_CATCH_EXCEPTIONS = exports.CUSTOM_ROUTE_ARGS_METADATA = exports.ROUTE_ARGS_METADATA = exports.METHOD_METADATA = exports.SCOPE_OPTIONS_METADATA = exports.OPTIONAL_PROPERTY_DEPS_METADATA = exports.PROPERTY_DEPS_METADATA = exports.OPTIONAL_DEPS_METADATA = exports.SELF_DECLARED_DEPS_METADATA = exports.PARAMTYPES_METADATA = exports.PATH_METADATA = exports.HOST_METADATA = exports.GLOBAL_MODULE_METADATA = exports.MODULE_METADATA = void 0; +exports.MODULE_METADATA = { + IMPORTS: 'imports', + PROVIDERS: 'providers', + CONTROLLERS: 'controllers', + EXPORTS: 'exports', +}; +exports.GLOBAL_MODULE_METADATA = '__module:global__'; +exports.HOST_METADATA = 'host'; +exports.PATH_METADATA = 'path'; +exports.PARAMTYPES_METADATA = 'design:paramtypes'; +exports.SELF_DECLARED_DEPS_METADATA = 'self:paramtypes'; +exports.OPTIONAL_DEPS_METADATA = 'optional:paramtypes'; +exports.PROPERTY_DEPS_METADATA = 'self:properties_metadata'; +exports.OPTIONAL_PROPERTY_DEPS_METADATA = 'optional:properties_metadata'; +exports.SCOPE_OPTIONS_METADATA = 'scope:options'; +exports.METHOD_METADATA = 'method'; +exports.ROUTE_ARGS_METADATA = '__routeArguments__'; +exports.CUSTOM_ROUTE_ARGS_METADATA = '__customRouteArgs__'; +exports.FILTER_CATCH_EXCEPTIONS = '__filterCatchExceptions__'; +exports.PIPES_METADATA = '__pipes__'; +exports.GUARDS_METADATA = '__guards__'; +exports.INTERCEPTORS_METADATA = '__interceptors__'; +exports.EXCEPTION_FILTERS_METADATA = '__exceptionFilters__'; +exports.ENHANCER_KEY_TO_SUBTYPE_MAP = { + [exports.GUARDS_METADATA]: 'guard', + [exports.INTERCEPTORS_METADATA]: 'interceptor', + [exports.PIPES_METADATA]: 'pipe', + [exports.EXCEPTION_FILTERS_METADATA]: 'filter', +}; +exports.RENDER_METADATA = '__renderTemplate__'; +exports.HTTP_CODE_METADATA = '__httpCode__'; +exports.MODULE_PATH = '__module_path__'; +exports.HEADERS_METADATA = '__headers__'; +exports.REDIRECT_METADATA = '__redirect__'; +exports.RESPONSE_PASSTHROUGH_METADATA = '__responsePassthrough__'; +exports.SSE_METADATA = '__sse__'; +exports.VERSION_METADATA = '__version__'; +exports.INJECTABLE_WATERMARK = '__injectable__'; +exports.CONTROLLER_WATERMARK = '__controller__'; +exports.CATCH_WATERMARK = '__catch__'; +exports.ENTRY_PROVIDER_WATERMARK = '__entryProvider__'; diff --git a/node_modules/@nestjs/common/decorators/core/apply-decorators.d.ts b/node_modules/@nestjs/common/decorators/core/apply-decorators.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..84dccfdceca6ab020e439febcbb7242ccebe8d65 --- /dev/null +++ b/node_modules/@nestjs/common/decorators/core/apply-decorators.d.ts @@ -0,0 +1,10 @@ +/** + * Function that returns a new decorator that applies all decorators provided by param + * + * Useful to build new decorators (or a decorator factory) encapsulating multiple decorators related with the same feature + * + * @param decorators one or more decorators (e.g., `ApplyGuard(...)`) + * + * @publicApi + */ +export declare function applyDecorators(...decorators: Array): (target: TFunction | object, propertyKey?: string | symbol, descriptor?: TypedPropertyDescriptor) => void; diff --git a/node_modules/@nestjs/common/decorators/core/apply-decorators.js b/node_modules/@nestjs/common/decorators/core/apply-decorators.js new file mode 100644 index 0000000000000000000000000000000000000000..117c331d81898d2081b2428f2cb09d65d713542d --- /dev/null +++ b/node_modules/@nestjs/common/decorators/core/apply-decorators.js @@ -0,0 +1,23 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.applyDecorators = applyDecorators; +/** + * Function that returns a new decorator that applies all decorators provided by param + * + * Useful to build new decorators (or a decorator factory) encapsulating multiple decorators related with the same feature + * + * @param decorators one or more decorators (e.g., `ApplyGuard(...)`) + * + * @publicApi + */ +function applyDecorators(...decorators) { + return (target, propertyKey, descriptor) => { + for (const decorator of decorators) { + if (target instanceof Function && !descriptor) { + decorator(target); + continue; + } + decorator(target, propertyKey, descriptor); + } + }; +} diff --git a/node_modules/@nestjs/common/decorators/core/bind.decorator.d.ts b/node_modules/@nestjs/common/decorators/core/bind.decorator.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..90cceeb5ba208dc434d5731edfa27df6f69f1459 --- /dev/null +++ b/node_modules/@nestjs/common/decorators/core/bind.decorator.d.ts @@ -0,0 +1,11 @@ +/** + * Decorator that binds *parameter decorators* to the method that follows. + * + * Useful when the language doesn't provide a 'Parameter Decorator' feature + * (i.e., vanilla JavaScript). + * + * @param decorators one or more parameter decorators (e.g., `Req()`) + * + * @publicApi + */ +export declare function Bind(...decorators: any[]): MethodDecorator; diff --git a/node_modules/@nestjs/common/decorators/core/bind.decorator.js b/node_modules/@nestjs/common/decorators/core/bind.decorator.js new file mode 100644 index 0000000000000000000000000000000000000000..591f9dc33e8b20252e817defd7cc4adb4c2525a4 --- /dev/null +++ b/node_modules/@nestjs/common/decorators/core/bind.decorator.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Bind = Bind; +/** + * Decorator that binds *parameter decorators* to the method that follows. + * + * Useful when the language doesn't provide a 'Parameter Decorator' feature + * (i.e., vanilla JavaScript). + * + * @param decorators one or more parameter decorators (e.g., `Req()`) + * + * @publicApi + */ +function Bind(...decorators) { + return (target, key, descriptor) => { + decorators.forEach((fn, index) => fn(target, key, index)); + return descriptor; + }; +} diff --git a/node_modules/@nestjs/common/decorators/core/catch.decorator.d.ts b/node_modules/@nestjs/common/decorators/core/catch.decorator.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d18e37c95edaa1d5339791b15dd69ff8e1998c93 --- /dev/null +++ b/node_modules/@nestjs/common/decorators/core/catch.decorator.d.ts @@ -0,0 +1,19 @@ +import { Type, Abstract } from '../../interfaces'; +/** + * Decorator that marks a class as a Nest exception filter. An exception filter + * handles exceptions thrown by or not handled by your application code. + * + * The decorated class must implement the `ExceptionFilter` interface. + * + * @param exceptions one or more exception *types* specifying + * the exceptions to be caught and handled by this filter. + * + * @see [Exception Filters](https://docs.nestjs.com/exception-filters) + * + * @usageNotes + * Exception filters are applied using the `@UseFilters()` decorator, or (globally) + * with `app.useGlobalFilters()`. + * + * @publicApi + */ +export declare function Catch(...exceptions: Array | Abstract>): ClassDecorator; diff --git a/node_modules/@nestjs/common/decorators/core/catch.decorator.js b/node_modules/@nestjs/common/decorators/core/catch.decorator.js new file mode 100644 index 0000000000000000000000000000000000000000..f4a382d5cb662d0b8bdf8c926bfd38704b61f7bf --- /dev/null +++ b/node_modules/@nestjs/common/decorators/core/catch.decorator.js @@ -0,0 +1,27 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Catch = Catch; +const constants_1 = require("../../constants"); +/** + * Decorator that marks a class as a Nest exception filter. An exception filter + * handles exceptions thrown by or not handled by your application code. + * + * The decorated class must implement the `ExceptionFilter` interface. + * + * @param exceptions one or more exception *types* specifying + * the exceptions to be caught and handled by this filter. + * + * @see [Exception Filters](https://docs.nestjs.com/exception-filters) + * + * @usageNotes + * Exception filters are applied using the `@UseFilters()` decorator, or (globally) + * with `app.useGlobalFilters()`. + * + * @publicApi + */ +function Catch(...exceptions) { + return (target) => { + Reflect.defineMetadata(constants_1.CATCH_WATERMARK, true, target); + Reflect.defineMetadata(constants_1.FILTER_CATCH_EXCEPTIONS, exceptions, target); + }; +} diff --git a/node_modules/@nestjs/common/decorators/core/controller.decorator.d.ts b/node_modules/@nestjs/common/decorators/core/controller.decorator.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..804208564a65c7b2fc312282cf379ae2ce4b3748 --- /dev/null +++ b/node_modules/@nestjs/common/decorators/core/controller.decorator.d.ts @@ -0,0 +1,102 @@ +import { ScopeOptions, VersionOptions } from '../../interfaces'; +/** + * Interface defining options that can be passed to `@Controller()` decorator + * + * @publicApi + */ +export interface ControllerOptions extends ScopeOptions, VersionOptions { + /** + * Specifies an optional `route path prefix`. The prefix is pre-pended to the + * path specified in any request decorator in the class. + * + * Supported only by HTTP-based applications (does not apply to non-HTTP microservices). + * + * @see [Routing](https://docs.nestjs.com/controllers#routing) + */ + path?: string | string[]; + /** + * Specifies an optional HTTP Request host filter. When configured, methods + * within the controller will only be routed if the request host matches the + * specified value. + * + * @see [Routing](https://docs.nestjs.com/controllers#routing) + */ + host?: string | RegExp | Array; +} +/** + * Decorator that marks a class as a Nest controller that can receive inbound + * requests and produce responses. + * + * An HTTP Controller responds to inbound HTTP Requests and produces HTTP Responses. + * It defines a class that provides the context for one or more related route + * handlers that correspond to HTTP request methods and associated routes + * for example `GET /api/profile`, `POST /users/resume`. + * + * A Microservice Controller responds to requests as well as events, running over + * a variety of transports [(read more here)](https://docs.nestjs.com/microservices/basics). + * It defines a class that provides a context for one or more message or event + * handlers. + * + * @see [Controllers](https://docs.nestjs.com/controllers) + * @see [Microservices](https://docs.nestjs.com/microservices/basics#request-response) + * + * @publicApi + */ +export declare function Controller(): ClassDecorator; +/** + * Decorator that marks a class as a Nest controller that can receive inbound + * requests and produce responses. + * + * An HTTP Controller responds to inbound HTTP Requests and produces HTTP Responses. + * It defines a class that provides the context for one or more related route + * handlers that correspond to HTTP request methods and associated routes + * for example `GET /api/profile`, `POST /users/resume`. + * + * A Microservice Controller responds to requests as well as events, running over + * a variety of transports [(read more here)](https://docs.nestjs.com/microservices/basics). + * It defines a class that provides a context for one or more message or event + * handlers. + * + * @param {string|Array} prefix string that defines a `route path prefix`. The prefix + * is pre-pended to the path specified in any request decorator in the class. + * + * @see [Routing](https://docs.nestjs.com/controllers#routing) + * @see [Controllers](https://docs.nestjs.com/controllers) + * @see [Microservices](https://docs.nestjs.com/microservices/basics#request-response) + * + * @publicApi + */ +export declare function Controller(prefix: string | string[]): ClassDecorator; +/** + * Decorator that marks a class as a Nest controller that can receive inbound + * requests and produce responses. + * + * An HTTP Controller responds to inbound HTTP Requests and produces HTTP Responses. + * It defines a class that provides the context for one or more related route + * handlers that correspond to HTTP request methods and associated routes + * for example `GET /api/profile`, `POST /users/resume`. + * + * A Microservice Controller responds to requests as well as events, running over + * a variety of transports [(read more here)](https://docs.nestjs.com/microservices/basics). + * It defines a class that provides a context for one or more message or event + * handlers. + * + * @param {object} options configuration object specifying: + * + * - `scope` - symbol that determines the lifetime of a Controller instance. + * [See Scope](https://docs.nestjs.com/fundamentals/injection-scopes#usage) for + * more details. + * - `prefix` - string that defines a `route path prefix`. The prefix + * is pre-pended to the path specified in any request decorator in the class. + * - `version` - string, array of strings, or Symbol that defines the version + * of all routes in the class. [See Versioning](https://docs.nestjs.com/techniques/versioning) + * for more details. + * + * @see [Routing](https://docs.nestjs.com/controllers#routing) + * @see [Controllers](https://docs.nestjs.com/controllers) + * @see [Microservices](https://docs.nestjs.com/microservices/basics#request-response) + * @see [Versioning](https://docs.nestjs.com/techniques/versioning) + * + * @publicApi + */ +export declare function Controller(options: ControllerOptions): ClassDecorator; diff --git a/node_modules/@nestjs/common/decorators/core/controller.decorator.js b/node_modules/@nestjs/common/decorators/core/controller.decorator.js new file mode 100644 index 0000000000000000000000000000000000000000..0f197e2f6b3c1a9a68821a096812c3a046d6a899 --- /dev/null +++ b/node_modules/@nestjs/common/decorators/core/controller.decorator.js @@ -0,0 +1,61 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Controller = Controller; +const constants_1 = require("../../constants"); +const shared_utils_1 = require("../../utils/shared.utils"); +/** + * Decorator that marks a class as a Nest controller that can receive inbound + * requests and produce responses. + * + * An HTTP Controller responds to inbound HTTP Requests and produces HTTP Responses. + * It defines a class that provides the context for one or more related route + * handlers that correspond to HTTP request methods and associated routes + * for example `GET /api/profile`, `POST /users/resume` + * + * A Microservice Controller responds to requests as well as events, running over + * a variety of transports [(read more here)](https://docs.nestjs.com/microservices/basics). + * It defines a class that provides a context for one or more message or event + * handlers. + * + * @param prefixOrOptions a `route path prefix` or a `ControllerOptions` object. + * A `route path prefix` is pre-pended to the path specified in any request decorator + * in the class. `ControllerOptions` is an options configuration object specifying: + * - `scope` - symbol that determines the lifetime of a Controller instance. + * [See Scope](https://docs.nestjs.com/fundamentals/injection-scopes#usage) for + * more details. + * - `prefix` - string that defines a `route path prefix`. The prefix + * is pre-pended to the path specified in any request decorator in the class. + * - `version` - string, array of strings, or Symbol that defines the version + * of all routes in the class. [See Versioning](https://docs.nestjs.com/techniques/versioning) + * for more details. + * + * @see [Routing](https://docs.nestjs.com/controllers#routing) + * @see [Controllers](https://docs.nestjs.com/controllers) + * @see [Microservices](https://docs.nestjs.com/microservices/basics#request-response) + * @see [Scope](https://docs.nestjs.com/fundamentals/injection-scopes#usage) + * @see [Versioning](https://docs.nestjs.com/techniques/versioning) + * + * @publicApi + */ +function Controller(prefixOrOptions) { + const defaultPath = '/'; + const [path, host, scopeOptions, versionOptions] = (0, shared_utils_1.isUndefined)(prefixOrOptions) + ? [defaultPath, undefined, undefined, undefined] + : (0, shared_utils_1.isString)(prefixOrOptions) || Array.isArray(prefixOrOptions) + ? [prefixOrOptions, undefined, undefined, undefined] + : [ + prefixOrOptions.path || defaultPath, + prefixOrOptions.host, + { scope: prefixOrOptions.scope, durable: prefixOrOptions.durable }, + Array.isArray(prefixOrOptions.version) + ? Array.from(new Set(prefixOrOptions.version)) + : prefixOrOptions.version, + ]; + return (target) => { + Reflect.defineMetadata(constants_1.CONTROLLER_WATERMARK, true, target); + Reflect.defineMetadata(constants_1.PATH_METADATA, path, target); + Reflect.defineMetadata(constants_1.HOST_METADATA, host, target); + Reflect.defineMetadata(constants_1.SCOPE_OPTIONS_METADATA, scopeOptions, target); + Reflect.defineMetadata(constants_1.VERSION_METADATA, versionOptions, target); + }; +} diff --git a/node_modules/@nestjs/common/decorators/core/dependencies.decorator.d.ts b/node_modules/@nestjs/common/decorators/core/dependencies.decorator.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7eceb2327c56caca07e0081374f26a326d94d937 --- /dev/null +++ b/node_modules/@nestjs/common/decorators/core/dependencies.decorator.d.ts @@ -0,0 +1,7 @@ +export declare function flatten = any>(arr: T): T extends Array ? R : never; +/** + * Decorator that sets required dependencies (required with a vanilla JavaScript objects) + * + * @publicApi + */ +export declare const Dependencies: (...dependencies: Array) => ClassDecorator; diff --git a/node_modules/@nestjs/common/decorators/core/dependencies.decorator.js b/node_modules/@nestjs/common/decorators/core/dependencies.decorator.js new file mode 100644 index 0000000000000000000000000000000000000000..b7db72c5e1469101dd8bab24ccc82a628ec35b68 --- /dev/null +++ b/node_modules/@nestjs/common/decorators/core/dependencies.decorator.js @@ -0,0 +1,23 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Dependencies = void 0; +exports.flatten = flatten; +const constants_1 = require("../../constants"); +function flatten(arr) { + const flat = [].concat(...arr); + return flat.some(Array.isArray) + ? flatten(flat) + : flat; +} +/** + * Decorator that sets required dependencies (required with a vanilla JavaScript objects) + * + * @publicApi + */ +const Dependencies = (...dependencies) => { + const flattenDeps = flatten(dependencies); + return (target) => { + Reflect.defineMetadata(constants_1.PARAMTYPES_METADATA, flattenDeps, target); + }; +}; +exports.Dependencies = Dependencies; diff --git a/node_modules/@nestjs/common/decorators/core/exception-filters.decorator.d.ts b/node_modules/@nestjs/common/decorators/core/exception-filters.decorator.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e3fe841539218830eb364a4198faee57bb9f1b91 --- /dev/null +++ b/node_modules/@nestjs/common/decorators/core/exception-filters.decorator.d.ts @@ -0,0 +1,23 @@ +import { ExceptionFilter } from '../../index'; +/** + * Decorator that binds exception filters to the scope of the controller or + * method, depending on its context. + * + * When `@UseFilters` is used at the controller level, the filter will be + * applied to every handler (method) in the controller. + * + * When `@UseFilters` is used at the individual handler level, the filter + * will apply only to that specific method. + * + * @param filters exception filter instance or class, or a list of exception + * filter instances or classes. + * + * @see [Exception filters](https://docs.nestjs.com/exception-filters) + * + * @usageNotes + * Exception filters can also be set up globally for all controllers and routes + * using `app.useGlobalFilters()`. [See here for details](https://docs.nestjs.com/exception-filters#binding-filters) + * + * @publicApi + */ +export declare const UseFilters: (...filters: (ExceptionFilter | Function)[]) => MethodDecorator & ClassDecorator; diff --git a/node_modules/@nestjs/common/decorators/core/exception-filters.decorator.js b/node_modules/@nestjs/common/decorators/core/exception-filters.decorator.js new file mode 100644 index 0000000000000000000000000000000000000000..fcdab56140b13d5e20d46a8547908c039989058b --- /dev/null +++ b/node_modules/@nestjs/common/decorators/core/exception-filters.decorator.js @@ -0,0 +1,43 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.UseFilters = void 0; +const constants_1 = require("../../constants"); +const extend_metadata_util_1 = require("../../utils/extend-metadata.util"); +const shared_utils_1 = require("../../utils/shared.utils"); +const validate_each_util_1 = require("../../utils/validate-each.util"); +/** + * Decorator that binds exception filters to the scope of the controller or + * method, depending on its context. + * + * When `@UseFilters` is used at the controller level, the filter will be + * applied to every handler (method) in the controller. + * + * When `@UseFilters` is used at the individual handler level, the filter + * will apply only to that specific method. + * + * @param filters exception filter instance or class, or a list of exception + * filter instances or classes. + * + * @see [Exception filters](https://docs.nestjs.com/exception-filters) + * + * @usageNotes + * Exception filters can also be set up globally for all controllers and routes + * using `app.useGlobalFilters()`. [See here for details](https://docs.nestjs.com/exception-filters#binding-filters) + * + * @publicApi + */ +const UseFilters = (...filters) => addExceptionFiltersMetadata(...filters); +exports.UseFilters = UseFilters; +function addExceptionFiltersMetadata(...filters) { + return (target, key, descriptor) => { + const isFilterValid = (filter) => filter && ((0, shared_utils_1.isFunction)(filter) || (0, shared_utils_1.isFunction)(filter.catch)); + if (descriptor) { + (0, validate_each_util_1.validateEach)(target.constructor, filters, isFilterValid, '@UseFilters', 'filter'); + (0, extend_metadata_util_1.extendArrayMetadata)(constants_1.EXCEPTION_FILTERS_METADATA, filters, descriptor.value); + return descriptor; + } + (0, validate_each_util_1.validateEach)(target, filters, isFilterValid, '@UseFilters', 'filter'); + (0, extend_metadata_util_1.extendArrayMetadata)(constants_1.EXCEPTION_FILTERS_METADATA, filters, target); + return target; + }; +} diff --git a/node_modules/@nestjs/common/decorators/core/index.d.ts b/node_modules/@nestjs/common/decorators/core/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c68c7744ffe5de74a84f4861ed35e6eac8804959 --- /dev/null +++ b/node_modules/@nestjs/common/decorators/core/index.d.ts @@ -0,0 +1,14 @@ +export * from './bind.decorator'; +export * from './catch.decorator'; +export * from './controller.decorator'; +export * from './dependencies.decorator'; +export * from './exception-filters.decorator'; +export * from './inject.decorator'; +export * from './injectable.decorator'; +export * from './optional.decorator'; +export * from './set-metadata.decorator'; +export * from './use-guards.decorator'; +export * from './use-interceptors.decorator'; +export * from './use-pipes.decorator'; +export * from './apply-decorators'; +export * from './version.decorator'; diff --git a/node_modules/@nestjs/common/decorators/core/index.js b/node_modules/@nestjs/common/decorators/core/index.js new file mode 100644 index 0000000000000000000000000000000000000000..31d8890b97561e31144607162cd4437f113b46d8 --- /dev/null +++ b/node_modules/@nestjs/common/decorators/core/index.js @@ -0,0 +1,17 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = require("tslib"); +tslib_1.__exportStar(require("./bind.decorator"), exports); +tslib_1.__exportStar(require("./catch.decorator"), exports); +tslib_1.__exportStar(require("./controller.decorator"), exports); +tslib_1.__exportStar(require("./dependencies.decorator"), exports); +tslib_1.__exportStar(require("./exception-filters.decorator"), exports); +tslib_1.__exportStar(require("./inject.decorator"), exports); +tslib_1.__exportStar(require("./injectable.decorator"), exports); +tslib_1.__exportStar(require("./optional.decorator"), exports); +tslib_1.__exportStar(require("./set-metadata.decorator"), exports); +tslib_1.__exportStar(require("./use-guards.decorator"), exports); +tslib_1.__exportStar(require("./use-interceptors.decorator"), exports); +tslib_1.__exportStar(require("./use-pipes.decorator"), exports); +tslib_1.__exportStar(require("./apply-decorators"), exports); +tslib_1.__exportStar(require("./version.decorator"), exports); diff --git a/node_modules/@nestjs/common/decorators/core/inject.decorator.d.ts b/node_modules/@nestjs/common/decorators/core/inject.decorator.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..08f472c512bbd7ee14ccee42b39ac93cb88f148b --- /dev/null +++ b/node_modules/@nestjs/common/decorators/core/inject.decorator.d.ts @@ -0,0 +1,31 @@ +import { ForwardReference, InjectionToken } from '../../interfaces'; +/** + * Decorator that marks a constructor parameter as a target for + * [Dependency Injection (DI)](https://docs.nestjs.com/providers#dependency-injection). + * + * Any injected provider must be visible within the module scope (loosely + * speaking, the containing module) of the class it is being injected into. This + * can be done by: + * + * - defining the provider in the same module scope + * - exporting the provider from one module scope and importing that module into the + * module scope of the class being injected into + * - exporting the provider from a module that is marked as global using the + * `@Global()` decorator + * + * #### Injection tokens + * Can be *types* (class names), *strings* or *symbols*. This depends on how the + * provider with which it is associated was defined. Providers defined with the + * `@Injectable()` decorator use the class name. Custom Providers may use strings + * or symbols as the injection token. + * + * @param token lookup key for the provider to be injected (assigned to the constructor + * parameter). + * + * @see [Providers](https://docs.nestjs.com/providers) + * @see [Custom Providers](https://docs.nestjs.com/fundamentals/custom-providers) + * @see [Injection Scopes](https://docs.nestjs.com/fundamentals/injection-scopes) + * + * @publicApi + */ +export declare function Inject(token?: InjectionToken | ForwardReference): PropertyDecorator & ParameterDecorator; diff --git a/node_modules/@nestjs/common/decorators/core/inject.decorator.js b/node_modules/@nestjs/common/decorators/core/inject.decorator.js new file mode 100644 index 0000000000000000000000000000000000000000..c694134ecfda17c6b0f46205ac4ba5fcff3aa327 --- /dev/null +++ b/node_modules/@nestjs/common/decorators/core/inject.decorator.js @@ -0,0 +1,53 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Inject = Inject; +const constants_1 = require("../../constants"); +const shared_utils_1 = require("../../utils/shared.utils"); +/** + * Decorator that marks a constructor parameter as a target for + * [Dependency Injection (DI)](https://docs.nestjs.com/providers#dependency-injection). + * + * Any injected provider must be visible within the module scope (loosely + * speaking, the containing module) of the class it is being injected into. This + * can be done by: + * + * - defining the provider in the same module scope + * - exporting the provider from one module scope and importing that module into the + * module scope of the class being injected into + * - exporting the provider from a module that is marked as global using the + * `@Global()` decorator + * + * #### Injection tokens + * Can be *types* (class names), *strings* or *symbols*. This depends on how the + * provider with which it is associated was defined. Providers defined with the + * `@Injectable()` decorator use the class name. Custom Providers may use strings + * or symbols as the injection token. + * + * @param token lookup key for the provider to be injected (assigned to the constructor + * parameter). + * + * @see [Providers](https://docs.nestjs.com/providers) + * @see [Custom Providers](https://docs.nestjs.com/fundamentals/custom-providers) + * @see [Injection Scopes](https://docs.nestjs.com/fundamentals/injection-scopes) + * + * @publicApi + */ +function Inject(token) { + const injectCallHasArguments = arguments.length > 0; + return (target, key, index) => { + let type = token || Reflect.getMetadata('design:type', target, key); + // Try to infer the token in a constructor-based injection + if (!type && !injectCallHasArguments) { + type = Reflect.getMetadata(constants_1.PARAMTYPES_METADATA, target, key)?.[index]; + } + if (!(0, shared_utils_1.isUndefined)(index)) { + let dependencies = Reflect.getMetadata(constants_1.SELF_DECLARED_DEPS_METADATA, target) || []; + dependencies = [...dependencies, { index, param: type }]; + Reflect.defineMetadata(constants_1.SELF_DECLARED_DEPS_METADATA, dependencies, target); + return; + } + let properties = Reflect.getMetadata(constants_1.PROPERTY_DEPS_METADATA, target.constructor) || []; + properties = [...properties, { key, type }]; + Reflect.defineMetadata(constants_1.PROPERTY_DEPS_METADATA, properties, target.constructor); + }; +} diff --git a/node_modules/@nestjs/common/decorators/core/injectable.decorator.d.ts b/node_modules/@nestjs/common/decorators/core/injectable.decorator.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..793e8f1e8c4f9c72cca3383b1b00feb30ffffe05 --- /dev/null +++ b/node_modules/@nestjs/common/decorators/core/injectable.decorator.d.ts @@ -0,0 +1,43 @@ +import { ScopeOptions } from '../../interfaces/scope-options.interface'; +import { Type } from '../../interfaces/type.interface'; +/** + * Defines the injection scope. + * + * @see [Injection Scopes](https://docs.nestjs.com/fundamentals/injection-scopes) + * + * @publicApi + */ +export type InjectableOptions = ScopeOptions; +/** + * Decorator that marks a class as a [provider](https://docs.nestjs.com/providers). + * Providers can be injected into other classes via constructor parameter injection + * using Nest's built-in [Dependency Injection (DI)](https://docs.nestjs.com/providers#dependency-injection) + * system. + * + * When injecting a provider, it must be visible within the module scope (loosely + * speaking, the containing module) of the class it is being injected into. This + * can be done by: + * + * - defining the provider in the same module scope + * - exporting the provider from one module scope and importing that module into the + * module scope of the class being injected into + * - exporting the provider from a module that is marked as global using the + * `@Global()` decorator + * + * Providers can also be defined in a more explicit and imperative form using + * various [custom provider](https://docs.nestjs.com/fundamentals/custom-providers) techniques that expose + * more capabilities of the DI system. + * + * @param options options specifying scope of injectable + * + * @see [Providers](https://docs.nestjs.com/providers) + * @see [Custom Providers](https://docs.nestjs.com/fundamentals/custom-providers) + * @see [Injection Scopes](https://docs.nestjs.com/fundamentals/injection-scopes) + * + * @publicApi + */ +export declare function Injectable(options?: InjectableOptions): ClassDecorator; +/** + * @publicApi + */ +export declare function mixin(mixinClass: Type): Type; diff --git a/node_modules/@nestjs/common/decorators/core/injectable.decorator.js b/node_modules/@nestjs/common/decorators/core/injectable.decorator.js new file mode 100644 index 0000000000000000000000000000000000000000..cf858bb5a1637ebe8abe261f18fea2ed066c9357 --- /dev/null +++ b/node_modules/@nestjs/common/decorators/core/injectable.decorator.js @@ -0,0 +1,50 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Injectable = Injectable; +exports.mixin = mixin; +const uid_1 = require("uid"); +const constants_1 = require("../../constants"); +/** + * Decorator that marks a class as a [provider](https://docs.nestjs.com/providers). + * Providers can be injected into other classes via constructor parameter injection + * using Nest's built-in [Dependency Injection (DI)](https://docs.nestjs.com/providers#dependency-injection) + * system. + * + * When injecting a provider, it must be visible within the module scope (loosely + * speaking, the containing module) of the class it is being injected into. This + * can be done by: + * + * - defining the provider in the same module scope + * - exporting the provider from one module scope and importing that module into the + * module scope of the class being injected into + * - exporting the provider from a module that is marked as global using the + * `@Global()` decorator + * + * Providers can also be defined in a more explicit and imperative form using + * various [custom provider](https://docs.nestjs.com/fundamentals/custom-providers) techniques that expose + * more capabilities of the DI system. + * + * @param options options specifying scope of injectable + * + * @see [Providers](https://docs.nestjs.com/providers) + * @see [Custom Providers](https://docs.nestjs.com/fundamentals/custom-providers) + * @see [Injection Scopes](https://docs.nestjs.com/fundamentals/injection-scopes) + * + * @publicApi + */ +function Injectable(options) { + return (target) => { + Reflect.defineMetadata(constants_1.INJECTABLE_WATERMARK, true, target); + Reflect.defineMetadata(constants_1.SCOPE_OPTIONS_METADATA, options, target); + }; +} +/** + * @publicApi + */ +function mixin(mixinClass) { + Object.defineProperty(mixinClass, 'name', { + value: (0, uid_1.uid)(21), + }); + Injectable()(mixinClass); + return mixinClass; +} diff --git a/node_modules/@nestjs/common/decorators/core/optional.decorator.d.ts b/node_modules/@nestjs/common/decorators/core/optional.decorator.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c195218e29775555b86576ebbe8aef17a9ed6aa2 --- /dev/null +++ b/node_modules/@nestjs/common/decorators/core/optional.decorator.d.ts @@ -0,0 +1,14 @@ +/** + * Parameter decorator for an injected dependency marking the + * dependency as optional. + * + * For example: + * ```typescript + * constructor(@Optional() @Inject('HTTP_OPTIONS')private readonly httpClient: T) {} + * ``` + * + * @see [Optional providers](https://docs.nestjs.com/providers#optional-providers) + * + * @publicApi + */ +export declare function Optional(): PropertyDecorator & ParameterDecorator; diff --git a/node_modules/@nestjs/common/decorators/core/optional.decorator.js b/node_modules/@nestjs/common/decorators/core/optional.decorator.js new file mode 100644 index 0000000000000000000000000000000000000000..869067d29ebae7971b745ebc0a3f1d92ec6f2801 --- /dev/null +++ b/node_modules/@nestjs/common/decorators/core/optional.decorator.js @@ -0,0 +1,29 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Optional = Optional; +const constants_1 = require("../../constants"); +const shared_utils_1 = require("../../utils/shared.utils"); +/** + * Parameter decorator for an injected dependency marking the + * dependency as optional. + * + * For example: + * ```typescript + * constructor(@Optional() @Inject('HTTP_OPTIONS')private readonly httpClient: T) {} + * ``` + * + * @see [Optional providers](https://docs.nestjs.com/providers#optional-providers) + * + * @publicApi + */ +function Optional() { + return (target, key, index) => { + if (!(0, shared_utils_1.isUndefined)(index)) { + const args = Reflect.getMetadata(constants_1.OPTIONAL_DEPS_METADATA, target) || []; + Reflect.defineMetadata(constants_1.OPTIONAL_DEPS_METADATA, [...args, index], target); + return; + } + const properties = Reflect.getMetadata(constants_1.OPTIONAL_PROPERTY_DEPS_METADATA, target.constructor) || []; + Reflect.defineMetadata(constants_1.OPTIONAL_PROPERTY_DEPS_METADATA, [...properties, key], target.constructor); + }; +} diff --git a/node_modules/@nestjs/common/decorators/core/set-metadata.decorator.d.ts b/node_modules/@nestjs/common/decorators/core/set-metadata.decorator.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e9fe786d9932b89413b0970177f84d80d596f7aa --- /dev/null +++ b/node_modules/@nestjs/common/decorators/core/set-metadata.decorator.d.ts @@ -0,0 +1,20 @@ +export type CustomDecorator = MethodDecorator & ClassDecorator & { + KEY: TKey; +}; +/** + * Decorator that assigns metadata to the class/function using the + * specified `key`. + * + * Requires two parameters: + * - `key` - a value defining the key under which the metadata is stored + * - `value` - metadata to be associated with `key` + * + * This metadata can be reflected using the `Reflector` class. + * + * Example: `@SetMetadata('roles', ['admin'])` + * + * @see [Reflection](https://docs.nestjs.com/fundamentals/execution-context#reflection-and-metadata) + * + * @publicApi + */ +export declare const SetMetadata: (metadataKey: K, metadataValue: V) => CustomDecorator; diff --git a/node_modules/@nestjs/common/decorators/core/set-metadata.decorator.js b/node_modules/@nestjs/common/decorators/core/set-metadata.decorator.js new file mode 100644 index 0000000000000000000000000000000000000000..a426145b8c32689f5198ba17ffde9adc8ae4a237 --- /dev/null +++ b/node_modules/@nestjs/common/decorators/core/set-metadata.decorator.js @@ -0,0 +1,32 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SetMetadata = void 0; +/** + * Decorator that assigns metadata to the class/function using the + * specified `key`. + * + * Requires two parameters: + * - `key` - a value defining the key under which the metadata is stored + * - `value` - metadata to be associated with `key` + * + * This metadata can be reflected using the `Reflector` class. + * + * Example: `@SetMetadata('roles', ['admin'])` + * + * @see [Reflection](https://docs.nestjs.com/fundamentals/execution-context#reflection-and-metadata) + * + * @publicApi + */ +const SetMetadata = (metadataKey, metadataValue) => { + const decoratorFactory = (target, key, descriptor) => { + if (descriptor) { + Reflect.defineMetadata(metadataKey, metadataValue, descriptor.value); + return descriptor; + } + Reflect.defineMetadata(metadataKey, metadataValue, target); + return target; + }; + decoratorFactory.KEY = metadataKey; + return decoratorFactory; +}; +exports.SetMetadata = SetMetadata; diff --git a/node_modules/@nestjs/common/decorators/core/use-guards.decorator.d.ts b/node_modules/@nestjs/common/decorators/core/use-guards.decorator.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..81ae99ca3581cd9983ebe2396612426c0e1ca3d7 --- /dev/null +++ b/node_modules/@nestjs/common/decorators/core/use-guards.decorator.d.ts @@ -0,0 +1,23 @@ +import { CanActivate } from '../../interfaces'; +/** + * Decorator that binds guards to the scope of the controller or method, + * depending on its context. + * + * When `@UseGuards` is used at the controller level, the guard will be + * applied to every handler (method) in the controller. + * + * When `@UseGuards` is used at the individual handler level, the guard + * will apply only to that specific method. + * + * @param guards a single guard instance or class, or a list of guard instances + * or classes. + * + * @see [Guards](https://docs.nestjs.com/guards) + * + * @usageNotes + * Guards can also be set up globally for all controllers and routes + * using `app.useGlobalGuards()`. [See here for details](https://docs.nestjs.com/guards#binding-guards) + * + * @publicApi + */ +export declare function UseGuards(...guards: (CanActivate | Function)[]): MethodDecorator & ClassDecorator; diff --git a/node_modules/@nestjs/common/decorators/core/use-guards.decorator.js b/node_modules/@nestjs/common/decorators/core/use-guards.decorator.js new file mode 100644 index 0000000000000000000000000000000000000000..b8a8f98de43ecdbe3e2972d86a709325b5953c1f --- /dev/null +++ b/node_modules/@nestjs/common/decorators/core/use-guards.decorator.js @@ -0,0 +1,41 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.UseGuards = UseGuards; +const constants_1 = require("../../constants"); +const extend_metadata_util_1 = require("../../utils/extend-metadata.util"); +const shared_utils_1 = require("../../utils/shared.utils"); +const validate_each_util_1 = require("../../utils/validate-each.util"); +/** + * Decorator that binds guards to the scope of the controller or method, + * depending on its context. + * + * When `@UseGuards` is used at the controller level, the guard will be + * applied to every handler (method) in the controller. + * + * When `@UseGuards` is used at the individual handler level, the guard + * will apply only to that specific method. + * + * @param guards a single guard instance or class, or a list of guard instances + * or classes. + * + * @see [Guards](https://docs.nestjs.com/guards) + * + * @usageNotes + * Guards can also be set up globally for all controllers and routes + * using `app.useGlobalGuards()`. [See here for details](https://docs.nestjs.com/guards#binding-guards) + * + * @publicApi + */ +function UseGuards(...guards) { + return (target, key, descriptor) => { + const isGuardValid = (guard) => guard && ((0, shared_utils_1.isFunction)(guard) || (0, shared_utils_1.isFunction)(guard.canActivate)); + if (descriptor) { + (0, validate_each_util_1.validateEach)(target.constructor, guards, isGuardValid, '@UseGuards', 'guard'); + (0, extend_metadata_util_1.extendArrayMetadata)(constants_1.GUARDS_METADATA, guards, descriptor.value); + return descriptor; + } + (0, validate_each_util_1.validateEach)(target, guards, isGuardValid, '@UseGuards', 'guard'); + (0, extend_metadata_util_1.extendArrayMetadata)(constants_1.GUARDS_METADATA, guards, target); + return target; + }; +} diff --git a/node_modules/@nestjs/common/decorators/core/use-interceptors.decorator.d.ts b/node_modules/@nestjs/common/decorators/core/use-interceptors.decorator.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ea9c9a87301c0a2d5e51f9885337b69d2f3d8467 --- /dev/null +++ b/node_modules/@nestjs/common/decorators/core/use-interceptors.decorator.d.ts @@ -0,0 +1,23 @@ +import { NestInterceptor } from '../../interfaces'; +/** + * Decorator that binds interceptors to the scope of the controller or method, + * depending on its context. + * + * When `@UseInterceptors` is used at the controller level, the interceptor will + * be applied to every handler (method) in the controller. + * + * When `@UseInterceptors` is used at the individual handler level, the interceptor + * will apply only to that specific method. + * + * @param interceptors a single interceptor instance or class, or a list of + * interceptor instances or classes. + * + * @see [Interceptors](https://docs.nestjs.com/interceptors) + * + * @usageNotes + * Interceptors can also be set up globally for all controllers and routes + * using `app.useGlobalInterceptors()`. [See here for details](https://docs.nestjs.com/interceptors#binding-interceptors) + * + * @publicApi + */ +export declare function UseInterceptors(...interceptors: (NestInterceptor | Function)[]): MethodDecorator & ClassDecorator; diff --git a/node_modules/@nestjs/common/decorators/core/use-interceptors.decorator.js b/node_modules/@nestjs/common/decorators/core/use-interceptors.decorator.js new file mode 100644 index 0000000000000000000000000000000000000000..d4ff80a6317b959e587abaa8f20329e9329b646d --- /dev/null +++ b/node_modules/@nestjs/common/decorators/core/use-interceptors.decorator.js @@ -0,0 +1,42 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.UseInterceptors = UseInterceptors; +const constants_1 = require("../../constants"); +const extend_metadata_util_1 = require("../../utils/extend-metadata.util"); +const shared_utils_1 = require("../../utils/shared.utils"); +const validate_each_util_1 = require("../../utils/validate-each.util"); +/** + * Decorator that binds interceptors to the scope of the controller or method, + * depending on its context. + * + * When `@UseInterceptors` is used at the controller level, the interceptor will + * be applied to every handler (method) in the controller. + * + * When `@UseInterceptors` is used at the individual handler level, the interceptor + * will apply only to that specific method. + * + * @param interceptors a single interceptor instance or class, or a list of + * interceptor instances or classes. + * + * @see [Interceptors](https://docs.nestjs.com/interceptors) + * + * @usageNotes + * Interceptors can also be set up globally for all controllers and routes + * using `app.useGlobalInterceptors()`. [See here for details](https://docs.nestjs.com/interceptors#binding-interceptors) + * + * @publicApi + */ +function UseInterceptors(...interceptors) { + return (target, key, descriptor) => { + const isInterceptorValid = (interceptor) => interceptor && + ((0, shared_utils_1.isFunction)(interceptor) || (0, shared_utils_1.isFunction)(interceptor.intercept)); + if (descriptor) { + (0, validate_each_util_1.validateEach)(target.constructor, interceptors, isInterceptorValid, '@UseInterceptors', 'interceptor'); + (0, extend_metadata_util_1.extendArrayMetadata)(constants_1.INTERCEPTORS_METADATA, interceptors, descriptor.value); + return descriptor; + } + (0, validate_each_util_1.validateEach)(target, interceptors, isInterceptorValid, '@UseInterceptors', 'interceptor'); + (0, extend_metadata_util_1.extendArrayMetadata)(constants_1.INTERCEPTORS_METADATA, interceptors, target); + return target; + }; +} diff --git a/node_modules/@nestjs/common/decorators/core/use-pipes.decorator.d.ts b/node_modules/@nestjs/common/decorators/core/use-pipes.decorator.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..48459a2926167b9eede4a20f951a17f0e40b91b2 --- /dev/null +++ b/node_modules/@nestjs/common/decorators/core/use-pipes.decorator.d.ts @@ -0,0 +1,23 @@ +import { PipeTransform } from '../../interfaces/index'; +/** + * Decorator that binds pipes to the scope of the controller or method, + * depending on its context. + * + * When `@UsePipes` is used at the controller level, the pipe will be + * applied to every handler (method) in the controller. + * + * When `@UsePipes` is used at the individual handler level, the pipe + * will apply only to that specific method. + * + * @param pipes a single pipe instance or class, or a list of pipe instances or + * classes. + * + * @see [Pipes](https://docs.nestjs.com/pipes) + * + * @usageNotes + * Pipes can also be set up globally for all controllers and routes + * using `app.useGlobalPipes()`. [See here for details](https://docs.nestjs.com/pipes#class-validator) + * + * @publicApi + */ +export declare function UsePipes(...pipes: (PipeTransform | Function)[]): ClassDecorator & MethodDecorator; diff --git a/node_modules/@nestjs/common/decorators/core/use-pipes.decorator.js b/node_modules/@nestjs/common/decorators/core/use-pipes.decorator.js new file mode 100644 index 0000000000000000000000000000000000000000..7b800923240bb188d31b4545a1ebf04b8de3da05 --- /dev/null +++ b/node_modules/@nestjs/common/decorators/core/use-pipes.decorator.js @@ -0,0 +1,41 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.UsePipes = UsePipes; +const constants_1 = require("../../constants"); +const extend_metadata_util_1 = require("../../utils/extend-metadata.util"); +const shared_utils_1 = require("../../utils/shared.utils"); +const validate_each_util_1 = require("../../utils/validate-each.util"); +/** + * Decorator that binds pipes to the scope of the controller or method, + * depending on its context. + * + * When `@UsePipes` is used at the controller level, the pipe will be + * applied to every handler (method) in the controller. + * + * When `@UsePipes` is used at the individual handler level, the pipe + * will apply only to that specific method. + * + * @param pipes a single pipe instance or class, or a list of pipe instances or + * classes. + * + * @see [Pipes](https://docs.nestjs.com/pipes) + * + * @usageNotes + * Pipes can also be set up globally for all controllers and routes + * using `app.useGlobalPipes()`. [See here for details](https://docs.nestjs.com/pipes#class-validator) + * + * @publicApi + */ +function UsePipes(...pipes) { + return (target, key, descriptor) => { + const isPipeValid = (pipe) => pipe && ((0, shared_utils_1.isFunction)(pipe) || (0, shared_utils_1.isFunction)(pipe.transform)); + if (descriptor) { + (0, validate_each_util_1.validateEach)(target.constructor, pipes, isPipeValid, '@UsePipes', 'pipe'); + (0, extend_metadata_util_1.extendArrayMetadata)(constants_1.PIPES_METADATA, pipes, descriptor.value); + return descriptor; + } + (0, validate_each_util_1.validateEach)(target, pipes, isPipeValid, '@UsePipes', 'pipe'); + (0, extend_metadata_util_1.extendArrayMetadata)(constants_1.PIPES_METADATA, pipes, target); + return target; + }; +} diff --git a/node_modules/@nestjs/common/decorators/core/version.decorator.d.ts b/node_modules/@nestjs/common/decorators/core/version.decorator.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..88aa997586823613d1c13c45938b5ff6df8a4f42 --- /dev/null +++ b/node_modules/@nestjs/common/decorators/core/version.decorator.d.ts @@ -0,0 +1,7 @@ +import { VersionValue } from '../../interfaces/version-options.interface'; +/** + * Sets the version of the endpoint to the passed version + * + * @publicApi + */ +export declare function Version(version: VersionValue): MethodDecorator; diff --git a/node_modules/@nestjs/common/decorators/core/version.decorator.js b/node_modules/@nestjs/common/decorators/core/version.decorator.js new file mode 100644 index 0000000000000000000000000000000000000000..85b6c206f36cb35fc1e4d78b085398e8e569a573 --- /dev/null +++ b/node_modules/@nestjs/common/decorators/core/version.decorator.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Version = Version; +const constants_1 = require("../../constants"); +/** + * Sets the version of the endpoint to the passed version + * + * @publicApi + */ +function Version(version) { + if (Array.isArray(version)) { + // Drop duplicated versions + version = Array.from(new Set(version)); + } + return (target, key, descriptor) => { + Reflect.defineMetadata(constants_1.VERSION_METADATA, version, descriptor.value); + return descriptor; + }; +} diff --git a/node_modules/@nestjs/common/decorators/http/create-route-param-metadata.decorator.d.ts b/node_modules/@nestjs/common/decorators/http/create-route-param-metadata.decorator.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..900b08e9ff8c449a2a75af3decdcb56675cd500c --- /dev/null +++ b/node_modules/@nestjs/common/decorators/http/create-route-param-metadata.decorator.d.ts @@ -0,0 +1,13 @@ +import { PipeTransform } from '../../index'; +import { Type } from '../../interfaces'; +import { CustomParamFactory } from '../../interfaces/features/custom-route-param-factory.interface'; +export type ParamDecoratorEnhancer = ParameterDecorator; +/** + * Defines HTTP route param decorator + * + * @param factory + * @param enhancers + * + * @publicApi + */ +export declare function createParamDecorator(factory: CustomParamFactory, enhancers?: ParamDecoratorEnhancer[]): (...dataOrPipes: (Type | PipeTransform | FactoryData)[]) => ParameterDecorator; diff --git a/node_modules/@nestjs/common/decorators/http/create-route-param-metadata.decorator.js b/node_modules/@nestjs/common/decorators/http/create-route-param-metadata.decorator.js new file mode 100644 index 0000000000000000000000000000000000000000..4d640129c0cf20ae2a7a19a58f8032a56d4122a9 --- /dev/null +++ b/node_modules/@nestjs/common/decorators/http/create-route-param-metadata.decorator.js @@ -0,0 +1,32 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createParamDecorator = createParamDecorator; +const uid_1 = require("uid"); +const constants_1 = require("../../constants"); +const assign_custom_metadata_util_1 = require("../../utils/assign-custom-metadata.util"); +const shared_utils_1 = require("../../utils/shared.utils"); +/** + * Defines HTTP route param decorator + * + * @param factory + * @param enhancers + * + * @publicApi + */ +function createParamDecorator(factory, enhancers = []) { + const paramtype = (0, uid_1.uid)(21); + return (data, ...pipes) => (target, key, index) => { + const args = Reflect.getMetadata(constants_1.ROUTE_ARGS_METADATA, target.constructor, key) || + {}; + const isPipe = (pipe) => pipe && + (((0, shared_utils_1.isFunction)(pipe) && + pipe.prototype && + (0, shared_utils_1.isFunction)(pipe.prototype.transform)) || + (0, shared_utils_1.isFunction)(pipe.transform)); + const hasParamData = (0, shared_utils_1.isNil)(data) || !isPipe(data); + const paramData = hasParamData ? data : undefined; + const paramPipes = hasParamData ? pipes : [data, ...pipes]; + Reflect.defineMetadata(constants_1.ROUTE_ARGS_METADATA, (0, assign_custom_metadata_util_1.assignCustomParameterMetadata)(args, paramtype, index, factory, paramData, ...paramPipes), target.constructor, key); + enhancers.forEach(fn => fn(target, key, index)); + }; +} diff --git a/node_modules/@nestjs/common/decorators/http/header.decorator.d.ts b/node_modules/@nestjs/common/decorators/http/header.decorator.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..39510a473a69304b98a2cca8944761aeb0b9739f --- /dev/null +++ b/node_modules/@nestjs/common/decorators/http/header.decorator.d.ts @@ -0,0 +1,15 @@ +/** + * Request method Decorator. Sets a response header. + * + * For example: + * `@Header('Cache-Control', 'none')` + * `@Header('Cache-Control', () => 'none')` + * + * @param name string to be used for header name + * @param value string to be used for header value + * + * @see [Headers](https://docs.nestjs.com/controllers#headers) + * + * @publicApi + */ +export declare function Header(name: string, value: string | (() => string)): MethodDecorator; diff --git a/node_modules/@nestjs/common/decorators/http/header.decorator.js b/node_modules/@nestjs/common/decorators/http/header.decorator.js new file mode 100644 index 0000000000000000000000000000000000000000..7a7e7d7aa6bbc0e58a314b8489b386bfae9f938b --- /dev/null +++ b/node_modules/@nestjs/common/decorators/http/header.decorator.js @@ -0,0 +1,25 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Header = Header; +const constants_1 = require("../../constants"); +const extend_metadata_util_1 = require("../../utils/extend-metadata.util"); +/** + * Request method Decorator. Sets a response header. + * + * For example: + * `@Header('Cache-Control', 'none')` + * `@Header('Cache-Control', () => 'none')` + * + * @param name string to be used for header name + * @param value string to be used for header value + * + * @see [Headers](https://docs.nestjs.com/controllers#headers) + * + * @publicApi + */ +function Header(name, value) { + return (target, key, descriptor) => { + (0, extend_metadata_util_1.extendArrayMetadata)(constants_1.HEADERS_METADATA, [{ name, value }], descriptor.value); + return descriptor; + }; +} diff --git a/node_modules/@nestjs/common/decorators/http/http-code.decorator.d.ts b/node_modules/@nestjs/common/decorators/http/http-code.decorator.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ca98dc9720c715e293b3321449113285d1fca1e9 --- /dev/null +++ b/node_modules/@nestjs/common/decorators/http/http-code.decorator.d.ts @@ -0,0 +1,11 @@ +/** + * Request method Decorator. Defines the HTTP response status code. Overrides + * default status code for the decorated request method. + * + * @param statusCode HTTP response code to be returned by route handler. + * + * @see [Http Status Codes](https://docs.nestjs.com/controllers#status-code) + * + * @publicApi + */ +export declare function HttpCode(statusCode: number): MethodDecorator; diff --git a/node_modules/@nestjs/common/decorators/http/http-code.decorator.js b/node_modules/@nestjs/common/decorators/http/http-code.decorator.js new file mode 100644 index 0000000000000000000000000000000000000000..aae99de6575d0d83ba3b6a47a856b4f77a3673e8 --- /dev/null +++ b/node_modules/@nestjs/common/decorators/http/http-code.decorator.js @@ -0,0 +1,20 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.HttpCode = HttpCode; +const constants_1 = require("../../constants"); +/** + * Request method Decorator. Defines the HTTP response status code. Overrides + * default status code for the decorated request method. + * + * @param statusCode HTTP response code to be returned by route handler. + * + * @see [Http Status Codes](https://docs.nestjs.com/controllers#status-code) + * + * @publicApi + */ +function HttpCode(statusCode) { + return (target, key, descriptor) => { + Reflect.defineMetadata(constants_1.HTTP_CODE_METADATA, statusCode, descriptor.value); + return descriptor; + }; +} diff --git a/node_modules/@nestjs/common/decorators/http/index.d.ts b/node_modules/@nestjs/common/decorators/http/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..39b61bf003bee881d2e12a982526d40c5902eb37 --- /dev/null +++ b/node_modules/@nestjs/common/decorators/http/index.d.ts @@ -0,0 +1,8 @@ +export * from './request-mapping.decorator'; +export * from './route-params.decorator'; +export * from './http-code.decorator'; +export * from './create-route-param-metadata.decorator'; +export * from './render.decorator'; +export * from './header.decorator'; +export * from './redirect.decorator'; +export * from './sse.decorator'; diff --git a/node_modules/@nestjs/common/decorators/http/index.js b/node_modules/@nestjs/common/decorators/http/index.js new file mode 100644 index 0000000000000000000000000000000000000000..f039fc51004905ce69cad2b1f328dfc022d9f52d --- /dev/null +++ b/node_modules/@nestjs/common/decorators/http/index.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = require("tslib"); +tslib_1.__exportStar(require("./request-mapping.decorator"), exports); +tslib_1.__exportStar(require("./route-params.decorator"), exports); +tslib_1.__exportStar(require("./http-code.decorator"), exports); +tslib_1.__exportStar(require("./create-route-param-metadata.decorator"), exports); +tslib_1.__exportStar(require("./render.decorator"), exports); +tslib_1.__exportStar(require("./header.decorator"), exports); +tslib_1.__exportStar(require("./redirect.decorator"), exports); +tslib_1.__exportStar(require("./sse.decorator"), exports); diff --git a/node_modules/@nestjs/common/decorators/http/redirect.decorator.d.ts b/node_modules/@nestjs/common/decorators/http/redirect.decorator.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..be01544fa6bf38b2c5808b2a68b0825648ebf81a --- /dev/null +++ b/node_modules/@nestjs/common/decorators/http/redirect.decorator.d.ts @@ -0,0 +1,6 @@ +/** + * Redirects request to the specified URL. + * + * @publicApi + */ +export declare function Redirect(url?: string, statusCode?: number): MethodDecorator; diff --git a/node_modules/@nestjs/common/decorators/http/redirect.decorator.js b/node_modules/@nestjs/common/decorators/http/redirect.decorator.js new file mode 100644 index 0000000000000000000000000000000000000000..e03cceac39fe0b67b11c0fbef837b71e397e0c75 --- /dev/null +++ b/node_modules/@nestjs/common/decorators/http/redirect.decorator.js @@ -0,0 +1,15 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Redirect = Redirect; +const constants_1 = require("../../constants"); +/** + * Redirects request to the specified URL. + * + * @publicApi + */ +function Redirect(url = '', statusCode) { + return (target, key, descriptor) => { + Reflect.defineMetadata(constants_1.REDIRECT_METADATA, { statusCode, url }, descriptor.value); + return descriptor; + }; +} diff --git a/node_modules/@nestjs/common/decorators/http/render.decorator.d.ts b/node_modules/@nestjs/common/decorators/http/render.decorator.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..294b5e0e7a09d990373b24210b3d373801db9333 --- /dev/null +++ b/node_modules/@nestjs/common/decorators/http/render.decorator.d.ts @@ -0,0 +1,12 @@ +/** + * Route handler method Decorator. Defines a template to be rendered by the controller. + * + * For example: `@Render('index')` + * + * @param template name of the render engine template file + * + * @see [Model-View-Controller](https://docs.nestjs.com/techniques/mvc) + * + * @publicApi + */ +export declare function Render(template: string): MethodDecorator; diff --git a/node_modules/@nestjs/common/decorators/http/render.decorator.js b/node_modules/@nestjs/common/decorators/http/render.decorator.js new file mode 100644 index 0000000000000000000000000000000000000000..5bf80e6c32200d2b9ee037d6e9ca97b8c7c43a52 --- /dev/null +++ b/node_modules/@nestjs/common/decorators/http/render.decorator.js @@ -0,0 +1,21 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Render = Render; +const constants_1 = require("../../constants"); +/** + * Route handler method Decorator. Defines a template to be rendered by the controller. + * + * For example: `@Render('index')` + * + * @param template name of the render engine template file + * + * @see [Model-View-Controller](https://docs.nestjs.com/techniques/mvc) + * + * @publicApi + */ +function Render(template) { + return (target, key, descriptor) => { + Reflect.defineMetadata(constants_1.RENDER_METADATA, template, descriptor.value); + return descriptor; + }; +} diff --git a/node_modules/@nestjs/common/decorators/http/request-mapping.decorator.d.ts b/node_modules/@nestjs/common/decorators/http/request-mapping.decorator.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..287f5778bd7881d57203bbc9f05ed3e523f86b98 --- /dev/null +++ b/node_modules/@nestjs/common/decorators/http/request-mapping.decorator.d.ts @@ -0,0 +1,134 @@ +import { RequestMethod } from '../../enums/request-method.enum'; +export interface RequestMappingMetadata { + path?: string | string[]; + method?: RequestMethod; +} +export declare const RequestMapping: (metadata?: RequestMappingMetadata) => MethodDecorator; +/** + * Route handler (method) Decorator. Routes HTTP POST requests to the specified path. + * + * @see [Routing](https://docs.nestjs.com/controllers#routing) + * + * @publicApi + */ +export declare const Post: (path?: string | string[]) => MethodDecorator; +/** + * Route handler (method) Decorator. Routes HTTP GET requests to the specified path. + * + * @see [Routing](https://docs.nestjs.com/controllers#routing) + * + * @publicApi + */ +export declare const Get: (path?: string | string[]) => MethodDecorator; +/** + * Route handler (method) Decorator. Routes HTTP DELETE requests to the specified path. + * + * @see [Routing](https://docs.nestjs.com/controllers#routing) + * + * @publicApi + */ +export declare const Delete: (path?: string | string[]) => MethodDecorator; +/** + * Route handler (method) Decorator. Routes HTTP PUT requests to the specified path. + * + * @see [Routing](https://docs.nestjs.com/controllers#routing) + * + * @publicApi + */ +export declare const Put: (path?: string | string[]) => MethodDecorator; +/** + * Route handler (method) Decorator. Routes HTTP PATCH requests to the specified path. + * + * @see [Routing](https://docs.nestjs.com/controllers#routing) + * + * @publicApi + */ +export declare const Patch: (path?: string | string[]) => MethodDecorator; +/** + * Route handler (method) Decorator. Routes HTTP OPTIONS requests to the specified path. + * + * @see [Routing](https://docs.nestjs.com/controllers#routing) + * + * @publicApi + */ +export declare const Options: (path?: string | string[]) => MethodDecorator; +/** + * Route handler (method) Decorator. Routes HTTP HEAD requests to the specified path. + * + * @see [Routing](https://docs.nestjs.com/controllers#routing) + * + * @publicApi + */ +export declare const Head: (path?: string | string[]) => MethodDecorator; +/** + * Route handler (method) Decorator. Routes all HTTP requests to the specified path. + * + * @see [Routing](https://docs.nestjs.com/controllers#routing) + * + * @publicApi + */ +export declare const All: (path?: string | string[]) => MethodDecorator; +/** + * Route handler (method) Decorator. Routes HTTP SEARCH requests to the specified path. + * + * @see [Routing](https://docs.nestjs.com/controllers#routing) + * + * @publicApi + */ +export declare const Search: (path?: string | string[]) => MethodDecorator; +/** + * Route handler (method) Decorator. Routes Webdav PROPFIND requests to the specified path. + * + * @see [Routing](https://docs.nestjs.com/controllers#routing) + * + * @publicApi + */ +export declare const Propfind: (path?: string | string[]) => MethodDecorator; +/** + * Route handler (method) Decorator. Routes Webdav PROPPATCH requests to the specified path. + * + * @see [Routing](https://docs.nestjs.com/controllers#routing) + * + * @publicApi + */ +export declare const Proppatch: (path?: string | string[]) => MethodDecorator; +/** + * Route handler (method) Decorator. Routes Webdav MKCOL requests to the specified path. + * + * @see [Routing](https://docs.nestjs.com/controllers#routing) + * + * @publicApi + */ +export declare const Mkcol: (path?: string | string[]) => MethodDecorator; +/** + * Route handler (method) Decorator. Routes Webdav COPY requests to the specified path. + * + * @see [Routing](https://docs.nestjs.com/controllers#routing) + * + * @publicApi + */ +export declare const Copy: (path?: string | string[]) => MethodDecorator; +/** + * Route handler (method) Decorator. Routes Webdav MOVE requests to the specified path. + * + * @see [Routing](https://docs.nestjs.com/controllers#routing) + * + * @publicApi + */ +export declare const Move: (path?: string | string[]) => MethodDecorator; +/** + * Route handler (method) Decorator. Routes Webdav LOCK requests to the specified path. + * + * @see [Routing](https://docs.nestjs.com/controllers#routing) + * + * @publicApi + */ +export declare const Lock: (path?: string | string[]) => MethodDecorator; +/** + * Route handler (method) Decorator. Routes Webdav UNLOCK requests to the specified path. + * + * @see [Routing](https://docs.nestjs.com/controllers#routing) + * + * @publicApi + */ +export declare const Unlock: (path?: string | string[]) => MethodDecorator; diff --git a/node_modules/@nestjs/common/decorators/http/request-mapping.decorator.js b/node_modules/@nestjs/common/decorators/http/request-mapping.decorator.js new file mode 100644 index 0000000000000000000000000000000000000000..cd55a034a169660626bc2dc6d8c6c04fdbbbc063 --- /dev/null +++ b/node_modules/@nestjs/common/decorators/http/request-mapping.decorator.js @@ -0,0 +1,154 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Unlock = exports.Lock = exports.Move = exports.Copy = exports.Mkcol = exports.Proppatch = exports.Propfind = exports.Search = exports.All = exports.Head = exports.Options = exports.Patch = exports.Put = exports.Delete = exports.Get = exports.Post = exports.RequestMapping = void 0; +const constants_1 = require("../../constants"); +const request_method_enum_1 = require("../../enums/request-method.enum"); +const defaultMetadata = { + [constants_1.PATH_METADATA]: '/', + [constants_1.METHOD_METADATA]: request_method_enum_1.RequestMethod.GET, +}; +const RequestMapping = (metadata = defaultMetadata) => { + const pathMetadata = metadata[constants_1.PATH_METADATA]; + const path = pathMetadata && pathMetadata.length ? pathMetadata : '/'; + const requestMethod = metadata[constants_1.METHOD_METADATA] || request_method_enum_1.RequestMethod.GET; + return (target, key, descriptor) => { + Reflect.defineMetadata(constants_1.PATH_METADATA, path, descriptor.value); + Reflect.defineMetadata(constants_1.METHOD_METADATA, requestMethod, descriptor.value); + return descriptor; + }; +}; +exports.RequestMapping = RequestMapping; +const createMappingDecorator = (method) => (path) => { + return (0, exports.RequestMapping)({ + [constants_1.PATH_METADATA]: path, + [constants_1.METHOD_METADATA]: method, + }); +}; +/** + * Route handler (method) Decorator. Routes HTTP POST requests to the specified path. + * + * @see [Routing](https://docs.nestjs.com/controllers#routing) + * + * @publicApi + */ +exports.Post = createMappingDecorator(request_method_enum_1.RequestMethod.POST); +/** + * Route handler (method) Decorator. Routes HTTP GET requests to the specified path. + * + * @see [Routing](https://docs.nestjs.com/controllers#routing) + * + * @publicApi + */ +exports.Get = createMappingDecorator(request_method_enum_1.RequestMethod.GET); +/** + * Route handler (method) Decorator. Routes HTTP DELETE requests to the specified path. + * + * @see [Routing](https://docs.nestjs.com/controllers#routing) + * + * @publicApi + */ +exports.Delete = createMappingDecorator(request_method_enum_1.RequestMethod.DELETE); +/** + * Route handler (method) Decorator. Routes HTTP PUT requests to the specified path. + * + * @see [Routing](https://docs.nestjs.com/controllers#routing) + * + * @publicApi + */ +exports.Put = createMappingDecorator(request_method_enum_1.RequestMethod.PUT); +/** + * Route handler (method) Decorator. Routes HTTP PATCH requests to the specified path. + * + * @see [Routing](https://docs.nestjs.com/controllers#routing) + * + * @publicApi + */ +exports.Patch = createMappingDecorator(request_method_enum_1.RequestMethod.PATCH); +/** + * Route handler (method) Decorator. Routes HTTP OPTIONS requests to the specified path. + * + * @see [Routing](https://docs.nestjs.com/controllers#routing) + * + * @publicApi + */ +exports.Options = createMappingDecorator(request_method_enum_1.RequestMethod.OPTIONS); +/** + * Route handler (method) Decorator. Routes HTTP HEAD requests to the specified path. + * + * @see [Routing](https://docs.nestjs.com/controllers#routing) + * + * @publicApi + */ +exports.Head = createMappingDecorator(request_method_enum_1.RequestMethod.HEAD); +/** + * Route handler (method) Decorator. Routes all HTTP requests to the specified path. + * + * @see [Routing](https://docs.nestjs.com/controllers#routing) + * + * @publicApi + */ +exports.All = createMappingDecorator(request_method_enum_1.RequestMethod.ALL); +/** + * Route handler (method) Decorator. Routes HTTP SEARCH requests to the specified path. + * + * @see [Routing](https://docs.nestjs.com/controllers#routing) + * + * @publicApi + */ +exports.Search = createMappingDecorator(request_method_enum_1.RequestMethod.SEARCH); +/** + * Route handler (method) Decorator. Routes Webdav PROPFIND requests to the specified path. + * + * @see [Routing](https://docs.nestjs.com/controllers#routing) + * + * @publicApi + */ +exports.Propfind = createMappingDecorator(request_method_enum_1.RequestMethod.PROPFIND); +/** + * Route handler (method) Decorator. Routes Webdav PROPPATCH requests to the specified path. + * + * @see [Routing](https://docs.nestjs.com/controllers#routing) + * + * @publicApi + */ +exports.Proppatch = createMappingDecorator(request_method_enum_1.RequestMethod.PROPPATCH); +/** + * Route handler (method) Decorator. Routes Webdav MKCOL requests to the specified path. + * + * @see [Routing](https://docs.nestjs.com/controllers#routing) + * + * @publicApi + */ +exports.Mkcol = createMappingDecorator(request_method_enum_1.RequestMethod.MKCOL); +/** + * Route handler (method) Decorator. Routes Webdav COPY requests to the specified path. + * + * @see [Routing](https://docs.nestjs.com/controllers#routing) + * + * @publicApi + */ +exports.Copy = createMappingDecorator(request_method_enum_1.RequestMethod.COPY); +/** + * Route handler (method) Decorator. Routes Webdav MOVE requests to the specified path. + * + * @see [Routing](https://docs.nestjs.com/controllers#routing) + * + * @publicApi + */ +exports.Move = createMappingDecorator(request_method_enum_1.RequestMethod.MOVE); +/** + * Route handler (method) Decorator. Routes Webdav LOCK requests to the specified path. + * + * @see [Routing](https://docs.nestjs.com/controllers#routing) + * + * @publicApi + */ +exports.Lock = createMappingDecorator(request_method_enum_1.RequestMethod.LOCK); +/** + * Route handler (method) Decorator. Routes Webdav UNLOCK requests to the specified path. + * + * @see [Routing](https://docs.nestjs.com/controllers#routing) + * + * @publicApi + */ +exports.Unlock = createMappingDecorator(request_method_enum_1.RequestMethod.UNLOCK); diff --git a/node_modules/@nestjs/common/decorators/http/route-params.decorator.d.ts b/node_modules/@nestjs/common/decorators/http/route-params.decorator.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..644c15c0372708b773a52ba540d15a0f3d894ee5 --- /dev/null +++ b/node_modules/@nestjs/common/decorators/http/route-params.decorator.d.ts @@ -0,0 +1,471 @@ +import { PipeTransform } from '../../index'; +import { Type } from '../../interfaces'; +/** + * The `@Response()`/`@Res` parameter decorator options. + */ +export interface ResponseDecoratorOptions { + /** + * Determines whether the response will be sent manually within the route handler, + * with the use of native response handling methods exposed by the platform-specific response object, + * or if it should passthrough Nest response processing pipeline. + * + * @default false + */ + passthrough: boolean; +} +export type ParamData = object | string | number; +export interface RouteParamMetadata { + index: number; + data?: ParamData; +} +export declare function assignMetadata(args: TArgs, paramtype: TParamtype, index: number, data?: ParamData, ...pipes: (Type | PipeTransform)[]): TArgs & { + [x: string]: { + index: number; + data: ParamData | undefined; + pipes: (PipeTransform | Type>)[]; + }; +}; +/** + * Route handler parameter decorator. Extracts the `Request` + * object from the underlying platform and populates the decorated + * parameter with the value of `Request`. + * + * Example: `logout(@Request() req)` + * + * @see [Request object](https://docs.nestjs.com/controllers#request-object) + * + * @publicApi + */ +export declare const Request: () => ParameterDecorator; +/** + * Route handler parameter decorator. Extracts the `Response` + * object from the underlying platform and populates the decorated + * parameter with the value of `Response`. + * + * Example: `logout(@Response() res)` + * + * @publicApi + */ +export declare const Response: (options?: ResponseDecoratorOptions) => ParameterDecorator; +/** + * Route handler parameter decorator. Extracts reference to the `Next` function + * from the underlying platform and populates the decorated + * parameter with the value of `Next`. + * + * @publicApi + */ +export declare const Next: () => ParameterDecorator; +/** + * Route handler parameter decorator. Extracts the `Ip` property + * from the `req` object and populates the decorated + * parameter with the value of `ip`. + * + * @see [Request object](https://docs.nestjs.com/controllers#request-object) + * + * @publicApi + */ +export declare const Ip: () => ParameterDecorator; +/** + * Route handler parameter decorator. Extracts the `Session` object + * from the underlying platform and populates the decorated + * parameter with the value of `Session`. + * + * @see [Request object](https://docs.nestjs.com/controllers#request-object) + * + * @publicApi + */ +export declare const Session: () => ParameterDecorator; +/** + * Route handler parameter decorator. Extracts the `file` object + * and populates the decorated parameter with the value of `file`. + * Used in conjunction with + * [multer middleware](https://github.com/expressjs/multer) for Express-based applications. + * + * For example: + * ```typescript + * uploadFile(@UploadedFile() file) { + * console.log(file); + * } + * ``` + * @see [Request object](https://docs.nestjs.com/techniques/file-upload) + * + * @publicApi + */ +export declare function UploadedFile(): ParameterDecorator; +/** + * Route handler parameter decorator. Extracts the `file` object + * and populates the decorated parameter with the value of `file`. + * Used in conjunction with + * [multer middleware](https://github.com/expressjs/multer) for Express-based applications. + * + * For example: + * ```typescript + * uploadFile(@UploadedFile() file) { + * console.log(file); + * } + * ``` + * @see [Request object](https://docs.nestjs.com/techniques/file-upload) + * + * @publicApi + */ +export declare function UploadedFile(...pipes: (Type | PipeTransform)[]): ParameterDecorator; +/** + * Route handler parameter decorator. Extracts the `file` object + * and populates the decorated parameter with the value of `file`. + * Used in conjunction with + * [multer middleware](https://github.com/expressjs/multer) for Express-based applications. + * + * For example: + * ```typescript + * uploadFile(@UploadedFile() file) { + * console.log(file); + * } + * ``` + * @see [Request object](https://docs.nestjs.com/techniques/file-upload) + * + * @publicApi + */ +export declare function UploadedFile(fileKey?: string, ...pipes: (Type | PipeTransform)[]): ParameterDecorator; +/** + * Route handler parameter decorator. Extracts the `files` object + * and populates the decorated parameter with the value of `files`. + * Used in conjunction with + * [multer middleware](https://github.com/expressjs/multer) for Express-based applications. + * + * For example: + * ```typescript + * uploadFile(@UploadedFiles() files) { + * console.log(files); + * } + * ``` + * @see [Request object](https://docs.nestjs.com/techniques/file-upload) + * + * @publicApi + */ +export declare function UploadedFiles(): ParameterDecorator; +/** + * Route handler parameter decorator. Extracts the `files` object + * and populates the decorated parameter with the value of `files`. + * Used in conjunction with + * [multer middleware](https://github.com/expressjs/multer) for Express-based applications. + * + * For example: + * ```typescript + * uploadFile(@UploadedFiles() files) { + * console.log(files); + * } + * ``` + * @see [Request object](https://docs.nestjs.com/techniques/file-upload) + * + * @publicApi + */ +export declare function UploadedFiles(...pipes: (Type | PipeTransform)[]): ParameterDecorator; +/** + * Route handler parameter decorator. Extracts the `headers` + * property from the `req` object and populates the decorated + * parameter with the value of `headers`. + * + * For example: `async update(@Headers('Cache-Control') cacheControl: string)` + * + * @param property name of single header property to extract. + * + * @see [Request object](https://docs.nestjs.com/controllers#request-object) + * + * @publicApi + */ +export declare const Headers: (property?: string) => ParameterDecorator; +/** + * Route handler parameter decorator. Extracts the `query` + * property from the `req` object and populates the decorated + * parameter with the value of `query`. May also apply pipes to the bound + * query parameter. + * + * For example: + * ```typescript + * async find(@Query('user') user: string) + * ``` + * + * @param property name of single property to extract from the `query` object + * @param pipes one or more pipes to apply to the bound query parameter + * + * @see [Request object](https://docs.nestjs.com/controllers#request-object) + * + * @publicApi + */ +export declare function Query(): ParameterDecorator; +/** + * Route handler parameter decorator. Extracts the `query` + * property from the `req` object and populates the decorated + * parameter with the value of `query`. May also apply pipes to the bound + * query parameter. + * + * For example: + * ```typescript + * async find(@Query('user') user: string) + * ``` + * + * @param property name of single property to extract from the `query` object + * @param pipes one or more pipes to apply to the bound query parameter + * + * @see [Request object](https://docs.nestjs.com/controllers#request-object) + * + * @publicApi + */ +export declare function Query(...pipes: (Type | PipeTransform)[]): ParameterDecorator; +/** + * Route handler parameter decorator. Extracts the `query` + * property from the `req` object and populates the decorated + * parameter with the value of `query`. May also apply pipes to the bound + * query parameter. + * + * For example: + * ```typescript + * async find(@Query('user') user: string) + * ``` + * + * @param property name of single property to extract from the `query` object + * @param pipes one or more pipes to apply to the bound query parameter + * + * @see [Request object](https://docs.nestjs.com/controllers#request-object) + * + * @publicApi + */ +export declare function Query(property: string, ...pipes: (Type | PipeTransform)[]): ParameterDecorator; +/** + * Route handler parameter decorator. Extracts the entire `body` + * object from the `req` object and populates the decorated + * parameter with the value of `body`. + * + * For example: + * ```typescript + * async create(@Body() createDto: CreateCatDto) + * ``` + * + * @see [Request object](https://docs.nestjs.com/controllers#request-object) + * + * @publicApi + */ +export declare function Body(): ParameterDecorator; +/** + * Route handler parameter decorator. Extracts the entire `body` + * object from the `req` object and populates the decorated + * parameter with the value of `body`. Also applies the specified + * pipes to that parameter. + * + * For example: + * ```typescript + * async create(@Body(new ValidationPipe()) createDto: CreateCatDto) + * ``` + * + * @param pipes one or more pipes - either instances or classes - to apply to + * the bound body parameter. + * + * @see [Request object](https://docs.nestjs.com/controllers#request-object) + * @see [Working with pipes](https://docs.nestjs.com/custom-decorators#working-with-pipes) + * + * @publicApi + */ +export declare function Body(...pipes: (Type | PipeTransform)[]): ParameterDecorator; +/** + * Route handler parameter decorator. Extracts a single property from + * the `body` object property of the `req` object and populates the decorated + * parameter with the value of that property. Also applies pipes to the bound + * body parameter. + * + * For example: + * ```typescript + * async create(@Body('role', new ValidationPipe()) role: string) + * ``` + * + * @param property name of single property to extract from the `body` object + * @param pipes one or more pipes - either instances or classes - to apply to + * the bound body parameter. + * + * @see [Request object](https://docs.nestjs.com/controllers#request-object) + * @see [Working with pipes](https://docs.nestjs.com/custom-decorators#working-with-pipes) + * + * @publicApi + */ +export declare function Body(property: string, ...pipes: (Type | PipeTransform)[]): ParameterDecorator; +/** + * Route handler parameter decorator. Extracts the `rawBody` Buffer + * property from the `req` object and populates the decorated parameter with that value. + * + * For example: + * ```typescript + * async create(@RawBody() rawBody: Buffer | undefined) + * ``` + * + * @see [Request object](https://docs.nestjs.com/controllers#request-object) + * @see [Raw body](https://docs.nestjs.com/faq/raw-body) + * + * @publicApi + */ +export declare function RawBody(): ParameterDecorator; +/** + * Route handler parameter decorator. Extracts the `rawBody` Buffer + * property from the `req` object and populates the decorated parameter with that value. + * Also applies pipes to the bound rawBody parameter. + * + * For example: + * ```typescript + * async create(@RawBody(new ValidationPipe()) rawBody: Buffer) + * ``` + * + * @param pipes one or more pipes - either instances or classes - to apply to + * the bound body parameter. + * + * @see [Request object](https://docs.nestjs.com/controllers#request-object) + * @see [Raw body](https://docs.nestjs.com/faq/raw-body) + * @see [Working with pipes](https://docs.nestjs.com/custom-decorators#working-with-pipes) + * + * @publicApi + */ +export declare function RawBody(...pipes: (Type> | PipeTransform)[]): ParameterDecorator; +/** + * Route handler parameter decorator. Extracts the `params` + * property from the `req` object and populates the decorated + * parameter with the value of `params`. May also apply pipes to the bound + * parameter. + * + * For example, extracting all params: + * ```typescript + * findOne(@Param() params: string[]) + * ``` + * + * For example, extracting a single param: + * ```typescript + * findOne(@Param('id') id: string) + * ``` + * @param property name of single property to extract from the `req` object + * @param pipes one or more pipes - either instances or classes - to apply to + * the bound parameter. + * + * @see [Request object](https://docs.nestjs.com/controllers#request-object) + * @see [Working with pipes](https://docs.nestjs.com/custom-decorators#working-with-pipes) + * + * @publicApi + */ +export declare function Param(): ParameterDecorator; +/** + * Route handler parameter decorator. Extracts the `params` + * property from the `req` object and populates the decorated + * parameter with the value of `params`. May also apply pipes to the bound + * parameter. + * + * For example, extracting all params: + * ```typescript + * findOne(@Param() params: string[]) + * ``` + * + * For example, extracting a single param: + * ```typescript + * findOne(@Param('id') id: string) + * ``` + * @param property name of single property to extract from the `req` object + * @param pipes one or more pipes - either instances or classes - to apply to + * the bound parameter. + * + * @see [Request object](https://docs.nestjs.com/controllers#request-object) + * @see [Working with pipes](https://docs.nestjs.com/custom-decorators#working-with-pipes) + * + * @publicApi + */ +export declare function Param(...pipes: (Type | PipeTransform)[]): ParameterDecorator; +/** + * Route handler parameter decorator. Extracts the `params` + * property from the `req` object and populates the decorated + * parameter with the value of `params`. May also apply pipes to the bound + * parameter. + * + * For example, extracting all params: + * ```typescript + * findOne(@Param() params: string[]) + * ``` + * + * For example, extracting a single param: + * ```typescript + * findOne(@Param('id') id: string) + * ``` + * @param property name of single property to extract from the `req` object + * @param pipes one or more pipes - either instances or classes - to apply to + * the bound parameter. + * + * @see [Request object](https://docs.nestjs.com/controllers#request-object) + * @see [Working with pipes](https://docs.nestjs.com/custom-decorators#working-with-pipes) + * + * @publicApi + */ +export declare function Param(property: string, ...pipes: (Type | PipeTransform)[]): ParameterDecorator; +/** + * Route handler parameter decorator. Extracts the `hosts` + * property from the `req` object and populates the decorated + * parameter with the value of `hosts`. May also apply pipes to the bound + * parameter. + * + * For example, extracting all params: + * ```typescript + * findOne(@HostParam() params: string[]) + * ``` + * + * For example, extracting a single param: + * ```typescript + * findOne(@HostParam('id') id: string) + * ``` + * @param property name of single property to extract from the `req` object + * + * @see [Request object](https://docs.nestjs.com/controllers#request-object) + * + * @publicApi + */ +export declare function HostParam(): ParameterDecorator; +/** + * Route handler parameter decorator. Extracts the `hosts` + * property from the `req` object and populates the decorated + * parameter with the value of `hosts`. May also apply pipes to the bound + * parameter. + * + * For example, extracting all params: + * ```typescript + * findOne(@HostParam() params: string[]) + * ``` + * + * For example, extracting a single param: + * ```typescript + * findOne(@HostParam('id') id: string) + * ``` + * @param property name of single property to extract from the `req` object + * + * @see [Request object](https://docs.nestjs.com/controllers#request-object) + * + * @publicApi + */ +export declare function HostParam(property: string): ParameterDecorator; +/** + * Route handler parameter decorator. Extracts the `Request` + * object from the underlying platform and populates the decorated + * parameter with the value of `Request`. + * + * Alias for @Request(). + * + * Example: `logout(@Req() req)` + * + * @see [Request object](https://docs.nestjs.com/controllers#request-object) + * + * @publicApi + */ +export declare const Req: () => ParameterDecorator; +/** + * Route handler parameter decorator. Extracts the `Response` + * object from the underlying platform and populates the decorated + * parameter with the value of `Response`. + * + * Alias for @Response(). + * + * Example: `logout(@Res() res)` + * + * @see [Response object](https://docs.nestjs.com/controllers#response-object) + * + * @publicApi + */ +export declare const Res: (options?: ResponseDecoratorOptions) => ParameterDecorator; diff --git a/node_modules/@nestjs/common/decorators/http/route-params.decorator.js b/node_modules/@nestjs/common/decorators/http/route-params.decorator.js new file mode 100644 index 0000000000000000000000000000000000000000..e612fdd5e88d6de0746f278f222c2eac354e54a2 --- /dev/null +++ b/node_modules/@nestjs/common/decorators/http/route-params.decorator.js @@ -0,0 +1,291 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Res = exports.Req = exports.Headers = exports.Session = exports.Ip = exports.Next = exports.Response = exports.Request = void 0; +exports.assignMetadata = assignMetadata; +exports.UploadedFile = UploadedFile; +exports.UploadedFiles = UploadedFiles; +exports.Query = Query; +exports.Body = Body; +exports.RawBody = RawBody; +exports.Param = Param; +exports.HostParam = HostParam; +const constants_1 = require("../../constants"); +const route_paramtypes_enum_1 = require("../../enums/route-paramtypes.enum"); +const shared_utils_1 = require("../../utils/shared.utils"); +function assignMetadata(args, paramtype, index, data, ...pipes) { + return { + ...args, + [`${paramtype}:${index}`]: { + index, + data, + pipes, + }, + }; +} +function createRouteParamDecorator(paramtype) { + return (data) => (target, key, index) => { + const args = Reflect.getMetadata(constants_1.ROUTE_ARGS_METADATA, target.constructor, key) || + {}; + Reflect.defineMetadata(constants_1.ROUTE_ARGS_METADATA, assignMetadata(args, paramtype, index, data), target.constructor, key); + }; +} +const createPipesRouteParamDecorator = (paramtype) => (data, ...pipes) => (target, key, index) => { + const args = Reflect.getMetadata(constants_1.ROUTE_ARGS_METADATA, target.constructor, key) || {}; + const hasParamData = (0, shared_utils_1.isNil)(data) || (0, shared_utils_1.isString)(data); + const paramData = hasParamData ? data : undefined; + const paramPipes = hasParamData ? pipes : [data, ...pipes]; + Reflect.defineMetadata(constants_1.ROUTE_ARGS_METADATA, assignMetadata(args, paramtype, index, paramData, ...paramPipes), target.constructor, key); +}; +/** + * Route handler parameter decorator. Extracts the `Request` + * object from the underlying platform and populates the decorated + * parameter with the value of `Request`. + * + * Example: `logout(@Request() req)` + * + * @see [Request object](https://docs.nestjs.com/controllers#request-object) + * + * @publicApi + */ +exports.Request = createRouteParamDecorator(route_paramtypes_enum_1.RouteParamtypes.REQUEST); +/** + * Route handler parameter decorator. Extracts the `Response` + * object from the underlying platform and populates the decorated + * parameter with the value of `Response`. + * + * Example: `logout(@Response() res)` + * + * @publicApi + */ +const Response = (options) => (target, key, index) => { + if (options?.passthrough) { + Reflect.defineMetadata(constants_1.RESPONSE_PASSTHROUGH_METADATA, options?.passthrough, target.constructor, key); + } + return createRouteParamDecorator(route_paramtypes_enum_1.RouteParamtypes.RESPONSE)()(target, key, index); +}; +exports.Response = Response; +/** + * Route handler parameter decorator. Extracts reference to the `Next` function + * from the underlying platform and populates the decorated + * parameter with the value of `Next`. + * + * @publicApi + */ +exports.Next = createRouteParamDecorator(route_paramtypes_enum_1.RouteParamtypes.NEXT); +/** + * Route handler parameter decorator. Extracts the `Ip` property + * from the `req` object and populates the decorated + * parameter with the value of `ip`. + * + * @see [Request object](https://docs.nestjs.com/controllers#request-object) + * + * @publicApi + */ +exports.Ip = createRouteParamDecorator(route_paramtypes_enum_1.RouteParamtypes.IP); +/** + * Route handler parameter decorator. Extracts the `Session` object + * from the underlying platform and populates the decorated + * parameter with the value of `Session`. + * + * @see [Request object](https://docs.nestjs.com/controllers#request-object) + * + * @publicApi + */ +exports.Session = createRouteParamDecorator(route_paramtypes_enum_1.RouteParamtypes.SESSION); +/** + * Route handler parameter decorator. Extracts the `file` object + * and populates the decorated parameter with the value of `file`. + * Used in conjunction with + * [multer middleware](https://github.com/expressjs/multer) for Express-based applications. + * + * For example: + * ```typescript + * uploadFile(@UploadedFile() file) { + * console.log(file); + * } + * ``` + * @see [Request object](https://docs.nestjs.com/techniques/file-upload) + * + * @publicApi + */ +function UploadedFile(fileKey, ...pipes) { + return createPipesRouteParamDecorator(route_paramtypes_enum_1.RouteParamtypes.FILE)(fileKey, ...pipes); +} +/** + * Route handler parameter decorator. Extracts the `files` object + * and populates the decorated parameter with the value of `files`. + * Used in conjunction with + * [multer middleware](https://github.com/expressjs/multer) for Express-based applications. + * + * For example: + * ```typescript + * uploadFile(@UploadedFiles() files) { + * console.log(files); + * } + * ``` + * @see [Request object](https://docs.nestjs.com/techniques/file-upload) + * + * @publicApi + */ +function UploadedFiles(...pipes) { + return createPipesRouteParamDecorator(route_paramtypes_enum_1.RouteParamtypes.FILES)(undefined, ...pipes); +} +/** + * Route handler parameter decorator. Extracts the `headers` + * property from the `req` object and populates the decorated + * parameter with the value of `headers`. + * + * For example: `async update(@Headers('Cache-Control') cacheControl: string)` + * + * @param property name of single header property to extract. + * + * @see [Request object](https://docs.nestjs.com/controllers#request-object) + * + * @publicApi + */ +exports.Headers = createRouteParamDecorator(route_paramtypes_enum_1.RouteParamtypes.HEADERS); +/** + * Route handler parameter decorator. Extracts the `query` + * property from the `req` object and populates the decorated + * parameter with the value of `query`. May also apply pipes to the bound + * query parameter. + * + * For example: + * ```typescript + * async find(@Query('user') user: string) + * ``` + * + * @param property name of single property to extract from the `query` object + * @param pipes one or more pipes to apply to the bound query parameter + * + * @see [Request object](https://docs.nestjs.com/controllers#request-object) + * + * @publicApi + */ +function Query(property, ...pipes) { + return createPipesRouteParamDecorator(route_paramtypes_enum_1.RouteParamtypes.QUERY)(property, ...pipes); +} +/** + * Route handler parameter decorator. Extracts the entire `body` object + * property, or optionally a named property of the `body` object, from + * the `req` object and populates the decorated parameter with that value. + * Also applies pipes to the bound body parameter. + * + * For example: + * ```typescript + * async create(@Body('role', new ValidationPipe()) role: string) + * ``` + * + * @param property name of single property to extract from the `body` object + * @param pipes one or more pipes - either instances or classes - to apply to + * the bound body parameter. + * + * @see [Request object](https://docs.nestjs.com/controllers#request-object) + * @see [Working with pipes](https://docs.nestjs.com/custom-decorators#working-with-pipes) + * + * @publicApi + */ +function Body(property, ...pipes) { + return createPipesRouteParamDecorator(route_paramtypes_enum_1.RouteParamtypes.BODY)(property, ...pipes); +} +/** + * Route handler parameter decorator. Extracts the `rawBody` Buffer + * property from the `req` object and populates the decorated parameter with that value. + * Also applies pipes to the bound rawBody parameter. + * + * For example: + * ```typescript + * async create(@RawBody(new ValidationPipe()) rawBody: Buffer) + * ``` + * + * @param pipes one or more pipes - either instances or classes - to apply to + * the bound body parameter. + * + * @see [Request object](https://docs.nestjs.com/controllers#request-object) + * @see [Raw body](https://docs.nestjs.com/faq/raw-body) + * @see [Working with pipes](https://docs.nestjs.com/custom-decorators#working-with-pipes) + * + * @publicApi + */ +function RawBody(...pipes) { + return createPipesRouteParamDecorator(route_paramtypes_enum_1.RouteParamtypes.RAW_BODY)(undefined, ...pipes); +} +/** + * Route handler parameter decorator. Extracts the `params` + * property from the `req` object and populates the decorated + * parameter with the value of `params`. May also apply pipes to the bound + * parameter. + * + * For example, extracting all params: + * ```typescript + * findOne(@Param() params: string[]) + * ``` + * + * For example, extracting a single param: + * ```typescript + * findOne(@Param('id') id: string) + * ``` + * @param property name of single property to extract from the `req` object + * @param pipes one or more pipes - either instances or classes - to apply to + * the bound parameter. + * + * @see [Request object](https://docs.nestjs.com/controllers#request-object) + * @see [Working with pipes](https://docs.nestjs.com/custom-decorators#working-with-pipes) + * + * @publicApi + */ +function Param(property, ...pipes) { + return createPipesRouteParamDecorator(route_paramtypes_enum_1.RouteParamtypes.PARAM)(property, ...pipes); +} +/** + * Route handler parameter decorator. Extracts the `hosts` + * property from the `req` object and populates the decorated + * parameter with the value of `params`. May also apply pipes to the bound + * parameter. + * + * For example, extracting all params: + * ```typescript + * findOne(@HostParam() params: string[]) + * ``` + * + * For example, extracting a single param: + * ```typescript + * findOne(@HostParam('id') id: string) + * ``` + * @param property name of single property to extract from the `req` object + * + * @see [Request object](https://docs.nestjs.com/controllers#request-object) + * + * @publicApi + */ +function HostParam(property) { + return createRouteParamDecorator(route_paramtypes_enum_1.RouteParamtypes.HOST)(property); +} +/** + * Route handler parameter decorator. Extracts the `Request` + * object from the underlying platform and populates the decorated + * parameter with the value of `Request`. + * + * Alias for @Request(). + * + * Example: `logout(@Req() req)` + * + * @see [Request object](https://docs.nestjs.com/controllers#request-object) + * + * @publicApi + */ +exports.Req = exports.Request; +/** + * Route handler parameter decorator. Extracts the `Response` + * object from the underlying platform and populates the decorated + * parameter with the value of `Response`. + * + * Alias for @Response(). + * + * Example: `logout(@Res() res)` + * + * @see [Response object](https://docs.nestjs.com/controllers#response-object) + * + * @publicApi + */ +exports.Res = exports.Response; diff --git a/node_modules/@nestjs/common/decorators/http/sse.decorator.d.ts b/node_modules/@nestjs/common/decorators/http/sse.decorator.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d14b7d8e16e8da45ced8a72e4e7985d7b078315f --- /dev/null +++ b/node_modules/@nestjs/common/decorators/http/sse.decorator.d.ts @@ -0,0 +1,10 @@ +import { METHOD_METADATA } from '../../constants'; +import { RequestMethod } from '../../enums/request-method.enum'; +/** + * Declares this route as a Server-Sent-Events endpoint + * + * @publicApi + */ +export declare function Sse(path?: string, options?: { + [METHOD_METADATA]?: RequestMethod; +}): MethodDecorator; diff --git a/node_modules/@nestjs/common/decorators/http/sse.decorator.js b/node_modules/@nestjs/common/decorators/http/sse.decorator.js new file mode 100644 index 0000000000000000000000000000000000000000..a00d10192a9de37011a55c5b189c51a77d21662a --- /dev/null +++ b/node_modules/@nestjs/common/decorators/http/sse.decorator.js @@ -0,0 +1,21 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Sse = Sse; +const constants_1 = require("../../constants"); +const request_method_enum_1 = require("../../enums/request-method.enum"); +/** + * Declares this route as a Server-Sent-Events endpoint + * + * @publicApi + */ +function Sse(path, options = { + [constants_1.METHOD_METADATA]: request_method_enum_1.RequestMethod.GET, +}) { + return (target, key, descriptor) => { + path = path && path.length ? path : '/'; + Reflect.defineMetadata(constants_1.PATH_METADATA, path, descriptor.value); + Reflect.defineMetadata(constants_1.METHOD_METADATA, options[constants_1.METHOD_METADATA], descriptor.value); + Reflect.defineMetadata(constants_1.SSE_METADATA, true, descriptor.value); + return descriptor; + }; +} diff --git a/node_modules/@nestjs/common/decorators/index.d.ts b/node_modules/@nestjs/common/decorators/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..20ab3a19c416d4a350055f53e1486ffb9e4c17f9 --- /dev/null +++ b/node_modules/@nestjs/common/decorators/index.d.ts @@ -0,0 +1,3 @@ +export * from './core'; +export * from './modules'; +export * from './http'; diff --git a/node_modules/@nestjs/common/decorators/index.js b/node_modules/@nestjs/common/decorators/index.js new file mode 100644 index 0000000000000000000000000000000000000000..3b4d4c16dded4c9c05f2f55f6478f5fcc534537a --- /dev/null +++ b/node_modules/@nestjs/common/decorators/index.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = require("tslib"); +tslib_1.__exportStar(require("./core"), exports); +tslib_1.__exportStar(require("./modules"), exports); +tslib_1.__exportStar(require("./http"), exports); diff --git a/node_modules/@nestjs/common/decorators/modules/global.decorator.d.ts b/node_modules/@nestjs/common/decorators/modules/global.decorator.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3e83727221da0c02a00501da99dfd94a3af779cc --- /dev/null +++ b/node_modules/@nestjs/common/decorators/modules/global.decorator.d.ts @@ -0,0 +1,12 @@ +/** + * Decorator that makes a module global-scoped. + * + * Once imported into any module, a global-scoped module will be visible + * in all modules. Thereafter, modules that wish to inject a service exported + * from a global module do not need to import the provider module. + * + * @see [Global modules](https://docs.nestjs.com/modules#global-modules) + * + * @publicApi + */ +export declare function Global(): ClassDecorator; diff --git a/node_modules/@nestjs/common/decorators/modules/global.decorator.js b/node_modules/@nestjs/common/decorators/modules/global.decorator.js new file mode 100644 index 0000000000000000000000000000000000000000..f3937530916cce31b9519a5ac09144ab5014edbb --- /dev/null +++ b/node_modules/@nestjs/common/decorators/modules/global.decorator.js @@ -0,0 +1,20 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Global = Global; +const constants_1 = require("../../constants"); +/** + * Decorator that makes a module global-scoped. + * + * Once imported into any module, a global-scoped module will be visible + * in all modules. Thereafter, modules that wish to inject a service exported + * from a global module do not need to import the provider module. + * + * @see [Global modules](https://docs.nestjs.com/modules#global-modules) + * + * @publicApi + */ +function Global() { + return (target) => { + Reflect.defineMetadata(constants_1.GLOBAL_MODULE_METADATA, true, target); + }; +} diff --git a/node_modules/@nestjs/common/decorators/modules/index.d.ts b/node_modules/@nestjs/common/decorators/modules/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e1994f74e79b7bc0189c47adba932c1e72b41e72 --- /dev/null +++ b/node_modules/@nestjs/common/decorators/modules/index.d.ts @@ -0,0 +1,2 @@ +export * from './global.decorator'; +export * from './module.decorator'; diff --git a/node_modules/@nestjs/common/decorators/modules/index.js b/node_modules/@nestjs/common/decorators/modules/index.js new file mode 100644 index 0000000000000000000000000000000000000000..3ec12299f2a87ccea2428c55270f9b4f300f9df1 --- /dev/null +++ b/node_modules/@nestjs/common/decorators/modules/index.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = require("tslib"); +tslib_1.__exportStar(require("./global.decorator"), exports); +tslib_1.__exportStar(require("./module.decorator"), exports); diff --git a/node_modules/@nestjs/common/decorators/modules/module.decorator.d.ts b/node_modules/@nestjs/common/decorators/modules/module.decorator.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..11c30aecbabc10c07d0996038b16b3f8da70443e --- /dev/null +++ b/node_modules/@nestjs/common/decorators/modules/module.decorator.d.ts @@ -0,0 +1,16 @@ +import { ModuleMetadata } from '../../interfaces/modules/module-metadata.interface'; +/** + * Decorator that marks a class as a [module](https://docs.nestjs.com/modules). + * + * Modules are used by Nest to organize the application structure into scopes. Controllers + * and Providers are scoped by the module they are declared in. Modules and their + * classes (Controllers and Providers) form a graph that determines how Nest + * performs [Dependency Injection (DI)](https://docs.nestjs.com/providers#dependency-injection). + * + * @param metadata module configuration metadata + * + * @see [Modules](https://docs.nestjs.com/modules) + * + * @publicApi + */ +export declare function Module(metadata: ModuleMetadata): ClassDecorator; diff --git a/node_modules/@nestjs/common/decorators/modules/module.decorator.js b/node_modules/@nestjs/common/decorators/modules/module.decorator.js new file mode 100644 index 0000000000000000000000000000000000000000..bd1d9122949d6c9aa872a653122e5ad32d9ed35c --- /dev/null +++ b/node_modules/@nestjs/common/decorators/modules/module.decorator.js @@ -0,0 +1,29 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Module = Module; +const validate_module_keys_util_1 = require("../../utils/validate-module-keys.util"); +/** + * Decorator that marks a class as a [module](https://docs.nestjs.com/modules). + * + * Modules are used by Nest to organize the application structure into scopes. Controllers + * and Providers are scoped by the module they are declared in. Modules and their + * classes (Controllers and Providers) form a graph that determines how Nest + * performs [Dependency Injection (DI)](https://docs.nestjs.com/providers#dependency-injection). + * + * @param metadata module configuration metadata + * + * @see [Modules](https://docs.nestjs.com/modules) + * + * @publicApi + */ +function Module(metadata) { + const propsKeys = Object.keys(metadata); + (0, validate_module_keys_util_1.validateModuleKeys)(propsKeys); + return (target) => { + for (const property in metadata) { + if (Object.hasOwnProperty.call(metadata, property)) { + Reflect.defineMetadata(property, metadata[property], target); + } + } + }; +} diff --git a/node_modules/@nestjs/common/enums/http-status.enum.d.ts b/node_modules/@nestjs/common/enums/http-status.enum.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5599068302daf0c80d28faefdf3e42ef1d3f8188 --- /dev/null +++ b/node_modules/@nestjs/common/enums/http-status.enum.d.ts @@ -0,0 +1,60 @@ +/** + * @publicApi + */ +export declare enum HttpStatus { + CONTINUE = 100, + SWITCHING_PROTOCOLS = 101, + PROCESSING = 102, + EARLYHINTS = 103, + OK = 200, + CREATED = 201, + ACCEPTED = 202, + NON_AUTHORITATIVE_INFORMATION = 203, + NO_CONTENT = 204, + RESET_CONTENT = 205, + PARTIAL_CONTENT = 206, + MULTI_STATUS = 207, + ALREADY_REPORTED = 208, + CONTENT_DIFFERENT = 210, + AMBIGUOUS = 300, + MOVED_PERMANENTLY = 301, + FOUND = 302, + SEE_OTHER = 303, + NOT_MODIFIED = 304, + TEMPORARY_REDIRECT = 307, + PERMANENT_REDIRECT = 308, + BAD_REQUEST = 400, + UNAUTHORIZED = 401, + PAYMENT_REQUIRED = 402, + FORBIDDEN = 403, + NOT_FOUND = 404, + METHOD_NOT_ALLOWED = 405, + NOT_ACCEPTABLE = 406, + PROXY_AUTHENTICATION_REQUIRED = 407, + REQUEST_TIMEOUT = 408, + CONFLICT = 409, + GONE = 410, + LENGTH_REQUIRED = 411, + PRECONDITION_FAILED = 412, + PAYLOAD_TOO_LARGE = 413, + URI_TOO_LONG = 414, + UNSUPPORTED_MEDIA_TYPE = 415, + REQUESTED_RANGE_NOT_SATISFIABLE = 416, + EXPECTATION_FAILED = 417, + I_AM_A_TEAPOT = 418, + MISDIRECTED = 421, + UNPROCESSABLE_ENTITY = 422, + LOCKED = 423, + FAILED_DEPENDENCY = 424, + PRECONDITION_REQUIRED = 428, + TOO_MANY_REQUESTS = 429, + UNRECOVERABLE_ERROR = 456, + INTERNAL_SERVER_ERROR = 500, + NOT_IMPLEMENTED = 501, + BAD_GATEWAY = 502, + SERVICE_UNAVAILABLE = 503, + GATEWAY_TIMEOUT = 504, + HTTP_VERSION_NOT_SUPPORTED = 505, + INSUFFICIENT_STORAGE = 507, + LOOP_DETECTED = 508 +} diff --git a/node_modules/@nestjs/common/enums/http-status.enum.js b/node_modules/@nestjs/common/enums/http-status.enum.js new file mode 100644 index 0000000000000000000000000000000000000000..5e915298915951d3ed1f858a5d4bf7db5a30f5f0 --- /dev/null +++ b/node_modules/@nestjs/common/enums/http-status.enum.js @@ -0,0 +1,64 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.HttpStatus = void 0; +/** + * @publicApi + */ +var HttpStatus; +(function (HttpStatus) { + HttpStatus[HttpStatus["CONTINUE"] = 100] = "CONTINUE"; + HttpStatus[HttpStatus["SWITCHING_PROTOCOLS"] = 101] = "SWITCHING_PROTOCOLS"; + HttpStatus[HttpStatus["PROCESSING"] = 102] = "PROCESSING"; + HttpStatus[HttpStatus["EARLYHINTS"] = 103] = "EARLYHINTS"; + HttpStatus[HttpStatus["OK"] = 200] = "OK"; + HttpStatus[HttpStatus["CREATED"] = 201] = "CREATED"; + HttpStatus[HttpStatus["ACCEPTED"] = 202] = "ACCEPTED"; + HttpStatus[HttpStatus["NON_AUTHORITATIVE_INFORMATION"] = 203] = "NON_AUTHORITATIVE_INFORMATION"; + HttpStatus[HttpStatus["NO_CONTENT"] = 204] = "NO_CONTENT"; + HttpStatus[HttpStatus["RESET_CONTENT"] = 205] = "RESET_CONTENT"; + HttpStatus[HttpStatus["PARTIAL_CONTENT"] = 206] = "PARTIAL_CONTENT"; + HttpStatus[HttpStatus["MULTI_STATUS"] = 207] = "MULTI_STATUS"; + HttpStatus[HttpStatus["ALREADY_REPORTED"] = 208] = "ALREADY_REPORTED"; + HttpStatus[HttpStatus["CONTENT_DIFFERENT"] = 210] = "CONTENT_DIFFERENT"; + HttpStatus[HttpStatus["AMBIGUOUS"] = 300] = "AMBIGUOUS"; + HttpStatus[HttpStatus["MOVED_PERMANENTLY"] = 301] = "MOVED_PERMANENTLY"; + HttpStatus[HttpStatus["FOUND"] = 302] = "FOUND"; + HttpStatus[HttpStatus["SEE_OTHER"] = 303] = "SEE_OTHER"; + HttpStatus[HttpStatus["NOT_MODIFIED"] = 304] = "NOT_MODIFIED"; + HttpStatus[HttpStatus["TEMPORARY_REDIRECT"] = 307] = "TEMPORARY_REDIRECT"; + HttpStatus[HttpStatus["PERMANENT_REDIRECT"] = 308] = "PERMANENT_REDIRECT"; + HttpStatus[HttpStatus["BAD_REQUEST"] = 400] = "BAD_REQUEST"; + HttpStatus[HttpStatus["UNAUTHORIZED"] = 401] = "UNAUTHORIZED"; + HttpStatus[HttpStatus["PAYMENT_REQUIRED"] = 402] = "PAYMENT_REQUIRED"; + HttpStatus[HttpStatus["FORBIDDEN"] = 403] = "FORBIDDEN"; + HttpStatus[HttpStatus["NOT_FOUND"] = 404] = "NOT_FOUND"; + HttpStatus[HttpStatus["METHOD_NOT_ALLOWED"] = 405] = "METHOD_NOT_ALLOWED"; + HttpStatus[HttpStatus["NOT_ACCEPTABLE"] = 406] = "NOT_ACCEPTABLE"; + HttpStatus[HttpStatus["PROXY_AUTHENTICATION_REQUIRED"] = 407] = "PROXY_AUTHENTICATION_REQUIRED"; + HttpStatus[HttpStatus["REQUEST_TIMEOUT"] = 408] = "REQUEST_TIMEOUT"; + HttpStatus[HttpStatus["CONFLICT"] = 409] = "CONFLICT"; + HttpStatus[HttpStatus["GONE"] = 410] = "GONE"; + HttpStatus[HttpStatus["LENGTH_REQUIRED"] = 411] = "LENGTH_REQUIRED"; + HttpStatus[HttpStatus["PRECONDITION_FAILED"] = 412] = "PRECONDITION_FAILED"; + HttpStatus[HttpStatus["PAYLOAD_TOO_LARGE"] = 413] = "PAYLOAD_TOO_LARGE"; + HttpStatus[HttpStatus["URI_TOO_LONG"] = 414] = "URI_TOO_LONG"; + HttpStatus[HttpStatus["UNSUPPORTED_MEDIA_TYPE"] = 415] = "UNSUPPORTED_MEDIA_TYPE"; + HttpStatus[HttpStatus["REQUESTED_RANGE_NOT_SATISFIABLE"] = 416] = "REQUESTED_RANGE_NOT_SATISFIABLE"; + HttpStatus[HttpStatus["EXPECTATION_FAILED"] = 417] = "EXPECTATION_FAILED"; + HttpStatus[HttpStatus["I_AM_A_TEAPOT"] = 418] = "I_AM_A_TEAPOT"; + HttpStatus[HttpStatus["MISDIRECTED"] = 421] = "MISDIRECTED"; + HttpStatus[HttpStatus["UNPROCESSABLE_ENTITY"] = 422] = "UNPROCESSABLE_ENTITY"; + HttpStatus[HttpStatus["LOCKED"] = 423] = "LOCKED"; + HttpStatus[HttpStatus["FAILED_DEPENDENCY"] = 424] = "FAILED_DEPENDENCY"; + HttpStatus[HttpStatus["PRECONDITION_REQUIRED"] = 428] = "PRECONDITION_REQUIRED"; + HttpStatus[HttpStatus["TOO_MANY_REQUESTS"] = 429] = "TOO_MANY_REQUESTS"; + HttpStatus[HttpStatus["UNRECOVERABLE_ERROR"] = 456] = "UNRECOVERABLE_ERROR"; + HttpStatus[HttpStatus["INTERNAL_SERVER_ERROR"] = 500] = "INTERNAL_SERVER_ERROR"; + HttpStatus[HttpStatus["NOT_IMPLEMENTED"] = 501] = "NOT_IMPLEMENTED"; + HttpStatus[HttpStatus["BAD_GATEWAY"] = 502] = "BAD_GATEWAY"; + HttpStatus[HttpStatus["SERVICE_UNAVAILABLE"] = 503] = "SERVICE_UNAVAILABLE"; + HttpStatus[HttpStatus["GATEWAY_TIMEOUT"] = 504] = "GATEWAY_TIMEOUT"; + HttpStatus[HttpStatus["HTTP_VERSION_NOT_SUPPORTED"] = 505] = "HTTP_VERSION_NOT_SUPPORTED"; + HttpStatus[HttpStatus["INSUFFICIENT_STORAGE"] = 507] = "INSUFFICIENT_STORAGE"; + HttpStatus[HttpStatus["LOOP_DETECTED"] = 508] = "LOOP_DETECTED"; +})(HttpStatus || (exports.HttpStatus = HttpStatus = {})); diff --git a/node_modules/@nestjs/common/enums/index.d.ts b/node_modules/@nestjs/common/enums/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..13ee987c228eea5ae53091f42167fe4815466b5a --- /dev/null +++ b/node_modules/@nestjs/common/enums/index.d.ts @@ -0,0 +1,4 @@ +export * from './request-method.enum'; +export * from './http-status.enum'; +export * from './shutdown-signal.enum'; +export * from './version-type.enum'; diff --git a/node_modules/@nestjs/common/enums/index.js b/node_modules/@nestjs/common/enums/index.js new file mode 100644 index 0000000000000000000000000000000000000000..9b08925562e1b97eadb2016a27792f2761362632 --- /dev/null +++ b/node_modules/@nestjs/common/enums/index.js @@ -0,0 +1,7 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = require("tslib"); +tslib_1.__exportStar(require("./request-method.enum"), exports); +tslib_1.__exportStar(require("./http-status.enum"), exports); +tslib_1.__exportStar(require("./shutdown-signal.enum"), exports); +tslib_1.__exportStar(require("./version-type.enum"), exports); diff --git a/node_modules/@nestjs/common/enums/request-method.enum.d.ts b/node_modules/@nestjs/common/enums/request-method.enum.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cd1c8966b5cd12623c6f2bb18f0a9be89b3b189a --- /dev/null +++ b/node_modules/@nestjs/common/enums/request-method.enum.d.ts @@ -0,0 +1,18 @@ +export declare enum RequestMethod { + GET = 0, + POST = 1, + PUT = 2, + DELETE = 3, + PATCH = 4, + ALL = 5, + OPTIONS = 6, + HEAD = 7, + SEARCH = 8, + PROPFIND = 9, + PROPPATCH = 10, + MKCOL = 11, + COPY = 12, + MOVE = 13, + LOCK = 14, + UNLOCK = 15 +} diff --git a/node_modules/@nestjs/common/enums/request-method.enum.js b/node_modules/@nestjs/common/enums/request-method.enum.js new file mode 100644 index 0000000000000000000000000000000000000000..decba23616554103146bc713b2e8cc3e907320d7 --- /dev/null +++ b/node_modules/@nestjs/common/enums/request-method.enum.js @@ -0,0 +1,22 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.RequestMethod = void 0; +var RequestMethod; +(function (RequestMethod) { + RequestMethod[RequestMethod["GET"] = 0] = "GET"; + RequestMethod[RequestMethod["POST"] = 1] = "POST"; + RequestMethod[RequestMethod["PUT"] = 2] = "PUT"; + RequestMethod[RequestMethod["DELETE"] = 3] = "DELETE"; + RequestMethod[RequestMethod["PATCH"] = 4] = "PATCH"; + RequestMethod[RequestMethod["ALL"] = 5] = "ALL"; + RequestMethod[RequestMethod["OPTIONS"] = 6] = "OPTIONS"; + RequestMethod[RequestMethod["HEAD"] = 7] = "HEAD"; + RequestMethod[RequestMethod["SEARCH"] = 8] = "SEARCH"; + RequestMethod[RequestMethod["PROPFIND"] = 9] = "PROPFIND"; + RequestMethod[RequestMethod["PROPPATCH"] = 10] = "PROPPATCH"; + RequestMethod[RequestMethod["MKCOL"] = 11] = "MKCOL"; + RequestMethod[RequestMethod["COPY"] = 12] = "COPY"; + RequestMethod[RequestMethod["MOVE"] = 13] = "MOVE"; + RequestMethod[RequestMethod["LOCK"] = 14] = "LOCK"; + RequestMethod[RequestMethod["UNLOCK"] = 15] = "UNLOCK"; +})(RequestMethod || (exports.RequestMethod = RequestMethod = {})); diff --git a/node_modules/@nestjs/common/enums/route-paramtypes.enum.d.ts b/node_modules/@nestjs/common/enums/route-paramtypes.enum.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6d3c38c0868ac3d0dd9e31de099388eb8660fc06 --- /dev/null +++ b/node_modules/@nestjs/common/enums/route-paramtypes.enum.d.ts @@ -0,0 +1,16 @@ +export declare enum RouteParamtypes { + REQUEST = 0, + RESPONSE = 1, + NEXT = 2, + BODY = 3, + QUERY = 4, + PARAM = 5, + HEADERS = 6, + SESSION = 7, + FILE = 8, + FILES = 9, + HOST = 10, + IP = 11, + RAW_BODY = 12, + ACK = 13 +} diff --git a/node_modules/@nestjs/common/enums/route-paramtypes.enum.js b/node_modules/@nestjs/common/enums/route-paramtypes.enum.js new file mode 100644 index 0000000000000000000000000000000000000000..4cfa429281b39e3d5f8dd284aa2a8e88a7f64e55 --- /dev/null +++ b/node_modules/@nestjs/common/enums/route-paramtypes.enum.js @@ -0,0 +1,20 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.RouteParamtypes = void 0; +var RouteParamtypes; +(function (RouteParamtypes) { + RouteParamtypes[RouteParamtypes["REQUEST"] = 0] = "REQUEST"; + RouteParamtypes[RouteParamtypes["RESPONSE"] = 1] = "RESPONSE"; + RouteParamtypes[RouteParamtypes["NEXT"] = 2] = "NEXT"; + RouteParamtypes[RouteParamtypes["BODY"] = 3] = "BODY"; + RouteParamtypes[RouteParamtypes["QUERY"] = 4] = "QUERY"; + RouteParamtypes[RouteParamtypes["PARAM"] = 5] = "PARAM"; + RouteParamtypes[RouteParamtypes["HEADERS"] = 6] = "HEADERS"; + RouteParamtypes[RouteParamtypes["SESSION"] = 7] = "SESSION"; + RouteParamtypes[RouteParamtypes["FILE"] = 8] = "FILE"; + RouteParamtypes[RouteParamtypes["FILES"] = 9] = "FILES"; + RouteParamtypes[RouteParamtypes["HOST"] = 10] = "HOST"; + RouteParamtypes[RouteParamtypes["IP"] = 11] = "IP"; + RouteParamtypes[RouteParamtypes["RAW_BODY"] = 12] = "RAW_BODY"; + RouteParamtypes[RouteParamtypes["ACK"] = 13] = "ACK"; +})(RouteParamtypes || (exports.RouteParamtypes = RouteParamtypes = {})); diff --git a/node_modules/@nestjs/common/enums/shutdown-signal.enum.d.ts b/node_modules/@nestjs/common/enums/shutdown-signal.enum.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..99f5b4d31f04971331c2887aca9b3b6f52d71f9a --- /dev/null +++ b/node_modules/@nestjs/common/enums/shutdown-signal.enum.d.ts @@ -0,0 +1,16 @@ +/** + * System signals which shut down a process + */ +export declare enum ShutdownSignal { + SIGHUP = "SIGHUP", + SIGINT = "SIGINT", + SIGQUIT = "SIGQUIT", + SIGILL = "SIGILL", + SIGTRAP = "SIGTRAP", + SIGABRT = "SIGABRT", + SIGBUS = "SIGBUS", + SIGFPE = "SIGFPE", + SIGSEGV = "SIGSEGV", + SIGUSR2 = "SIGUSR2", + SIGTERM = "SIGTERM" +} diff --git a/node_modules/@nestjs/common/enums/shutdown-signal.enum.js b/node_modules/@nestjs/common/enums/shutdown-signal.enum.js new file mode 100644 index 0000000000000000000000000000000000000000..9b753cb4a1dedfb4814c53159cc3d8296f5779a4 --- /dev/null +++ b/node_modules/@nestjs/common/enums/shutdown-signal.enum.js @@ -0,0 +1,20 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ShutdownSignal = void 0; +/** + * System signals which shut down a process + */ +var ShutdownSignal; +(function (ShutdownSignal) { + ShutdownSignal["SIGHUP"] = "SIGHUP"; + ShutdownSignal["SIGINT"] = "SIGINT"; + ShutdownSignal["SIGQUIT"] = "SIGQUIT"; + ShutdownSignal["SIGILL"] = "SIGILL"; + ShutdownSignal["SIGTRAP"] = "SIGTRAP"; + ShutdownSignal["SIGABRT"] = "SIGABRT"; + ShutdownSignal["SIGBUS"] = "SIGBUS"; + ShutdownSignal["SIGFPE"] = "SIGFPE"; + ShutdownSignal["SIGSEGV"] = "SIGSEGV"; + ShutdownSignal["SIGUSR2"] = "SIGUSR2"; + ShutdownSignal["SIGTERM"] = "SIGTERM"; +})(ShutdownSignal || (exports.ShutdownSignal = ShutdownSignal = {})); diff --git a/node_modules/@nestjs/common/enums/version-type.enum.d.ts b/node_modules/@nestjs/common/enums/version-type.enum.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..98248fdad12ced825112eddbc74fe326903bdf70 --- /dev/null +++ b/node_modules/@nestjs/common/enums/version-type.enum.d.ts @@ -0,0 +1,9 @@ +/** + * @publicApi + */ +export declare enum VersioningType { + URI = 0, + HEADER = 1, + MEDIA_TYPE = 2, + CUSTOM = 3 +} diff --git a/node_modules/@nestjs/common/enums/version-type.enum.js b/node_modules/@nestjs/common/enums/version-type.enum.js new file mode 100644 index 0000000000000000000000000000000000000000..9aacb5b06ad8e9bdb065b49282c1dda753b1a039 --- /dev/null +++ b/node_modules/@nestjs/common/enums/version-type.enum.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.VersioningType = void 0; +/** + * @publicApi + */ +var VersioningType; +(function (VersioningType) { + VersioningType[VersioningType["URI"] = 0] = "URI"; + VersioningType[VersioningType["HEADER"] = 1] = "HEADER"; + VersioningType[VersioningType["MEDIA_TYPE"] = 2] = "MEDIA_TYPE"; + VersioningType[VersioningType["CUSTOM"] = 3] = "CUSTOM"; +})(VersioningType || (exports.VersioningType = VersioningType = {})); diff --git a/node_modules/@nestjs/common/exceptions/bad-gateway.exception.d.ts b/node_modules/@nestjs/common/exceptions/bad-gateway.exception.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5e72b1277441cad6bdc40fbc76ef77456a61a61e --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/bad-gateway.exception.d.ts @@ -0,0 +1,35 @@ +import { HttpException, HttpExceptionOptions } from './http.exception'; +/** + * Defines an HTTP exception for *Bad Gateway* type errors. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +export declare class BadGatewayException extends HttpException { + /** + * Instantiate a `BadGatewayException` Exception. + * + * @example + * `throw new BadGatewayException()` + * + * @usageNotes + * The HTTP response status code will be 502. + * - The `objectOrError` argument defines the JSON response body or the message string. + * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause. + * + * By default, the JSON response body contains two properties: + * - `statusCode`: this will be the value 502. + * - `message`: the string `'Bad Gateway'` by default; override this by supplying + * a string in the `objectOrError` parameter. + * + * If the parameter `objectOrError` is a string, the response body will contain an + * additional property, `error`, with a short description of the HTTP error. To override the + * entire JSON response body, pass an object instead. Nest will serialize the object + * and return it as the JSON response body. + * + * @param objectOrError string or object describing the error condition. + * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause + */ + constructor(objectOrError?: any, descriptionOrOptions?: string | HttpExceptionOptions); +} diff --git a/node_modules/@nestjs/common/exceptions/bad-gateway.exception.js b/node_modules/@nestjs/common/exceptions/bad-gateway.exception.js new file mode 100644 index 0000000000000000000000000000000000000000..6f1bd4e716439b3230e913a6fce65494f1679e58 --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/bad-gateway.exception.js @@ -0,0 +1,43 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BadGatewayException = void 0; +const http_status_enum_1 = require("../enums/http-status.enum"); +const http_exception_1 = require("./http.exception"); +/** + * Defines an HTTP exception for *Bad Gateway* type errors. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +class BadGatewayException extends http_exception_1.HttpException { + /** + * Instantiate a `BadGatewayException` Exception. + * + * @example + * `throw new BadGatewayException()` + * + * @usageNotes + * The HTTP response status code will be 502. + * - The `objectOrError` argument defines the JSON response body or the message string. + * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause. + * + * By default, the JSON response body contains two properties: + * - `statusCode`: this will be the value 502. + * - `message`: the string `'Bad Gateway'` by default; override this by supplying + * a string in the `objectOrError` parameter. + * + * If the parameter `objectOrError` is a string, the response body will contain an + * additional property, `error`, with a short description of the HTTP error. To override the + * entire JSON response body, pass an object instead. Nest will serialize the object + * and return it as the JSON response body. + * + * @param objectOrError string or object describing the error condition. + * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause + */ + constructor(objectOrError, descriptionOrOptions = 'Bad Gateway') { + const { description, httpExceptionOptions } = http_exception_1.HttpException.extractDescriptionAndOptionsFrom(descriptionOrOptions); + super(http_exception_1.HttpException.createBody(objectOrError, description, http_status_enum_1.HttpStatus.BAD_GATEWAY), http_status_enum_1.HttpStatus.BAD_GATEWAY, httpExceptionOptions); + } +} +exports.BadGatewayException = BadGatewayException; diff --git a/node_modules/@nestjs/common/exceptions/bad-request.exception.d.ts b/node_modules/@nestjs/common/exceptions/bad-request.exception.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c4edd890740d9e189870623282be25c70f8e89b9 --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/bad-request.exception.d.ts @@ -0,0 +1,35 @@ +import { HttpException, HttpExceptionOptions } from './http.exception'; +/** + * Defines an HTTP exception for *Bad Request* type errors. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +export declare class BadRequestException extends HttpException { + /** + * Instantiate a `BadRequestException` Exception. + * + * @example + * `throw new BadRequestException()` + * + * @usageNotes + * The HTTP response status code will be 400. + * - The `objectOrError` argument defines the JSON response body or the message string. + * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause. + * + * By default, the JSON response body contains two properties: + * - `statusCode`: this will be the value 400. + * - `message`: the string `'Bad Request'` by default; override this by supplying + * a string in the `objectOrError` parameter. + * + * If the parameter `objectOrError` is a string, the response body will contain an + * additional property, `error`, with a short description of the HTTP error. To override the + * entire JSON response body, pass an object instead. Nest will serialize the object + * and return it as the JSON response body. + * + * @param objectOrError string or object describing the error condition. + * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause + */ + constructor(objectOrError?: any, descriptionOrOptions?: string | HttpExceptionOptions); +} diff --git a/node_modules/@nestjs/common/exceptions/bad-request.exception.js b/node_modules/@nestjs/common/exceptions/bad-request.exception.js new file mode 100644 index 0000000000000000000000000000000000000000..df486e1f2165b4042a745f0058fe303fc352aaa3 --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/bad-request.exception.js @@ -0,0 +1,43 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BadRequestException = void 0; +const http_status_enum_1 = require("../enums/http-status.enum"); +const http_exception_1 = require("./http.exception"); +/** + * Defines an HTTP exception for *Bad Request* type errors. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +class BadRequestException extends http_exception_1.HttpException { + /** + * Instantiate a `BadRequestException` Exception. + * + * @example + * `throw new BadRequestException()` + * + * @usageNotes + * The HTTP response status code will be 400. + * - The `objectOrError` argument defines the JSON response body or the message string. + * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause. + * + * By default, the JSON response body contains two properties: + * - `statusCode`: this will be the value 400. + * - `message`: the string `'Bad Request'` by default; override this by supplying + * a string in the `objectOrError` parameter. + * + * If the parameter `objectOrError` is a string, the response body will contain an + * additional property, `error`, with a short description of the HTTP error. To override the + * entire JSON response body, pass an object instead. Nest will serialize the object + * and return it as the JSON response body. + * + * @param objectOrError string or object describing the error condition. + * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause + */ + constructor(objectOrError, descriptionOrOptions = 'Bad Request') { + const { description, httpExceptionOptions } = http_exception_1.HttpException.extractDescriptionAndOptionsFrom(descriptionOrOptions); + super(http_exception_1.HttpException.createBody(objectOrError, description, http_status_enum_1.HttpStatus.BAD_REQUEST), http_status_enum_1.HttpStatus.BAD_REQUEST, httpExceptionOptions); + } +} +exports.BadRequestException = BadRequestException; diff --git a/node_modules/@nestjs/common/exceptions/conflict.exception.d.ts b/node_modules/@nestjs/common/exceptions/conflict.exception.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9cb047c7b19ceee5a134654ad7b52484b833778b --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/conflict.exception.d.ts @@ -0,0 +1,35 @@ +import { HttpException, HttpExceptionOptions } from './http.exception'; +/** + * Defines an HTTP exception for *Conflict* type errors. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +export declare class ConflictException extends HttpException { + /** + * Instantiate a `ConflictException` Exception. + * + * @example + * `throw new ConflictException()` + * + * @usageNotes + * The HTTP response status code will be 409. + * - The `objectOrError` argument defines the JSON response body or the message string. + * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause. + * + * By default, the JSON response body contains two properties: + * - `statusCode`: this will be the value 409. + * - `message`: the string `'Conflict'` by default; override this by supplying + * a string in the `objectOrError` parameter. + * + * If the parameter `objectOrError` is a string, the response body will contain an + * additional property, `error`, with a short description of the HTTP error. To override the + * entire JSON response body, pass an object instead. Nest will serialize the object + * and return it as the JSON response body. + * + * @param objectOrError string or object describing the error condition. + * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause + */ + constructor(objectOrError?: any, descriptionOrOptions?: string | HttpExceptionOptions); +} diff --git a/node_modules/@nestjs/common/exceptions/conflict.exception.js b/node_modules/@nestjs/common/exceptions/conflict.exception.js new file mode 100644 index 0000000000000000000000000000000000000000..f73a78e13dee509ff67ebdd6156ee2b9f89b7a59 --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/conflict.exception.js @@ -0,0 +1,43 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ConflictException = void 0; +const http_status_enum_1 = require("../enums/http-status.enum"); +const http_exception_1 = require("./http.exception"); +/** + * Defines an HTTP exception for *Conflict* type errors. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +class ConflictException extends http_exception_1.HttpException { + /** + * Instantiate a `ConflictException` Exception. + * + * @example + * `throw new ConflictException()` + * + * @usageNotes + * The HTTP response status code will be 409. + * - The `objectOrError` argument defines the JSON response body or the message string. + * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause. + * + * By default, the JSON response body contains two properties: + * - `statusCode`: this will be the value 409. + * - `message`: the string `'Conflict'` by default; override this by supplying + * a string in the `objectOrError` parameter. + * + * If the parameter `objectOrError` is a string, the response body will contain an + * additional property, `error`, with a short description of the HTTP error. To override the + * entire JSON response body, pass an object instead. Nest will serialize the object + * and return it as the JSON response body. + * + * @param objectOrError string or object describing the error condition. + * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause + */ + constructor(objectOrError, descriptionOrOptions = 'Conflict') { + const { description, httpExceptionOptions } = http_exception_1.HttpException.extractDescriptionAndOptionsFrom(descriptionOrOptions); + super(http_exception_1.HttpException.createBody(objectOrError, description, http_status_enum_1.HttpStatus.CONFLICT), http_status_enum_1.HttpStatus.CONFLICT, httpExceptionOptions); + } +} +exports.ConflictException = ConflictException; diff --git a/node_modules/@nestjs/common/exceptions/forbidden.exception.d.ts b/node_modules/@nestjs/common/exceptions/forbidden.exception.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..76b686082719f90360cc4794256b71e1b0d7e29b --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/forbidden.exception.d.ts @@ -0,0 +1,35 @@ +import { HttpException, HttpExceptionOptions } from './http.exception'; +/** + * Defines an HTTP exception for *Forbidden* type errors. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +export declare class ForbiddenException extends HttpException { + /** + * Instantiate a `ForbiddenException` Exception. + * + * @example + * `throw new ForbiddenException()` + * + * @usageNotes + * The HTTP response status code will be 403. + * - The `objectOrError` argument defines the JSON response body or the message string. + * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause. + * + * By default, the JSON response body contains two properties: + * - `statusCode`: this will be the value 403. + * - `message`: the string `'Forbidden'` by default; override this by supplying + * a string in the `objectOrError` parameter. + * + * If the parameter `objectOrError` is a string, the response body will contain an + * additional property, `error`, with a short description of the HTTP error. To override the + * entire JSON response body, pass an object instead. Nest will serialize the object + * and return it as the JSON response body. + * + * @param objectOrError string or object describing the error condition. + * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause + */ + constructor(objectOrError?: any, descriptionOrOptions?: string | HttpExceptionOptions); +} diff --git a/node_modules/@nestjs/common/exceptions/forbidden.exception.js b/node_modules/@nestjs/common/exceptions/forbidden.exception.js new file mode 100644 index 0000000000000000000000000000000000000000..3362bcba39c02aba62345e682d92cfaec6afbbca --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/forbidden.exception.js @@ -0,0 +1,43 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ForbiddenException = void 0; +const http_status_enum_1 = require("../enums/http-status.enum"); +const http_exception_1 = require("./http.exception"); +/** + * Defines an HTTP exception for *Forbidden* type errors. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +class ForbiddenException extends http_exception_1.HttpException { + /** + * Instantiate a `ForbiddenException` Exception. + * + * @example + * `throw new ForbiddenException()` + * + * @usageNotes + * The HTTP response status code will be 403. + * - The `objectOrError` argument defines the JSON response body or the message string. + * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause. + * + * By default, the JSON response body contains two properties: + * - `statusCode`: this will be the value 403. + * - `message`: the string `'Forbidden'` by default; override this by supplying + * a string in the `objectOrError` parameter. + * + * If the parameter `objectOrError` is a string, the response body will contain an + * additional property, `error`, with a short description of the HTTP error. To override the + * entire JSON response body, pass an object instead. Nest will serialize the object + * and return it as the JSON response body. + * + * @param objectOrError string or object describing the error condition. + * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause + */ + constructor(objectOrError, descriptionOrOptions = 'Forbidden') { + const { description, httpExceptionOptions } = http_exception_1.HttpException.extractDescriptionAndOptionsFrom(descriptionOrOptions); + super(http_exception_1.HttpException.createBody(objectOrError, description, http_status_enum_1.HttpStatus.FORBIDDEN), http_status_enum_1.HttpStatus.FORBIDDEN, httpExceptionOptions); + } +} +exports.ForbiddenException = ForbiddenException; diff --git a/node_modules/@nestjs/common/exceptions/gateway-timeout.exception.d.ts b/node_modules/@nestjs/common/exceptions/gateway-timeout.exception.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a42411a2bba0fbefa2242b5d467dd038351eb439 --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/gateway-timeout.exception.d.ts @@ -0,0 +1,35 @@ +import { HttpException, HttpExceptionOptions } from './http.exception'; +/** + * Defines an HTTP exception for *Gateway Timeout* type errors. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +export declare class GatewayTimeoutException extends HttpException { + /** + * Instantiate a `GatewayTimeoutException` Exception. + * + * @example + * `throw new GatewayTimeoutException()` + * + * @usageNotes + * The HTTP response status code will be 504. + * - The `objectOrError` argument defines the JSON response body or the message string. + * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause. + * + * By default, the JSON response body contains two properties: + * - `statusCode`: this will be the value 504. + * - `message`: the string `'Gateway Timeout'` by default; override this by supplying + * a string in the `objectOrError` parameter. + * + * If the parameter `objectOrError` is a string, the response body will contain an + * additional property, `error`, with a short description of the HTTP error. To override the + * entire JSON response body, pass an object instead. Nest will serialize the object + * and return it as the JSON response body. + * + * @param objectOrError string or object describing the error condition. + * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause + */ + constructor(objectOrError?: any, descriptionOrOptions?: string | HttpExceptionOptions); +} diff --git a/node_modules/@nestjs/common/exceptions/gateway-timeout.exception.js b/node_modules/@nestjs/common/exceptions/gateway-timeout.exception.js new file mode 100644 index 0000000000000000000000000000000000000000..28cedc9069c7fc496c9c2e3df84b9ab35332322b --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/gateway-timeout.exception.js @@ -0,0 +1,43 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.GatewayTimeoutException = void 0; +const http_status_enum_1 = require("../enums/http-status.enum"); +const http_exception_1 = require("./http.exception"); +/** + * Defines an HTTP exception for *Gateway Timeout* type errors. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +class GatewayTimeoutException extends http_exception_1.HttpException { + /** + * Instantiate a `GatewayTimeoutException` Exception. + * + * @example + * `throw new GatewayTimeoutException()` + * + * @usageNotes + * The HTTP response status code will be 504. + * - The `objectOrError` argument defines the JSON response body or the message string. + * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause. + * + * By default, the JSON response body contains two properties: + * - `statusCode`: this will be the value 504. + * - `message`: the string `'Gateway Timeout'` by default; override this by supplying + * a string in the `objectOrError` parameter. + * + * If the parameter `objectOrError` is a string, the response body will contain an + * additional property, `error`, with a short description of the HTTP error. To override the + * entire JSON response body, pass an object instead. Nest will serialize the object + * and return it as the JSON response body. + * + * @param objectOrError string or object describing the error condition. + * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause + */ + constructor(objectOrError, descriptionOrOptions = 'Gateway Timeout') { + const { description, httpExceptionOptions } = http_exception_1.HttpException.extractDescriptionAndOptionsFrom(descriptionOrOptions); + super(http_exception_1.HttpException.createBody(objectOrError, description, http_status_enum_1.HttpStatus.GATEWAY_TIMEOUT), http_status_enum_1.HttpStatus.GATEWAY_TIMEOUT, httpExceptionOptions); + } +} +exports.GatewayTimeoutException = GatewayTimeoutException; diff --git a/node_modules/@nestjs/common/exceptions/gone.exception.d.ts b/node_modules/@nestjs/common/exceptions/gone.exception.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..46f11266954f7ce9b3306a3a49e552582735becb --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/gone.exception.d.ts @@ -0,0 +1,35 @@ +import { HttpException, HttpExceptionOptions } from './http.exception'; +/** + * Defines an HTTP exception for *Gone* type errors. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +export declare class GoneException extends HttpException { + /** + * Instantiate a `GoneException` Exception. + * + * @example + * `throw new GoneException()` + * + * @usageNotes + * The HTTP response status code will be 410. + * - The `objectOrError` argument defines the JSON response body or the message string. + * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause. + * + * By default, the JSON response body contains two properties: + * - `statusCode`: this will be the value 410. + * - `message`: the string `'Gone'` by default; override this by supplying + * a string in the `objectOrError` parameter. + * + * If the parameter `objectOrError` is a string, the response body will contain an + * additional property, `error`, with a short description of the HTTP error. To override the + * entire JSON response body, pass an object instead. Nest will serialize the object + * and return it as the JSON response body. + * + * @param objectOrError string or object describing the error condition. + * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause + */ + constructor(objectOrError?: any, descriptionOrOptions?: string | HttpExceptionOptions); +} diff --git a/node_modules/@nestjs/common/exceptions/gone.exception.js b/node_modules/@nestjs/common/exceptions/gone.exception.js new file mode 100644 index 0000000000000000000000000000000000000000..affca5bd718d9300a727e8b54169626eb6a0ab6f --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/gone.exception.js @@ -0,0 +1,43 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.GoneException = void 0; +const http_status_enum_1 = require("../enums/http-status.enum"); +const http_exception_1 = require("./http.exception"); +/** + * Defines an HTTP exception for *Gone* type errors. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +class GoneException extends http_exception_1.HttpException { + /** + * Instantiate a `GoneException` Exception. + * + * @example + * `throw new GoneException()` + * + * @usageNotes + * The HTTP response status code will be 410. + * - The `objectOrError` argument defines the JSON response body or the message string. + * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause. + * + * By default, the JSON response body contains two properties: + * - `statusCode`: this will be the value 410. + * - `message`: the string `'Gone'` by default; override this by supplying + * a string in the `objectOrError` parameter. + * + * If the parameter `objectOrError` is a string, the response body will contain an + * additional property, `error`, with a short description of the HTTP error. To override the + * entire JSON response body, pass an object instead. Nest will serialize the object + * and return it as the JSON response body. + * + * @param objectOrError string or object describing the error condition. + * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause + */ + constructor(objectOrError, descriptionOrOptions = 'Gone') { + const { description, httpExceptionOptions } = http_exception_1.HttpException.extractDescriptionAndOptionsFrom(descriptionOrOptions); + super(http_exception_1.HttpException.createBody(objectOrError, description, http_status_enum_1.HttpStatus.GONE), http_status_enum_1.HttpStatus.GONE, httpExceptionOptions); + } +} +exports.GoneException = GoneException; diff --git a/node_modules/@nestjs/common/exceptions/http-version-not-supported.exception.d.ts b/node_modules/@nestjs/common/exceptions/http-version-not-supported.exception.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c2b7390270893d0a95a652b6c8341e03517ed7d6 --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/http-version-not-supported.exception.d.ts @@ -0,0 +1,35 @@ +import { HttpException, HttpExceptionOptions } from './http.exception'; +/** + * Defines an HTTP exception for *Http Version Not Supported* type errors. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +export declare class HttpVersionNotSupportedException extends HttpException { + /** + * Instantiate a `HttpVersionNotSupportedException` Exception. + * + * @example + * `throw new HttpVersionNotSupportedException()` + * + * @usageNotes + * The HTTP response status code will be 505. + * - The `objectOrError` argument defines the JSON response body or the message string. + * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause. + * + * By default, the JSON response body contains two properties: + * - `statusCode`: this will be the value 505. + * - `message`: the string `'HTTP Version Not Supported'` by default; override this by supplying + * a string in the `objectOrError` parameter. + * + * If the parameter `objectOrError` is a string, the response body will contain an + * additional property, `error`, with a short description of the HTTP error. To override the + * entire JSON response body, pass an object instead. Nest will serialize the object + * and return it as the JSON response body. + * + * @param objectOrError string or object describing the error condition. + * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause + */ + constructor(objectOrError?: any, descriptionOrOptions?: string | HttpExceptionOptions); +} diff --git a/node_modules/@nestjs/common/exceptions/http-version-not-supported.exception.js b/node_modules/@nestjs/common/exceptions/http-version-not-supported.exception.js new file mode 100644 index 0000000000000000000000000000000000000000..89648cc72956b58d23e3c89aa0859d08fa4311e4 --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/http-version-not-supported.exception.js @@ -0,0 +1,43 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.HttpVersionNotSupportedException = void 0; +const http_status_enum_1 = require("../enums/http-status.enum"); +const http_exception_1 = require("./http.exception"); +/** + * Defines an HTTP exception for *Http Version Not Supported* type errors. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +class HttpVersionNotSupportedException extends http_exception_1.HttpException { + /** + * Instantiate a `HttpVersionNotSupportedException` Exception. + * + * @example + * `throw new HttpVersionNotSupportedException()` + * + * @usageNotes + * The HTTP response status code will be 505. + * - The `objectOrError` argument defines the JSON response body or the message string. + * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause. + * + * By default, the JSON response body contains two properties: + * - `statusCode`: this will be the value 505. + * - `message`: the string `'HTTP Version Not Supported'` by default; override this by supplying + * a string in the `objectOrError` parameter. + * + * If the parameter `objectOrError` is a string, the response body will contain an + * additional property, `error`, with a short description of the HTTP error. To override the + * entire JSON response body, pass an object instead. Nest will serialize the object + * and return it as the JSON response body. + * + * @param objectOrError string or object describing the error condition. + * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause + */ + constructor(objectOrError, descriptionOrOptions = 'HTTP Version Not Supported') { + const { description, httpExceptionOptions } = http_exception_1.HttpException.extractDescriptionAndOptionsFrom(descriptionOrOptions); + super(http_exception_1.HttpException.createBody(objectOrError, description, http_status_enum_1.HttpStatus.HTTP_VERSION_NOT_SUPPORTED), http_status_enum_1.HttpStatus.HTTP_VERSION_NOT_SUPPORTED, httpExceptionOptions); + } +} +exports.HttpVersionNotSupportedException = HttpVersionNotSupportedException; diff --git a/node_modules/@nestjs/common/exceptions/http.exception.d.ts b/node_modules/@nestjs/common/exceptions/http.exception.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..83373e351a2581691740f3b53c27e6d4348fdb27 --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/http.exception.d.ts @@ -0,0 +1,85 @@ +import { HttpExceptionBody, HttpExceptionBodyMessage } from '../interfaces/http/http-exception-body.interface'; +import { IntrinsicException } from './intrinsic.exception'; +export interface HttpExceptionOptions { + /** original cause of the error */ + cause?: unknown; + description?: string; +} +export interface DescriptionAndOptions { + description?: string; + httpExceptionOptions?: HttpExceptionOptions; +} +/** + * Defines the base Nest HTTP exception, which is handled by the default + * Exceptions Handler. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +export declare class HttpException extends IntrinsicException { + private readonly response; + private readonly status; + private readonly options?; + /** + * Exception cause. Indicates the specific original cause of the error. + * It is used when catching and re-throwing an error with a more-specific or useful error message in order to still have access to the original error. + */ + cause: unknown; + /** + * Instantiate a plain HTTP Exception. + * + * @example + * throw new HttpException('message', HttpStatus.BAD_REQUEST) + * throw new HttpException('custom message', HttpStatus.BAD_REQUEST, { + * cause: new Error('Cause Error'), + * }) + * + * + * @usageNotes + * The constructor arguments define the response and the HTTP response status code. + * - The `response` argument (required) defines the JSON response body. alternatively, it can also be + * an error object that is used to define an error [cause](https://nodejs.org/en/blog/release/v16.9.0/#error-cause). + * - The `status` argument (required) defines the HTTP Status Code. + * - The `options` argument (optional) defines additional error options. Currently, it supports the `cause` attribute, + * and can be used as an alternative way to specify the error cause: `const error = new HttpException('description', 400, { cause: new Error() });` + * + * By default, the JSON response body contains two properties: + * - `statusCode`: the Http Status Code. + * - `message`: a short description of the HTTP error by default; override this + * by supplying a string in the `response` parameter. + * + * To override the entire JSON response body, pass an object to the `createBody` + * method. Nest will serialize the object and return it as the JSON response body. + * + * The `status` argument is required, and should be a valid HTTP status code. + * Best practice is to use the `HttpStatus` enum imported from `nestjs/common`. + * + * @param response string, object describing the error condition or the error cause. + * @param status HTTP response status code. + * @param options An object used to add an error cause. + */ + constructor(response: string | Record, status: number, options?: HttpExceptionOptions | undefined); + /** + * Configures error chaining support + * + * @see https://nodejs.org/en/blog/release/v16.9.0/#error-cause + * @see https://github.com/microsoft/TypeScript/issues/45167 + */ + initCause(): void; + initMessage(): void; + initName(): void; + getResponse(): string | object; + getStatus(): number; + static createBody(nil: null | '', message: HttpExceptionBodyMessage, statusCode: number): HttpExceptionBody; + static createBody(message: HttpExceptionBodyMessage, error: string, statusCode: number): HttpExceptionBody; + static createBody>(custom: Body): Body; + static getDescriptionFrom(descriptionOrOptions: string | HttpExceptionOptions): string; + static getHttpExceptionOptionsFrom(descriptionOrOptions: string | HttpExceptionOptions): HttpExceptionOptions; + /** + * Utility method used to extract the error description and httpExceptionOptions from the given argument. + * This is used by inheriting classes to correctly parse both options. + * @returns the error description and the httpExceptionOptions as an object. + */ + static extractDescriptionAndOptionsFrom(descriptionOrOptions: string | HttpExceptionOptions): DescriptionAndOptions; +} diff --git a/node_modules/@nestjs/common/exceptions/http.exception.js b/node_modules/@nestjs/common/exceptions/http.exception.js new file mode 100644 index 0000000000000000000000000000000000000000..9f117ccc78979847881efc8cf349cf73a085e375 --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/http.exception.js @@ -0,0 +1,133 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.HttpException = void 0; +const shared_utils_1 = require("../utils/shared.utils"); +const intrinsic_exception_1 = require("./intrinsic.exception"); +/** + * Defines the base Nest HTTP exception, which is handled by the default + * Exceptions Handler. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +class HttpException extends intrinsic_exception_1.IntrinsicException { + /** + * Instantiate a plain HTTP Exception. + * + * @example + * throw new HttpException('message', HttpStatus.BAD_REQUEST) + * throw new HttpException('custom message', HttpStatus.BAD_REQUEST, { + * cause: new Error('Cause Error'), + * }) + * + * + * @usageNotes + * The constructor arguments define the response and the HTTP response status code. + * - The `response` argument (required) defines the JSON response body. alternatively, it can also be + * an error object that is used to define an error [cause](https://nodejs.org/en/blog/release/v16.9.0/#error-cause). + * - The `status` argument (required) defines the HTTP Status Code. + * - The `options` argument (optional) defines additional error options. Currently, it supports the `cause` attribute, + * and can be used as an alternative way to specify the error cause: `const error = new HttpException('description', 400, { cause: new Error() });` + * + * By default, the JSON response body contains two properties: + * - `statusCode`: the Http Status Code. + * - `message`: a short description of the HTTP error by default; override this + * by supplying a string in the `response` parameter. + * + * To override the entire JSON response body, pass an object to the `createBody` + * method. Nest will serialize the object and return it as the JSON response body. + * + * The `status` argument is required, and should be a valid HTTP status code. + * Best practice is to use the `HttpStatus` enum imported from `nestjs/common`. + * + * @param response string, object describing the error condition or the error cause. + * @param status HTTP response status code. + * @param options An object used to add an error cause. + */ + constructor(response, status, options) { + super(); + this.response = response; + this.status = status; + this.options = options; + this.initMessage(); + this.initName(); + this.initCause(); + } + /** + * Configures error chaining support + * + * @see https://nodejs.org/en/blog/release/v16.9.0/#error-cause + * @see https://github.com/microsoft/TypeScript/issues/45167 + */ + initCause() { + if (this.options?.cause) { + this.cause = this.options.cause; + return; + } + } + initMessage() { + if ((0, shared_utils_1.isString)(this.response)) { + this.message = this.response; + } + else if ((0, shared_utils_1.isObject)(this.response) && (0, shared_utils_1.isString)(this.response.message)) { + this.message = this.response.message; + } + else if (this.constructor) { + this.message = + this.constructor.name.match(/[A-Z][a-z]+|[0-9]+/g)?.join(' ') ?? + 'Error'; + } + } + initName() { + this.name = this.constructor.name; + } + getResponse() { + return this.response; + } + getStatus() { + return this.status; + } + static createBody(arg0, arg1, statusCode) { + if (!arg0) { + return { + message: arg1, + statusCode: statusCode, + }; + } + if ((0, shared_utils_1.isString)(arg0) || Array.isArray(arg0) || (0, shared_utils_1.isNumber)(arg0)) { + return { + message: arg0, + error: arg1, + statusCode: statusCode, + }; + } + return arg0; + } + static getDescriptionFrom(descriptionOrOptions) { + return (0, shared_utils_1.isString)(descriptionOrOptions) + ? descriptionOrOptions + : descriptionOrOptions?.description; + } + static getHttpExceptionOptionsFrom(descriptionOrOptions) { + return (0, shared_utils_1.isString)(descriptionOrOptions) ? {} : descriptionOrOptions; + } + /** + * Utility method used to extract the error description and httpExceptionOptions from the given argument. + * This is used by inheriting classes to correctly parse both options. + * @returns the error description and the httpExceptionOptions as an object. + */ + static extractDescriptionAndOptionsFrom(descriptionOrOptions) { + const description = (0, shared_utils_1.isString)(descriptionOrOptions) + ? descriptionOrOptions + : descriptionOrOptions?.description; + const httpExceptionOptions = (0, shared_utils_1.isString)(descriptionOrOptions) + ? {} + : descriptionOrOptions; + return { + description, + httpExceptionOptions, + }; + } +} +exports.HttpException = HttpException; diff --git a/node_modules/@nestjs/common/exceptions/im-a-teapot.exception.d.ts b/node_modules/@nestjs/common/exceptions/im-a-teapot.exception.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b7d2d5bb8e910de264c051bf713db22fef704318 --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/im-a-teapot.exception.d.ts @@ -0,0 +1,38 @@ +import { HttpException, HttpExceptionOptions } from './http.exception'; +/** + * Defines an HTTP exception for *ImATeapotException* type errors. + * + * Any attempt to brew coffee with a teapot should result in the error code + * "418 I'm a teapot". The resulting entity body MAY be short and stout. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +export declare class ImATeapotException extends HttpException { + /** + * Instantiate an `ImATeapotException` Exception. + * + * @example + * `throw new ImATeapotException()` + * + * @usageNotes + * The HTTP response status code will be 418. + * - The `objectOrError` argument defines the JSON response body or the message string. + * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause. + * + * By default, the JSON response body contains two properties: + * - `statusCode`: this will be the value 418. + * - `message`: the string `"I'm a Teapot"` by default; override this by supplying + * a string in the `objectOrError` parameter. + * + * If the parameter `objectOrError` is a string, the response body will contain an + * additional property, `error`, with a short description of the HTTP error. To override the + * entire JSON response body, pass an object instead. Nest will serialize the object + * and return it as the JSON response body. + * + * @param objectOrError string or object describing the error condition. + * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause + */ + constructor(objectOrError?: any, descriptionOrOptions?: string | HttpExceptionOptions); +} diff --git a/node_modules/@nestjs/common/exceptions/im-a-teapot.exception.js b/node_modules/@nestjs/common/exceptions/im-a-teapot.exception.js new file mode 100644 index 0000000000000000000000000000000000000000..03d12964aef5f61f698490390bba69003de5238e --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/im-a-teapot.exception.js @@ -0,0 +1,46 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ImATeapotException = void 0; +const http_status_enum_1 = require("../enums/http-status.enum"); +const http_exception_1 = require("./http.exception"); +/** + * Defines an HTTP exception for *ImATeapotException* type errors. + * + * Any attempt to brew coffee with a teapot should result in the error code + * "418 I'm a teapot". The resulting entity body MAY be short and stout. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +class ImATeapotException extends http_exception_1.HttpException { + /** + * Instantiate an `ImATeapotException` Exception. + * + * @example + * `throw new ImATeapotException()` + * + * @usageNotes + * The HTTP response status code will be 418. + * - The `objectOrError` argument defines the JSON response body or the message string. + * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause. + * + * By default, the JSON response body contains two properties: + * - `statusCode`: this will be the value 418. + * - `message`: the string `"I'm a Teapot"` by default; override this by supplying + * a string in the `objectOrError` parameter. + * + * If the parameter `objectOrError` is a string, the response body will contain an + * additional property, `error`, with a short description of the HTTP error. To override the + * entire JSON response body, pass an object instead. Nest will serialize the object + * and return it as the JSON response body. + * + * @param objectOrError string or object describing the error condition. + * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause + */ + constructor(objectOrError, descriptionOrOptions = `I'm a teapot`) { + const { description, httpExceptionOptions } = http_exception_1.HttpException.extractDescriptionAndOptionsFrom(descriptionOrOptions); + super(http_exception_1.HttpException.createBody(objectOrError, description, http_status_enum_1.HttpStatus.I_AM_A_TEAPOT), http_status_enum_1.HttpStatus.I_AM_A_TEAPOT, httpExceptionOptions); + } +} +exports.ImATeapotException = ImATeapotException; diff --git a/node_modules/@nestjs/common/exceptions/index.d.ts b/node_modules/@nestjs/common/exceptions/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..554218336dfce885b8d258220d509b83b49ec3ea --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/index.d.ts @@ -0,0 +1,23 @@ +export * from './bad-gateway.exception'; +export * from './bad-request.exception'; +export * from './conflict.exception'; +export * from './forbidden.exception'; +export * from './gateway-timeout.exception'; +export * from './gone.exception'; +export * from './http-version-not-supported.exception'; +export * from './http.exception'; +export * from './im-a-teapot.exception'; +export * from './internal-server-error.exception'; +export * from './intrinsic.exception'; +export * from './method-not-allowed.exception'; +export * from './misdirected.exception'; +export * from './not-acceptable.exception'; +export * from './not-found.exception'; +export * from './not-implemented.exception'; +export * from './payload-too-large.exception'; +export * from './precondition-failed.exception'; +export * from './request-timeout.exception'; +export * from './service-unavailable.exception'; +export * from './unauthorized.exception'; +export * from './unprocessable-entity.exception'; +export * from './unsupported-media-type.exception'; diff --git a/node_modules/@nestjs/common/exceptions/index.js b/node_modules/@nestjs/common/exceptions/index.js new file mode 100644 index 0000000000000000000000000000000000000000..1aa3f1b8d410335c7a44f837fbd1053e9ae1a216 --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/index.js @@ -0,0 +1,26 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = require("tslib"); +tslib_1.__exportStar(require("./bad-gateway.exception"), exports); +tslib_1.__exportStar(require("./bad-request.exception"), exports); +tslib_1.__exportStar(require("./conflict.exception"), exports); +tslib_1.__exportStar(require("./forbidden.exception"), exports); +tslib_1.__exportStar(require("./gateway-timeout.exception"), exports); +tslib_1.__exportStar(require("./gone.exception"), exports); +tslib_1.__exportStar(require("./http-version-not-supported.exception"), exports); +tslib_1.__exportStar(require("./http.exception"), exports); +tslib_1.__exportStar(require("./im-a-teapot.exception"), exports); +tslib_1.__exportStar(require("./internal-server-error.exception"), exports); +tslib_1.__exportStar(require("./intrinsic.exception"), exports); +tslib_1.__exportStar(require("./method-not-allowed.exception"), exports); +tslib_1.__exportStar(require("./misdirected.exception"), exports); +tslib_1.__exportStar(require("./not-acceptable.exception"), exports); +tslib_1.__exportStar(require("./not-found.exception"), exports); +tslib_1.__exportStar(require("./not-implemented.exception"), exports); +tslib_1.__exportStar(require("./payload-too-large.exception"), exports); +tslib_1.__exportStar(require("./precondition-failed.exception"), exports); +tslib_1.__exportStar(require("./request-timeout.exception"), exports); +tslib_1.__exportStar(require("./service-unavailable.exception"), exports); +tslib_1.__exportStar(require("./unauthorized.exception"), exports); +tslib_1.__exportStar(require("./unprocessable-entity.exception"), exports); +tslib_1.__exportStar(require("./unsupported-media-type.exception"), exports); diff --git a/node_modules/@nestjs/common/exceptions/internal-server-error.exception.d.ts b/node_modules/@nestjs/common/exceptions/internal-server-error.exception.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ecdecef5494f46fff90bc2c6101aba330e13acd4 --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/internal-server-error.exception.d.ts @@ -0,0 +1,35 @@ +import { HttpException, HttpExceptionOptions } from './http.exception'; +/** + * Defines an HTTP exception for *Internal Server Error* type errors. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +export declare class InternalServerErrorException extends HttpException { + /** + * Instantiate an `InternalServerErrorException` Exception. + * + * @example + * `throw new InternalServerErrorException()` + * + * @usageNotes + * The HTTP response status code will be 500. + * - The `objectOrError` argument defines the JSON response body or the message string. + * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause. + * + * By default, the JSON response body contains two properties: + * - `statusCode`: this will be the value 500. + * - `message`: the string `'Internal Server Error'` by default; override this by supplying + * a string in the `objectOrError` parameter. + * + * If the parameter `objectOrError` is a string, the response body will contain an + * additional property, `error`, with a short description of the HTTP error. To override the + * entire JSON response body, pass an object instead. Nest will serialize the object + * and return it as the JSON response body. + * + * @param objectOrError string or object describing the error condition. + * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause + */ + constructor(objectOrError?: any, descriptionOrOptions?: string | HttpExceptionOptions); +} diff --git a/node_modules/@nestjs/common/exceptions/internal-server-error.exception.js b/node_modules/@nestjs/common/exceptions/internal-server-error.exception.js new file mode 100644 index 0000000000000000000000000000000000000000..2c794b737fd1817c75def15d19bfb9f805512063 --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/internal-server-error.exception.js @@ -0,0 +1,43 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.InternalServerErrorException = void 0; +const http_status_enum_1 = require("../enums/http-status.enum"); +const http_exception_1 = require("./http.exception"); +/** + * Defines an HTTP exception for *Internal Server Error* type errors. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +class InternalServerErrorException extends http_exception_1.HttpException { + /** + * Instantiate an `InternalServerErrorException` Exception. + * + * @example + * `throw new InternalServerErrorException()` + * + * @usageNotes + * The HTTP response status code will be 500. + * - The `objectOrError` argument defines the JSON response body or the message string. + * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause. + * + * By default, the JSON response body contains two properties: + * - `statusCode`: this will be the value 500. + * - `message`: the string `'Internal Server Error'` by default; override this by supplying + * a string in the `objectOrError` parameter. + * + * If the parameter `objectOrError` is a string, the response body will contain an + * additional property, `error`, with a short description of the HTTP error. To override the + * entire JSON response body, pass an object instead. Nest will serialize the object + * and return it as the JSON response body. + * + * @param objectOrError string or object describing the error condition. + * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause + */ + constructor(objectOrError, descriptionOrOptions = 'Internal Server Error') { + const { description, httpExceptionOptions } = http_exception_1.HttpException.extractDescriptionAndOptionsFrom(descriptionOrOptions); + super(http_exception_1.HttpException.createBody(objectOrError, description, http_status_enum_1.HttpStatus.INTERNAL_SERVER_ERROR), http_status_enum_1.HttpStatus.INTERNAL_SERVER_ERROR, httpExceptionOptions); + } +} +exports.InternalServerErrorException = InternalServerErrorException; diff --git a/node_modules/@nestjs/common/exceptions/intrinsic.exception.d.ts b/node_modules/@nestjs/common/exceptions/intrinsic.exception.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b1b7efcbaa847c0055eae1a55ca561cb1fbff92d --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/intrinsic.exception.d.ts @@ -0,0 +1,8 @@ +/** + * Exception that represents an intrinsic error in the application. + * When thrown, the default exception filter will not log the error message. + * + * @publicApi + */ +export declare class IntrinsicException extends Error { +} diff --git a/node_modules/@nestjs/common/exceptions/intrinsic.exception.js b/node_modules/@nestjs/common/exceptions/intrinsic.exception.js new file mode 100644 index 0000000000000000000000000000000000000000..37b0611ffb02b6a539a40909ae48acb36ba4a266 --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/intrinsic.exception.js @@ -0,0 +1,12 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.IntrinsicException = void 0; +/** + * Exception that represents an intrinsic error in the application. + * When thrown, the default exception filter will not log the error message. + * + * @publicApi + */ +class IntrinsicException extends Error { +} +exports.IntrinsicException = IntrinsicException; diff --git a/node_modules/@nestjs/common/exceptions/method-not-allowed.exception.d.ts b/node_modules/@nestjs/common/exceptions/method-not-allowed.exception.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4975bcf899c8c1c01e9db59ddeb710d041447ed6 --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/method-not-allowed.exception.d.ts @@ -0,0 +1,35 @@ +import { HttpException, HttpExceptionOptions } from './http.exception'; +/** + * Defines an HTTP exception for *Method Not Allowed* type errors. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +export declare class MethodNotAllowedException extends HttpException { + /** + * Instantiate a `MethodNotAllowedException` Exception. + * + * @example + * `throw new MethodNotAllowedException()` + * + * @usageNotes + * The HTTP response status code will be 405. + * - The `objectOrError` argument defines the JSON response body or the message string. + * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause. + * + * By default, the JSON response body contains two properties: + * - `statusCode`: this will be the value 405. + * - `message`: the string `'Method Not Allowed'` by default; override this by supplying + * a string in the `objectOrError` parameter. + * + * If the parameter `objectOrError` is a string, the response body will contain an + * additional property, `error`, with a short description of the HTTP error. To override the + * entire JSON response body, pass an object instead. Nest will serialize the object + * and return it as the JSON response body. + * + * @param objectOrError string or object describing the error condition. + * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause + */ + constructor(objectOrError?: any, descriptionOrOptions?: string | HttpExceptionOptions); +} diff --git a/node_modules/@nestjs/common/exceptions/method-not-allowed.exception.js b/node_modules/@nestjs/common/exceptions/method-not-allowed.exception.js new file mode 100644 index 0000000000000000000000000000000000000000..ec131fac5c4c71708b2e744d96b79bdb33d1517b --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/method-not-allowed.exception.js @@ -0,0 +1,43 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MethodNotAllowedException = void 0; +const http_status_enum_1 = require("../enums/http-status.enum"); +const http_exception_1 = require("./http.exception"); +/** + * Defines an HTTP exception for *Method Not Allowed* type errors. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +class MethodNotAllowedException extends http_exception_1.HttpException { + /** + * Instantiate a `MethodNotAllowedException` Exception. + * + * @example + * `throw new MethodNotAllowedException()` + * + * @usageNotes + * The HTTP response status code will be 405. + * - The `objectOrError` argument defines the JSON response body or the message string. + * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause. + * + * By default, the JSON response body contains two properties: + * - `statusCode`: this will be the value 405. + * - `message`: the string `'Method Not Allowed'` by default; override this by supplying + * a string in the `objectOrError` parameter. + * + * If the parameter `objectOrError` is a string, the response body will contain an + * additional property, `error`, with a short description of the HTTP error. To override the + * entire JSON response body, pass an object instead. Nest will serialize the object + * and return it as the JSON response body. + * + * @param objectOrError string or object describing the error condition. + * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause + */ + constructor(objectOrError, descriptionOrOptions = 'Method Not Allowed') { + const { description, httpExceptionOptions } = http_exception_1.HttpException.extractDescriptionAndOptionsFrom(descriptionOrOptions); + super(http_exception_1.HttpException.createBody(objectOrError, description, http_status_enum_1.HttpStatus.METHOD_NOT_ALLOWED), http_status_enum_1.HttpStatus.METHOD_NOT_ALLOWED, httpExceptionOptions); + } +} +exports.MethodNotAllowedException = MethodNotAllowedException; diff --git a/node_modules/@nestjs/common/exceptions/misdirected.exception.d.ts b/node_modules/@nestjs/common/exceptions/misdirected.exception.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..90795e7fe88c749e96ab5ec856b376836db57461 --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/misdirected.exception.d.ts @@ -0,0 +1,35 @@ +import { HttpException, HttpExceptionOptions } from './http.exception'; +/** + * Defines an HTTP exception for *Misdirected* type errors. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +export declare class MisdirectedException extends HttpException { + /** + * Instantiate a `MisdirectedException` Exception. + * + * @example + * `throw new MisdirectedException()` + * + * @usageNotes + * The HTTP response status code will be 421. + * - The `objectOrError` argument defines the JSON response body or the message string. + * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause. + * + * By default, the JSON response body contains two properties: + * - `statusCode`: this will be the value 421. + * - `message`: the string `'Bad Gateway'` by default; override this by supplying + * a string in the `objectOrError` parameter. + * + * If the parameter `objectOrError` is a string, the response body will contain an + * additional property, `error`, with a short description of the HTTP error. To override the + * entire JSON response body, pass an object instead. Nest will serialize the object + * and return it as the JSON response body. + * + * @param objectOrError string or object describing the error condition. + * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause + */ + constructor(objectOrError?: any, descriptionOrOptions?: string | HttpExceptionOptions); +} diff --git a/node_modules/@nestjs/common/exceptions/misdirected.exception.js b/node_modules/@nestjs/common/exceptions/misdirected.exception.js new file mode 100644 index 0000000000000000000000000000000000000000..bd903444bdd13f9320b958e601581e639bd0ce2a --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/misdirected.exception.js @@ -0,0 +1,43 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MisdirectedException = void 0; +const http_status_enum_1 = require("../enums/http-status.enum"); +const http_exception_1 = require("./http.exception"); +/** + * Defines an HTTP exception for *Misdirected* type errors. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +class MisdirectedException extends http_exception_1.HttpException { + /** + * Instantiate a `MisdirectedException` Exception. + * + * @example + * `throw new MisdirectedException()` + * + * @usageNotes + * The HTTP response status code will be 421. + * - The `objectOrError` argument defines the JSON response body or the message string. + * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause. + * + * By default, the JSON response body contains two properties: + * - `statusCode`: this will be the value 421. + * - `message`: the string `'Bad Gateway'` by default; override this by supplying + * a string in the `objectOrError` parameter. + * + * If the parameter `objectOrError` is a string, the response body will contain an + * additional property, `error`, with a short description of the HTTP error. To override the + * entire JSON response body, pass an object instead. Nest will serialize the object + * and return it as the JSON response body. + * + * @param objectOrError string or object describing the error condition. + * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause + */ + constructor(objectOrError, descriptionOrOptions = 'Misdirected') { + const { description, httpExceptionOptions } = http_exception_1.HttpException.extractDescriptionAndOptionsFrom(descriptionOrOptions); + super(http_exception_1.HttpException.createBody(objectOrError, description, http_status_enum_1.HttpStatus.MISDIRECTED), http_status_enum_1.HttpStatus.MISDIRECTED, httpExceptionOptions); + } +} +exports.MisdirectedException = MisdirectedException; diff --git a/node_modules/@nestjs/common/exceptions/not-acceptable.exception.d.ts b/node_modules/@nestjs/common/exceptions/not-acceptable.exception.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8a737efd4c5532d1a3008b81dc2808f4bb776827 --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/not-acceptable.exception.d.ts @@ -0,0 +1,35 @@ +import { HttpException, HttpExceptionOptions } from './http.exception'; +/** + * Defines an HTTP exception for *Not Acceptable* type errors. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +export declare class NotAcceptableException extends HttpException { + /** + * Instantiate a `NotAcceptableException` Exception. + * + * @example + * `throw new NotAcceptableException()` + * + * @usageNotes + * The HTTP response status code will be 406. + * - The `objectOrError` argument defines the JSON response body or the message string. + * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause. + * + * By default, the JSON response body contains two properties: + * - `statusCode`: this will be the value 406. + * - `error`: the string `'Not Acceptable'` by default; override this by supplying + * a string in the `error` parameter. + * + * If the parameter `objectOrError` is a string, the response body will contain an + * additional property, `error`, with a short description of the HTTP error. To override the + * entire JSON response body, pass an object instead. Nest will serialize the object + * and return it as the JSON response body. + * + * @param objectOrError string or object describing the error condition. + * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause + */ + constructor(objectOrError?: any, descriptionOrOptions?: string | HttpExceptionOptions); +} diff --git a/node_modules/@nestjs/common/exceptions/not-acceptable.exception.js b/node_modules/@nestjs/common/exceptions/not-acceptable.exception.js new file mode 100644 index 0000000000000000000000000000000000000000..a7c3212f6c931bdb69a68efc7ab805249a84d414 --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/not-acceptable.exception.js @@ -0,0 +1,43 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NotAcceptableException = void 0; +const http_status_enum_1 = require("../enums/http-status.enum"); +const http_exception_1 = require("./http.exception"); +/** + * Defines an HTTP exception for *Not Acceptable* type errors. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +class NotAcceptableException extends http_exception_1.HttpException { + /** + * Instantiate a `NotAcceptableException` Exception. + * + * @example + * `throw new NotAcceptableException()` + * + * @usageNotes + * The HTTP response status code will be 406. + * - The `objectOrError` argument defines the JSON response body or the message string. + * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause. + * + * By default, the JSON response body contains two properties: + * - `statusCode`: this will be the value 406. + * - `error`: the string `'Not Acceptable'` by default; override this by supplying + * a string in the `error` parameter. + * + * If the parameter `objectOrError` is a string, the response body will contain an + * additional property, `error`, with a short description of the HTTP error. To override the + * entire JSON response body, pass an object instead. Nest will serialize the object + * and return it as the JSON response body. + * + * @param objectOrError string or object describing the error condition. + * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause + */ + constructor(objectOrError, descriptionOrOptions = 'Not Acceptable') { + const { description, httpExceptionOptions } = http_exception_1.HttpException.extractDescriptionAndOptionsFrom(descriptionOrOptions); + super(http_exception_1.HttpException.createBody(objectOrError, description, http_status_enum_1.HttpStatus.NOT_ACCEPTABLE), http_status_enum_1.HttpStatus.NOT_ACCEPTABLE, httpExceptionOptions); + } +} +exports.NotAcceptableException = NotAcceptableException; diff --git a/node_modules/@nestjs/common/exceptions/not-found.exception.d.ts b/node_modules/@nestjs/common/exceptions/not-found.exception.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7ac89c9453934c285cde64252bf8f0d9e4a5fe2e --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/not-found.exception.d.ts @@ -0,0 +1,35 @@ +import { HttpException, HttpExceptionOptions } from './http.exception'; +/** + * Defines an HTTP exception for *Not Found* type errors. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +export declare class NotFoundException extends HttpException { + /** + * Instantiate a `NotFoundException` Exception. + * + * @example + * `throw new NotFoundException()` + * + * @usageNotes + * The HTTP response status code will be 404. + * - The `objectOrError` argument defines the JSON response body or the message string. + * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause. + * + * By default, the JSON response body contains two properties: + * - `statusCode`: this will be the value 404. + * - `message`: the string `'Not Found'` by default; override this by supplying + * a string in the `objectOrError` parameter. + * + * If the parameter `objectOrError` is a string, the response body will contain an + * additional property, `error`, with a short description of the HTTP error. To override the + * entire JSON response body, pass an object instead. Nest will serialize the object + * and return it as the JSON response body. + * + * @param objectOrError string or object describing the error condition. + * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause + */ + constructor(objectOrError?: any, descriptionOrOptions?: string | HttpExceptionOptions); +} diff --git a/node_modules/@nestjs/common/exceptions/not-found.exception.js b/node_modules/@nestjs/common/exceptions/not-found.exception.js new file mode 100644 index 0000000000000000000000000000000000000000..bce036df929e7b784edfe6649e004388d72582a8 --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/not-found.exception.js @@ -0,0 +1,43 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NotFoundException = void 0; +const http_status_enum_1 = require("../enums/http-status.enum"); +const http_exception_1 = require("./http.exception"); +/** + * Defines an HTTP exception for *Not Found* type errors. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +class NotFoundException extends http_exception_1.HttpException { + /** + * Instantiate a `NotFoundException` Exception. + * + * @example + * `throw new NotFoundException()` + * + * @usageNotes + * The HTTP response status code will be 404. + * - The `objectOrError` argument defines the JSON response body or the message string. + * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause. + * + * By default, the JSON response body contains two properties: + * - `statusCode`: this will be the value 404. + * - `message`: the string `'Not Found'` by default; override this by supplying + * a string in the `objectOrError` parameter. + * + * If the parameter `objectOrError` is a string, the response body will contain an + * additional property, `error`, with a short description of the HTTP error. To override the + * entire JSON response body, pass an object instead. Nest will serialize the object + * and return it as the JSON response body. + * + * @param objectOrError string or object describing the error condition. + * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause + */ + constructor(objectOrError, descriptionOrOptions = 'Not Found') { + const { description, httpExceptionOptions } = http_exception_1.HttpException.extractDescriptionAndOptionsFrom(descriptionOrOptions); + super(http_exception_1.HttpException.createBody(objectOrError, description, http_status_enum_1.HttpStatus.NOT_FOUND), http_status_enum_1.HttpStatus.NOT_FOUND, httpExceptionOptions); + } +} +exports.NotFoundException = NotFoundException; diff --git a/node_modules/@nestjs/common/exceptions/not-implemented.exception.d.ts b/node_modules/@nestjs/common/exceptions/not-implemented.exception.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..65b4c8a26a47d5d71fcbd0b796d46e2181b1204c --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/not-implemented.exception.d.ts @@ -0,0 +1,35 @@ +import { HttpException, HttpExceptionOptions } from './http.exception'; +/** + * Defines an HTTP exception for *Not Implemented* type errors. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +export declare class NotImplementedException extends HttpException { + /** + * Instantiate a `NotImplementedException` Exception. + * + * @example + * `throw new NotImplementedException()` + * + * @usageNotes + * The HTTP response status code will be 501. + * - The `objectOrError` argument defines the JSON response body or the message string. + * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause. + * + * By default, the JSON response body contains two properties: + * - `statusCode`: this will be the value 501. + * - `message`: the string `'Not Implemented'` by default; override this by supplying + * a string in the `objectOrError` parameter. + * + * If the parameter `objectOrError` is a string, the response body will contain an + * additional property, `error`, with a short description of the HTTP error. To override the + * entire JSON response body, pass an object instead. Nest will serialize the object + * and return it as the JSON response body. + * + * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause + * @param error a short description of the HTTP error. + */ + constructor(objectOrError?: any, descriptionOrOptions?: string | HttpExceptionOptions); +} diff --git a/node_modules/@nestjs/common/exceptions/not-implemented.exception.js b/node_modules/@nestjs/common/exceptions/not-implemented.exception.js new file mode 100644 index 0000000000000000000000000000000000000000..c1b2fd868d203cb8817bceec368a33bbc43ba0b9 --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/not-implemented.exception.js @@ -0,0 +1,43 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NotImplementedException = void 0; +const http_status_enum_1 = require("../enums/http-status.enum"); +const http_exception_1 = require("./http.exception"); +/** + * Defines an HTTP exception for *Not Implemented* type errors. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +class NotImplementedException extends http_exception_1.HttpException { + /** + * Instantiate a `NotImplementedException` Exception. + * + * @example + * `throw new NotImplementedException()` + * + * @usageNotes + * The HTTP response status code will be 501. + * - The `objectOrError` argument defines the JSON response body or the message string. + * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause. + * + * By default, the JSON response body contains two properties: + * - `statusCode`: this will be the value 501. + * - `message`: the string `'Not Implemented'` by default; override this by supplying + * a string in the `objectOrError` parameter. + * + * If the parameter `objectOrError` is a string, the response body will contain an + * additional property, `error`, with a short description of the HTTP error. To override the + * entire JSON response body, pass an object instead. Nest will serialize the object + * and return it as the JSON response body. + * + * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause + * @param error a short description of the HTTP error. + */ + constructor(objectOrError, descriptionOrOptions = 'Not Implemented') { + const { description, httpExceptionOptions } = http_exception_1.HttpException.extractDescriptionAndOptionsFrom(descriptionOrOptions); + super(http_exception_1.HttpException.createBody(objectOrError, description, http_status_enum_1.HttpStatus.NOT_IMPLEMENTED), http_status_enum_1.HttpStatus.NOT_IMPLEMENTED, httpExceptionOptions); + } +} +exports.NotImplementedException = NotImplementedException; diff --git a/node_modules/@nestjs/common/exceptions/payload-too-large.exception.d.ts b/node_modules/@nestjs/common/exceptions/payload-too-large.exception.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d944883b883773d130a67fc0115c34a083751891 --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/payload-too-large.exception.d.ts @@ -0,0 +1,35 @@ +import { HttpException, HttpExceptionOptions } from './http.exception'; +/** + * Defines an HTTP exception for *Payload Too Large* type errors. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +export declare class PayloadTooLargeException extends HttpException { + /** + * Instantiate a `PayloadTooLargeException` Exception. + * + * @example + * `throw new PayloadTooLargeException()` + * + * @usageNotes + * The HTTP response status code will be 413. + * - The `objectOrError` argument defines the JSON response body or the message string. + * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause. + * + * By default, the JSON response body contains two properties: + * - `statusCode`: this will be the value 413. + * - `message`: the string `'Payload Too Large'` by default; override this by supplying + * a string in the `objectOrError` parameter. + * + * If the parameter `objectOrError` is a string, the response body will contain an + * additional property, `error`, with a short description of the HTTP error. To override the + * entire JSON response body, pass an object instead. Nest will serialize the object + * and return it as the JSON response body. + * + * @param objectOrError string or object describing the error condition. + * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause + */ + constructor(objectOrError?: any, descriptionOrOptions?: string | HttpExceptionOptions); +} diff --git a/node_modules/@nestjs/common/exceptions/payload-too-large.exception.js b/node_modules/@nestjs/common/exceptions/payload-too-large.exception.js new file mode 100644 index 0000000000000000000000000000000000000000..7368944567751476728cdcf59b21ae8ce3716c55 --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/payload-too-large.exception.js @@ -0,0 +1,43 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PayloadTooLargeException = void 0; +const http_status_enum_1 = require("../enums/http-status.enum"); +const http_exception_1 = require("./http.exception"); +/** + * Defines an HTTP exception for *Payload Too Large* type errors. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +class PayloadTooLargeException extends http_exception_1.HttpException { + /** + * Instantiate a `PayloadTooLargeException` Exception. + * + * @example + * `throw new PayloadTooLargeException()` + * + * @usageNotes + * The HTTP response status code will be 413. + * - The `objectOrError` argument defines the JSON response body or the message string. + * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause. + * + * By default, the JSON response body contains two properties: + * - `statusCode`: this will be the value 413. + * - `message`: the string `'Payload Too Large'` by default; override this by supplying + * a string in the `objectOrError` parameter. + * + * If the parameter `objectOrError` is a string, the response body will contain an + * additional property, `error`, with a short description of the HTTP error. To override the + * entire JSON response body, pass an object instead. Nest will serialize the object + * and return it as the JSON response body. + * + * @param objectOrError string or object describing the error condition. + * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause + */ + constructor(objectOrError, descriptionOrOptions = 'Payload Too Large') { + const { description, httpExceptionOptions } = http_exception_1.HttpException.extractDescriptionAndOptionsFrom(descriptionOrOptions); + super(http_exception_1.HttpException.createBody(objectOrError, description, http_status_enum_1.HttpStatus.PAYLOAD_TOO_LARGE), http_status_enum_1.HttpStatus.PAYLOAD_TOO_LARGE, httpExceptionOptions); + } +} +exports.PayloadTooLargeException = PayloadTooLargeException; diff --git a/node_modules/@nestjs/common/exceptions/precondition-failed.exception.d.ts b/node_modules/@nestjs/common/exceptions/precondition-failed.exception.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..057c513064d25c861366fdc73e00e51d5766cac8 --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/precondition-failed.exception.d.ts @@ -0,0 +1,35 @@ +import { HttpException, HttpExceptionOptions } from './http.exception'; +/** + * Defines an HTTP exception for *Precondition Failed* type errors. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +export declare class PreconditionFailedException extends HttpException { + /** + * Instantiate a `PreconditionFailedException` Exception. + * + * @example + * `throw new PreconditionFailedException()` + * + * @usageNotes + * The HTTP response status code will be 412. + * - The `objectOrError` argument defines the JSON response body or the message string. + * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause. + * + * By default, the JSON response body contains two properties: + * - `statusCode`: this will be the value 412. + * - `message`: the string `'Precondition Failed'` by default; override this by supplying + * a string in the `objectOrError` parameter. + * + * If the parameter `objectOrError` is a string, the response body will contain an + * additional property, `error`, with a short description of the HTTP error. To override the + * entire JSON response body, pass an object instead. Nest will serialize the object + * and return it as the JSON response body. + * + * @param objectOrError string or object describing the error condition. + * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause + */ + constructor(objectOrError?: any, descriptionOrOptions?: string | HttpExceptionOptions); +} diff --git a/node_modules/@nestjs/common/exceptions/precondition-failed.exception.js b/node_modules/@nestjs/common/exceptions/precondition-failed.exception.js new file mode 100644 index 0000000000000000000000000000000000000000..d3696adc1079dffb318e16c1ad0a561b336f3370 --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/precondition-failed.exception.js @@ -0,0 +1,43 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PreconditionFailedException = void 0; +const http_status_enum_1 = require("../enums/http-status.enum"); +const http_exception_1 = require("./http.exception"); +/** + * Defines an HTTP exception for *Precondition Failed* type errors. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +class PreconditionFailedException extends http_exception_1.HttpException { + /** + * Instantiate a `PreconditionFailedException` Exception. + * + * @example + * `throw new PreconditionFailedException()` + * + * @usageNotes + * The HTTP response status code will be 412. + * - The `objectOrError` argument defines the JSON response body or the message string. + * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause. + * + * By default, the JSON response body contains two properties: + * - `statusCode`: this will be the value 412. + * - `message`: the string `'Precondition Failed'` by default; override this by supplying + * a string in the `objectOrError` parameter. + * + * If the parameter `objectOrError` is a string, the response body will contain an + * additional property, `error`, with a short description of the HTTP error. To override the + * entire JSON response body, pass an object instead. Nest will serialize the object + * and return it as the JSON response body. + * + * @param objectOrError string or object describing the error condition. + * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause + */ + constructor(objectOrError, descriptionOrOptions = 'Precondition Failed') { + const { description, httpExceptionOptions } = http_exception_1.HttpException.extractDescriptionAndOptionsFrom(descriptionOrOptions); + super(http_exception_1.HttpException.createBody(objectOrError, description, http_status_enum_1.HttpStatus.PRECONDITION_FAILED), http_status_enum_1.HttpStatus.PRECONDITION_FAILED, httpExceptionOptions); + } +} +exports.PreconditionFailedException = PreconditionFailedException; diff --git a/node_modules/@nestjs/common/exceptions/request-timeout.exception.d.ts b/node_modules/@nestjs/common/exceptions/request-timeout.exception.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2c77b5fc1b87fa4a1e1b191bf650e7b003174d8a --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/request-timeout.exception.d.ts @@ -0,0 +1,35 @@ +import { HttpException, HttpExceptionOptions } from './http.exception'; +/** + * Defines an HTTP exception for *Request Timeout* type errors. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +export declare class RequestTimeoutException extends HttpException { + /** + * Instantiate a `RequestTimeoutException` Exception. + * + * @example + * `throw new RequestTimeoutException()` + * + * @usageNotes + * The HTTP response status code will be 408. + * - The `objectOrError` argument defines the JSON response body or the message string. + * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause. + * + * By default, the JSON response body contains two properties: + * - `statusCode`: this will be the value 408. + * - `message`: the string `'Request Timeout'` by default; override this by supplying + * a string in the `objectOrError` parameter. + * + * If the parameter `objectOrError` is a string, the response body will contain an + * additional property, `error`, with a short description of the HTTP error. To override the + * entire JSON response body, pass an object instead. Nest will serialize the object + * and return it as the JSON response body. + * + * @param objectOrError string or object describing the error condition. + * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause + */ + constructor(objectOrError?: any, descriptionOrOptions?: string | HttpExceptionOptions); +} diff --git a/node_modules/@nestjs/common/exceptions/request-timeout.exception.js b/node_modules/@nestjs/common/exceptions/request-timeout.exception.js new file mode 100644 index 0000000000000000000000000000000000000000..b0bb23f025702e738ca986a0e1e97f7163ebdbf8 --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/request-timeout.exception.js @@ -0,0 +1,43 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.RequestTimeoutException = void 0; +const http_status_enum_1 = require("../enums/http-status.enum"); +const http_exception_1 = require("./http.exception"); +/** + * Defines an HTTP exception for *Request Timeout* type errors. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +class RequestTimeoutException extends http_exception_1.HttpException { + /** + * Instantiate a `RequestTimeoutException` Exception. + * + * @example + * `throw new RequestTimeoutException()` + * + * @usageNotes + * The HTTP response status code will be 408. + * - The `objectOrError` argument defines the JSON response body or the message string. + * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause. + * + * By default, the JSON response body contains two properties: + * - `statusCode`: this will be the value 408. + * - `message`: the string `'Request Timeout'` by default; override this by supplying + * a string in the `objectOrError` parameter. + * + * If the parameter `objectOrError` is a string, the response body will contain an + * additional property, `error`, with a short description of the HTTP error. To override the + * entire JSON response body, pass an object instead. Nest will serialize the object + * and return it as the JSON response body. + * + * @param objectOrError string or object describing the error condition. + * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause + */ + constructor(objectOrError, descriptionOrOptions = 'Request Timeout') { + const { description, httpExceptionOptions } = http_exception_1.HttpException.extractDescriptionAndOptionsFrom(descriptionOrOptions); + super(http_exception_1.HttpException.createBody(objectOrError, description, http_status_enum_1.HttpStatus.REQUEST_TIMEOUT), http_status_enum_1.HttpStatus.REQUEST_TIMEOUT, httpExceptionOptions); + } +} +exports.RequestTimeoutException = RequestTimeoutException; diff --git a/node_modules/@nestjs/common/exceptions/service-unavailable.exception.d.ts b/node_modules/@nestjs/common/exceptions/service-unavailable.exception.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5160fbd5dfa1c7440f6bd4f775bdc3e4e3b90fe2 --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/service-unavailable.exception.d.ts @@ -0,0 +1,35 @@ +import { HttpException, HttpExceptionOptions } from './http.exception'; +/** + * Defines an HTTP exception for *Service Unavailable* type errors. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +export declare class ServiceUnavailableException extends HttpException { + /** + * Instantiate a `ServiceUnavailableException` Exception. + * + * @example + * `throw new ServiceUnavailableException()` + * + * @usageNotes + * The HTTP response status code will be 503. + * - The `objectOrError` argument defines the JSON response body or the message string. + * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause. + * + * By default, the JSON response body contains two properties: + * - `statusCode`: this will be the value 503. + * - `message`: the string `'Service Unavailable'` by default; override this by supplying + * a string in the `objectOrError` parameter. + * + * If the parameter `objectOrError` is a string, the response body will contain an + * additional property, `error`, with a short description of the HTTP error. To override the + * entire JSON response body, pass an object instead. Nest will serialize the object + * and return it as the JSON response body. + * + * @param objectOrError string or object describing the error condition. + * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause + */ + constructor(objectOrError?: any, descriptionOrOptions?: string | HttpExceptionOptions); +} diff --git a/node_modules/@nestjs/common/exceptions/service-unavailable.exception.js b/node_modules/@nestjs/common/exceptions/service-unavailable.exception.js new file mode 100644 index 0000000000000000000000000000000000000000..088a9b3fb1847a54c822ca3362535a7cc090f573 --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/service-unavailable.exception.js @@ -0,0 +1,43 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ServiceUnavailableException = void 0; +const http_status_enum_1 = require("../enums/http-status.enum"); +const http_exception_1 = require("./http.exception"); +/** + * Defines an HTTP exception for *Service Unavailable* type errors. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +class ServiceUnavailableException extends http_exception_1.HttpException { + /** + * Instantiate a `ServiceUnavailableException` Exception. + * + * @example + * `throw new ServiceUnavailableException()` + * + * @usageNotes + * The HTTP response status code will be 503. + * - The `objectOrError` argument defines the JSON response body or the message string. + * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause. + * + * By default, the JSON response body contains two properties: + * - `statusCode`: this will be the value 503. + * - `message`: the string `'Service Unavailable'` by default; override this by supplying + * a string in the `objectOrError` parameter. + * + * If the parameter `objectOrError` is a string, the response body will contain an + * additional property, `error`, with a short description of the HTTP error. To override the + * entire JSON response body, pass an object instead. Nest will serialize the object + * and return it as the JSON response body. + * + * @param objectOrError string or object describing the error condition. + * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause + */ + constructor(objectOrError, descriptionOrOptions = 'Service Unavailable') { + const { description, httpExceptionOptions } = http_exception_1.HttpException.extractDescriptionAndOptionsFrom(descriptionOrOptions); + super(http_exception_1.HttpException.createBody(objectOrError, description, http_status_enum_1.HttpStatus.SERVICE_UNAVAILABLE), http_status_enum_1.HttpStatus.SERVICE_UNAVAILABLE, httpExceptionOptions); + } +} +exports.ServiceUnavailableException = ServiceUnavailableException; diff --git a/node_modules/@nestjs/common/exceptions/unauthorized.exception.d.ts b/node_modules/@nestjs/common/exceptions/unauthorized.exception.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2755fe04b0446b6a0f0f639d3dc539e59a3f30d1 --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/unauthorized.exception.d.ts @@ -0,0 +1,35 @@ +import { HttpException, HttpExceptionOptions } from './http.exception'; +/** + * Defines an HTTP exception for *Unauthorized* type errors. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +export declare class UnauthorizedException extends HttpException { + /** + * Instantiate an `UnauthorizedException` Exception. + * + * @example + * `throw new UnauthorizedException()` + * + * @usageNotes + * The HTTP response status code will be 401. + * - The `objectOrError` argument defines the JSON response body or the message string. + * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause. + * + * By default, the JSON response body contains two properties: + * - `statusCode`: this will be the value 401. + * - `message`: the string `'Unauthorized'` by default; override this by supplying + * a string in the `objectOrError` parameter. + * + * If the parameter `objectOrError` is a string, the response body will contain an + * additional property, `error`, with a short description of the HTTP error. To override the + * entire JSON response body, pass an object instead. Nest will serialize the object + * and return it as the JSON response body. + * + * @param objectOrError string or object describing the error condition. + * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause + */ + constructor(objectOrError?: any, descriptionOrOptions?: string | HttpExceptionOptions); +} diff --git a/node_modules/@nestjs/common/exceptions/unauthorized.exception.js b/node_modules/@nestjs/common/exceptions/unauthorized.exception.js new file mode 100644 index 0000000000000000000000000000000000000000..ccfbc037eced799f9d0b9168e31a27e86089fd68 --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/unauthorized.exception.js @@ -0,0 +1,43 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.UnauthorizedException = void 0; +const http_status_enum_1 = require("../enums/http-status.enum"); +const http_exception_1 = require("./http.exception"); +/** + * Defines an HTTP exception for *Unauthorized* type errors. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +class UnauthorizedException extends http_exception_1.HttpException { + /** + * Instantiate an `UnauthorizedException` Exception. + * + * @example + * `throw new UnauthorizedException()` + * + * @usageNotes + * The HTTP response status code will be 401. + * - The `objectOrError` argument defines the JSON response body or the message string. + * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause. + * + * By default, the JSON response body contains two properties: + * - `statusCode`: this will be the value 401. + * - `message`: the string `'Unauthorized'` by default; override this by supplying + * a string in the `objectOrError` parameter. + * + * If the parameter `objectOrError` is a string, the response body will contain an + * additional property, `error`, with a short description of the HTTP error. To override the + * entire JSON response body, pass an object instead. Nest will serialize the object + * and return it as the JSON response body. + * + * @param objectOrError string or object describing the error condition. + * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause + */ + constructor(objectOrError, descriptionOrOptions = 'Unauthorized') { + const { description, httpExceptionOptions } = http_exception_1.HttpException.extractDescriptionAndOptionsFrom(descriptionOrOptions); + super(http_exception_1.HttpException.createBody(objectOrError, description, http_status_enum_1.HttpStatus.UNAUTHORIZED), http_status_enum_1.HttpStatus.UNAUTHORIZED, httpExceptionOptions); + } +} +exports.UnauthorizedException = UnauthorizedException; diff --git a/node_modules/@nestjs/common/exceptions/unprocessable-entity.exception.d.ts b/node_modules/@nestjs/common/exceptions/unprocessable-entity.exception.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..02e81295ce26b397e77262d4df5b196dd0ef5d8d --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/unprocessable-entity.exception.d.ts @@ -0,0 +1,35 @@ +import { HttpException, HttpExceptionOptions } from './http.exception'; +/** + * Defines an HTTP exception for *Unprocessable Entity* type errors. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +export declare class UnprocessableEntityException extends HttpException { + /** + * Instantiate an `UnprocessableEntityException` Exception. + * + * @example + * `throw new UnprocessableEntityException()` + * + * @usageNotes + * The HTTP response status code will be 422. + * - The `objectOrError` argument defines the JSON response body or the message string. + * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause. + * + * By default, the JSON response body contains two properties: + * - `statusCode`: this will be the value 422. + * - `message`: the string `'Unprocessable Entity'` by default; override this by supplying + * a string in the `objectOrError` parameter. + * + * If the parameter `objectOrError` is a string, the response body will contain an + * additional property, `error`, with a short description of the HTTP error. To override the + * entire JSON response body, pass an object instead. Nest will serialize the object + * and return it as the JSON response body. + * + * @param objectOrError string or object describing the error condition. + * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause + */ + constructor(objectOrError?: any, descriptionOrOptions?: string | HttpExceptionOptions); +} diff --git a/node_modules/@nestjs/common/exceptions/unprocessable-entity.exception.js b/node_modules/@nestjs/common/exceptions/unprocessable-entity.exception.js new file mode 100644 index 0000000000000000000000000000000000000000..c6713dee1c73d8ce94a4f7cceea1cb7f73f3834a --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/unprocessable-entity.exception.js @@ -0,0 +1,43 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.UnprocessableEntityException = void 0; +const http_status_enum_1 = require("../enums/http-status.enum"); +const http_exception_1 = require("./http.exception"); +/** + * Defines an HTTP exception for *Unprocessable Entity* type errors. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +class UnprocessableEntityException extends http_exception_1.HttpException { + /** + * Instantiate an `UnprocessableEntityException` Exception. + * + * @example + * `throw new UnprocessableEntityException()` + * + * @usageNotes + * The HTTP response status code will be 422. + * - The `objectOrError` argument defines the JSON response body or the message string. + * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause. + * + * By default, the JSON response body contains two properties: + * - `statusCode`: this will be the value 422. + * - `message`: the string `'Unprocessable Entity'` by default; override this by supplying + * a string in the `objectOrError` parameter. + * + * If the parameter `objectOrError` is a string, the response body will contain an + * additional property, `error`, with a short description of the HTTP error. To override the + * entire JSON response body, pass an object instead. Nest will serialize the object + * and return it as the JSON response body. + * + * @param objectOrError string or object describing the error condition. + * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause + */ + constructor(objectOrError, descriptionOrOptions = 'Unprocessable Entity') { + const { description, httpExceptionOptions } = http_exception_1.HttpException.extractDescriptionAndOptionsFrom(descriptionOrOptions); + super(http_exception_1.HttpException.createBody(objectOrError, description, http_status_enum_1.HttpStatus.UNPROCESSABLE_ENTITY), http_status_enum_1.HttpStatus.UNPROCESSABLE_ENTITY, httpExceptionOptions); + } +} +exports.UnprocessableEntityException = UnprocessableEntityException; diff --git a/node_modules/@nestjs/common/exceptions/unsupported-media-type.exception.d.ts b/node_modules/@nestjs/common/exceptions/unsupported-media-type.exception.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f9cd0c731caa513e68087fc6b8757c65c8a4076b --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/unsupported-media-type.exception.d.ts @@ -0,0 +1,35 @@ +import { HttpException, HttpExceptionOptions } from './http.exception'; +/** + * Defines an HTTP exception for *Unsupported Media Type* type errors. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +export declare class UnsupportedMediaTypeException extends HttpException { + /** + * Instantiate an `UnsupportedMediaTypeException` Exception. + * + * @example + * `throw new UnsupportedMediaTypeException()` + * + * @usageNotes + * The HTTP response status code will be 415. + * - The `objectOrError` argument defines the JSON response body or the message string. + * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause. + * + * By default, the JSON response body contains two properties: + * - `statusCode`: this will be the value 415. + * - `message`: the string `'Unsupported Media Type'` by default; override this by supplying + * a string in the `objectOrError` parameter. + * + * If the parameter `objectOrError` is a string, the response body will contain an + * additional property, `error`, with a short description of the HTTP error. To override the + * entire JSON response body, pass an object instead. Nest will serialize the object + * and return it as the JSON response body. + * + * @param objectOrError string or object describing the error condition. + * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause + */ + constructor(objectOrError?: any, descriptionOrOptions?: string | HttpExceptionOptions); +} diff --git a/node_modules/@nestjs/common/exceptions/unsupported-media-type.exception.js b/node_modules/@nestjs/common/exceptions/unsupported-media-type.exception.js new file mode 100644 index 0000000000000000000000000000000000000000..e85e7fc555d485989c16c1822836cd896b316ddd --- /dev/null +++ b/node_modules/@nestjs/common/exceptions/unsupported-media-type.exception.js @@ -0,0 +1,43 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.UnsupportedMediaTypeException = void 0; +const http_status_enum_1 = require("../enums/http-status.enum"); +const http_exception_1 = require("./http.exception"); +/** + * Defines an HTTP exception for *Unsupported Media Type* type errors. + * + * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions) + * + * @publicApi + */ +class UnsupportedMediaTypeException extends http_exception_1.HttpException { + /** + * Instantiate an `UnsupportedMediaTypeException` Exception. + * + * @example + * `throw new UnsupportedMediaTypeException()` + * + * @usageNotes + * The HTTP response status code will be 415. + * - The `objectOrError` argument defines the JSON response body or the message string. + * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause. + * + * By default, the JSON response body contains two properties: + * - `statusCode`: this will be the value 415. + * - `message`: the string `'Unsupported Media Type'` by default; override this by supplying + * a string in the `objectOrError` parameter. + * + * If the parameter `objectOrError` is a string, the response body will contain an + * additional property, `error`, with a short description of the HTTP error. To override the + * entire JSON response body, pass an object instead. Nest will serialize the object + * and return it as the JSON response body. + * + * @param objectOrError string or object describing the error condition. + * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause + */ + constructor(objectOrError, descriptionOrOptions = 'Unsupported Media Type') { + const { description, httpExceptionOptions } = http_exception_1.HttpException.extractDescriptionAndOptionsFrom(descriptionOrOptions); + super(http_exception_1.HttpException.createBody(objectOrError, description, http_status_enum_1.HttpStatus.UNSUPPORTED_MEDIA_TYPE), http_status_enum_1.HttpStatus.UNSUPPORTED_MEDIA_TYPE, httpExceptionOptions); + } +} +exports.UnsupportedMediaTypeException = UnsupportedMediaTypeException; diff --git a/node_modules/@nestjs/common/file-stream/index.d.ts b/node_modules/@nestjs/common/file-stream/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..75a39abefa3a91e63468eb979ffd1c7f8e6c46cd --- /dev/null +++ b/node_modules/@nestjs/common/file-stream/index.d.ts @@ -0,0 +1 @@ +export * from './streamable-file'; diff --git a/node_modules/@nestjs/common/file-stream/index.js b/node_modules/@nestjs/common/file-stream/index.js new file mode 100644 index 0000000000000000000000000000000000000000..4795e2c696728944a0c15c41f30bf65cadc10c7b --- /dev/null +++ b/node_modules/@nestjs/common/file-stream/index.js @@ -0,0 +1,4 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = require("tslib"); +tslib_1.__exportStar(require("./streamable-file"), exports); diff --git a/node_modules/@nestjs/common/file-stream/interfaces/index.d.ts b/node_modules/@nestjs/common/file-stream/interfaces/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9be413e21b41fa6b4ec10095796db0a3671d7c6d --- /dev/null +++ b/node_modules/@nestjs/common/file-stream/interfaces/index.d.ts @@ -0,0 +1,2 @@ +export * from './streamable-options.interface'; +export * from './streamable-handler-response.interface'; diff --git a/node_modules/@nestjs/common/file-stream/interfaces/index.js b/node_modules/@nestjs/common/file-stream/interfaces/index.js new file mode 100644 index 0000000000000000000000000000000000000000..5d18a949dbeb0d8bc8e594aaa61211f02336db2e --- /dev/null +++ b/node_modules/@nestjs/common/file-stream/interfaces/index.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = require("tslib"); +tslib_1.__exportStar(require("./streamable-options.interface"), exports); +tslib_1.__exportStar(require("./streamable-handler-response.interface"), exports); diff --git a/node_modules/@nestjs/common/file-stream/interfaces/streamable-handler-response.interface.d.ts b/node_modules/@nestjs/common/file-stream/interfaces/streamable-handler-response.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..36ad796e912e365ddbce7095f352e945de1df787 --- /dev/null +++ b/node_modules/@nestjs/common/file-stream/interfaces/streamable-handler-response.interface.d.ts @@ -0,0 +1,12 @@ +export interface StreamableHandlerResponse { + /** `true` if the connection is destroyed, `false` otherwise. */ + destroyed: boolean; + /** `true` if headers were sent, `false` otherwise. */ + headersSent: boolean; + /** The status code that will be sent to the client when the headers get flushed. */ + statusCode: number; + /** Sends the HTTP response. */ + send: (body: string) => void; + /** Signals to the server that all of the response headers and body have been sent. */ + end: () => void; +} diff --git a/node_modules/@nestjs/common/file-stream/interfaces/streamable-handler-response.interface.js b/node_modules/@nestjs/common/file-stream/interfaces/streamable-handler-response.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/file-stream/interfaces/streamable-handler-response.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/file-stream/interfaces/streamable-options.interface.d.ts b/node_modules/@nestjs/common/file-stream/interfaces/streamable-options.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b5fc863c393889cd016d0e07a20d29870759751a --- /dev/null +++ b/node_modules/@nestjs/common/file-stream/interfaces/streamable-options.interface.d.ts @@ -0,0 +1,22 @@ +/** + * Options for `StreamableFile` + * + * @see [Streaming files](https://docs.nestjs.com/techniques/streaming-files) + * + * @publicApi + */ +export interface StreamableFileOptions { + /** + * The value that will be used for the `Content-Type` response header. + * @default `"application/octet-stream"` + */ + type?: string; + /** + * The value that will be used for the `Content-Disposition` response header. + */ + disposition?: string | string[]; + /** + * The value that will be used for the `Content-Length` response header. + */ + length?: number; +} diff --git a/node_modules/@nestjs/common/file-stream/interfaces/streamable-options.interface.js b/node_modules/@nestjs/common/file-stream/interfaces/streamable-options.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/file-stream/interfaces/streamable-options.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/file-stream/streamable-file.d.ts b/node_modules/@nestjs/common/file-stream/streamable-file.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b385e7b555d9507ad01bc3ea91d77ffbe0ff560e --- /dev/null +++ b/node_modules/@nestjs/common/file-stream/streamable-file.d.ts @@ -0,0 +1,27 @@ +import { Readable } from 'stream'; +import { Logger } from '../services'; +import { StreamableFileOptions, StreamableHandlerResponse } from './interfaces'; +/** + * @see [Streaming files](https://docs.nestjs.com/techniques/streaming-files) + * + * @publicApi + */ +export declare class StreamableFile { + readonly options: StreamableFileOptions; + private readonly stream; + protected logger: Logger; + protected handleError: (err: Error, response: StreamableHandlerResponse) => void; + protected logError: (err: Error) => void; + constructor(buffer: Uint8Array, options?: StreamableFileOptions); + constructor(readable: Readable, options?: StreamableFileOptions); + getStream(): Readable; + getHeaders(): { + type: string; + disposition: string | string[] | undefined; + length: number | undefined; + }; + get errorHandler(): (err: Error, response: StreamableHandlerResponse) => void; + setErrorHandler(handler: (err: Error, response: StreamableHandlerResponse) => void): this; + get errorLogger(): (err: Error) => void; + setErrorLogger(handler: (err: Error) => void): this; +} diff --git a/node_modules/@nestjs/common/file-stream/streamable-file.js b/node_modules/@nestjs/common/file-stream/streamable-file.js new file mode 100644 index 0000000000000000000000000000000000000000..07cbf77d5a15dd4d49a065fe2b5d5cf281e8c4d2 --- /dev/null +++ b/node_modules/@nestjs/common/file-stream/streamable-file.js @@ -0,0 +1,68 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.StreamableFile = void 0; +const stream_1 = require("stream"); +const util_1 = require("util"); +const enums_1 = require("../enums"); +const services_1 = require("../services"); +const shared_utils_1 = require("../utils/shared.utils"); +/** + * @see [Streaming files](https://docs.nestjs.com/techniques/streaming-files) + * + * @publicApi + */ +class StreamableFile { + constructor(bufferOrReadStream, options = {}) { + this.options = options; + this.logger = new services_1.Logger('StreamableFile'); + this.handleError = (err, res) => { + if (res.destroyed) { + return; + } + if (res.headersSent) { + res.end(); + return; + } + res.statusCode = enums_1.HttpStatus.BAD_REQUEST; + res.send(err.message); + }; + this.logError = (err) => { + this.logger.error(err); + }; + if (util_1.types.isUint8Array(bufferOrReadStream)) { + this.stream = new stream_1.Readable(); + this.stream.push(bufferOrReadStream); + this.stream.push(null); + this.options.length ??= bufferOrReadStream.length; + } + else if (bufferOrReadStream.pipe && (0, shared_utils_1.isFunction)(bufferOrReadStream.pipe)) { + this.stream = bufferOrReadStream; + } + } + getStream() { + return this.stream; + } + getHeaders() { + const { type = 'application/octet-stream', disposition = undefined, length = undefined, } = this.options; + return { + type, + disposition, + length, + }; + } + get errorHandler() { + return this.handleError; + } + setErrorHandler(handler) { + this.handleError = handler; + return this; + } + get errorLogger() { + return this.logError; + } + setErrorLogger(handler) { + this.logError = handler; + return this; + } +} +exports.StreamableFile = StreamableFile; diff --git a/node_modules/@nestjs/common/index.d.ts b/node_modules/@nestjs/common/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..77ae696ac9811fea3da775d6673883c71fc1bdb9 --- /dev/null +++ b/node_modules/@nestjs/common/index.d.ts @@ -0,0 +1,11 @@ +import 'reflect-metadata'; +export * from './decorators'; +export * from './enums'; +export * from './exceptions'; +export * from './file-stream'; +export { Abstract, ArgumentMetadata, ArgumentsHost, BeforeApplicationShutdown, CallHandler, CanActivate, ClassProvider, ContextType, DynamicModule, ExceptionFilter, ExecutionContext, ExistingProvider, FactoryProvider, ForwardReference, HttpServer, HttpExceptionBody, HttpExceptionBodyMessage, HttpRedirectResponse, INestApplication, INestApplicationContext, INestMicroservice, InjectionToken, IntrospectionResult, MessageEvent, MiddlewareConsumer, ModuleMetadata, NestApplicationOptions, NestHybridApplicationOptions, NestInterceptor, NestMiddleware, NestModule, OnApplicationBootstrap, OnApplicationShutdown, OnModuleDestroy, OnModuleInit, OptionalFactoryDependency, Paramtype, PipeTransform, Provider, RawBodyRequest, RpcExceptionFilter, Scope, ScopeOptions, Type, ValidationError, ValueProvider, VersioningOptions, VERSION_NEUTRAL, WebSocketAdapter, WsExceptionFilter, WsMessageHandler, } from './interfaces'; +export * from './module-utils'; +export * from './pipes'; +export * from './serializer'; +export * from './services'; +export * from './utils'; diff --git a/node_modules/@nestjs/common/index.js b/node_modules/@nestjs/common/index.js new file mode 100644 index 0000000000000000000000000000000000000000..498cf11a603222e2782e3de12cf67dd027b797db --- /dev/null +++ b/node_modules/@nestjs/common/index.js @@ -0,0 +1,23 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.VERSION_NEUTRAL = exports.Scope = void 0; +const tslib_1 = require("tslib"); +/* + * Nest @common + * Copyright(c) 2017 - 2025 Kamil Mysliwiec + * https://nestjs.com + * MIT Licensed + */ +require("reflect-metadata"); +tslib_1.__exportStar(require("./decorators"), exports); +tslib_1.__exportStar(require("./enums"), exports); +tslib_1.__exportStar(require("./exceptions"), exports); +tslib_1.__exportStar(require("./file-stream"), exports); +var interfaces_1 = require("./interfaces"); +Object.defineProperty(exports, "Scope", { enumerable: true, get: function () { return interfaces_1.Scope; } }); +Object.defineProperty(exports, "VERSION_NEUTRAL", { enumerable: true, get: function () { return interfaces_1.VERSION_NEUTRAL; } }); +tslib_1.__exportStar(require("./module-utils"), exports); +tslib_1.__exportStar(require("./pipes"), exports); +tslib_1.__exportStar(require("./serializer"), exports); +tslib_1.__exportStar(require("./services"), exports); +tslib_1.__exportStar(require("./utils"), exports); diff --git a/node_modules/@nestjs/common/interfaces/abstract.interface.d.ts b/node_modules/@nestjs/common/interfaces/abstract.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..be7a40b08eeab84e5f2c380287d1175b9c2cb37e --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/abstract.interface.d.ts @@ -0,0 +1,3 @@ +export interface Abstract extends Function { + prototype: T; +} diff --git a/node_modules/@nestjs/common/interfaces/abstract.interface.js b/node_modules/@nestjs/common/interfaces/abstract.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/abstract.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/controllers/controller-metadata.interface.d.ts b/node_modules/@nestjs/common/interfaces/controllers/controller-metadata.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b816bf9aafbb47622030e0274fdacbd5c4d362bb --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/controllers/controller-metadata.interface.d.ts @@ -0,0 +1,3 @@ +export interface ControllerMetadata { + path?: string; +} diff --git a/node_modules/@nestjs/common/interfaces/controllers/controller-metadata.interface.js b/node_modules/@nestjs/common/interfaces/controllers/controller-metadata.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/controllers/controller-metadata.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/controllers/controller.interface.d.ts b/node_modules/@nestjs/common/interfaces/controllers/controller.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b937a659faeca60b31369bb5f09e6b11de9ef49b --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/controllers/controller.interface.d.ts @@ -0,0 +1 @@ +export type Controller = object; diff --git a/node_modules/@nestjs/common/interfaces/controllers/controller.interface.js b/node_modules/@nestjs/common/interfaces/controllers/controller.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/controllers/controller.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/controllers/index.d.ts b/node_modules/@nestjs/common/interfaces/controllers/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4bd60924b00e25d1816acbd96953273fc5787f5d --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/controllers/index.d.ts @@ -0,0 +1,2 @@ +export * from './controller-metadata.interface'; +export * from './controller.interface'; diff --git a/node_modules/@nestjs/common/interfaces/controllers/index.js b/node_modules/@nestjs/common/interfaces/controllers/index.js new file mode 100644 index 0000000000000000000000000000000000000000..aa33c74a0ad4ec89e6a22852d5302fe5b25a51ca --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/controllers/index.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = require("tslib"); +tslib_1.__exportStar(require("./controller-metadata.interface"), exports); +tslib_1.__exportStar(require("./controller.interface"), exports); diff --git a/node_modules/@nestjs/common/interfaces/exceptions/exception-filter-metadata.interface.d.ts b/node_modules/@nestjs/common/interfaces/exceptions/exception-filter-metadata.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..75700d5c6b0aa478471cae20700a61f6a5294764 --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/exceptions/exception-filter-metadata.interface.d.ts @@ -0,0 +1,6 @@ +import { ExceptionFilter } from './exception-filter.interface'; +import { Type } from '../type.interface'; +export interface ExceptionFilterMetadata { + func: ExceptionFilter['catch']; + exceptionMetatypes: Type[]; +} diff --git a/node_modules/@nestjs/common/interfaces/exceptions/exception-filter-metadata.interface.js b/node_modules/@nestjs/common/interfaces/exceptions/exception-filter-metadata.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/exceptions/exception-filter-metadata.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/exceptions/exception-filter.interface.d.ts b/node_modules/@nestjs/common/interfaces/exceptions/exception-filter.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e02baed7cfed60ec6d54a91f32ca4fb7528bfdaf --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/exceptions/exception-filter.interface.d.ts @@ -0,0 +1,18 @@ +import { ArgumentsHost } from '../features/arguments-host.interface'; +/** + * Interface describing implementation of an exception filter. + * + * @see [Exception Filters](https://docs.nestjs.com/exception-filters) + * + * @publicApi + */ +export interface ExceptionFilter { + /** + * Method to implement a custom exception filter. + * + * @param exception the class of the exception being handled + * @param host used to access an array of arguments for + * the in-flight request + */ + catch(exception: T, host: ArgumentsHost): any; +} diff --git a/node_modules/@nestjs/common/interfaces/exceptions/exception-filter.interface.js b/node_modules/@nestjs/common/interfaces/exceptions/exception-filter.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/exceptions/exception-filter.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/exceptions/index.d.ts b/node_modules/@nestjs/common/interfaces/exceptions/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f35002c2e21166e6c168b45fcc71f5ba0794d144 --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/exceptions/index.d.ts @@ -0,0 +1,5 @@ +export * from './exception-filter-metadata.interface'; +export * from './exception-filter.interface'; +export * from './rpc-exception-filter-metadata.interface'; +export * from './rpc-exception-filter.interface'; +export * from './ws-exception-filter.interface'; diff --git a/node_modules/@nestjs/common/interfaces/exceptions/index.js b/node_modules/@nestjs/common/interfaces/exceptions/index.js new file mode 100644 index 0000000000000000000000000000000000000000..079791a2f5499d8e5ce5821b9fbaca886946ab9f --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/exceptions/index.js @@ -0,0 +1,8 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = require("tslib"); +tslib_1.__exportStar(require("./exception-filter-metadata.interface"), exports); +tslib_1.__exportStar(require("./exception-filter.interface"), exports); +tslib_1.__exportStar(require("./rpc-exception-filter-metadata.interface"), exports); +tslib_1.__exportStar(require("./rpc-exception-filter.interface"), exports); +tslib_1.__exportStar(require("./ws-exception-filter.interface"), exports); diff --git a/node_modules/@nestjs/common/interfaces/exceptions/rpc-exception-filter-metadata.interface.d.ts b/node_modules/@nestjs/common/interfaces/exceptions/rpc-exception-filter-metadata.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8b17fb93c49998e1e6722fca197420bc307581ab --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/exceptions/rpc-exception-filter-metadata.interface.d.ts @@ -0,0 +1,6 @@ +import { RpcExceptionFilter } from './rpc-exception-filter.interface'; +import { Type } from '../type.interface'; +export interface RpcExceptionFilterMetadata { + func: RpcExceptionFilter['catch']; + exceptionMetatypes: Type[]; +} diff --git a/node_modules/@nestjs/common/interfaces/exceptions/rpc-exception-filter-metadata.interface.js b/node_modules/@nestjs/common/interfaces/exceptions/rpc-exception-filter-metadata.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/exceptions/rpc-exception-filter-metadata.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/exceptions/rpc-exception-filter.interface.d.ts b/node_modules/@nestjs/common/interfaces/exceptions/rpc-exception-filter.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f14c8f9dcb83dc1a213ab923ba5aaa26cfcac5f8 --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/exceptions/rpc-exception-filter.interface.d.ts @@ -0,0 +1,19 @@ +import { Observable } from 'rxjs'; +import { ArgumentsHost } from '../features/arguments-host.interface'; +/** + * Interface describing implementation of an RPC exception filter. + * + * @see [Exception Filters](https://docs.nestjs.com/microservices/exception-filters) + * + * @publicApi + */ +export interface RpcExceptionFilter { + /** + * Method to implement a custom (microservice) exception filter. + * + * @param exception the type (class) of the exception being handled + * @param host used to access an array of arguments for + * the in-flight message + */ + catch(exception: T, host: ArgumentsHost): Observable; +} diff --git a/node_modules/@nestjs/common/interfaces/exceptions/rpc-exception-filter.interface.js b/node_modules/@nestjs/common/interfaces/exceptions/rpc-exception-filter.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/exceptions/rpc-exception-filter.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/exceptions/ws-exception-filter.interface.d.ts b/node_modules/@nestjs/common/interfaces/exceptions/ws-exception-filter.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f3de66fc768a3038de4e3c7b66f85c08f76c112a --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/exceptions/ws-exception-filter.interface.d.ts @@ -0,0 +1,18 @@ +import { ArgumentsHost } from '../features/arguments-host.interface'; +/** + * Interface describing implementation of a Web Sockets exception filter. + * + * @see [Exception Filters](https://docs.nestjs.com/websockets/exception-filters) + * + * @publicApi + */ +export interface WsExceptionFilter { + /** + * Method to implement a custom (web sockets) exception filter. + * + * @param exception the type (class) of the exception being handled + * @param host used to access an array of arguments for + * the in-flight message catch(exception: T, host: ArgumentsHost): any; + */ + catch(exception: T, host: ArgumentsHost): any; +} diff --git a/node_modules/@nestjs/common/interfaces/exceptions/ws-exception-filter.interface.js b/node_modules/@nestjs/common/interfaces/exceptions/ws-exception-filter.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/exceptions/ws-exception-filter.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/external/class-transform-options.interface.d.ts b/node_modules/@nestjs/common/interfaces/external/class-transform-options.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a82df5d9421869c5bed513a3b181732185c3b514 --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/external/class-transform-options.interface.d.ts @@ -0,0 +1,65 @@ +/** + * Options to be passed during transformation. + * + * @see https://github.com/typestack/class-transformer + * + * @publicApi + */ +export interface ClassTransformOptions { + /** + * Exclusion strategy. By default exposeAll is used, which means that it will expose all properties that + * are transformed by default. + */ + strategy?: 'excludeAll' | 'exposeAll'; + /** + * Only properties with given groups will be transformed. + */ + groups?: string[]; + /** + * Only properties with "since" > version < "until" will be transformed. + */ + version?: number; + /** + * Excludes properties with the given prefixes. For example, if you mark your private properties with "_" and "__" + * you can set this option's value to ["_", "__"] and all private properties will be skipped. + * This works only for "exposeAll" strategy. + */ + excludePrefixes?: string[]; + /** + * If set to true then class transformer will ignore all @Expose and @Exclude decorators and what's inside them. + * This option is useful if you want to "clone" your object but not apply decorators affects. + */ + ignoreDecorators?: boolean; + /** + * Target maps allows to set a Types of the transforming object without using @Type decorator. + * This is useful when you are transforming external classes, or if you already have type metadata for + * objects and you don't want to set it up again. + */ + targetMaps?: any[]; + /** + * If set to true then class transformer will perform a circular check. (Circular check is turned off by default) + * This option is useful when you know for sure that your types might have a circular dependency. + */ + enableCircularCheck?: boolean; + /** + * If set to true class-transformer will attempt conversion based on TS reflected type + */ + enableImplicitConversion?: boolean; + /** + * If set to true class-transformer will exclude properties which are not part of the original class + * and exposing all class properties (with undefined, if nothing else is given) + */ + excludeExtraneousValues?: boolean; + /** + * If set to true then class transformer will take default values for unprovided fields. + * This is useful when you convert a plain object to a class and have an optional field with a default value. + */ + exposeDefaultValues?: boolean; + /** + * When set to true, fields with `undefined` as value will be included in class to plain transformation. Otherwise + * those fields will be omitted from the result. + * + * DEFAULT: `true` + */ + exposeUnsetFields?: boolean; +} diff --git a/node_modules/@nestjs/common/interfaces/external/class-transform-options.interface.js b/node_modules/@nestjs/common/interfaces/external/class-transform-options.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/external/class-transform-options.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/external/cors-options.interface.d.ts b/node_modules/@nestjs/common/interfaces/external/cors-options.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..76b27d6fd058b9de2fcd2956e6d7f5bbdb61cae8 --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/external/cors-options.interface.d.ts @@ -0,0 +1,58 @@ +type StaticOrigin = boolean | string | RegExp | (string | RegExp)[]; +/** + * Set origin to a function implementing some custom logic. The function takes the + * request origin as the first parameter and a callback (which expects the signature + * err [object], allow [bool]) as the second. + * + * @see https://github.com/expressjs/cors + * + * @publicApi + */ +export type CustomOrigin = (requestOrigin: string | undefined, callback: (err: Error | null, origin?: StaticOrigin) => void) => void; +/** + * Interface describing CORS options that can be set. + * + * @see https://github.com/expressjs/cors + * @publicApi + */ +export interface CorsOptions { + /** + * Configures the `Access-Control-Allow-Origins` CORS header. See [here for more detail.](https://github.com/expressjs/cors#configuration-options) + */ + origin?: StaticOrigin | CustomOrigin; + /** + * Configures the Access-Control-Allow-Methods CORS header. + */ + methods?: string | string[]; + /** + * Configures the Access-Control-Allow-Headers CORS header. + */ + allowedHeaders?: string | string[]; + /** + * Configures the Access-Control-Expose-Headers CORS header. + */ + exposedHeaders?: string | string[]; + /** + * Configures the Access-Control-Allow-Credentials CORS header. + */ + credentials?: boolean; + /** + * Configures the Access-Control-Max-Age CORS header. + */ + maxAge?: number; + /** + * Whether to pass the CORS preflight response to the next handler. + */ + preflightContinue?: boolean; + /** + * Provides a status code to use for successful OPTIONS requests. + */ + optionsSuccessStatus?: number; +} +export interface CorsOptionsCallback { + (error: Error | null, options: CorsOptions): void; +} +export interface CorsOptionsDelegate { + (req: T, cb: CorsOptionsCallback): void; +} +export {}; diff --git a/node_modules/@nestjs/common/interfaces/external/cors-options.interface.js b/node_modules/@nestjs/common/interfaces/external/cors-options.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/external/cors-options.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/external/https-options.interface.d.ts b/node_modules/@nestjs/common/interfaces/external/https-options.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fbb6ab6805f18f3f04cc6adff1f1e9f77d7c89b6 --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/external/https-options.interface.d.ts @@ -0,0 +1,105 @@ +/** + * Interface describing Https Options that can be set. + * + * @see https://nodejs.org/api/tls.html + * + * @publicApi + */ +export interface HttpsOptions { + /** + * PFX or PKCS12 encoded private key and certificate chain. pfx is an alternative + * to providing key and cert individually. PFX is usually encrypted, if it is, + * passphrase will be used to decrypt it. Multiple PFX can be provided either + * as an array of unencrypted PFX buffers, or an array of objects in the form + * {buf: [, passphrase: ]}. The object form can only + * occur in an array. object.passphrase is optional. Encrypted PFX will be decrypted + * with object.passphrase if provided, or options.passphrase if it is not. + */ + pfx?: any; + /** + * Private keys in PEM format. PEM allows the option of private keys being encrypted. + * Encrypted keys will be decrypted with options.passphrase. Multiple keys using + * different algorithms can be provided either as an array of unencrypted key + * strings or buffers, or an array of objects in the form {pem: [, passphrase: ]}. + * The object form can only occur in an array. object.passphrase is optional. + * Encrypted keys will be decrypted with object.passphrase if provided, or options.passphrase + * if it is not + */ + key?: any; + /** + * Shared passphrase used for a single private key and/or a PFX. + */ + passphrase?: string; + /** + * Cert chains in PEM format. One cert chain should be provided per private key. + * Each cert chain should consist of the PEM formatted certificate for a provided + * private key, followed by the PEM formatted intermediate certificates (if any), + * in order, and not including the root CA (the root CA must be pre-known to the + * peer, see ca). When providing multiple cert chains, they do not have to be + * in the same order as their private keys in key. If the intermediate certificates + * are not provided, the peer will not be able to validate the certificate, and + * the handshake will fail. + */ + cert?: any; + /** + * Optionally override the trusted CA certificates. Default is to trust the well-known + * CAs curated by Mozilla. Mozilla's CAs are completely replaced when CAs are + * explicitly specified using this option. The value can be a string or Buffer, + * or an Array of strings and/or Buffers. Any string or Buffer can contain multiple + * PEM CAs concatenated together. The peer's certificate must be chainable to + * a CA trusted by the server for the connection to be authenticated. When using + * certificates that are not chainable to a well-known CA, the certificate's CA + * must be explicitly specified as a trusted or the connection will fail to authenticate. + * If the peer uses a certificate that doesn't match or chain to one of the default + * CAs, use the ca option to provide a CA certificate that the peer's certificate + * can match or chain to. For self-signed certificates, the certificate is its + * own CA, and must be provided. For PEM encoded certificates, supported types + * are "TRUSTED CERTIFICATE", "X509 CERTIFICATE", and "CERTIFICATE". See also tls.rootCertificates. + */ + ca?: any; + /** + * PEM formatted CRLs (Certificate Revocation Lists). + */ + crl?: any; + /** + * Cipher suite specification, replacing the default. For more information, see + * modifying the default cipher suite. Permitted ciphers can be obtained via tls.getCiphers(). + * Cipher names must be uppercased in order for OpenSSL to accept them. + */ + ciphers?: string; + /** + * Attempt to use the server's cipher suite preferences instead of the client's. + * When true, causes SSL_OP_CIPHER_SERVER_PREFERENCE to be set in secureOptions, + * see OpenSSL Options for more information. + */ + honorCipherOrder?: boolean; + /** + * If true the server will request a certificate from clients that connect and + * attempt to verify that certificate. Default: false. + */ + requestCert?: boolean; + /** + * If not false the server will reject any connection which is not authorized + * with the list of supplied CAs. This option only has an effect if requestCert is true. Default: true + */ + rejectUnauthorized?: boolean; + /** + * An array or Buffer of possible NPN protocols. (Protocols should be ordered + * by their priority). + */ + NPNProtocols?: any; + /** + * A function that will be called if the client supports SNI TLS extension. Two + * arguments will be passed when called: servername and cb. SNICallback should + * invoke cb(null, ctx), where ctx is a SecureContext instance. (tls.createSecureContext(...) + * can be used to get a proper SecureContext.) If SNICallback wasn't provided + * the default callback with high-level API will be used. + */ + SNICallback?: (servername: string, cb: (err: Error, ctx: any) => any) => any; + /** + * Optionally affect the OpenSSL protocol behavior, which is not usually necessary. + * This should be used carefully if at all! Value is a numeric bitmask of the SSL_OP_* options + * from OpenSSL Options. + */ + secureOptions?: number; +} diff --git a/node_modules/@nestjs/common/interfaces/external/https-options.interface.js b/node_modules/@nestjs/common/interfaces/external/https-options.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/external/https-options.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/external/transformer-package.interface.d.ts b/node_modules/@nestjs/common/interfaces/external/transformer-package.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1222e9fa97d80ed81de7491cf4f95b6ce6368427 --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/external/transformer-package.interface.d.ts @@ -0,0 +1,6 @@ +import { Type } from '../type.interface'; +import { ClassTransformOptions } from './class-transform-options.interface'; +export interface TransformerPackage { + plainToInstance(cls: Type, plain: unknown, options?: ClassTransformOptions): T | T[]; + classToPlain(object: unknown, options?: ClassTransformOptions): Record | Record[]; +} diff --git a/node_modules/@nestjs/common/interfaces/external/transformer-package.interface.js b/node_modules/@nestjs/common/interfaces/external/transformer-package.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/external/transformer-package.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/external/validation-error.interface.d.ts b/node_modules/@nestjs/common/interfaces/external/validation-error.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..30d38df4cdadf14f24fce42e1cd15139bd786c4d --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/external/validation-error.interface.d.ts @@ -0,0 +1,42 @@ +/** + * Validation error description. + * @see https://github.com/typestack/class-validator + * + * class-validator@0.13.0 + * + * @publicApi + */ +export interface ValidationError { + /** + * Object that was validated. + * + * OPTIONAL - configurable via the ValidatorOptions.validationError.target option + */ + target?: Record; + /** + * Object's property that hasn't passed validation. + */ + property: string; + /** + * Value that haven't pass a validation. + * + * OPTIONAL - configurable via the ValidatorOptions.validationError.value option + */ + value?: any; + /** + * Constraints that failed validation with error messages. + */ + constraints?: { + [type: string]: string; + }; + /** + * Contains all nested validation errors of the property. + */ + children?: ValidationError[]; + /** + * A transient set of data passed through to the validation result for response mapping + */ + contexts?: { + [type: string]: any; + }; +} diff --git a/node_modules/@nestjs/common/interfaces/external/validation-error.interface.js b/node_modules/@nestjs/common/interfaces/external/validation-error.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/external/validation-error.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/external/validator-options.interface.d.ts b/node_modules/@nestjs/common/interfaces/external/validator-options.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0a5396ab7191d7fe87d1ed1ba9fc8ecd0143fce3 --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/external/validator-options.interface.d.ts @@ -0,0 +1,76 @@ +/** + * Options passed to validator during validation. + * @see https://github.com/typestack/class-validator + * + * class-validator@0.13.0 + * + * @publicApi + */ +export interface ValidatorOptions { + /** + * If set to true then class-validator will print extra warning messages to the console when something is not right. + */ + enableDebugMessages?: boolean; + /** + * If set to true then validator will skip validation of all properties that are undefined in the validating object. + */ + skipUndefinedProperties?: boolean; + /** + * If set to true then validator will skip validation of all properties that are null in the validating object. + */ + skipNullProperties?: boolean; + /** + * If set to true then validator will skip validation of all properties that are null or undefined in the validating object. + */ + skipMissingProperties?: boolean; + /** + * If set to true validator will strip validated object of any properties that do not have any decorators. + * + * Tip: if no other decorator is suitable for your property use @Allow decorator. + */ + whitelist?: boolean; + /** + * If set to true, instead of stripping non-whitelisted properties validator will throw an error + */ + forbidNonWhitelisted?: boolean; + /** + * Groups to be used during validation of the object. + */ + groups?: string[]; + /** + * Set default for `always` option of decorators. Default can be overridden in decorator options. + */ + always?: boolean; + /** + * If [groups]{@link ValidatorOptions#groups} is not given or is empty, + * ignore decorators with at least one group. + */ + strictGroups?: boolean; + /** + * If set to true, the validation will not use default messages. + * Error message always will be undefined if its not explicitly set. + */ + dismissDefaultMessages?: boolean; + /** + * ValidationError special options. + */ + validationError?: { + /** + * Indicates if target should be exposed in ValidationError. + */ + target?: boolean; + /** + * Indicates if validated value should be exposed in ValidationError. + */ + value?: boolean; + }; + /** + * Settings true will cause fail validation of unknown objects. + */ + forbidUnknownValues?: boolean; + /** + * When set to true, validation of the given property will stop after encountering the first error. + * This is enabled by default. + */ + stopAtFirstError?: boolean; +} diff --git a/node_modules/@nestjs/common/interfaces/external/validator-options.interface.js b/node_modules/@nestjs/common/interfaces/external/validator-options.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/external/validator-options.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/external/validator-package.interface.d.ts b/node_modules/@nestjs/common/interfaces/external/validator-package.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7a83d60de20a4010c3e1df59c5c79a3fa01e70a1 --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/external/validator-package.interface.d.ts @@ -0,0 +1,5 @@ +import { ValidationError } from './validation-error.interface'; +import { ValidatorOptions } from './validator-options.interface'; +export interface ValidatorPackage { + validate(object: unknown, validatorOptions?: ValidatorOptions): ValidationError[] | Promise; +} diff --git a/node_modules/@nestjs/common/interfaces/external/validator-package.interface.js b/node_modules/@nestjs/common/interfaces/external/validator-package.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/external/validator-package.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/features/arguments-host.interface.d.ts b/node_modules/@nestjs/common/interfaces/features/arguments-host.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..112fc0b15d7017d78f4bb79e06effa537d274c63 --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/features/arguments-host.interface.d.ts @@ -0,0 +1,88 @@ +export type ContextType = 'http' | 'ws' | 'rpc'; +/** + * Methods to obtain request and response objects. + * + * @publicApi + */ +export interface HttpArgumentsHost { + /** + * Returns the in-flight `request` object. + */ + getRequest(): T; + /** + * Returns the in-flight `response` object. + */ + getResponse(): T; + getNext(): T; +} +/** + * Methods to obtain WebSocket data and client objects. + * + * @publicApi + */ +export interface WsArgumentsHost { + /** + * Returns the data object. + */ + getData(): T; + /** + * Returns the client object. + */ + getClient(): T; + /** + * Returns the pattern for the event + */ + getPattern(): string; +} +/** + * Methods to obtain RPC data object. + * + * @publicApi + */ +export interface RpcArgumentsHost { + /** + * Returns the data object. + */ + getData(): T; + /** + * Returns the context object. + */ + getContext(): T; +} +/** + * Provides methods for retrieving the arguments being passed to a handler. + * Allows choosing the appropriate execution context (e.g., Http, RPC, or + * WebSockets) to retrieve the arguments from. + * + * @publicApi + */ +export interface ArgumentsHost { + /** + * Returns the array of arguments being passed to the handler. + */ + getArgs = any[]>(): T; + /** + * Returns a particular argument by index. + * @param index index of argument to retrieve + */ + getArgByIndex(index: number): T; + /** + * Switch context to RPC. + * @returns interface with methods to retrieve RPC arguments + */ + switchToRpc(): RpcArgumentsHost; + /** + * Switch context to HTTP. + * @returns interface with methods to retrieve HTTP arguments + */ + switchToHttp(): HttpArgumentsHost; + /** + * Switch context to WebSockets. + * @returns interface with methods to retrieve WebSockets arguments + */ + switchToWs(): WsArgumentsHost; + /** + * Returns the current execution context type (string) + */ + getType(): TContext; +} diff --git a/node_modules/@nestjs/common/interfaces/features/arguments-host.interface.js b/node_modules/@nestjs/common/interfaces/features/arguments-host.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/features/arguments-host.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/features/can-activate.interface.d.ts b/node_modules/@nestjs/common/interfaces/features/can-activate.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..722dee7b5bedaf277cf62ebe91f3bed3fd2f0492 --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/features/can-activate.interface.d.ts @@ -0,0 +1,22 @@ +import { Observable } from 'rxjs'; +import { ExecutionContext } from './execution-context.interface'; +/** + * Interface defining the `canActivate()` function that must be implemented + * by a guard. Return value indicates whether or not the current request is + * allowed to proceed. Return can be either synchronous (`boolean`) + * or asynchronous (`Promise` or `Observable`). + * + * @see [Guards](https://docs.nestjs.com/guards) + * + * @publicApi + */ +export interface CanActivate { + /** + * @param context Current execution context. Provides access to details about + * the current request pipeline. + * + * @returns Value indicating whether or not the current request is allowed to + * proceed. + */ + canActivate(context: ExecutionContext): boolean | Promise | Observable; +} diff --git a/node_modules/@nestjs/common/interfaces/features/can-activate.interface.js b/node_modules/@nestjs/common/interfaces/features/can-activate.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/features/can-activate.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/features/custom-route-param-factory.interface.d.ts b/node_modules/@nestjs/common/interfaces/features/custom-route-param-factory.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cde0838e6005240a7dfcbf4ae35ad5546a7c767b --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/features/custom-route-param-factory.interface.d.ts @@ -0,0 +1,5 @@ +import { ExecutionContext } from './execution-context.interface'; +/** + * @publicApi + */ +export type CustomParamFactory = (data: TData, context: ExecutionContext) => TOutput; diff --git a/node_modules/@nestjs/common/interfaces/features/custom-route-param-factory.interface.js b/node_modules/@nestjs/common/interfaces/features/custom-route-param-factory.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/features/custom-route-param-factory.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/features/execution-context.interface.d.ts b/node_modules/@nestjs/common/interfaces/features/execution-context.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..22051e8a7856ffdf2278f33a08a67581debe29e1 --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/features/execution-context.interface.d.ts @@ -0,0 +1,20 @@ +import { Type } from '../index'; +import { ArgumentsHost } from './arguments-host.interface'; +/** + * Interface describing details about the current request pipeline. + * + * @see [Execution Context](https://docs.nestjs.com/guards#execution-context) + * + * @publicApi + */ +export interface ExecutionContext extends ArgumentsHost { + /** + * Returns the *type* of the controller class which the current handler belongs to. + */ + getClass(): Type; + /** + * Returns a reference to the handler (method) that will be invoked next in the + * request pipeline. + */ + getHandler(): Function; +} diff --git a/node_modules/@nestjs/common/interfaces/features/execution-context.interface.js b/node_modules/@nestjs/common/interfaces/features/execution-context.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/features/execution-context.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/features/nest-interceptor.interface.d.ts b/node_modules/@nestjs/common/interfaces/features/nest-interceptor.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9400939c05abb15ce3af8ff191bd4303277666ca --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/features/nest-interceptor.interface.d.ts @@ -0,0 +1,34 @@ +import { Observable } from 'rxjs'; +import { ExecutionContext } from './execution-context.interface'; +/** + * Interface providing access to the response stream. + * + * @see [Interceptors](https://docs.nestjs.com/interceptors) + * + * @publicApi + */ +export interface CallHandler { + /** + * Returns an `Observable` representing the response stream from the route + * handler. + */ + handle(): Observable; +} +/** + * Interface describing implementation of an interceptor. + * + * @see [Interceptors](https://docs.nestjs.com/interceptors) + * + * @publicApi + */ +export interface NestInterceptor { + /** + * Method to implement a custom interceptor. + * + * @param context an `ExecutionContext` object providing methods to access the + * route handler and class about to be invoked. + * @param next a reference to the `CallHandler`, which provides access to an + * `Observable` representing the response stream from the route handler. + */ + intercept(context: ExecutionContext, next: CallHandler): Observable | Promise>; +} diff --git a/node_modules/@nestjs/common/interfaces/features/nest-interceptor.interface.js b/node_modules/@nestjs/common/interfaces/features/nest-interceptor.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/features/nest-interceptor.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/features/paramtype.interface.d.ts b/node_modules/@nestjs/common/interfaces/features/paramtype.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a63184f8ce83330453b3aa538d8ef7fcba7216ea --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/features/paramtype.interface.d.ts @@ -0,0 +1,4 @@ +/** + * @publicApi + */ +export type Paramtype = 'body' | 'query' | 'param' | 'custom'; diff --git a/node_modules/@nestjs/common/interfaces/features/paramtype.interface.js b/node_modules/@nestjs/common/interfaces/features/paramtype.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/features/paramtype.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/features/pipe-transform.interface.d.ts b/node_modules/@nestjs/common/interfaces/features/pipe-transform.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6efa44d46eb522e7b5a780c69fab7f9aa2ccb47a --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/features/pipe-transform.interface.d.ts @@ -0,0 +1,42 @@ +import { Type } from '../type.interface'; +import { Paramtype } from './paramtype.interface'; +export type Transform = (value: T, metadata: ArgumentMetadata) => any; +/** + * Interface describing a pipe implementation's `transform()` method metadata argument. + * + * @see [Pipes](https://docs.nestjs.com/pipes) + * + * @publicApi + */ +export interface ArgumentMetadata { + /** + * Indicates whether argument is a body, query, param, or custom parameter + */ + readonly type: Paramtype; + /** + * Underlying base type (e.g., `String`) of the parameter, based on the type + * definition in the route handler. + */ + readonly metatype?: Type | undefined; + /** + * String passed as an argument to the decorator. + * Example: `@Body('userId')` would yield `userId` + */ + readonly data?: string | undefined; +} +/** + * Interface describing implementation of a pipe. + * + * @see [Pipes](https://docs.nestjs.com/pipes) + * + * @publicApi + */ +export interface PipeTransform { + /** + * Method to implement a custom pipe. Called with two parameters + * + * @param value argument before it is received by route handler method + * @param metadata contains metadata about the value + */ + transform(value: T, metadata: ArgumentMetadata): R; +} diff --git a/node_modules/@nestjs/common/interfaces/features/pipe-transform.interface.js b/node_modules/@nestjs/common/interfaces/features/pipe-transform.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/features/pipe-transform.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/global-prefix-options.interface.d.ts b/node_modules/@nestjs/common/interfaces/global-prefix-options.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5de362d94719f571700d4e3181441e3f44234154 --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/global-prefix-options.interface.d.ts @@ -0,0 +1,7 @@ +import { RouteInfo } from './middleware'; +/** + * @publicApi + */ +export interface GlobalPrefixOptions { + exclude?: T[]; +} diff --git a/node_modules/@nestjs/common/interfaces/global-prefix-options.interface.js b/node_modules/@nestjs/common/interfaces/global-prefix-options.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/global-prefix-options.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/hooks/before-application-shutdown.interface.d.ts b/node_modules/@nestjs/common/interfaces/hooks/before-application-shutdown.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4024cb527fa95ed42a68dd36d7f5b5c42ddc38f5 --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/hooks/before-application-shutdown.interface.d.ts @@ -0,0 +1,3 @@ +export interface BeforeApplicationShutdown { + beforeApplicationShutdown(signal?: string): any; +} diff --git a/node_modules/@nestjs/common/interfaces/hooks/before-application-shutdown.interface.js b/node_modules/@nestjs/common/interfaces/hooks/before-application-shutdown.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/hooks/before-application-shutdown.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/hooks/index.d.ts b/node_modules/@nestjs/common/interfaces/hooks/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..01aad24975cbdca5457562953b3ba40e87f72e73 --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/hooks/index.d.ts @@ -0,0 +1,5 @@ +export * from './before-application-shutdown.interface'; +export * from './on-application-bootstrap.interface'; +export * from './on-application-shutdown.interface'; +export * from './on-destroy.interface'; +export * from './on-init.interface'; diff --git a/node_modules/@nestjs/common/interfaces/hooks/index.js b/node_modules/@nestjs/common/interfaces/hooks/index.js new file mode 100644 index 0000000000000000000000000000000000000000..547b6f555f42c2e74a6584ecfde1c49c985d7b9c --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/hooks/index.js @@ -0,0 +1,8 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = require("tslib"); +tslib_1.__exportStar(require("./before-application-shutdown.interface"), exports); +tslib_1.__exportStar(require("./on-application-bootstrap.interface"), exports); +tslib_1.__exportStar(require("./on-application-shutdown.interface"), exports); +tslib_1.__exportStar(require("./on-destroy.interface"), exports); +tslib_1.__exportStar(require("./on-init.interface"), exports); diff --git a/node_modules/@nestjs/common/interfaces/hooks/on-application-bootstrap.interface.d.ts b/node_modules/@nestjs/common/interfaces/hooks/on-application-bootstrap.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5e1f523077bd7f681b445638d75d4b7379e2c17d --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/hooks/on-application-bootstrap.interface.d.ts @@ -0,0 +1,11 @@ +/** + * Interface defining method called once the application has fully started and + * is bootstrapped. + * + * @see [Lifecycle Events](https://docs.nestjs.com/fundamentals/lifecycle-events) + * + * @publicApi + */ +export interface OnApplicationBootstrap { + onApplicationBootstrap(): any; +} diff --git a/node_modules/@nestjs/common/interfaces/hooks/on-application-bootstrap.interface.js b/node_modules/@nestjs/common/interfaces/hooks/on-application-bootstrap.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/hooks/on-application-bootstrap.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/hooks/on-application-shutdown.interface.d.ts b/node_modules/@nestjs/common/interfaces/hooks/on-application-shutdown.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cdace1cdda3db07519b4ab70e9d116b9145cde0a --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/hooks/on-application-shutdown.interface.d.ts @@ -0,0 +1,11 @@ +/** + * Interface defining method to respond to system signals (when application gets + * shutdown by, e.g., SIGTERM) + * + * @see [Lifecycle Events](https://docs.nestjs.com/fundamentals/lifecycle-events) + * + * @publicApi + */ +export interface OnApplicationShutdown { + onApplicationShutdown(signal?: string): any; +} diff --git a/node_modules/@nestjs/common/interfaces/hooks/on-application-shutdown.interface.js b/node_modules/@nestjs/common/interfaces/hooks/on-application-shutdown.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/hooks/on-application-shutdown.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/hooks/on-destroy.interface.d.ts b/node_modules/@nestjs/common/interfaces/hooks/on-destroy.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ad235a9510c2c48f3c6feeba03ee1c09141f2ac4 --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/hooks/on-destroy.interface.d.ts @@ -0,0 +1,12 @@ +/** + * Interface defining method called just before Nest destroys the host module + * (`app.close()` method has been evaluated). Use to perform cleanup on + * resources (e.g., Database connections). + * + * @see [Lifecycle Events](https://docs.nestjs.com/fundamentals/lifecycle-events) + * + * @publicApi + */ +export interface OnModuleDestroy { + onModuleDestroy(): any; +} diff --git a/node_modules/@nestjs/common/interfaces/hooks/on-destroy.interface.js b/node_modules/@nestjs/common/interfaces/hooks/on-destroy.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/hooks/on-destroy.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/hooks/on-init.interface.d.ts b/node_modules/@nestjs/common/interfaces/hooks/on-init.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..595d81969ac7214f0246735088e7121e245ca319 --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/hooks/on-init.interface.d.ts @@ -0,0 +1,10 @@ +/** + * Interface defining method called once the host module has been initialized. + * + * @see [Lifecycle Events](https://docs.nestjs.com/fundamentals/lifecycle-events) + * + * @publicApi + */ +export interface OnModuleInit { + onModuleInit(): any; +} diff --git a/node_modules/@nestjs/common/interfaces/hooks/on-init.interface.js b/node_modules/@nestjs/common/interfaces/hooks/on-init.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/hooks/on-init.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/http/http-exception-body.interface.d.ts b/node_modules/@nestjs/common/interfaces/http/http-exception-body.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..85a829bcb81417f418bc1a3dc5747e3c37a7c87e --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/http/http-exception-body.interface.d.ts @@ -0,0 +1,6 @@ +export type HttpExceptionBodyMessage = string | string[] | number; +export interface HttpExceptionBody { + message: HttpExceptionBodyMessage; + error?: string; + statusCode: number; +} diff --git a/node_modules/@nestjs/common/interfaces/http/http-exception-body.interface.js b/node_modules/@nestjs/common/interfaces/http/http-exception-body.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/http/http-exception-body.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/http/http-redirect-response.interface.d.ts b/node_modules/@nestjs/common/interfaces/http/http-redirect-response.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8eb2508a208f6a21c71473108c9ea72af8d80328 --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/http/http-redirect-response.interface.d.ts @@ -0,0 +1,5 @@ +import { HttpStatus } from '../../enums'; +export interface HttpRedirectResponse { + url: string; + statusCode: HttpStatus; +} diff --git a/node_modules/@nestjs/common/interfaces/http/http-redirect-response.interface.js b/node_modules/@nestjs/common/interfaces/http/http-redirect-response.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/http/http-redirect-response.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/http/http-server.interface.d.ts b/node_modules/@nestjs/common/interfaces/http/http-server.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fc06b80197fee34f6ccee037d9c9380cc3006865 --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/http/http-server.interface.d.ts @@ -0,0 +1,70 @@ +import { RequestMethod } from '../../enums'; +import { NestApplicationOptions } from '../../interfaces/nest-application-options.interface'; +import { VersionValue, VersioningOptions } from '../version-options.interface'; +export type ErrorHandler = (error: any, req: TRequest, res: TResponse, next?: Function) => any; +export type RequestHandler = (req: TRequest, res: TResponse, next?: Function) => any; +export interface HttpServer { + use(handler: RequestHandler | ErrorHandler): any; + use(path: string, handler: RequestHandler | ErrorHandler): any; + useBodyParser?(...args: any[]): any; + get(handler: RequestHandler): any; + get(path: string, handler: RequestHandler): any; + post(handler: RequestHandler): any; + post(path: string, handler: RequestHandler): any; + head(handler: RequestHandler): any; + head(path: string, handler: RequestHandler): any; + delete(handler: RequestHandler): any; + delete(path: string, handler: RequestHandler): any; + put(handler: RequestHandler): any; + put(path: string, handler: RequestHandler): any; + patch(handler: RequestHandler): any; + patch(path: string, handler: RequestHandler): any; + propfind?(handler: RequestHandler): any; + propfind?(path: string, handler: RequestHandler): any; + proppatch?(handler: RequestHandler): any; + proppatch?(path: string, handler: RequestHandler): any; + mkcol?(handler: RequestHandler): any; + mkcol?(path: string, handler: RequestHandler): any; + copy?(handler: RequestHandler): any; + copy?(path: string, handler: RequestHandler): any; + move?(handler: RequestHandler): any; + move?(path: string, handler: RequestHandler): any; + lock?(handler: RequestHandler): any; + lock?(path: string, handler: RequestHandler): any; + unlock?(handler: RequestHandler): any; + unlock?(path: string, handler: RequestHandler): any; + all(path: string, handler: RequestHandler): any; + all(handler: RequestHandler): any; + options(handler: RequestHandler): any; + options(path: string, handler: RequestHandler): any; + search?(handler: RequestHandler): any; + search?(path: string, handler: RequestHandler): any; + listen(port: number | string, callback?: () => void): any; + listen(port: number | string, hostname: string, callback?: () => void): any; + reply(response: any, body: any, statusCode?: number): any; + status(response: any, statusCode: number): any; + end(response: any, message?: string): any; + render(response: any, view: string, options: any): any; + redirect(response: any, statusCode: number, url: string): any; + isHeadersSent(response: any): boolean; + setHeader(response: any, name: string, value: string): any; + setErrorHandler?(handler: Function, prefix?: string): any; + setNotFoundHandler?(handler: Function, prefix?: string): any; + useStaticAssets?(...args: any[]): this; + setBaseViewsDir?(path: string | string[]): this; + setViewEngine?(engineOrOptions: any): this; + createMiddlewareFactory(method: RequestMethod): ((path: string, callback: Function) => any) | Promise<(path: string, callback: Function) => any>; + getRequestHostname?(request: TRequest): string; + getRequestMethod?(request: TRequest): string; + getRequestUrl?(request: TRequest): string; + getInstance(): ServerInstance; + registerParserMiddleware(...args: any[]): any; + enableCors(options: any): any; + getHttpServer(): any; + initHttpServer(options: NestApplicationOptions): void; + close(): any; + getType(): string; + init?(): Promise; + applyVersionFilter(handler: Function, version: VersionValue, versioningOptions: VersioningOptions): (req: TRequest, res: TResponse, next: () => void) => Function; + normalizePath?(path: string): string; +} diff --git a/node_modules/@nestjs/common/interfaces/http/http-server.interface.js b/node_modules/@nestjs/common/interfaces/http/http-server.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/http/http-server.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/http/index.d.ts b/node_modules/@nestjs/common/interfaces/http/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ad8ebfc83fd0d4163fcb42e877e923796d7f2c77 --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/http/index.d.ts @@ -0,0 +1,5 @@ +export * from './http-exception-body.interface'; +export * from './http-redirect-response.interface'; +export * from './http-server.interface'; +export * from './message-event.interface'; +export * from './raw-body-request.interface'; diff --git a/node_modules/@nestjs/common/interfaces/http/index.js b/node_modules/@nestjs/common/interfaces/http/index.js new file mode 100644 index 0000000000000000000000000000000000000000..22af770717969410c34e0b858b823b1bc03a3433 --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/http/index.js @@ -0,0 +1,8 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = require("tslib"); +tslib_1.__exportStar(require("./http-exception-body.interface"), exports); +tslib_1.__exportStar(require("./http-redirect-response.interface"), exports); +tslib_1.__exportStar(require("./http-server.interface"), exports); +tslib_1.__exportStar(require("./message-event.interface"), exports); +tslib_1.__exportStar(require("./raw-body-request.interface"), exports); diff --git a/node_modules/@nestjs/common/interfaces/http/message-event.interface.d.ts b/node_modules/@nestjs/common/interfaces/http/message-event.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..530a4d9ed61ea3984610052d802b50f0026c644c --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/http/message-event.interface.d.ts @@ -0,0 +1,6 @@ +export interface MessageEvent { + data: string | object; + id?: string; + type?: string; + retry?: number; +} diff --git a/node_modules/@nestjs/common/interfaces/http/message-event.interface.js b/node_modules/@nestjs/common/interfaces/http/message-event.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/http/message-event.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/http/raw-body-request.interface.d.ts b/node_modules/@nestjs/common/interfaces/http/raw-body-request.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5537aee537743516f83e68f3b02a8b12eecc61a7 --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/http/raw-body-request.interface.d.ts @@ -0,0 +1,6 @@ +/** + * @publicApi + */ +export type RawBodyRequest = T & { + rawBody?: Buffer; +}; diff --git a/node_modules/@nestjs/common/interfaces/http/raw-body-request.interface.js b/node_modules/@nestjs/common/interfaces/http/raw-body-request.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/http/raw-body-request.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/index.d.ts b/node_modules/@nestjs/common/interfaces/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..94ceff93cee425490447d0f783b15f75d0df71f7 --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/index.d.ts @@ -0,0 +1,30 @@ +export * from './abstract.interface'; +export * from './controllers/controller-metadata.interface'; +export * from './controllers/controller.interface'; +export * from './exceptions/exception-filter.interface'; +export * from './exceptions/rpc-exception-filter.interface'; +export * from './exceptions/ws-exception-filter.interface'; +export * from './external/validation-error.interface'; +export * from './features/arguments-host.interface'; +export * from './features/can-activate.interface'; +export * from './features/custom-route-param-factory.interface'; +export * from './features/execution-context.interface'; +export * from './features/nest-interceptor.interface'; +export * from './features/paramtype.interface'; +export * from './features/pipe-transform.interface'; +export * from './global-prefix-options.interface'; +export * from './hooks'; +export * from './http'; +export * from './injectable.interface'; +export * from './microservices/nest-hybrid-application-options.interface'; +export * from './middleware'; +export * from './modules'; +export * from './nest-application-context.interface'; +export * from './nest-application-options.interface'; +export * from './nest-application.interface'; +export * from './nest-microservice.interface'; +export * from './scope-options.interface'; +export * from './shutdown-hooks-options.interface'; +export * from './type.interface'; +export * from './version-options.interface'; +export * from './websockets/web-socket-adapter.interface'; diff --git a/node_modules/@nestjs/common/interfaces/index.js b/node_modules/@nestjs/common/interfaces/index.js new file mode 100644 index 0000000000000000000000000000000000000000..2d18bdad2d78f952e5a7897547dff956a8e08998 --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/index.js @@ -0,0 +1,33 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = require("tslib"); +tslib_1.__exportStar(require("./abstract.interface"), exports); +tslib_1.__exportStar(require("./controllers/controller-metadata.interface"), exports); +tslib_1.__exportStar(require("./controllers/controller.interface"), exports); +tslib_1.__exportStar(require("./exceptions/exception-filter.interface"), exports); +tslib_1.__exportStar(require("./exceptions/rpc-exception-filter.interface"), exports); +tslib_1.__exportStar(require("./exceptions/ws-exception-filter.interface"), exports); +tslib_1.__exportStar(require("./external/validation-error.interface"), exports); +tslib_1.__exportStar(require("./features/arguments-host.interface"), exports); +tslib_1.__exportStar(require("./features/can-activate.interface"), exports); +tslib_1.__exportStar(require("./features/custom-route-param-factory.interface"), exports); +tslib_1.__exportStar(require("./features/execution-context.interface"), exports); +tslib_1.__exportStar(require("./features/nest-interceptor.interface"), exports); +tslib_1.__exportStar(require("./features/paramtype.interface"), exports); +tslib_1.__exportStar(require("./features/pipe-transform.interface"), exports); +tslib_1.__exportStar(require("./global-prefix-options.interface"), exports); +tslib_1.__exportStar(require("./hooks"), exports); +tslib_1.__exportStar(require("./http"), exports); +tslib_1.__exportStar(require("./injectable.interface"), exports); +tslib_1.__exportStar(require("./microservices/nest-hybrid-application-options.interface"), exports); +tslib_1.__exportStar(require("./middleware"), exports); +tslib_1.__exportStar(require("./modules"), exports); +tslib_1.__exportStar(require("./nest-application-context.interface"), exports); +tslib_1.__exportStar(require("./nest-application-options.interface"), exports); +tslib_1.__exportStar(require("./nest-application.interface"), exports); +tslib_1.__exportStar(require("./nest-microservice.interface"), exports); +tslib_1.__exportStar(require("./scope-options.interface"), exports); +tslib_1.__exportStar(require("./shutdown-hooks-options.interface"), exports); +tslib_1.__exportStar(require("./type.interface"), exports); +tslib_1.__exportStar(require("./version-options.interface"), exports); +tslib_1.__exportStar(require("./websockets/web-socket-adapter.interface"), exports); diff --git a/node_modules/@nestjs/common/interfaces/injectable.interface.d.ts b/node_modules/@nestjs/common/interfaces/injectable.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0839daad253eee1ee2d913776ad579dd6c69e401 --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/injectable.interface.d.ts @@ -0,0 +1 @@ +export type Injectable = unknown; diff --git a/node_modules/@nestjs/common/interfaces/injectable.interface.js b/node_modules/@nestjs/common/interfaces/injectable.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/injectable.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/microservices/nest-hybrid-application-options.interface.d.ts b/node_modules/@nestjs/common/interfaces/microservices/nest-hybrid-application-options.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7e3aeab559df06544d6faf5f9d42cb27c9154a16 --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/microservices/nest-hybrid-application-options.interface.d.ts @@ -0,0 +1,7 @@ +/** + * @publicApi + */ +export interface NestHybridApplicationOptions { + inheritAppConfig?: boolean; + deferInitialization?: boolean; +} diff --git a/node_modules/@nestjs/common/interfaces/microservices/nest-hybrid-application-options.interface.js b/node_modules/@nestjs/common/interfaces/microservices/nest-hybrid-application-options.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/microservices/nest-hybrid-application-options.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/microservices/nest-microservice-options.interface.d.ts b/node_modules/@nestjs/common/interfaces/microservices/nest-microservice-options.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..16caa642a74b8533d869b0d74d15fd55314d25d0 --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/microservices/nest-microservice-options.interface.d.ts @@ -0,0 +1,5 @@ +import { NestApplicationContextOptions } from '../nest-application-context-options.interface'; +/** + * @publicApi + */ +export type NestMicroserviceOptions = NestApplicationContextOptions; diff --git a/node_modules/@nestjs/common/interfaces/microservices/nest-microservice-options.interface.js b/node_modules/@nestjs/common/interfaces/microservices/nest-microservice-options.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/microservices/nest-microservice-options.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/microservices/pre-request-hook.interface.d.ts b/node_modules/@nestjs/common/interfaces/microservices/pre-request-hook.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b41e72591b590c22dc70f7317f79f3f172d50cd2 --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/microservices/pre-request-hook.interface.d.ts @@ -0,0 +1,22 @@ +import { Observable } from 'rxjs'; +import { ExecutionContext } from '../features/execution-context.interface.js'; +/** + * Interface describing a global preRequest hook for microservices. + * + * Hooks are executed before guards, allowing setup of context (e.g. AsyncLocalStorage) + * that is available to all downstream enhancers. + * + * @example + * ```typescript + * const als = new AsyncLocalStorage(); + * app.registerPreRequestHook((context, next) => { + * als.enterWith({ correlationId: uuid() }); + * return next(); + * }); + * ``` + * + * @publicApi + */ +export interface PreRequestHook { + (context: ExecutionContext, next: () => Observable): Observable; +} diff --git a/node_modules/@nestjs/common/interfaces/microservices/pre-request-hook.interface.js b/node_modules/@nestjs/common/interfaces/microservices/pre-request-hook.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..cb0ff5c3b541f646105198ee23ac0fc3d805023e --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/microservices/pre-request-hook.interface.js @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/@nestjs/common/interfaces/middleware/index.d.ts b/node_modules/@nestjs/common/interfaces/middleware/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b23e220972aa9fe689bfe292c9a30c1608a139ea --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/middleware/index.d.ts @@ -0,0 +1,4 @@ +export * from './middleware-config-proxy.interface'; +export * from './middleware-configuration.interface'; +export * from './middleware-consumer.interface'; +export * from './nest-middleware.interface'; diff --git a/node_modules/@nestjs/common/interfaces/middleware/index.js b/node_modules/@nestjs/common/interfaces/middleware/index.js new file mode 100644 index 0000000000000000000000000000000000000000..3302f82fdde7e0d72b12e81cf68fde36e2249a3d --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/middleware/index.js @@ -0,0 +1,7 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = require("tslib"); +tslib_1.__exportStar(require("./middleware-config-proxy.interface"), exports); +tslib_1.__exportStar(require("./middleware-configuration.interface"), exports); +tslib_1.__exportStar(require("./middleware-consumer.interface"), exports); +tslib_1.__exportStar(require("./nest-middleware.interface"), exports); diff --git a/node_modules/@nestjs/common/interfaces/middleware/middleware-config-proxy.interface.d.ts b/node_modules/@nestjs/common/interfaces/middleware/middleware-config-proxy.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7952c45dd26fade3e075a093df8809bab319bd1f --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/middleware/middleware-config-proxy.interface.d.ts @@ -0,0 +1,24 @@ +import { Type } from '../type.interface'; +import { RouteInfo } from './middleware-configuration.interface'; +import { MiddlewareConsumer } from './middleware-consumer.interface'; +/** + * @publicApi + */ +export interface MiddlewareConfigProxy { + /** + * Routes to exclude from the current middleware. + * + * @param {(string | RouteInfo)[]} routes + * @returns {MiddlewareConfigProxy} + */ + exclude(...routes: (string | RouteInfo)[]): MiddlewareConfigProxy; + /** + * Attaches either routes or controllers to the current middleware. + * If you pass a controller class, Nest will attach the current middleware to every path + * defined within it. + * + * @param {(string | Type | RouteInfo)[]} routes + * @returns {MiddlewareConsumer} + */ + forRoutes(...routes: (string | Type | RouteInfo)[]): MiddlewareConsumer; +} diff --git a/node_modules/@nestjs/common/interfaces/middleware/middleware-config-proxy.interface.js b/node_modules/@nestjs/common/interfaces/middleware/middleware-config-proxy.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/middleware/middleware-config-proxy.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/middleware/middleware-configuration.interface.d.ts b/node_modules/@nestjs/common/interfaces/middleware/middleware-configuration.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d927313f58ab099f4726b1827ad226e57b89b9cc --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/middleware/middleware-configuration.interface.d.ts @@ -0,0 +1,12 @@ +import { RequestMethod } from '../../enums'; +import { Type } from '../type.interface'; +import { VersionValue } from '../version-options.interface'; +export interface RouteInfo { + path: string; + method: RequestMethod; + version?: VersionValue; +} +export interface MiddlewareConfiguration { + middleware: T; + forRoutes: (Type | string | RouteInfo)[]; +} diff --git a/node_modules/@nestjs/common/interfaces/middleware/middleware-configuration.interface.js b/node_modules/@nestjs/common/interfaces/middleware/middleware-configuration.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/middleware/middleware-configuration.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/middleware/middleware-consumer.interface.d.ts b/node_modules/@nestjs/common/interfaces/middleware/middleware-consumer.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..84feba2eb3528c29f3bb5cbbd54e9449fcae8ade --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/middleware/middleware-consumer.interface.d.ts @@ -0,0 +1,18 @@ +import { Type } from '../type.interface'; +import { MiddlewareConfigProxy } from './middleware-config-proxy.interface'; +/** + * Interface defining method for applying user defined middleware to routes. + * + * @see [MiddlewareConsumer](https://docs.nestjs.com/middleware#middleware-consumer) + * + * @publicApi + */ +export interface MiddlewareConsumer { + /** + * @param {...(Type | Function)} middleware middleware class/function or array of classes/functions + * to be attached to the passed routes. + * + * @returns {MiddlewareConfigProxy} + */ + apply(...middleware: (Type | Function)[]): MiddlewareConfigProxy; +} diff --git a/node_modules/@nestjs/common/interfaces/middleware/middleware-consumer.interface.js b/node_modules/@nestjs/common/interfaces/middleware/middleware-consumer.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/middleware/middleware-consumer.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/middleware/nest-middleware.interface.d.ts b/node_modules/@nestjs/common/interfaces/middleware/nest-middleware.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b8e3ed86d57fb187ea7084db34b5c70b9eb180b0 --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/middleware/nest-middleware.interface.d.ts @@ -0,0 +1,8 @@ +/** + * @see [Middleware](https://docs.nestjs.com/middleware) + * + * @publicApi + */ +export interface NestMiddleware { + use(req: TRequest, res: TResponse, next: (error?: any) => void): any; +} diff --git a/node_modules/@nestjs/common/interfaces/middleware/nest-middleware.interface.js b/node_modules/@nestjs/common/interfaces/middleware/nest-middleware.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/middleware/nest-middleware.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/modules/dynamic-module.interface.d.ts b/node_modules/@nestjs/common/interfaces/modules/dynamic-module.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3a42edffa2b43f9678a0e09d8f4cdac020523eaa --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/modules/dynamic-module.interface.d.ts @@ -0,0 +1,25 @@ +import { Type } from '../type.interface'; +import { ModuleMetadata } from './module-metadata.interface'; +/** + * Interface defining a Dynamic Module. + * + * @see [Dynamic Modules](https://docs.nestjs.com/modules#dynamic-modules) + * + * @publicApi + */ +export interface DynamicModule extends ModuleMetadata { + /** + * A module reference + */ + module: Type; + /** + * When "true", makes a module global-scoped. + * + * Once imported into any module, a global-scoped module will be visible + * in all modules. Thereafter, modules that wish to inject a service exported + * from a global module do not need to import the provider module. + * + * @default false + */ + global?: boolean; +} diff --git a/node_modules/@nestjs/common/interfaces/modules/dynamic-module.interface.js b/node_modules/@nestjs/common/interfaces/modules/dynamic-module.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/modules/dynamic-module.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/modules/forward-reference.interface.d.ts b/node_modules/@nestjs/common/interfaces/modules/forward-reference.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3b11eb8f3c19f3f07478fe222cabf0eed515afe6 --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/modules/forward-reference.interface.d.ts @@ -0,0 +1,3 @@ +export interface ForwardReference { + forwardRef: T; +} diff --git a/node_modules/@nestjs/common/interfaces/modules/forward-reference.interface.js b/node_modules/@nestjs/common/interfaces/modules/forward-reference.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/modules/forward-reference.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/modules/index.d.ts b/node_modules/@nestjs/common/interfaces/modules/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..458f952a3919bba25277979d19fb273eb963f9a6 --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/modules/index.d.ts @@ -0,0 +1,8 @@ +export * from './dynamic-module.interface'; +export * from './forward-reference.interface'; +export * from './injection-token.interface'; +export * from './introspection-result.interface'; +export * from './module-metadata.interface'; +export * from './nest-module.interface'; +export * from './optional-factory-dependency.interface'; +export * from './provider.interface'; diff --git a/node_modules/@nestjs/common/interfaces/modules/index.js b/node_modules/@nestjs/common/interfaces/modules/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a630045fc158103e3b8da94500f20c118115f809 --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/modules/index.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = require("tslib"); +tslib_1.__exportStar(require("./dynamic-module.interface"), exports); +tslib_1.__exportStar(require("./forward-reference.interface"), exports); +tslib_1.__exportStar(require("./injection-token.interface"), exports); +tslib_1.__exportStar(require("./introspection-result.interface"), exports); +tslib_1.__exportStar(require("./module-metadata.interface"), exports); +tslib_1.__exportStar(require("./nest-module.interface"), exports); +tslib_1.__exportStar(require("./optional-factory-dependency.interface"), exports); +tslib_1.__exportStar(require("./provider.interface"), exports); diff --git a/node_modules/@nestjs/common/interfaces/modules/injection-token.interface.d.ts b/node_modules/@nestjs/common/interfaces/modules/injection-token.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ef930f4762740785490d763dfa8095fc7cad147f --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/modules/injection-token.interface.d.ts @@ -0,0 +1,6 @@ +import { Abstract } from '../abstract.interface'; +import { Type } from '../type.interface'; +/** + * @publicApi + */ +export type InjectionToken = string | symbol | Type | Abstract | Function; diff --git a/node_modules/@nestjs/common/interfaces/modules/injection-token.interface.js b/node_modules/@nestjs/common/interfaces/modules/injection-token.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/modules/injection-token.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/modules/introspection-result.interface.d.ts b/node_modules/@nestjs/common/interfaces/modules/introspection-result.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2d132bda711307163f017b35f6fe2a3e7203c2a7 --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/modules/introspection-result.interface.d.ts @@ -0,0 +1,10 @@ +import { Scope } from '../scope-options.interface'; +/** + * @publicApi + */ +export interface IntrospectionResult { + /** + * Enum defining lifetime of host class or factory. + */ + scope: Scope; +} diff --git a/node_modules/@nestjs/common/interfaces/modules/introspection-result.interface.js b/node_modules/@nestjs/common/interfaces/modules/introspection-result.interface.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/modules/introspection-result.interface.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/@nestjs/common/interfaces/modules/module-metadata.interface.d.ts b/node_modules/@nestjs/common/interfaces/modules/module-metadata.interface.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4c34bcdf13b1eeab2daf2035adf722f2373c0540 --- /dev/null +++ b/node_modules/@nestjs/common/interfaces/modules/module-metadata.interface.d.ts @@ -0,0 +1,34 @@ +import { Abstract } from '../abstract.interface'; +import { Type } from '../type.interface'; +import { DynamicModule } from './dynamic-module.interface'; +import { ForwardReference } from './forward-reference.interface'; +import { Provider } from './provider.interface'; +/** + * Interface defining the property object that describes the module. + * + * @see [Modules](https://docs.nestjs.com/modules) + * + * @publicApi + */ +export interface ModuleMetadata { + /** + * Optional list of imported modules that export the providers which are + * required in this module. + */ + imports?: Array | DynamicModule | Promise | ForwardReference>; + /** + * Optional list of controllers defined in this module which have to be + * instantiated. + */ + controllers?: Type[]; + /** + * Optional list of providers that will be instantiated by the Nest injector + * and that may be shared at least across this module. + */ + providers?: Provider[]; + /** + * Optional list of the subset of providers that are provided by this module + * and should be available in other modules which import this module. + */ + exports?: Array | Function>; +}