Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/typescript/lib/lib.es2019.array.d.ts +79 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/typescript/lib/lib.es2020.full.d.ts +24 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/typescript/lib/lib.es2022.string.d.ts +25 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/typescript/lib/lib.es6.d.ts +23 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/typescript/lib/lib.esnext.array.d.ts +35 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/typescript/lib/lib.esnext.disposable.d.ts +193 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/docs/docs/api/Fetch.md +52 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/docs/docs/api/MockCallHistory.md +197 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/docs/docs/api/MockCallHistoryLog.md +43 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/docs/docs/api/MockClient.md +81 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/docs/docs/api/MockErrors.md +12 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/docs/docs/api/MockPool.md +554 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/docs/docs/api/Pool.md +84 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/docs/docs/api/PoolStats.md +35 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/docs/docs/api/ProxyAgent.md +229 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/docs/docs/api/RedirectHandler.md +96 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/docs/docs/api/RetryAgent.md +50 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/docs/docs/api/RetryHandler.md +118 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/docs/docs/api/SnapshotAgent.md +616 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/docs/docs/api/Util.md +25 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/docs/docs/api/WebSocket.md +112 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/docs/docs/api/api-lifecycle.md +91 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/docs/docs/best-practices/client-certificate.md +64 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/docs/docs/best-practices/mocking-request.md +190 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/docs/docs/best-practices/proxy.md +127 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/docs/docs/best-practices/writing-tests.md +20 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/api/abort-signal.js +59 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/api/api-connect.js +110 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/api/api-pipeline.js +252 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/api/api-request.js +199 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/api/api-stream.js +209 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/api/api-upgrade.js +110 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/api/index.js +7 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/api/readable.js +578 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/cache/memory-cache-store.js +234 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/cache/sqlite-cache-store.js +461 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/core/connect.js +134 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/core/constants.js +143 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/core/diagnostics.js +198 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/core/errors.js +244 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/core/request.js +408 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/core/symbols.js +68 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/core/tree.js +160 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/core/util.js +954 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/dispatcher/agent.js +144 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/dispatcher/balanced-pool.js +206 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/dispatcher/client-h1.js +1606 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/dispatcher/client-h2.js +798 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/dispatcher/client.js +614 -0
- platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/dispatcher/dispatcher-base.js +161 -0
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/typescript/lib/lib.es2019.array.d.ts
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/*! *****************************************************************************
|
| 2 |
+
Copyright (c) Microsoft Corporation. All rights reserved.
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
|
| 4 |
+
this file except in compliance with the License. You may obtain a copy of the
|
| 5 |
+
License at http://www.apache.org/licenses/LICENSE-2.0
|
| 6 |
+
|
| 7 |
+
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
| 8 |
+
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
|
| 9 |
+
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
|
| 10 |
+
MERCHANTABLITY OR NON-INFRINGEMENT.
|
| 11 |
+
|
| 12 |
+
See the Apache Version 2.0 License for specific language governing permissions
|
| 13 |
+
and limitations under the License.
|
| 14 |
+
***************************************************************************** */
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
/// <reference no-default-lib="true"/>
|
| 18 |
+
|
| 19 |
+
type FlatArray<Arr, Depth extends number> = {
|
| 20 |
+
done: Arr;
|
| 21 |
+
recur: Arr extends ReadonlyArray<infer InnerArr> ? FlatArray<InnerArr, [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20][Depth]>
|
| 22 |
+
: Arr;
|
| 23 |
+
}[Depth extends -1 ? "done" : "recur"];
|
| 24 |
+
|
| 25 |
+
interface ReadonlyArray<T> {
|
| 26 |
+
/**
|
| 27 |
+
* Calls a defined callback function on each element of an array. Then, flattens the result into
|
| 28 |
+
* a new array.
|
| 29 |
+
* This is identical to a map followed by flat with depth 1.
|
| 30 |
+
*
|
| 31 |
+
* @param callback A function that accepts up to three arguments. The flatMap method calls the
|
| 32 |
+
* callback function one time for each element in the array.
|
| 33 |
+
* @param thisArg An object to which the this keyword can refer in the callback function. If
|
| 34 |
+
* thisArg is omitted, undefined is used as the this value.
|
| 35 |
+
*/
|
| 36 |
+
flatMap<U, This = undefined>(
|
| 37 |
+
callback: (this: This, value: T, index: number, array: T[]) => U | ReadonlyArray<U>,
|
| 38 |
+
thisArg?: This,
|
| 39 |
+
): U[];
|
| 40 |
+
|
| 41 |
+
/**
|
| 42 |
+
* Returns a new array with all sub-array elements concatenated into it recursively up to the
|
| 43 |
+
* specified depth.
|
| 44 |
+
*
|
| 45 |
+
* @param depth The maximum recursion depth
|
| 46 |
+
*/
|
| 47 |
+
flat<A, D extends number = 1>(
|
| 48 |
+
this: A,
|
| 49 |
+
depth?: D,
|
| 50 |
+
): FlatArray<A, D>[];
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
interface Array<T> {
|
| 54 |
+
/**
|
| 55 |
+
* Calls a defined callback function on each element of an array. Then, flattens the result into
|
| 56 |
+
* a new array.
|
| 57 |
+
* This is identical to a map followed by flat with depth 1.
|
| 58 |
+
*
|
| 59 |
+
* @param callback A function that accepts up to three arguments. The flatMap method calls the
|
| 60 |
+
* callback function one time for each element in the array.
|
| 61 |
+
* @param thisArg An object to which the this keyword can refer in the callback function. If
|
| 62 |
+
* thisArg is omitted, undefined is used as the this value.
|
| 63 |
+
*/
|
| 64 |
+
flatMap<U, This = undefined>(
|
| 65 |
+
callback: (this: This, value: T, index: number, array: T[]) => U | ReadonlyArray<U>,
|
| 66 |
+
thisArg?: This,
|
| 67 |
+
): U[];
|
| 68 |
+
|
| 69 |
+
/**
|
| 70 |
+
* Returns a new array with all sub-array elements concatenated into it recursively up to the
|
| 71 |
+
* specified depth.
|
| 72 |
+
*
|
| 73 |
+
* @param depth The maximum recursion depth
|
| 74 |
+
*/
|
| 75 |
+
flat<A, D extends number = 1>(
|
| 76 |
+
this: A,
|
| 77 |
+
depth?: D,
|
| 78 |
+
): FlatArray<A, D>[];
|
| 79 |
+
}
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/typescript/lib/lib.es2020.full.d.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/*! *****************************************************************************
|
| 2 |
+
Copyright (c) Microsoft Corporation. All rights reserved.
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
|
| 4 |
+
this file except in compliance with the License. You may obtain a copy of the
|
| 5 |
+
License at http://www.apache.org/licenses/LICENSE-2.0
|
| 6 |
+
|
| 7 |
+
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
| 8 |
+
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
|
| 9 |
+
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
|
| 10 |
+
MERCHANTABLITY OR NON-INFRINGEMENT.
|
| 11 |
+
|
| 12 |
+
See the Apache Version 2.0 License for specific language governing permissions
|
| 13 |
+
and limitations under the License.
|
| 14 |
+
***************************************************************************** */
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
/// <reference no-default-lib="true"/>
|
| 18 |
+
|
| 19 |
+
/// <reference lib="es2020" />
|
| 20 |
+
/// <reference lib="dom" />
|
| 21 |
+
/// <reference lib="webworker.importscripts" />
|
| 22 |
+
/// <reference lib="scripthost" />
|
| 23 |
+
/// <reference lib="dom.iterable" />
|
| 24 |
+
/// <reference lib="dom.asynciterable" />
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/typescript/lib/lib.es2022.string.d.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/*! *****************************************************************************
|
| 2 |
+
Copyright (c) Microsoft Corporation. All rights reserved.
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
|
| 4 |
+
this file except in compliance with the License. You may obtain a copy of the
|
| 5 |
+
License at http://www.apache.org/licenses/LICENSE-2.0
|
| 6 |
+
|
| 7 |
+
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
| 8 |
+
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
|
| 9 |
+
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
|
| 10 |
+
MERCHANTABLITY OR NON-INFRINGEMENT.
|
| 11 |
+
|
| 12 |
+
See the Apache Version 2.0 License for specific language governing permissions
|
| 13 |
+
and limitations under the License.
|
| 14 |
+
***************************************************************************** */
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
/// <reference no-default-lib="true"/>
|
| 18 |
+
|
| 19 |
+
interface String {
|
| 20 |
+
/**
|
| 21 |
+
* Returns a new String consisting of the single UTF-16 code unit located at the specified index.
|
| 22 |
+
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
|
| 23 |
+
*/
|
| 24 |
+
at(index: number): string | undefined;
|
| 25 |
+
}
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/typescript/lib/lib.es6.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/*! *****************************************************************************
|
| 2 |
+
Copyright (c) Microsoft Corporation. All rights reserved.
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
|
| 4 |
+
this file except in compliance with the License. You may obtain a copy of the
|
| 5 |
+
License at http://www.apache.org/licenses/LICENSE-2.0
|
| 6 |
+
|
| 7 |
+
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
| 8 |
+
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
|
| 9 |
+
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
|
| 10 |
+
MERCHANTABLITY OR NON-INFRINGEMENT.
|
| 11 |
+
|
| 12 |
+
See the Apache Version 2.0 License for specific language governing permissions
|
| 13 |
+
and limitations under the License.
|
| 14 |
+
***************************************************************************** */
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
/// <reference no-default-lib="true"/>
|
| 18 |
+
|
| 19 |
+
/// <reference lib="es2015" />
|
| 20 |
+
/// <reference lib="dom" />
|
| 21 |
+
/// <reference lib="dom.iterable" />
|
| 22 |
+
/// <reference lib="webworker.importscripts" />
|
| 23 |
+
/// <reference lib="scripthost" />
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/typescript/lib/lib.esnext.array.d.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/*! *****************************************************************************
|
| 2 |
+
Copyright (c) Microsoft Corporation. All rights reserved.
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
|
| 4 |
+
this file except in compliance with the License. You may obtain a copy of the
|
| 5 |
+
License at http://www.apache.org/licenses/LICENSE-2.0
|
| 6 |
+
|
| 7 |
+
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
| 8 |
+
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
|
| 9 |
+
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
|
| 10 |
+
MERCHANTABLITY OR NON-INFRINGEMENT.
|
| 11 |
+
|
| 12 |
+
See the Apache Version 2.0 License for specific language governing permissions
|
| 13 |
+
and limitations under the License.
|
| 14 |
+
***************************************************************************** */
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
/// <reference no-default-lib="true"/>
|
| 18 |
+
|
| 19 |
+
interface ArrayConstructor {
|
| 20 |
+
/**
|
| 21 |
+
* Creates an array from an async iterator or iterable object.
|
| 22 |
+
* @param iterableOrArrayLike An async iterator or array-like object to convert to an array.
|
| 23 |
+
*/
|
| 24 |
+
fromAsync<T>(iterableOrArrayLike: AsyncIterable<T> | Iterable<T | PromiseLike<T>> | ArrayLike<T | PromiseLike<T>>): Promise<T[]>;
|
| 25 |
+
|
| 26 |
+
/**
|
| 27 |
+
* Creates an array from an async iterator or iterable object.
|
| 28 |
+
*
|
| 29 |
+
* @param iterableOrArrayLike An async iterator or array-like object to convert to an array.
|
| 30 |
+
* @param mapfn A mapping function to call on every element of itarableOrArrayLike.
|
| 31 |
+
* Each return value is awaited before being added to result array.
|
| 32 |
+
* @param thisArg Value of 'this' used when executing mapfn.
|
| 33 |
+
*/
|
| 34 |
+
fromAsync<T, U>(iterableOrArrayLike: AsyncIterable<T> | Iterable<T> | ArrayLike<T>, mapFn: (value: Awaited<T>, index: number) => U, thisArg?: any): Promise<Awaited<U>[]>;
|
| 35 |
+
}
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/typescript/lib/lib.esnext.disposable.d.ts
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/*! *****************************************************************************
|
| 2 |
+
Copyright (c) Microsoft Corporation. All rights reserved.
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
|
| 4 |
+
this file except in compliance with the License. You may obtain a copy of the
|
| 5 |
+
License at http://www.apache.org/licenses/LICENSE-2.0
|
| 6 |
+
|
| 7 |
+
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
| 8 |
+
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
|
| 9 |
+
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
|
| 10 |
+
MERCHANTABLITY OR NON-INFRINGEMENT.
|
| 11 |
+
|
| 12 |
+
See the Apache Version 2.0 License for specific language governing permissions
|
| 13 |
+
and limitations under the License.
|
| 14 |
+
***************************************************************************** */
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
/// <reference no-default-lib="true"/>
|
| 18 |
+
|
| 19 |
+
/// <reference lib="es2015.symbol" />
|
| 20 |
+
/// <reference lib="es2015.iterable" />
|
| 21 |
+
/// <reference lib="es2018.asynciterable" />
|
| 22 |
+
|
| 23 |
+
interface SymbolConstructor {
|
| 24 |
+
/**
|
| 25 |
+
* A method that is used to release resources held by an object. Called by the semantics of the `using` statement.
|
| 26 |
+
*/
|
| 27 |
+
readonly dispose: unique symbol;
|
| 28 |
+
|
| 29 |
+
/**
|
| 30 |
+
* A method that is used to asynchronously release resources held by an object. Called by the semantics of the `await using` statement.
|
| 31 |
+
*/
|
| 32 |
+
readonly asyncDispose: unique symbol;
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
interface Disposable {
|
| 36 |
+
[Symbol.dispose](): void;
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
interface AsyncDisposable {
|
| 40 |
+
[Symbol.asyncDispose](): PromiseLike<void>;
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
interface SuppressedError extends Error {
|
| 44 |
+
error: any;
|
| 45 |
+
suppressed: any;
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
interface SuppressedErrorConstructor {
|
| 49 |
+
new (error: any, suppressed: any, message?: string): SuppressedError;
|
| 50 |
+
(error: any, suppressed: any, message?: string): SuppressedError;
|
| 51 |
+
readonly prototype: SuppressedError;
|
| 52 |
+
}
|
| 53 |
+
declare var SuppressedError: SuppressedErrorConstructor;
|
| 54 |
+
|
| 55 |
+
interface DisposableStack {
|
| 56 |
+
/**
|
| 57 |
+
* Returns a value indicating whether this stack has been disposed.
|
| 58 |
+
*/
|
| 59 |
+
readonly disposed: boolean;
|
| 60 |
+
/**
|
| 61 |
+
* Disposes each resource in the stack in the reverse order that they were added.
|
| 62 |
+
*/
|
| 63 |
+
dispose(): void;
|
| 64 |
+
/**
|
| 65 |
+
* Adds a disposable resource to the stack, returning the resource.
|
| 66 |
+
* @param value The resource to add. `null` and `undefined` will not be added, but will be returned.
|
| 67 |
+
* @returns The provided {@link value}.
|
| 68 |
+
*/
|
| 69 |
+
use<T extends Disposable | null | undefined>(value: T): T;
|
| 70 |
+
/**
|
| 71 |
+
* Adds a value and associated disposal callback as a resource to the stack.
|
| 72 |
+
* @param value The value to add.
|
| 73 |
+
* @param onDispose The callback to use in place of a `[Symbol.dispose]()` method. Will be invoked with `value`
|
| 74 |
+
* as the first parameter.
|
| 75 |
+
* @returns The provided {@link value}.
|
| 76 |
+
*/
|
| 77 |
+
adopt<T>(value: T, onDispose: (value: T) => void): T;
|
| 78 |
+
/**
|
| 79 |
+
* Adds a callback to be invoked when the stack is disposed.
|
| 80 |
+
*/
|
| 81 |
+
defer(onDispose: () => void): void;
|
| 82 |
+
/**
|
| 83 |
+
* Move all resources out of this stack and into a new `DisposableStack`, and marks this stack as disposed.
|
| 84 |
+
* @example
|
| 85 |
+
* ```ts
|
| 86 |
+
* class C {
|
| 87 |
+
* #res1: Disposable;
|
| 88 |
+
* #res2: Disposable;
|
| 89 |
+
* #disposables: DisposableStack;
|
| 90 |
+
* constructor() {
|
| 91 |
+
* // stack will be disposed when exiting constructor for any reason
|
| 92 |
+
* using stack = new DisposableStack();
|
| 93 |
+
*
|
| 94 |
+
* // get first resource
|
| 95 |
+
* this.#res1 = stack.use(getResource1());
|
| 96 |
+
*
|
| 97 |
+
* // get second resource. If this fails, both `stack` and `#res1` will be disposed.
|
| 98 |
+
* this.#res2 = stack.use(getResource2());
|
| 99 |
+
*
|
| 100 |
+
* // all operations succeeded, move resources out of `stack` so that they aren't disposed
|
| 101 |
+
* // when constructor exits
|
| 102 |
+
* this.#disposables = stack.move();
|
| 103 |
+
* }
|
| 104 |
+
*
|
| 105 |
+
* [Symbol.dispose]() {
|
| 106 |
+
* this.#disposables.dispose();
|
| 107 |
+
* }
|
| 108 |
+
* }
|
| 109 |
+
* ```
|
| 110 |
+
*/
|
| 111 |
+
move(): DisposableStack;
|
| 112 |
+
[Symbol.dispose](): void;
|
| 113 |
+
readonly [Symbol.toStringTag]: string;
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
interface DisposableStackConstructor {
|
| 117 |
+
new (): DisposableStack;
|
| 118 |
+
readonly prototype: DisposableStack;
|
| 119 |
+
}
|
| 120 |
+
declare var DisposableStack: DisposableStackConstructor;
|
| 121 |
+
|
| 122 |
+
interface AsyncDisposableStack {
|
| 123 |
+
/**
|
| 124 |
+
* Returns a value indicating whether this stack has been disposed.
|
| 125 |
+
*/
|
| 126 |
+
readonly disposed: boolean;
|
| 127 |
+
/**
|
| 128 |
+
* Disposes each resource in the stack in the reverse order that they were added.
|
| 129 |
+
*/
|
| 130 |
+
disposeAsync(): Promise<void>;
|
| 131 |
+
/**
|
| 132 |
+
* Adds a disposable resource to the stack, returning the resource.
|
| 133 |
+
* @param value The resource to add. `null` and `undefined` will not be added, but will be returned.
|
| 134 |
+
* @returns The provided {@link value}.
|
| 135 |
+
*/
|
| 136 |
+
use<T extends AsyncDisposable | Disposable | null | undefined>(value: T): T;
|
| 137 |
+
/**
|
| 138 |
+
* Adds a value and associated disposal callback as a resource to the stack.
|
| 139 |
+
* @param value The value to add.
|
| 140 |
+
* @param onDisposeAsync The callback to use in place of a `[Symbol.asyncDispose]()` method. Will be invoked with `value`
|
| 141 |
+
* as the first parameter.
|
| 142 |
+
* @returns The provided {@link value}.
|
| 143 |
+
*/
|
| 144 |
+
adopt<T>(value: T, onDisposeAsync: (value: T) => PromiseLike<void> | void): T;
|
| 145 |
+
/**
|
| 146 |
+
* Adds a callback to be invoked when the stack is disposed.
|
| 147 |
+
*/
|
| 148 |
+
defer(onDisposeAsync: () => PromiseLike<void> | void): void;
|
| 149 |
+
/**
|
| 150 |
+
* Move all resources out of this stack and into a new `DisposableStack`, and marks this stack as disposed.
|
| 151 |
+
* @example
|
| 152 |
+
* ```ts
|
| 153 |
+
* class C {
|
| 154 |
+
* #res1: Disposable;
|
| 155 |
+
* #res2: Disposable;
|
| 156 |
+
* #disposables: DisposableStack;
|
| 157 |
+
* constructor() {
|
| 158 |
+
* // stack will be disposed when exiting constructor for any reason
|
| 159 |
+
* using stack = new DisposableStack();
|
| 160 |
+
*
|
| 161 |
+
* // get first resource
|
| 162 |
+
* this.#res1 = stack.use(getResource1());
|
| 163 |
+
*
|
| 164 |
+
* // get second resource. If this fails, both `stack` and `#res1` will be disposed.
|
| 165 |
+
* this.#res2 = stack.use(getResource2());
|
| 166 |
+
*
|
| 167 |
+
* // all operations succeeded, move resources out of `stack` so that they aren't disposed
|
| 168 |
+
* // when constructor exits
|
| 169 |
+
* this.#disposables = stack.move();
|
| 170 |
+
* }
|
| 171 |
+
*
|
| 172 |
+
* [Symbol.dispose]() {
|
| 173 |
+
* this.#disposables.dispose();
|
| 174 |
+
* }
|
| 175 |
+
* }
|
| 176 |
+
* ```
|
| 177 |
+
*/
|
| 178 |
+
move(): AsyncDisposableStack;
|
| 179 |
+
[Symbol.asyncDispose](): Promise<void>;
|
| 180 |
+
readonly [Symbol.toStringTag]: string;
|
| 181 |
+
}
|
| 182 |
+
|
| 183 |
+
interface AsyncDisposableStackConstructor {
|
| 184 |
+
new (): AsyncDisposableStack;
|
| 185 |
+
readonly prototype: AsyncDisposableStack;
|
| 186 |
+
}
|
| 187 |
+
declare var AsyncDisposableStack: AsyncDisposableStackConstructor;
|
| 188 |
+
|
| 189 |
+
interface IteratorObject<T, TReturn, TNext> extends Disposable {
|
| 190 |
+
}
|
| 191 |
+
|
| 192 |
+
interface AsyncIteratorObject<T, TReturn, TNext> extends AsyncDisposable {
|
| 193 |
+
}
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/docs/docs/api/Fetch.md
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Fetch
|
| 2 |
+
|
| 3 |
+
Undici exposes a fetch() method starts the process of fetching a resource from the network.
|
| 4 |
+
|
| 5 |
+
Documentation and examples can be found on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/fetch).
|
| 6 |
+
|
| 7 |
+
## FormData
|
| 8 |
+
|
| 9 |
+
This API is implemented as per the standard, you can find documentation on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/FormData).
|
| 10 |
+
|
| 11 |
+
If any parameters are passed to the FormData constructor other than `undefined`, an error will be thrown. Other parameters are ignored.
|
| 12 |
+
|
| 13 |
+
## Response
|
| 14 |
+
|
| 15 |
+
This API is implemented as per the standard, you can find documentation on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Response)
|
| 16 |
+
|
| 17 |
+
## Request
|
| 18 |
+
|
| 19 |
+
This API is implemented as per the standard, you can find documentation on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Request)
|
| 20 |
+
|
| 21 |
+
## Header
|
| 22 |
+
|
| 23 |
+
This API is implemented as per the standard, you can find documentation on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Headers)
|
| 24 |
+
|
| 25 |
+
# Body Mixins
|
| 26 |
+
|
| 27 |
+
`Response` and `Request` body inherit body mixin methods. These methods include:
|
| 28 |
+
|
| 29 |
+
- [`.arrayBuffer()`](https://fetch.spec.whatwg.org/#dom-body-arraybuffer)
|
| 30 |
+
- [`.blob()`](https://fetch.spec.whatwg.org/#dom-body-blob)
|
| 31 |
+
- [`.bytes()`](https://fetch.spec.whatwg.org/#dom-body-bytes)
|
| 32 |
+
- [`.formData()`](https://fetch.spec.whatwg.org/#dom-body-formdata)
|
| 33 |
+
- [`.json()`](https://fetch.spec.whatwg.org/#dom-body-json)
|
| 34 |
+
- [`.text()`](https://fetch.spec.whatwg.org/#dom-body-text)
|
| 35 |
+
|
| 36 |
+
There is an ongoing discussion regarding `.formData()` and its usefulness and performance in server environments. It is recommended to use a dedicated library for parsing `multipart/form-data` bodies, such as [Busboy](https://www.npmjs.com/package/busboy) or [@fastify/busboy](https://www.npmjs.com/package/@fastify/busboy).
|
| 37 |
+
|
| 38 |
+
These libraries can be interfaced with fetch with the following example code:
|
| 39 |
+
|
| 40 |
+
```mjs
|
| 41 |
+
import { Busboy } from '@fastify/busboy'
|
| 42 |
+
import { Readable } from 'node:stream'
|
| 43 |
+
|
| 44 |
+
const response = await fetch('...')
|
| 45 |
+
const busboy = new Busboy({
|
| 46 |
+
headers: {
|
| 47 |
+
'content-type': response.headers.get('content-type')
|
| 48 |
+
}
|
| 49 |
+
})
|
| 50 |
+
|
| 51 |
+
Readable.fromWeb(response.body).pipe(busboy)
|
| 52 |
+
```
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/docs/docs/api/MockCallHistory.md
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Class: MockCallHistory
|
| 2 |
+
|
| 3 |
+
Access to an instance with :
|
| 4 |
+
|
| 5 |
+
```js
|
| 6 |
+
const mockAgent = new MockAgent({ enableCallHistory: true })
|
| 7 |
+
mockAgent.getCallHistory()
|
| 8 |
+
|
| 9 |
+
// or
|
| 10 |
+
const mockAgent = new MockAgent()
|
| 11 |
+
mockAgent.enableMockHistory()
|
| 12 |
+
mockAgent.getCallHistory()
|
| 13 |
+
|
| 14 |
+
```
|
| 15 |
+
|
| 16 |
+
a MockCallHistory instance implements a **Symbol.iterator** letting you iterate on registered logs :
|
| 17 |
+
|
| 18 |
+
```ts
|
| 19 |
+
for (const log of mockAgent.getCallHistory()) {
|
| 20 |
+
//...
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
const array: Array<MockCallHistoryLog> = [...mockAgent.getCallHistory()]
|
| 24 |
+
const set: Set<MockCallHistoryLog> = new Set(mockAgent.getCallHistory())
|
| 25 |
+
```
|
| 26 |
+
|
| 27 |
+
## class methods
|
| 28 |
+
|
| 29 |
+
### clear
|
| 30 |
+
|
| 31 |
+
Clear all MockCallHistoryLog registered. This is automatically done when calling `mockAgent.close()`
|
| 32 |
+
|
| 33 |
+
```js
|
| 34 |
+
mockAgent.clearCallHistory()
|
| 35 |
+
// same as
|
| 36 |
+
mockAgent.getCallHistory()?.clear()
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
### calls
|
| 40 |
+
|
| 41 |
+
Get all MockCallHistoryLog registered as an array
|
| 42 |
+
|
| 43 |
+
```js
|
| 44 |
+
mockAgent.getCallHistory()?.calls()
|
| 45 |
+
```
|
| 46 |
+
|
| 47 |
+
### firstCall
|
| 48 |
+
|
| 49 |
+
Get the first MockCallHistoryLog registered or undefined
|
| 50 |
+
|
| 51 |
+
```js
|
| 52 |
+
mockAgent.getCallHistory()?.firstCall()
|
| 53 |
+
```
|
| 54 |
+
|
| 55 |
+
### lastCall
|
| 56 |
+
|
| 57 |
+
Get the last MockCallHistoryLog registered or undefined
|
| 58 |
+
|
| 59 |
+
```js
|
| 60 |
+
mockAgent.getCallHistory()?.lastCall()
|
| 61 |
+
```
|
| 62 |
+
|
| 63 |
+
### nthCall
|
| 64 |
+
|
| 65 |
+
Get the nth MockCallHistoryLog registered or undefined
|
| 66 |
+
|
| 67 |
+
```js
|
| 68 |
+
mockAgent.getCallHistory()?.nthCall(3) // the third MockCallHistoryLog registered
|
| 69 |
+
```
|
| 70 |
+
|
| 71 |
+
### filterCallsByProtocol
|
| 72 |
+
|
| 73 |
+
Filter MockCallHistoryLog by protocol.
|
| 74 |
+
|
| 75 |
+
> more details for the first parameter can be found [here](/docs/docs/api/MockCallHistory.md#filter-parameter)
|
| 76 |
+
|
| 77 |
+
```js
|
| 78 |
+
mockAgent.getCallHistory()?.filterCallsByProtocol(/https/)
|
| 79 |
+
mockAgent.getCallHistory()?.filterCallsByProtocol('https:')
|
| 80 |
+
```
|
| 81 |
+
|
| 82 |
+
### filterCallsByHost
|
| 83 |
+
|
| 84 |
+
Filter MockCallHistoryLog by host.
|
| 85 |
+
|
| 86 |
+
> more details for the first parameter can be found [here](/docs/docs/api/MockCallHistory.md#filter-parameter)
|
| 87 |
+
|
| 88 |
+
```js
|
| 89 |
+
mockAgent.getCallHistory()?.filterCallsByHost(/localhost/)
|
| 90 |
+
mockAgent.getCallHistory()?.filterCallsByHost('localhost:3000')
|
| 91 |
+
```
|
| 92 |
+
|
| 93 |
+
### filterCallsByPort
|
| 94 |
+
|
| 95 |
+
Filter MockCallHistoryLog by port.
|
| 96 |
+
|
| 97 |
+
> more details for the first parameter can be found [here](/docs/docs/api/MockCallHistory.md#filter-parameter)
|
| 98 |
+
|
| 99 |
+
```js
|
| 100 |
+
mockAgent.getCallHistory()?.filterCallsByPort(/3000/)
|
| 101 |
+
mockAgent.getCallHistory()?.filterCallsByPort('3000')
|
| 102 |
+
mockAgent.getCallHistory()?.filterCallsByPort('')
|
| 103 |
+
```
|
| 104 |
+
|
| 105 |
+
### filterCallsByOrigin
|
| 106 |
+
|
| 107 |
+
Filter MockCallHistoryLog by origin.
|
| 108 |
+
|
| 109 |
+
> more details for the first parameter can be found [here](/docs/docs/api/MockCallHistory.md#filter-parameter)
|
| 110 |
+
|
| 111 |
+
```js
|
| 112 |
+
mockAgent.getCallHistory()?.filterCallsByOrigin(/http:\/\/localhost:3000/)
|
| 113 |
+
mockAgent.getCallHistory()?.filterCallsByOrigin('http://localhost:3000')
|
| 114 |
+
```
|
| 115 |
+
|
| 116 |
+
### filterCallsByPath
|
| 117 |
+
|
| 118 |
+
Filter MockCallHistoryLog by path.
|
| 119 |
+
|
| 120 |
+
> more details for the first parameter can be found [here](/docs/docs/api/MockCallHistory.md#filter-parameter)
|
| 121 |
+
|
| 122 |
+
```js
|
| 123 |
+
mockAgent.getCallHistory()?.filterCallsByPath(/api\/v1\/graphql/)
|
| 124 |
+
mockAgent.getCallHistory()?.filterCallsByPath('/api/v1/graphql')
|
| 125 |
+
```
|
| 126 |
+
|
| 127 |
+
### filterCallsByHash
|
| 128 |
+
|
| 129 |
+
Filter MockCallHistoryLog by hash.
|
| 130 |
+
|
| 131 |
+
> more details for the first parameter can be found [here](/docs/docs/api/MockCallHistory.md#filter-parameter)
|
| 132 |
+
|
| 133 |
+
```js
|
| 134 |
+
mockAgent.getCallHistory()?.filterCallsByPath(/hash/)
|
| 135 |
+
mockAgent.getCallHistory()?.filterCallsByPath('#hash')
|
| 136 |
+
```
|
| 137 |
+
|
| 138 |
+
### filterCallsByFullUrl
|
| 139 |
+
|
| 140 |
+
Filter MockCallHistoryLog by fullUrl. fullUrl contains protocol, host, port, path, hash, and query params
|
| 141 |
+
|
| 142 |
+
> more details for the first parameter can be found [here](/docs/docs/api/MockCallHistory.md#filter-parameter)
|
| 143 |
+
|
| 144 |
+
```js
|
| 145 |
+
mockAgent.getCallHistory()?.filterCallsByFullUrl(/https:\/\/localhost:3000\/\?query=value#hash/)
|
| 146 |
+
mockAgent.getCallHistory()?.filterCallsByFullUrl('https://localhost:3000/?query=value#hash')
|
| 147 |
+
```
|
| 148 |
+
|
| 149 |
+
### filterCallsByMethod
|
| 150 |
+
|
| 151 |
+
Filter MockCallHistoryLog by method.
|
| 152 |
+
|
| 153 |
+
> more details for the first parameter can be found [here](/docs/docs/api/MockCallHistory.md#filter-parameter)
|
| 154 |
+
|
| 155 |
+
```js
|
| 156 |
+
mockAgent.getCallHistory()?.filterCallsByMethod(/POST/)
|
| 157 |
+
mockAgent.getCallHistory()?.filterCallsByMethod('POST')
|
| 158 |
+
```
|
| 159 |
+
|
| 160 |
+
### filterCalls
|
| 161 |
+
|
| 162 |
+
This class method is a meta function / alias to apply complex filtering in a single way.
|
| 163 |
+
|
| 164 |
+
Parameters :
|
| 165 |
+
|
| 166 |
+
- criteria : the first parameter. a function, regexp or object.
|
| 167 |
+
- function : filter MockCallHistoryLog when the function returns false
|
| 168 |
+
- regexp : filter MockCallHistoryLog when the regexp does not match on MockCallHistoryLog.toString() ([see](./MockCallHistoryLog.md#to-string))
|
| 169 |
+
- object : an object with MockCallHistoryLog properties as keys to apply multiple filters. each values are a [filter parameter](/docs/docs/api/MockCallHistory.md#filter-parameter)
|
| 170 |
+
- options : the second parameter. an object.
|
| 171 |
+
- options.operator : `'AND'` or `'OR'` (default `'OR'`). Used only if criteria is an object. see below
|
| 172 |
+
|
| 173 |
+
```js
|
| 174 |
+
mockAgent.getCallHistory()?.filterCalls((log) => log.hash === value && log.headers?.['authorization'] !== undefined)
|
| 175 |
+
mockAgent.getCallHistory()?.filterCalls(/"data": "{ "errors": "wrong body" }"/)
|
| 176 |
+
|
| 177 |
+
// returns an Array of MockCallHistoryLog which all have
|
| 178 |
+
// - a hash containing my-hash
|
| 179 |
+
// - OR
|
| 180 |
+
// - a path equal to /endpoint
|
| 181 |
+
mockAgent.getCallHistory()?.filterCalls({ hash: /my-hash/, path: '/endpoint' })
|
| 182 |
+
|
| 183 |
+
// returns an Array of MockCallHistoryLog which all have
|
| 184 |
+
// - a hash containing my-hash
|
| 185 |
+
// - AND
|
| 186 |
+
// - a path equal to /endpoint
|
| 187 |
+
mockAgent.getCallHistory()?.filterCalls({ hash: /my-hash/, path: '/endpoint' }, { operator: 'AND' })
|
| 188 |
+
```
|
| 189 |
+
|
| 190 |
+
## filter parameter
|
| 191 |
+
|
| 192 |
+
Can be :
|
| 193 |
+
|
| 194 |
+
- string. MockCallHistoryLog filtered if `value !== parameterValue`
|
| 195 |
+
- null. MockCallHistoryLog filtered if `value !== parameterValue`
|
| 196 |
+
- undefined. MockCallHistoryLog filtered if `value !== parameterValue`
|
| 197 |
+
- regexp. MockCallHistoryLog filtered if `!parameterValue.test(value)`
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/docs/docs/api/MockCallHistoryLog.md
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Class: MockCallHistoryLog
|
| 2 |
+
|
| 3 |
+
Access to an instance with :
|
| 4 |
+
|
| 5 |
+
```js
|
| 6 |
+
const mockAgent = new MockAgent({ enableCallHistory: true })
|
| 7 |
+
mockAgent.getCallHistory()?.firstCall()
|
| 8 |
+
```
|
| 9 |
+
|
| 10 |
+
## class properties
|
| 11 |
+
|
| 12 |
+
- body `mockAgent.getCallHistory()?.firstCall()?.body`
|
| 13 |
+
- headers `mockAgent.getCallHistory()?.firstCall()?.headers` an object
|
| 14 |
+
- method `mockAgent.getCallHistory()?.firstCall()?.method` a string
|
| 15 |
+
- fullUrl `mockAgent.getCallHistory()?.firstCall()?.fullUrl` a string containing the protocol, origin, path, query and hash
|
| 16 |
+
- origin `mockAgent.getCallHistory()?.firstCall()?.origin` a string containing the protocol and the host
|
| 17 |
+
- headers `mockAgent.getCallHistory()?.firstCall()?.headers` an object
|
| 18 |
+
- path `mockAgent.getCallHistory()?.firstCall()?.path` a string always starting with `/`
|
| 19 |
+
- searchParams `mockAgent.getCallHistory()?.firstCall()?.searchParams` an object
|
| 20 |
+
- protocol `mockAgent.getCallHistory()?.firstCall()?.protocol` a string (`https:`)
|
| 21 |
+
- host `mockAgent.getCallHistory()?.firstCall()?.host` a string
|
| 22 |
+
- port `mockAgent.getCallHistory()?.firstCall()?.port` an empty string or a string containing numbers
|
| 23 |
+
- hash `mockAgent.getCallHistory()?.firstCall()?.hash` an empty string or a string starting with `#`
|
| 24 |
+
|
| 25 |
+
## class methods
|
| 26 |
+
|
| 27 |
+
### toMap
|
| 28 |
+
|
| 29 |
+
Returns a Map instance
|
| 30 |
+
|
| 31 |
+
```js
|
| 32 |
+
mockAgent.getCallHistory()?.firstCall()?.toMap()?.get('hash')
|
| 33 |
+
// #hash
|
| 34 |
+
```
|
| 35 |
+
|
| 36 |
+
### toString
|
| 37 |
+
|
| 38 |
+
Returns a string computed with any class property name and value pair
|
| 39 |
+
|
| 40 |
+
```js
|
| 41 |
+
mockAgent.getCallHistory()?.firstCall()?.toString()
|
| 42 |
+
// protocol->https:|host->localhost:4000|port->4000|origin->https://localhost:4000|path->/endpoint|hash->#here|searchParams->{"query":"value"}|fullUrl->https://localhost:4000/endpoint?query=value#here|method->PUT|body->"{ "data": "hello" }"|headers->{"content-type":"application/json"}
|
| 43 |
+
```
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/docs/docs/api/MockClient.md
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Class: MockClient
|
| 2 |
+
|
| 3 |
+
Extends: `undici.Client`
|
| 4 |
+
|
| 5 |
+
A mock client class that implements the same api as [MockPool](/docs/docs/api/MockPool.md).
|
| 6 |
+
|
| 7 |
+
## `new MockClient(origin, [options])`
|
| 8 |
+
|
| 9 |
+
Arguments:
|
| 10 |
+
|
| 11 |
+
* **origin** `string` - It should only include the **protocol, hostname, and port**.
|
| 12 |
+
* **options** `MockClientOptions` - It extends the `Client` options.
|
| 13 |
+
|
| 14 |
+
Returns: `MockClient`
|
| 15 |
+
|
| 16 |
+
### Parameter: `MockClientOptions`
|
| 17 |
+
|
| 18 |
+
Extends: `ClientOptions`
|
| 19 |
+
|
| 20 |
+
* **agent** `Agent` - the agent to associate this MockClient with.
|
| 21 |
+
|
| 22 |
+
### Example - Basic MockClient instantiation
|
| 23 |
+
|
| 24 |
+
We can use MockAgent to instantiate a MockClient ready to be used to intercept specified requests. It will not do anything until registered as the agent to use and any mock request are registered.
|
| 25 |
+
|
| 26 |
+
```js
|
| 27 |
+
import { MockAgent } from 'undici'
|
| 28 |
+
|
| 29 |
+
// Connections must be set to 1 to return a MockClient instance
|
| 30 |
+
const mockAgent = new MockAgent({ connections: 1 })
|
| 31 |
+
|
| 32 |
+
const mockClient = mockAgent.get('http://localhost:3000')
|
| 33 |
+
```
|
| 34 |
+
|
| 35 |
+
## Instance Methods
|
| 36 |
+
|
| 37 |
+
### `MockClient.intercept(options)`
|
| 38 |
+
|
| 39 |
+
Implements: [`MockPool.intercept(options)`](/docs/docs/api/MockPool.md#mockpoolinterceptoptions)
|
| 40 |
+
|
| 41 |
+
### `MockClient.cleanMocks()`
|
| 42 |
+
|
| 43 |
+
Implements: [`MockPool.cleanMocks()`](/docs/docs/api/MockPool.md#mockpoolcleanmocks)
|
| 44 |
+
|
| 45 |
+
### `MockClient.close()`
|
| 46 |
+
|
| 47 |
+
Implements: [`MockPool.close()`](/docs/docs/api/MockPool.md#mockpoolclose)
|
| 48 |
+
|
| 49 |
+
### `MockClient.dispatch(options, handlers)`
|
| 50 |
+
|
| 51 |
+
Implements [`Dispatcher.dispatch(options, handlers)`](/docs/docs/api/Dispatcher.md#dispatcherdispatchoptions-handler).
|
| 52 |
+
|
| 53 |
+
### `MockClient.request(options[, callback])`
|
| 54 |
+
|
| 55 |
+
See [`Dispatcher.request(options [, callback])`](/docs/docs/api/Dispatcher.md#dispatcherrequestoptions-callback).
|
| 56 |
+
|
| 57 |
+
#### Example - MockClient request
|
| 58 |
+
|
| 59 |
+
```js
|
| 60 |
+
import { MockAgent } from 'undici'
|
| 61 |
+
|
| 62 |
+
const mockAgent = new MockAgent({ connections: 1 })
|
| 63 |
+
|
| 64 |
+
const mockClient = mockAgent.get('http://localhost:3000')
|
| 65 |
+
mockClient.intercept({ path: '/foo' }).reply(200, 'foo')
|
| 66 |
+
|
| 67 |
+
const {
|
| 68 |
+
statusCode,
|
| 69 |
+
body
|
| 70 |
+
} = await mockClient.request({
|
| 71 |
+
origin: 'http://localhost:3000',
|
| 72 |
+
path: '/foo',
|
| 73 |
+
method: 'GET'
|
| 74 |
+
})
|
| 75 |
+
|
| 76 |
+
console.log('response received', statusCode) // response received 200
|
| 77 |
+
|
| 78 |
+
for await (const data of body) {
|
| 79 |
+
console.log('data', data.toString('utf8')) // data foo
|
| 80 |
+
}
|
| 81 |
+
```
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/docs/docs/api/MockErrors.md
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# MockErrors
|
| 2 |
+
|
| 3 |
+
Undici exposes a variety of mock error objects that you can use to enhance your mock error handling.
|
| 4 |
+
You can find all the mock error objects inside the `mockErrors` key.
|
| 5 |
+
|
| 6 |
+
```js
|
| 7 |
+
import { mockErrors } from 'undici'
|
| 8 |
+
```
|
| 9 |
+
|
| 10 |
+
| Mock Error | Mock Error Codes | Description |
|
| 11 |
+
| --------------------- | ------------------------------- | ---------------------------------------------------------- |
|
| 12 |
+
| `MockNotMatchedError` | `UND_MOCK_ERR_MOCK_NOT_MATCHED` | The request does not match any registered mock dispatches. |
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/docs/docs/api/MockPool.md
ADDED
|
@@ -0,0 +1,554 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Class: MockPool
|
| 2 |
+
|
| 3 |
+
Extends: `undici.Pool`
|
| 4 |
+
|
| 5 |
+
A mock Pool class that implements the Pool API and is used by MockAgent to intercept real requests and return mocked responses.
|
| 6 |
+
|
| 7 |
+
## `new MockPool(origin, [options])`
|
| 8 |
+
|
| 9 |
+
Arguments:
|
| 10 |
+
|
| 11 |
+
* **origin** `string` - It should only include the **protocol, hostname, and port**.
|
| 12 |
+
* **options** `MockPoolOptions` - It extends the `Pool` options.
|
| 13 |
+
|
| 14 |
+
Returns: `MockPool`
|
| 15 |
+
|
| 16 |
+
### Parameter: `MockPoolOptions`
|
| 17 |
+
|
| 18 |
+
Extends: `PoolOptions`
|
| 19 |
+
|
| 20 |
+
* **agent** `Agent` - the agent to associate this MockPool with.
|
| 21 |
+
|
| 22 |
+
### Example - Basic MockPool instantiation
|
| 23 |
+
|
| 24 |
+
We can use MockAgent to instantiate a MockPool ready to be used to intercept specified requests. It will not do anything until registered as the agent to use and any mock request are registered.
|
| 25 |
+
|
| 26 |
+
```js
|
| 27 |
+
import { MockAgent } from 'undici'
|
| 28 |
+
|
| 29 |
+
const mockAgent = new MockAgent()
|
| 30 |
+
|
| 31 |
+
const mockPool = mockAgent.get('http://localhost:3000')
|
| 32 |
+
```
|
| 33 |
+
|
| 34 |
+
## Instance Methods
|
| 35 |
+
|
| 36 |
+
### `MockPool.intercept(options)`
|
| 37 |
+
|
| 38 |
+
This method defines the interception rules for matching against requests for a MockPool or MockPool. We can intercept multiple times on a single instance, but each intercept is only used once. For example if you expect to make 2 requests inside a test, you need to call `intercept()` twice. Assuming you use `disableNetConnect()` you will get `MockNotMatchedError` on the second request when you only call `intercept()` once.
|
| 39 |
+
|
| 40 |
+
When defining interception rules, all the rules must pass for a request to be intercepted. If a request is not intercepted, a real request will be attempted.
|
| 41 |
+
|
| 42 |
+
| Matcher type | Condition to pass |
|
| 43 |
+
|:------------:| -------------------------- |
|
| 44 |
+
| `string` | Exact match against string |
|
| 45 |
+
| `RegExp` | Regex must pass |
|
| 46 |
+
| `Function` | Function must return true |
|
| 47 |
+
|
| 48 |
+
Arguments:
|
| 49 |
+
|
| 50 |
+
* **options** `MockPoolInterceptOptions` - Interception options.
|
| 51 |
+
|
| 52 |
+
Returns: `MockInterceptor` corresponding to the input options.
|
| 53 |
+
|
| 54 |
+
### Parameter: `MockPoolInterceptOptions`
|
| 55 |
+
|
| 56 |
+
* **path** `string | RegExp | (path: string) => boolean` - a matcher for the HTTP request path. When a `RegExp` or callback is used, it will match against the request path including all query parameters in alphabetical order. When a `string` is provided, the query parameters can be conveniently specified through the `MockPoolInterceptOptions.query` setting.
|
| 57 |
+
* **method** `string | RegExp | (method: string) => boolean` - (optional) - a matcher for the HTTP request method. Defaults to `GET`.
|
| 58 |
+
* **body** `string | RegExp | (body: string) => boolean` - (optional) - a matcher for the HTTP request body.
|
| 59 |
+
* **headers** `Record<string, string | RegExp | (body: string) => boolean`> - (optional) - a matcher for the HTTP request headers. To be intercepted, a request must match all defined headers. Extra headers not defined here may (or may not) be included in the request and do not affect the interception in any way.
|
| 60 |
+
* **query** `Record<string, any> | null` - (optional) - a matcher for the HTTP request query string params. Only applies when a `string` was provided for `MockPoolInterceptOptions.path`.
|
| 61 |
+
* **ignoreTrailingSlash** `boolean` - (optional) - set to `true` if the matcher should also match by ignoring potential trailing slashes in `MockPoolInterceptOptions.path`.
|
| 62 |
+
|
| 63 |
+
### Return: `MockInterceptor`
|
| 64 |
+
|
| 65 |
+
We can define the behaviour of an intercepted request with the following options.
|
| 66 |
+
|
| 67 |
+
* **reply** `(statusCode: number, replyData: string | Buffer | object | MockInterceptor.MockResponseDataHandler, responseOptions?: MockResponseOptions) => MockScope` - define a reply for a matching request. You can define the replyData as a callback to read incoming request data. Default for `responseOptions` is `{}`.
|
| 68 |
+
* **reply** `(callback: MockInterceptor.MockReplyOptionsCallback) => MockScope` - define a reply for a matching request, allowing dynamic mocking of all reply options rather than just the data.
|
| 69 |
+
* **replyWithError** `(error: Error) => MockScope` - define an error for a matching request to throw.
|
| 70 |
+
* **defaultReplyHeaders** `(headers: Record<string, string>) => MockInterceptor` - define default headers to be included in subsequent replies. These are in addition to headers on a specific reply.
|
| 71 |
+
* **defaultReplyTrailers** `(trailers: Record<string, string>) => MockInterceptor` - define default trailers to be included in subsequent replies. These are in addition to trailers on a specific reply.
|
| 72 |
+
* **replyContentLength** `() => MockInterceptor` - define automatically calculated `content-length` headers to be included in subsequent replies.
|
| 73 |
+
|
| 74 |
+
The reply data of an intercepted request may either be a string, buffer, or JavaScript object. Objects are converted to JSON while strings and buffers are sent as-is.
|
| 75 |
+
|
| 76 |
+
By default, `reply` and `replyWithError` define the behaviour for the first matching request only. Subsequent requests will not be affected (this can be changed using the returned `MockScope`).
|
| 77 |
+
|
| 78 |
+
### Parameter: `MockResponseOptions`
|
| 79 |
+
|
| 80 |
+
* **headers** `Record<string, string>` - headers to be included on the mocked reply.
|
| 81 |
+
* **trailers** `Record<string, string>` - trailers to be included on the mocked reply.
|
| 82 |
+
|
| 83 |
+
### Return: `MockScope`
|
| 84 |
+
|
| 85 |
+
A `MockScope` is associated with a single `MockInterceptor`. With this, we can configure the default behaviour of an intercepted reply.
|
| 86 |
+
|
| 87 |
+
* **delay** `(waitInMs: number) => MockScope` - delay the associated reply by a set amount in ms.
|
| 88 |
+
* **persist** `() => MockScope` - any matching request will always reply with the defined response indefinitely.
|
| 89 |
+
* **times** `(repeatTimes: number) => MockScope` - any matching request will reply with the defined response a fixed amount of times. This is overridden by **persist**.
|
| 90 |
+
|
| 91 |
+
#### Example - Basic Mocked Request
|
| 92 |
+
|
| 93 |
+
```js
|
| 94 |
+
import { MockAgent, setGlobalDispatcher, request } from 'undici'
|
| 95 |
+
|
| 96 |
+
const mockAgent = new MockAgent()
|
| 97 |
+
setGlobalDispatcher(mockAgent)
|
| 98 |
+
|
| 99 |
+
// MockPool
|
| 100 |
+
const mockPool = mockAgent.get('http://localhost:3000')
|
| 101 |
+
mockPool.intercept({ path: '/foo' }).reply(200, 'foo')
|
| 102 |
+
|
| 103 |
+
const {
|
| 104 |
+
statusCode,
|
| 105 |
+
body
|
| 106 |
+
} = await request('http://localhost:3000/foo')
|
| 107 |
+
|
| 108 |
+
console.log('response received', statusCode) // response received 200
|
| 109 |
+
|
| 110 |
+
for await (const data of body) {
|
| 111 |
+
console.log('data', data.toString('utf8')) // data foo
|
| 112 |
+
}
|
| 113 |
+
```
|
| 114 |
+
|
| 115 |
+
#### Example - Mocked request using reply data callbacks
|
| 116 |
+
|
| 117 |
+
```js
|
| 118 |
+
import { MockAgent, setGlobalDispatcher, request } from 'undici'
|
| 119 |
+
|
| 120 |
+
const mockAgent = new MockAgent()
|
| 121 |
+
setGlobalDispatcher(mockAgent)
|
| 122 |
+
|
| 123 |
+
const mockPool = mockAgent.get('http://localhost:3000')
|
| 124 |
+
|
| 125 |
+
mockPool.intercept({
|
| 126 |
+
path: '/echo',
|
| 127 |
+
method: 'GET',
|
| 128 |
+
headers: {
|
| 129 |
+
'User-Agent': 'undici',
|
| 130 |
+
Host: 'example.com'
|
| 131 |
+
}
|
| 132 |
+
}).reply(200, ({ headers }) => ({ message: headers.get('message') }))
|
| 133 |
+
|
| 134 |
+
const { statusCode, body, headers } = await request('http://localhost:3000', {
|
| 135 |
+
headers: {
|
| 136 |
+
message: 'hello world!'
|
| 137 |
+
}
|
| 138 |
+
})
|
| 139 |
+
|
| 140 |
+
console.log('response received', statusCode) // response received 200
|
| 141 |
+
console.log('headers', headers) // { 'content-type': 'application/json' }
|
| 142 |
+
|
| 143 |
+
for await (const data of body) {
|
| 144 |
+
console.log('data', data.toString('utf8')) // { "message":"hello world!" }
|
| 145 |
+
}
|
| 146 |
+
```
|
| 147 |
+
|
| 148 |
+
#### Example - Mocked request using reply options callback
|
| 149 |
+
|
| 150 |
+
```js
|
| 151 |
+
import { MockAgent, setGlobalDispatcher, request } from 'undici'
|
| 152 |
+
|
| 153 |
+
const mockAgent = new MockAgent()
|
| 154 |
+
setGlobalDispatcher(mockAgent)
|
| 155 |
+
|
| 156 |
+
const mockPool = mockAgent.get('http://localhost:3000')
|
| 157 |
+
|
| 158 |
+
mockPool.intercept({
|
| 159 |
+
path: '/echo',
|
| 160 |
+
method: 'GET',
|
| 161 |
+
headers: {
|
| 162 |
+
'User-Agent': 'undici',
|
| 163 |
+
Host: 'example.com'
|
| 164 |
+
}
|
| 165 |
+
}).reply(({ headers }) => ({ statusCode: 200, data: { message: headers.get('message') }})))
|
| 166 |
+
|
| 167 |
+
const { statusCode, body, headers } = await request('http://localhost:3000', {
|
| 168 |
+
headers: {
|
| 169 |
+
message: 'hello world!'
|
| 170 |
+
}
|
| 171 |
+
})
|
| 172 |
+
|
| 173 |
+
console.log('response received', statusCode) // response received 200
|
| 174 |
+
console.log('headers', headers) // { 'content-type': 'application/json' }
|
| 175 |
+
|
| 176 |
+
for await (const data of body) {
|
| 177 |
+
console.log('data', data.toString('utf8')) // { "message":"hello world!" }
|
| 178 |
+
}
|
| 179 |
+
```
|
| 180 |
+
|
| 181 |
+
#### Example - Basic Mocked requests with multiple intercepts
|
| 182 |
+
|
| 183 |
+
```js
|
| 184 |
+
import { MockAgent, setGlobalDispatcher, request } from 'undici'
|
| 185 |
+
|
| 186 |
+
const mockAgent = new MockAgent()
|
| 187 |
+
setGlobalDispatcher(mockAgent)
|
| 188 |
+
|
| 189 |
+
const mockPool = mockAgent.get('http://localhost:3000')
|
| 190 |
+
|
| 191 |
+
mockPool.intercept({
|
| 192 |
+
path: '/foo',
|
| 193 |
+
method: 'GET'
|
| 194 |
+
}).reply(200, 'foo')
|
| 195 |
+
|
| 196 |
+
mockPool.intercept({
|
| 197 |
+
path: '/hello',
|
| 198 |
+
method: 'GET',
|
| 199 |
+
}).reply(200, 'hello')
|
| 200 |
+
|
| 201 |
+
const result1 = await request('http://localhost:3000/foo')
|
| 202 |
+
|
| 203 |
+
console.log('response received', result1.statusCode) // response received 200
|
| 204 |
+
|
| 205 |
+
for await (const data of result1.body) {
|
| 206 |
+
console.log('data', data.toString('utf8')) // data foo
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
const result2 = await request('http://localhost:3000/hello')
|
| 210 |
+
|
| 211 |
+
console.log('response received', result2.statusCode) // response received 200
|
| 212 |
+
|
| 213 |
+
for await (const data of result2.body) {
|
| 214 |
+
console.log('data', data.toString('utf8')) // data hello
|
| 215 |
+
}
|
| 216 |
+
```
|
| 217 |
+
|
| 218 |
+
#### Example - Mocked request with query body, request headers and response headers and trailers
|
| 219 |
+
|
| 220 |
+
```js
|
| 221 |
+
import { MockAgent, setGlobalDispatcher, request } from 'undici'
|
| 222 |
+
|
| 223 |
+
const mockAgent = new MockAgent()
|
| 224 |
+
setGlobalDispatcher(mockAgent)
|
| 225 |
+
|
| 226 |
+
const mockPool = mockAgent.get('http://localhost:3000')
|
| 227 |
+
|
| 228 |
+
mockPool.intercept({
|
| 229 |
+
path: '/foo?hello=there&see=ya',
|
| 230 |
+
method: 'POST',
|
| 231 |
+
body: 'form1=data1&form2=data2',
|
| 232 |
+
headers: {
|
| 233 |
+
'User-Agent': 'undici',
|
| 234 |
+
Host: 'example.com'
|
| 235 |
+
}
|
| 236 |
+
}).reply(200, { foo: 'bar' }, {
|
| 237 |
+
headers: { 'content-type': 'application/json' },
|
| 238 |
+
trailers: { 'Content-MD5': 'test' }
|
| 239 |
+
})
|
| 240 |
+
|
| 241 |
+
const {
|
| 242 |
+
statusCode,
|
| 243 |
+
headers,
|
| 244 |
+
trailers,
|
| 245 |
+
body
|
| 246 |
+
} = await request('http://localhost:3000/foo?hello=there&see=ya', {
|
| 247 |
+
method: 'POST',
|
| 248 |
+
body: 'form1=data1&form2=data2',
|
| 249 |
+
headers: {
|
| 250 |
+
foo: 'bar',
|
| 251 |
+
'User-Agent': 'undici',
|
| 252 |
+
Host: 'example.com'
|
| 253 |
+
}
|
| 254 |
+
})
|
| 255 |
+
|
| 256 |
+
console.log('response received', statusCode) // response received 200
|
| 257 |
+
console.log('headers', headers) // { 'content-type': 'application/json' }
|
| 258 |
+
|
| 259 |
+
for await (const data of body) {
|
| 260 |
+
console.log('data', data.toString('utf8')) // '{"foo":"bar"}'
|
| 261 |
+
}
|
| 262 |
+
|
| 263 |
+
console.log('trailers', trailers) // { 'content-md5': 'test' }
|
| 264 |
+
```
|
| 265 |
+
|
| 266 |
+
#### Example - Mocked request using different matchers
|
| 267 |
+
|
| 268 |
+
```js
|
| 269 |
+
import { MockAgent, setGlobalDispatcher, request } from 'undici'
|
| 270 |
+
|
| 271 |
+
const mockAgent = new MockAgent()
|
| 272 |
+
setGlobalDispatcher(mockAgent)
|
| 273 |
+
|
| 274 |
+
const mockPool = mockAgent.get('http://localhost:3000')
|
| 275 |
+
|
| 276 |
+
mockPool.intercept({
|
| 277 |
+
path: '/foo',
|
| 278 |
+
method: /^GET$/,
|
| 279 |
+
body: (value) => value === 'form=data',
|
| 280 |
+
headers: {
|
| 281 |
+
'User-Agent': 'undici',
|
| 282 |
+
Host: /^example.com$/
|
| 283 |
+
}
|
| 284 |
+
}).reply(200, 'foo')
|
| 285 |
+
|
| 286 |
+
const {
|
| 287 |
+
statusCode,
|
| 288 |
+
body
|
| 289 |
+
} = await request('http://localhost:3000/foo', {
|
| 290 |
+
method: 'GET',
|
| 291 |
+
body: 'form=data',
|
| 292 |
+
headers: {
|
| 293 |
+
foo: 'bar',
|
| 294 |
+
'User-Agent': 'undici',
|
| 295 |
+
Host: 'example.com'
|
| 296 |
+
}
|
| 297 |
+
})
|
| 298 |
+
|
| 299 |
+
console.log('response received', statusCode) // response received 200
|
| 300 |
+
|
| 301 |
+
for await (const data of body) {
|
| 302 |
+
console.log('data', data.toString('utf8')) // data foo
|
| 303 |
+
}
|
| 304 |
+
```
|
| 305 |
+
|
| 306 |
+
#### Example - Mocked request with reply with a defined error
|
| 307 |
+
|
| 308 |
+
```js
|
| 309 |
+
import { MockAgent, setGlobalDispatcher, request } from 'undici'
|
| 310 |
+
|
| 311 |
+
const mockAgent = new MockAgent()
|
| 312 |
+
setGlobalDispatcher(mockAgent)
|
| 313 |
+
|
| 314 |
+
const mockPool = mockAgent.get('http://localhost:3000')
|
| 315 |
+
|
| 316 |
+
mockPool.intercept({
|
| 317 |
+
path: '/foo',
|
| 318 |
+
method: 'GET'
|
| 319 |
+
}).replyWithError(new Error('kaboom'))
|
| 320 |
+
|
| 321 |
+
try {
|
| 322 |
+
await request('http://localhost:3000/foo', {
|
| 323 |
+
method: 'GET'
|
| 324 |
+
})
|
| 325 |
+
} catch (error) {
|
| 326 |
+
console.error(error) // Error: kaboom
|
| 327 |
+
}
|
| 328 |
+
```
|
| 329 |
+
|
| 330 |
+
#### Example - Mocked request with defaultReplyHeaders
|
| 331 |
+
|
| 332 |
+
```js
|
| 333 |
+
import { MockAgent, setGlobalDispatcher, request } from 'undici'
|
| 334 |
+
|
| 335 |
+
const mockAgent = new MockAgent()
|
| 336 |
+
setGlobalDispatcher(mockAgent)
|
| 337 |
+
|
| 338 |
+
const mockPool = mockAgent.get('http://localhost:3000')
|
| 339 |
+
|
| 340 |
+
mockPool.intercept({
|
| 341 |
+
path: '/foo',
|
| 342 |
+
method: 'GET'
|
| 343 |
+
}).defaultReplyHeaders({ foo: 'bar' })
|
| 344 |
+
.reply(200, 'foo')
|
| 345 |
+
|
| 346 |
+
const { headers } = await request('http://localhost:3000/foo')
|
| 347 |
+
|
| 348 |
+
console.log('headers', headers) // headers { foo: 'bar' }
|
| 349 |
+
```
|
| 350 |
+
|
| 351 |
+
#### Example - Mocked request with defaultReplyTrailers
|
| 352 |
+
|
| 353 |
+
```js
|
| 354 |
+
import { MockAgent, setGlobalDispatcher, request } from 'undici'
|
| 355 |
+
|
| 356 |
+
const mockAgent = new MockAgent()
|
| 357 |
+
setGlobalDispatcher(mockAgent)
|
| 358 |
+
|
| 359 |
+
const mockPool = mockAgent.get('http://localhost:3000')
|
| 360 |
+
|
| 361 |
+
mockPool.intercept({
|
| 362 |
+
path: '/foo',
|
| 363 |
+
method: 'GET'
|
| 364 |
+
}).defaultReplyTrailers({ foo: 'bar' })
|
| 365 |
+
.reply(200, 'foo')
|
| 366 |
+
|
| 367 |
+
const { trailers } = await request('http://localhost:3000/foo')
|
| 368 |
+
|
| 369 |
+
console.log('trailers', trailers) // trailers { foo: 'bar' }
|
| 370 |
+
```
|
| 371 |
+
|
| 372 |
+
#### Example - Mocked request with automatic content-length calculation
|
| 373 |
+
|
| 374 |
+
```js
|
| 375 |
+
import { MockAgent, setGlobalDispatcher, request } from 'undici'
|
| 376 |
+
|
| 377 |
+
const mockAgent = new MockAgent()
|
| 378 |
+
setGlobalDispatcher(mockAgent)
|
| 379 |
+
|
| 380 |
+
const mockPool = mockAgent.get('http://localhost:3000')
|
| 381 |
+
|
| 382 |
+
mockPool.intercept({
|
| 383 |
+
path: '/foo',
|
| 384 |
+
method: 'GET'
|
| 385 |
+
}).replyContentLength().reply(200, 'foo')
|
| 386 |
+
|
| 387 |
+
const { headers } = await request('http://localhost:3000/foo')
|
| 388 |
+
|
| 389 |
+
console.log('headers', headers) // headers { 'content-length': '3' }
|
| 390 |
+
```
|
| 391 |
+
|
| 392 |
+
#### Example - Mocked request with automatic content-length calculation on an object
|
| 393 |
+
|
| 394 |
+
```js
|
| 395 |
+
import { MockAgent, setGlobalDispatcher, request } from 'undici'
|
| 396 |
+
|
| 397 |
+
const mockAgent = new MockAgent()
|
| 398 |
+
setGlobalDispatcher(mockAgent)
|
| 399 |
+
|
| 400 |
+
const mockPool = mockAgent.get('http://localhost:3000')
|
| 401 |
+
|
| 402 |
+
mockPool.intercept({
|
| 403 |
+
path: '/foo',
|
| 404 |
+
method: 'GET'
|
| 405 |
+
}).replyContentLength().reply(200, { foo: 'bar' })
|
| 406 |
+
|
| 407 |
+
const { headers } = await request('http://localhost:3000/foo')
|
| 408 |
+
|
| 409 |
+
console.log('headers', headers) // headers { 'content-length': '13' }
|
| 410 |
+
```
|
| 411 |
+
|
| 412 |
+
#### Example - Mocked request with persist enabled
|
| 413 |
+
|
| 414 |
+
```js
|
| 415 |
+
import { MockAgent, setGlobalDispatcher, request } from 'undici'
|
| 416 |
+
|
| 417 |
+
const mockAgent = new MockAgent()
|
| 418 |
+
setGlobalDispatcher(mockAgent)
|
| 419 |
+
|
| 420 |
+
const mockPool = mockAgent.get('http://localhost:3000')
|
| 421 |
+
|
| 422 |
+
mockPool.intercept({
|
| 423 |
+
path: '/foo',
|
| 424 |
+
method: 'GET'
|
| 425 |
+
}).reply(200, 'foo').persist()
|
| 426 |
+
|
| 427 |
+
const result1 = await request('http://localhost:3000/foo')
|
| 428 |
+
// Will match and return mocked data
|
| 429 |
+
|
| 430 |
+
const result2 = await request('http://localhost:3000/foo')
|
| 431 |
+
// Will match and return mocked data
|
| 432 |
+
|
| 433 |
+
// Etc
|
| 434 |
+
```
|
| 435 |
+
|
| 436 |
+
#### Example - Mocked request with times enabled
|
| 437 |
+
|
| 438 |
+
```js
|
| 439 |
+
import { MockAgent, setGlobalDispatcher, request } from 'undici'
|
| 440 |
+
|
| 441 |
+
const mockAgent = new MockAgent()
|
| 442 |
+
setGlobalDispatcher(mockAgent)
|
| 443 |
+
|
| 444 |
+
const mockPool = mockAgent.get('http://localhost:3000')
|
| 445 |
+
|
| 446 |
+
mockPool.intercept({
|
| 447 |
+
path: '/foo',
|
| 448 |
+
method: 'GET'
|
| 449 |
+
}).reply(200, 'foo').times(2)
|
| 450 |
+
|
| 451 |
+
const result1 = await request('http://localhost:3000/foo')
|
| 452 |
+
// Will match and return mocked data
|
| 453 |
+
|
| 454 |
+
const result2 = await request('http://localhost:3000/foo')
|
| 455 |
+
// Will match and return mocked data
|
| 456 |
+
|
| 457 |
+
const result3 = await request('http://localhost:3000/foo')
|
| 458 |
+
// Will not match and make attempt a real request
|
| 459 |
+
```
|
| 460 |
+
|
| 461 |
+
#### Example - Mocked request with path callback
|
| 462 |
+
|
| 463 |
+
```js
|
| 464 |
+
import { MockAgent, setGlobalDispatcher, request } from 'undici'
|
| 465 |
+
import querystring from 'querystring'
|
| 466 |
+
|
| 467 |
+
const mockAgent = new MockAgent()
|
| 468 |
+
setGlobalDispatcher(mockAgent)
|
| 469 |
+
|
| 470 |
+
const mockPool = mockAgent.get('http://localhost:3000')
|
| 471 |
+
|
| 472 |
+
const matchPath = requestPath => {
|
| 473 |
+
const [pathname, search] = requestPath.split('?')
|
| 474 |
+
const requestQuery = querystring.parse(search)
|
| 475 |
+
|
| 476 |
+
if (!pathname.startsWith('/foo')) {
|
| 477 |
+
return false
|
| 478 |
+
}
|
| 479 |
+
|
| 480 |
+
if (!Object.keys(requestQuery).includes('foo') || requestQuery.foo !== 'bar') {
|
| 481 |
+
return false
|
| 482 |
+
}
|
| 483 |
+
|
| 484 |
+
return true
|
| 485 |
+
}
|
| 486 |
+
|
| 487 |
+
mockPool.intercept({
|
| 488 |
+
path: matchPath,
|
| 489 |
+
method: 'GET'
|
| 490 |
+
}).reply(200, 'foo')
|
| 491 |
+
|
| 492 |
+
const result = await request('http://localhost:3000/foo?foo=bar')
|
| 493 |
+
// Will match and return mocked data
|
| 494 |
+
```
|
| 495 |
+
|
| 496 |
+
### `MockPool.close()`
|
| 497 |
+
|
| 498 |
+
Closes the mock pool and de-registers from associated MockAgent.
|
| 499 |
+
|
| 500 |
+
Returns: `Promise<void>`
|
| 501 |
+
|
| 502 |
+
#### Example - clean up after tests are complete
|
| 503 |
+
|
| 504 |
+
```js
|
| 505 |
+
import { MockAgent } from 'undici'
|
| 506 |
+
|
| 507 |
+
const mockAgent = new MockAgent()
|
| 508 |
+
const mockPool = mockAgent.get('http://localhost:3000')
|
| 509 |
+
|
| 510 |
+
await mockPool.close()
|
| 511 |
+
```
|
| 512 |
+
|
| 513 |
+
### `MockPool.dispatch(options, handlers)`
|
| 514 |
+
|
| 515 |
+
Implements [`Dispatcher.dispatch(options, handlers)`](/docs/docs/api/Dispatcher.md#dispatcherdispatchoptions-handler).
|
| 516 |
+
|
| 517 |
+
### `MockPool.request(options[, callback])`
|
| 518 |
+
|
| 519 |
+
See [`Dispatcher.request(options [, callback])`](/docs/docs/api/Dispatcher.md#dispatcherrequestoptions-callback).
|
| 520 |
+
|
| 521 |
+
#### Example - MockPool request
|
| 522 |
+
|
| 523 |
+
```js
|
| 524 |
+
import { MockAgent } from 'undici'
|
| 525 |
+
|
| 526 |
+
const mockAgent = new MockAgent()
|
| 527 |
+
|
| 528 |
+
const mockPool = mockAgent.get('http://localhost:3000')
|
| 529 |
+
mockPool.intercept({
|
| 530 |
+
path: '/foo',
|
| 531 |
+
method: 'GET',
|
| 532 |
+
}).reply(200, 'foo')
|
| 533 |
+
|
| 534 |
+
const {
|
| 535 |
+
statusCode,
|
| 536 |
+
body
|
| 537 |
+
} = await mockPool.request({
|
| 538 |
+
origin: 'http://localhost:3000',
|
| 539 |
+
path: '/foo',
|
| 540 |
+
method: 'GET'
|
| 541 |
+
})
|
| 542 |
+
|
| 543 |
+
console.log('response received', statusCode) // response received 200
|
| 544 |
+
|
| 545 |
+
for await (const data of body) {
|
| 546 |
+
console.log('data', data.toString('utf8')) // data foo
|
| 547 |
+
}
|
| 548 |
+
```
|
| 549 |
+
|
| 550 |
+
### `MockPool.cleanMocks()`
|
| 551 |
+
|
| 552 |
+
This method cleans up all the prepared mocks.
|
| 553 |
+
|
| 554 |
+
Returns: `void`
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/docs/docs/api/Pool.md
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Class: Pool
|
| 2 |
+
|
| 3 |
+
Extends: `undici.Dispatcher`
|
| 4 |
+
|
| 5 |
+
A pool of [Client](/docs/docs/api/Client.md) instances connected to the same upstream target.
|
| 6 |
+
|
| 7 |
+
Requests are not guaranteed to be dispatched in order of invocation.
|
| 8 |
+
|
| 9 |
+
## `new Pool(url[, options])`
|
| 10 |
+
|
| 11 |
+
Arguments:
|
| 12 |
+
|
| 13 |
+
* **url** `URL | string` - It should only include the **protocol, hostname, and port**.
|
| 14 |
+
* **options** `PoolOptions` (optional)
|
| 15 |
+
|
| 16 |
+
### Parameter: `PoolOptions`
|
| 17 |
+
|
| 18 |
+
Extends: [`ClientOptions`](/docs/docs/api/Client.md#parameter-clientoptions)
|
| 19 |
+
|
| 20 |
+
* **factory** `(origin: URL, opts: Object) => Dispatcher` - Default: `(origin, opts) => new Client(origin, opts)`
|
| 21 |
+
* **connections** `number | null` (optional) - Default: `null` - The number of `Client` instances to create. When set to `null`, the `Pool` instance will create an unlimited amount of `Client` instances.
|
| 22 |
+
* **clientTtl** `number | null` (optional) - Default: `null` - The amount of time before a `Client` instance is removed from the `Pool` and closed. When set to `null`, `Client` instances will not be removed or closed based on age.
|
| 23 |
+
|
| 24 |
+
## Instance Properties
|
| 25 |
+
|
| 26 |
+
### `Pool.closed`
|
| 27 |
+
|
| 28 |
+
Implements [Client.closed](/docs/docs/api/Client.md#clientclosed)
|
| 29 |
+
|
| 30 |
+
### `Pool.destroyed`
|
| 31 |
+
|
| 32 |
+
Implements [Client.destroyed](/docs/docs/api/Client.md#clientdestroyed)
|
| 33 |
+
|
| 34 |
+
### `Pool.stats`
|
| 35 |
+
|
| 36 |
+
Returns [`PoolStats`](PoolStats.md) instance for this pool.
|
| 37 |
+
|
| 38 |
+
## Instance Methods
|
| 39 |
+
|
| 40 |
+
### `Pool.close([callback])`
|
| 41 |
+
|
| 42 |
+
Implements [`Dispatcher.close([callback])`](/docs/docs/api/Dispatcher.md#dispatcherclosecallback-promise).
|
| 43 |
+
|
| 44 |
+
### `Pool.destroy([error, callback])`
|
| 45 |
+
|
| 46 |
+
Implements [`Dispatcher.destroy([error, callback])`](/docs/docs/api/Dispatcher.md#dispatcherdestroyerror-callback-promise).
|
| 47 |
+
|
| 48 |
+
### `Pool.connect(options[, callback])`
|
| 49 |
+
|
| 50 |
+
See [`Dispatcher.connect(options[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherconnectoptions-callback).
|
| 51 |
+
|
| 52 |
+
### `Pool.dispatch(options, handler)`
|
| 53 |
+
|
| 54 |
+
Implements [`Dispatcher.dispatch(options, handler)`](/docs/docs/api/Dispatcher.md#dispatcherdispatchoptions-handler).
|
| 55 |
+
|
| 56 |
+
### `Pool.pipeline(options, handler)`
|
| 57 |
+
|
| 58 |
+
See [`Dispatcher.pipeline(options, handler)`](/docs/docs/api/Dispatcher.md#dispatcherpipelineoptions-handler).
|
| 59 |
+
|
| 60 |
+
### `Pool.request(options[, callback])`
|
| 61 |
+
|
| 62 |
+
See [`Dispatcher.request(options [, callback])`](/docs/docs/api/Dispatcher.md#dispatcherrequestoptions-callback).
|
| 63 |
+
|
| 64 |
+
### `Pool.stream(options, factory[, callback])`
|
| 65 |
+
|
| 66 |
+
See [`Dispatcher.stream(options, factory[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherstreamoptions-factory-callback).
|
| 67 |
+
|
| 68 |
+
### `Pool.upgrade(options[, callback])`
|
| 69 |
+
|
| 70 |
+
See [`Dispatcher.upgrade(options[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherupgradeoptions-callback).
|
| 71 |
+
|
| 72 |
+
## Instance Events
|
| 73 |
+
|
| 74 |
+
### Event: `'connect'`
|
| 75 |
+
|
| 76 |
+
See [Dispatcher Event: `'connect'`](/docs/docs/api/Dispatcher.md#event-connect).
|
| 77 |
+
|
| 78 |
+
### Event: `'disconnect'`
|
| 79 |
+
|
| 80 |
+
See [Dispatcher Event: `'disconnect'`](/docs/docs/api/Dispatcher.md#event-disconnect).
|
| 81 |
+
|
| 82 |
+
### Event: `'drain'`
|
| 83 |
+
|
| 84 |
+
See [Dispatcher Event: `'drain'`](/docs/docs/api/Dispatcher.md#event-drain).
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/docs/docs/api/PoolStats.md
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Class: PoolStats
|
| 2 |
+
|
| 3 |
+
Aggregate stats for a [Pool](/docs/docs/api/Pool.md) or [BalancedPool](/docs/docs/api/BalancedPool.md).
|
| 4 |
+
|
| 5 |
+
## `new PoolStats(pool)`
|
| 6 |
+
|
| 7 |
+
Arguments:
|
| 8 |
+
|
| 9 |
+
* **pool** `Pool` - Pool or BalancedPool from which to return stats.
|
| 10 |
+
|
| 11 |
+
## Instance Properties
|
| 12 |
+
|
| 13 |
+
### `PoolStats.connected`
|
| 14 |
+
|
| 15 |
+
Number of open socket connections in this pool.
|
| 16 |
+
|
| 17 |
+
### `PoolStats.free`
|
| 18 |
+
|
| 19 |
+
Number of open socket connections in this pool that do not have an active request.
|
| 20 |
+
|
| 21 |
+
### `PoolStats.pending`
|
| 22 |
+
|
| 23 |
+
Number of pending requests across all clients in this pool.
|
| 24 |
+
|
| 25 |
+
### `PoolStats.queued`
|
| 26 |
+
|
| 27 |
+
Number of queued requests across all clients in this pool.
|
| 28 |
+
|
| 29 |
+
### `PoolStats.running`
|
| 30 |
+
|
| 31 |
+
Number of currently active requests across all clients in this pool.
|
| 32 |
+
|
| 33 |
+
### `PoolStats.size`
|
| 34 |
+
|
| 35 |
+
Number of active, pending, or queued requests across all clients in this pool.
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/docs/docs/api/ProxyAgent.md
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Class: ProxyAgent
|
| 2 |
+
|
| 3 |
+
Extends: `undici.Dispatcher`
|
| 4 |
+
|
| 5 |
+
A Proxy Agent class that implements the Agent API. It allows the connection through proxy in a simple way.
|
| 6 |
+
|
| 7 |
+
## `new ProxyAgent([options])`
|
| 8 |
+
|
| 9 |
+
Arguments:
|
| 10 |
+
|
| 11 |
+
* **options** `ProxyAgentOptions` (required) - It extends the `Agent` options.
|
| 12 |
+
|
| 13 |
+
Returns: `ProxyAgent`
|
| 14 |
+
|
| 15 |
+
### Parameter: `ProxyAgentOptions`
|
| 16 |
+
|
| 17 |
+
Extends: [`AgentOptions`](/docs/docs/api/Agent.md#parameter-agentoptions)
|
| 18 |
+
> It ommits `AgentOptions#connect`.
|
| 19 |
+
|
| 20 |
+
> **Note:** When `AgentOptions#connections` is set, and different from `0`, the non-standard [`proxy-connection` header](https://udger.com/resources/http-request-headers-detail?header=Proxy-Connection) will be set to `keep-alive` in the request.
|
| 21 |
+
|
| 22 |
+
* **uri** `string | URL` (required) - The URI of the proxy server. This can be provided as a string, as an instance of the URL class, or as an object with a `uri` property of type string.
|
| 23 |
+
If the `uri` is provided as a string or `uri` is an object with an `uri` property of type string, then it will be parsed into a `URL` object according to the [WHATWG URL Specification](https://url.spec.whatwg.org).
|
| 24 |
+
For detailed information on the parsing process and potential validation errors, please refer to the ["Writing" section](https://url.spec.whatwg.org/#writing) of the WHATWG URL Specification.
|
| 25 |
+
* **token** `string` (optional) - It can be passed by a string of token for authentication.
|
| 26 |
+
* **auth** `string` (**deprecated**) - Use token.
|
| 27 |
+
* **clientFactory** `(origin: URL, opts: Object) => Dispatcher` (optional) - Default: `(origin, opts) => new Pool(origin, opts)`
|
| 28 |
+
* **requestTls** `BuildOptions` (optional) - Options object passed when creating the underlying socket via the connector builder for the request. It extends from [`Client#ConnectOptions`](/docs/docs/api/Client.md#parameter-connectoptions).
|
| 29 |
+
* **proxyTls** `BuildOptions` (optional) - Options object passed when creating the underlying socket via the connector builder for the proxy server. It extends from [`Client#ConnectOptions`](/docs/docs/api/Client.md#parameter-connectoptions).
|
| 30 |
+
* **proxyTunnel** `boolean` (optional) - For connections involving secure protocols, Undici will always establish a tunnel via the HTTP2 CONNECT extension. If proxyTunnel is set to true, this will occur for unsecured proxy/endpoint connections as well. Currently, there is no way to facilitate HTTP1 IP tunneling as described in https://www.rfc-editor.org/rfc/rfc9484.html#name-http-11-request. If proxyTunnel is set to false (the default), ProxyAgent connections where both the Proxy and Endpoint are unsecured will issue all requests to the Proxy, and prefix the endpoint request path with the endpoint origin address.
|
| 31 |
+
|
| 32 |
+
Examples:
|
| 33 |
+
|
| 34 |
+
```js
|
| 35 |
+
import { ProxyAgent } from 'undici'
|
| 36 |
+
|
| 37 |
+
const proxyAgent = new ProxyAgent('my.proxy.server')
|
| 38 |
+
// or
|
| 39 |
+
const proxyAgent = new ProxyAgent(new URL('my.proxy.server'))
|
| 40 |
+
// or
|
| 41 |
+
const proxyAgent = new ProxyAgent({ uri: 'my.proxy.server' })
|
| 42 |
+
// or
|
| 43 |
+
const proxyAgent = new ProxyAgent({
|
| 44 |
+
uri: new URL('my.proxy.server'),
|
| 45 |
+
proxyTls: {
|
| 46 |
+
signal: AbortSignal.timeout(1000)
|
| 47 |
+
}
|
| 48 |
+
})
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
#### Example - Basic ProxyAgent instantiation
|
| 52 |
+
|
| 53 |
+
This will instantiate the ProxyAgent. It will not do anything until registered as the agent to use with requests.
|
| 54 |
+
|
| 55 |
+
```js
|
| 56 |
+
import { ProxyAgent } from 'undici'
|
| 57 |
+
|
| 58 |
+
const proxyAgent = new ProxyAgent('my.proxy.server')
|
| 59 |
+
```
|
| 60 |
+
|
| 61 |
+
#### Example - Basic Proxy Request with global agent dispatcher
|
| 62 |
+
|
| 63 |
+
```js
|
| 64 |
+
import { setGlobalDispatcher, request, ProxyAgent } from 'undici'
|
| 65 |
+
|
| 66 |
+
const proxyAgent = new ProxyAgent('my.proxy.server')
|
| 67 |
+
setGlobalDispatcher(proxyAgent)
|
| 68 |
+
|
| 69 |
+
const { statusCode, body } = await request('http://localhost:3000/foo')
|
| 70 |
+
|
| 71 |
+
console.log('response received', statusCode) // response received 200
|
| 72 |
+
|
| 73 |
+
for await (const data of body) {
|
| 74 |
+
console.log('data', data.toString('utf8')) // data foo
|
| 75 |
+
}
|
| 76 |
+
```
|
| 77 |
+
|
| 78 |
+
#### Example - Basic Proxy Request with local agent dispatcher
|
| 79 |
+
|
| 80 |
+
```js
|
| 81 |
+
import { ProxyAgent, request } from 'undici'
|
| 82 |
+
|
| 83 |
+
const proxyAgent = new ProxyAgent('my.proxy.server')
|
| 84 |
+
|
| 85 |
+
const {
|
| 86 |
+
statusCode,
|
| 87 |
+
body
|
| 88 |
+
} = await request('http://localhost:3000/foo', { dispatcher: proxyAgent })
|
| 89 |
+
|
| 90 |
+
console.log('response received', statusCode) // response received 200
|
| 91 |
+
|
| 92 |
+
for await (const data of body) {
|
| 93 |
+
console.log('data', data.toString('utf8')) // data foo
|
| 94 |
+
}
|
| 95 |
+
```
|
| 96 |
+
|
| 97 |
+
#### Example - Basic Proxy Request with authentication
|
| 98 |
+
|
| 99 |
+
```js
|
| 100 |
+
import { setGlobalDispatcher, request, ProxyAgent } from 'undici';
|
| 101 |
+
|
| 102 |
+
const proxyAgent = new ProxyAgent({
|
| 103 |
+
uri: 'my.proxy.server',
|
| 104 |
+
// token: 'Bearer xxxx'
|
| 105 |
+
token: `Basic ${Buffer.from('username:password').toString('base64')}`
|
| 106 |
+
});
|
| 107 |
+
setGlobalDispatcher(proxyAgent);
|
| 108 |
+
|
| 109 |
+
const { statusCode, body } = await request('http://localhost:3000/foo');
|
| 110 |
+
|
| 111 |
+
console.log('response received', statusCode); // response received 200
|
| 112 |
+
|
| 113 |
+
for await (const data of body) {
|
| 114 |
+
console.log('data', data.toString('utf8')); // data foo
|
| 115 |
+
}
|
| 116 |
+
```
|
| 117 |
+
|
| 118 |
+
### `ProxyAgent.close()`
|
| 119 |
+
|
| 120 |
+
Closes the proxy agent and waits for registered pools and clients to also close before resolving.
|
| 121 |
+
|
| 122 |
+
Returns: `Promise<void>`
|
| 123 |
+
|
| 124 |
+
#### Example - clean up after tests are complete
|
| 125 |
+
|
| 126 |
+
```js
|
| 127 |
+
import { ProxyAgent, setGlobalDispatcher } from 'undici'
|
| 128 |
+
|
| 129 |
+
const proxyAgent = new ProxyAgent('my.proxy.server')
|
| 130 |
+
setGlobalDispatcher(proxyAgent)
|
| 131 |
+
|
| 132 |
+
await proxyAgent.close()
|
| 133 |
+
```
|
| 134 |
+
|
| 135 |
+
### `ProxyAgent.dispatch(options, handlers)`
|
| 136 |
+
|
| 137 |
+
Implements [`Agent.dispatch(options, handlers)`](/docs/docs/api/Agent.md#parameter-agentdispatchoptions).
|
| 138 |
+
|
| 139 |
+
### `ProxyAgent.request(options[, callback])`
|
| 140 |
+
|
| 141 |
+
See [`Dispatcher.request(options [, callback])`](/docs/docs/api/Dispatcher.md#dispatcherrequestoptions-callback).
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
#### Example - ProxyAgent with Fetch
|
| 145 |
+
|
| 146 |
+
This example demonstrates how to use `fetch` with a proxy via `ProxyAgent`. It is particularly useful for scenarios requiring proxy tunneling.
|
| 147 |
+
|
| 148 |
+
```javascript
|
| 149 |
+
import { ProxyAgent, fetch } from 'undici';
|
| 150 |
+
|
| 151 |
+
// Define the ProxyAgent
|
| 152 |
+
const proxyAgent = new ProxyAgent('http://localhost:8000');
|
| 153 |
+
|
| 154 |
+
// Make a GET request through the proxy
|
| 155 |
+
const response = await fetch('http://localhost:3000/foo', {
|
| 156 |
+
dispatcher: proxyAgent,
|
| 157 |
+
method: 'GET',
|
| 158 |
+
});
|
| 159 |
+
|
| 160 |
+
console.log('Response status:', response.status);
|
| 161 |
+
console.log('Response data:', await response.text());
|
| 162 |
+
```
|
| 163 |
+
|
| 164 |
+
---
|
| 165 |
+
|
| 166 |
+
#### Example - ProxyAgent with a Custom Proxy Server
|
| 167 |
+
|
| 168 |
+
This example shows how to create a custom proxy server and use it with `ProxyAgent`.
|
| 169 |
+
|
| 170 |
+
```javascript
|
| 171 |
+
import * as http from 'node:http';
|
| 172 |
+
import { createProxy } from 'proxy';
|
| 173 |
+
import { ProxyAgent, fetch } from 'undici';
|
| 174 |
+
|
| 175 |
+
// Create a proxy server
|
| 176 |
+
const proxyServer = createProxy(http.createServer());
|
| 177 |
+
proxyServer.listen(8000, () => {
|
| 178 |
+
console.log('Proxy server running on port 8000');
|
| 179 |
+
});
|
| 180 |
+
|
| 181 |
+
// Define and use the ProxyAgent
|
| 182 |
+
const proxyAgent = new ProxyAgent('http://localhost:8000');
|
| 183 |
+
|
| 184 |
+
const response = await fetch('http://example.com', {
|
| 185 |
+
dispatcher: proxyAgent,
|
| 186 |
+
method: 'GET',
|
| 187 |
+
});
|
| 188 |
+
|
| 189 |
+
console.log('Response status:', response.status);
|
| 190 |
+
console.log('Response data:', await response.text());
|
| 191 |
+
```
|
| 192 |
+
|
| 193 |
+
---
|
| 194 |
+
|
| 195 |
+
#### Example - ProxyAgent with HTTPS Tunneling
|
| 196 |
+
|
| 197 |
+
This example demonstrates how to perform HTTPS tunneling using a proxy.
|
| 198 |
+
|
| 199 |
+
```javascript
|
| 200 |
+
import { ProxyAgent, fetch } from 'undici';
|
| 201 |
+
|
| 202 |
+
// Define a ProxyAgent for HTTPS proxy
|
| 203 |
+
const proxyAgent = new ProxyAgent('https://secure.proxy.server');
|
| 204 |
+
|
| 205 |
+
// Make a request to an HTTPS endpoint via the proxy
|
| 206 |
+
const response = await fetch('https://secure.endpoint.com/api/data', {
|
| 207 |
+
dispatcher: proxyAgent,
|
| 208 |
+
method: 'GET',
|
| 209 |
+
});
|
| 210 |
+
|
| 211 |
+
console.log('Response status:', response.status);
|
| 212 |
+
console.log('Response data:', await response.json());
|
| 213 |
+
```
|
| 214 |
+
|
| 215 |
+
#### Example - ProxyAgent as a Global Dispatcher
|
| 216 |
+
|
| 217 |
+
`ProxyAgent` can be configured as a global dispatcher, making it available for all requests without explicitly passing it. This simplifies code and is useful when a single proxy configuration applies to all requests.
|
| 218 |
+
|
| 219 |
+
```javascript
|
| 220 |
+
import { ProxyAgent, setGlobalDispatcher, fetch } from 'undici';
|
| 221 |
+
|
| 222 |
+
// Define and configure the ProxyAgent
|
| 223 |
+
const proxyAgent = new ProxyAgent('http://localhost:8000');
|
| 224 |
+
setGlobalDispatcher(proxyAgent);
|
| 225 |
+
|
| 226 |
+
// Make requests without specifying the dispatcher
|
| 227 |
+
const response = await fetch('http://example.com');
|
| 228 |
+
console.log('Response status:', response.status);
|
| 229 |
+
console.log('Response data:', await response.text());
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/docs/docs/api/RedirectHandler.md
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Class: RedirectHandler
|
| 2 |
+
|
| 3 |
+
A class that handles redirection logic for HTTP requests.
|
| 4 |
+
|
| 5 |
+
## `new RedirectHandler(dispatch, maxRedirections, opts, handler, redirectionLimitReached)`
|
| 6 |
+
|
| 7 |
+
Arguments:
|
| 8 |
+
|
| 9 |
+
- **dispatch** `function` - The dispatch function to be called after every retry.
|
| 10 |
+
- **maxRedirections** `number` - Maximum number of redirections allowed.
|
| 11 |
+
- **opts** `object` - Options for handling redirection.
|
| 12 |
+
- **handler** `object` - An object containing handlers for different stages of the request lifecycle.
|
| 13 |
+
- **redirectionLimitReached** `boolean` (default: `false`) - A flag that the implementer can provide to enable or disable the feature. If set to `false`, it indicates that the caller doesn't want to use the feature and prefers the old behavior.
|
| 14 |
+
|
| 15 |
+
Returns: `RedirectHandler`
|
| 16 |
+
|
| 17 |
+
### Parameters
|
| 18 |
+
|
| 19 |
+
- **dispatch** `(options: Dispatch.DispatchOptions, handlers: Dispatch.DispatchHandler) => Promise<Dispatch.DispatchResponse>` (required) - Dispatch function to be called after every redirection.
|
| 20 |
+
- **maxRedirections** `number` (required) - Maximum number of redirections allowed.
|
| 21 |
+
- **opts** `object` (required) - Options for handling redirection.
|
| 22 |
+
- **handler** `object` (required) - Handlers for different stages of the request lifecycle.
|
| 23 |
+
- **redirectionLimitReached** `boolean` (default: `false`) - A flag that the implementer can provide to enable or disable the feature. If set to `false`, it indicates that the caller doesn't want to use the feature and prefers the old behavior.
|
| 24 |
+
|
| 25 |
+
### Properties
|
| 26 |
+
|
| 27 |
+
- **location** `string` - The current redirection location.
|
| 28 |
+
- **abort** `function` - The abort function.
|
| 29 |
+
- **opts** `object` - The options for handling redirection.
|
| 30 |
+
- **maxRedirections** `number` - Maximum number of redirections allowed.
|
| 31 |
+
- **handler** `object` - Handlers for different stages of the request lifecycle.
|
| 32 |
+
- **history** `Array` - An array representing the history of URLs during redirection.
|
| 33 |
+
- **redirectionLimitReached** `boolean` - Indicates whether the redirection limit has been reached.
|
| 34 |
+
|
| 35 |
+
### Methods
|
| 36 |
+
|
| 37 |
+
#### `onConnect(abort)`
|
| 38 |
+
|
| 39 |
+
Called when the connection is established.
|
| 40 |
+
|
| 41 |
+
Parameters:
|
| 42 |
+
|
| 43 |
+
- **abort** `function` - The abort function.
|
| 44 |
+
|
| 45 |
+
#### `onUpgrade(statusCode, headers, socket)`
|
| 46 |
+
|
| 47 |
+
Called when an upgrade is requested.
|
| 48 |
+
|
| 49 |
+
Parameters:
|
| 50 |
+
|
| 51 |
+
- **statusCode** `number` - The HTTP status code.
|
| 52 |
+
- **headers** `object` - The headers received in the response.
|
| 53 |
+
- **socket** `object` - The socket object.
|
| 54 |
+
|
| 55 |
+
#### `onError(error)`
|
| 56 |
+
|
| 57 |
+
Called when an error occurs.
|
| 58 |
+
|
| 59 |
+
Parameters:
|
| 60 |
+
|
| 61 |
+
- **error** `Error` - The error that occurred.
|
| 62 |
+
|
| 63 |
+
#### `onHeaders(statusCode, headers, resume, statusText)`
|
| 64 |
+
|
| 65 |
+
Called when headers are received.
|
| 66 |
+
|
| 67 |
+
Parameters:
|
| 68 |
+
|
| 69 |
+
- **statusCode** `number` - The HTTP status code.
|
| 70 |
+
- **headers** `object` - The headers received in the response.
|
| 71 |
+
- **resume** `function` - The resume function.
|
| 72 |
+
- **statusText** `string` - The status text.
|
| 73 |
+
|
| 74 |
+
#### `onData(chunk)`
|
| 75 |
+
|
| 76 |
+
Called when data is received.
|
| 77 |
+
|
| 78 |
+
Parameters:
|
| 79 |
+
|
| 80 |
+
- **chunk** `Buffer` - The data chunk received.
|
| 81 |
+
|
| 82 |
+
#### `onComplete(trailers)`
|
| 83 |
+
|
| 84 |
+
Called when the request is complete.
|
| 85 |
+
|
| 86 |
+
Parameters:
|
| 87 |
+
|
| 88 |
+
- **trailers** `object` - The trailers received.
|
| 89 |
+
|
| 90 |
+
#### `onBodySent(chunk)`
|
| 91 |
+
|
| 92 |
+
Called when the request body is sent.
|
| 93 |
+
|
| 94 |
+
Parameters:
|
| 95 |
+
|
| 96 |
+
- **chunk** `Buffer` - The chunk of the request body sent.
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/docs/docs/api/RetryAgent.md
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Class: RetryAgent
|
| 2 |
+
|
| 3 |
+
Extends: `undici.Dispatcher`
|
| 4 |
+
|
| 5 |
+
A `undici.Dispatcher` that allows to automatically retry a request.
|
| 6 |
+
Wraps a `undici.RetryHandler`.
|
| 7 |
+
|
| 8 |
+
## `new RetryAgent(dispatcher, [options])`
|
| 9 |
+
|
| 10 |
+
Arguments:
|
| 11 |
+
|
| 12 |
+
* **dispatcher** `undici.Dispatcher` (required) - the dispatcher to wrap
|
| 13 |
+
* **options** `RetryHandlerOptions` (optional) - the options
|
| 14 |
+
|
| 15 |
+
Returns: `ProxyAgent`
|
| 16 |
+
|
| 17 |
+
### Parameter: `RetryHandlerOptions`
|
| 18 |
+
|
| 19 |
+
- **throwOnError** `boolean` (optional) - Disable to prevent throwing error on last retry attept, useful if you need the body on errors from server or if you have custom error handler. Default: `true`
|
| 20 |
+
- **retry** `(err: Error, context: RetryContext, callback: (err?: Error | null) => void) => void` (optional) - Function to be called after every retry. It should pass error if no more retries should be performed.
|
| 21 |
+
- **maxRetries** `number` (optional) - Maximum number of retries. Default: `5`
|
| 22 |
+
- **maxTimeout** `number` (optional) - Maximum number of milliseconds to wait before retrying. Default: `30000` (30 seconds)
|
| 23 |
+
- **minTimeout** `number` (optional) - Minimum number of milliseconds to wait before retrying. Default: `500` (half a second)
|
| 24 |
+
- **timeoutFactor** `number` (optional) - Factor to multiply the timeout by for each retry attempt. Default: `2`
|
| 25 |
+
- **retryAfter** `boolean` (optional) - It enables automatic retry after the `Retry-After` header is received. Default: `true`
|
| 26 |
+
-
|
| 27 |
+
- **methods** `string[]` (optional) - Array of HTTP methods to retry. Default: `['GET', 'PUT', 'HEAD', 'OPTIONS', 'DELETE']`
|
| 28 |
+
- **statusCodes** `number[]` (optional) - Array of HTTP status codes to retry. Default: `[429, 500, 502, 503, 504]`
|
| 29 |
+
- **errorCodes** `string[]` (optional) - Array of Error codes to retry. Default: `['ECONNRESET', 'ECONNREFUSED', 'ENOTFOUND', 'ENETDOWN','ENETUNREACH', 'EHOSTDOWN', 'UND_ERR_SOCKET']`
|
| 30 |
+
|
| 31 |
+
**`RetryContext`**
|
| 32 |
+
|
| 33 |
+
- `state`: `RetryState` - Current retry state. It can be mutated.
|
| 34 |
+
- `opts`: `Dispatch.DispatchOptions & RetryOptions` - Options passed to the retry handler.
|
| 35 |
+
|
| 36 |
+
Example:
|
| 37 |
+
|
| 38 |
+
```js
|
| 39 |
+
import { Agent, RetryAgent } from 'undici'
|
| 40 |
+
|
| 41 |
+
const agent = new RetryAgent(new Agent())
|
| 42 |
+
|
| 43 |
+
const res = await agent.request({
|
| 44 |
+
method: 'GET',
|
| 45 |
+
origin: 'http://example.com',
|
| 46 |
+
path: '/',
|
| 47 |
+
})
|
| 48 |
+
console.log(res.statusCode)
|
| 49 |
+
console.log(await res.body.text())
|
| 50 |
+
```
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/docs/docs/api/RetryHandler.md
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Class: RetryHandler
|
| 2 |
+
|
| 3 |
+
Extends: `undici.DispatcherHandlers`
|
| 4 |
+
|
| 5 |
+
A handler class that implements the retry logic for a request.
|
| 6 |
+
|
| 7 |
+
## `new RetryHandler(dispatchOptions, retryHandlers, [retryOptions])`
|
| 8 |
+
|
| 9 |
+
Arguments:
|
| 10 |
+
|
| 11 |
+
- **options** `Dispatch.DispatchOptions & RetryOptions` (required) - It is an intersection of `Dispatcher.DispatchOptions` and `RetryOptions`.
|
| 12 |
+
- **retryHandlers** `RetryHandlers` (required) - Object containing the `dispatch` to be used on every retry, and `handler` for handling the `dispatch` lifecycle.
|
| 13 |
+
|
| 14 |
+
Returns: `retryHandler`
|
| 15 |
+
|
| 16 |
+
### Parameter: `Dispatch.DispatchOptions & RetryOptions`
|
| 17 |
+
|
| 18 |
+
Extends: [`Dispatch.DispatchOptions`](/docs/docs/api/Dispatcher.md#parameter-dispatchoptions).
|
| 19 |
+
|
| 20 |
+
#### `RetryOptions`
|
| 21 |
+
|
| 22 |
+
- **throwOnError** `boolean` (optional) - Disable to prevent throwing error on last retry attept, useful if you need the body on errors from server or if you have custom error handler.
|
| 23 |
+
- **retry** `(err: Error, context: RetryContext, callback: (err?: Error | null) => void) => number | null` (optional) - Function to be called after every retry. It should pass error if no more retries should be performed.
|
| 24 |
+
- **maxRetries** `number` (optional) - Maximum number of retries. Default: `5`
|
| 25 |
+
- **maxTimeout** `number` (optional) - Maximum number of milliseconds to wait before retrying. Default: `30000` (30 seconds)
|
| 26 |
+
- **minTimeout** `number` (optional) - Minimum number of milliseconds to wait before retrying. Default: `500` (half a second)
|
| 27 |
+
- **timeoutFactor** `number` (optional) - Factor to multiply the timeout by for each retry attempt. Default: `2`
|
| 28 |
+
- **retryAfter** `boolean` (optional) - It enables automatic retry after the `Retry-After` header is received. Default: `true`
|
| 29 |
+
-
|
| 30 |
+
- **methods** `string[]` (optional) - Array of HTTP methods to retry. Default: `['GET', 'PUT', 'HEAD', 'OPTIONS', 'DELETE']`
|
| 31 |
+
- **statusCodes** `number[]` (optional) - Array of HTTP status codes to retry. Default: `[429, 500, 502, 503, 504]`
|
| 32 |
+
- **errorCodes** `string[]` (optional) - Array of Error codes to retry. Default: `['ECONNRESET', 'ECONNREFUSED', 'ENOTFOUND', 'ENETDOWN','ENETUNREACH', 'EHOSTDOWN', 'UND_ERR_SOCKET']`
|
| 33 |
+
|
| 34 |
+
**`RetryContext`**
|
| 35 |
+
|
| 36 |
+
- `state`: `RetryState` - Current retry state. It can be mutated.
|
| 37 |
+
- `opts`: `Dispatch.DispatchOptions & RetryOptions` - Options passed to the retry handler.
|
| 38 |
+
|
| 39 |
+
**`RetryState`**
|
| 40 |
+
|
| 41 |
+
It represents the retry state for a given request.
|
| 42 |
+
|
| 43 |
+
- `counter`: `number` - Current retry attempt.
|
| 44 |
+
|
| 45 |
+
### Parameter `RetryHandlers`
|
| 46 |
+
|
| 47 |
+
- **dispatch** `(options: Dispatch.DispatchOptions, handlers: Dispatch.DispatchHandler) => Promise<Dispatch.DispatchResponse>` (required) - Dispatch function to be called after every retry.
|
| 48 |
+
- **handler** Extends [`Dispatch.DispatchHandler`](/docs/docs/api/Dispatcher.md#dispatcherdispatchoptions-handler) (required) - Handler function to be called after the request is successful or the retries are exhausted.
|
| 49 |
+
|
| 50 |
+
>__Note__: The `RetryHandler` does not retry over stateful bodies (e.g. streams, AsyncIterable) as those, once consumed, are left in a state that cannot be reutilized. For these situations the `RetryHandler` will identify
|
| 51 |
+
>the body as stateful and will not retry the request rejecting with the error `UND_ERR_REQ_RETRY`.
|
| 52 |
+
|
| 53 |
+
Examples:
|
| 54 |
+
|
| 55 |
+
```js
|
| 56 |
+
const client = new Client(`http://localhost:${server.address().port}`);
|
| 57 |
+
const chunks = [];
|
| 58 |
+
const handler = new RetryHandler(
|
| 59 |
+
{
|
| 60 |
+
...dispatchOptions,
|
| 61 |
+
retryOptions: {
|
| 62 |
+
// custom retry function
|
| 63 |
+
retry: function (err, state, callback) {
|
| 64 |
+
counter++;
|
| 65 |
+
|
| 66 |
+
if (err.code && err.code === "UND_ERR_DESTROYED") {
|
| 67 |
+
callback(err);
|
| 68 |
+
return;
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
if (err.statusCode === 206) {
|
| 72 |
+
callback(err);
|
| 73 |
+
return;
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
setTimeout(() => callback(null), 1000);
|
| 77 |
+
},
|
| 78 |
+
},
|
| 79 |
+
},
|
| 80 |
+
{
|
| 81 |
+
dispatch: (...args) => {
|
| 82 |
+
return client.dispatch(...args);
|
| 83 |
+
},
|
| 84 |
+
handler: {
|
| 85 |
+
onConnect() {},
|
| 86 |
+
onBodySent() {},
|
| 87 |
+
onHeaders(status, _rawHeaders, resume, _statusMessage) {
|
| 88 |
+
// do something with headers
|
| 89 |
+
},
|
| 90 |
+
onData(chunk) {
|
| 91 |
+
chunks.push(chunk);
|
| 92 |
+
return true;
|
| 93 |
+
},
|
| 94 |
+
onComplete() {},
|
| 95 |
+
onError() {
|
| 96 |
+
// handle error properly
|
| 97 |
+
},
|
| 98 |
+
},
|
| 99 |
+
}
|
| 100 |
+
);
|
| 101 |
+
```
|
| 102 |
+
|
| 103 |
+
#### Example - Basic RetryHandler with defaults
|
| 104 |
+
|
| 105 |
+
```js
|
| 106 |
+
const client = new Client(`http://localhost:${server.address().port}`);
|
| 107 |
+
const handler = new RetryHandler(dispatchOptions, {
|
| 108 |
+
dispatch: client.dispatch.bind(client),
|
| 109 |
+
handler: {
|
| 110 |
+
onConnect() {},
|
| 111 |
+
onBodySent() {},
|
| 112 |
+
onHeaders(status, _rawHeaders, resume, _statusMessage) {},
|
| 113 |
+
onData(chunk) {},
|
| 114 |
+
onComplete() {},
|
| 115 |
+
onError(err) {},
|
| 116 |
+
},
|
| 117 |
+
});
|
| 118 |
+
```
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/docs/docs/api/SnapshotAgent.md
ADDED
|
@@ -0,0 +1,616 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SnapshotAgent
|
| 2 |
+
|
| 3 |
+
The `SnapshotAgent` provides a powerful way to record and replay HTTP requests for testing purposes. It extends `MockAgent` to enable automatic snapshot testing, eliminating the need to manually define mock responses.
|
| 4 |
+
|
| 5 |
+
## Use Cases
|
| 6 |
+
|
| 7 |
+
- **Integration Testing**: Record real API interactions and replay them in tests
|
| 8 |
+
- **Offline Development**: Work with APIs without network connectivity
|
| 9 |
+
- **Consistent Test Data**: Ensure tests use the same responses across runs
|
| 10 |
+
- **API Contract Testing**: Capture and validate API behavior over time
|
| 11 |
+
|
| 12 |
+
## Constructor
|
| 13 |
+
|
| 14 |
+
```javascript
|
| 15 |
+
new SnapshotAgent([options])
|
| 16 |
+
```
|
| 17 |
+
|
| 18 |
+
### Parameters
|
| 19 |
+
|
| 20 |
+
- **options** `Object` (optional)
|
| 21 |
+
- **mode** `String` - The snapshot mode: `'record'`, `'playback'`, or `'update'`. Default: `'record'`
|
| 22 |
+
- **snapshotPath** `String` - Path to the snapshot file for loading/saving
|
| 23 |
+
- **maxSnapshots** `Number` - Maximum number of snapshots to keep in memory. Default: `Infinity`
|
| 24 |
+
- **autoFlush** `Boolean` - Whether to automatically save snapshots to disk. Default: `false`
|
| 25 |
+
- **flushInterval** `Number` - Interval in milliseconds for auto-flush. Default: `30000`
|
| 26 |
+
- **matchHeaders** `Array<String>` - Specific headers to include in request matching. Default: all headers
|
| 27 |
+
- **ignoreHeaders** `Array<String>` - Headers to ignore during request matching
|
| 28 |
+
- **excludeHeaders** `Array<String>` - Headers to exclude from snapshots (for security)
|
| 29 |
+
- **matchBody** `Boolean` - Whether to include request body in matching. Default: `true`
|
| 30 |
+
- **matchQuery** `Boolean` - Whether to include query parameters in matching. Default: `true`
|
| 31 |
+
- **caseSensitive** `Boolean` - Whether header matching is case-sensitive. Default: `false`
|
| 32 |
+
- **shouldRecord** `Function` - Callback to determine if a request should be recorded
|
| 33 |
+
- **shouldPlayback** `Function` - Callback to determine if a request should be played back
|
| 34 |
+
- **excludeUrls** `Array` - URL patterns (strings or RegExp) to exclude from recording/playback
|
| 35 |
+
- All other options from `MockAgent` are supported
|
| 36 |
+
|
| 37 |
+
### Modes
|
| 38 |
+
|
| 39 |
+
#### Record Mode (`'record'`)
|
| 40 |
+
Makes real HTTP requests and saves the responses to snapshots.
|
| 41 |
+
|
| 42 |
+
```javascript
|
| 43 |
+
import { SnapshotAgent, setGlobalDispatcher } from 'undici'
|
| 44 |
+
|
| 45 |
+
const agent = new SnapshotAgent({
|
| 46 |
+
mode: 'record',
|
| 47 |
+
snapshotPath: './test/snapshots/api-calls.json'
|
| 48 |
+
})
|
| 49 |
+
setGlobalDispatcher(agent)
|
| 50 |
+
|
| 51 |
+
// Makes real requests and records them
|
| 52 |
+
const response = await fetch('https://api.example.com/users')
|
| 53 |
+
const users = await response.json()
|
| 54 |
+
|
| 55 |
+
// Save recorded snapshots
|
| 56 |
+
await agent.saveSnapshots()
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
#### Playback Mode (`'playback'`)
|
| 60 |
+
Replays recorded responses without making real HTTP requests.
|
| 61 |
+
|
| 62 |
+
```javascript
|
| 63 |
+
import { SnapshotAgent, setGlobalDispatcher } from 'undici'
|
| 64 |
+
|
| 65 |
+
const agent = new SnapshotAgent({
|
| 66 |
+
mode: 'playback',
|
| 67 |
+
snapshotPath: './test/snapshots/api-calls.json'
|
| 68 |
+
})
|
| 69 |
+
setGlobalDispatcher(agent)
|
| 70 |
+
|
| 71 |
+
// Uses recorded response instead of real request
|
| 72 |
+
const response = await fetch('https://api.example.com/users')
|
| 73 |
+
```
|
| 74 |
+
|
| 75 |
+
#### Update Mode (`'update'`)
|
| 76 |
+
Uses existing snapshots when available, but records new ones for missing requests.
|
| 77 |
+
|
| 78 |
+
```javascript
|
| 79 |
+
import { SnapshotAgent, setGlobalDispatcher } from 'undici'
|
| 80 |
+
|
| 81 |
+
const agent = new SnapshotAgent({
|
| 82 |
+
mode: 'update',
|
| 83 |
+
snapshotPath: './test/snapshots/api-calls.json'
|
| 84 |
+
})
|
| 85 |
+
setGlobalDispatcher(agent)
|
| 86 |
+
|
| 87 |
+
// Uses snapshot if exists, otherwise makes real request and records it
|
| 88 |
+
const response = await fetch('https://api.example.com/new-endpoint')
|
| 89 |
+
```
|
| 90 |
+
|
| 91 |
+
## Instance Methods
|
| 92 |
+
|
| 93 |
+
### `agent.saveSnapshots([filePath])`
|
| 94 |
+
|
| 95 |
+
Saves all recorded snapshots to a file.
|
| 96 |
+
|
| 97 |
+
#### Parameters
|
| 98 |
+
|
| 99 |
+
- **filePath** `String` (optional) - Path to save snapshots. Uses constructor `snapshotPath` if not provided.
|
| 100 |
+
|
| 101 |
+
#### Returns
|
| 102 |
+
|
| 103 |
+
`Promise<void>`
|
| 104 |
+
|
| 105 |
+
```javascript
|
| 106 |
+
await agent.saveSnapshots('./custom-snapshots.json')
|
| 107 |
+
```
|
| 108 |
+
|
| 109 |
+
## Advanced Configuration
|
| 110 |
+
|
| 111 |
+
### Header Filtering
|
| 112 |
+
|
| 113 |
+
Control which headers are used for request matching and what gets stored in snapshots:
|
| 114 |
+
|
| 115 |
+
```javascript
|
| 116 |
+
const agent = new SnapshotAgent({
|
| 117 |
+
mode: 'record',
|
| 118 |
+
snapshotPath: './snapshots.json',
|
| 119 |
+
|
| 120 |
+
// Only match these specific headers
|
| 121 |
+
matchHeaders: ['content-type', 'accept'],
|
| 122 |
+
|
| 123 |
+
// Ignore these headers during matching (but still store them)
|
| 124 |
+
ignoreHeaders: ['user-agent', 'date'],
|
| 125 |
+
|
| 126 |
+
// Exclude sensitive headers from snapshots entirely
|
| 127 |
+
excludeHeaders: ['authorization', 'x-api-key', 'cookie']
|
| 128 |
+
})
|
| 129 |
+
```
|
| 130 |
+
|
| 131 |
+
### Custom Request/Response Filtering
|
| 132 |
+
|
| 133 |
+
Use callback functions to determine what gets recorded or played back:
|
| 134 |
+
|
| 135 |
+
```javascript
|
| 136 |
+
const agent = new SnapshotAgent({
|
| 137 |
+
mode: 'record',
|
| 138 |
+
snapshotPath: './snapshots.json',
|
| 139 |
+
|
| 140 |
+
// Only record GET requests to specific endpoints
|
| 141 |
+
shouldRecord: (requestOpts) => {
|
| 142 |
+
const url = new URL(requestOpts.path, requestOpts.origin)
|
| 143 |
+
return requestOpts.method === 'GET' && url.pathname.startsWith('/api/v1/')
|
| 144 |
+
},
|
| 145 |
+
|
| 146 |
+
// Skip authentication endpoints during playback
|
| 147 |
+
shouldPlayback: (requestOpts) => {
|
| 148 |
+
const url = new URL(requestOpts.path, requestOpts.origin)
|
| 149 |
+
return !url.pathname.includes('/auth/')
|
| 150 |
+
}
|
| 151 |
+
})
|
| 152 |
+
```
|
| 153 |
+
|
| 154 |
+
### URL Pattern Exclusion
|
| 155 |
+
|
| 156 |
+
Exclude specific URLs from recording/playback using patterns:
|
| 157 |
+
|
| 158 |
+
```javascript
|
| 159 |
+
const agent = new SnapshotAgent({
|
| 160 |
+
mode: 'record',
|
| 161 |
+
snapshotPath: './snapshots.json',
|
| 162 |
+
|
| 163 |
+
excludeUrls: [
|
| 164 |
+
'https://analytics.example.com', // String match
|
| 165 |
+
/\/api\/v\d+\/health/, // Regex pattern
|
| 166 |
+
'telemetry' // Substring match
|
| 167 |
+
]
|
| 168 |
+
})
|
| 169 |
+
```
|
| 170 |
+
|
| 171 |
+
### Memory Management
|
| 172 |
+
|
| 173 |
+
Configure automatic memory and disk management:
|
| 174 |
+
|
| 175 |
+
```javascript
|
| 176 |
+
const agent = new SnapshotAgent({
|
| 177 |
+
mode: 'record',
|
| 178 |
+
snapshotPath: './snapshots.json',
|
| 179 |
+
|
| 180 |
+
// Keep only 1000 snapshots in memory
|
| 181 |
+
maxSnapshots: 1000,
|
| 182 |
+
|
| 183 |
+
// Automatically save to disk every 30 seconds
|
| 184 |
+
autoFlush: true,
|
| 185 |
+
flushInterval: 30000
|
| 186 |
+
})
|
| 187 |
+
```
|
| 188 |
+
|
| 189 |
+
### Sequential Response Handling
|
| 190 |
+
|
| 191 |
+
Handle multiple responses for the same request (similar to nock):
|
| 192 |
+
|
| 193 |
+
```javascript
|
| 194 |
+
// In record mode, multiple identical requests get recorded as separate responses
|
| 195 |
+
const agent = new SnapshotAgent({ mode: 'record', snapshotPath: './sequential.json' })
|
| 196 |
+
|
| 197 |
+
// First call returns response A
|
| 198 |
+
await fetch('https://api.example.com/random')
|
| 199 |
+
|
| 200 |
+
// Second call returns response B
|
| 201 |
+
await fetch('https://api.example.com/random')
|
| 202 |
+
|
| 203 |
+
await agent.saveSnapshots()
|
| 204 |
+
|
| 205 |
+
// In playback mode, calls return responses in sequence
|
| 206 |
+
const playbackAgent = new SnapshotAgent({ mode: 'playback', snapshotPath: './sequential.json' })
|
| 207 |
+
|
| 208 |
+
// Returns response A
|
| 209 |
+
const first = await fetch('https://api.example.com/random')
|
| 210 |
+
|
| 211 |
+
// Returns response B
|
| 212 |
+
const second = await fetch('https://api.example.com/random')
|
| 213 |
+
|
| 214 |
+
// Third call repeats the last response (B)
|
| 215 |
+
const third = await fetch('https://api.example.com/random')
|
| 216 |
+
```
|
| 217 |
+
|
| 218 |
+
## Managing Snapshots
|
| 219 |
+
|
| 220 |
+
### Replacing Existing Snapshots
|
| 221 |
+
|
| 222 |
+
```javascript
|
| 223 |
+
// Load existing snapshots
|
| 224 |
+
await agent.loadSnapshots('./old-snapshots.json')
|
| 225 |
+
|
| 226 |
+
// Get snapshot data
|
| 227 |
+
const recorder = agent.getRecorder()
|
| 228 |
+
const snapshots = recorder.getSnapshots()
|
| 229 |
+
|
| 230 |
+
// Modify or filter snapshots
|
| 231 |
+
const filteredSnapshots = snapshots.filter(s =>
|
| 232 |
+
!s.request.url.includes('deprecated')
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
// Replace all snapshots
|
| 236 |
+
agent.replaceSnapshots(filteredSnapshots.map((snapshot, index) => ({
|
| 237 |
+
hash: `new-hash-${index}`,
|
| 238 |
+
snapshot
|
| 239 |
+
})))
|
| 240 |
+
|
| 241 |
+
// Save updated snapshots
|
| 242 |
+
await agent.saveSnapshots('./updated-snapshots.json')
|
| 243 |
+
```
|
| 244 |
+
|
| 245 |
+
### `agent.loadSnapshots([filePath])`
|
| 246 |
+
|
| 247 |
+
Loads snapshots from a file.
|
| 248 |
+
|
| 249 |
+
#### Parameters
|
| 250 |
+
|
| 251 |
+
- **filePath** `String` (optional) - Path to load snapshots from. Uses constructor `snapshotPath` if not provided.
|
| 252 |
+
|
| 253 |
+
#### Returns
|
| 254 |
+
|
| 255 |
+
`Promise<void>`
|
| 256 |
+
|
| 257 |
+
```javascript
|
| 258 |
+
await agent.loadSnapshots('./existing-snapshots.json')
|
| 259 |
+
```
|
| 260 |
+
|
| 261 |
+
### `agent.getRecorder()`
|
| 262 |
+
|
| 263 |
+
Gets the underlying `SnapshotRecorder` instance.
|
| 264 |
+
|
| 265 |
+
#### Returns
|
| 266 |
+
|
| 267 |
+
`SnapshotRecorder`
|
| 268 |
+
|
| 269 |
+
```javascript
|
| 270 |
+
const recorder = agent.getRecorder()
|
| 271 |
+
console.log(`Recorded ${recorder.size()} interactions`)
|
| 272 |
+
```
|
| 273 |
+
|
| 274 |
+
### `agent.getMode()`
|
| 275 |
+
|
| 276 |
+
Gets the current snapshot mode.
|
| 277 |
+
|
| 278 |
+
#### Returns
|
| 279 |
+
|
| 280 |
+
`String` - The current mode (`'record'`, `'playback'`, or `'update'`)
|
| 281 |
+
|
| 282 |
+
### `agent.clearSnapshots()`
|
| 283 |
+
|
| 284 |
+
Clears all recorded snapshots from memory.
|
| 285 |
+
|
| 286 |
+
```javascript
|
| 287 |
+
agent.clearSnapshots()
|
| 288 |
+
```
|
| 289 |
+
|
| 290 |
+
## Working with Different Request Types
|
| 291 |
+
|
| 292 |
+
### GET Requests
|
| 293 |
+
|
| 294 |
+
```javascript
|
| 295 |
+
// Record mode
|
| 296 |
+
const agent = new SnapshotAgent({ mode: 'record', snapshotPath: './get-snapshots.json' })
|
| 297 |
+
setGlobalDispatcher(agent)
|
| 298 |
+
|
| 299 |
+
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1')
|
| 300 |
+
const post = await response.json()
|
| 301 |
+
|
| 302 |
+
await agent.saveSnapshots()
|
| 303 |
+
```
|
| 304 |
+
|
| 305 |
+
### POST Requests with Body
|
| 306 |
+
|
| 307 |
+
```javascript
|
| 308 |
+
// Record mode
|
| 309 |
+
const agent = new SnapshotAgent({ mode: 'record', snapshotPath: './post-snapshots.json' })
|
| 310 |
+
setGlobalDispatcher(agent)
|
| 311 |
+
|
| 312 |
+
const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
|
| 313 |
+
method: 'POST',
|
| 314 |
+
headers: { 'Content-Type': 'application/json' },
|
| 315 |
+
body: JSON.stringify({ title: 'Test Post', body: 'Content' })
|
| 316 |
+
})
|
| 317 |
+
|
| 318 |
+
await agent.saveSnapshots()
|
| 319 |
+
```
|
| 320 |
+
|
| 321 |
+
### Using with `undici.request`
|
| 322 |
+
|
| 323 |
+
SnapshotAgent works with all undici APIs, not just fetch:
|
| 324 |
+
|
| 325 |
+
```javascript
|
| 326 |
+
import { SnapshotAgent, request, setGlobalDispatcher } from 'undici'
|
| 327 |
+
|
| 328 |
+
const agent = new SnapshotAgent({ mode: 'record', snapshotPath: './request-snapshots.json' })
|
| 329 |
+
setGlobalDispatcher(agent)
|
| 330 |
+
|
| 331 |
+
const { statusCode, headers, body } = await request('https://api.example.com/data')
|
| 332 |
+
const data = await body.json()
|
| 333 |
+
|
| 334 |
+
await agent.saveSnapshots()
|
| 335 |
+
```
|
| 336 |
+
|
| 337 |
+
## Test Integration
|
| 338 |
+
|
| 339 |
+
### Basic Test Setup
|
| 340 |
+
|
| 341 |
+
```javascript
|
| 342 |
+
import { test } from 'node:test'
|
| 343 |
+
import { SnapshotAgent, setGlobalDispatcher, getGlobalDispatcher } from 'undici'
|
| 344 |
+
|
| 345 |
+
test('API integration test', async (t) => {
|
| 346 |
+
const originalDispatcher = getGlobalDispatcher()
|
| 347 |
+
|
| 348 |
+
const agent = new SnapshotAgent({
|
| 349 |
+
mode: 'playback',
|
| 350 |
+
snapshotPath: './test/snapshots/api-test.json'
|
| 351 |
+
})
|
| 352 |
+
setGlobalDispatcher(agent)
|
| 353 |
+
|
| 354 |
+
t.after(() => setGlobalDispatcher(originalDispatcher))
|
| 355 |
+
|
| 356 |
+
// This will use recorded data
|
| 357 |
+
const response = await fetch('https://api.example.com/users')
|
| 358 |
+
const users = await response.json()
|
| 359 |
+
|
| 360 |
+
assert(Array.isArray(users))
|
| 361 |
+
assert(users.length > 0)
|
| 362 |
+
})
|
| 363 |
+
```
|
| 364 |
+
|
| 365 |
+
### Environment-Based Mode Selection
|
| 366 |
+
|
| 367 |
+
```javascript
|
| 368 |
+
const mode = process.env.SNAPSHOT_MODE || 'playback'
|
| 369 |
+
|
| 370 |
+
const agent = new SnapshotAgent({
|
| 371 |
+
mode,
|
| 372 |
+
snapshotPath: './test/snapshots/integration.json'
|
| 373 |
+
})
|
| 374 |
+
|
| 375 |
+
// Run with: SNAPSHOT_MODE=record npm test (to record)
|
| 376 |
+
// Run with: npm test (to playback)
|
| 377 |
+
```
|
| 378 |
+
|
| 379 |
+
### Test Helper Function
|
| 380 |
+
|
| 381 |
+
```javascript
|
| 382 |
+
function createSnapshotAgent(testName, mode = 'playback') {
|
| 383 |
+
return new SnapshotAgent({
|
| 384 |
+
mode,
|
| 385 |
+
snapshotPath: `./test/snapshots/${testName}.json`
|
| 386 |
+
})
|
| 387 |
+
}
|
| 388 |
+
|
| 389 |
+
test('user API test', async (t) => {
|
| 390 |
+
const agent = createSnapshotAgent('user-api')
|
| 391 |
+
setGlobalDispatcher(agent)
|
| 392 |
+
|
| 393 |
+
// Test implementation...
|
| 394 |
+
})
|
| 395 |
+
```
|
| 396 |
+
|
| 397 |
+
## Snapshot File Format
|
| 398 |
+
|
| 399 |
+
Snapshots are stored as JSON with the following structure:
|
| 400 |
+
|
| 401 |
+
```json
|
| 402 |
+
[
|
| 403 |
+
{
|
| 404 |
+
"hash": "dGVzdC1oYXNo...",
|
| 405 |
+
"snapshot": {
|
| 406 |
+
"request": {
|
| 407 |
+
"method": "GET",
|
| 408 |
+
"url": "https://api.example.com/users",
|
| 409 |
+
"headers": {
|
| 410 |
+
"authorization": "Bearer token"
|
| 411 |
+
},
|
| 412 |
+
"body": undefined
|
| 413 |
+
},
|
| 414 |
+
"response": {
|
| 415 |
+
"statusCode": 200,
|
| 416 |
+
"headers": {
|
| 417 |
+
"content-type": "application/json"
|
| 418 |
+
},
|
| 419 |
+
"body": "eyJkYXRhIjoidGVzdCJ9", // base64 encoded
|
| 420 |
+
"trailers": {}
|
| 421 |
+
},
|
| 422 |
+
"timestamp": "2024-01-01T00:00:00.000Z"
|
| 423 |
+
}
|
| 424 |
+
}
|
| 425 |
+
]
|
| 426 |
+
```
|
| 427 |
+
|
| 428 |
+
## Security Considerations
|
| 429 |
+
|
| 430 |
+
### Sensitive Data in Snapshots
|
| 431 |
+
|
| 432 |
+
By default, SnapshotAgent records all headers and request/response data. For production use, always exclude sensitive information:
|
| 433 |
+
|
| 434 |
+
```javascript
|
| 435 |
+
const agent = new SnapshotAgent({
|
| 436 |
+
mode: 'record',
|
| 437 |
+
snapshotPath: './snapshots.json',
|
| 438 |
+
|
| 439 |
+
// Exclude sensitive headers from snapshots
|
| 440 |
+
excludeHeaders: [
|
| 441 |
+
'authorization',
|
| 442 |
+
'x-api-key',
|
| 443 |
+
'cookie',
|
| 444 |
+
'set-cookie',
|
| 445 |
+
'x-auth-token',
|
| 446 |
+
'x-csrf-token'
|
| 447 |
+
],
|
| 448 |
+
|
| 449 |
+
// Filter out requests with sensitive data
|
| 450 |
+
shouldRecord: (requestOpts) => {
|
| 451 |
+
const url = new URL(requestOpts.path, requestOpts.origin)
|
| 452 |
+
|
| 453 |
+
// Don't record authentication endpoints
|
| 454 |
+
if (url.pathname.includes('/auth/') || url.pathname.includes('/login')) {
|
| 455 |
+
return false
|
| 456 |
+
}
|
| 457 |
+
|
| 458 |
+
// Don't record if request contains sensitive body data
|
| 459 |
+
if (requestOpts.body && typeof requestOpts.body === 'string') {
|
| 460 |
+
const body = requestOpts.body.toLowerCase()
|
| 461 |
+
if (body.includes('password') || body.includes('secret')) {
|
| 462 |
+
return false
|
| 463 |
+
}
|
| 464 |
+
}
|
| 465 |
+
|
| 466 |
+
return true
|
| 467 |
+
}
|
| 468 |
+
})
|
| 469 |
+
```
|
| 470 |
+
|
| 471 |
+
### Snapshot File Security
|
| 472 |
+
|
| 473 |
+
**Important**: Snapshot files may contain sensitive data. Handle them securely:
|
| 474 |
+
|
| 475 |
+
- ✅ Add snapshot files to `.gitignore` if they contain real API data
|
| 476 |
+
- ✅ Use environment-specific snapshots (dev/staging/prod)
|
| 477 |
+
- ✅ Regularly review snapshot contents for sensitive information
|
| 478 |
+
- ✅ Use the `excludeHeaders` option for production snapshots
|
| 479 |
+
- ❌ Never commit snapshots with real authentication tokens
|
| 480 |
+
- ❌ Don't share snapshot files containing personal data
|
| 481 |
+
|
| 482 |
+
```gitignore
|
| 483 |
+
# Exclude snapshots with real data
|
| 484 |
+
/test/snapshots/production-*.json
|
| 485 |
+
/test/snapshots/*-real-data.json
|
| 486 |
+
|
| 487 |
+
# Include sanitized test snapshots
|
| 488 |
+
!/test/snapshots/mock-*.json
|
| 489 |
+
```
|
| 490 |
+
|
| 491 |
+
## Error Handling
|
| 492 |
+
|
| 493 |
+
### Missing Snapshots in Playback Mode
|
| 494 |
+
|
| 495 |
+
```javascript
|
| 496 |
+
try {
|
| 497 |
+
const response = await fetch('https://api.example.com/nonexistent')
|
| 498 |
+
} catch (error) {
|
| 499 |
+
if (error.message.includes('No snapshot found')) {
|
| 500 |
+
// Handle missing snapshot
|
| 501 |
+
console.log('Snapshot not found for this request')
|
| 502 |
+
}
|
| 503 |
+
}
|
| 504 |
+
```
|
| 505 |
+
|
| 506 |
+
### Handling Network Errors in Record Mode
|
| 507 |
+
|
| 508 |
+
```javascript
|
| 509 |
+
const agent = new SnapshotAgent({ mode: 'record', snapshotPath: './snapshots.json' })
|
| 510 |
+
|
| 511 |
+
try {
|
| 512 |
+
const response = await fetch('https://nonexistent-api.example.com/data')
|
| 513 |
+
} catch (error) {
|
| 514 |
+
// Network errors are not recorded as snapshots
|
| 515 |
+
console.log('Network error:', error.message)
|
| 516 |
+
}
|
| 517 |
+
```
|
| 518 |
+
|
| 519 |
+
## Best Practices
|
| 520 |
+
|
| 521 |
+
### 1. Organize Snapshots by Test Suite
|
| 522 |
+
|
| 523 |
+
```javascript
|
| 524 |
+
// Use descriptive snapshot file names
|
| 525 |
+
const agent = new SnapshotAgent({
|
| 526 |
+
mode: 'playback',
|
| 527 |
+
snapshotPath: `./test/snapshots/${testSuiteName}-${testName}.json`
|
| 528 |
+
})
|
| 529 |
+
```
|
| 530 |
+
|
| 531 |
+
### 2. Version Control Snapshots
|
| 532 |
+
|
| 533 |
+
Add snapshot files to version control to ensure consistent test behavior across environments:
|
| 534 |
+
|
| 535 |
+
```gitignore
|
| 536 |
+
# Include snapshots in version control
|
| 537 |
+
!/test/snapshots/*.json
|
| 538 |
+
```
|
| 539 |
+
|
| 540 |
+
### 3. Clean Up Test Data
|
| 541 |
+
|
| 542 |
+
```javascript
|
| 543 |
+
test('API test', async (t) => {
|
| 544 |
+
const agent = new SnapshotAgent({
|
| 545 |
+
mode: 'playback',
|
| 546 |
+
snapshotPath: './test/snapshots/temp-test.json'
|
| 547 |
+
})
|
| 548 |
+
|
| 549 |
+
// Clean up after test
|
| 550 |
+
t.after(() => {
|
| 551 |
+
agent.clearSnapshots()
|
| 552 |
+
})
|
| 553 |
+
})
|
| 554 |
+
```
|
| 555 |
+
|
| 556 |
+
### 4. Snapshot Validation
|
| 557 |
+
|
| 558 |
+
```javascript
|
| 559 |
+
test('validate snapshot contents', async (t) => {
|
| 560 |
+
const agent = new SnapshotAgent({
|
| 561 |
+
mode: 'playback',
|
| 562 |
+
snapshotPath: './test/snapshots/validation.json'
|
| 563 |
+
})
|
| 564 |
+
|
| 565 |
+
const recorder = agent.getRecorder()
|
| 566 |
+
const snapshots = recorder.getSnapshots()
|
| 567 |
+
|
| 568 |
+
// Validate snapshot structure
|
| 569 |
+
assert(snapshots.length > 0, 'Should have recorded snapshots')
|
| 570 |
+
assert(snapshots[0].request.url.startsWith('https://'), 'Should use HTTPS')
|
| 571 |
+
})
|
| 572 |
+
```
|
| 573 |
+
|
| 574 |
+
## Comparison with Other Tools
|
| 575 |
+
|
| 576 |
+
### vs Manual MockAgent Setup
|
| 577 |
+
|
| 578 |
+
**Manual MockAgent:**
|
| 579 |
+
```javascript
|
| 580 |
+
const mockAgent = new MockAgent()
|
| 581 |
+
const mockPool = mockAgent.get('https://api.example.com')
|
| 582 |
+
|
| 583 |
+
mockPool.intercept({
|
| 584 |
+
path: '/users',
|
| 585 |
+
method: 'GET'
|
| 586 |
+
}).reply(200, [
|
| 587 |
+
{ id: 1, name: 'User 1' },
|
| 588 |
+
{ id: 2, name: 'User 2' }
|
| 589 |
+
])
|
| 590 |
+
```
|
| 591 |
+
|
| 592 |
+
**SnapshotAgent:**
|
| 593 |
+
```javascript
|
| 594 |
+
// Record once
|
| 595 |
+
const agent = new SnapshotAgent({ mode: 'record', snapshotPath: './snapshots.json' })
|
| 596 |
+
// Real API call gets recorded automatically
|
| 597 |
+
|
| 598 |
+
// Use in tests
|
| 599 |
+
const agent = new SnapshotAgent({ mode: 'playback', snapshotPath: './snapshots.json' })
|
| 600 |
+
// Automatically replays recorded response
|
| 601 |
+
```
|
| 602 |
+
|
| 603 |
+
### vs nock
|
| 604 |
+
|
| 605 |
+
SnapshotAgent provides similar functionality to nock but is specifically designed for undici:
|
| 606 |
+
|
| 607 |
+
- ✅ Works with all undici APIs (`request`, `stream`, `pipeline`, etc.)
|
| 608 |
+
- ✅ Supports undici-specific features (RetryAgent, connection pooling)
|
| 609 |
+
- ✅ Better TypeScript integration
|
| 610 |
+
- ✅ More efficient for high-performance scenarios
|
| 611 |
+
|
| 612 |
+
## See Also
|
| 613 |
+
|
| 614 |
+
- [MockAgent](./MockAgent.md) - Manual mocking for more control
|
| 615 |
+
- [MockCallHistory](./MockCallHistory.md) - Inspecting request history
|
| 616 |
+
- [Testing Best Practices](../best-practices/writing-tests.md) - General testing guidance
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/docs/docs/api/Util.md
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Util
|
| 2 |
+
|
| 3 |
+
Utility API for third-party implementations of the dispatcher API.
|
| 4 |
+
|
| 5 |
+
## `parseHeaders(headers, [obj])`
|
| 6 |
+
|
| 7 |
+
Receives a header object and returns the parsed value.
|
| 8 |
+
|
| 9 |
+
Arguments:
|
| 10 |
+
|
| 11 |
+
- **headers** `(Buffer | string | (Buffer | string)[])[]` (required) - Header object.
|
| 12 |
+
|
| 13 |
+
- **obj** `Record<string, string | string[]>` (optional) - Object to specify a proxy object. The parsed value is assigned to this object. But, if **headers** is an object, it is not used.
|
| 14 |
+
|
| 15 |
+
Returns: `Record<string, string | string[]>` If **obj** is specified, it is equivalent to **obj**.
|
| 16 |
+
|
| 17 |
+
## `headerNameToString(value)`
|
| 18 |
+
|
| 19 |
+
Retrieves a header name and returns its lowercase value.
|
| 20 |
+
|
| 21 |
+
Arguments:
|
| 22 |
+
|
| 23 |
+
- **value** `string | Buffer` (required) - Header name.
|
| 24 |
+
|
| 25 |
+
Returns: `string`
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/docs/docs/api/WebSocket.md
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Class: WebSocket
|
| 2 |
+
|
| 3 |
+
Extends: [`EventTarget`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget)
|
| 4 |
+
|
| 5 |
+
The WebSocket object provides a way to manage a WebSocket connection to a server, allowing bidirectional communication. The API follows the [WebSocket spec](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) and [RFC 6455](https://datatracker.ietf.org/doc/html/rfc6455).
|
| 6 |
+
|
| 7 |
+
## `new WebSocket(url[, protocol])`
|
| 8 |
+
|
| 9 |
+
Arguments:
|
| 10 |
+
|
| 11 |
+
* **url** `URL | string`
|
| 12 |
+
* **protocol** `string | string[] | WebSocketInit` (optional) - Subprotocol(s) to request the server use, or a [`Dispatcher`](/docs/docs/api/Dispatcher.md).
|
| 13 |
+
|
| 14 |
+
### Example:
|
| 15 |
+
|
| 16 |
+
This example will not work in browsers or other platforms that don't allow passing an object.
|
| 17 |
+
|
| 18 |
+
```mjs
|
| 19 |
+
import { WebSocket, ProxyAgent } from 'undici'
|
| 20 |
+
|
| 21 |
+
const proxyAgent = new ProxyAgent('my.proxy.server')
|
| 22 |
+
|
| 23 |
+
const ws = new WebSocket('wss://echo.websocket.events', {
|
| 24 |
+
dispatcher: proxyAgent,
|
| 25 |
+
protocols: ['echo', 'chat']
|
| 26 |
+
})
|
| 27 |
+
```
|
| 28 |
+
|
| 29 |
+
If you do not need a custom Dispatcher, it's recommended to use the following pattern:
|
| 30 |
+
|
| 31 |
+
```mjs
|
| 32 |
+
import { WebSocket } from 'undici'
|
| 33 |
+
|
| 34 |
+
const ws = new WebSocket('wss://echo.websocket.events', ['echo', 'chat'])
|
| 35 |
+
```
|
| 36 |
+
|
| 37 |
+
# Class: WebSocketStream
|
| 38 |
+
|
| 39 |
+
> ⚠️ Warning: the WebSocketStream API has not been finalized and is likely to change.
|
| 40 |
+
|
| 41 |
+
See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/WebSocketStream) for more information.
|
| 42 |
+
|
| 43 |
+
## `new WebSocketStream(url[, protocol])`
|
| 44 |
+
|
| 45 |
+
Arguments:
|
| 46 |
+
|
| 47 |
+
* **url** `URL | string`
|
| 48 |
+
* **options** `WebSocketStreamOptions` (optional)
|
| 49 |
+
|
| 50 |
+
### WebSocketStream Example
|
| 51 |
+
|
| 52 |
+
```js
|
| 53 |
+
const stream = new WebSocketStream('https://echo.websocket.org/')
|
| 54 |
+
const { readable, writable } = await stream.opened
|
| 55 |
+
|
| 56 |
+
async function read () {
|
| 57 |
+
/** @type {ReadableStreamReader} */
|
| 58 |
+
const reader = readable.getReader()
|
| 59 |
+
|
| 60 |
+
while (true) {
|
| 61 |
+
const { done, value } = await reader.read()
|
| 62 |
+
if (done) break
|
| 63 |
+
|
| 64 |
+
// do something with value
|
| 65 |
+
}
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
async function write () {
|
| 69 |
+
/** @type {WritableStreamDefaultWriter} */
|
| 70 |
+
const writer = writable.getWriter()
|
| 71 |
+
writer.write('Hello, world!')
|
| 72 |
+
writer.releaseLock()
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
read()
|
| 76 |
+
|
| 77 |
+
setInterval(() => write(), 5000)
|
| 78 |
+
|
| 79 |
+
```
|
| 80 |
+
|
| 81 |
+
## ping(websocket, payload)
|
| 82 |
+
Arguments:
|
| 83 |
+
|
| 84 |
+
* **websocket** `WebSocket` - The WebSocket instance to send the ping frame on
|
| 85 |
+
* **payload** `Buffer|undefined` (optional) - Optional payload data to include with the ping frame. Must not exceed 125 bytes.
|
| 86 |
+
|
| 87 |
+
Sends a ping frame to the WebSocket server. The server must respond with a pong frame containing the same payload data. This can be used for keepalive purposes or to verify that the connection is still active.
|
| 88 |
+
|
| 89 |
+
### Example:
|
| 90 |
+
|
| 91 |
+
```js
|
| 92 |
+
import { WebSocket, ping } from 'undici'
|
| 93 |
+
|
| 94 |
+
const ws = new WebSocket('wss://echo.websocket.events')
|
| 95 |
+
|
| 96 |
+
ws.addEventListener('open', () => {
|
| 97 |
+
// Send ping with no payload
|
| 98 |
+
ping(ws)
|
| 99 |
+
|
| 100 |
+
// Send ping with payload
|
| 101 |
+
const payload = Buffer.from('hello')
|
| 102 |
+
ping(ws, payload)
|
| 103 |
+
})
|
| 104 |
+
```
|
| 105 |
+
|
| 106 |
+
**Note**: A ping frame cannot have a payload larger than 125 bytes. The ping will only be sent if the WebSocket connection is in the OPEN state.
|
| 107 |
+
|
| 108 |
+
## Read More
|
| 109 |
+
|
| 110 |
+
- [MDN - WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket)
|
| 111 |
+
- [The WebSocket Specification](https://www.rfc-editor.org/rfc/rfc6455)
|
| 112 |
+
- [The WHATWG WebSocket Specification](https://websockets.spec.whatwg.org/)
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/docs/docs/api/api-lifecycle.md
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Client Lifecycle
|
| 2 |
+
|
| 3 |
+
An Undici [Client](/docs/docs/api/Client.md) can be best described as a state machine. The following list is a summary of the various state transitions the `Client` will go through in its lifecycle. This document also contains detailed breakdowns of each state.
|
| 4 |
+
|
| 5 |
+
> This diagram is not a perfect representation of the undici Client. Since the Client class is not actually implemented as a state-machine, actual execution may deviate slightly from what is described below. Consider this as a general resource for understanding the inner workings of the Undici client rather than some kind of formal specification.
|
| 6 |
+
|
| 7 |
+
## State Transition Overview
|
| 8 |
+
|
| 9 |
+
* A `Client` begins in the **idle** state with no socket connection and no requests in queue.
|
| 10 |
+
* The *connect* event transitions the `Client` to the **pending** state where requests can be queued prior to processing.
|
| 11 |
+
* The *close* and *destroy* events transition the `Client` to the **destroyed** state. Since there are no requests in the queue, the *close* event immediately transitions to the **destroyed** state.
|
| 12 |
+
* The **pending** state indicates the underlying socket connection has been successfully established and requests are queueing.
|
| 13 |
+
* The *process* event transitions the `Client` to the **processing** state where requests are processed.
|
| 14 |
+
* If requests are queued, the *close* event transitions to the **processing** state; otherwise, it transitions to the **destroyed** state.
|
| 15 |
+
* The *destroy* event transitions to the **destroyed** state.
|
| 16 |
+
* The **processing** state initializes to the **processing.running** state.
|
| 17 |
+
* If the current request requires draining, the *needDrain* event transitions the `Client` into the **processing.busy** state which will return to the **processing.running** state with the *drainComplete* event.
|
| 18 |
+
* After all queued requests are completed, the *keepalive* event transitions the `Client` back to the **pending** state. If no requests are queued during the timeout, the **close** event transitions the `Client` to the **destroyed** state.
|
| 19 |
+
* If the *close* event is fired while the `Client` still has queued requests, the `Client` transitions to the **process.closing** state where it will complete all existing requests before firing the *done* event.
|
| 20 |
+
* The *done* event gracefully transitions the `Client` to the **destroyed** state.
|
| 21 |
+
* At any point in time, the *destroy* event will transition the `Client` from the **processing** state to the **destroyed** state, destroying any queued requests.
|
| 22 |
+
* The **destroyed** state is a final state and the `Client` is no longer functional.
|
| 23 |
+
|
| 24 |
+
A state diagram representing an Undici Client instance:
|
| 25 |
+
|
| 26 |
+
```mermaid
|
| 27 |
+
stateDiagram-v2
|
| 28 |
+
[*] --> idle
|
| 29 |
+
idle --> pending : connect
|
| 30 |
+
idle --> destroyed : destroy/close
|
| 31 |
+
|
| 32 |
+
pending --> idle : timeout
|
| 33 |
+
pending --> destroyed : destroy
|
| 34 |
+
|
| 35 |
+
state close_fork <<fork>>
|
| 36 |
+
pending --> close_fork : close
|
| 37 |
+
close_fork --> processing
|
| 38 |
+
close_fork --> destroyed
|
| 39 |
+
|
| 40 |
+
pending --> processing : process
|
| 41 |
+
|
| 42 |
+
processing --> pending : keepalive
|
| 43 |
+
processing --> destroyed : done
|
| 44 |
+
processing --> destroyed : destroy
|
| 45 |
+
|
| 46 |
+
destroyed --> [*]
|
| 47 |
+
|
| 48 |
+
state processing {
|
| 49 |
+
[*] --> running
|
| 50 |
+
running --> closing : close
|
| 51 |
+
running --> busy : needDrain
|
| 52 |
+
busy --> running : drainComplete
|
| 53 |
+
running --> [*] : keepalive
|
| 54 |
+
closing --> [*] : done
|
| 55 |
+
}
|
| 56 |
+
```
|
| 57 |
+
## State details
|
| 58 |
+
|
| 59 |
+
### idle
|
| 60 |
+
|
| 61 |
+
The **idle** state is the initial state of a `Client` instance. While an `origin` is required for instantiating a `Client` instance, the underlying socket connection will not be established until a request is queued using [`Client.dispatch()`](/docs/docs/api/Client.md#clientdispatchoptions-handlers). By calling `Client.dispatch()` directly or using one of the multiple implementations ([`Client.connect()`](Client.md#clientconnectoptions-callback), [`Client.pipeline()`](Client.md#clientpipelineoptions-handler), [`Client.request()`](Client.md#clientrequestoptions-callback), [`Client.stream()`](Client.md#clientstreamoptions-factory-callback), and [`Client.upgrade()`](/docs/docs/api/Client.md#clientupgradeoptions-callback)), the `Client` instance will transition from **idle** to [**pending**](/docs/docs/api/Client.md#pending) and then most likely directly to [**processing**](/docs/docs/api/Client.md#processing).
|
| 62 |
+
|
| 63 |
+
Calling [`Client.close()`](/docs/docs/api/Client.md#clientclosecallback) or [`Client.destroy()`](Client.md#clientdestroyerror-callback) transitions directly to the [**destroyed**](/docs/docs/api/Client.md#destroyed) state since the `Client` instance will have no queued requests in this state.
|
| 64 |
+
|
| 65 |
+
### pending
|
| 66 |
+
|
| 67 |
+
The **pending** state signifies a non-processing `Client`. Upon entering this state, the `Client` establishes a socket connection and emits the [`'connect'`](/docs/docs/api/Client.md#event-connect) event signalling a connection was successfully established with the `origin` provided during `Client` instantiation. The internal queue is initially empty, and requests can start queueing.
|
| 68 |
+
|
| 69 |
+
Calling [`Client.close()`](/docs/docs/api/Client.md#clientclosecallback) with queued requests, transitions the `Client` to the [**processing**](/docs/docs/api/Client.md#processing) state. Without queued requests, it transitions to the [**destroyed**](/docs/docs/api/Client.md#destroyed) state.
|
| 70 |
+
|
| 71 |
+
Calling [`Client.destroy()`](/docs/docs/api/Client.md#clientdestroyerror-callback) transitions directly to the [**destroyed**](/docs/docs/api/Client.md#destroyed) state regardless of existing requests.
|
| 72 |
+
|
| 73 |
+
### processing
|
| 74 |
+
|
| 75 |
+
The **processing** state is a state machine within itself. It initializes to the [**processing.running**](/docs/docs/api/Client.md#running) state. The [`Client.dispatch()`](/docs/docs/api/Client.md#clientdispatchoptions-handlers), [`Client.close()`](Client.md#clientclosecallback), and [`Client.destroy()`](Client.md#clientdestroyerror-callback) can be called at any time while the `Client` is in this state. `Client.dispatch()` will add more requests to the queue while existing requests continue to be processed. `Client.close()` will transition to the [**processing.closing**](/docs/docs/api/Client.md#closing) state. And `Client.destroy()` will transition to [**destroyed**](/docs/docs/api/Client.md#destroyed).
|
| 76 |
+
|
| 77 |
+
#### running
|
| 78 |
+
|
| 79 |
+
In the **processing.running** sub-state, queued requests are being processed in a FIFO order. If a request body requires draining, the *needDrain* event transitions to the [**processing.busy**](/docs/docs/api/Client.md#busy) sub-state. The *close* event transitions the Client to the [**process.closing**](/docs/docs/api/Client.md#closing) sub-state. If all queued requests are processed and neither [`Client.close()`](/docs/docs/api/Client.md#clientclosecallback) nor [`Client.destroy()`](Client.md#clientdestroyerror-callback) are called, then the [**processing**](/docs/docs/api/Client.md#processing) machine will trigger a *keepalive* event transitioning the `Client` back to the [**pending**](/docs/docs/api/Client.md#pending) state. During this time, the `Client` is waiting for the socket connection to timeout, and once it does, it triggers the *timeout* event and transitions to the [**idle**](/docs/docs/api/Client.md#idle) state.
|
| 80 |
+
|
| 81 |
+
#### busy
|
| 82 |
+
|
| 83 |
+
This sub-state is only entered when a request body is an instance of [Stream](https://nodejs.org/api/stream.html) and requires draining. The `Client` cannot process additional requests while in this state and must wait until the currently processing request body is completely drained before transitioning back to [**processing.running**](/docs/docs/api/Client.md#running).
|
| 84 |
+
|
| 85 |
+
#### closing
|
| 86 |
+
|
| 87 |
+
This sub-state is only entered when a `Client` instance has queued requests and the [`Client.close()`](/docs/docs/api/Client.md#clientclosecallback) method is called. In this state, the `Client` instance continues to process requests as usual, with the one exception that no additional requests can be queued. Once all of the queued requests are processed, the `Client` will trigger the *done* event gracefully entering the [**destroyed**](/docs/docs/api/Client.md#destroyed) state without an error.
|
| 88 |
+
|
| 89 |
+
### destroyed
|
| 90 |
+
|
| 91 |
+
The **destroyed** state is a final state for the `Client` instance. Once in this state, a `Client` is nonfunctional. Calling any other `Client` methods will result in an `ClientDestroyedError`.
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/docs/docs/best-practices/client-certificate.md
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Client certificate
|
| 2 |
+
|
| 3 |
+
Client certificate authentication can be configured with the `Client`, the required options are passed along through the `connect` option.
|
| 4 |
+
|
| 5 |
+
The client certificates must be signed by a trusted CA. The Node.js default is to trust the well-known CAs curated by Mozilla.
|
| 6 |
+
|
| 7 |
+
Setting the server option `requestCert: true` tells the server to request the client certificate.
|
| 8 |
+
|
| 9 |
+
The server option `rejectUnauthorized: false` allows us to handle any invalid certificate errors in client code. The `authorized` property on the socket of the incoming request will show if the client certificate was valid. The `authorizationError` property will give the reason if the certificate was not valid.
|
| 10 |
+
|
| 11 |
+
### Client Certificate Authentication
|
| 12 |
+
|
| 13 |
+
```js
|
| 14 |
+
const { readFileSync } = require('node:fs')
|
| 15 |
+
const { join } = require('node:path')
|
| 16 |
+
const { createServer } = require('node:https')
|
| 17 |
+
const { Client } = require('undici')
|
| 18 |
+
|
| 19 |
+
const serverOptions = {
|
| 20 |
+
ca: [
|
| 21 |
+
readFileSync(join(__dirname, 'client-ca-crt.pem'), 'utf8')
|
| 22 |
+
],
|
| 23 |
+
key: readFileSync(join(__dirname, 'server-key.pem'), 'utf8'),
|
| 24 |
+
cert: readFileSync(join(__dirname, 'server-crt.pem'), 'utf8'),
|
| 25 |
+
requestCert: true,
|
| 26 |
+
rejectUnauthorized: false
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
const server = createServer(serverOptions, (req, res) => {
|
| 30 |
+
// true if client cert is valid
|
| 31 |
+
if(req.client.authorized === true) {
|
| 32 |
+
console.log('valid')
|
| 33 |
+
} else {
|
| 34 |
+
console.error(req.client.authorizationError)
|
| 35 |
+
}
|
| 36 |
+
res.end()
|
| 37 |
+
})
|
| 38 |
+
|
| 39 |
+
server.listen(0, function () {
|
| 40 |
+
const tls = {
|
| 41 |
+
ca: [
|
| 42 |
+
readFileSync(join(__dirname, 'server-ca-crt.pem'), 'utf8')
|
| 43 |
+
],
|
| 44 |
+
key: readFileSync(join(__dirname, 'client-key.pem'), 'utf8'),
|
| 45 |
+
cert: readFileSync(join(__dirname, 'client-crt.pem'), 'utf8'),
|
| 46 |
+
rejectUnauthorized: false,
|
| 47 |
+
servername: 'agent1'
|
| 48 |
+
}
|
| 49 |
+
const client = new Client(`https://localhost:${server.address().port}`, {
|
| 50 |
+
connect: tls
|
| 51 |
+
})
|
| 52 |
+
|
| 53 |
+
client.request({
|
| 54 |
+
path: '/',
|
| 55 |
+
method: 'GET'
|
| 56 |
+
}, (err, { body }) => {
|
| 57 |
+
body.on('data', (buf) => {})
|
| 58 |
+
body.on('end', () => {
|
| 59 |
+
client.close()
|
| 60 |
+
server.close()
|
| 61 |
+
})
|
| 62 |
+
})
|
| 63 |
+
})
|
| 64 |
+
```
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/docs/docs/best-practices/mocking-request.md
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Mocking Request
|
| 2 |
+
|
| 3 |
+
Undici has its own mocking [utility](/docs/docs/api/MockAgent.md). It allow us to intercept undici HTTP requests and return mocked values instead. It can be useful for testing purposes.
|
| 4 |
+
|
| 5 |
+
Example:
|
| 6 |
+
|
| 7 |
+
```js
|
| 8 |
+
// bank.mjs
|
| 9 |
+
import { request } from 'undici'
|
| 10 |
+
|
| 11 |
+
export async function bankTransfer(recipient, amount) {
|
| 12 |
+
const { body } = await request('http://localhost:3000/bank-transfer',
|
| 13 |
+
{
|
| 14 |
+
method: 'POST',
|
| 15 |
+
headers: {
|
| 16 |
+
'X-TOKEN-SECRET': 'SuperSecretToken',
|
| 17 |
+
},
|
| 18 |
+
body: JSON.stringify({
|
| 19 |
+
recipient,
|
| 20 |
+
amount
|
| 21 |
+
})
|
| 22 |
+
}
|
| 23 |
+
)
|
| 24 |
+
return await body.json()
|
| 25 |
+
}
|
| 26 |
+
```
|
| 27 |
+
|
| 28 |
+
And this is what the test file looks like:
|
| 29 |
+
|
| 30 |
+
```js
|
| 31 |
+
// index.test.mjs
|
| 32 |
+
import { strict as assert } from 'node:assert'
|
| 33 |
+
import { MockAgent, setGlobalDispatcher, } from 'undici'
|
| 34 |
+
import { bankTransfer } from './bank.mjs'
|
| 35 |
+
|
| 36 |
+
const mockAgent = new MockAgent();
|
| 37 |
+
|
| 38 |
+
setGlobalDispatcher(mockAgent);
|
| 39 |
+
|
| 40 |
+
// Provide the base url to the request
|
| 41 |
+
const mockPool = mockAgent.get('http://localhost:3000');
|
| 42 |
+
|
| 43 |
+
// intercept the request
|
| 44 |
+
mockPool.intercept({
|
| 45 |
+
path: '/bank-transfer',
|
| 46 |
+
method: 'POST',
|
| 47 |
+
headers: {
|
| 48 |
+
'X-TOKEN-SECRET': 'SuperSecretToken',
|
| 49 |
+
},
|
| 50 |
+
body: JSON.stringify({
|
| 51 |
+
recipient: '1234567890',
|
| 52 |
+
amount: '100'
|
| 53 |
+
})
|
| 54 |
+
}).reply(200, {
|
| 55 |
+
message: 'transaction processed'
|
| 56 |
+
})
|
| 57 |
+
|
| 58 |
+
const success = await bankTransfer('1234567890', '100')
|
| 59 |
+
|
| 60 |
+
assert.deepEqual(success, { message: 'transaction processed' })
|
| 61 |
+
|
| 62 |
+
// if you dont want to check whether the body or the headers contain the same value
|
| 63 |
+
// just remove it from interceptor
|
| 64 |
+
mockPool.intercept({
|
| 65 |
+
path: '/bank-transfer',
|
| 66 |
+
method: 'POST',
|
| 67 |
+
}).reply(400, {
|
| 68 |
+
message: 'bank account not found'
|
| 69 |
+
})
|
| 70 |
+
|
| 71 |
+
const badRequest = await bankTransfer('1234567890', '100')
|
| 72 |
+
|
| 73 |
+
assert.deepEqual(badRequest, { message: 'bank account not found' })
|
| 74 |
+
```
|
| 75 |
+
|
| 76 |
+
Explore other MockAgent functionality [here](/docs/docs/api/MockAgent.md)
|
| 77 |
+
|
| 78 |
+
## Access agent call history
|
| 79 |
+
|
| 80 |
+
Using a MockAgent also allows you to make assertions on the configuration used to make your request in your application.
|
| 81 |
+
|
| 82 |
+
Here is an example :
|
| 83 |
+
|
| 84 |
+
```js
|
| 85 |
+
// index.test.mjs
|
| 86 |
+
import { strict as assert } from 'node:assert'
|
| 87 |
+
import { MockAgent, setGlobalDispatcher, fetch } from 'undici'
|
| 88 |
+
import { app } from './app.mjs'
|
| 89 |
+
|
| 90 |
+
// given an application server running on http://localhost:3000
|
| 91 |
+
await app.start()
|
| 92 |
+
|
| 93 |
+
// enable call history at instantiation
|
| 94 |
+
const mockAgent = new MockAgent({ enableCallHistory: true })
|
| 95 |
+
// or after instantiation
|
| 96 |
+
mockAgent.enableCallHistory()
|
| 97 |
+
|
| 98 |
+
setGlobalDispatcher(mockAgent)
|
| 99 |
+
|
| 100 |
+
// this call is made (not intercepted)
|
| 101 |
+
await fetch(`http://localhost:3000/endpoint?query='hello'`, {
|
| 102 |
+
method: 'POST',
|
| 103 |
+
headers: { 'content-type': 'application/json' }
|
| 104 |
+
body: JSON.stringify({ data: '' })
|
| 105 |
+
})
|
| 106 |
+
|
| 107 |
+
// access to the call history of the MockAgent (which register every call made intercepted or not)
|
| 108 |
+
assert.ok(mockAgent.getCallHistory()?.calls().length === 1)
|
| 109 |
+
assert.strictEqual(mockAgent.getCallHistory()?.firstCall()?.fullUrl, `http://localhost:3000/endpoint?query='hello'`)
|
| 110 |
+
assert.strictEqual(mockAgent.getCallHistory()?.firstCall()?.body, JSON.stringify({ data: '' }))
|
| 111 |
+
assert.deepStrictEqual(mockAgent.getCallHistory()?.firstCall()?.searchParams, { query: 'hello' })
|
| 112 |
+
assert.strictEqual(mockAgent.getCallHistory()?.firstCall()?.port, '3000')
|
| 113 |
+
assert.strictEqual(mockAgent.getCallHistory()?.firstCall()?.host, 'localhost:3000')
|
| 114 |
+
assert.strictEqual(mockAgent.getCallHistory()?.firstCall()?.method, 'POST')
|
| 115 |
+
assert.strictEqual(mockAgent.getCallHistory()?.firstCall()?.path, '/endpoint')
|
| 116 |
+
assert.deepStrictEqual(mockAgent.getCallHistory()?.firstCall()?.headers, { 'content-type': 'application/json' })
|
| 117 |
+
|
| 118 |
+
// clear all call history logs
|
| 119 |
+
mockAgent.clearCallHistory()
|
| 120 |
+
|
| 121 |
+
assert.ok(mockAgent.getCallHistory()?.calls().length === 0)
|
| 122 |
+
```
|
| 123 |
+
|
| 124 |
+
Calling `mockAgent.close()` will automatically clear and delete every call history for you.
|
| 125 |
+
|
| 126 |
+
Explore other MockAgent functionality [here](/docs/docs/api/MockAgent.md)
|
| 127 |
+
|
| 128 |
+
Explore other MockCallHistory functionality [here](/docs/docs/api/MockCallHistory.md)
|
| 129 |
+
|
| 130 |
+
Explore other MockCallHistoryLog functionality [here](/docs/docs/api/MockCallHistoryLog.md)
|
| 131 |
+
|
| 132 |
+
## Debug Mock Value
|
| 133 |
+
|
| 134 |
+
When the interceptor and the request options are not the same, undici will automatically make a real HTTP request. To prevent real requests from being made, use `mockAgent.disableNetConnect()`:
|
| 135 |
+
|
| 136 |
+
```js
|
| 137 |
+
const mockAgent = new MockAgent();
|
| 138 |
+
|
| 139 |
+
setGlobalDispatcher(mockAgent);
|
| 140 |
+
mockAgent.disableNetConnect()
|
| 141 |
+
|
| 142 |
+
// Provide the base url to the request
|
| 143 |
+
const mockPool = mockAgent.get('http://localhost:3000');
|
| 144 |
+
|
| 145 |
+
mockPool.intercept({
|
| 146 |
+
path: '/bank-transfer',
|
| 147 |
+
method: 'POST',
|
| 148 |
+
}).reply(200, {
|
| 149 |
+
message: 'transaction processed'
|
| 150 |
+
})
|
| 151 |
+
|
| 152 |
+
const badRequest = await bankTransfer('1234567890', '100')
|
| 153 |
+
// Will throw an error
|
| 154 |
+
// MockNotMatchedError: Mock dispatch not matched for path '/bank-transfer':
|
| 155 |
+
// subsequent request to origin http://localhost:3000 was not allowed (net.connect disabled)
|
| 156 |
+
```
|
| 157 |
+
|
| 158 |
+
## Reply with data based on request
|
| 159 |
+
|
| 160 |
+
If the mocked response needs to be dynamically derived from the request parameters, you can provide a function instead of an object to `reply`:
|
| 161 |
+
|
| 162 |
+
```js
|
| 163 |
+
mockPool.intercept({
|
| 164 |
+
path: '/bank-transfer',
|
| 165 |
+
method: 'POST',
|
| 166 |
+
headers: {
|
| 167 |
+
'X-TOKEN-SECRET': 'SuperSecretToken',
|
| 168 |
+
},
|
| 169 |
+
body: JSON.stringify({
|
| 170 |
+
recipient: '1234567890',
|
| 171 |
+
amount: '100'
|
| 172 |
+
})
|
| 173 |
+
}).reply(200, (opts) => {
|
| 174 |
+
// do something with opts
|
| 175 |
+
|
| 176 |
+
return { message: 'transaction processed' }
|
| 177 |
+
})
|
| 178 |
+
```
|
| 179 |
+
|
| 180 |
+
in this case opts will be
|
| 181 |
+
|
| 182 |
+
```
|
| 183 |
+
{
|
| 184 |
+
method: 'POST',
|
| 185 |
+
headers: { 'X-TOKEN-SECRET': 'SuperSecretToken' },
|
| 186 |
+
body: '{"recipient":"1234567890","amount":"100"}',
|
| 187 |
+
origin: 'http://localhost:3000',
|
| 188 |
+
path: '/bank-transfer'
|
| 189 |
+
}
|
| 190 |
+
```
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/docs/docs/best-practices/proxy.md
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Connecting through a proxy
|
| 2 |
+
|
| 3 |
+
Connecting through a proxy is possible by:
|
| 4 |
+
|
| 5 |
+
- Using [ProxyAgent](/docs/docs/api/ProxyAgent.md).
|
| 6 |
+
- Configuring `Client` or `Pool` constructor.
|
| 7 |
+
|
| 8 |
+
The proxy url should be passed to the `Client` or `Pool` constructor, while the upstream server url
|
| 9 |
+
should be added to every request call in the `path`.
|
| 10 |
+
For instance, if you need to send a request to the `/hello` route of your upstream server,
|
| 11 |
+
the `path` should be `path: 'http://upstream.server:port/hello?foo=bar'`.
|
| 12 |
+
|
| 13 |
+
If you proxy requires basic authentication, you can send it via the `proxy-authorization` header.
|
| 14 |
+
|
| 15 |
+
### Connect without authentication
|
| 16 |
+
|
| 17 |
+
```js
|
| 18 |
+
import { Client } from 'undici'
|
| 19 |
+
import { createServer } from 'http'
|
| 20 |
+
import { createProxy } from 'proxy'
|
| 21 |
+
|
| 22 |
+
const server = await buildServer()
|
| 23 |
+
const proxyServer = await buildProxy()
|
| 24 |
+
|
| 25 |
+
const serverUrl = `http://localhost:${server.address().port}`
|
| 26 |
+
const proxyUrl = `http://localhost:${proxyServer.address().port}`
|
| 27 |
+
|
| 28 |
+
server.on('request', (req, res) => {
|
| 29 |
+
console.log(req.url) // '/hello?foo=bar'
|
| 30 |
+
res.setHeader('content-type', 'application/json')
|
| 31 |
+
res.end(JSON.stringify({ hello: 'world' }))
|
| 32 |
+
})
|
| 33 |
+
|
| 34 |
+
const client = new Client(proxyUrl)
|
| 35 |
+
|
| 36 |
+
const response = await client.request({
|
| 37 |
+
method: 'GET',
|
| 38 |
+
path: serverUrl + '/hello?foo=bar'
|
| 39 |
+
})
|
| 40 |
+
|
| 41 |
+
response.body.setEncoding('utf8')
|
| 42 |
+
let data = ''
|
| 43 |
+
for await (const chunk of response.body) {
|
| 44 |
+
data += chunk
|
| 45 |
+
}
|
| 46 |
+
console.log(response.statusCode) // 200
|
| 47 |
+
console.log(JSON.parse(data)) // { hello: 'world' }
|
| 48 |
+
|
| 49 |
+
server.close()
|
| 50 |
+
proxyServer.close()
|
| 51 |
+
client.close()
|
| 52 |
+
|
| 53 |
+
function buildServer () {
|
| 54 |
+
return new Promise((resolve, reject) => {
|
| 55 |
+
const server = createServer()
|
| 56 |
+
server.listen(0, () => resolve(server))
|
| 57 |
+
})
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
function buildProxy () {
|
| 61 |
+
return new Promise((resolve, reject) => {
|
| 62 |
+
const server = createProxy(createServer())
|
| 63 |
+
server.listen(0, () => resolve(server))
|
| 64 |
+
})
|
| 65 |
+
}
|
| 66 |
+
```
|
| 67 |
+
|
| 68 |
+
### Connect with authentication
|
| 69 |
+
|
| 70 |
+
```js
|
| 71 |
+
import { Client } from 'undici'
|
| 72 |
+
import { createServer } from 'http'
|
| 73 |
+
import { createProxy } from 'proxy'
|
| 74 |
+
|
| 75 |
+
const server = await buildServer()
|
| 76 |
+
const proxyServer = await buildProxy()
|
| 77 |
+
|
| 78 |
+
const serverUrl = `http://localhost:${server.address().port}`
|
| 79 |
+
const proxyUrl = `http://localhost:${proxyServer.address().port}`
|
| 80 |
+
|
| 81 |
+
proxyServer.authenticate = function (req) {
|
| 82 |
+
return req.headers['proxy-authorization'] === `Basic ${Buffer.from('user:pass').toString('base64')}`
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
server.on('request', (req, res) => {
|
| 86 |
+
console.log(req.url) // '/hello?foo=bar'
|
| 87 |
+
res.setHeader('content-type', 'application/json')
|
| 88 |
+
res.end(JSON.stringify({ hello: 'world' }))
|
| 89 |
+
})
|
| 90 |
+
|
| 91 |
+
const client = new Client(proxyUrl)
|
| 92 |
+
|
| 93 |
+
const response = await client.request({
|
| 94 |
+
method: 'GET',
|
| 95 |
+
path: serverUrl + '/hello?foo=bar',
|
| 96 |
+
headers: {
|
| 97 |
+
'proxy-authorization': `Basic ${Buffer.from('user:pass').toString('base64')}`
|
| 98 |
+
}
|
| 99 |
+
})
|
| 100 |
+
|
| 101 |
+
response.body.setEncoding('utf8')
|
| 102 |
+
let data = ''
|
| 103 |
+
for await (const chunk of response.body) {
|
| 104 |
+
data += chunk
|
| 105 |
+
}
|
| 106 |
+
console.log(response.statusCode) // 200
|
| 107 |
+
console.log(JSON.parse(data)) // { hello: 'world' }
|
| 108 |
+
|
| 109 |
+
server.close()
|
| 110 |
+
proxyServer.close()
|
| 111 |
+
client.close()
|
| 112 |
+
|
| 113 |
+
function buildServer () {
|
| 114 |
+
return new Promise((resolve, reject) => {
|
| 115 |
+
const server = createServer()
|
| 116 |
+
server.listen(0, () => resolve(server))
|
| 117 |
+
})
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
function buildProxy () {
|
| 121 |
+
return new Promise((resolve, reject) => {
|
| 122 |
+
const server = createProxy(createServer())
|
| 123 |
+
server.listen(0, () => resolve(server))
|
| 124 |
+
})
|
| 125 |
+
}
|
| 126 |
+
```
|
| 127 |
+
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/docs/docs/best-practices/writing-tests.md
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Writing tests
|
| 2 |
+
|
| 3 |
+
Undici is tuned for a production use case and its default will keep
|
| 4 |
+
a socket open for a few seconds after an HTTP request is completed to
|
| 5 |
+
remove the overhead of opening up a new socket. These settings that makes
|
| 6 |
+
Undici shine in production are not a good fit for using Undici in automated
|
| 7 |
+
tests, as it will result in longer execution times.
|
| 8 |
+
|
| 9 |
+
The following are good defaults that will keep the socket open for only 10ms:
|
| 10 |
+
|
| 11 |
+
```js
|
| 12 |
+
import { request, setGlobalDispatcher, Agent } from 'undici'
|
| 13 |
+
|
| 14 |
+
const agent = new Agent({
|
| 15 |
+
keepAliveTimeout: 10, // milliseconds
|
| 16 |
+
keepAliveMaxTimeout: 10 // milliseconds
|
| 17 |
+
})
|
| 18 |
+
|
| 19 |
+
setGlobalDispatcher(agent)
|
| 20 |
+
```
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/api/abort-signal.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'use strict'
|
| 2 |
+
|
| 3 |
+
const { addAbortListener } = require('../core/util')
|
| 4 |
+
const { RequestAbortedError } = require('../core/errors')
|
| 5 |
+
|
| 6 |
+
const kListener = Symbol('kListener')
|
| 7 |
+
const kSignal = Symbol('kSignal')
|
| 8 |
+
|
| 9 |
+
function abort (self) {
|
| 10 |
+
if (self.abort) {
|
| 11 |
+
self.abort(self[kSignal]?.reason)
|
| 12 |
+
} else {
|
| 13 |
+
self.reason = self[kSignal]?.reason ?? new RequestAbortedError()
|
| 14 |
+
}
|
| 15 |
+
removeSignal(self)
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
function addSignal (self, signal) {
|
| 19 |
+
self.reason = null
|
| 20 |
+
|
| 21 |
+
self[kSignal] = null
|
| 22 |
+
self[kListener] = null
|
| 23 |
+
|
| 24 |
+
if (!signal) {
|
| 25 |
+
return
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
if (signal.aborted) {
|
| 29 |
+
abort(self)
|
| 30 |
+
return
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
self[kSignal] = signal
|
| 34 |
+
self[kListener] = () => {
|
| 35 |
+
abort(self)
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
addAbortListener(self[kSignal], self[kListener])
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
function removeSignal (self) {
|
| 42 |
+
if (!self[kSignal]) {
|
| 43 |
+
return
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
if ('removeEventListener' in self[kSignal]) {
|
| 47 |
+
self[kSignal].removeEventListener('abort', self[kListener])
|
| 48 |
+
} else {
|
| 49 |
+
self[kSignal].removeListener('abort', self[kListener])
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
self[kSignal] = null
|
| 53 |
+
self[kListener] = null
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
module.exports = {
|
| 57 |
+
addSignal,
|
| 58 |
+
removeSignal
|
| 59 |
+
}
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/api/api-connect.js
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'use strict'
|
| 2 |
+
|
| 3 |
+
const assert = require('node:assert')
|
| 4 |
+
const { AsyncResource } = require('node:async_hooks')
|
| 5 |
+
const { InvalidArgumentError, SocketError } = require('../core/errors')
|
| 6 |
+
const util = require('../core/util')
|
| 7 |
+
const { addSignal, removeSignal } = require('./abort-signal')
|
| 8 |
+
|
| 9 |
+
class ConnectHandler extends AsyncResource {
|
| 10 |
+
constructor (opts, callback) {
|
| 11 |
+
if (!opts || typeof opts !== 'object') {
|
| 12 |
+
throw new InvalidArgumentError('invalid opts')
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
if (typeof callback !== 'function') {
|
| 16 |
+
throw new InvalidArgumentError('invalid callback')
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
const { signal, opaque, responseHeaders } = opts
|
| 20 |
+
|
| 21 |
+
if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
|
| 22 |
+
throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
super('UNDICI_CONNECT')
|
| 26 |
+
|
| 27 |
+
this.opaque = opaque || null
|
| 28 |
+
this.responseHeaders = responseHeaders || null
|
| 29 |
+
this.callback = callback
|
| 30 |
+
this.abort = null
|
| 31 |
+
|
| 32 |
+
addSignal(this, signal)
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
onConnect (abort, context) {
|
| 36 |
+
if (this.reason) {
|
| 37 |
+
abort(this.reason)
|
| 38 |
+
return
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
assert(this.callback)
|
| 42 |
+
|
| 43 |
+
this.abort = abort
|
| 44 |
+
this.context = context
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
onHeaders () {
|
| 48 |
+
throw new SocketError('bad connect', null)
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
onUpgrade (statusCode, rawHeaders, socket) {
|
| 52 |
+
const { callback, opaque, context } = this
|
| 53 |
+
|
| 54 |
+
removeSignal(this)
|
| 55 |
+
|
| 56 |
+
this.callback = null
|
| 57 |
+
|
| 58 |
+
let headers = rawHeaders
|
| 59 |
+
// Indicates is an HTTP2Session
|
| 60 |
+
if (headers != null) {
|
| 61 |
+
headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
this.runInAsyncScope(callback, null, null, {
|
| 65 |
+
statusCode,
|
| 66 |
+
headers,
|
| 67 |
+
socket,
|
| 68 |
+
opaque,
|
| 69 |
+
context
|
| 70 |
+
})
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
onError (err) {
|
| 74 |
+
const { callback, opaque } = this
|
| 75 |
+
|
| 76 |
+
removeSignal(this)
|
| 77 |
+
|
| 78 |
+
if (callback) {
|
| 79 |
+
this.callback = null
|
| 80 |
+
queueMicrotask(() => {
|
| 81 |
+
this.runInAsyncScope(callback, null, err, { opaque })
|
| 82 |
+
})
|
| 83 |
+
}
|
| 84 |
+
}
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
function connect (opts, callback) {
|
| 88 |
+
if (callback === undefined) {
|
| 89 |
+
return new Promise((resolve, reject) => {
|
| 90 |
+
connect.call(this, opts, (err, data) => {
|
| 91 |
+
return err ? reject(err) : resolve(data)
|
| 92 |
+
})
|
| 93 |
+
})
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
try {
|
| 97 |
+
const connectHandler = new ConnectHandler(opts, callback)
|
| 98 |
+
const connectOptions = { ...opts, method: 'CONNECT' }
|
| 99 |
+
|
| 100 |
+
this.dispatch(connectOptions, connectHandler)
|
| 101 |
+
} catch (err) {
|
| 102 |
+
if (typeof callback !== 'function') {
|
| 103 |
+
throw err
|
| 104 |
+
}
|
| 105 |
+
const opaque = opts?.opaque
|
| 106 |
+
queueMicrotask(() => callback(err, { opaque }))
|
| 107 |
+
}
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
module.exports = connect
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/api/api-pipeline.js
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'use strict'
|
| 2 |
+
|
| 3 |
+
const {
|
| 4 |
+
Readable,
|
| 5 |
+
Duplex,
|
| 6 |
+
PassThrough
|
| 7 |
+
} = require('node:stream')
|
| 8 |
+
const assert = require('node:assert')
|
| 9 |
+
const { AsyncResource } = require('node:async_hooks')
|
| 10 |
+
const {
|
| 11 |
+
InvalidArgumentError,
|
| 12 |
+
InvalidReturnValueError,
|
| 13 |
+
RequestAbortedError
|
| 14 |
+
} = require('../core/errors')
|
| 15 |
+
const util = require('../core/util')
|
| 16 |
+
const { addSignal, removeSignal } = require('./abort-signal')
|
| 17 |
+
|
| 18 |
+
function noop () {}
|
| 19 |
+
|
| 20 |
+
const kResume = Symbol('resume')
|
| 21 |
+
|
| 22 |
+
class PipelineRequest extends Readable {
|
| 23 |
+
constructor () {
|
| 24 |
+
super({ autoDestroy: true })
|
| 25 |
+
|
| 26 |
+
this[kResume] = null
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
_read () {
|
| 30 |
+
const { [kResume]: resume } = this
|
| 31 |
+
|
| 32 |
+
if (resume) {
|
| 33 |
+
this[kResume] = null
|
| 34 |
+
resume()
|
| 35 |
+
}
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
_destroy (err, callback) {
|
| 39 |
+
this._read()
|
| 40 |
+
|
| 41 |
+
callback(err)
|
| 42 |
+
}
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
class PipelineResponse extends Readable {
|
| 46 |
+
constructor (resume) {
|
| 47 |
+
super({ autoDestroy: true })
|
| 48 |
+
this[kResume] = resume
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
_read () {
|
| 52 |
+
this[kResume]()
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
_destroy (err, callback) {
|
| 56 |
+
if (!err && !this._readableState.endEmitted) {
|
| 57 |
+
err = new RequestAbortedError()
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
callback(err)
|
| 61 |
+
}
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
class PipelineHandler extends AsyncResource {
|
| 65 |
+
constructor (opts, handler) {
|
| 66 |
+
if (!opts || typeof opts !== 'object') {
|
| 67 |
+
throw new InvalidArgumentError('invalid opts')
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
if (typeof handler !== 'function') {
|
| 71 |
+
throw new InvalidArgumentError('invalid handler')
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
const { signal, method, opaque, onInfo, responseHeaders } = opts
|
| 75 |
+
|
| 76 |
+
if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
|
| 77 |
+
throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
if (method === 'CONNECT') {
|
| 81 |
+
throw new InvalidArgumentError('invalid method')
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
if (onInfo && typeof onInfo !== 'function') {
|
| 85 |
+
throw new InvalidArgumentError('invalid onInfo callback')
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
super('UNDICI_PIPELINE')
|
| 89 |
+
|
| 90 |
+
this.opaque = opaque || null
|
| 91 |
+
this.responseHeaders = responseHeaders || null
|
| 92 |
+
this.handler = handler
|
| 93 |
+
this.abort = null
|
| 94 |
+
this.context = null
|
| 95 |
+
this.onInfo = onInfo || null
|
| 96 |
+
|
| 97 |
+
this.req = new PipelineRequest().on('error', noop)
|
| 98 |
+
|
| 99 |
+
this.ret = new Duplex({
|
| 100 |
+
readableObjectMode: opts.objectMode,
|
| 101 |
+
autoDestroy: true,
|
| 102 |
+
read: () => {
|
| 103 |
+
const { body } = this
|
| 104 |
+
|
| 105 |
+
if (body?.resume) {
|
| 106 |
+
body.resume()
|
| 107 |
+
}
|
| 108 |
+
},
|
| 109 |
+
write: (chunk, encoding, callback) => {
|
| 110 |
+
const { req } = this
|
| 111 |
+
|
| 112 |
+
if (req.push(chunk, encoding) || req._readableState.destroyed) {
|
| 113 |
+
callback()
|
| 114 |
+
} else {
|
| 115 |
+
req[kResume] = callback
|
| 116 |
+
}
|
| 117 |
+
},
|
| 118 |
+
destroy: (err, callback) => {
|
| 119 |
+
const { body, req, res, ret, abort } = this
|
| 120 |
+
|
| 121 |
+
if (!err && !ret._readableState.endEmitted) {
|
| 122 |
+
err = new RequestAbortedError()
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
if (abort && err) {
|
| 126 |
+
abort()
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
util.destroy(body, err)
|
| 130 |
+
util.destroy(req, err)
|
| 131 |
+
util.destroy(res, err)
|
| 132 |
+
|
| 133 |
+
removeSignal(this)
|
| 134 |
+
|
| 135 |
+
callback(err)
|
| 136 |
+
}
|
| 137 |
+
}).on('prefinish', () => {
|
| 138 |
+
const { req } = this
|
| 139 |
+
|
| 140 |
+
// Node < 15 does not call _final in same tick.
|
| 141 |
+
req.push(null)
|
| 142 |
+
})
|
| 143 |
+
|
| 144 |
+
this.res = null
|
| 145 |
+
|
| 146 |
+
addSignal(this, signal)
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
onConnect (abort, context) {
|
| 150 |
+
const { res } = this
|
| 151 |
+
|
| 152 |
+
if (this.reason) {
|
| 153 |
+
abort(this.reason)
|
| 154 |
+
return
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
assert(!res, 'pipeline cannot be retried')
|
| 158 |
+
|
| 159 |
+
this.abort = abort
|
| 160 |
+
this.context = context
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
onHeaders (statusCode, rawHeaders, resume) {
|
| 164 |
+
const { opaque, handler, context } = this
|
| 165 |
+
|
| 166 |
+
if (statusCode < 200) {
|
| 167 |
+
if (this.onInfo) {
|
| 168 |
+
const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
|
| 169 |
+
this.onInfo({ statusCode, headers })
|
| 170 |
+
}
|
| 171 |
+
return
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
this.res = new PipelineResponse(resume)
|
| 175 |
+
|
| 176 |
+
let body
|
| 177 |
+
try {
|
| 178 |
+
this.handler = null
|
| 179 |
+
const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
|
| 180 |
+
body = this.runInAsyncScope(handler, null, {
|
| 181 |
+
statusCode,
|
| 182 |
+
headers,
|
| 183 |
+
opaque,
|
| 184 |
+
body: this.res,
|
| 185 |
+
context
|
| 186 |
+
})
|
| 187 |
+
} catch (err) {
|
| 188 |
+
this.res.on('error', noop)
|
| 189 |
+
throw err
|
| 190 |
+
}
|
| 191 |
+
|
| 192 |
+
if (!body || typeof body.on !== 'function') {
|
| 193 |
+
throw new InvalidReturnValueError('expected Readable')
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
body
|
| 197 |
+
.on('data', (chunk) => {
|
| 198 |
+
const { ret, body } = this
|
| 199 |
+
|
| 200 |
+
if (!ret.push(chunk) && body.pause) {
|
| 201 |
+
body.pause()
|
| 202 |
+
}
|
| 203 |
+
})
|
| 204 |
+
.on('error', (err) => {
|
| 205 |
+
const { ret } = this
|
| 206 |
+
|
| 207 |
+
util.destroy(ret, err)
|
| 208 |
+
})
|
| 209 |
+
.on('end', () => {
|
| 210 |
+
const { ret } = this
|
| 211 |
+
|
| 212 |
+
ret.push(null)
|
| 213 |
+
})
|
| 214 |
+
.on('close', () => {
|
| 215 |
+
const { ret } = this
|
| 216 |
+
|
| 217 |
+
if (!ret._readableState.ended) {
|
| 218 |
+
util.destroy(ret, new RequestAbortedError())
|
| 219 |
+
}
|
| 220 |
+
})
|
| 221 |
+
|
| 222 |
+
this.body = body
|
| 223 |
+
}
|
| 224 |
+
|
| 225 |
+
onData (chunk) {
|
| 226 |
+
const { res } = this
|
| 227 |
+
return res.push(chunk)
|
| 228 |
+
}
|
| 229 |
+
|
| 230 |
+
onComplete (trailers) {
|
| 231 |
+
const { res } = this
|
| 232 |
+
res.push(null)
|
| 233 |
+
}
|
| 234 |
+
|
| 235 |
+
onError (err) {
|
| 236 |
+
const { ret } = this
|
| 237 |
+
this.handler = null
|
| 238 |
+
util.destroy(ret, err)
|
| 239 |
+
}
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
function pipeline (opts, handler) {
|
| 243 |
+
try {
|
| 244 |
+
const pipelineHandler = new PipelineHandler(opts, handler)
|
| 245 |
+
this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler)
|
| 246 |
+
return pipelineHandler.ret
|
| 247 |
+
} catch (err) {
|
| 248 |
+
return new PassThrough().destroy(err)
|
| 249 |
+
}
|
| 250 |
+
}
|
| 251 |
+
|
| 252 |
+
module.exports = pipeline
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/api/api-request.js
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'use strict'
|
| 2 |
+
|
| 3 |
+
const assert = require('node:assert')
|
| 4 |
+
const { AsyncResource } = require('node:async_hooks')
|
| 5 |
+
const { Readable } = require('./readable')
|
| 6 |
+
const { InvalidArgumentError, RequestAbortedError } = require('../core/errors')
|
| 7 |
+
const util = require('../core/util')
|
| 8 |
+
|
| 9 |
+
function noop () {}
|
| 10 |
+
|
| 11 |
+
class RequestHandler extends AsyncResource {
|
| 12 |
+
constructor (opts, callback) {
|
| 13 |
+
if (!opts || typeof opts !== 'object') {
|
| 14 |
+
throw new InvalidArgumentError('invalid opts')
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
const { signal, method, opaque, body, onInfo, responseHeaders, highWaterMark } = opts
|
| 18 |
+
|
| 19 |
+
try {
|
| 20 |
+
if (typeof callback !== 'function') {
|
| 21 |
+
throw new InvalidArgumentError('invalid callback')
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
if (highWaterMark && (typeof highWaterMark !== 'number' || highWaterMark < 0)) {
|
| 25 |
+
throw new InvalidArgumentError('invalid highWaterMark')
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
|
| 29 |
+
throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
if (method === 'CONNECT') {
|
| 33 |
+
throw new InvalidArgumentError('invalid method')
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
if (onInfo && typeof onInfo !== 'function') {
|
| 37 |
+
throw new InvalidArgumentError('invalid onInfo callback')
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
super('UNDICI_REQUEST')
|
| 41 |
+
} catch (err) {
|
| 42 |
+
if (util.isStream(body)) {
|
| 43 |
+
util.destroy(body.on('error', noop), err)
|
| 44 |
+
}
|
| 45 |
+
throw err
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
this.method = method
|
| 49 |
+
this.responseHeaders = responseHeaders || null
|
| 50 |
+
this.opaque = opaque || null
|
| 51 |
+
this.callback = callback
|
| 52 |
+
this.res = null
|
| 53 |
+
this.abort = null
|
| 54 |
+
this.body = body
|
| 55 |
+
this.trailers = {}
|
| 56 |
+
this.context = null
|
| 57 |
+
this.onInfo = onInfo || null
|
| 58 |
+
this.highWaterMark = highWaterMark
|
| 59 |
+
this.reason = null
|
| 60 |
+
this.removeAbortListener = null
|
| 61 |
+
|
| 62 |
+
if (signal?.aborted) {
|
| 63 |
+
this.reason = signal.reason ?? new RequestAbortedError()
|
| 64 |
+
} else if (signal) {
|
| 65 |
+
this.removeAbortListener = util.addAbortListener(signal, () => {
|
| 66 |
+
this.reason = signal.reason ?? new RequestAbortedError()
|
| 67 |
+
if (this.res) {
|
| 68 |
+
util.destroy(this.res.on('error', noop), this.reason)
|
| 69 |
+
} else if (this.abort) {
|
| 70 |
+
this.abort(this.reason)
|
| 71 |
+
}
|
| 72 |
+
})
|
| 73 |
+
}
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
onConnect (abort, context) {
|
| 77 |
+
if (this.reason) {
|
| 78 |
+
abort(this.reason)
|
| 79 |
+
return
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
assert(this.callback)
|
| 83 |
+
|
| 84 |
+
this.abort = abort
|
| 85 |
+
this.context = context
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
onHeaders (statusCode, rawHeaders, resume, statusMessage) {
|
| 89 |
+
const { callback, opaque, abort, context, responseHeaders, highWaterMark } = this
|
| 90 |
+
|
| 91 |
+
const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
|
| 92 |
+
|
| 93 |
+
if (statusCode < 200) {
|
| 94 |
+
if (this.onInfo) {
|
| 95 |
+
this.onInfo({ statusCode, headers })
|
| 96 |
+
}
|
| 97 |
+
return
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers
|
| 101 |
+
const contentType = parsedHeaders['content-type']
|
| 102 |
+
const contentLength = parsedHeaders['content-length']
|
| 103 |
+
const res = new Readable({
|
| 104 |
+
resume,
|
| 105 |
+
abort,
|
| 106 |
+
contentType,
|
| 107 |
+
contentLength: this.method !== 'HEAD' && contentLength
|
| 108 |
+
? Number(contentLength)
|
| 109 |
+
: null,
|
| 110 |
+
highWaterMark
|
| 111 |
+
})
|
| 112 |
+
|
| 113 |
+
if (this.removeAbortListener) {
|
| 114 |
+
res.on('close', this.removeAbortListener)
|
| 115 |
+
this.removeAbortListener = null
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
this.callback = null
|
| 119 |
+
this.res = res
|
| 120 |
+
if (callback !== null) {
|
| 121 |
+
this.runInAsyncScope(callback, null, null, {
|
| 122 |
+
statusCode,
|
| 123 |
+
headers,
|
| 124 |
+
trailers: this.trailers,
|
| 125 |
+
opaque,
|
| 126 |
+
body: res,
|
| 127 |
+
context
|
| 128 |
+
})
|
| 129 |
+
}
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
onData (chunk) {
|
| 133 |
+
return this.res.push(chunk)
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
onComplete (trailers) {
|
| 137 |
+
util.parseHeaders(trailers, this.trailers)
|
| 138 |
+
this.res.push(null)
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
onError (err) {
|
| 142 |
+
const { res, callback, body, opaque } = this
|
| 143 |
+
|
| 144 |
+
if (callback) {
|
| 145 |
+
// TODO: Does this need queueMicrotask?
|
| 146 |
+
this.callback = null
|
| 147 |
+
queueMicrotask(() => {
|
| 148 |
+
this.runInAsyncScope(callback, null, err, { opaque })
|
| 149 |
+
})
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
if (res) {
|
| 153 |
+
this.res = null
|
| 154 |
+
// Ensure all queued handlers are invoked before destroying res.
|
| 155 |
+
queueMicrotask(() => {
|
| 156 |
+
util.destroy(res.on('error', noop), err)
|
| 157 |
+
})
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
+
if (body) {
|
| 161 |
+
this.body = null
|
| 162 |
+
|
| 163 |
+
if (util.isStream(body)) {
|
| 164 |
+
body.on('error', noop)
|
| 165 |
+
util.destroy(body, err)
|
| 166 |
+
}
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
if (this.removeAbortListener) {
|
| 170 |
+
this.removeAbortListener()
|
| 171 |
+
this.removeAbortListener = null
|
| 172 |
+
}
|
| 173 |
+
}
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
function request (opts, callback) {
|
| 177 |
+
if (callback === undefined) {
|
| 178 |
+
return new Promise((resolve, reject) => {
|
| 179 |
+
request.call(this, opts, (err, data) => {
|
| 180 |
+
return err ? reject(err) : resolve(data)
|
| 181 |
+
})
|
| 182 |
+
})
|
| 183 |
+
}
|
| 184 |
+
|
| 185 |
+
try {
|
| 186 |
+
const handler = new RequestHandler(opts, callback)
|
| 187 |
+
|
| 188 |
+
this.dispatch(opts, handler)
|
| 189 |
+
} catch (err) {
|
| 190 |
+
if (typeof callback !== 'function') {
|
| 191 |
+
throw err
|
| 192 |
+
}
|
| 193 |
+
const opaque = opts?.opaque
|
| 194 |
+
queueMicrotask(() => callback(err, { opaque }))
|
| 195 |
+
}
|
| 196 |
+
}
|
| 197 |
+
|
| 198 |
+
module.exports = request
|
| 199 |
+
module.exports.RequestHandler = RequestHandler
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/api/api-stream.js
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'use strict'
|
| 2 |
+
|
| 3 |
+
const assert = require('node:assert')
|
| 4 |
+
const { finished } = require('node:stream')
|
| 5 |
+
const { AsyncResource } = require('node:async_hooks')
|
| 6 |
+
const { InvalidArgumentError, InvalidReturnValueError } = require('../core/errors')
|
| 7 |
+
const util = require('../core/util')
|
| 8 |
+
const { addSignal, removeSignal } = require('./abort-signal')
|
| 9 |
+
|
| 10 |
+
function noop () {}
|
| 11 |
+
|
| 12 |
+
class StreamHandler extends AsyncResource {
|
| 13 |
+
constructor (opts, factory, callback) {
|
| 14 |
+
if (!opts || typeof opts !== 'object') {
|
| 15 |
+
throw new InvalidArgumentError('invalid opts')
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
const { signal, method, opaque, body, onInfo, responseHeaders } = opts
|
| 19 |
+
|
| 20 |
+
try {
|
| 21 |
+
if (typeof callback !== 'function') {
|
| 22 |
+
throw new InvalidArgumentError('invalid callback')
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
if (typeof factory !== 'function') {
|
| 26 |
+
throw new InvalidArgumentError('invalid factory')
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
|
| 30 |
+
throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
if (method === 'CONNECT') {
|
| 34 |
+
throw new InvalidArgumentError('invalid method')
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
if (onInfo && typeof onInfo !== 'function') {
|
| 38 |
+
throw new InvalidArgumentError('invalid onInfo callback')
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
super('UNDICI_STREAM')
|
| 42 |
+
} catch (err) {
|
| 43 |
+
if (util.isStream(body)) {
|
| 44 |
+
util.destroy(body.on('error', noop), err)
|
| 45 |
+
}
|
| 46 |
+
throw err
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
this.responseHeaders = responseHeaders || null
|
| 50 |
+
this.opaque = opaque || null
|
| 51 |
+
this.factory = factory
|
| 52 |
+
this.callback = callback
|
| 53 |
+
this.res = null
|
| 54 |
+
this.abort = null
|
| 55 |
+
this.context = null
|
| 56 |
+
this.trailers = null
|
| 57 |
+
this.body = body
|
| 58 |
+
this.onInfo = onInfo || null
|
| 59 |
+
|
| 60 |
+
if (util.isStream(body)) {
|
| 61 |
+
body.on('error', (err) => {
|
| 62 |
+
this.onError(err)
|
| 63 |
+
})
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
addSignal(this, signal)
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
onConnect (abort, context) {
|
| 70 |
+
if (this.reason) {
|
| 71 |
+
abort(this.reason)
|
| 72 |
+
return
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
assert(this.callback)
|
| 76 |
+
|
| 77 |
+
this.abort = abort
|
| 78 |
+
this.context = context
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
onHeaders (statusCode, rawHeaders, resume, statusMessage) {
|
| 82 |
+
const { factory, opaque, context, responseHeaders } = this
|
| 83 |
+
|
| 84 |
+
const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
|
| 85 |
+
|
| 86 |
+
if (statusCode < 200) {
|
| 87 |
+
if (this.onInfo) {
|
| 88 |
+
this.onInfo({ statusCode, headers })
|
| 89 |
+
}
|
| 90 |
+
return
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
this.factory = null
|
| 94 |
+
|
| 95 |
+
if (factory === null) {
|
| 96 |
+
return
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
const res = this.runInAsyncScope(factory, null, {
|
| 100 |
+
statusCode,
|
| 101 |
+
headers,
|
| 102 |
+
opaque,
|
| 103 |
+
context
|
| 104 |
+
})
|
| 105 |
+
|
| 106 |
+
if (
|
| 107 |
+
!res ||
|
| 108 |
+
typeof res.write !== 'function' ||
|
| 109 |
+
typeof res.end !== 'function' ||
|
| 110 |
+
typeof res.on !== 'function'
|
| 111 |
+
) {
|
| 112 |
+
throw new InvalidReturnValueError('expected Writable')
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
// TODO: Avoid finished. It registers an unnecessary amount of listeners.
|
| 116 |
+
finished(res, { readable: false }, (err) => {
|
| 117 |
+
const { callback, res, opaque, trailers, abort } = this
|
| 118 |
+
|
| 119 |
+
this.res = null
|
| 120 |
+
if (err || !res?.readable) {
|
| 121 |
+
util.destroy(res, err)
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
this.callback = null
|
| 125 |
+
this.runInAsyncScope(callback, null, err || null, { opaque, trailers })
|
| 126 |
+
|
| 127 |
+
if (err) {
|
| 128 |
+
abort()
|
| 129 |
+
}
|
| 130 |
+
})
|
| 131 |
+
|
| 132 |
+
res.on('drain', resume)
|
| 133 |
+
|
| 134 |
+
this.res = res
|
| 135 |
+
|
| 136 |
+
const needDrain = res.writableNeedDrain !== undefined
|
| 137 |
+
? res.writableNeedDrain
|
| 138 |
+
: res._writableState?.needDrain
|
| 139 |
+
|
| 140 |
+
return needDrain !== true
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
onData (chunk) {
|
| 144 |
+
const { res } = this
|
| 145 |
+
|
| 146 |
+
return res ? res.write(chunk) : true
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
onComplete (trailers) {
|
| 150 |
+
const { res } = this
|
| 151 |
+
|
| 152 |
+
removeSignal(this)
|
| 153 |
+
|
| 154 |
+
if (!res) {
|
| 155 |
+
return
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
this.trailers = util.parseHeaders(trailers)
|
| 159 |
+
|
| 160 |
+
res.end()
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
onError (err) {
|
| 164 |
+
const { res, callback, opaque, body } = this
|
| 165 |
+
|
| 166 |
+
removeSignal(this)
|
| 167 |
+
|
| 168 |
+
this.factory = null
|
| 169 |
+
|
| 170 |
+
if (res) {
|
| 171 |
+
this.res = null
|
| 172 |
+
util.destroy(res, err)
|
| 173 |
+
} else if (callback) {
|
| 174 |
+
this.callback = null
|
| 175 |
+
queueMicrotask(() => {
|
| 176 |
+
this.runInAsyncScope(callback, null, err, { opaque })
|
| 177 |
+
})
|
| 178 |
+
}
|
| 179 |
+
|
| 180 |
+
if (body) {
|
| 181 |
+
this.body = null
|
| 182 |
+
util.destroy(body, err)
|
| 183 |
+
}
|
| 184 |
+
}
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
function stream (opts, factory, callback) {
|
| 188 |
+
if (callback === undefined) {
|
| 189 |
+
return new Promise((resolve, reject) => {
|
| 190 |
+
stream.call(this, opts, factory, (err, data) => {
|
| 191 |
+
return err ? reject(err) : resolve(data)
|
| 192 |
+
})
|
| 193 |
+
})
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
try {
|
| 197 |
+
const handler = new StreamHandler(opts, factory, callback)
|
| 198 |
+
|
| 199 |
+
this.dispatch(opts, handler)
|
| 200 |
+
} catch (err) {
|
| 201 |
+
if (typeof callback !== 'function') {
|
| 202 |
+
throw err
|
| 203 |
+
}
|
| 204 |
+
const opaque = opts?.opaque
|
| 205 |
+
queueMicrotask(() => callback(err, { opaque }))
|
| 206 |
+
}
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
module.exports = stream
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/api/api-upgrade.js
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'use strict'
|
| 2 |
+
|
| 3 |
+
const { InvalidArgumentError, SocketError } = require('../core/errors')
|
| 4 |
+
const { AsyncResource } = require('node:async_hooks')
|
| 5 |
+
const assert = require('node:assert')
|
| 6 |
+
const util = require('../core/util')
|
| 7 |
+
const { addSignal, removeSignal } = require('./abort-signal')
|
| 8 |
+
|
| 9 |
+
class UpgradeHandler extends AsyncResource {
|
| 10 |
+
constructor (opts, callback) {
|
| 11 |
+
if (!opts || typeof opts !== 'object') {
|
| 12 |
+
throw new InvalidArgumentError('invalid opts')
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
if (typeof callback !== 'function') {
|
| 16 |
+
throw new InvalidArgumentError('invalid callback')
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
const { signal, opaque, responseHeaders } = opts
|
| 20 |
+
|
| 21 |
+
if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
|
| 22 |
+
throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
super('UNDICI_UPGRADE')
|
| 26 |
+
|
| 27 |
+
this.responseHeaders = responseHeaders || null
|
| 28 |
+
this.opaque = opaque || null
|
| 29 |
+
this.callback = callback
|
| 30 |
+
this.abort = null
|
| 31 |
+
this.context = null
|
| 32 |
+
|
| 33 |
+
addSignal(this, signal)
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
onConnect (abort, context) {
|
| 37 |
+
if (this.reason) {
|
| 38 |
+
abort(this.reason)
|
| 39 |
+
return
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
assert(this.callback)
|
| 43 |
+
|
| 44 |
+
this.abort = abort
|
| 45 |
+
this.context = null
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
onHeaders () {
|
| 49 |
+
throw new SocketError('bad upgrade', null)
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
onUpgrade (statusCode, rawHeaders, socket) {
|
| 53 |
+
assert(statusCode === 101)
|
| 54 |
+
|
| 55 |
+
const { callback, opaque, context } = this
|
| 56 |
+
|
| 57 |
+
removeSignal(this)
|
| 58 |
+
|
| 59 |
+
this.callback = null
|
| 60 |
+
const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
|
| 61 |
+
this.runInAsyncScope(callback, null, null, {
|
| 62 |
+
headers,
|
| 63 |
+
socket,
|
| 64 |
+
opaque,
|
| 65 |
+
context
|
| 66 |
+
})
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
onError (err) {
|
| 70 |
+
const { callback, opaque } = this
|
| 71 |
+
|
| 72 |
+
removeSignal(this)
|
| 73 |
+
|
| 74 |
+
if (callback) {
|
| 75 |
+
this.callback = null
|
| 76 |
+
queueMicrotask(() => {
|
| 77 |
+
this.runInAsyncScope(callback, null, err, { opaque })
|
| 78 |
+
})
|
| 79 |
+
}
|
| 80 |
+
}
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
function upgrade (opts, callback) {
|
| 84 |
+
if (callback === undefined) {
|
| 85 |
+
return new Promise((resolve, reject) => {
|
| 86 |
+
upgrade.call(this, opts, (err, data) => {
|
| 87 |
+
return err ? reject(err) : resolve(data)
|
| 88 |
+
})
|
| 89 |
+
})
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
try {
|
| 93 |
+
const upgradeHandler = new UpgradeHandler(opts, callback)
|
| 94 |
+
const upgradeOpts = {
|
| 95 |
+
...opts,
|
| 96 |
+
method: opts.method || 'GET',
|
| 97 |
+
upgrade: opts.protocol || 'Websocket'
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
this.dispatch(upgradeOpts, upgradeHandler)
|
| 101 |
+
} catch (err) {
|
| 102 |
+
if (typeof callback !== 'function') {
|
| 103 |
+
throw err
|
| 104 |
+
}
|
| 105 |
+
const opaque = opts?.opaque
|
| 106 |
+
queueMicrotask(() => callback(err, { opaque }))
|
| 107 |
+
}
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
module.exports = upgrade
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/api/index.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'use strict'
|
| 2 |
+
|
| 3 |
+
module.exports.request = require('./api-request')
|
| 4 |
+
module.exports.stream = require('./api-stream')
|
| 5 |
+
module.exports.pipeline = require('./api-pipeline')
|
| 6 |
+
module.exports.upgrade = require('./api-upgrade')
|
| 7 |
+
module.exports.connect = require('./api-connect')
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/api/readable.js
ADDED
|
@@ -0,0 +1,578 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'use strict'
|
| 2 |
+
|
| 3 |
+
const assert = require('node:assert')
|
| 4 |
+
const { Readable } = require('node:stream')
|
| 5 |
+
const { RequestAbortedError, NotSupportedError, InvalidArgumentError, AbortError } = require('../core/errors')
|
| 6 |
+
const util = require('../core/util')
|
| 7 |
+
const { ReadableStreamFrom } = require('../core/util')
|
| 8 |
+
|
| 9 |
+
const kConsume = Symbol('kConsume')
|
| 10 |
+
const kReading = Symbol('kReading')
|
| 11 |
+
const kBody = Symbol('kBody')
|
| 12 |
+
const kAbort = Symbol('kAbort')
|
| 13 |
+
const kContentType = Symbol('kContentType')
|
| 14 |
+
const kContentLength = Symbol('kContentLength')
|
| 15 |
+
const kUsed = Symbol('kUsed')
|
| 16 |
+
const kBytesRead = Symbol('kBytesRead')
|
| 17 |
+
|
| 18 |
+
const noop = () => {}
|
| 19 |
+
|
| 20 |
+
/**
|
| 21 |
+
* @class
|
| 22 |
+
* @extends {Readable}
|
| 23 |
+
* @see https://fetch.spec.whatwg.org/#body
|
| 24 |
+
*/
|
| 25 |
+
class BodyReadable extends Readable {
|
| 26 |
+
/**
|
| 27 |
+
* @param {object} opts
|
| 28 |
+
* @param {(this: Readable, size: number) => void} opts.resume
|
| 29 |
+
* @param {() => (void | null)} opts.abort
|
| 30 |
+
* @param {string} [opts.contentType = '']
|
| 31 |
+
* @param {number} [opts.contentLength]
|
| 32 |
+
* @param {number} [opts.highWaterMark = 64 * 1024]
|
| 33 |
+
*/
|
| 34 |
+
constructor ({
|
| 35 |
+
resume,
|
| 36 |
+
abort,
|
| 37 |
+
contentType = '',
|
| 38 |
+
contentLength,
|
| 39 |
+
highWaterMark = 64 * 1024 // Same as nodejs fs streams.
|
| 40 |
+
}) {
|
| 41 |
+
super({
|
| 42 |
+
autoDestroy: true,
|
| 43 |
+
read: resume,
|
| 44 |
+
highWaterMark
|
| 45 |
+
})
|
| 46 |
+
|
| 47 |
+
this._readableState.dataEmitted = false
|
| 48 |
+
|
| 49 |
+
this[kAbort] = abort
|
| 50 |
+
|
| 51 |
+
/** @type {Consume | null} */
|
| 52 |
+
this[kConsume] = null
|
| 53 |
+
|
| 54 |
+
/** @type {number} */
|
| 55 |
+
this[kBytesRead] = 0
|
| 56 |
+
|
| 57 |
+
/** @type {ReadableStream|null} */
|
| 58 |
+
this[kBody] = null
|
| 59 |
+
|
| 60 |
+
/** @type {boolean} */
|
| 61 |
+
this[kUsed] = false
|
| 62 |
+
|
| 63 |
+
/** @type {string} */
|
| 64 |
+
this[kContentType] = contentType
|
| 65 |
+
|
| 66 |
+
/** @type {number|null} */
|
| 67 |
+
this[kContentLength] = Number.isFinite(contentLength) ? contentLength : null
|
| 68 |
+
|
| 69 |
+
/**
|
| 70 |
+
* Is stream being consumed through Readable API?
|
| 71 |
+
* This is an optimization so that we avoid checking
|
| 72 |
+
* for 'data' and 'readable' listeners in the hot path
|
| 73 |
+
* inside push().
|
| 74 |
+
*
|
| 75 |
+
* @type {boolean}
|
| 76 |
+
*/
|
| 77 |
+
this[kReading] = false
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
/**
|
| 81 |
+
* @param {Error|null} err
|
| 82 |
+
* @param {(error:(Error|null)) => void} callback
|
| 83 |
+
* @returns {void}
|
| 84 |
+
*/
|
| 85 |
+
_destroy (err, callback) {
|
| 86 |
+
if (!err && !this._readableState.endEmitted) {
|
| 87 |
+
err = new RequestAbortedError()
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
if (err) {
|
| 91 |
+
this[kAbort]()
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
// Workaround for Node "bug". If the stream is destroyed in same
|
| 95 |
+
// tick as it is created, then a user who is waiting for a
|
| 96 |
+
// promise (i.e micro tick) for installing an 'error' listener will
|
| 97 |
+
// never get a chance and will always encounter an unhandled exception.
|
| 98 |
+
if (!this[kUsed]) {
|
| 99 |
+
setImmediate(callback, err)
|
| 100 |
+
} else {
|
| 101 |
+
callback(err)
|
| 102 |
+
}
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
/**
|
| 106 |
+
* @param {string|symbol} event
|
| 107 |
+
* @param {(...args: any[]) => void} listener
|
| 108 |
+
* @returns {this}
|
| 109 |
+
*/
|
| 110 |
+
on (event, listener) {
|
| 111 |
+
if (event === 'data' || event === 'readable') {
|
| 112 |
+
this[kReading] = true
|
| 113 |
+
this[kUsed] = true
|
| 114 |
+
}
|
| 115 |
+
return super.on(event, listener)
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
/**
|
| 119 |
+
* @param {string|symbol} event
|
| 120 |
+
* @param {(...args: any[]) => void} listener
|
| 121 |
+
* @returns {this}
|
| 122 |
+
*/
|
| 123 |
+
addListener (event, listener) {
|
| 124 |
+
return this.on(event, listener)
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
/**
|
| 128 |
+
* @param {string|symbol} event
|
| 129 |
+
* @param {(...args: any[]) => void} listener
|
| 130 |
+
* @returns {this}
|
| 131 |
+
*/
|
| 132 |
+
off (event, listener) {
|
| 133 |
+
const ret = super.off(event, listener)
|
| 134 |
+
if (event === 'data' || event === 'readable') {
|
| 135 |
+
this[kReading] = (
|
| 136 |
+
this.listenerCount('data') > 0 ||
|
| 137 |
+
this.listenerCount('readable') > 0
|
| 138 |
+
)
|
| 139 |
+
}
|
| 140 |
+
return ret
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
/**
|
| 144 |
+
* @param {string|symbol} event
|
| 145 |
+
* @param {(...args: any[]) => void} listener
|
| 146 |
+
* @returns {this}
|
| 147 |
+
*/
|
| 148 |
+
removeListener (event, listener) {
|
| 149 |
+
return this.off(event, listener)
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
/**
|
| 153 |
+
* @param {Buffer|null} chunk
|
| 154 |
+
* @returns {boolean}
|
| 155 |
+
*/
|
| 156 |
+
push (chunk) {
|
| 157 |
+
if (chunk) {
|
| 158 |
+
this[kBytesRead] += chunk.length
|
| 159 |
+
if (this[kConsume]) {
|
| 160 |
+
consumePush(this[kConsume], chunk)
|
| 161 |
+
return this[kReading] ? super.push(chunk) : true
|
| 162 |
+
}
|
| 163 |
+
}
|
| 164 |
+
|
| 165 |
+
return super.push(chunk)
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
/**
|
| 169 |
+
* Consumes and returns the body as a string.
|
| 170 |
+
*
|
| 171 |
+
* @see https://fetch.spec.whatwg.org/#dom-body-text
|
| 172 |
+
* @returns {Promise<string>}
|
| 173 |
+
*/
|
| 174 |
+
text () {
|
| 175 |
+
return consume(this, 'text')
|
| 176 |
+
}
|
| 177 |
+
|
| 178 |
+
/**
|
| 179 |
+
* Consumes and returns the body as a JavaScript Object.
|
| 180 |
+
*
|
| 181 |
+
* @see https://fetch.spec.whatwg.org/#dom-body-json
|
| 182 |
+
* @returns {Promise<unknown>}
|
| 183 |
+
*/
|
| 184 |
+
json () {
|
| 185 |
+
return consume(this, 'json')
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
/**
|
| 189 |
+
* Consumes and returns the body as a Blob
|
| 190 |
+
*
|
| 191 |
+
* @see https://fetch.spec.whatwg.org/#dom-body-blob
|
| 192 |
+
* @returns {Promise<Blob>}
|
| 193 |
+
*/
|
| 194 |
+
blob () {
|
| 195 |
+
return consume(this, 'blob')
|
| 196 |
+
}
|
| 197 |
+
|
| 198 |
+
/**
|
| 199 |
+
* Consumes and returns the body as an Uint8Array.
|
| 200 |
+
*
|
| 201 |
+
* @see https://fetch.spec.whatwg.org/#dom-body-bytes
|
| 202 |
+
* @returns {Promise<Uint8Array>}
|
| 203 |
+
*/
|
| 204 |
+
bytes () {
|
| 205 |
+
return consume(this, 'bytes')
|
| 206 |
+
}
|
| 207 |
+
|
| 208 |
+
/**
|
| 209 |
+
* Consumes and returns the body as an ArrayBuffer.
|
| 210 |
+
*
|
| 211 |
+
* @see https://fetch.spec.whatwg.org/#dom-body-arraybuffer
|
| 212 |
+
* @returns {Promise<ArrayBuffer>}
|
| 213 |
+
*/
|
| 214 |
+
arrayBuffer () {
|
| 215 |
+
return consume(this, 'arrayBuffer')
|
| 216 |
+
}
|
| 217 |
+
|
| 218 |
+
/**
|
| 219 |
+
* Not implemented
|
| 220 |
+
*
|
| 221 |
+
* @see https://fetch.spec.whatwg.org/#dom-body-formdata
|
| 222 |
+
* @throws {NotSupportedError}
|
| 223 |
+
*/
|
| 224 |
+
async formData () {
|
| 225 |
+
// TODO: Implement.
|
| 226 |
+
throw new NotSupportedError()
|
| 227 |
+
}
|
| 228 |
+
|
| 229 |
+
/**
|
| 230 |
+
* Returns true if the body is not null and the body has been consumed.
|
| 231 |
+
* Otherwise, returns false.
|
| 232 |
+
*
|
| 233 |
+
* @see https://fetch.spec.whatwg.org/#dom-body-bodyused
|
| 234 |
+
* @readonly
|
| 235 |
+
* @returns {boolean}
|
| 236 |
+
*/
|
| 237 |
+
get bodyUsed () {
|
| 238 |
+
return util.isDisturbed(this)
|
| 239 |
+
}
|
| 240 |
+
|
| 241 |
+
/**
|
| 242 |
+
* @see https://fetch.spec.whatwg.org/#dom-body-body
|
| 243 |
+
* @readonly
|
| 244 |
+
* @returns {ReadableStream}
|
| 245 |
+
*/
|
| 246 |
+
get body () {
|
| 247 |
+
if (!this[kBody]) {
|
| 248 |
+
this[kBody] = ReadableStreamFrom(this)
|
| 249 |
+
if (this[kConsume]) {
|
| 250 |
+
// TODO: Is this the best way to force a lock?
|
| 251 |
+
this[kBody].getReader() // Ensure stream is locked.
|
| 252 |
+
assert(this[kBody].locked)
|
| 253 |
+
}
|
| 254 |
+
}
|
| 255 |
+
return this[kBody]
|
| 256 |
+
}
|
| 257 |
+
|
| 258 |
+
/**
|
| 259 |
+
* Dumps the response body by reading `limit` number of bytes.
|
| 260 |
+
* @param {object} opts
|
| 261 |
+
* @param {number} [opts.limit = 131072] Number of bytes to read.
|
| 262 |
+
* @param {AbortSignal} [opts.signal] An AbortSignal to cancel the dump.
|
| 263 |
+
* @returns {Promise<null>}
|
| 264 |
+
*/
|
| 265 |
+
async dump (opts) {
|
| 266 |
+
const signal = opts?.signal
|
| 267 |
+
|
| 268 |
+
if (signal != null && (typeof signal !== 'object' || !('aborted' in signal))) {
|
| 269 |
+
throw new InvalidArgumentError('signal must be an AbortSignal')
|
| 270 |
+
}
|
| 271 |
+
|
| 272 |
+
const limit = opts?.limit && Number.isFinite(opts.limit)
|
| 273 |
+
? opts.limit
|
| 274 |
+
: 128 * 1024
|
| 275 |
+
|
| 276 |
+
signal?.throwIfAborted()
|
| 277 |
+
|
| 278 |
+
if (this._readableState.closeEmitted) {
|
| 279 |
+
return null
|
| 280 |
+
}
|
| 281 |
+
|
| 282 |
+
return await new Promise((resolve, reject) => {
|
| 283 |
+
if (
|
| 284 |
+
(this[kContentLength] && (this[kContentLength] > limit)) ||
|
| 285 |
+
this[kBytesRead] > limit
|
| 286 |
+
) {
|
| 287 |
+
this.destroy(new AbortError())
|
| 288 |
+
}
|
| 289 |
+
|
| 290 |
+
if (signal) {
|
| 291 |
+
const onAbort = () => {
|
| 292 |
+
this.destroy(signal.reason ?? new AbortError())
|
| 293 |
+
}
|
| 294 |
+
signal.addEventListener('abort', onAbort)
|
| 295 |
+
this
|
| 296 |
+
.on('close', function () {
|
| 297 |
+
signal.removeEventListener('abort', onAbort)
|
| 298 |
+
if (signal.aborted) {
|
| 299 |
+
reject(signal.reason ?? new AbortError())
|
| 300 |
+
} else {
|
| 301 |
+
resolve(null)
|
| 302 |
+
}
|
| 303 |
+
})
|
| 304 |
+
} else {
|
| 305 |
+
this.on('close', resolve)
|
| 306 |
+
}
|
| 307 |
+
|
| 308 |
+
this
|
| 309 |
+
.on('error', noop)
|
| 310 |
+
.on('data', () => {
|
| 311 |
+
if (this[kBytesRead] > limit) {
|
| 312 |
+
this.destroy()
|
| 313 |
+
}
|
| 314 |
+
})
|
| 315 |
+
.resume()
|
| 316 |
+
})
|
| 317 |
+
}
|
| 318 |
+
|
| 319 |
+
/**
|
| 320 |
+
* @param {BufferEncoding} encoding
|
| 321 |
+
* @returns {this}
|
| 322 |
+
*/
|
| 323 |
+
setEncoding (encoding) {
|
| 324 |
+
if (Buffer.isEncoding(encoding)) {
|
| 325 |
+
this._readableState.encoding = encoding
|
| 326 |
+
}
|
| 327 |
+
return this
|
| 328 |
+
}
|
| 329 |
+
}
|
| 330 |
+
|
| 331 |
+
/**
|
| 332 |
+
* @see https://streams.spec.whatwg.org/#readablestream-locked
|
| 333 |
+
* @param {BodyReadable} bodyReadable
|
| 334 |
+
* @returns {boolean}
|
| 335 |
+
*/
|
| 336 |
+
function isLocked (bodyReadable) {
|
| 337 |
+
// Consume is an implicit lock.
|
| 338 |
+
return bodyReadable[kBody]?.locked === true || bodyReadable[kConsume] !== null
|
| 339 |
+
}
|
| 340 |
+
|
| 341 |
+
/**
|
| 342 |
+
* @see https://fetch.spec.whatwg.org/#body-unusable
|
| 343 |
+
* @param {BodyReadable} bodyReadable
|
| 344 |
+
* @returns {boolean}
|
| 345 |
+
*/
|
| 346 |
+
function isUnusable (bodyReadable) {
|
| 347 |
+
return util.isDisturbed(bodyReadable) || isLocked(bodyReadable)
|
| 348 |
+
}
|
| 349 |
+
|
| 350 |
+
/**
|
| 351 |
+
* @typedef {'text' | 'json' | 'blob' | 'bytes' | 'arrayBuffer'} ConsumeType
|
| 352 |
+
*/
|
| 353 |
+
|
| 354 |
+
/**
|
| 355 |
+
* @template {ConsumeType} T
|
| 356 |
+
* @typedef {T extends 'text' ? string :
|
| 357 |
+
* T extends 'json' ? unknown :
|
| 358 |
+
* T extends 'blob' ? Blob :
|
| 359 |
+
* T extends 'arrayBuffer' ? ArrayBuffer :
|
| 360 |
+
* T extends 'bytes' ? Uint8Array :
|
| 361 |
+
* never
|
| 362 |
+
* } ConsumeReturnType
|
| 363 |
+
*/
|
| 364 |
+
/**
|
| 365 |
+
* @typedef {object} Consume
|
| 366 |
+
* @property {ConsumeType} type
|
| 367 |
+
* @property {BodyReadable} stream
|
| 368 |
+
* @property {((value?: any) => void)} resolve
|
| 369 |
+
* @property {((err: Error) => void)} reject
|
| 370 |
+
* @property {number} length
|
| 371 |
+
* @property {Buffer[]} body
|
| 372 |
+
*/
|
| 373 |
+
|
| 374 |
+
/**
|
| 375 |
+
* @template {ConsumeType} T
|
| 376 |
+
* @param {BodyReadable} stream
|
| 377 |
+
* @param {T} type
|
| 378 |
+
* @returns {Promise<ConsumeReturnType<T>>}
|
| 379 |
+
*/
|
| 380 |
+
function consume (stream, type) {
|
| 381 |
+
assert(!stream[kConsume])
|
| 382 |
+
|
| 383 |
+
return new Promise((resolve, reject) => {
|
| 384 |
+
if (isUnusable(stream)) {
|
| 385 |
+
const rState = stream._readableState
|
| 386 |
+
if (rState.destroyed && rState.closeEmitted === false) {
|
| 387 |
+
stream
|
| 388 |
+
.on('error', reject)
|
| 389 |
+
.on('close', () => {
|
| 390 |
+
reject(new TypeError('unusable'))
|
| 391 |
+
})
|
| 392 |
+
} else {
|
| 393 |
+
reject(rState.errored ?? new TypeError('unusable'))
|
| 394 |
+
}
|
| 395 |
+
} else {
|
| 396 |
+
queueMicrotask(() => {
|
| 397 |
+
stream[kConsume] = {
|
| 398 |
+
type,
|
| 399 |
+
stream,
|
| 400 |
+
resolve,
|
| 401 |
+
reject,
|
| 402 |
+
length: 0,
|
| 403 |
+
body: []
|
| 404 |
+
}
|
| 405 |
+
|
| 406 |
+
stream
|
| 407 |
+
.on('error', function (err) {
|
| 408 |
+
consumeFinish(this[kConsume], err)
|
| 409 |
+
})
|
| 410 |
+
.on('close', function () {
|
| 411 |
+
if (this[kConsume].body !== null) {
|
| 412 |
+
consumeFinish(this[kConsume], new RequestAbortedError())
|
| 413 |
+
}
|
| 414 |
+
})
|
| 415 |
+
|
| 416 |
+
consumeStart(stream[kConsume])
|
| 417 |
+
})
|
| 418 |
+
}
|
| 419 |
+
})
|
| 420 |
+
}
|
| 421 |
+
|
| 422 |
+
/**
|
| 423 |
+
* @param {Consume} consume
|
| 424 |
+
* @returns {void}
|
| 425 |
+
*/
|
| 426 |
+
function consumeStart (consume) {
|
| 427 |
+
if (consume.body === null) {
|
| 428 |
+
return
|
| 429 |
+
}
|
| 430 |
+
|
| 431 |
+
const { _readableState: state } = consume.stream
|
| 432 |
+
|
| 433 |
+
if (state.bufferIndex) {
|
| 434 |
+
const start = state.bufferIndex
|
| 435 |
+
const end = state.buffer.length
|
| 436 |
+
for (let n = start; n < end; n++) {
|
| 437 |
+
consumePush(consume, state.buffer[n])
|
| 438 |
+
}
|
| 439 |
+
} else {
|
| 440 |
+
for (const chunk of state.buffer) {
|
| 441 |
+
consumePush(consume, chunk)
|
| 442 |
+
}
|
| 443 |
+
}
|
| 444 |
+
|
| 445 |
+
if (state.endEmitted) {
|
| 446 |
+
consumeEnd(this[kConsume], this._readableState.encoding)
|
| 447 |
+
} else {
|
| 448 |
+
consume.stream.on('end', function () {
|
| 449 |
+
consumeEnd(this[kConsume], this._readableState.encoding)
|
| 450 |
+
})
|
| 451 |
+
}
|
| 452 |
+
|
| 453 |
+
consume.stream.resume()
|
| 454 |
+
|
| 455 |
+
while (consume.stream.read() != null) {
|
| 456 |
+
// Loop
|
| 457 |
+
}
|
| 458 |
+
}
|
| 459 |
+
|
| 460 |
+
/**
|
| 461 |
+
* @param {Buffer[]} chunks
|
| 462 |
+
* @param {number} length
|
| 463 |
+
* @param {BufferEncoding} [encoding='utf8']
|
| 464 |
+
* @returns {string}
|
| 465 |
+
*/
|
| 466 |
+
function chunksDecode (chunks, length, encoding) {
|
| 467 |
+
if (chunks.length === 0 || length === 0) {
|
| 468 |
+
return ''
|
| 469 |
+
}
|
| 470 |
+
const buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks, length)
|
| 471 |
+
const bufferLength = buffer.length
|
| 472 |
+
|
| 473 |
+
// Skip BOM.
|
| 474 |
+
const start =
|
| 475 |
+
bufferLength > 2 &&
|
| 476 |
+
buffer[0] === 0xef &&
|
| 477 |
+
buffer[1] === 0xbb &&
|
| 478 |
+
buffer[2] === 0xbf
|
| 479 |
+
? 3
|
| 480 |
+
: 0
|
| 481 |
+
if (!encoding || encoding === 'utf8' || encoding === 'utf-8') {
|
| 482 |
+
return buffer.utf8Slice(start, bufferLength)
|
| 483 |
+
} else {
|
| 484 |
+
return buffer.subarray(start, bufferLength).toString(encoding)
|
| 485 |
+
}
|
| 486 |
+
}
|
| 487 |
+
|
| 488 |
+
/**
|
| 489 |
+
* @param {Buffer[]} chunks
|
| 490 |
+
* @param {number} length
|
| 491 |
+
* @returns {Uint8Array}
|
| 492 |
+
*/
|
| 493 |
+
function chunksConcat (chunks, length) {
|
| 494 |
+
if (chunks.length === 0 || length === 0) {
|
| 495 |
+
return new Uint8Array(0)
|
| 496 |
+
}
|
| 497 |
+
if (chunks.length === 1) {
|
| 498 |
+
// fast-path
|
| 499 |
+
return new Uint8Array(chunks[0])
|
| 500 |
+
}
|
| 501 |
+
const buffer = new Uint8Array(Buffer.allocUnsafeSlow(length).buffer)
|
| 502 |
+
|
| 503 |
+
let offset = 0
|
| 504 |
+
for (let i = 0; i < chunks.length; ++i) {
|
| 505 |
+
const chunk = chunks[i]
|
| 506 |
+
buffer.set(chunk, offset)
|
| 507 |
+
offset += chunk.length
|
| 508 |
+
}
|
| 509 |
+
|
| 510 |
+
return buffer
|
| 511 |
+
}
|
| 512 |
+
|
| 513 |
+
/**
|
| 514 |
+
* @param {Consume} consume
|
| 515 |
+
* @param {BufferEncoding} encoding
|
| 516 |
+
* @returns {void}
|
| 517 |
+
*/
|
| 518 |
+
function consumeEnd (consume, encoding) {
|
| 519 |
+
const { type, body, resolve, stream, length } = consume
|
| 520 |
+
|
| 521 |
+
try {
|
| 522 |
+
if (type === 'text') {
|
| 523 |
+
resolve(chunksDecode(body, length, encoding))
|
| 524 |
+
} else if (type === 'json') {
|
| 525 |
+
resolve(JSON.parse(chunksDecode(body, length, encoding)))
|
| 526 |
+
} else if (type === 'arrayBuffer') {
|
| 527 |
+
resolve(chunksConcat(body, length).buffer)
|
| 528 |
+
} else if (type === 'blob') {
|
| 529 |
+
resolve(new Blob(body, { type: stream[kContentType] }))
|
| 530 |
+
} else if (type === 'bytes') {
|
| 531 |
+
resolve(chunksConcat(body, length))
|
| 532 |
+
}
|
| 533 |
+
|
| 534 |
+
consumeFinish(consume)
|
| 535 |
+
} catch (err) {
|
| 536 |
+
stream.destroy(err)
|
| 537 |
+
}
|
| 538 |
+
}
|
| 539 |
+
|
| 540 |
+
/**
|
| 541 |
+
* @param {Consume} consume
|
| 542 |
+
* @param {Buffer} chunk
|
| 543 |
+
* @returns {void}
|
| 544 |
+
*/
|
| 545 |
+
function consumePush (consume, chunk) {
|
| 546 |
+
consume.length += chunk.length
|
| 547 |
+
consume.body.push(chunk)
|
| 548 |
+
}
|
| 549 |
+
|
| 550 |
+
/**
|
| 551 |
+
* @param {Consume} consume
|
| 552 |
+
* @param {Error} [err]
|
| 553 |
+
* @returns {void}
|
| 554 |
+
*/
|
| 555 |
+
function consumeFinish (consume, err) {
|
| 556 |
+
if (consume.body === null) {
|
| 557 |
+
return
|
| 558 |
+
}
|
| 559 |
+
|
| 560 |
+
if (err) {
|
| 561 |
+
consume.reject(err)
|
| 562 |
+
} else {
|
| 563 |
+
consume.resolve()
|
| 564 |
+
}
|
| 565 |
+
|
| 566 |
+
// Reset the consume object to allow for garbage collection.
|
| 567 |
+
consume.type = null
|
| 568 |
+
consume.stream = null
|
| 569 |
+
consume.resolve = null
|
| 570 |
+
consume.reject = null
|
| 571 |
+
consume.length = 0
|
| 572 |
+
consume.body = null
|
| 573 |
+
}
|
| 574 |
+
|
| 575 |
+
module.exports = {
|
| 576 |
+
Readable: BodyReadable,
|
| 577 |
+
chunksDecode
|
| 578 |
+
}
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/cache/memory-cache-store.js
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'use strict'
|
| 2 |
+
|
| 3 |
+
const { Writable } = require('node:stream')
|
| 4 |
+
const { EventEmitter } = require('node:events')
|
| 5 |
+
const { assertCacheKey, assertCacheValue } = require('../util/cache.js')
|
| 6 |
+
|
| 7 |
+
/**
|
| 8 |
+
* @typedef {import('../../types/cache-interceptor.d.ts').default.CacheKey} CacheKey
|
| 9 |
+
* @typedef {import('../../types/cache-interceptor.d.ts').default.CacheValue} CacheValue
|
| 10 |
+
* @typedef {import('../../types/cache-interceptor.d.ts').default.CacheStore} CacheStore
|
| 11 |
+
* @typedef {import('../../types/cache-interceptor.d.ts').default.GetResult} GetResult
|
| 12 |
+
*/
|
| 13 |
+
|
| 14 |
+
/**
|
| 15 |
+
* @implements {CacheStore}
|
| 16 |
+
* @extends {EventEmitter}
|
| 17 |
+
*/
|
| 18 |
+
class MemoryCacheStore extends EventEmitter {
|
| 19 |
+
#maxCount = 1024
|
| 20 |
+
#maxSize = 104857600 // 100MB
|
| 21 |
+
#maxEntrySize = 5242880 // 5MB
|
| 22 |
+
|
| 23 |
+
#size = 0
|
| 24 |
+
#count = 0
|
| 25 |
+
#entries = new Map()
|
| 26 |
+
#hasEmittedMaxSizeEvent = false
|
| 27 |
+
|
| 28 |
+
/**
|
| 29 |
+
* @param {import('../../types/cache-interceptor.d.ts').default.MemoryCacheStoreOpts | undefined} [opts]
|
| 30 |
+
*/
|
| 31 |
+
constructor (opts) {
|
| 32 |
+
super()
|
| 33 |
+
if (opts) {
|
| 34 |
+
if (typeof opts !== 'object') {
|
| 35 |
+
throw new TypeError('MemoryCacheStore options must be an object')
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
if (opts.maxCount !== undefined) {
|
| 39 |
+
if (
|
| 40 |
+
typeof opts.maxCount !== 'number' ||
|
| 41 |
+
!Number.isInteger(opts.maxCount) ||
|
| 42 |
+
opts.maxCount < 0
|
| 43 |
+
) {
|
| 44 |
+
throw new TypeError('MemoryCacheStore options.maxCount must be a non-negative integer')
|
| 45 |
+
}
|
| 46 |
+
this.#maxCount = opts.maxCount
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
if (opts.maxSize !== undefined) {
|
| 50 |
+
if (
|
| 51 |
+
typeof opts.maxSize !== 'number' ||
|
| 52 |
+
!Number.isInteger(opts.maxSize) ||
|
| 53 |
+
opts.maxSize < 0
|
| 54 |
+
) {
|
| 55 |
+
throw new TypeError('MemoryCacheStore options.maxSize must be a non-negative integer')
|
| 56 |
+
}
|
| 57 |
+
this.#maxSize = opts.maxSize
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
if (opts.maxEntrySize !== undefined) {
|
| 61 |
+
if (
|
| 62 |
+
typeof opts.maxEntrySize !== 'number' ||
|
| 63 |
+
!Number.isInteger(opts.maxEntrySize) ||
|
| 64 |
+
opts.maxEntrySize < 0
|
| 65 |
+
) {
|
| 66 |
+
throw new TypeError('MemoryCacheStore options.maxEntrySize must be a non-negative integer')
|
| 67 |
+
}
|
| 68 |
+
this.#maxEntrySize = opts.maxEntrySize
|
| 69 |
+
}
|
| 70 |
+
}
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
/**
|
| 74 |
+
* Get the current size of the cache in bytes
|
| 75 |
+
* @returns {number} The current size of the cache in bytes
|
| 76 |
+
*/
|
| 77 |
+
get size () {
|
| 78 |
+
return this.#size
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
/**
|
| 82 |
+
* Check if the cache is full (either max size or max count reached)
|
| 83 |
+
* @returns {boolean} True if the cache is full, false otherwise
|
| 84 |
+
*/
|
| 85 |
+
isFull () {
|
| 86 |
+
return this.#size >= this.#maxSize || this.#count >= this.#maxCount
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
/**
|
| 90 |
+
* @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} req
|
| 91 |
+
* @returns {import('../../types/cache-interceptor.d.ts').default.GetResult | undefined}
|
| 92 |
+
*/
|
| 93 |
+
get (key) {
|
| 94 |
+
assertCacheKey(key)
|
| 95 |
+
|
| 96 |
+
const topLevelKey = `${key.origin}:${key.path}`
|
| 97 |
+
|
| 98 |
+
const now = Date.now()
|
| 99 |
+
const entries = this.#entries.get(topLevelKey)
|
| 100 |
+
|
| 101 |
+
const entry = entries ? findEntry(key, entries, now) : null
|
| 102 |
+
|
| 103 |
+
return entry == null
|
| 104 |
+
? undefined
|
| 105 |
+
: {
|
| 106 |
+
statusMessage: entry.statusMessage,
|
| 107 |
+
statusCode: entry.statusCode,
|
| 108 |
+
headers: entry.headers,
|
| 109 |
+
body: entry.body,
|
| 110 |
+
vary: entry.vary ? entry.vary : undefined,
|
| 111 |
+
etag: entry.etag,
|
| 112 |
+
cacheControlDirectives: entry.cacheControlDirectives,
|
| 113 |
+
cachedAt: entry.cachedAt,
|
| 114 |
+
staleAt: entry.staleAt,
|
| 115 |
+
deleteAt: entry.deleteAt
|
| 116 |
+
}
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
/**
|
| 120 |
+
* @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key
|
| 121 |
+
* @param {import('../../types/cache-interceptor.d.ts').default.CacheValue} val
|
| 122 |
+
* @returns {Writable | undefined}
|
| 123 |
+
*/
|
| 124 |
+
createWriteStream (key, val) {
|
| 125 |
+
assertCacheKey(key)
|
| 126 |
+
assertCacheValue(val)
|
| 127 |
+
|
| 128 |
+
const topLevelKey = `${key.origin}:${key.path}`
|
| 129 |
+
|
| 130 |
+
const store = this
|
| 131 |
+
const entry = { ...key, ...val, body: [], size: 0 }
|
| 132 |
+
|
| 133 |
+
return new Writable({
|
| 134 |
+
write (chunk, encoding, callback) {
|
| 135 |
+
if (typeof chunk === 'string') {
|
| 136 |
+
chunk = Buffer.from(chunk, encoding)
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
entry.size += chunk.byteLength
|
| 140 |
+
|
| 141 |
+
if (entry.size >= store.#maxEntrySize) {
|
| 142 |
+
this.destroy()
|
| 143 |
+
} else {
|
| 144 |
+
entry.body.push(chunk)
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
callback(null)
|
| 148 |
+
},
|
| 149 |
+
final (callback) {
|
| 150 |
+
let entries = store.#entries.get(topLevelKey)
|
| 151 |
+
if (!entries) {
|
| 152 |
+
entries = []
|
| 153 |
+
store.#entries.set(topLevelKey, entries)
|
| 154 |
+
}
|
| 155 |
+
const previousEntry = findEntry(key, entries, Date.now())
|
| 156 |
+
if (previousEntry) {
|
| 157 |
+
const index = entries.indexOf(previousEntry)
|
| 158 |
+
entries.splice(index, 1, entry)
|
| 159 |
+
store.#size -= previousEntry.size
|
| 160 |
+
} else {
|
| 161 |
+
entries.push(entry)
|
| 162 |
+
store.#count += 1
|
| 163 |
+
}
|
| 164 |
+
|
| 165 |
+
store.#size += entry.size
|
| 166 |
+
|
| 167 |
+
// Check if cache is full and emit event if needed
|
| 168 |
+
if (store.#size > store.#maxSize || store.#count > store.#maxCount) {
|
| 169 |
+
// Emit maxSizeExceeded event if we haven't already
|
| 170 |
+
if (!store.#hasEmittedMaxSizeEvent) {
|
| 171 |
+
store.emit('maxSizeExceeded', {
|
| 172 |
+
size: store.#size,
|
| 173 |
+
maxSize: store.#maxSize,
|
| 174 |
+
count: store.#count,
|
| 175 |
+
maxCount: store.#maxCount
|
| 176 |
+
})
|
| 177 |
+
store.#hasEmittedMaxSizeEvent = true
|
| 178 |
+
}
|
| 179 |
+
|
| 180 |
+
// Perform eviction
|
| 181 |
+
for (const [key, entries] of store.#entries) {
|
| 182 |
+
for (const entry of entries.splice(0, entries.length / 2)) {
|
| 183 |
+
store.#size -= entry.size
|
| 184 |
+
store.#count -= 1
|
| 185 |
+
}
|
| 186 |
+
if (entries.length === 0) {
|
| 187 |
+
store.#entries.delete(key)
|
| 188 |
+
}
|
| 189 |
+
}
|
| 190 |
+
|
| 191 |
+
// Reset the event flag after eviction
|
| 192 |
+
if (store.#size < store.#maxSize && store.#count < store.#maxCount) {
|
| 193 |
+
store.#hasEmittedMaxSizeEvent = false
|
| 194 |
+
}
|
| 195 |
+
}
|
| 196 |
+
|
| 197 |
+
callback(null)
|
| 198 |
+
}
|
| 199 |
+
})
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
/**
|
| 203 |
+
* @param {CacheKey} key
|
| 204 |
+
*/
|
| 205 |
+
delete (key) {
|
| 206 |
+
if (typeof key !== 'object') {
|
| 207 |
+
throw new TypeError(`expected key to be object, got ${typeof key}`)
|
| 208 |
+
}
|
| 209 |
+
|
| 210 |
+
const topLevelKey = `${key.origin}:${key.path}`
|
| 211 |
+
|
| 212 |
+
for (const entry of this.#entries.get(topLevelKey) ?? []) {
|
| 213 |
+
this.#size -= entry.size
|
| 214 |
+
this.#count -= 1
|
| 215 |
+
}
|
| 216 |
+
this.#entries.delete(topLevelKey)
|
| 217 |
+
}
|
| 218 |
+
}
|
| 219 |
+
|
| 220 |
+
function findEntry (key, entries, now) {
|
| 221 |
+
return entries.find((entry) => (
|
| 222 |
+
entry.deleteAt > now &&
|
| 223 |
+
entry.method === key.method &&
|
| 224 |
+
(entry.vary == null || Object.keys(entry.vary).every(headerName => {
|
| 225 |
+
if (entry.vary[headerName] === null) {
|
| 226 |
+
return key.headers[headerName] === undefined
|
| 227 |
+
}
|
| 228 |
+
|
| 229 |
+
return entry.vary[headerName] === key.headers[headerName]
|
| 230 |
+
}))
|
| 231 |
+
))
|
| 232 |
+
}
|
| 233 |
+
|
| 234 |
+
module.exports = MemoryCacheStore
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/cache/sqlite-cache-store.js
ADDED
|
@@ -0,0 +1,461 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'use strict'
|
| 2 |
+
|
| 3 |
+
const { Writable } = require('node:stream')
|
| 4 |
+
const { assertCacheKey, assertCacheValue } = require('../util/cache.js')
|
| 5 |
+
|
| 6 |
+
let DatabaseSync
|
| 7 |
+
|
| 8 |
+
const VERSION = 3
|
| 9 |
+
|
| 10 |
+
// 2gb
|
| 11 |
+
const MAX_ENTRY_SIZE = 2 * 1000 * 1000 * 1000
|
| 12 |
+
|
| 13 |
+
/**
|
| 14 |
+
* @typedef {import('../../types/cache-interceptor.d.ts').default.CacheStore} CacheStore
|
| 15 |
+
* @implements {CacheStore}
|
| 16 |
+
*
|
| 17 |
+
* @typedef {{
|
| 18 |
+
* id: Readonly<number>,
|
| 19 |
+
* body?: Uint8Array
|
| 20 |
+
* statusCode: number
|
| 21 |
+
* statusMessage: string
|
| 22 |
+
* headers?: string
|
| 23 |
+
* vary?: string
|
| 24 |
+
* etag?: string
|
| 25 |
+
* cacheControlDirectives?: string
|
| 26 |
+
* cachedAt: number
|
| 27 |
+
* staleAt: number
|
| 28 |
+
* deleteAt: number
|
| 29 |
+
* }} SqliteStoreValue
|
| 30 |
+
*/
|
| 31 |
+
module.exports = class SqliteCacheStore {
|
| 32 |
+
#maxEntrySize = MAX_ENTRY_SIZE
|
| 33 |
+
#maxCount = Infinity
|
| 34 |
+
|
| 35 |
+
/**
|
| 36 |
+
* @type {import('node:sqlite').DatabaseSync}
|
| 37 |
+
*/
|
| 38 |
+
#db
|
| 39 |
+
|
| 40 |
+
/**
|
| 41 |
+
* @type {import('node:sqlite').StatementSync}
|
| 42 |
+
*/
|
| 43 |
+
#getValuesQuery
|
| 44 |
+
|
| 45 |
+
/**
|
| 46 |
+
* @type {import('node:sqlite').StatementSync}
|
| 47 |
+
*/
|
| 48 |
+
#updateValueQuery
|
| 49 |
+
|
| 50 |
+
/**
|
| 51 |
+
* @type {import('node:sqlite').StatementSync}
|
| 52 |
+
*/
|
| 53 |
+
#insertValueQuery
|
| 54 |
+
|
| 55 |
+
/**
|
| 56 |
+
* @type {import('node:sqlite').StatementSync}
|
| 57 |
+
*/
|
| 58 |
+
#deleteExpiredValuesQuery
|
| 59 |
+
|
| 60 |
+
/**
|
| 61 |
+
* @type {import('node:sqlite').StatementSync}
|
| 62 |
+
*/
|
| 63 |
+
#deleteByUrlQuery
|
| 64 |
+
|
| 65 |
+
/**
|
| 66 |
+
* @type {import('node:sqlite').StatementSync}
|
| 67 |
+
*/
|
| 68 |
+
#countEntriesQuery
|
| 69 |
+
|
| 70 |
+
/**
|
| 71 |
+
* @type {import('node:sqlite').StatementSync | null}
|
| 72 |
+
*/
|
| 73 |
+
#deleteOldValuesQuery
|
| 74 |
+
|
| 75 |
+
/**
|
| 76 |
+
* @param {import('../../types/cache-interceptor.d.ts').default.SqliteCacheStoreOpts | undefined} opts
|
| 77 |
+
*/
|
| 78 |
+
constructor (opts) {
|
| 79 |
+
if (opts) {
|
| 80 |
+
if (typeof opts !== 'object') {
|
| 81 |
+
throw new TypeError('SqliteCacheStore options must be an object')
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
if (opts.maxEntrySize !== undefined) {
|
| 85 |
+
if (
|
| 86 |
+
typeof opts.maxEntrySize !== 'number' ||
|
| 87 |
+
!Number.isInteger(opts.maxEntrySize) ||
|
| 88 |
+
opts.maxEntrySize < 0
|
| 89 |
+
) {
|
| 90 |
+
throw new TypeError('SqliteCacheStore options.maxEntrySize must be a non-negative integer')
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
if (opts.maxEntrySize > MAX_ENTRY_SIZE) {
|
| 94 |
+
throw new TypeError('SqliteCacheStore options.maxEntrySize must be less than 2gb')
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
this.#maxEntrySize = opts.maxEntrySize
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
if (opts.maxCount !== undefined) {
|
| 101 |
+
if (
|
| 102 |
+
typeof opts.maxCount !== 'number' ||
|
| 103 |
+
!Number.isInteger(opts.maxCount) ||
|
| 104 |
+
opts.maxCount < 0
|
| 105 |
+
) {
|
| 106 |
+
throw new TypeError('SqliteCacheStore options.maxCount must be a non-negative integer')
|
| 107 |
+
}
|
| 108 |
+
this.#maxCount = opts.maxCount
|
| 109 |
+
}
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
if (!DatabaseSync) {
|
| 113 |
+
DatabaseSync = require('node:sqlite').DatabaseSync
|
| 114 |
+
}
|
| 115 |
+
this.#db = new DatabaseSync(opts?.location ?? ':memory:')
|
| 116 |
+
|
| 117 |
+
this.#db.exec(`
|
| 118 |
+
PRAGMA journal_mode = WAL;
|
| 119 |
+
PRAGMA synchronous = NORMAL;
|
| 120 |
+
PRAGMA temp_store = memory;
|
| 121 |
+
PRAGMA optimize;
|
| 122 |
+
|
| 123 |
+
CREATE TABLE IF NOT EXISTS cacheInterceptorV${VERSION} (
|
| 124 |
+
-- Data specific to us
|
| 125 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 126 |
+
url TEXT NOT NULL,
|
| 127 |
+
method TEXT NOT NULL,
|
| 128 |
+
|
| 129 |
+
-- Data returned to the interceptor
|
| 130 |
+
body BUF NULL,
|
| 131 |
+
deleteAt INTEGER NOT NULL,
|
| 132 |
+
statusCode INTEGER NOT NULL,
|
| 133 |
+
statusMessage TEXT NOT NULL,
|
| 134 |
+
headers TEXT NULL,
|
| 135 |
+
cacheControlDirectives TEXT NULL,
|
| 136 |
+
etag TEXT NULL,
|
| 137 |
+
vary TEXT NULL,
|
| 138 |
+
cachedAt INTEGER NOT NULL,
|
| 139 |
+
staleAt INTEGER NOT NULL
|
| 140 |
+
);
|
| 141 |
+
|
| 142 |
+
CREATE INDEX IF NOT EXISTS idx_cacheInterceptorV${VERSION}_getValuesQuery ON cacheInterceptorV${VERSION}(url, method, deleteAt);
|
| 143 |
+
CREATE INDEX IF NOT EXISTS idx_cacheInterceptorV${VERSION}_deleteByUrlQuery ON cacheInterceptorV${VERSION}(deleteAt);
|
| 144 |
+
`)
|
| 145 |
+
|
| 146 |
+
this.#getValuesQuery = this.#db.prepare(`
|
| 147 |
+
SELECT
|
| 148 |
+
id,
|
| 149 |
+
body,
|
| 150 |
+
deleteAt,
|
| 151 |
+
statusCode,
|
| 152 |
+
statusMessage,
|
| 153 |
+
headers,
|
| 154 |
+
etag,
|
| 155 |
+
cacheControlDirectives,
|
| 156 |
+
vary,
|
| 157 |
+
cachedAt,
|
| 158 |
+
staleAt
|
| 159 |
+
FROM cacheInterceptorV${VERSION}
|
| 160 |
+
WHERE
|
| 161 |
+
url = ?
|
| 162 |
+
AND method = ?
|
| 163 |
+
ORDER BY
|
| 164 |
+
deleteAt ASC
|
| 165 |
+
`)
|
| 166 |
+
|
| 167 |
+
this.#updateValueQuery = this.#db.prepare(`
|
| 168 |
+
UPDATE cacheInterceptorV${VERSION} SET
|
| 169 |
+
body = ?,
|
| 170 |
+
deleteAt = ?,
|
| 171 |
+
statusCode = ?,
|
| 172 |
+
statusMessage = ?,
|
| 173 |
+
headers = ?,
|
| 174 |
+
etag = ?,
|
| 175 |
+
cacheControlDirectives = ?,
|
| 176 |
+
cachedAt = ?,
|
| 177 |
+
staleAt = ?
|
| 178 |
+
WHERE
|
| 179 |
+
id = ?
|
| 180 |
+
`)
|
| 181 |
+
|
| 182 |
+
this.#insertValueQuery = this.#db.prepare(`
|
| 183 |
+
INSERT INTO cacheInterceptorV${VERSION} (
|
| 184 |
+
url,
|
| 185 |
+
method,
|
| 186 |
+
body,
|
| 187 |
+
deleteAt,
|
| 188 |
+
statusCode,
|
| 189 |
+
statusMessage,
|
| 190 |
+
headers,
|
| 191 |
+
etag,
|
| 192 |
+
cacheControlDirectives,
|
| 193 |
+
vary,
|
| 194 |
+
cachedAt,
|
| 195 |
+
staleAt
|
| 196 |
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
| 197 |
+
`)
|
| 198 |
+
|
| 199 |
+
this.#deleteByUrlQuery = this.#db.prepare(
|
| 200 |
+
`DELETE FROM cacheInterceptorV${VERSION} WHERE url = ?`
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
this.#countEntriesQuery = this.#db.prepare(
|
| 204 |
+
`SELECT COUNT(*) AS total FROM cacheInterceptorV${VERSION}`
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
this.#deleteExpiredValuesQuery = this.#db.prepare(
|
| 208 |
+
`DELETE FROM cacheInterceptorV${VERSION} WHERE deleteAt <= ?`
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
this.#deleteOldValuesQuery = this.#maxCount === Infinity
|
| 212 |
+
? null
|
| 213 |
+
: this.#db.prepare(`
|
| 214 |
+
DELETE FROM cacheInterceptorV${VERSION}
|
| 215 |
+
WHERE id IN (
|
| 216 |
+
SELECT
|
| 217 |
+
id
|
| 218 |
+
FROM cacheInterceptorV${VERSION}
|
| 219 |
+
ORDER BY cachedAt DESC
|
| 220 |
+
LIMIT ?
|
| 221 |
+
)
|
| 222 |
+
`)
|
| 223 |
+
}
|
| 224 |
+
|
| 225 |
+
close () {
|
| 226 |
+
this.#db.close()
|
| 227 |
+
}
|
| 228 |
+
|
| 229 |
+
/**
|
| 230 |
+
* @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key
|
| 231 |
+
* @returns {(import('../../types/cache-interceptor.d.ts').default.GetResult & { body?: Buffer }) | undefined}
|
| 232 |
+
*/
|
| 233 |
+
get (key) {
|
| 234 |
+
assertCacheKey(key)
|
| 235 |
+
|
| 236 |
+
const value = this.#findValue(key)
|
| 237 |
+
return value
|
| 238 |
+
? {
|
| 239 |
+
body: value.body ? Buffer.from(value.body.buffer, value.body.byteOffset, value.body.byteLength) : undefined,
|
| 240 |
+
statusCode: value.statusCode,
|
| 241 |
+
statusMessage: value.statusMessage,
|
| 242 |
+
headers: value.headers ? JSON.parse(value.headers) : undefined,
|
| 243 |
+
etag: value.etag ? value.etag : undefined,
|
| 244 |
+
vary: value.vary ? JSON.parse(value.vary) : undefined,
|
| 245 |
+
cacheControlDirectives: value.cacheControlDirectives
|
| 246 |
+
? JSON.parse(value.cacheControlDirectives)
|
| 247 |
+
: undefined,
|
| 248 |
+
cachedAt: value.cachedAt,
|
| 249 |
+
staleAt: value.staleAt,
|
| 250 |
+
deleteAt: value.deleteAt
|
| 251 |
+
}
|
| 252 |
+
: undefined
|
| 253 |
+
}
|
| 254 |
+
|
| 255 |
+
/**
|
| 256 |
+
* @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key
|
| 257 |
+
* @param {import('../../types/cache-interceptor.d.ts').default.CacheValue & { body: null | Buffer | Array<Buffer>}} value
|
| 258 |
+
*/
|
| 259 |
+
set (key, value) {
|
| 260 |
+
assertCacheKey(key)
|
| 261 |
+
|
| 262 |
+
const url = this.#makeValueUrl(key)
|
| 263 |
+
const body = Array.isArray(value.body) ? Buffer.concat(value.body) : value.body
|
| 264 |
+
const size = body?.byteLength
|
| 265 |
+
|
| 266 |
+
if (size && size > this.#maxEntrySize) {
|
| 267 |
+
return
|
| 268 |
+
}
|
| 269 |
+
|
| 270 |
+
const existingValue = this.#findValue(key, true)
|
| 271 |
+
if (existingValue) {
|
| 272 |
+
// Updating an existing response, let's overwrite it
|
| 273 |
+
this.#updateValueQuery.run(
|
| 274 |
+
body,
|
| 275 |
+
value.deleteAt,
|
| 276 |
+
value.statusCode,
|
| 277 |
+
value.statusMessage,
|
| 278 |
+
value.headers ? JSON.stringify(value.headers) : null,
|
| 279 |
+
value.etag ? value.etag : null,
|
| 280 |
+
value.cacheControlDirectives ? JSON.stringify(value.cacheControlDirectives) : null,
|
| 281 |
+
value.cachedAt,
|
| 282 |
+
value.staleAt,
|
| 283 |
+
existingValue.id
|
| 284 |
+
)
|
| 285 |
+
} else {
|
| 286 |
+
this.#prune()
|
| 287 |
+
// New response, let's insert it
|
| 288 |
+
this.#insertValueQuery.run(
|
| 289 |
+
url,
|
| 290 |
+
key.method,
|
| 291 |
+
body,
|
| 292 |
+
value.deleteAt,
|
| 293 |
+
value.statusCode,
|
| 294 |
+
value.statusMessage,
|
| 295 |
+
value.headers ? JSON.stringify(value.headers) : null,
|
| 296 |
+
value.etag ? value.etag : null,
|
| 297 |
+
value.cacheControlDirectives ? JSON.stringify(value.cacheControlDirectives) : null,
|
| 298 |
+
value.vary ? JSON.stringify(value.vary) : null,
|
| 299 |
+
value.cachedAt,
|
| 300 |
+
value.staleAt
|
| 301 |
+
)
|
| 302 |
+
}
|
| 303 |
+
}
|
| 304 |
+
|
| 305 |
+
/**
|
| 306 |
+
* @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key
|
| 307 |
+
* @param {import('../../types/cache-interceptor.d.ts').default.CacheValue} value
|
| 308 |
+
* @returns {Writable | undefined}
|
| 309 |
+
*/
|
| 310 |
+
createWriteStream (key, value) {
|
| 311 |
+
assertCacheKey(key)
|
| 312 |
+
assertCacheValue(value)
|
| 313 |
+
|
| 314 |
+
let size = 0
|
| 315 |
+
/**
|
| 316 |
+
* @type {Buffer[] | null}
|
| 317 |
+
*/
|
| 318 |
+
const body = []
|
| 319 |
+
const store = this
|
| 320 |
+
|
| 321 |
+
return new Writable({
|
| 322 |
+
decodeStrings: true,
|
| 323 |
+
write (chunk, encoding, callback) {
|
| 324 |
+
size += chunk.byteLength
|
| 325 |
+
|
| 326 |
+
if (size < store.#maxEntrySize) {
|
| 327 |
+
body.push(chunk)
|
| 328 |
+
} else {
|
| 329 |
+
this.destroy()
|
| 330 |
+
}
|
| 331 |
+
|
| 332 |
+
callback()
|
| 333 |
+
},
|
| 334 |
+
final (callback) {
|
| 335 |
+
store.set(key, { ...value, body })
|
| 336 |
+
callback()
|
| 337 |
+
}
|
| 338 |
+
})
|
| 339 |
+
}
|
| 340 |
+
|
| 341 |
+
/**
|
| 342 |
+
* @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key
|
| 343 |
+
*/
|
| 344 |
+
delete (key) {
|
| 345 |
+
if (typeof key !== 'object') {
|
| 346 |
+
throw new TypeError(`expected key to be object, got ${typeof key}`)
|
| 347 |
+
}
|
| 348 |
+
|
| 349 |
+
this.#deleteByUrlQuery.run(this.#makeValueUrl(key))
|
| 350 |
+
}
|
| 351 |
+
|
| 352 |
+
#prune () {
|
| 353 |
+
if (Number.isFinite(this.#maxCount) && this.size <= this.#maxCount) {
|
| 354 |
+
return 0
|
| 355 |
+
}
|
| 356 |
+
|
| 357 |
+
{
|
| 358 |
+
const removed = this.#deleteExpiredValuesQuery.run(Date.now()).changes
|
| 359 |
+
if (removed) {
|
| 360 |
+
return removed
|
| 361 |
+
}
|
| 362 |
+
}
|
| 363 |
+
|
| 364 |
+
{
|
| 365 |
+
const removed = this.#deleteOldValuesQuery?.run(Math.max(Math.floor(this.#maxCount * 0.1), 1)).changes
|
| 366 |
+
if (removed) {
|
| 367 |
+
return removed
|
| 368 |
+
}
|
| 369 |
+
}
|
| 370 |
+
|
| 371 |
+
return 0
|
| 372 |
+
}
|
| 373 |
+
|
| 374 |
+
/**
|
| 375 |
+
* Counts the number of rows in the cache
|
| 376 |
+
* @returns {Number}
|
| 377 |
+
*/
|
| 378 |
+
get size () {
|
| 379 |
+
const { total } = this.#countEntriesQuery.get()
|
| 380 |
+
return total
|
| 381 |
+
}
|
| 382 |
+
|
| 383 |
+
/**
|
| 384 |
+
* @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key
|
| 385 |
+
* @returns {string}
|
| 386 |
+
*/
|
| 387 |
+
#makeValueUrl (key) {
|
| 388 |
+
return `${key.origin}/${key.path}`
|
| 389 |
+
}
|
| 390 |
+
|
| 391 |
+
/**
|
| 392 |
+
* @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key
|
| 393 |
+
* @param {boolean} [canBeExpired=false]
|
| 394 |
+
* @returns {SqliteStoreValue | undefined}
|
| 395 |
+
*/
|
| 396 |
+
#findValue (key, canBeExpired = false) {
|
| 397 |
+
const url = this.#makeValueUrl(key)
|
| 398 |
+
const { headers, method } = key
|
| 399 |
+
|
| 400 |
+
/**
|
| 401 |
+
* @type {SqliteStoreValue[]}
|
| 402 |
+
*/
|
| 403 |
+
const values = this.#getValuesQuery.all(url, method)
|
| 404 |
+
|
| 405 |
+
if (values.length === 0) {
|
| 406 |
+
return undefined
|
| 407 |
+
}
|
| 408 |
+
|
| 409 |
+
const now = Date.now()
|
| 410 |
+
for (const value of values) {
|
| 411 |
+
if (now >= value.deleteAt && !canBeExpired) {
|
| 412 |
+
return undefined
|
| 413 |
+
}
|
| 414 |
+
|
| 415 |
+
let matches = true
|
| 416 |
+
|
| 417 |
+
if (value.vary) {
|
| 418 |
+
const vary = JSON.parse(value.vary)
|
| 419 |
+
|
| 420 |
+
for (const header in vary) {
|
| 421 |
+
if (!headerValueEquals(headers[header], vary[header])) {
|
| 422 |
+
matches = false
|
| 423 |
+
break
|
| 424 |
+
}
|
| 425 |
+
}
|
| 426 |
+
}
|
| 427 |
+
|
| 428 |
+
if (matches) {
|
| 429 |
+
return value
|
| 430 |
+
}
|
| 431 |
+
}
|
| 432 |
+
|
| 433 |
+
return undefined
|
| 434 |
+
}
|
| 435 |
+
}
|
| 436 |
+
|
| 437 |
+
/**
|
| 438 |
+
* @param {string|string[]|null|undefined} lhs
|
| 439 |
+
* @param {string|string[]|null|undefined} rhs
|
| 440 |
+
* @returns {boolean}
|
| 441 |
+
*/
|
| 442 |
+
function headerValueEquals (lhs, rhs) {
|
| 443 |
+
if (lhs == null && rhs == null) {
|
| 444 |
+
return true
|
| 445 |
+
}
|
| 446 |
+
|
| 447 |
+
if ((lhs == null && rhs != null) ||
|
| 448 |
+
(lhs != null && rhs == null)) {
|
| 449 |
+
return false
|
| 450 |
+
}
|
| 451 |
+
|
| 452 |
+
if (Array.isArray(lhs) && Array.isArray(rhs)) {
|
| 453 |
+
if (lhs.length !== rhs.length) {
|
| 454 |
+
return false
|
| 455 |
+
}
|
| 456 |
+
|
| 457 |
+
return lhs.every((x, i) => x === rhs[i])
|
| 458 |
+
}
|
| 459 |
+
|
| 460 |
+
return lhs === rhs
|
| 461 |
+
}
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/core/connect.js
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'use strict'
|
| 2 |
+
|
| 3 |
+
const net = require('node:net')
|
| 4 |
+
const assert = require('node:assert')
|
| 5 |
+
const util = require('./util')
|
| 6 |
+
const { InvalidArgumentError } = require('./errors')
|
| 7 |
+
|
| 8 |
+
let tls // include tls conditionally since it is not always available
|
| 9 |
+
|
| 10 |
+
// TODO: session re-use does not wait for the first
|
| 11 |
+
// connection to resolve the session and might therefore
|
| 12 |
+
// resolve the same servername multiple times even when
|
| 13 |
+
// re-use is enabled.
|
| 14 |
+
|
| 15 |
+
const SessionCache = class WeakSessionCache {
|
| 16 |
+
constructor (maxCachedSessions) {
|
| 17 |
+
this._maxCachedSessions = maxCachedSessions
|
| 18 |
+
this._sessionCache = new Map()
|
| 19 |
+
this._sessionRegistry = new FinalizationRegistry((key) => {
|
| 20 |
+
if (this._sessionCache.size < this._maxCachedSessions) {
|
| 21 |
+
return
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
const ref = this._sessionCache.get(key)
|
| 25 |
+
if (ref !== undefined && ref.deref() === undefined) {
|
| 26 |
+
this._sessionCache.delete(key)
|
| 27 |
+
}
|
| 28 |
+
})
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
get (sessionKey) {
|
| 32 |
+
const ref = this._sessionCache.get(sessionKey)
|
| 33 |
+
return ref ? ref.deref() : null
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
set (sessionKey, session) {
|
| 37 |
+
if (this._maxCachedSessions === 0) {
|
| 38 |
+
return
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
this._sessionCache.set(sessionKey, new WeakRef(session))
|
| 42 |
+
this._sessionRegistry.register(session, sessionKey)
|
| 43 |
+
}
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
function buildConnector ({ allowH2, maxCachedSessions, socketPath, timeout, session: customSession, ...opts }) {
|
| 47 |
+
if (maxCachedSessions != null && (!Number.isInteger(maxCachedSessions) || maxCachedSessions < 0)) {
|
| 48 |
+
throw new InvalidArgumentError('maxCachedSessions must be a positive integer or zero')
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
const options = { path: socketPath, ...opts }
|
| 52 |
+
const sessionCache = new SessionCache(maxCachedSessions == null ? 100 : maxCachedSessions)
|
| 53 |
+
timeout = timeout == null ? 10e3 : timeout
|
| 54 |
+
allowH2 = allowH2 != null ? allowH2 : false
|
| 55 |
+
return function connect ({ hostname, host, protocol, port, servername, localAddress, httpSocket }, callback) {
|
| 56 |
+
let socket
|
| 57 |
+
if (protocol === 'https:') {
|
| 58 |
+
if (!tls) {
|
| 59 |
+
tls = require('node:tls')
|
| 60 |
+
}
|
| 61 |
+
servername = servername || options.servername || util.getServerName(host) || null
|
| 62 |
+
|
| 63 |
+
const sessionKey = servername || hostname
|
| 64 |
+
assert(sessionKey)
|
| 65 |
+
|
| 66 |
+
const session = customSession || sessionCache.get(sessionKey) || null
|
| 67 |
+
|
| 68 |
+
port = port || 443
|
| 69 |
+
|
| 70 |
+
socket = tls.connect({
|
| 71 |
+
highWaterMark: 16384, // TLS in node can't have bigger HWM anyway...
|
| 72 |
+
...options,
|
| 73 |
+
servername,
|
| 74 |
+
session,
|
| 75 |
+
localAddress,
|
| 76 |
+
ALPNProtocols: allowH2 ? ['http/1.1', 'h2'] : ['http/1.1'],
|
| 77 |
+
socket: httpSocket, // upgrade socket connection
|
| 78 |
+
port,
|
| 79 |
+
host: hostname
|
| 80 |
+
})
|
| 81 |
+
|
| 82 |
+
socket
|
| 83 |
+
.on('session', function (session) {
|
| 84 |
+
// TODO (fix): Can a session become invalid once established? Don't think so?
|
| 85 |
+
sessionCache.set(sessionKey, session)
|
| 86 |
+
})
|
| 87 |
+
} else {
|
| 88 |
+
assert(!httpSocket, 'httpSocket can only be sent on TLS update')
|
| 89 |
+
|
| 90 |
+
port = port || 80
|
| 91 |
+
|
| 92 |
+
socket = net.connect({
|
| 93 |
+
highWaterMark: 64 * 1024, // Same as nodejs fs streams.
|
| 94 |
+
...options,
|
| 95 |
+
localAddress,
|
| 96 |
+
port,
|
| 97 |
+
host: hostname
|
| 98 |
+
})
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
// Set TCP keep alive options on the socket here instead of in connect() for the case of assigning the socket
|
| 102 |
+
if (options.keepAlive == null || options.keepAlive) {
|
| 103 |
+
const keepAliveInitialDelay = options.keepAliveInitialDelay === undefined ? 60e3 : options.keepAliveInitialDelay
|
| 104 |
+
socket.setKeepAlive(true, keepAliveInitialDelay)
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
const clearConnectTimeout = util.setupConnectTimeout(new WeakRef(socket), { timeout, hostname, port })
|
| 108 |
+
|
| 109 |
+
socket
|
| 110 |
+
.setNoDelay(true)
|
| 111 |
+
.once(protocol === 'https:' ? 'secureConnect' : 'connect', function () {
|
| 112 |
+
queueMicrotask(clearConnectTimeout)
|
| 113 |
+
|
| 114 |
+
if (callback) {
|
| 115 |
+
const cb = callback
|
| 116 |
+
callback = null
|
| 117 |
+
cb(null, this)
|
| 118 |
+
}
|
| 119 |
+
})
|
| 120 |
+
.on('error', function (err) {
|
| 121 |
+
queueMicrotask(clearConnectTimeout)
|
| 122 |
+
|
| 123 |
+
if (callback) {
|
| 124 |
+
const cb = callback
|
| 125 |
+
callback = null
|
| 126 |
+
cb(err)
|
| 127 |
+
}
|
| 128 |
+
})
|
| 129 |
+
|
| 130 |
+
return socket
|
| 131 |
+
}
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
module.exports = buildConnector
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/core/constants.js
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'use strict'
|
| 2 |
+
|
| 3 |
+
/**
|
| 4 |
+
* @see https://developer.mozilla.org/docs/Web/HTTP/Headers
|
| 5 |
+
*/
|
| 6 |
+
const wellknownHeaderNames = /** @type {const} */ ([
|
| 7 |
+
'Accept',
|
| 8 |
+
'Accept-Encoding',
|
| 9 |
+
'Accept-Language',
|
| 10 |
+
'Accept-Ranges',
|
| 11 |
+
'Access-Control-Allow-Credentials',
|
| 12 |
+
'Access-Control-Allow-Headers',
|
| 13 |
+
'Access-Control-Allow-Methods',
|
| 14 |
+
'Access-Control-Allow-Origin',
|
| 15 |
+
'Access-Control-Expose-Headers',
|
| 16 |
+
'Access-Control-Max-Age',
|
| 17 |
+
'Access-Control-Request-Headers',
|
| 18 |
+
'Access-Control-Request-Method',
|
| 19 |
+
'Age',
|
| 20 |
+
'Allow',
|
| 21 |
+
'Alt-Svc',
|
| 22 |
+
'Alt-Used',
|
| 23 |
+
'Authorization',
|
| 24 |
+
'Cache-Control',
|
| 25 |
+
'Clear-Site-Data',
|
| 26 |
+
'Connection',
|
| 27 |
+
'Content-Disposition',
|
| 28 |
+
'Content-Encoding',
|
| 29 |
+
'Content-Language',
|
| 30 |
+
'Content-Length',
|
| 31 |
+
'Content-Location',
|
| 32 |
+
'Content-Range',
|
| 33 |
+
'Content-Security-Policy',
|
| 34 |
+
'Content-Security-Policy-Report-Only',
|
| 35 |
+
'Content-Type',
|
| 36 |
+
'Cookie',
|
| 37 |
+
'Cross-Origin-Embedder-Policy',
|
| 38 |
+
'Cross-Origin-Opener-Policy',
|
| 39 |
+
'Cross-Origin-Resource-Policy',
|
| 40 |
+
'Date',
|
| 41 |
+
'Device-Memory',
|
| 42 |
+
'Downlink',
|
| 43 |
+
'ECT',
|
| 44 |
+
'ETag',
|
| 45 |
+
'Expect',
|
| 46 |
+
'Expect-CT',
|
| 47 |
+
'Expires',
|
| 48 |
+
'Forwarded',
|
| 49 |
+
'From',
|
| 50 |
+
'Host',
|
| 51 |
+
'If-Match',
|
| 52 |
+
'If-Modified-Since',
|
| 53 |
+
'If-None-Match',
|
| 54 |
+
'If-Range',
|
| 55 |
+
'If-Unmodified-Since',
|
| 56 |
+
'Keep-Alive',
|
| 57 |
+
'Last-Modified',
|
| 58 |
+
'Link',
|
| 59 |
+
'Location',
|
| 60 |
+
'Max-Forwards',
|
| 61 |
+
'Origin',
|
| 62 |
+
'Permissions-Policy',
|
| 63 |
+
'Pragma',
|
| 64 |
+
'Proxy-Authenticate',
|
| 65 |
+
'Proxy-Authorization',
|
| 66 |
+
'RTT',
|
| 67 |
+
'Range',
|
| 68 |
+
'Referer',
|
| 69 |
+
'Referrer-Policy',
|
| 70 |
+
'Refresh',
|
| 71 |
+
'Retry-After',
|
| 72 |
+
'Sec-WebSocket-Accept',
|
| 73 |
+
'Sec-WebSocket-Extensions',
|
| 74 |
+
'Sec-WebSocket-Key',
|
| 75 |
+
'Sec-WebSocket-Protocol',
|
| 76 |
+
'Sec-WebSocket-Version',
|
| 77 |
+
'Server',
|
| 78 |
+
'Server-Timing',
|
| 79 |
+
'Service-Worker-Allowed',
|
| 80 |
+
'Service-Worker-Navigation-Preload',
|
| 81 |
+
'Set-Cookie',
|
| 82 |
+
'SourceMap',
|
| 83 |
+
'Strict-Transport-Security',
|
| 84 |
+
'Supports-Loading-Mode',
|
| 85 |
+
'TE',
|
| 86 |
+
'Timing-Allow-Origin',
|
| 87 |
+
'Trailer',
|
| 88 |
+
'Transfer-Encoding',
|
| 89 |
+
'Upgrade',
|
| 90 |
+
'Upgrade-Insecure-Requests',
|
| 91 |
+
'User-Agent',
|
| 92 |
+
'Vary',
|
| 93 |
+
'Via',
|
| 94 |
+
'WWW-Authenticate',
|
| 95 |
+
'X-Content-Type-Options',
|
| 96 |
+
'X-DNS-Prefetch-Control',
|
| 97 |
+
'X-Frame-Options',
|
| 98 |
+
'X-Permitted-Cross-Domain-Policies',
|
| 99 |
+
'X-Powered-By',
|
| 100 |
+
'X-Requested-With',
|
| 101 |
+
'X-XSS-Protection'
|
| 102 |
+
])
|
| 103 |
+
|
| 104 |
+
/** @type {Record<typeof wellknownHeaderNames[number]|Lowercase<typeof wellknownHeaderNames[number]>, string>} */
|
| 105 |
+
const headerNameLowerCasedRecord = {}
|
| 106 |
+
|
| 107 |
+
// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`.
|
| 108 |
+
Object.setPrototypeOf(headerNameLowerCasedRecord, null)
|
| 109 |
+
|
| 110 |
+
/**
|
| 111 |
+
* @type {Record<Lowercase<typeof wellknownHeaderNames[number]>, Buffer>}
|
| 112 |
+
*/
|
| 113 |
+
const wellknownHeaderNameBuffers = {}
|
| 114 |
+
|
| 115 |
+
// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`.
|
| 116 |
+
Object.setPrototypeOf(wellknownHeaderNameBuffers, null)
|
| 117 |
+
|
| 118 |
+
/**
|
| 119 |
+
* @param {string} header Lowercased header
|
| 120 |
+
* @returns {Buffer}
|
| 121 |
+
*/
|
| 122 |
+
function getHeaderNameAsBuffer (header) {
|
| 123 |
+
let buffer = wellknownHeaderNameBuffers[header]
|
| 124 |
+
|
| 125 |
+
if (buffer === undefined) {
|
| 126 |
+
buffer = Buffer.from(header)
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
return buffer
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
for (let i = 0; i < wellknownHeaderNames.length; ++i) {
|
| 133 |
+
const key = wellknownHeaderNames[i]
|
| 134 |
+
const lowerCasedKey = key.toLowerCase()
|
| 135 |
+
headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] =
|
| 136 |
+
lowerCasedKey
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
module.exports = {
|
| 140 |
+
wellknownHeaderNames,
|
| 141 |
+
headerNameLowerCasedRecord,
|
| 142 |
+
getHeaderNameAsBuffer
|
| 143 |
+
}
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/core/diagnostics.js
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'use strict'
|
| 2 |
+
|
| 3 |
+
const diagnosticsChannel = require('node:diagnostics_channel')
|
| 4 |
+
const util = require('node:util')
|
| 5 |
+
|
| 6 |
+
const undiciDebugLog = util.debuglog('undici')
|
| 7 |
+
const fetchDebuglog = util.debuglog('fetch')
|
| 8 |
+
const websocketDebuglog = util.debuglog('websocket')
|
| 9 |
+
|
| 10 |
+
const channels = {
|
| 11 |
+
// Client
|
| 12 |
+
beforeConnect: diagnosticsChannel.channel('undici:client:beforeConnect'),
|
| 13 |
+
connected: diagnosticsChannel.channel('undici:client:connected'),
|
| 14 |
+
connectError: diagnosticsChannel.channel('undici:client:connectError'),
|
| 15 |
+
sendHeaders: diagnosticsChannel.channel('undici:client:sendHeaders'),
|
| 16 |
+
// Request
|
| 17 |
+
create: diagnosticsChannel.channel('undici:request:create'),
|
| 18 |
+
bodySent: diagnosticsChannel.channel('undici:request:bodySent'),
|
| 19 |
+
bodyChunkSent: diagnosticsChannel.channel('undici:request:bodyChunkSent'),
|
| 20 |
+
bodyChunkReceived: diagnosticsChannel.channel('undici:request:bodyChunkReceived'),
|
| 21 |
+
headers: diagnosticsChannel.channel('undici:request:headers'),
|
| 22 |
+
trailers: diagnosticsChannel.channel('undici:request:trailers'),
|
| 23 |
+
error: diagnosticsChannel.channel('undici:request:error'),
|
| 24 |
+
// WebSocket
|
| 25 |
+
open: diagnosticsChannel.channel('undici:websocket:open'),
|
| 26 |
+
close: diagnosticsChannel.channel('undici:websocket:close'),
|
| 27 |
+
socketError: diagnosticsChannel.channel('undici:websocket:socket_error'),
|
| 28 |
+
ping: diagnosticsChannel.channel('undici:websocket:ping'),
|
| 29 |
+
pong: diagnosticsChannel.channel('undici:websocket:pong')
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
let isTrackingClientEvents = false
|
| 33 |
+
|
| 34 |
+
function trackClientEvents (debugLog = undiciDebugLog) {
|
| 35 |
+
if (isTrackingClientEvents) {
|
| 36 |
+
return
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
isTrackingClientEvents = true
|
| 40 |
+
|
| 41 |
+
diagnosticsChannel.subscribe('undici:client:beforeConnect',
|
| 42 |
+
evt => {
|
| 43 |
+
const {
|
| 44 |
+
connectParams: { version, protocol, port, host }
|
| 45 |
+
} = evt
|
| 46 |
+
debugLog(
|
| 47 |
+
'connecting to %s%s using %s%s',
|
| 48 |
+
host,
|
| 49 |
+
port ? `:${port}` : '',
|
| 50 |
+
protocol,
|
| 51 |
+
version
|
| 52 |
+
)
|
| 53 |
+
})
|
| 54 |
+
|
| 55 |
+
diagnosticsChannel.subscribe('undici:client:connected',
|
| 56 |
+
evt => {
|
| 57 |
+
const {
|
| 58 |
+
connectParams: { version, protocol, port, host }
|
| 59 |
+
} = evt
|
| 60 |
+
debugLog(
|
| 61 |
+
'connected to %s%s using %s%s',
|
| 62 |
+
host,
|
| 63 |
+
port ? `:${port}` : '',
|
| 64 |
+
protocol,
|
| 65 |
+
version
|
| 66 |
+
)
|
| 67 |
+
})
|
| 68 |
+
|
| 69 |
+
diagnosticsChannel.subscribe('undici:client:connectError',
|
| 70 |
+
evt => {
|
| 71 |
+
const {
|
| 72 |
+
connectParams: { version, protocol, port, host },
|
| 73 |
+
error
|
| 74 |
+
} = evt
|
| 75 |
+
debugLog(
|
| 76 |
+
'connection to %s%s using %s%s errored - %s',
|
| 77 |
+
host,
|
| 78 |
+
port ? `:${port}` : '',
|
| 79 |
+
protocol,
|
| 80 |
+
version,
|
| 81 |
+
error.message
|
| 82 |
+
)
|
| 83 |
+
})
|
| 84 |
+
|
| 85 |
+
diagnosticsChannel.subscribe('undici:client:sendHeaders',
|
| 86 |
+
evt => {
|
| 87 |
+
const {
|
| 88 |
+
request: { method, path, origin }
|
| 89 |
+
} = evt
|
| 90 |
+
debugLog('sending request to %s %s%s', method, origin, path)
|
| 91 |
+
})
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
let isTrackingRequestEvents = false
|
| 95 |
+
|
| 96 |
+
function trackRequestEvents (debugLog = undiciDebugLog) {
|
| 97 |
+
if (isTrackingRequestEvents) {
|
| 98 |
+
return
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
isTrackingRequestEvents = true
|
| 102 |
+
|
| 103 |
+
diagnosticsChannel.subscribe('undici:request:headers',
|
| 104 |
+
evt => {
|
| 105 |
+
const {
|
| 106 |
+
request: { method, path, origin },
|
| 107 |
+
response: { statusCode }
|
| 108 |
+
} = evt
|
| 109 |
+
debugLog(
|
| 110 |
+
'received response to %s %s%s - HTTP %d',
|
| 111 |
+
method,
|
| 112 |
+
origin,
|
| 113 |
+
path,
|
| 114 |
+
statusCode
|
| 115 |
+
)
|
| 116 |
+
})
|
| 117 |
+
|
| 118 |
+
diagnosticsChannel.subscribe('undici:request:trailers',
|
| 119 |
+
evt => {
|
| 120 |
+
const {
|
| 121 |
+
request: { method, path, origin }
|
| 122 |
+
} = evt
|
| 123 |
+
debugLog('trailers received from %s %s%s', method, origin, path)
|
| 124 |
+
})
|
| 125 |
+
|
| 126 |
+
diagnosticsChannel.subscribe('undici:request:error',
|
| 127 |
+
evt => {
|
| 128 |
+
const {
|
| 129 |
+
request: { method, path, origin },
|
| 130 |
+
error
|
| 131 |
+
} = evt
|
| 132 |
+
debugLog(
|
| 133 |
+
'request to %s %s%s errored - %s',
|
| 134 |
+
method,
|
| 135 |
+
origin,
|
| 136 |
+
path,
|
| 137 |
+
error.message
|
| 138 |
+
)
|
| 139 |
+
})
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
let isTrackingWebSocketEvents = false
|
| 143 |
+
|
| 144 |
+
function trackWebSocketEvents (debugLog = websocketDebuglog) {
|
| 145 |
+
if (isTrackingWebSocketEvents) {
|
| 146 |
+
return
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
isTrackingWebSocketEvents = true
|
| 150 |
+
|
| 151 |
+
diagnosticsChannel.subscribe('undici:websocket:open',
|
| 152 |
+
evt => {
|
| 153 |
+
const {
|
| 154 |
+
address: { address, port }
|
| 155 |
+
} = evt
|
| 156 |
+
debugLog('connection opened %s%s', address, port ? `:${port}` : '')
|
| 157 |
+
})
|
| 158 |
+
|
| 159 |
+
diagnosticsChannel.subscribe('undici:websocket:close',
|
| 160 |
+
evt => {
|
| 161 |
+
const { websocket, code, reason } = evt
|
| 162 |
+
debugLog(
|
| 163 |
+
'closed connection to %s - %s %s',
|
| 164 |
+
websocket.url,
|
| 165 |
+
code,
|
| 166 |
+
reason
|
| 167 |
+
)
|
| 168 |
+
})
|
| 169 |
+
|
| 170 |
+
diagnosticsChannel.subscribe('undici:websocket:socket_error',
|
| 171 |
+
err => {
|
| 172 |
+
debugLog('connection errored - %s', err.message)
|
| 173 |
+
})
|
| 174 |
+
|
| 175 |
+
diagnosticsChannel.subscribe('undici:websocket:ping',
|
| 176 |
+
evt => {
|
| 177 |
+
debugLog('ping received')
|
| 178 |
+
})
|
| 179 |
+
|
| 180 |
+
diagnosticsChannel.subscribe('undici:websocket:pong',
|
| 181 |
+
evt => {
|
| 182 |
+
debugLog('pong received')
|
| 183 |
+
})
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
if (undiciDebugLog.enabled || fetchDebuglog.enabled) {
|
| 187 |
+
trackClientEvents(fetchDebuglog.enabled ? fetchDebuglog : undiciDebugLog)
|
| 188 |
+
trackRequestEvents(fetchDebuglog.enabled ? fetchDebuglog : undiciDebugLog)
|
| 189 |
+
}
|
| 190 |
+
|
| 191 |
+
if (websocketDebuglog.enabled) {
|
| 192 |
+
trackClientEvents(undiciDebugLog.enabled ? undiciDebugLog : websocketDebuglog)
|
| 193 |
+
trackWebSocketEvents(websocketDebuglog)
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
module.exports = {
|
| 197 |
+
channels
|
| 198 |
+
}
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/core/errors.js
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'use strict'
|
| 2 |
+
|
| 3 |
+
class UndiciError extends Error {
|
| 4 |
+
constructor (message, options) {
|
| 5 |
+
super(message, options)
|
| 6 |
+
this.name = 'UndiciError'
|
| 7 |
+
this.code = 'UND_ERR'
|
| 8 |
+
}
|
| 9 |
+
}
|
| 10 |
+
|
| 11 |
+
class ConnectTimeoutError extends UndiciError {
|
| 12 |
+
constructor (message) {
|
| 13 |
+
super(message)
|
| 14 |
+
this.name = 'ConnectTimeoutError'
|
| 15 |
+
this.message = message || 'Connect Timeout Error'
|
| 16 |
+
this.code = 'UND_ERR_CONNECT_TIMEOUT'
|
| 17 |
+
}
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
class HeadersTimeoutError extends UndiciError {
|
| 21 |
+
constructor (message) {
|
| 22 |
+
super(message)
|
| 23 |
+
this.name = 'HeadersTimeoutError'
|
| 24 |
+
this.message = message || 'Headers Timeout Error'
|
| 25 |
+
this.code = 'UND_ERR_HEADERS_TIMEOUT'
|
| 26 |
+
}
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
class HeadersOverflowError extends UndiciError {
|
| 30 |
+
constructor (message) {
|
| 31 |
+
super(message)
|
| 32 |
+
this.name = 'HeadersOverflowError'
|
| 33 |
+
this.message = message || 'Headers Overflow Error'
|
| 34 |
+
this.code = 'UND_ERR_HEADERS_OVERFLOW'
|
| 35 |
+
}
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
class BodyTimeoutError extends UndiciError {
|
| 39 |
+
constructor (message) {
|
| 40 |
+
super(message)
|
| 41 |
+
this.name = 'BodyTimeoutError'
|
| 42 |
+
this.message = message || 'Body Timeout Error'
|
| 43 |
+
this.code = 'UND_ERR_BODY_TIMEOUT'
|
| 44 |
+
}
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
class ResponseStatusCodeError extends UndiciError {
|
| 48 |
+
constructor (message, statusCode, headers, body) {
|
| 49 |
+
super(message)
|
| 50 |
+
this.name = 'ResponseStatusCodeError'
|
| 51 |
+
this.message = message || 'Response Status Code Error'
|
| 52 |
+
this.code = 'UND_ERR_RESPONSE_STATUS_CODE'
|
| 53 |
+
this.body = body
|
| 54 |
+
this.status = statusCode
|
| 55 |
+
this.statusCode = statusCode
|
| 56 |
+
this.headers = headers
|
| 57 |
+
}
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
class InvalidArgumentError extends UndiciError {
|
| 61 |
+
constructor (message) {
|
| 62 |
+
super(message)
|
| 63 |
+
this.name = 'InvalidArgumentError'
|
| 64 |
+
this.message = message || 'Invalid Argument Error'
|
| 65 |
+
this.code = 'UND_ERR_INVALID_ARG'
|
| 66 |
+
}
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
class InvalidReturnValueError extends UndiciError {
|
| 70 |
+
constructor (message) {
|
| 71 |
+
super(message)
|
| 72 |
+
this.name = 'InvalidReturnValueError'
|
| 73 |
+
this.message = message || 'Invalid Return Value Error'
|
| 74 |
+
this.code = 'UND_ERR_INVALID_RETURN_VALUE'
|
| 75 |
+
}
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
class AbortError extends UndiciError {
|
| 79 |
+
constructor (message) {
|
| 80 |
+
super(message)
|
| 81 |
+
this.name = 'AbortError'
|
| 82 |
+
this.message = message || 'The operation was aborted'
|
| 83 |
+
}
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
class RequestAbortedError extends AbortError {
|
| 87 |
+
constructor (message) {
|
| 88 |
+
super(message)
|
| 89 |
+
this.name = 'AbortError'
|
| 90 |
+
this.message = message || 'Request aborted'
|
| 91 |
+
this.code = 'UND_ERR_ABORTED'
|
| 92 |
+
}
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
class InformationalError extends UndiciError {
|
| 96 |
+
constructor (message) {
|
| 97 |
+
super(message)
|
| 98 |
+
this.name = 'InformationalError'
|
| 99 |
+
this.message = message || 'Request information'
|
| 100 |
+
this.code = 'UND_ERR_INFO'
|
| 101 |
+
}
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
class RequestContentLengthMismatchError extends UndiciError {
|
| 105 |
+
constructor (message) {
|
| 106 |
+
super(message)
|
| 107 |
+
this.name = 'RequestContentLengthMismatchError'
|
| 108 |
+
this.message = message || 'Request body length does not match content-length header'
|
| 109 |
+
this.code = 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH'
|
| 110 |
+
}
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
class ResponseContentLengthMismatchError extends UndiciError {
|
| 114 |
+
constructor (message) {
|
| 115 |
+
super(message)
|
| 116 |
+
this.name = 'ResponseContentLengthMismatchError'
|
| 117 |
+
this.message = message || 'Response body length does not match content-length header'
|
| 118 |
+
this.code = 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH'
|
| 119 |
+
}
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
class ClientDestroyedError extends UndiciError {
|
| 123 |
+
constructor (message) {
|
| 124 |
+
super(message)
|
| 125 |
+
this.name = 'ClientDestroyedError'
|
| 126 |
+
this.message = message || 'The client is destroyed'
|
| 127 |
+
this.code = 'UND_ERR_DESTROYED'
|
| 128 |
+
}
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
class ClientClosedError extends UndiciError {
|
| 132 |
+
constructor (message) {
|
| 133 |
+
super(message)
|
| 134 |
+
this.name = 'ClientClosedError'
|
| 135 |
+
this.message = message || 'The client is closed'
|
| 136 |
+
this.code = 'UND_ERR_CLOSED'
|
| 137 |
+
}
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
class SocketError extends UndiciError {
|
| 141 |
+
constructor (message, socket) {
|
| 142 |
+
super(message)
|
| 143 |
+
this.name = 'SocketError'
|
| 144 |
+
this.message = message || 'Socket error'
|
| 145 |
+
this.code = 'UND_ERR_SOCKET'
|
| 146 |
+
this.socket = socket
|
| 147 |
+
}
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
class NotSupportedError extends UndiciError {
|
| 151 |
+
constructor (message) {
|
| 152 |
+
super(message)
|
| 153 |
+
this.name = 'NotSupportedError'
|
| 154 |
+
this.message = message || 'Not supported error'
|
| 155 |
+
this.code = 'UND_ERR_NOT_SUPPORTED'
|
| 156 |
+
}
|
| 157 |
+
}
|
| 158 |
+
|
| 159 |
+
class BalancedPoolMissingUpstreamError extends UndiciError {
|
| 160 |
+
constructor (message) {
|
| 161 |
+
super(message)
|
| 162 |
+
this.name = 'MissingUpstreamError'
|
| 163 |
+
this.message = message || 'No upstream has been added to the BalancedPool'
|
| 164 |
+
this.code = 'UND_ERR_BPL_MISSING_UPSTREAM'
|
| 165 |
+
}
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
class HTTPParserError extends Error {
|
| 169 |
+
constructor (message, code, data) {
|
| 170 |
+
super(message)
|
| 171 |
+
this.name = 'HTTPParserError'
|
| 172 |
+
this.code = code ? `HPE_${code}` : undefined
|
| 173 |
+
this.data = data ? data.toString() : undefined
|
| 174 |
+
}
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
class ResponseExceededMaxSizeError extends UndiciError {
|
| 178 |
+
constructor (message) {
|
| 179 |
+
super(message)
|
| 180 |
+
this.name = 'ResponseExceededMaxSizeError'
|
| 181 |
+
this.message = message || 'Response content exceeded max size'
|
| 182 |
+
this.code = 'UND_ERR_RES_EXCEEDED_MAX_SIZE'
|
| 183 |
+
}
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
class RequestRetryError extends UndiciError {
|
| 187 |
+
constructor (message, code, { headers, data }) {
|
| 188 |
+
super(message)
|
| 189 |
+
this.name = 'RequestRetryError'
|
| 190 |
+
this.message = message || 'Request retry error'
|
| 191 |
+
this.code = 'UND_ERR_REQ_RETRY'
|
| 192 |
+
this.statusCode = code
|
| 193 |
+
this.data = data
|
| 194 |
+
this.headers = headers
|
| 195 |
+
}
|
| 196 |
+
}
|
| 197 |
+
|
| 198 |
+
class ResponseError extends UndiciError {
|
| 199 |
+
constructor (message, code, { headers, body }) {
|
| 200 |
+
super(message)
|
| 201 |
+
this.name = 'ResponseError'
|
| 202 |
+
this.message = message || 'Response error'
|
| 203 |
+
this.code = 'UND_ERR_RESPONSE'
|
| 204 |
+
this.statusCode = code
|
| 205 |
+
this.body = body
|
| 206 |
+
this.headers = headers
|
| 207 |
+
}
|
| 208 |
+
}
|
| 209 |
+
|
| 210 |
+
class SecureProxyConnectionError extends UndiciError {
|
| 211 |
+
constructor (cause, message, options = {}) {
|
| 212 |
+
super(message, { cause, ...options })
|
| 213 |
+
this.name = 'SecureProxyConnectionError'
|
| 214 |
+
this.message = message || 'Secure Proxy Connection failed'
|
| 215 |
+
this.code = 'UND_ERR_PRX_TLS'
|
| 216 |
+
this.cause = cause
|
| 217 |
+
}
|
| 218 |
+
}
|
| 219 |
+
|
| 220 |
+
module.exports = {
|
| 221 |
+
AbortError,
|
| 222 |
+
HTTPParserError,
|
| 223 |
+
UndiciError,
|
| 224 |
+
HeadersTimeoutError,
|
| 225 |
+
HeadersOverflowError,
|
| 226 |
+
BodyTimeoutError,
|
| 227 |
+
RequestContentLengthMismatchError,
|
| 228 |
+
ConnectTimeoutError,
|
| 229 |
+
ResponseStatusCodeError,
|
| 230 |
+
InvalidArgumentError,
|
| 231 |
+
InvalidReturnValueError,
|
| 232 |
+
RequestAbortedError,
|
| 233 |
+
ClientDestroyedError,
|
| 234 |
+
ClientClosedError,
|
| 235 |
+
InformationalError,
|
| 236 |
+
SocketError,
|
| 237 |
+
NotSupportedError,
|
| 238 |
+
ResponseContentLengthMismatchError,
|
| 239 |
+
BalancedPoolMissingUpstreamError,
|
| 240 |
+
ResponseExceededMaxSizeError,
|
| 241 |
+
RequestRetryError,
|
| 242 |
+
ResponseError,
|
| 243 |
+
SecureProxyConnectionError
|
| 244 |
+
}
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/core/request.js
ADDED
|
@@ -0,0 +1,408 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'use strict'
|
| 2 |
+
|
| 3 |
+
const {
|
| 4 |
+
InvalidArgumentError,
|
| 5 |
+
NotSupportedError
|
| 6 |
+
} = require('./errors')
|
| 7 |
+
const assert = require('node:assert')
|
| 8 |
+
const {
|
| 9 |
+
isValidHTTPToken,
|
| 10 |
+
isValidHeaderValue,
|
| 11 |
+
isStream,
|
| 12 |
+
destroy,
|
| 13 |
+
isBuffer,
|
| 14 |
+
isFormDataLike,
|
| 15 |
+
isIterable,
|
| 16 |
+
isBlobLike,
|
| 17 |
+
serializePathWithQuery,
|
| 18 |
+
assertRequestHandler,
|
| 19 |
+
getServerName,
|
| 20 |
+
normalizedMethodRecords
|
| 21 |
+
} = require('./util')
|
| 22 |
+
const { channels } = require('./diagnostics.js')
|
| 23 |
+
const { headerNameLowerCasedRecord } = require('./constants')
|
| 24 |
+
|
| 25 |
+
// Verifies that a given path is valid does not contain control chars \x00 to \x20
|
| 26 |
+
const invalidPathRegex = /[^\u0021-\u00ff]/
|
| 27 |
+
|
| 28 |
+
const kHandler = Symbol('handler')
|
| 29 |
+
|
| 30 |
+
class Request {
|
| 31 |
+
constructor (origin, {
|
| 32 |
+
path,
|
| 33 |
+
method,
|
| 34 |
+
body,
|
| 35 |
+
headers,
|
| 36 |
+
query,
|
| 37 |
+
idempotent,
|
| 38 |
+
blocking,
|
| 39 |
+
upgrade,
|
| 40 |
+
headersTimeout,
|
| 41 |
+
bodyTimeout,
|
| 42 |
+
reset,
|
| 43 |
+
expectContinue,
|
| 44 |
+
servername,
|
| 45 |
+
throwOnError,
|
| 46 |
+
maxRedirections
|
| 47 |
+
}, handler) {
|
| 48 |
+
if (typeof path !== 'string') {
|
| 49 |
+
throw new InvalidArgumentError('path must be a string')
|
| 50 |
+
} else if (
|
| 51 |
+
path[0] !== '/' &&
|
| 52 |
+
!(path.startsWith('http://') || path.startsWith('https://')) &&
|
| 53 |
+
method !== 'CONNECT'
|
| 54 |
+
) {
|
| 55 |
+
throw new InvalidArgumentError('path must be an absolute URL or start with a slash')
|
| 56 |
+
} else if (invalidPathRegex.test(path)) {
|
| 57 |
+
throw new InvalidArgumentError('invalid request path')
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
if (typeof method !== 'string') {
|
| 61 |
+
throw new InvalidArgumentError('method must be a string')
|
| 62 |
+
} else if (normalizedMethodRecords[method] === undefined && !isValidHTTPToken(method)) {
|
| 63 |
+
throw new InvalidArgumentError('invalid request method')
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
if (upgrade && typeof upgrade !== 'string') {
|
| 67 |
+
throw new InvalidArgumentError('upgrade must be a string')
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) {
|
| 71 |
+
throw new InvalidArgumentError('invalid headersTimeout')
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) {
|
| 75 |
+
throw new InvalidArgumentError('invalid bodyTimeout')
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
if (reset != null && typeof reset !== 'boolean') {
|
| 79 |
+
throw new InvalidArgumentError('invalid reset')
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
if (expectContinue != null && typeof expectContinue !== 'boolean') {
|
| 83 |
+
throw new InvalidArgumentError('invalid expectContinue')
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
if (throwOnError != null) {
|
| 87 |
+
throw new InvalidArgumentError('invalid throwOnError')
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
if (maxRedirections != null && maxRedirections !== 0) {
|
| 91 |
+
throw new InvalidArgumentError('maxRedirections is not supported, use the redirect interceptor')
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
this.headersTimeout = headersTimeout
|
| 95 |
+
|
| 96 |
+
this.bodyTimeout = bodyTimeout
|
| 97 |
+
|
| 98 |
+
this.method = method
|
| 99 |
+
|
| 100 |
+
this.abort = null
|
| 101 |
+
|
| 102 |
+
if (body == null) {
|
| 103 |
+
this.body = null
|
| 104 |
+
} else if (isStream(body)) {
|
| 105 |
+
this.body = body
|
| 106 |
+
|
| 107 |
+
const rState = this.body._readableState
|
| 108 |
+
if (!rState || !rState.autoDestroy) {
|
| 109 |
+
this.endHandler = function autoDestroy () {
|
| 110 |
+
destroy(this)
|
| 111 |
+
}
|
| 112 |
+
this.body.on('end', this.endHandler)
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
this.errorHandler = err => {
|
| 116 |
+
if (this.abort) {
|
| 117 |
+
this.abort(err)
|
| 118 |
+
} else {
|
| 119 |
+
this.error = err
|
| 120 |
+
}
|
| 121 |
+
}
|
| 122 |
+
this.body.on('error', this.errorHandler)
|
| 123 |
+
} else if (isBuffer(body)) {
|
| 124 |
+
this.body = body.byteLength ? body : null
|
| 125 |
+
} else if (ArrayBuffer.isView(body)) {
|
| 126 |
+
this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null
|
| 127 |
+
} else if (body instanceof ArrayBuffer) {
|
| 128 |
+
this.body = body.byteLength ? Buffer.from(body) : null
|
| 129 |
+
} else if (typeof body === 'string') {
|
| 130 |
+
this.body = body.length ? Buffer.from(body) : null
|
| 131 |
+
} else if (isFormDataLike(body) || isIterable(body) || isBlobLike(body)) {
|
| 132 |
+
this.body = body
|
| 133 |
+
} else {
|
| 134 |
+
throw new InvalidArgumentError('body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable')
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
this.completed = false
|
| 138 |
+
this.aborted = false
|
| 139 |
+
|
| 140 |
+
this.upgrade = upgrade || null
|
| 141 |
+
|
| 142 |
+
this.path = query ? serializePathWithQuery(path, query) : path
|
| 143 |
+
|
| 144 |
+
this.origin = origin
|
| 145 |
+
|
| 146 |
+
this.idempotent = idempotent == null
|
| 147 |
+
? method === 'HEAD' || method === 'GET'
|
| 148 |
+
: idempotent
|
| 149 |
+
|
| 150 |
+
this.blocking = blocking ?? this.method !== 'HEAD'
|
| 151 |
+
|
| 152 |
+
this.reset = reset == null ? null : reset
|
| 153 |
+
|
| 154 |
+
this.host = null
|
| 155 |
+
|
| 156 |
+
this.contentLength = null
|
| 157 |
+
|
| 158 |
+
this.contentType = null
|
| 159 |
+
|
| 160 |
+
this.headers = []
|
| 161 |
+
|
| 162 |
+
// Only for H2
|
| 163 |
+
this.expectContinue = expectContinue != null ? expectContinue : false
|
| 164 |
+
|
| 165 |
+
if (Array.isArray(headers)) {
|
| 166 |
+
if (headers.length % 2 !== 0) {
|
| 167 |
+
throw new InvalidArgumentError('headers array must be even')
|
| 168 |
+
}
|
| 169 |
+
for (let i = 0; i < headers.length; i += 2) {
|
| 170 |
+
processHeader(this, headers[i], headers[i + 1])
|
| 171 |
+
}
|
| 172 |
+
} else if (headers && typeof headers === 'object') {
|
| 173 |
+
if (headers[Symbol.iterator]) {
|
| 174 |
+
for (const header of headers) {
|
| 175 |
+
if (!Array.isArray(header) || header.length !== 2) {
|
| 176 |
+
throw new InvalidArgumentError('headers must be in key-value pair format')
|
| 177 |
+
}
|
| 178 |
+
processHeader(this, header[0], header[1])
|
| 179 |
+
}
|
| 180 |
+
} else {
|
| 181 |
+
const keys = Object.keys(headers)
|
| 182 |
+
for (let i = 0; i < keys.length; ++i) {
|
| 183 |
+
processHeader(this, keys[i], headers[keys[i]])
|
| 184 |
+
}
|
| 185 |
+
}
|
| 186 |
+
} else if (headers != null) {
|
| 187 |
+
throw new InvalidArgumentError('headers must be an object or an array')
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
assertRequestHandler(handler, method, upgrade)
|
| 191 |
+
|
| 192 |
+
this.servername = servername || getServerName(this.host) || null
|
| 193 |
+
|
| 194 |
+
this[kHandler] = handler
|
| 195 |
+
|
| 196 |
+
if (channels.create.hasSubscribers) {
|
| 197 |
+
channels.create.publish({ request: this })
|
| 198 |
+
}
|
| 199 |
+
}
|
| 200 |
+
|
| 201 |
+
onBodySent (chunk) {
|
| 202 |
+
if (channels.bodyChunkSent.hasSubscribers) {
|
| 203 |
+
channels.bodyChunkSent.publish({ request: this, chunk })
|
| 204 |
+
}
|
| 205 |
+
if (this[kHandler].onBodySent) {
|
| 206 |
+
try {
|
| 207 |
+
return this[kHandler].onBodySent(chunk)
|
| 208 |
+
} catch (err) {
|
| 209 |
+
this.abort(err)
|
| 210 |
+
}
|
| 211 |
+
}
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
onRequestSent () {
|
| 215 |
+
if (channels.bodySent.hasSubscribers) {
|
| 216 |
+
channels.bodySent.publish({ request: this })
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
if (this[kHandler].onRequestSent) {
|
| 220 |
+
try {
|
| 221 |
+
return this[kHandler].onRequestSent()
|
| 222 |
+
} catch (err) {
|
| 223 |
+
this.abort(err)
|
| 224 |
+
}
|
| 225 |
+
}
|
| 226 |
+
}
|
| 227 |
+
|
| 228 |
+
onConnect (abort) {
|
| 229 |
+
assert(!this.aborted)
|
| 230 |
+
assert(!this.completed)
|
| 231 |
+
|
| 232 |
+
if (this.error) {
|
| 233 |
+
abort(this.error)
|
| 234 |
+
} else {
|
| 235 |
+
this.abort = abort
|
| 236 |
+
return this[kHandler].onConnect(abort)
|
| 237 |
+
}
|
| 238 |
+
}
|
| 239 |
+
|
| 240 |
+
onResponseStarted () {
|
| 241 |
+
return this[kHandler].onResponseStarted?.()
|
| 242 |
+
}
|
| 243 |
+
|
| 244 |
+
onHeaders (statusCode, headers, resume, statusText) {
|
| 245 |
+
assert(!this.aborted)
|
| 246 |
+
assert(!this.completed)
|
| 247 |
+
|
| 248 |
+
if (channels.headers.hasSubscribers) {
|
| 249 |
+
channels.headers.publish({ request: this, response: { statusCode, headers, statusText } })
|
| 250 |
+
}
|
| 251 |
+
|
| 252 |
+
try {
|
| 253 |
+
return this[kHandler].onHeaders(statusCode, headers, resume, statusText)
|
| 254 |
+
} catch (err) {
|
| 255 |
+
this.abort(err)
|
| 256 |
+
}
|
| 257 |
+
}
|
| 258 |
+
|
| 259 |
+
onData (chunk) {
|
| 260 |
+
assert(!this.aborted)
|
| 261 |
+
assert(!this.completed)
|
| 262 |
+
|
| 263 |
+
if (channels.bodyChunkReceived.hasSubscribers) {
|
| 264 |
+
channels.bodyChunkReceived.publish({ request: this, chunk })
|
| 265 |
+
}
|
| 266 |
+
try {
|
| 267 |
+
return this[kHandler].onData(chunk)
|
| 268 |
+
} catch (err) {
|
| 269 |
+
this.abort(err)
|
| 270 |
+
return false
|
| 271 |
+
}
|
| 272 |
+
}
|
| 273 |
+
|
| 274 |
+
onUpgrade (statusCode, headers, socket) {
|
| 275 |
+
assert(!this.aborted)
|
| 276 |
+
assert(!this.completed)
|
| 277 |
+
|
| 278 |
+
return this[kHandler].onUpgrade(statusCode, headers, socket)
|
| 279 |
+
}
|
| 280 |
+
|
| 281 |
+
onComplete (trailers) {
|
| 282 |
+
this.onFinally()
|
| 283 |
+
|
| 284 |
+
assert(!this.aborted)
|
| 285 |
+
assert(!this.completed)
|
| 286 |
+
|
| 287 |
+
this.completed = true
|
| 288 |
+
if (channels.trailers.hasSubscribers) {
|
| 289 |
+
channels.trailers.publish({ request: this, trailers })
|
| 290 |
+
}
|
| 291 |
+
|
| 292 |
+
try {
|
| 293 |
+
return this[kHandler].onComplete(trailers)
|
| 294 |
+
} catch (err) {
|
| 295 |
+
// TODO (fix): This might be a bad idea?
|
| 296 |
+
this.onError(err)
|
| 297 |
+
}
|
| 298 |
+
}
|
| 299 |
+
|
| 300 |
+
onError (error) {
|
| 301 |
+
this.onFinally()
|
| 302 |
+
|
| 303 |
+
if (channels.error.hasSubscribers) {
|
| 304 |
+
channels.error.publish({ request: this, error })
|
| 305 |
+
}
|
| 306 |
+
|
| 307 |
+
if (this.aborted) {
|
| 308 |
+
return
|
| 309 |
+
}
|
| 310 |
+
this.aborted = true
|
| 311 |
+
|
| 312 |
+
return this[kHandler].onError(error)
|
| 313 |
+
}
|
| 314 |
+
|
| 315 |
+
onFinally () {
|
| 316 |
+
if (this.errorHandler) {
|
| 317 |
+
this.body.off('error', this.errorHandler)
|
| 318 |
+
this.errorHandler = null
|
| 319 |
+
}
|
| 320 |
+
|
| 321 |
+
if (this.endHandler) {
|
| 322 |
+
this.body.off('end', this.endHandler)
|
| 323 |
+
this.endHandler = null
|
| 324 |
+
}
|
| 325 |
+
}
|
| 326 |
+
|
| 327 |
+
addHeader (key, value) {
|
| 328 |
+
processHeader(this, key, value)
|
| 329 |
+
return this
|
| 330 |
+
}
|
| 331 |
+
}
|
| 332 |
+
|
| 333 |
+
function processHeader (request, key, val) {
|
| 334 |
+
if (val && (typeof val === 'object' && !Array.isArray(val))) {
|
| 335 |
+
throw new InvalidArgumentError(`invalid ${key} header`)
|
| 336 |
+
} else if (val === undefined) {
|
| 337 |
+
return
|
| 338 |
+
}
|
| 339 |
+
|
| 340 |
+
let headerName = headerNameLowerCasedRecord[key]
|
| 341 |
+
|
| 342 |
+
if (headerName === undefined) {
|
| 343 |
+
headerName = key.toLowerCase()
|
| 344 |
+
if (headerNameLowerCasedRecord[headerName] === undefined && !isValidHTTPToken(headerName)) {
|
| 345 |
+
throw new InvalidArgumentError('invalid header key')
|
| 346 |
+
}
|
| 347 |
+
}
|
| 348 |
+
|
| 349 |
+
if (Array.isArray(val)) {
|
| 350 |
+
const arr = []
|
| 351 |
+
for (let i = 0; i < val.length; i++) {
|
| 352 |
+
if (typeof val[i] === 'string') {
|
| 353 |
+
if (!isValidHeaderValue(val[i])) {
|
| 354 |
+
throw new InvalidArgumentError(`invalid ${key} header`)
|
| 355 |
+
}
|
| 356 |
+
arr.push(val[i])
|
| 357 |
+
} else if (val[i] === null) {
|
| 358 |
+
arr.push('')
|
| 359 |
+
} else if (typeof val[i] === 'object') {
|
| 360 |
+
throw new InvalidArgumentError(`invalid ${key} header`)
|
| 361 |
+
} else {
|
| 362 |
+
arr.push(`${val[i]}`)
|
| 363 |
+
}
|
| 364 |
+
}
|
| 365 |
+
val = arr
|
| 366 |
+
} else if (typeof val === 'string') {
|
| 367 |
+
if (!isValidHeaderValue(val)) {
|
| 368 |
+
throw new InvalidArgumentError(`invalid ${key} header`)
|
| 369 |
+
}
|
| 370 |
+
} else if (val === null) {
|
| 371 |
+
val = ''
|
| 372 |
+
} else {
|
| 373 |
+
val = `${val}`
|
| 374 |
+
}
|
| 375 |
+
|
| 376 |
+
if (request.host === null && headerName === 'host') {
|
| 377 |
+
if (typeof val !== 'string') {
|
| 378 |
+
throw new InvalidArgumentError('invalid host header')
|
| 379 |
+
}
|
| 380 |
+
// Consumed by Client
|
| 381 |
+
request.host = val
|
| 382 |
+
} else if (request.contentLength === null && headerName === 'content-length') {
|
| 383 |
+
request.contentLength = parseInt(val, 10)
|
| 384 |
+
if (!Number.isFinite(request.contentLength)) {
|
| 385 |
+
throw new InvalidArgumentError('invalid content-length header')
|
| 386 |
+
}
|
| 387 |
+
} else if (request.contentType === null && headerName === 'content-type') {
|
| 388 |
+
request.contentType = val
|
| 389 |
+
request.headers.push(key, val)
|
| 390 |
+
} else if (headerName === 'transfer-encoding' || headerName === 'keep-alive' || headerName === 'upgrade') {
|
| 391 |
+
throw new InvalidArgumentError(`invalid ${headerName} header`)
|
| 392 |
+
} else if (headerName === 'connection') {
|
| 393 |
+
const value = typeof val === 'string' ? val.toLowerCase() : null
|
| 394 |
+
if (value !== 'close' && value !== 'keep-alive') {
|
| 395 |
+
throw new InvalidArgumentError('invalid connection header')
|
| 396 |
+
}
|
| 397 |
+
|
| 398 |
+
if (value === 'close') {
|
| 399 |
+
request.reset = true
|
| 400 |
+
}
|
| 401 |
+
} else if (headerName === 'expect') {
|
| 402 |
+
throw new NotSupportedError('expect header not supported')
|
| 403 |
+
} else {
|
| 404 |
+
request.headers.push(key, val)
|
| 405 |
+
}
|
| 406 |
+
}
|
| 407 |
+
|
| 408 |
+
module.exports = Request
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/core/symbols.js
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'use strict'
|
| 2 |
+
|
| 3 |
+
module.exports = {
|
| 4 |
+
kClose: Symbol('close'),
|
| 5 |
+
kDestroy: Symbol('destroy'),
|
| 6 |
+
kDispatch: Symbol('dispatch'),
|
| 7 |
+
kUrl: Symbol('url'),
|
| 8 |
+
kWriting: Symbol('writing'),
|
| 9 |
+
kResuming: Symbol('resuming'),
|
| 10 |
+
kQueue: Symbol('queue'),
|
| 11 |
+
kConnect: Symbol('connect'),
|
| 12 |
+
kConnecting: Symbol('connecting'),
|
| 13 |
+
kKeepAliveDefaultTimeout: Symbol('default keep alive timeout'),
|
| 14 |
+
kKeepAliveMaxTimeout: Symbol('max keep alive timeout'),
|
| 15 |
+
kKeepAliveTimeoutThreshold: Symbol('keep alive timeout threshold'),
|
| 16 |
+
kKeepAliveTimeoutValue: Symbol('keep alive timeout'),
|
| 17 |
+
kKeepAlive: Symbol('keep alive'),
|
| 18 |
+
kHeadersTimeout: Symbol('headers timeout'),
|
| 19 |
+
kBodyTimeout: Symbol('body timeout'),
|
| 20 |
+
kServerName: Symbol('server name'),
|
| 21 |
+
kLocalAddress: Symbol('local address'),
|
| 22 |
+
kHost: Symbol('host'),
|
| 23 |
+
kNoRef: Symbol('no ref'),
|
| 24 |
+
kBodyUsed: Symbol('used'),
|
| 25 |
+
kBody: Symbol('abstracted request body'),
|
| 26 |
+
kRunning: Symbol('running'),
|
| 27 |
+
kBlocking: Symbol('blocking'),
|
| 28 |
+
kPending: Symbol('pending'),
|
| 29 |
+
kSize: Symbol('size'),
|
| 30 |
+
kBusy: Symbol('busy'),
|
| 31 |
+
kQueued: Symbol('queued'),
|
| 32 |
+
kFree: Symbol('free'),
|
| 33 |
+
kConnected: Symbol('connected'),
|
| 34 |
+
kClosed: Symbol('closed'),
|
| 35 |
+
kNeedDrain: Symbol('need drain'),
|
| 36 |
+
kReset: Symbol('reset'),
|
| 37 |
+
kDestroyed: Symbol.for('nodejs.stream.destroyed'),
|
| 38 |
+
kResume: Symbol('resume'),
|
| 39 |
+
kOnError: Symbol('on error'),
|
| 40 |
+
kMaxHeadersSize: Symbol('max headers size'),
|
| 41 |
+
kRunningIdx: Symbol('running index'),
|
| 42 |
+
kPendingIdx: Symbol('pending index'),
|
| 43 |
+
kError: Symbol('error'),
|
| 44 |
+
kClients: Symbol('clients'),
|
| 45 |
+
kClient: Symbol('client'),
|
| 46 |
+
kParser: Symbol('parser'),
|
| 47 |
+
kOnDestroyed: Symbol('destroy callbacks'),
|
| 48 |
+
kPipelining: Symbol('pipelining'),
|
| 49 |
+
kSocket: Symbol('socket'),
|
| 50 |
+
kHostHeader: Symbol('host header'),
|
| 51 |
+
kConnector: Symbol('connector'),
|
| 52 |
+
kStrictContentLength: Symbol('strict content length'),
|
| 53 |
+
kMaxRedirections: Symbol('maxRedirections'),
|
| 54 |
+
kMaxRequests: Symbol('maxRequestsPerClient'),
|
| 55 |
+
kProxy: Symbol('proxy agent options'),
|
| 56 |
+
kCounter: Symbol('socket request counter'),
|
| 57 |
+
kMaxResponseSize: Symbol('max response size'),
|
| 58 |
+
kHTTP2Session: Symbol('http2Session'),
|
| 59 |
+
kHTTP2SessionState: Symbol('http2Session state'),
|
| 60 |
+
kRetryHandlerDefaultRetry: Symbol('retry agent default retry'),
|
| 61 |
+
kConstruct: Symbol('constructable'),
|
| 62 |
+
kListeners: Symbol('listeners'),
|
| 63 |
+
kHTTPContext: Symbol('http context'),
|
| 64 |
+
kMaxConcurrentStreams: Symbol('max concurrent streams'),
|
| 65 |
+
kNoProxyAgent: Symbol('no proxy agent'),
|
| 66 |
+
kHttpProxyAgent: Symbol('http proxy agent'),
|
| 67 |
+
kHttpsProxyAgent: Symbol('https proxy agent')
|
| 68 |
+
}
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/core/tree.js
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 10 |
+
value = null
|
| 11 |
+
/** @type {null | TstNode} */
|
| 12 |
+
left = null
|
| 13 |
+
/** @type {null | TstNode} */
|
| 14 |
+
middle = null
|
| 15 |
+
/** @type {null | TstNode} */
|
| 16 |
+
right = null
|
| 17 |
+
/** @type {number} */
|
| 18 |
+
code
|
| 19 |
+
/**
|
| 20 |
+
* @param {string} key
|
| 21 |
+
* @param {any} value
|
| 22 |
+
* @param {number} index
|
| 23 |
+
*/
|
| 24 |
+
constructor (key, value, index) {
|
| 25 |
+
if (index === undefined || index >= key.length) {
|
| 26 |
+
throw new TypeError('Unreachable')
|
| 27 |
+
}
|
| 28 |
+
const code = this.code = key.charCodeAt(index)
|
| 29 |
+
// check code is ascii string
|
| 30 |
+
if (code > 0x7F) {
|
| 31 |
+
throw new TypeError('key must be ascii string')
|
| 32 |
+
}
|
| 33 |
+
if (key.length !== ++index) {
|
| 34 |
+
this.middle = new TstNode(key, value, index)
|
| 35 |
+
} else {
|
| 36 |
+
this.value = value
|
| 37 |
+
}
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
/**
|
| 41 |
+
* @param {string} key
|
| 42 |
+
* @param {any} value
|
| 43 |
+
* @returns {void}
|
| 44 |
+
*/
|
| 45 |
+
add (key, value) {
|
| 46 |
+
const length = key.length
|
| 47 |
+
if (length === 0) {
|
| 48 |
+
throw new TypeError('Unreachable')
|
| 49 |
+
}
|
| 50 |
+
let index = 0
|
| 51 |
+
/**
|
| 52 |
+
* @type {TstNode}
|
| 53 |
+
*/
|
| 54 |
+
let node = this
|
| 55 |
+
while (true) {
|
| 56 |
+
const code = key.charCodeAt(index)
|
| 57 |
+
// check code is ascii string
|
| 58 |
+
if (code > 0x7F) {
|
| 59 |
+
throw new TypeError('key must be ascii string')
|
| 60 |
+
}
|
| 61 |
+
if (node.code === code) {
|
| 62 |
+
if (length === ++index) {
|
| 63 |
+
node.value = value
|
| 64 |
+
break
|
| 65 |
+
} else if (node.middle !== null) {
|
| 66 |
+
node = node.middle
|
| 67 |
+
} else {
|
| 68 |
+
node.middle = new TstNode(key, value, index)
|
| 69 |
+
break
|
| 70 |
+
}
|
| 71 |
+
} else if (node.code < code) {
|
| 72 |
+
if (node.left !== null) {
|
| 73 |
+
node = node.left
|
| 74 |
+
} else {
|
| 75 |
+
node.left = new TstNode(key, value, index)
|
| 76 |
+
break
|
| 77 |
+
}
|
| 78 |
+
} else if (node.right !== null) {
|
| 79 |
+
node = node.right
|
| 80 |
+
} else {
|
| 81 |
+
node.right = new TstNode(key, value, index)
|
| 82 |
+
break
|
| 83 |
+
}
|
| 84 |
+
}
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
/**
|
| 88 |
+
* @param {Uint8Array} key
|
| 89 |
+
* @returns {TstNode | null}
|
| 90 |
+
*/
|
| 91 |
+
search (key) {
|
| 92 |
+
const keylength = key.length
|
| 93 |
+
let index = 0
|
| 94 |
+
/**
|
| 95 |
+
* @type {TstNode|null}
|
| 96 |
+
*/
|
| 97 |
+
let node = this
|
| 98 |
+
while (node !== null && index < keylength) {
|
| 99 |
+
let code = key[index]
|
| 100 |
+
// A-Z
|
| 101 |
+
// First check if it is bigger than 0x5a.
|
| 102 |
+
// Lowercase letters have higher char codes than uppercase ones.
|
| 103 |
+
// Also we assume that headers will mostly contain lowercase characters.
|
| 104 |
+
if (code <= 0x5a && code >= 0x41) {
|
| 105 |
+
// Lowercase for uppercase.
|
| 106 |
+
code |= 32
|
| 107 |
+
}
|
| 108 |
+
while (node !== null) {
|
| 109 |
+
if (code === node.code) {
|
| 110 |
+
if (keylength === ++index) {
|
| 111 |
+
// Returns Node since it is the last key.
|
| 112 |
+
return node
|
| 113 |
+
}
|
| 114 |
+
node = node.middle
|
| 115 |
+
break
|
| 116 |
+
}
|
| 117 |
+
node = node.code < code ? node.left : node.right
|
| 118 |
+
}
|
| 119 |
+
}
|
| 120 |
+
return null
|
| 121 |
+
}
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
class TernarySearchTree {
|
| 125 |
+
/** @type {TstNode | null} */
|
| 126 |
+
node = null
|
| 127 |
+
|
| 128 |
+
/**
|
| 129 |
+
* @param {string} key
|
| 130 |
+
* @param {any} value
|
| 131 |
+
* @returns {void}
|
| 132 |
+
* */
|
| 133 |
+
insert (key, value) {
|
| 134 |
+
if (this.node === null) {
|
| 135 |
+
this.node = new TstNode(key, value, 0)
|
| 136 |
+
} else {
|
| 137 |
+
this.node.add(key, value)
|
| 138 |
+
}
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
/**
|
| 142 |
+
* @param {Uint8Array} key
|
| 143 |
+
* @returns {any}
|
| 144 |
+
*/
|
| 145 |
+
lookup (key) {
|
| 146 |
+
return this.node?.search(key)?.value ?? null
|
| 147 |
+
}
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
const tree = new TernarySearchTree()
|
| 151 |
+
|
| 152 |
+
for (let i = 0; i < wellknownHeaderNames.length; ++i) {
|
| 153 |
+
const key = headerNameLowerCasedRecord[wellknownHeaderNames[i]]
|
| 154 |
+
tree.insert(key, key)
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
module.exports = {
|
| 158 |
+
TernarySearchTree,
|
| 159 |
+
tree
|
| 160 |
+
}
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/core/util.js
ADDED
|
@@ -0,0 +1,954 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'use strict'
|
| 2 |
+
|
| 3 |
+
const assert = require('node:assert')
|
| 4 |
+
const { kDestroyed, kBodyUsed, kListeners, kBody } = require('./symbols')
|
| 5 |
+
const { IncomingMessage } = require('node:http')
|
| 6 |
+
const stream = require('node:stream')
|
| 7 |
+
const net = require('node:net')
|
| 8 |
+
const { stringify } = require('node:querystring')
|
| 9 |
+
const { EventEmitter: EE } = require('node:events')
|
| 10 |
+
const timers = require('../util/timers')
|
| 11 |
+
const { InvalidArgumentError, ConnectTimeoutError } = require('./errors')
|
| 12 |
+
const { headerNameLowerCasedRecord } = require('./constants')
|
| 13 |
+
const { tree } = require('./tree')
|
| 14 |
+
|
| 15 |
+
const [nodeMajor, nodeMinor] = process.versions.node.split('.', 2).map(v => Number(v))
|
| 16 |
+
|
| 17 |
+
class BodyAsyncIterable {
|
| 18 |
+
constructor (body) {
|
| 19 |
+
this[kBody] = body
|
| 20 |
+
this[kBodyUsed] = false
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
async * [Symbol.asyncIterator] () {
|
| 24 |
+
assert(!this[kBodyUsed], 'disturbed')
|
| 25 |
+
this[kBodyUsed] = true
|
| 26 |
+
yield * this[kBody]
|
| 27 |
+
}
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
function noop () {}
|
| 31 |
+
|
| 32 |
+
/**
|
| 33 |
+
* @param {*} body
|
| 34 |
+
* @returns {*}
|
| 35 |
+
*/
|
| 36 |
+
function wrapRequestBody (body) {
|
| 37 |
+
if (isStream(body)) {
|
| 38 |
+
// TODO (fix): Provide some way for the user to cache the file to e.g. /tmp
|
| 39 |
+
// so that it can be dispatched again?
|
| 40 |
+
// TODO (fix): Do we need 100-expect support to provide a way to do this properly?
|
| 41 |
+
if (bodyLength(body) === 0) {
|
| 42 |
+
body
|
| 43 |
+
.on('data', function () {
|
| 44 |
+
assert(false)
|
| 45 |
+
})
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
if (typeof body.readableDidRead !== 'boolean') {
|
| 49 |
+
body[kBodyUsed] = false
|
| 50 |
+
EE.prototype.on.call(body, 'data', function () {
|
| 51 |
+
this[kBodyUsed] = true
|
| 52 |
+
})
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
return body
|
| 56 |
+
} else if (body && typeof body.pipeTo === 'function') {
|
| 57 |
+
// TODO (fix): We can't access ReadableStream internal state
|
| 58 |
+
// to determine whether or not it has been disturbed. This is just
|
| 59 |
+
// a workaround.
|
| 60 |
+
return new BodyAsyncIterable(body)
|
| 61 |
+
} else if (
|
| 62 |
+
body &&
|
| 63 |
+
typeof body !== 'string' &&
|
| 64 |
+
!ArrayBuffer.isView(body) &&
|
| 65 |
+
isIterable(body)
|
| 66 |
+
) {
|
| 67 |
+
// TODO: Should we allow re-using iterable if !this.opts.idempotent
|
| 68 |
+
// or through some other flag?
|
| 69 |
+
return new BodyAsyncIterable(body)
|
| 70 |
+
} else {
|
| 71 |
+
return body
|
| 72 |
+
}
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
/**
|
| 76 |
+
* @param {*} obj
|
| 77 |
+
* @returns {obj is import('node:stream').Stream}
|
| 78 |
+
*/
|
| 79 |
+
function isStream (obj) {
|
| 80 |
+
return obj && typeof obj === 'object' && typeof obj.pipe === 'function' && typeof obj.on === 'function'
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
/**
|
| 84 |
+
* @param {*} object
|
| 85 |
+
* @returns {object is Blob}
|
| 86 |
+
* based on https://github.com/node-fetch/fetch-blob/blob/8ab587d34080de94140b54f07168451e7d0b655e/index.js#L229-L241 (MIT License)
|
| 87 |
+
*/
|
| 88 |
+
function isBlobLike (object) {
|
| 89 |
+
if (object === null) {
|
| 90 |
+
return false
|
| 91 |
+
} else if (object instanceof Blob) {
|
| 92 |
+
return true
|
| 93 |
+
} else if (typeof object !== 'object') {
|
| 94 |
+
return false
|
| 95 |
+
} else {
|
| 96 |
+
const sTag = object[Symbol.toStringTag]
|
| 97 |
+
|
| 98 |
+
return (sTag === 'Blob' || sTag === 'File') && (
|
| 99 |
+
('stream' in object && typeof object.stream === 'function') ||
|
| 100 |
+
('arrayBuffer' in object && typeof object.arrayBuffer === 'function')
|
| 101 |
+
)
|
| 102 |
+
}
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
/**
|
| 106 |
+
* @param {string} url The path to check for query strings or fragments.
|
| 107 |
+
* @returns {boolean} Returns true if the path contains a query string or fragment.
|
| 108 |
+
*/
|
| 109 |
+
function pathHasQueryOrFragment (url) {
|
| 110 |
+
return (
|
| 111 |
+
url.includes('?') ||
|
| 112 |
+
url.includes('#')
|
| 113 |
+
)
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
/**
|
| 117 |
+
* @param {string} url The URL to add the query params to
|
| 118 |
+
* @param {import('node:querystring').ParsedUrlQueryInput} queryParams The object to serialize into a URL query string
|
| 119 |
+
* @returns {string} The URL with the query params added
|
| 120 |
+
*/
|
| 121 |
+
function serializePathWithQuery (url, queryParams) {
|
| 122 |
+
if (pathHasQueryOrFragment(url)) {
|
| 123 |
+
throw new Error('Query params cannot be passed when url already contains "?" or "#".')
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
const stringified = stringify(queryParams)
|
| 127 |
+
|
| 128 |
+
if (stringified) {
|
| 129 |
+
url += '?' + stringified
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
return url
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
/**
|
| 136 |
+
* @param {number|string|undefined} port
|
| 137 |
+
* @returns {boolean}
|
| 138 |
+
*/
|
| 139 |
+
function isValidPort (port) {
|
| 140 |
+
const value = parseInt(port, 10)
|
| 141 |
+
return (
|
| 142 |
+
value === Number(port) &&
|
| 143 |
+
value >= 0 &&
|
| 144 |
+
value <= 65535
|
| 145 |
+
)
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
/**
|
| 149 |
+
* Check if the value is a valid http or https prefixed string.
|
| 150 |
+
*
|
| 151 |
+
* @param {string} value
|
| 152 |
+
* @returns {boolean}
|
| 153 |
+
*/
|
| 154 |
+
function isHttpOrHttpsPrefixed (value) {
|
| 155 |
+
return (
|
| 156 |
+
value != null &&
|
| 157 |
+
value[0] === 'h' &&
|
| 158 |
+
value[1] === 't' &&
|
| 159 |
+
value[2] === 't' &&
|
| 160 |
+
value[3] === 'p' &&
|
| 161 |
+
(
|
| 162 |
+
value[4] === ':' ||
|
| 163 |
+
(
|
| 164 |
+
value[4] === 's' &&
|
| 165 |
+
value[5] === ':'
|
| 166 |
+
)
|
| 167 |
+
)
|
| 168 |
+
)
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
/**
|
| 172 |
+
* @param {string|URL|Record<string,string>} url
|
| 173 |
+
* @returns {URL}
|
| 174 |
+
*/
|
| 175 |
+
function parseURL (url) {
|
| 176 |
+
if (typeof url === 'string') {
|
| 177 |
+
/**
|
| 178 |
+
* @type {URL}
|
| 179 |
+
*/
|
| 180 |
+
url = new URL(url)
|
| 181 |
+
|
| 182 |
+
if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) {
|
| 183 |
+
throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
return url
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
if (!url || typeof url !== 'object') {
|
| 190 |
+
throw new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.')
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
if (!(url instanceof URL)) {
|
| 194 |
+
if (url.port != null && url.port !== '' && isValidPort(url.port) === false) {
|
| 195 |
+
throw new InvalidArgumentError('Invalid URL: port must be a valid integer or a string representation of an integer.')
|
| 196 |
+
}
|
| 197 |
+
|
| 198 |
+
if (url.path != null && typeof url.path !== 'string') {
|
| 199 |
+
throw new InvalidArgumentError('Invalid URL path: the path must be a string or null/undefined.')
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
if (url.pathname != null && typeof url.pathname !== 'string') {
|
| 203 |
+
throw new InvalidArgumentError('Invalid URL pathname: the pathname must be a string or null/undefined.')
|
| 204 |
+
}
|
| 205 |
+
|
| 206 |
+
if (url.hostname != null && typeof url.hostname !== 'string') {
|
| 207 |
+
throw new InvalidArgumentError('Invalid URL hostname: the hostname must be a string or null/undefined.')
|
| 208 |
+
}
|
| 209 |
+
|
| 210 |
+
if (url.origin != null && typeof url.origin !== 'string') {
|
| 211 |
+
throw new InvalidArgumentError('Invalid URL origin: the origin must be a string or null/undefined.')
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) {
|
| 215 |
+
throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')
|
| 216 |
+
}
|
| 217 |
+
|
| 218 |
+
const port = url.port != null
|
| 219 |
+
? url.port
|
| 220 |
+
: (url.protocol === 'https:' ? 443 : 80)
|
| 221 |
+
let origin = url.origin != null
|
| 222 |
+
? url.origin
|
| 223 |
+
: `${url.protocol || ''}//${url.hostname || ''}:${port}`
|
| 224 |
+
let path = url.path != null
|
| 225 |
+
? url.path
|
| 226 |
+
: `${url.pathname || ''}${url.search || ''}`
|
| 227 |
+
|
| 228 |
+
if (origin[origin.length - 1] === '/') {
|
| 229 |
+
origin = origin.slice(0, origin.length - 1)
|
| 230 |
+
}
|
| 231 |
+
|
| 232 |
+
if (path && path[0] !== '/') {
|
| 233 |
+
path = `/${path}`
|
| 234 |
+
}
|
| 235 |
+
// new URL(path, origin) is unsafe when `path` contains an absolute URL
|
| 236 |
+
// From https://developer.mozilla.org/en-US/docs/Web/API/URL/URL:
|
| 237 |
+
// If first parameter is a relative URL, second param is required, and will be used as the base URL.
|
| 238 |
+
// If first parameter is an absolute URL, a given second param will be ignored.
|
| 239 |
+
return new URL(`${origin}${path}`)
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) {
|
| 243 |
+
throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')
|
| 244 |
+
}
|
| 245 |
+
|
| 246 |
+
return url
|
| 247 |
+
}
|
| 248 |
+
|
| 249 |
+
/**
|
| 250 |
+
* @param {string|URL|Record<string, string>} url
|
| 251 |
+
* @returns {URL}
|
| 252 |
+
*/
|
| 253 |
+
function parseOrigin (url) {
|
| 254 |
+
url = parseURL(url)
|
| 255 |
+
|
| 256 |
+
if (url.pathname !== '/' || url.search || url.hash) {
|
| 257 |
+
throw new InvalidArgumentError('invalid url')
|
| 258 |
+
}
|
| 259 |
+
|
| 260 |
+
return url
|
| 261 |
+
}
|
| 262 |
+
|
| 263 |
+
/**
|
| 264 |
+
* @param {string} host
|
| 265 |
+
* @returns {string}
|
| 266 |
+
*/
|
| 267 |
+
function getHostname (host) {
|
| 268 |
+
if (host[0] === '[') {
|
| 269 |
+
const idx = host.indexOf(']')
|
| 270 |
+
|
| 271 |
+
assert(idx !== -1)
|
| 272 |
+
return host.substring(1, idx)
|
| 273 |
+
}
|
| 274 |
+
|
| 275 |
+
const idx = host.indexOf(':')
|
| 276 |
+
if (idx === -1) return host
|
| 277 |
+
|
| 278 |
+
return host.substring(0, idx)
|
| 279 |
+
}
|
| 280 |
+
|
| 281 |
+
/**
|
| 282 |
+
* IP addresses are not valid server names per RFC6066
|
| 283 |
+
* Currently, the only server names supported are DNS hostnames
|
| 284 |
+
* @param {string|null} host
|
| 285 |
+
* @returns {string|null}
|
| 286 |
+
*/
|
| 287 |
+
function getServerName (host) {
|
| 288 |
+
if (!host) {
|
| 289 |
+
return null
|
| 290 |
+
}
|
| 291 |
+
|
| 292 |
+
assert(typeof host === 'string')
|
| 293 |
+
|
| 294 |
+
const servername = getHostname(host)
|
| 295 |
+
if (net.isIP(servername)) {
|
| 296 |
+
return ''
|
| 297 |
+
}
|
| 298 |
+
|
| 299 |
+
return servername
|
| 300 |
+
}
|
| 301 |
+
|
| 302 |
+
/**
|
| 303 |
+
* @function
|
| 304 |
+
* @template T
|
| 305 |
+
* @param {T} obj
|
| 306 |
+
* @returns {T}
|
| 307 |
+
*/
|
| 308 |
+
function deepClone (obj) {
|
| 309 |
+
return JSON.parse(JSON.stringify(obj))
|
| 310 |
+
}
|
| 311 |
+
|
| 312 |
+
/**
|
| 313 |
+
* @param {*} obj
|
| 314 |
+
* @returns {obj is AsyncIterable}
|
| 315 |
+
*/
|
| 316 |
+
function isAsyncIterable (obj) {
|
| 317 |
+
return !!(obj != null && typeof obj[Symbol.asyncIterator] === 'function')
|
| 318 |
+
}
|
| 319 |
+
|
| 320 |
+
/**
|
| 321 |
+
* @param {*} obj
|
| 322 |
+
* @returns {obj is Iterable}
|
| 323 |
+
*/
|
| 324 |
+
function isIterable (obj) {
|
| 325 |
+
return !!(obj != null && (typeof obj[Symbol.iterator] === 'function' || typeof obj[Symbol.asyncIterator] === 'function'))
|
| 326 |
+
}
|
| 327 |
+
|
| 328 |
+
/**
|
| 329 |
+
* @param {Blob|Buffer|import ('stream').Stream} body
|
| 330 |
+
* @returns {number|null}
|
| 331 |
+
*/
|
| 332 |
+
function bodyLength (body) {
|
| 333 |
+
if (body == null) {
|
| 334 |
+
return 0
|
| 335 |
+
} else if (isStream(body)) {
|
| 336 |
+
const state = body._readableState
|
| 337 |
+
return state && state.objectMode === false && state.ended === true && Number.isFinite(state.length)
|
| 338 |
+
? state.length
|
| 339 |
+
: null
|
| 340 |
+
} else if (isBlobLike(body)) {
|
| 341 |
+
return body.size != null ? body.size : null
|
| 342 |
+
} else if (isBuffer(body)) {
|
| 343 |
+
return body.byteLength
|
| 344 |
+
}
|
| 345 |
+
|
| 346 |
+
return null
|
| 347 |
+
}
|
| 348 |
+
|
| 349 |
+
/**
|
| 350 |
+
* @param {import ('stream').Stream} body
|
| 351 |
+
* @returns {boolean}
|
| 352 |
+
*/
|
| 353 |
+
function isDestroyed (body) {
|
| 354 |
+
return body && !!(body.destroyed || body[kDestroyed] || (stream.isDestroyed?.(body)))
|
| 355 |
+
}
|
| 356 |
+
|
| 357 |
+
/**
|
| 358 |
+
* @param {import ('stream').Stream} stream
|
| 359 |
+
* @param {Error} [err]
|
| 360 |
+
* @returns {void}
|
| 361 |
+
*/
|
| 362 |
+
function destroy (stream, err) {
|
| 363 |
+
if (stream == null || !isStream(stream) || isDestroyed(stream)) {
|
| 364 |
+
return
|
| 365 |
+
}
|
| 366 |
+
|
| 367 |
+
if (typeof stream.destroy === 'function') {
|
| 368 |
+
if (Object.getPrototypeOf(stream).constructor === IncomingMessage) {
|
| 369 |
+
// See: https://github.com/nodejs/node/pull/38505/files
|
| 370 |
+
stream.socket = null
|
| 371 |
+
}
|
| 372 |
+
|
| 373 |
+
stream.destroy(err)
|
| 374 |
+
} else if (err) {
|
| 375 |
+
queueMicrotask(() => {
|
| 376 |
+
stream.emit('error', err)
|
| 377 |
+
})
|
| 378 |
+
}
|
| 379 |
+
|
| 380 |
+
if (stream.destroyed !== true) {
|
| 381 |
+
stream[kDestroyed] = true
|
| 382 |
+
}
|
| 383 |
+
}
|
| 384 |
+
|
| 385 |
+
const KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/
|
| 386 |
+
/**
|
| 387 |
+
* @param {string} val
|
| 388 |
+
* @returns {number | null}
|
| 389 |
+
*/
|
| 390 |
+
function parseKeepAliveTimeout (val) {
|
| 391 |
+
const m = val.match(KEEPALIVE_TIMEOUT_EXPR)
|
| 392 |
+
return m ? parseInt(m[1], 10) * 1000 : null
|
| 393 |
+
}
|
| 394 |
+
|
| 395 |
+
/**
|
| 396 |
+
* Retrieves a header name and returns its lowercase value.
|
| 397 |
+
* @param {string | Buffer} value Header name
|
| 398 |
+
* @returns {string}
|
| 399 |
+
*/
|
| 400 |
+
function headerNameToString (value) {
|
| 401 |
+
return typeof value === 'string'
|
| 402 |
+
? headerNameLowerCasedRecord[value] ?? value.toLowerCase()
|
| 403 |
+
: tree.lookup(value) ?? value.toString('latin1').toLowerCase()
|
| 404 |
+
}
|
| 405 |
+
|
| 406 |
+
/**
|
| 407 |
+
* Receive the buffer as a string and return its lowercase value.
|
| 408 |
+
* @param {Buffer} value Header name
|
| 409 |
+
* @returns {string}
|
| 410 |
+
*/
|
| 411 |
+
function bufferToLowerCasedHeaderName (value) {
|
| 412 |
+
return tree.lookup(value) ?? value.toString('latin1').toLowerCase()
|
| 413 |
+
}
|
| 414 |
+
|
| 415 |
+
/**
|
| 416 |
+
* @param {(Buffer | string)[]} headers
|
| 417 |
+
* @param {Record<string, string | string[]>} [obj]
|
| 418 |
+
* @returns {Record<string, string | string[]>}
|
| 419 |
+
*/
|
| 420 |
+
function parseHeaders (headers, obj) {
|
| 421 |
+
if (obj === undefined) obj = {}
|
| 422 |
+
|
| 423 |
+
for (let i = 0; i < headers.length; i += 2) {
|
| 424 |
+
const key = headerNameToString(headers[i])
|
| 425 |
+
let val = obj[key]
|
| 426 |
+
|
| 427 |
+
if (val) {
|
| 428 |
+
if (typeof val === 'string') {
|
| 429 |
+
val = [val]
|
| 430 |
+
obj[key] = val
|
| 431 |
+
}
|
| 432 |
+
val.push(headers[i + 1].toString('utf8'))
|
| 433 |
+
} else {
|
| 434 |
+
const headersValue = headers[i + 1]
|
| 435 |
+
if (typeof headersValue === 'string') {
|
| 436 |
+
obj[key] = headersValue
|
| 437 |
+
} else {
|
| 438 |
+
obj[key] = Array.isArray(headersValue) ? headersValue.map(x => x.toString('utf8')) : headersValue.toString('utf8')
|
| 439 |
+
}
|
| 440 |
+
}
|
| 441 |
+
}
|
| 442 |
+
|
| 443 |
+
// See https://github.com/nodejs/node/pull/46528
|
| 444 |
+
if ('content-length' in obj && 'content-disposition' in obj) {
|
| 445 |
+
obj['content-disposition'] = Buffer.from(obj['content-disposition']).toString('latin1')
|
| 446 |
+
}
|
| 447 |
+
|
| 448 |
+
return obj
|
| 449 |
+
}
|
| 450 |
+
|
| 451 |
+
/**
|
| 452 |
+
* @param {Buffer[]} headers
|
| 453 |
+
* @returns {string[]}
|
| 454 |
+
*/
|
| 455 |
+
function parseRawHeaders (headers) {
|
| 456 |
+
const headersLength = headers.length
|
| 457 |
+
/**
|
| 458 |
+
* @type {string[]}
|
| 459 |
+
*/
|
| 460 |
+
const ret = new Array(headersLength)
|
| 461 |
+
|
| 462 |
+
let hasContentLength = false
|
| 463 |
+
let contentDispositionIdx = -1
|
| 464 |
+
let key
|
| 465 |
+
let val
|
| 466 |
+
let kLen = 0
|
| 467 |
+
|
| 468 |
+
for (let n = 0; n < headersLength; n += 2) {
|
| 469 |
+
key = headers[n]
|
| 470 |
+
val = headers[n + 1]
|
| 471 |
+
|
| 472 |
+
typeof key !== 'string' && (key = key.toString())
|
| 473 |
+
typeof val !== 'string' && (val = val.toString('utf8'))
|
| 474 |
+
|
| 475 |
+
kLen = key.length
|
| 476 |
+
if (kLen === 14 && key[7] === '-' && (key === 'content-length' || key.toLowerCase() === 'content-length')) {
|
| 477 |
+
hasContentLength = true
|
| 478 |
+
} else if (kLen === 19 && key[7] === '-' && (key === 'content-disposition' || key.toLowerCase() === 'content-disposition')) {
|
| 479 |
+
contentDispositionIdx = n + 1
|
| 480 |
+
}
|
| 481 |
+
ret[n] = key
|
| 482 |
+
ret[n + 1] = val
|
| 483 |
+
}
|
| 484 |
+
|
| 485 |
+
// See https://github.com/nodejs/node/pull/46528
|
| 486 |
+
if (hasContentLength && contentDispositionIdx !== -1) {
|
| 487 |
+
ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString('latin1')
|
| 488 |
+
}
|
| 489 |
+
|
| 490 |
+
return ret
|
| 491 |
+
}
|
| 492 |
+
|
| 493 |
+
/**
|
| 494 |
+
* @param {string[]} headers
|
| 495 |
+
* @param {Buffer[]} headers
|
| 496 |
+
*/
|
| 497 |
+
function encodeRawHeaders (headers) {
|
| 498 |
+
if (!Array.isArray(headers)) {
|
| 499 |
+
throw new TypeError('expected headers to be an array')
|
| 500 |
+
}
|
| 501 |
+
return headers.map(x => Buffer.from(x))
|
| 502 |
+
}
|
| 503 |
+
|
| 504 |
+
/**
|
| 505 |
+
* @param {*} buffer
|
| 506 |
+
* @returns {buffer is Buffer}
|
| 507 |
+
*/
|
| 508 |
+
function isBuffer (buffer) {
|
| 509 |
+
// See, https://github.com/mcollina/undici/pull/319
|
| 510 |
+
return buffer instanceof Uint8Array || Buffer.isBuffer(buffer)
|
| 511 |
+
}
|
| 512 |
+
|
| 513 |
+
/**
|
| 514 |
+
* Asserts that the handler object is a request handler.
|
| 515 |
+
*
|
| 516 |
+
* @param {object} handler
|
| 517 |
+
* @param {string} method
|
| 518 |
+
* @param {string} [upgrade]
|
| 519 |
+
* @returns {asserts handler is import('../api/api-request').RequestHandler}
|
| 520 |
+
*/
|
| 521 |
+
function assertRequestHandler (handler, method, upgrade) {
|
| 522 |
+
if (!handler || typeof handler !== 'object') {
|
| 523 |
+
throw new InvalidArgumentError('handler must be an object')
|
| 524 |
+
}
|
| 525 |
+
|
| 526 |
+
if (typeof handler.onRequestStart === 'function') {
|
| 527 |
+
// TODO (fix): More checks...
|
| 528 |
+
return
|
| 529 |
+
}
|
| 530 |
+
|
| 531 |
+
if (typeof handler.onConnect !== 'function') {
|
| 532 |
+
throw new InvalidArgumentError('invalid onConnect method')
|
| 533 |
+
}
|
| 534 |
+
|
| 535 |
+
if (typeof handler.onError !== 'function') {
|
| 536 |
+
throw new InvalidArgumentError('invalid onError method')
|
| 537 |
+
}
|
| 538 |
+
|
| 539 |
+
if (typeof handler.onBodySent !== 'function' && handler.onBodySent !== undefined) {
|
| 540 |
+
throw new InvalidArgumentError('invalid onBodySent method')
|
| 541 |
+
}
|
| 542 |
+
|
| 543 |
+
if (upgrade || method === 'CONNECT') {
|
| 544 |
+
if (typeof handler.onUpgrade !== 'function') {
|
| 545 |
+
throw new InvalidArgumentError('invalid onUpgrade method')
|
| 546 |
+
}
|
| 547 |
+
} else {
|
| 548 |
+
if (typeof handler.onHeaders !== 'function') {
|
| 549 |
+
throw new InvalidArgumentError('invalid onHeaders method')
|
| 550 |
+
}
|
| 551 |
+
|
| 552 |
+
if (typeof handler.onData !== 'function') {
|
| 553 |
+
throw new InvalidArgumentError('invalid onData method')
|
| 554 |
+
}
|
| 555 |
+
|
| 556 |
+
if (typeof handler.onComplete !== 'function') {
|
| 557 |
+
throw new InvalidArgumentError('invalid onComplete method')
|
| 558 |
+
}
|
| 559 |
+
}
|
| 560 |
+
}
|
| 561 |
+
|
| 562 |
+
/**
|
| 563 |
+
* A body is disturbed if it has been read from and it cannot be re-used without
|
| 564 |
+
* losing state or data.
|
| 565 |
+
* @param {import('node:stream').Readable} body
|
| 566 |
+
* @returns {boolean}
|
| 567 |
+
*/
|
| 568 |
+
function isDisturbed (body) {
|
| 569 |
+
// TODO (fix): Why is body[kBodyUsed] needed?
|
| 570 |
+
return !!(body && (stream.isDisturbed(body) || body[kBodyUsed]))
|
| 571 |
+
}
|
| 572 |
+
|
| 573 |
+
/**
|
| 574 |
+
* @typedef {object} SocketInfo
|
| 575 |
+
* @property {string} [localAddress]
|
| 576 |
+
* @property {number} [localPort]
|
| 577 |
+
* @property {string} [remoteAddress]
|
| 578 |
+
* @property {number} [remotePort]
|
| 579 |
+
* @property {string} [remoteFamily]
|
| 580 |
+
* @property {number} [timeout]
|
| 581 |
+
* @property {number} bytesWritten
|
| 582 |
+
* @property {number} bytesRead
|
| 583 |
+
*/
|
| 584 |
+
|
| 585 |
+
/**
|
| 586 |
+
* @param {import('net').Socket} socket
|
| 587 |
+
* @returns {SocketInfo}
|
| 588 |
+
*/
|
| 589 |
+
function getSocketInfo (socket) {
|
| 590 |
+
return {
|
| 591 |
+
localAddress: socket.localAddress,
|
| 592 |
+
localPort: socket.localPort,
|
| 593 |
+
remoteAddress: socket.remoteAddress,
|
| 594 |
+
remotePort: socket.remotePort,
|
| 595 |
+
remoteFamily: socket.remoteFamily,
|
| 596 |
+
timeout: socket.timeout,
|
| 597 |
+
bytesWritten: socket.bytesWritten,
|
| 598 |
+
bytesRead: socket.bytesRead
|
| 599 |
+
}
|
| 600 |
+
}
|
| 601 |
+
|
| 602 |
+
/**
|
| 603 |
+
* @param {Iterable} iterable
|
| 604 |
+
* @returns {ReadableStream}
|
| 605 |
+
*/
|
| 606 |
+
function ReadableStreamFrom (iterable) {
|
| 607 |
+
// We cannot use ReadableStream.from here because it does not return a byte stream.
|
| 608 |
+
|
| 609 |
+
let iterator
|
| 610 |
+
return new ReadableStream(
|
| 611 |
+
{
|
| 612 |
+
async start () {
|
| 613 |
+
iterator = iterable[Symbol.asyncIterator]()
|
| 614 |
+
},
|
| 615 |
+
pull (controller) {
|
| 616 |
+
async function pull () {
|
| 617 |
+
const { done, value } = await iterator.next()
|
| 618 |
+
if (done) {
|
| 619 |
+
queueMicrotask(() => {
|
| 620 |
+
controller.close()
|
| 621 |
+
controller.byobRequest?.respond(0)
|
| 622 |
+
})
|
| 623 |
+
} else {
|
| 624 |
+
const buf = Buffer.isBuffer(value) ? value : Buffer.from(value)
|
| 625 |
+
if (buf.byteLength) {
|
| 626 |
+
controller.enqueue(new Uint8Array(buf))
|
| 627 |
+
} else {
|
| 628 |
+
return await pull()
|
| 629 |
+
}
|
| 630 |
+
}
|
| 631 |
+
}
|
| 632 |
+
|
| 633 |
+
return pull()
|
| 634 |
+
},
|
| 635 |
+
async cancel () {
|
| 636 |
+
await iterator.return()
|
| 637 |
+
},
|
| 638 |
+
type: 'bytes'
|
| 639 |
+
}
|
| 640 |
+
)
|
| 641 |
+
}
|
| 642 |
+
|
| 643 |
+
/**
|
| 644 |
+
* The object should be a FormData instance and contains all the required
|
| 645 |
+
* methods.
|
| 646 |
+
* @param {*} object
|
| 647 |
+
* @returns {object is FormData}
|
| 648 |
+
*/
|
| 649 |
+
function isFormDataLike (object) {
|
| 650 |
+
return (
|
| 651 |
+
object &&
|
| 652 |
+
typeof object === 'object' &&
|
| 653 |
+
typeof object.append === 'function' &&
|
| 654 |
+
typeof object.delete === 'function' &&
|
| 655 |
+
typeof object.get === 'function' &&
|
| 656 |
+
typeof object.getAll === 'function' &&
|
| 657 |
+
typeof object.has === 'function' &&
|
| 658 |
+
typeof object.set === 'function' &&
|
| 659 |
+
object[Symbol.toStringTag] === 'FormData'
|
| 660 |
+
)
|
| 661 |
+
}
|
| 662 |
+
|
| 663 |
+
function addAbortListener (signal, listener) {
|
| 664 |
+
if ('addEventListener' in signal) {
|
| 665 |
+
signal.addEventListener('abort', listener, { once: true })
|
| 666 |
+
return () => signal.removeEventListener('abort', listener)
|
| 667 |
+
}
|
| 668 |
+
signal.once('abort', listener)
|
| 669 |
+
return () => signal.removeListener('abort', listener)
|
| 670 |
+
}
|
| 671 |
+
|
| 672 |
+
/**
|
| 673 |
+
* @see https://tools.ietf.org/html/rfc7230#section-3.2.6
|
| 674 |
+
* @param {number} c
|
| 675 |
+
* @returns {boolean}
|
| 676 |
+
*/
|
| 677 |
+
function isTokenCharCode (c) {
|
| 678 |
+
switch (c) {
|
| 679 |
+
case 0x22:
|
| 680 |
+
case 0x28:
|
| 681 |
+
case 0x29:
|
| 682 |
+
case 0x2c:
|
| 683 |
+
case 0x2f:
|
| 684 |
+
case 0x3a:
|
| 685 |
+
case 0x3b:
|
| 686 |
+
case 0x3c:
|
| 687 |
+
case 0x3d:
|
| 688 |
+
case 0x3e:
|
| 689 |
+
case 0x3f:
|
| 690 |
+
case 0x40:
|
| 691 |
+
case 0x5b:
|
| 692 |
+
case 0x5c:
|
| 693 |
+
case 0x5d:
|
| 694 |
+
case 0x7b:
|
| 695 |
+
case 0x7d:
|
| 696 |
+
// DQUOTE and "(),/:;<=>?@[\]{}"
|
| 697 |
+
return false
|
| 698 |
+
default:
|
| 699 |
+
// VCHAR %x21-7E
|
| 700 |
+
return c >= 0x21 && c <= 0x7e
|
| 701 |
+
}
|
| 702 |
+
}
|
| 703 |
+
|
| 704 |
+
/**
|
| 705 |
+
* @param {string} characters
|
| 706 |
+
* @returns {boolean}
|
| 707 |
+
*/
|
| 708 |
+
function isValidHTTPToken (characters) {
|
| 709 |
+
if (characters.length === 0) {
|
| 710 |
+
return false
|
| 711 |
+
}
|
| 712 |
+
for (let i = 0; i < characters.length; ++i) {
|
| 713 |
+
if (!isTokenCharCode(characters.charCodeAt(i))) {
|
| 714 |
+
return false
|
| 715 |
+
}
|
| 716 |
+
}
|
| 717 |
+
return true
|
| 718 |
+
}
|
| 719 |
+
|
| 720 |
+
// headerCharRegex have been lifted from
|
| 721 |
+
// https://github.com/nodejs/node/blob/main/lib/_http_common.js
|
| 722 |
+
|
| 723 |
+
/**
|
| 724 |
+
* Matches if val contains an invalid field-vchar
|
| 725 |
+
* field-value = *( field-content / obs-fold )
|
| 726 |
+
* field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
|
| 727 |
+
* field-vchar = VCHAR / obs-text
|
| 728 |
+
*/
|
| 729 |
+
const headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/
|
| 730 |
+
|
| 731 |
+
/**
|
| 732 |
+
* @param {string} characters
|
| 733 |
+
* @returns {boolean}
|
| 734 |
+
*/
|
| 735 |
+
function isValidHeaderValue (characters) {
|
| 736 |
+
return !headerCharRegex.test(characters)
|
| 737 |
+
}
|
| 738 |
+
|
| 739 |
+
const rangeHeaderRegex = /^bytes (\d+)-(\d+)\/(\d+)?$/
|
| 740 |
+
|
| 741 |
+
/**
|
| 742 |
+
* @typedef {object} RangeHeader
|
| 743 |
+
* @property {number} start
|
| 744 |
+
* @property {number | null} end
|
| 745 |
+
* @property {number | null} size
|
| 746 |
+
*/
|
| 747 |
+
|
| 748 |
+
/**
|
| 749 |
+
* Parse accordingly to RFC 9110
|
| 750 |
+
* @see https://www.rfc-editor.org/rfc/rfc9110#field.content-range
|
| 751 |
+
* @param {string} [range]
|
| 752 |
+
* @returns {RangeHeader|null}
|
| 753 |
+
*/
|
| 754 |
+
function parseRangeHeader (range) {
|
| 755 |
+
if (range == null || range === '') return { start: 0, end: null, size: null }
|
| 756 |
+
|
| 757 |
+
const m = range ? range.match(rangeHeaderRegex) : null
|
| 758 |
+
return m
|
| 759 |
+
? {
|
| 760 |
+
start: parseInt(m[1]),
|
| 761 |
+
end: m[2] ? parseInt(m[2]) : null,
|
| 762 |
+
size: m[3] ? parseInt(m[3]) : null
|
| 763 |
+
}
|
| 764 |
+
: null
|
| 765 |
+
}
|
| 766 |
+
|
| 767 |
+
/**
|
| 768 |
+
* @template {import("events").EventEmitter} T
|
| 769 |
+
* @param {T} obj
|
| 770 |
+
* @param {string} name
|
| 771 |
+
* @param {(...args: any[]) => void} listener
|
| 772 |
+
* @returns {T}
|
| 773 |
+
*/
|
| 774 |
+
function addListener (obj, name, listener) {
|
| 775 |
+
const listeners = (obj[kListeners] ??= [])
|
| 776 |
+
listeners.push([name, listener])
|
| 777 |
+
obj.on(name, listener)
|
| 778 |
+
return obj
|
| 779 |
+
}
|
| 780 |
+
|
| 781 |
+
/**
|
| 782 |
+
* @template {import("events").EventEmitter} T
|
| 783 |
+
* @param {T} obj
|
| 784 |
+
* @returns {T}
|
| 785 |
+
*/
|
| 786 |
+
function removeAllListeners (obj) {
|
| 787 |
+
if (obj[kListeners] != null) {
|
| 788 |
+
for (const [name, listener] of obj[kListeners]) {
|
| 789 |
+
obj.removeListener(name, listener)
|
| 790 |
+
}
|
| 791 |
+
obj[kListeners] = null
|
| 792 |
+
}
|
| 793 |
+
return obj
|
| 794 |
+
}
|
| 795 |
+
|
| 796 |
+
/**
|
| 797 |
+
* @param {import ('../dispatcher/client')} client
|
| 798 |
+
* @param {import ('../core/request')} request
|
| 799 |
+
* @param {Error} err
|
| 800 |
+
*/
|
| 801 |
+
function errorRequest (client, request, err) {
|
| 802 |
+
try {
|
| 803 |
+
request.onError(err)
|
| 804 |
+
assert(request.aborted)
|
| 805 |
+
} catch (err) {
|
| 806 |
+
client.emit('error', err)
|
| 807 |
+
}
|
| 808 |
+
}
|
| 809 |
+
|
| 810 |
+
/**
|
| 811 |
+
* @param {WeakRef<net.Socket>} socketWeakRef
|
| 812 |
+
* @param {object} opts
|
| 813 |
+
* @param {number} opts.timeout
|
| 814 |
+
* @param {string} opts.hostname
|
| 815 |
+
* @param {number} opts.port
|
| 816 |
+
* @returns {() => void}
|
| 817 |
+
*/
|
| 818 |
+
const setupConnectTimeout = process.platform === 'win32'
|
| 819 |
+
? (socketWeakRef, opts) => {
|
| 820 |
+
if (!opts.timeout) {
|
| 821 |
+
return noop
|
| 822 |
+
}
|
| 823 |
+
|
| 824 |
+
let s1 = null
|
| 825 |
+
let s2 = null
|
| 826 |
+
const fastTimer = timers.setFastTimeout(() => {
|
| 827 |
+
// setImmediate is added to make sure that we prioritize socket error events over timeouts
|
| 828 |
+
s1 = setImmediate(() => {
|
| 829 |
+
// Windows needs an extra setImmediate probably due to implementation differences in the socket logic
|
| 830 |
+
s2 = setImmediate(() => onConnectTimeout(socketWeakRef.deref(), opts))
|
| 831 |
+
})
|
| 832 |
+
}, opts.timeout)
|
| 833 |
+
return () => {
|
| 834 |
+
timers.clearFastTimeout(fastTimer)
|
| 835 |
+
clearImmediate(s1)
|
| 836 |
+
clearImmediate(s2)
|
| 837 |
+
}
|
| 838 |
+
}
|
| 839 |
+
: (socketWeakRef, opts) => {
|
| 840 |
+
if (!opts.timeout) {
|
| 841 |
+
return noop
|
| 842 |
+
}
|
| 843 |
+
|
| 844 |
+
let s1 = null
|
| 845 |
+
const fastTimer = timers.setFastTimeout(() => {
|
| 846 |
+
// setImmediate is added to make sure that we prioritize socket error events over timeouts
|
| 847 |
+
s1 = setImmediate(() => {
|
| 848 |
+
onConnectTimeout(socketWeakRef.deref(), opts)
|
| 849 |
+
})
|
| 850 |
+
}, opts.timeout)
|
| 851 |
+
return () => {
|
| 852 |
+
timers.clearFastTimeout(fastTimer)
|
| 853 |
+
clearImmediate(s1)
|
| 854 |
+
}
|
| 855 |
+
}
|
| 856 |
+
|
| 857 |
+
/**
|
| 858 |
+
* @param {net.Socket} socket
|
| 859 |
+
* @param {object} opts
|
| 860 |
+
* @param {number} opts.timeout
|
| 861 |
+
* @param {string} opts.hostname
|
| 862 |
+
* @param {number} opts.port
|
| 863 |
+
*/
|
| 864 |
+
function onConnectTimeout (socket, opts) {
|
| 865 |
+
// The socket could be already garbage collected
|
| 866 |
+
if (socket == null) {
|
| 867 |
+
return
|
| 868 |
+
}
|
| 869 |
+
|
| 870 |
+
let message = 'Connect Timeout Error'
|
| 871 |
+
if (Array.isArray(socket.autoSelectFamilyAttemptedAddresses)) {
|
| 872 |
+
message += ` (attempted addresses: ${socket.autoSelectFamilyAttemptedAddresses.join(', ')},`
|
| 873 |
+
} else {
|
| 874 |
+
message += ` (attempted address: ${opts.hostname}:${opts.port},`
|
| 875 |
+
}
|
| 876 |
+
|
| 877 |
+
message += ` timeout: ${opts.timeout}ms)`
|
| 878 |
+
|
| 879 |
+
destroy(socket, new ConnectTimeoutError(message))
|
| 880 |
+
}
|
| 881 |
+
|
| 882 |
+
const kEnumerableProperty = Object.create(null)
|
| 883 |
+
kEnumerableProperty.enumerable = true
|
| 884 |
+
|
| 885 |
+
const normalizedMethodRecordsBase = {
|
| 886 |
+
delete: 'DELETE',
|
| 887 |
+
DELETE: 'DELETE',
|
| 888 |
+
get: 'GET',
|
| 889 |
+
GET: 'GET',
|
| 890 |
+
head: 'HEAD',
|
| 891 |
+
HEAD: 'HEAD',
|
| 892 |
+
options: 'OPTIONS',
|
| 893 |
+
OPTIONS: 'OPTIONS',
|
| 894 |
+
post: 'POST',
|
| 895 |
+
POST: 'POST',
|
| 896 |
+
put: 'PUT',
|
| 897 |
+
PUT: 'PUT'
|
| 898 |
+
}
|
| 899 |
+
|
| 900 |
+
const normalizedMethodRecords = {
|
| 901 |
+
...normalizedMethodRecordsBase,
|
| 902 |
+
patch: 'patch',
|
| 903 |
+
PATCH: 'PATCH'
|
| 904 |
+
}
|
| 905 |
+
|
| 906 |
+
// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`.
|
| 907 |
+
Object.setPrototypeOf(normalizedMethodRecordsBase, null)
|
| 908 |
+
Object.setPrototypeOf(normalizedMethodRecords, null)
|
| 909 |
+
|
| 910 |
+
module.exports = {
|
| 911 |
+
kEnumerableProperty,
|
| 912 |
+
isDisturbed,
|
| 913 |
+
isBlobLike,
|
| 914 |
+
parseOrigin,
|
| 915 |
+
parseURL,
|
| 916 |
+
getServerName,
|
| 917 |
+
isStream,
|
| 918 |
+
isIterable,
|
| 919 |
+
isAsyncIterable,
|
| 920 |
+
isDestroyed,
|
| 921 |
+
headerNameToString,
|
| 922 |
+
bufferToLowerCasedHeaderName,
|
| 923 |
+
addListener,
|
| 924 |
+
removeAllListeners,
|
| 925 |
+
errorRequest,
|
| 926 |
+
parseRawHeaders,
|
| 927 |
+
encodeRawHeaders,
|
| 928 |
+
parseHeaders,
|
| 929 |
+
parseKeepAliveTimeout,
|
| 930 |
+
destroy,
|
| 931 |
+
bodyLength,
|
| 932 |
+
deepClone,
|
| 933 |
+
ReadableStreamFrom,
|
| 934 |
+
isBuffer,
|
| 935 |
+
assertRequestHandler,
|
| 936 |
+
getSocketInfo,
|
| 937 |
+
isFormDataLike,
|
| 938 |
+
pathHasQueryOrFragment,
|
| 939 |
+
serializePathWithQuery,
|
| 940 |
+
addAbortListener,
|
| 941 |
+
isValidHTTPToken,
|
| 942 |
+
isValidHeaderValue,
|
| 943 |
+
isTokenCharCode,
|
| 944 |
+
parseRangeHeader,
|
| 945 |
+
normalizedMethodRecordsBase,
|
| 946 |
+
normalizedMethodRecords,
|
| 947 |
+
isValidPort,
|
| 948 |
+
isHttpOrHttpsPrefixed,
|
| 949 |
+
nodeMajor,
|
| 950 |
+
nodeMinor,
|
| 951 |
+
safeHTTPMethods: Object.freeze(['GET', 'HEAD', 'OPTIONS', 'TRACE']),
|
| 952 |
+
wrapRequestBody,
|
| 953 |
+
setupConnectTimeout
|
| 954 |
+
}
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/dispatcher/agent.js
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'use strict'
|
| 2 |
+
|
| 3 |
+
const { InvalidArgumentError } = require('../core/errors')
|
| 4 |
+
const { kClients, kRunning, kClose, kDestroy, kDispatch, kUrl } = require('../core/symbols')
|
| 5 |
+
const DispatcherBase = require('./dispatcher-base')
|
| 6 |
+
const Pool = require('./pool')
|
| 7 |
+
const Client = require('./client')
|
| 8 |
+
const util = require('../core/util')
|
| 9 |
+
|
| 10 |
+
const kOnConnect = Symbol('onConnect')
|
| 11 |
+
const kOnDisconnect = Symbol('onDisconnect')
|
| 12 |
+
const kOnConnectionError = Symbol('onConnectionError')
|
| 13 |
+
const kOnDrain = Symbol('onDrain')
|
| 14 |
+
const kFactory = Symbol('factory')
|
| 15 |
+
const kOptions = Symbol('options')
|
| 16 |
+
|
| 17 |
+
function defaultFactory (origin, opts) {
|
| 18 |
+
return opts && opts.connections === 1
|
| 19 |
+
? new Client(origin, opts)
|
| 20 |
+
: new Pool(origin, opts)
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
class Agent extends DispatcherBase {
|
| 24 |
+
constructor ({ factory = defaultFactory, connect, ...options } = {}) {
|
| 25 |
+
if (typeof factory !== 'function') {
|
| 26 |
+
throw new InvalidArgumentError('factory must be a function.')
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {
|
| 30 |
+
throw new InvalidArgumentError('connect must be a function or an object')
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
super()
|
| 34 |
+
|
| 35 |
+
if (connect && typeof connect !== 'function') {
|
| 36 |
+
connect = { ...connect }
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
this[kOptions] = { ...util.deepClone(options), connect }
|
| 40 |
+
this[kFactory] = factory
|
| 41 |
+
this[kClients] = new Map()
|
| 42 |
+
|
| 43 |
+
this[kOnDrain] = (origin, targets) => {
|
| 44 |
+
this.emit('drain', origin, [this, ...targets])
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
this[kOnConnect] = (origin, targets) => {
|
| 48 |
+
this.emit('connect', origin, [this, ...targets])
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
this[kOnDisconnect] = (origin, targets, err) => {
|
| 52 |
+
this.emit('disconnect', origin, [this, ...targets], err)
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
this[kOnConnectionError] = (origin, targets, err) => {
|
| 56 |
+
this.emit('connectionError', origin, [this, ...targets], err)
|
| 57 |
+
}
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
get [kRunning] () {
|
| 61 |
+
let ret = 0
|
| 62 |
+
for (const { dispatcher } of this[kClients].values()) {
|
| 63 |
+
ret += dispatcher[kRunning]
|
| 64 |
+
}
|
| 65 |
+
return ret
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
[kDispatch] (opts, handler) {
|
| 69 |
+
let key
|
| 70 |
+
if (opts.origin && (typeof opts.origin === 'string' || opts.origin instanceof URL)) {
|
| 71 |
+
key = String(opts.origin)
|
| 72 |
+
} else {
|
| 73 |
+
throw new InvalidArgumentError('opts.origin must be a non-empty string or URL.')
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
const result = this[kClients].get(key)
|
| 77 |
+
let dispatcher = result && result.dispatcher
|
| 78 |
+
if (!dispatcher) {
|
| 79 |
+
const closeClientIfUnused = (connected) => {
|
| 80 |
+
const result = this[kClients].get(key)
|
| 81 |
+
if (result) {
|
| 82 |
+
if (connected) result.count -= 1
|
| 83 |
+
if (result.count <= 0) {
|
| 84 |
+
this[kClients].delete(key)
|
| 85 |
+
result.dispatcher.close()
|
| 86 |
+
}
|
| 87 |
+
}
|
| 88 |
+
}
|
| 89 |
+
dispatcher = this[kFactory](opts.origin, this[kOptions])
|
| 90 |
+
.on('drain', this[kOnDrain])
|
| 91 |
+
.on('connect', (origin, targets) => {
|
| 92 |
+
const result = this[kClients].get(key)
|
| 93 |
+
if (result) {
|
| 94 |
+
result.count += 1
|
| 95 |
+
}
|
| 96 |
+
this[kOnConnect](origin, targets)
|
| 97 |
+
})
|
| 98 |
+
.on('disconnect', (origin, targets, err) => {
|
| 99 |
+
closeClientIfUnused(true)
|
| 100 |
+
this[kOnDisconnect](origin, targets, err)
|
| 101 |
+
})
|
| 102 |
+
.on('connectionError', (origin, targets, err) => {
|
| 103 |
+
closeClientIfUnused(false)
|
| 104 |
+
this[kOnConnectionError](origin, targets, err)
|
| 105 |
+
})
|
| 106 |
+
|
| 107 |
+
this[kClients].set(key, { count: 0, dispatcher })
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
return dispatcher.dispatch(opts, handler)
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
async [kClose] () {
|
| 114 |
+
const closePromises = []
|
| 115 |
+
for (const { dispatcher } of this[kClients].values()) {
|
| 116 |
+
closePromises.push(dispatcher.close())
|
| 117 |
+
}
|
| 118 |
+
this[kClients].clear()
|
| 119 |
+
|
| 120 |
+
await Promise.all(closePromises)
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
async [kDestroy] (err) {
|
| 124 |
+
const destroyPromises = []
|
| 125 |
+
for (const { dispatcher } of this[kClients].values()) {
|
| 126 |
+
destroyPromises.push(dispatcher.destroy(err))
|
| 127 |
+
}
|
| 128 |
+
this[kClients].clear()
|
| 129 |
+
|
| 130 |
+
await Promise.all(destroyPromises)
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
get stats () {
|
| 134 |
+
const allClientStats = {}
|
| 135 |
+
for (const { dispatcher } of this[kClients].values()) {
|
| 136 |
+
if (dispatcher.stats) {
|
| 137 |
+
allClientStats[dispatcher[kUrl].origin] = dispatcher.stats
|
| 138 |
+
}
|
| 139 |
+
}
|
| 140 |
+
return allClientStats
|
| 141 |
+
}
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
module.exports = Agent
|
platform/aiml/elizabeth/e-1-first_session/claude-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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'use strict'
|
| 2 |
+
|
| 3 |
+
const {
|
| 4 |
+
BalancedPoolMissingUpstreamError,
|
| 5 |
+
InvalidArgumentError
|
| 6 |
+
} = require('../core/errors')
|
| 7 |
+
const {
|
| 8 |
+
PoolBase,
|
| 9 |
+
kClients,
|
| 10 |
+
kNeedDrain,
|
| 11 |
+
kAddClient,
|
| 12 |
+
kRemoveClient,
|
| 13 |
+
kGetDispatcher
|
| 14 |
+
} = require('./pool-base')
|
| 15 |
+
const Pool = require('./pool')
|
| 16 |
+
const { kUrl } = require('../core/symbols')
|
| 17 |
+
const { parseOrigin } = require('../core/util')
|
| 18 |
+
const kFactory = Symbol('factory')
|
| 19 |
+
|
| 20 |
+
const kOptions = Symbol('options')
|
| 21 |
+
const kGreatestCommonDivisor = Symbol('kGreatestCommonDivisor')
|
| 22 |
+
const kCurrentWeight = Symbol('kCurrentWeight')
|
| 23 |
+
const kIndex = Symbol('kIndex')
|
| 24 |
+
const kWeight = Symbol('kWeight')
|
| 25 |
+
const kMaxWeightPerServer = Symbol('kMaxWeightPerServer')
|
| 26 |
+
const kErrorPenalty = Symbol('kErrorPenalty')
|
| 27 |
+
|
| 28 |
+
/**
|
| 29 |
+
* Calculate the greatest common divisor of two numbers by
|
| 30 |
+
* using the Euclidean algorithm.
|
| 31 |
+
*
|
| 32 |
+
* @param {number} a
|
| 33 |
+
* @param {number} b
|
| 34 |
+
* @returns {number}
|
| 35 |
+
*/
|
| 36 |
+
function getGreatestCommonDivisor (a, b) {
|
| 37 |
+
if (a === 0) return b
|
| 38 |
+
|
| 39 |
+
while (b !== 0) {
|
| 40 |
+
const t = b
|
| 41 |
+
b = a % b
|
| 42 |
+
a = t
|
| 43 |
+
}
|
| 44 |
+
return a
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
function defaultFactory (origin, opts) {
|
| 48 |
+
return new Pool(origin, opts)
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
class BalancedPool extends PoolBase {
|
| 52 |
+
constructor (upstreams = [], { factory = defaultFactory, ...opts } = {}) {
|
| 53 |
+
if (typeof factory !== 'function') {
|
| 54 |
+
throw new InvalidArgumentError('factory must be a function.')
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
super()
|
| 58 |
+
|
| 59 |
+
this[kOptions] = opts
|
| 60 |
+
this[kIndex] = -1
|
| 61 |
+
this[kCurrentWeight] = 0
|
| 62 |
+
|
| 63 |
+
this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100
|
| 64 |
+
this[kErrorPenalty] = this[kOptions].errorPenalty || 15
|
| 65 |
+
|
| 66 |
+
if (!Array.isArray(upstreams)) {
|
| 67 |
+
upstreams = [upstreams]
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
this[kFactory] = factory
|
| 71 |
+
|
| 72 |
+
for (const upstream of upstreams) {
|
| 73 |
+
this.addUpstream(upstream)
|
| 74 |
+
}
|
| 75 |
+
this._updateBalancedPoolStats()
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
addUpstream (upstream) {
|
| 79 |
+
const upstreamOrigin = parseOrigin(upstream).origin
|
| 80 |
+
|
| 81 |
+
if (this[kClients].find((pool) => (
|
| 82 |
+
pool[kUrl].origin === upstreamOrigin &&
|
| 83 |
+
pool.closed !== true &&
|
| 84 |
+
pool.destroyed !== true
|
| 85 |
+
))) {
|
| 86 |
+
return this
|
| 87 |
+
}
|
| 88 |
+
const pool = this[kFactory](upstreamOrigin, Object.assign({}, this[kOptions]))
|
| 89 |
+
|
| 90 |
+
this[kAddClient](pool)
|
| 91 |
+
pool.on('connect', () => {
|
| 92 |
+
pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty])
|
| 93 |
+
})
|
| 94 |
+
|
| 95 |
+
pool.on('connectionError', () => {
|
| 96 |
+
pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty])
|
| 97 |
+
this._updateBalancedPoolStats()
|
| 98 |
+
})
|
| 99 |
+
|
| 100 |
+
pool.on('disconnect', (...args) => {
|
| 101 |
+
const err = args[2]
|
| 102 |
+
if (err && err.code === 'UND_ERR_SOCKET') {
|
| 103 |
+
// decrease the weight of the pool.
|
| 104 |
+
pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty])
|
| 105 |
+
this._updateBalancedPoolStats()
|
| 106 |
+
}
|
| 107 |
+
})
|
| 108 |
+
|
| 109 |
+
for (const client of this[kClients]) {
|
| 110 |
+
client[kWeight] = this[kMaxWeightPerServer]
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
this._updateBalancedPoolStats()
|
| 114 |
+
|
| 115 |
+
return this
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
_updateBalancedPoolStats () {
|
| 119 |
+
let result = 0
|
| 120 |
+
for (let i = 0; i < this[kClients].length; i++) {
|
| 121 |
+
result = getGreatestCommonDivisor(this[kClients][i][kWeight], result)
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
this[kGreatestCommonDivisor] = result
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
removeUpstream (upstream) {
|
| 128 |
+
const upstreamOrigin = parseOrigin(upstream).origin
|
| 129 |
+
|
| 130 |
+
const pool = this[kClients].find((pool) => (
|
| 131 |
+
pool[kUrl].origin === upstreamOrigin &&
|
| 132 |
+
pool.closed !== true &&
|
| 133 |
+
pool.destroyed !== true
|
| 134 |
+
))
|
| 135 |
+
|
| 136 |
+
if (pool) {
|
| 137 |
+
this[kRemoveClient](pool)
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
return this
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
get upstreams () {
|
| 144 |
+
return this[kClients]
|
| 145 |
+
.filter(dispatcher => dispatcher.closed !== true && dispatcher.destroyed !== true)
|
| 146 |
+
.map((p) => p[kUrl].origin)
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
[kGetDispatcher] () {
|
| 150 |
+
// We validate that pools is greater than 0,
|
| 151 |
+
// otherwise we would have to wait until an upstream
|
| 152 |
+
// is added, which might never happen.
|
| 153 |
+
if (this[kClients].length === 0) {
|
| 154 |
+
throw new BalancedPoolMissingUpstreamError()
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
const dispatcher = this[kClients].find(dispatcher => (
|
| 158 |
+
!dispatcher[kNeedDrain] &&
|
| 159 |
+
dispatcher.closed !== true &&
|
| 160 |
+
dispatcher.destroyed !== true
|
| 161 |
+
))
|
| 162 |
+
|
| 163 |
+
if (!dispatcher) {
|
| 164 |
+
return
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
const allClientsBusy = this[kClients].map(pool => pool[kNeedDrain]).reduce((a, b) => a && b, true)
|
| 168 |
+
|
| 169 |
+
if (allClientsBusy) {
|
| 170 |
+
return
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
let counter = 0
|
| 174 |
+
|
| 175 |
+
let maxWeightIndex = this[kClients].findIndex(pool => !pool[kNeedDrain])
|
| 176 |
+
|
| 177 |
+
while (counter++ < this[kClients].length) {
|
| 178 |
+
this[kIndex] = (this[kIndex] + 1) % this[kClients].length
|
| 179 |
+
const pool = this[kClients][this[kIndex]]
|
| 180 |
+
|
| 181 |
+
// find pool index with the largest weight
|
| 182 |
+
if (pool[kWeight] > this[kClients][maxWeightIndex][kWeight] && !pool[kNeedDrain]) {
|
| 183 |
+
maxWeightIndex = this[kIndex]
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
// decrease the current weight every `this[kClients].length`.
|
| 187 |
+
if (this[kIndex] === 0) {
|
| 188 |
+
// Set the current weight to the next lower weight.
|
| 189 |
+
this[kCurrentWeight] = this[kCurrentWeight] - this[kGreatestCommonDivisor]
|
| 190 |
+
|
| 191 |
+
if (this[kCurrentWeight] <= 0) {
|
| 192 |
+
this[kCurrentWeight] = this[kMaxWeightPerServer]
|
| 193 |
+
}
|
| 194 |
+
}
|
| 195 |
+
if (pool[kWeight] >= this[kCurrentWeight] && (!pool[kNeedDrain])) {
|
| 196 |
+
return pool
|
| 197 |
+
}
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight]
|
| 201 |
+
this[kIndex] = maxWeightIndex
|
| 202 |
+
return this[kClients][maxWeightIndex]
|
| 203 |
+
}
|
| 204 |
+
}
|
| 205 |
+
|
| 206 |
+
module.exports = BalancedPool
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/dispatcher/client-h1.js
ADDED
|
@@ -0,0 +1,1606 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
| 4 |
+
|
| 5 |
+
const assert = require('node:assert')
|
| 6 |
+
const util = require('../core/util.js')
|
| 7 |
+
const { channels } = require('../core/diagnostics.js')
|
| 8 |
+
const timers = require('../util/timers.js')
|
| 9 |
+
const {
|
| 10 |
+
RequestContentLengthMismatchError,
|
| 11 |
+
ResponseContentLengthMismatchError,
|
| 12 |
+
RequestAbortedError,
|
| 13 |
+
HeadersTimeoutError,
|
| 14 |
+
HeadersOverflowError,
|
| 15 |
+
SocketError,
|
| 16 |
+
InformationalError,
|
| 17 |
+
BodyTimeoutError,
|
| 18 |
+
HTTPParserError,
|
| 19 |
+
ResponseExceededMaxSizeError
|
| 20 |
+
} = require('../core/errors.js')
|
| 21 |
+
const {
|
| 22 |
+
kUrl,
|
| 23 |
+
kReset,
|
| 24 |
+
kClient,
|
| 25 |
+
kParser,
|
| 26 |
+
kBlocking,
|
| 27 |
+
kRunning,
|
| 28 |
+
kPending,
|
| 29 |
+
kSize,
|
| 30 |
+
kWriting,
|
| 31 |
+
kQueue,
|
| 32 |
+
kNoRef,
|
| 33 |
+
kKeepAliveDefaultTimeout,
|
| 34 |
+
kHostHeader,
|
| 35 |
+
kPendingIdx,
|
| 36 |
+
kRunningIdx,
|
| 37 |
+
kError,
|
| 38 |
+
kPipelining,
|
| 39 |
+
kSocket,
|
| 40 |
+
kKeepAliveTimeoutValue,
|
| 41 |
+
kMaxHeadersSize,
|
| 42 |
+
kKeepAliveMaxTimeout,
|
| 43 |
+
kKeepAliveTimeoutThreshold,
|
| 44 |
+
kHeadersTimeout,
|
| 45 |
+
kBodyTimeout,
|
| 46 |
+
kStrictContentLength,
|
| 47 |
+
kMaxRequests,
|
| 48 |
+
kCounter,
|
| 49 |
+
kMaxResponseSize,
|
| 50 |
+
kOnError,
|
| 51 |
+
kResume,
|
| 52 |
+
kHTTPContext,
|
| 53 |
+
kClosed
|
| 54 |
+
} = require('../core/symbols.js')
|
| 55 |
+
|
| 56 |
+
const constants = require('../llhttp/constants.js')
|
| 57 |
+
const EMPTY_BUF = Buffer.alloc(0)
|
| 58 |
+
const FastBuffer = Buffer[Symbol.species]
|
| 59 |
+
const removeAllListeners = util.removeAllListeners
|
| 60 |
+
|
| 61 |
+
let extractBody
|
| 62 |
+
|
| 63 |
+
function lazyllhttp () {
|
| 64 |
+
const llhttpWasmData = process.env.JEST_WORKER_ID ? require('../llhttp/llhttp-wasm.js') : undefined
|
| 65 |
+
|
| 66 |
+
let mod
|
| 67 |
+
try {
|
| 68 |
+
mod = new WebAssembly.Module(require('../llhttp/llhttp_simd-wasm.js'))
|
| 69 |
+
} catch {
|
| 70 |
+
/* istanbul ignore next */
|
| 71 |
+
|
| 72 |
+
// We could check if the error was caused by the simd option not
|
| 73 |
+
// being enabled, but the occurring of this other error
|
| 74 |
+
// * https://github.com/emscripten-core/emscripten/issues/11495
|
| 75 |
+
// got me to remove that check to avoid breaking Node 12.
|
| 76 |
+
mod = new WebAssembly.Module(llhttpWasmData || require('../llhttp/llhttp-wasm.js'))
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
return new WebAssembly.Instance(mod, {
|
| 80 |
+
env: {
|
| 81 |
+
/**
|
| 82 |
+
* @param {number} p
|
| 83 |
+
* @param {number} at
|
| 84 |
+
* @param {number} len
|
| 85 |
+
* @returns {number}
|
| 86 |
+
*/
|
| 87 |
+
wasm_on_url: (p, at, len) => {
|
| 88 |
+
/* istanbul ignore next */
|
| 89 |
+
return 0
|
| 90 |
+
},
|
| 91 |
+
/**
|
| 92 |
+
* @param {number} p
|
| 93 |
+
* @param {number} at
|
| 94 |
+
* @param {number} len
|
| 95 |
+
* @returns {number}
|
| 96 |
+
*/
|
| 97 |
+
wasm_on_status: (p, at, len) => {
|
| 98 |
+
assert(currentParser.ptr === p)
|
| 99 |
+
const start = at - currentBufferPtr + currentBufferRef.byteOffset
|
| 100 |
+
return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len))
|
| 101 |
+
},
|
| 102 |
+
/**
|
| 103 |
+
* @param {number} p
|
| 104 |
+
* @returns {number}
|
| 105 |
+
*/
|
| 106 |
+
wasm_on_message_begin: (p) => {
|
| 107 |
+
assert(currentParser.ptr === p)
|
| 108 |
+
return currentParser.onMessageBegin()
|
| 109 |
+
},
|
| 110 |
+
/**
|
| 111 |
+
* @param {number} p
|
| 112 |
+
* @param {number} at
|
| 113 |
+
* @param {number} len
|
| 114 |
+
* @returns {number}
|
| 115 |
+
*/
|
| 116 |
+
wasm_on_header_field: (p, at, len) => {
|
| 117 |
+
assert(currentParser.ptr === p)
|
| 118 |
+
const start = at - currentBufferPtr + currentBufferRef.byteOffset
|
| 119 |
+
return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len))
|
| 120 |
+
},
|
| 121 |
+
/**
|
| 122 |
+
* @param {number} p
|
| 123 |
+
* @param {number} at
|
| 124 |
+
* @param {number} len
|
| 125 |
+
* @returns {number}
|
| 126 |
+
*/
|
| 127 |
+
wasm_on_header_value: (p, at, len) => {
|
| 128 |
+
assert(currentParser.ptr === p)
|
| 129 |
+
const start = at - currentBufferPtr + currentBufferRef.byteOffset
|
| 130 |
+
return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len))
|
| 131 |
+
},
|
| 132 |
+
/**
|
| 133 |
+
* @param {number} p
|
| 134 |
+
* @param {number} statusCode
|
| 135 |
+
* @param {0|1} upgrade
|
| 136 |
+
* @param {0|1} shouldKeepAlive
|
| 137 |
+
* @returns {number}
|
| 138 |
+
*/
|
| 139 |
+
wasm_on_headers_complete: (p, statusCode, upgrade, shouldKeepAlive) => {
|
| 140 |
+
assert(currentParser.ptr === p)
|
| 141 |
+
return currentParser.onHeadersComplete(statusCode, upgrade === 1, shouldKeepAlive === 1)
|
| 142 |
+
},
|
| 143 |
+
/**
|
| 144 |
+
* @param {number} p
|
| 145 |
+
* @param {number} at
|
| 146 |
+
* @param {number} len
|
| 147 |
+
* @returns {number}
|
| 148 |
+
*/
|
| 149 |
+
wasm_on_body: (p, at, len) => {
|
| 150 |
+
assert(currentParser.ptr === p)
|
| 151 |
+
const start = at - currentBufferPtr + currentBufferRef.byteOffset
|
| 152 |
+
return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len))
|
| 153 |
+
},
|
| 154 |
+
/**
|
| 155 |
+
* @param {number} p
|
| 156 |
+
* @returns {number}
|
| 157 |
+
*/
|
| 158 |
+
wasm_on_message_complete: (p) => {
|
| 159 |
+
assert(currentParser.ptr === p)
|
| 160 |
+
return currentParser.onMessageComplete()
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
}
|
| 164 |
+
})
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
let llhttpInstance = null
|
| 168 |
+
|
| 169 |
+
/**
|
| 170 |
+
* @type {Parser|null}
|
| 171 |
+
*/
|
| 172 |
+
let currentParser = null
|
| 173 |
+
let currentBufferRef = null
|
| 174 |
+
/**
|
| 175 |
+
* @type {number}
|
| 176 |
+
*/
|
| 177 |
+
let currentBufferSize = 0
|
| 178 |
+
let currentBufferPtr = null
|
| 179 |
+
|
| 180 |
+
const USE_NATIVE_TIMER = 0
|
| 181 |
+
const USE_FAST_TIMER = 1
|
| 182 |
+
|
| 183 |
+
// Use fast timers for headers and body to take eventual event loop
|
| 184 |
+
// latency into account.
|
| 185 |
+
const TIMEOUT_HEADERS = 2 | USE_FAST_TIMER
|
| 186 |
+
const TIMEOUT_BODY = 4 | USE_FAST_TIMER
|
| 187 |
+
|
| 188 |
+
// Use native timers to ignore event loop latency for keep-alive
|
| 189 |
+
// handling.
|
| 190 |
+
const TIMEOUT_KEEP_ALIVE = 8 | USE_NATIVE_TIMER
|
| 191 |
+
|
| 192 |
+
class Parser {
|
| 193 |
+
/**
|
| 194 |
+
* @param {import('./client.js')} client
|
| 195 |
+
* @param {import('net').Socket} socket
|
| 196 |
+
* @param {*} llhttp
|
| 197 |
+
*/
|
| 198 |
+
constructor (client, socket, { exports }) {
|
| 199 |
+
this.llhttp = exports
|
| 200 |
+
this.ptr = this.llhttp.llhttp_alloc(constants.TYPE.RESPONSE)
|
| 201 |
+
this.client = client
|
| 202 |
+
/**
|
| 203 |
+
* @type {import('net').Socket}
|
| 204 |
+
*/
|
| 205 |
+
this.socket = socket
|
| 206 |
+
this.timeout = null
|
| 207 |
+
this.timeoutValue = null
|
| 208 |
+
this.timeoutType = null
|
| 209 |
+
this.statusCode = 0
|
| 210 |
+
this.statusText = ''
|
| 211 |
+
this.upgrade = false
|
| 212 |
+
this.headers = []
|
| 213 |
+
this.headersSize = 0
|
| 214 |
+
this.headersMaxSize = client[kMaxHeadersSize]
|
| 215 |
+
this.shouldKeepAlive = false
|
| 216 |
+
this.paused = false
|
| 217 |
+
this.resume = this.resume.bind(this)
|
| 218 |
+
|
| 219 |
+
this.bytesRead = 0
|
| 220 |
+
|
| 221 |
+
this.keepAlive = ''
|
| 222 |
+
this.contentLength = ''
|
| 223 |
+
this.connection = ''
|
| 224 |
+
this.maxResponseSize = client[kMaxResponseSize]
|
| 225 |
+
}
|
| 226 |
+
|
| 227 |
+
setTimeout (delay, type) {
|
| 228 |
+
// If the existing timer and the new timer are of different timer type
|
| 229 |
+
// (fast or native) or have different delay, we need to clear the existing
|
| 230 |
+
// timer and set a new one.
|
| 231 |
+
if (
|
| 232 |
+
delay !== this.timeoutValue ||
|
| 233 |
+
(type & USE_FAST_TIMER) ^ (this.timeoutType & USE_FAST_TIMER)
|
| 234 |
+
) {
|
| 235 |
+
// If a timeout is already set, clear it with clearTimeout of the fast
|
| 236 |
+
// timer implementation, as it can clear fast and native timers.
|
| 237 |
+
if (this.timeout) {
|
| 238 |
+
timers.clearTimeout(this.timeout)
|
| 239 |
+
this.timeout = null
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
if (delay) {
|
| 243 |
+
if (type & USE_FAST_TIMER) {
|
| 244 |
+
this.timeout = timers.setFastTimeout(onParserTimeout, delay, new WeakRef(this))
|
| 245 |
+
} else {
|
| 246 |
+
this.timeout = setTimeout(onParserTimeout, delay, new WeakRef(this))
|
| 247 |
+
this.timeout?.unref()
|
| 248 |
+
}
|
| 249 |
+
}
|
| 250 |
+
|
| 251 |
+
this.timeoutValue = delay
|
| 252 |
+
} else if (this.timeout) {
|
| 253 |
+
// istanbul ignore else: only for jest
|
| 254 |
+
if (this.timeout.refresh) {
|
| 255 |
+
this.timeout.refresh()
|
| 256 |
+
}
|
| 257 |
+
}
|
| 258 |
+
|
| 259 |
+
this.timeoutType = type
|
| 260 |
+
}
|
| 261 |
+
|
| 262 |
+
resume () {
|
| 263 |
+
if (this.socket.destroyed || !this.paused) {
|
| 264 |
+
return
|
| 265 |
+
}
|
| 266 |
+
|
| 267 |
+
assert(this.ptr != null)
|
| 268 |
+
assert(currentParser === null)
|
| 269 |
+
|
| 270 |
+
this.llhttp.llhttp_resume(this.ptr)
|
| 271 |
+
|
| 272 |
+
assert(this.timeoutType === TIMEOUT_BODY)
|
| 273 |
+
if (this.timeout) {
|
| 274 |
+
// istanbul ignore else: only for jest
|
| 275 |
+
if (this.timeout.refresh) {
|
| 276 |
+
this.timeout.refresh()
|
| 277 |
+
}
|
| 278 |
+
}
|
| 279 |
+
|
| 280 |
+
this.paused = false
|
| 281 |
+
this.execute(this.socket.read() || EMPTY_BUF) // Flush parser.
|
| 282 |
+
this.readMore()
|
| 283 |
+
}
|
| 284 |
+
|
| 285 |
+
readMore () {
|
| 286 |
+
while (!this.paused && this.ptr) {
|
| 287 |
+
const chunk = this.socket.read()
|
| 288 |
+
if (chunk === null) {
|
| 289 |
+
break
|
| 290 |
+
}
|
| 291 |
+
this.execute(chunk)
|
| 292 |
+
}
|
| 293 |
+
}
|
| 294 |
+
|
| 295 |
+
/**
|
| 296 |
+
* @param {Buffer} chunk
|
| 297 |
+
*/
|
| 298 |
+
execute (chunk) {
|
| 299 |
+
assert(currentParser === null)
|
| 300 |
+
assert(this.ptr != null)
|
| 301 |
+
assert(!this.paused)
|
| 302 |
+
|
| 303 |
+
const { socket, llhttp } = this
|
| 304 |
+
|
| 305 |
+
// Allocate a new buffer if the current buffer is too small.
|
| 306 |
+
if (chunk.length > currentBufferSize) {
|
| 307 |
+
if (currentBufferPtr) {
|
| 308 |
+
llhttp.free(currentBufferPtr)
|
| 309 |
+
}
|
| 310 |
+
// Allocate a buffer that is a multiple of 4096 bytes.
|
| 311 |
+
currentBufferSize = Math.ceil(chunk.length / 4096) * 4096
|
| 312 |
+
currentBufferPtr = llhttp.malloc(currentBufferSize)
|
| 313 |
+
}
|
| 314 |
+
|
| 315 |
+
new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(chunk)
|
| 316 |
+
|
| 317 |
+
// Call `execute` on the wasm parser.
|
| 318 |
+
// We pass the `llhttp_parser` pointer address, the pointer address of buffer view data,
|
| 319 |
+
// and finally the length of bytes to parse.
|
| 320 |
+
// The return value is an error code or `constants.ERROR.OK`.
|
| 321 |
+
try {
|
| 322 |
+
let ret
|
| 323 |
+
|
| 324 |
+
try {
|
| 325 |
+
currentBufferRef = chunk
|
| 326 |
+
currentParser = this
|
| 327 |
+
ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, chunk.length)
|
| 328 |
+
/* eslint-disable-next-line no-useless-catch */
|
| 329 |
+
} catch (err) {
|
| 330 |
+
/* istanbul ignore next: difficult to make a test case for */
|
| 331 |
+
throw err
|
| 332 |
+
} finally {
|
| 333 |
+
currentParser = null
|
| 334 |
+
currentBufferRef = null
|
| 335 |
+
}
|
| 336 |
+
|
| 337 |
+
if (ret !== constants.ERROR.OK) {
|
| 338 |
+
const data = chunk.subarray(llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr)
|
| 339 |
+
|
| 340 |
+
if (ret === constants.ERROR.PAUSED_UPGRADE) {
|
| 341 |
+
this.onUpgrade(data)
|
| 342 |
+
} else if (ret === constants.ERROR.PAUSED) {
|
| 343 |
+
this.paused = true
|
| 344 |
+
socket.unshift(data)
|
| 345 |
+
} else {
|
| 346 |
+
const ptr = llhttp.llhttp_get_error_reason(this.ptr)
|
| 347 |
+
let message = ''
|
| 348 |
+
/* istanbul ignore else: difficult to make a test case for */
|
| 349 |
+
if (ptr) {
|
| 350 |
+
const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0)
|
| 351 |
+
message =
|
| 352 |
+
'Response does not match the HTTP/1.1 protocol (' +
|
| 353 |
+
Buffer.from(llhttp.memory.buffer, ptr, len).toString() +
|
| 354 |
+
')'
|
| 355 |
+
}
|
| 356 |
+
throw new HTTPParserError(message, constants.ERROR[ret], data)
|
| 357 |
+
}
|
| 358 |
+
}
|
| 359 |
+
} catch (err) {
|
| 360 |
+
util.destroy(socket, err)
|
| 361 |
+
}
|
| 362 |
+
}
|
| 363 |
+
|
| 364 |
+
destroy () {
|
| 365 |
+
assert(currentParser === null)
|
| 366 |
+
assert(this.ptr != null)
|
| 367 |
+
|
| 368 |
+
this.llhttp.llhttp_free(this.ptr)
|
| 369 |
+
this.ptr = null
|
| 370 |
+
|
| 371 |
+
this.timeout && timers.clearTimeout(this.timeout)
|
| 372 |
+
this.timeout = null
|
| 373 |
+
this.timeoutValue = null
|
| 374 |
+
this.timeoutType = null
|
| 375 |
+
|
| 376 |
+
this.paused = false
|
| 377 |
+
}
|
| 378 |
+
|
| 379 |
+
/**
|
| 380 |
+
* @param {Buffer} buf
|
| 381 |
+
* @returns {0}
|
| 382 |
+
*/
|
| 383 |
+
onStatus (buf) {
|
| 384 |
+
this.statusText = buf.toString()
|
| 385 |
+
return 0
|
| 386 |
+
}
|
| 387 |
+
|
| 388 |
+
/**
|
| 389 |
+
* @returns {0|-1}
|
| 390 |
+
*/
|
| 391 |
+
onMessageBegin () {
|
| 392 |
+
const { socket, client } = this
|
| 393 |
+
|
| 394 |
+
/* istanbul ignore next: difficult to make a test case for */
|
| 395 |
+
if (socket.destroyed) {
|
| 396 |
+
return -1
|
| 397 |
+
}
|
| 398 |
+
|
| 399 |
+
const request = client[kQueue][client[kRunningIdx]]
|
| 400 |
+
if (!request) {
|
| 401 |
+
return -1
|
| 402 |
+
}
|
| 403 |
+
request.onResponseStarted()
|
| 404 |
+
|
| 405 |
+
return 0
|
| 406 |
+
}
|
| 407 |
+
|
| 408 |
+
/**
|
| 409 |
+
* @param {Buffer} buf
|
| 410 |
+
* @returns {number}
|
| 411 |
+
*/
|
| 412 |
+
onHeaderField (buf) {
|
| 413 |
+
const len = this.headers.length
|
| 414 |
+
|
| 415 |
+
if ((len & 1) === 0) {
|
| 416 |
+
this.headers.push(buf)
|
| 417 |
+
} else {
|
| 418 |
+
this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf])
|
| 419 |
+
}
|
| 420 |
+
|
| 421 |
+
this.trackHeader(buf.length)
|
| 422 |
+
|
| 423 |
+
return 0
|
| 424 |
+
}
|
| 425 |
+
|
| 426 |
+
/**
|
| 427 |
+
* @param {Buffer} buf
|
| 428 |
+
* @returns {number}
|
| 429 |
+
*/
|
| 430 |
+
onHeaderValue (buf) {
|
| 431 |
+
let len = this.headers.length
|
| 432 |
+
|
| 433 |
+
if ((len & 1) === 1) {
|
| 434 |
+
this.headers.push(buf)
|
| 435 |
+
len += 1
|
| 436 |
+
} else {
|
| 437 |
+
this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf])
|
| 438 |
+
}
|
| 439 |
+
|
| 440 |
+
const key = this.headers[len - 2]
|
| 441 |
+
if (key.length === 10) {
|
| 442 |
+
const headerName = util.bufferToLowerCasedHeaderName(key)
|
| 443 |
+
if (headerName === 'keep-alive') {
|
| 444 |
+
this.keepAlive += buf.toString()
|
| 445 |
+
} else if (headerName === 'connection') {
|
| 446 |
+
this.connection += buf.toString()
|
| 447 |
+
}
|
| 448 |
+
} else if (key.length === 14 && util.bufferToLowerCasedHeaderName(key) === 'content-length') {
|
| 449 |
+
this.contentLength += buf.toString()
|
| 450 |
+
}
|
| 451 |
+
|
| 452 |
+
this.trackHeader(buf.length)
|
| 453 |
+
|
| 454 |
+
return 0
|
| 455 |
+
}
|
| 456 |
+
|
| 457 |
+
/**
|
| 458 |
+
* @param {number} len
|
| 459 |
+
*/
|
| 460 |
+
trackHeader (len) {
|
| 461 |
+
this.headersSize += len
|
| 462 |
+
if (this.headersSize >= this.headersMaxSize) {
|
| 463 |
+
util.destroy(this.socket, new HeadersOverflowError())
|
| 464 |
+
}
|
| 465 |
+
}
|
| 466 |
+
|
| 467 |
+
/**
|
| 468 |
+
* @param {Buffer} head
|
| 469 |
+
*/
|
| 470 |
+
onUpgrade (head) {
|
| 471 |
+
const { upgrade, client, socket, headers, statusCode } = this
|
| 472 |
+
|
| 473 |
+
assert(upgrade)
|
| 474 |
+
assert(client[kSocket] === socket)
|
| 475 |
+
assert(!socket.destroyed)
|
| 476 |
+
assert(!this.paused)
|
| 477 |
+
assert((headers.length & 1) === 0)
|
| 478 |
+
|
| 479 |
+
const request = client[kQueue][client[kRunningIdx]]
|
| 480 |
+
assert(request)
|
| 481 |
+
assert(request.upgrade || request.method === 'CONNECT')
|
| 482 |
+
|
| 483 |
+
this.statusCode = 0
|
| 484 |
+
this.statusText = ''
|
| 485 |
+
this.shouldKeepAlive = false
|
| 486 |
+
|
| 487 |
+
this.headers = []
|
| 488 |
+
this.headersSize = 0
|
| 489 |
+
|
| 490 |
+
socket.unshift(head)
|
| 491 |
+
|
| 492 |
+
socket[kParser].destroy()
|
| 493 |
+
socket[kParser] = null
|
| 494 |
+
|
| 495 |
+
socket[kClient] = null
|
| 496 |
+
socket[kError] = null
|
| 497 |
+
|
| 498 |
+
removeAllListeners(socket)
|
| 499 |
+
|
| 500 |
+
client[kSocket] = null
|
| 501 |
+
client[kHTTPContext] = null // TODO (fix): This is hacky...
|
| 502 |
+
client[kQueue][client[kRunningIdx]++] = null
|
| 503 |
+
client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade'))
|
| 504 |
+
|
| 505 |
+
try {
|
| 506 |
+
request.onUpgrade(statusCode, headers, socket)
|
| 507 |
+
} catch (err) {
|
| 508 |
+
util.destroy(socket, err)
|
| 509 |
+
}
|
| 510 |
+
|
| 511 |
+
client[kResume]()
|
| 512 |
+
}
|
| 513 |
+
|
| 514 |
+
/**
|
| 515 |
+
* @param {number} statusCode
|
| 516 |
+
* @param {boolean} upgrade
|
| 517 |
+
* @param {boolean} shouldKeepAlive
|
| 518 |
+
* @returns {number}
|
| 519 |
+
*/
|
| 520 |
+
onHeadersComplete (statusCode, upgrade, shouldKeepAlive) {
|
| 521 |
+
const { client, socket, headers, statusText } = this
|
| 522 |
+
|
| 523 |
+
/* istanbul ignore next: difficult to make a test case for */
|
| 524 |
+
if (socket.destroyed) {
|
| 525 |
+
return -1
|
| 526 |
+
}
|
| 527 |
+
|
| 528 |
+
const request = client[kQueue][client[kRunningIdx]]
|
| 529 |
+
|
| 530 |
+
/* istanbul ignore next: difficult to make a test case for */
|
| 531 |
+
if (!request) {
|
| 532 |
+
return -1
|
| 533 |
+
}
|
| 534 |
+
|
| 535 |
+
assert(!this.upgrade)
|
| 536 |
+
assert(this.statusCode < 200)
|
| 537 |
+
|
| 538 |
+
if (statusCode === 100) {
|
| 539 |
+
util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket)))
|
| 540 |
+
return -1
|
| 541 |
+
}
|
| 542 |
+
|
| 543 |
+
/* this can only happen if server is misbehaving */
|
| 544 |
+
if (upgrade && !request.upgrade) {
|
| 545 |
+
util.destroy(socket, new SocketError('bad upgrade', util.getSocketInfo(socket)))
|
| 546 |
+
return -1
|
| 547 |
+
}
|
| 548 |
+
|
| 549 |
+
assert(this.timeoutType === TIMEOUT_HEADERS)
|
| 550 |
+
|
| 551 |
+
this.statusCode = statusCode
|
| 552 |
+
this.shouldKeepAlive = (
|
| 553 |
+
shouldKeepAlive ||
|
| 554 |
+
// Override llhttp value which does not allow keepAlive for HEAD.
|
| 555 |
+
(request.method === 'HEAD' && !socket[kReset] && this.connection.toLowerCase() === 'keep-alive')
|
| 556 |
+
)
|
| 557 |
+
|
| 558 |
+
if (this.statusCode >= 200) {
|
| 559 |
+
const bodyTimeout = request.bodyTimeout != null
|
| 560 |
+
? request.bodyTimeout
|
| 561 |
+
: client[kBodyTimeout]
|
| 562 |
+
this.setTimeout(bodyTimeout, TIMEOUT_BODY)
|
| 563 |
+
} else if (this.timeout) {
|
| 564 |
+
// istanbul ignore else: only for jest
|
| 565 |
+
if (this.timeout.refresh) {
|
| 566 |
+
this.timeout.refresh()
|
| 567 |
+
}
|
| 568 |
+
}
|
| 569 |
+
|
| 570 |
+
if (request.method === 'CONNECT') {
|
| 571 |
+
assert(client[kRunning] === 1)
|
| 572 |
+
this.upgrade = true
|
| 573 |
+
return 2
|
| 574 |
+
}
|
| 575 |
+
|
| 576 |
+
if (upgrade) {
|
| 577 |
+
assert(client[kRunning] === 1)
|
| 578 |
+
this.upgrade = true
|
| 579 |
+
return 2
|
| 580 |
+
}
|
| 581 |
+
|
| 582 |
+
assert((this.headers.length & 1) === 0)
|
| 583 |
+
this.headers = []
|
| 584 |
+
this.headersSize = 0
|
| 585 |
+
|
| 586 |
+
if (this.shouldKeepAlive && client[kPipelining]) {
|
| 587 |
+
const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null
|
| 588 |
+
|
| 589 |
+
if (keepAliveTimeout != null) {
|
| 590 |
+
const timeout = Math.min(
|
| 591 |
+
keepAliveTimeout - client[kKeepAliveTimeoutThreshold],
|
| 592 |
+
client[kKeepAliveMaxTimeout]
|
| 593 |
+
)
|
| 594 |
+
if (timeout <= 0) {
|
| 595 |
+
socket[kReset] = true
|
| 596 |
+
} else {
|
| 597 |
+
client[kKeepAliveTimeoutValue] = timeout
|
| 598 |
+
}
|
| 599 |
+
} else {
|
| 600 |
+
client[kKeepAliveTimeoutValue] = client[kKeepAliveDefaultTimeout]
|
| 601 |
+
}
|
| 602 |
+
} else {
|
| 603 |
+
// Stop more requests from being dispatched.
|
| 604 |
+
socket[kReset] = true
|
| 605 |
+
}
|
| 606 |
+
|
| 607 |
+
const pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false
|
| 608 |
+
|
| 609 |
+
if (request.aborted) {
|
| 610 |
+
return -1
|
| 611 |
+
}
|
| 612 |
+
|
| 613 |
+
if (request.method === 'HEAD') {
|
| 614 |
+
return 1
|
| 615 |
+
}
|
| 616 |
+
|
| 617 |
+
if (statusCode < 200) {
|
| 618 |
+
return 1
|
| 619 |
+
}
|
| 620 |
+
|
| 621 |
+
if (socket[kBlocking]) {
|
| 622 |
+
socket[kBlocking] = false
|
| 623 |
+
client[kResume]()
|
| 624 |
+
}
|
| 625 |
+
|
| 626 |
+
return pause ? constants.ERROR.PAUSED : 0
|
| 627 |
+
}
|
| 628 |
+
|
| 629 |
+
/**
|
| 630 |
+
* @param {Buffer} buf
|
| 631 |
+
* @returns {number}
|
| 632 |
+
*/
|
| 633 |
+
onBody (buf) {
|
| 634 |
+
const { client, socket, statusCode, maxResponseSize } = this
|
| 635 |
+
|
| 636 |
+
if (socket.destroyed) {
|
| 637 |
+
return -1
|
| 638 |
+
}
|
| 639 |
+
|
| 640 |
+
const request = client[kQueue][client[kRunningIdx]]
|
| 641 |
+
assert(request)
|
| 642 |
+
|
| 643 |
+
assert(this.timeoutType === TIMEOUT_BODY)
|
| 644 |
+
if (this.timeout) {
|
| 645 |
+
// istanbul ignore else: only for jest
|
| 646 |
+
if (this.timeout.refresh) {
|
| 647 |
+
this.timeout.refresh()
|
| 648 |
+
}
|
| 649 |
+
}
|
| 650 |
+
|
| 651 |
+
assert(statusCode >= 200)
|
| 652 |
+
|
| 653 |
+
if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) {
|
| 654 |
+
util.destroy(socket, new ResponseExceededMaxSizeError())
|
| 655 |
+
return -1
|
| 656 |
+
}
|
| 657 |
+
|
| 658 |
+
this.bytesRead += buf.length
|
| 659 |
+
|
| 660 |
+
if (request.onData(buf) === false) {
|
| 661 |
+
return constants.ERROR.PAUSED
|
| 662 |
+
}
|
| 663 |
+
|
| 664 |
+
return 0
|
| 665 |
+
}
|
| 666 |
+
|
| 667 |
+
/**
|
| 668 |
+
* @returns {number}
|
| 669 |
+
*/
|
| 670 |
+
onMessageComplete () {
|
| 671 |
+
const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this
|
| 672 |
+
|
| 673 |
+
if (socket.destroyed && (!statusCode || shouldKeepAlive)) {
|
| 674 |
+
return -1
|
| 675 |
+
}
|
| 676 |
+
|
| 677 |
+
if (upgrade) {
|
| 678 |
+
return 0
|
| 679 |
+
}
|
| 680 |
+
|
| 681 |
+
assert(statusCode >= 100)
|
| 682 |
+
assert((this.headers.length & 1) === 0)
|
| 683 |
+
|
| 684 |
+
const request = client[kQueue][client[kRunningIdx]]
|
| 685 |
+
assert(request)
|
| 686 |
+
|
| 687 |
+
this.statusCode = 0
|
| 688 |
+
this.statusText = ''
|
| 689 |
+
this.bytesRead = 0
|
| 690 |
+
this.contentLength = ''
|
| 691 |
+
this.keepAlive = ''
|
| 692 |
+
this.connection = ''
|
| 693 |
+
|
| 694 |
+
this.headers = []
|
| 695 |
+
this.headersSize = 0
|
| 696 |
+
|
| 697 |
+
if (statusCode < 200) {
|
| 698 |
+
return 0
|
| 699 |
+
}
|
| 700 |
+
|
| 701 |
+
/* istanbul ignore next: should be handled by llhttp? */
|
| 702 |
+
if (request.method !== 'HEAD' && contentLength && bytesRead !== parseInt(contentLength, 10)) {
|
| 703 |
+
util.destroy(socket, new ResponseContentLengthMismatchError())
|
| 704 |
+
return -1
|
| 705 |
+
}
|
| 706 |
+
|
| 707 |
+
request.onComplete(headers)
|
| 708 |
+
|
| 709 |
+
client[kQueue][client[kRunningIdx]++] = null
|
| 710 |
+
|
| 711 |
+
if (socket[kWriting]) {
|
| 712 |
+
assert(client[kRunning] === 0)
|
| 713 |
+
// Response completed before request.
|
| 714 |
+
util.destroy(socket, new InformationalError('reset'))
|
| 715 |
+
return constants.ERROR.PAUSED
|
| 716 |
+
} else if (!shouldKeepAlive) {
|
| 717 |
+
util.destroy(socket, new InformationalError('reset'))
|
| 718 |
+
return constants.ERROR.PAUSED
|
| 719 |
+
} else if (socket[kReset] && client[kRunning] === 0) {
|
| 720 |
+
// Destroy socket once all requests have completed.
|
| 721 |
+
// The request at the tail of the pipeline is the one
|
| 722 |
+
// that requested reset and no further requests should
|
| 723 |
+
// have been queued since then.
|
| 724 |
+
util.destroy(socket, new InformationalError('reset'))
|
| 725 |
+
return constants.ERROR.PAUSED
|
| 726 |
+
} else if (client[kPipelining] == null || client[kPipelining] === 1) {
|
| 727 |
+
// We must wait a full event loop cycle to reuse this socket to make sure
|
| 728 |
+
// that non-spec compliant servers are not closing the connection even if they
|
| 729 |
+
// said they won't.
|
| 730 |
+
setImmediate(client[kResume])
|
| 731 |
+
} else {
|
| 732 |
+
client[kResume]()
|
| 733 |
+
}
|
| 734 |
+
|
| 735 |
+
return 0
|
| 736 |
+
}
|
| 737 |
+
}
|
| 738 |
+
|
| 739 |
+
function onParserTimeout (parser) {
|
| 740 |
+
const { socket, timeoutType, client, paused } = parser.deref()
|
| 741 |
+
|
| 742 |
+
/* istanbul ignore else */
|
| 743 |
+
if (timeoutType === TIMEOUT_HEADERS) {
|
| 744 |
+
if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) {
|
| 745 |
+
assert(!paused, 'cannot be paused while waiting for headers')
|
| 746 |
+
util.destroy(socket, new HeadersTimeoutError())
|
| 747 |
+
}
|
| 748 |
+
} else if (timeoutType === TIMEOUT_BODY) {
|
| 749 |
+
if (!paused) {
|
| 750 |
+
util.destroy(socket, new BodyTimeoutError())
|
| 751 |
+
}
|
| 752 |
+
} else if (timeoutType === TIMEOUT_KEEP_ALIVE) {
|
| 753 |
+
assert(client[kRunning] === 0 && client[kKeepAliveTimeoutValue])
|
| 754 |
+
util.destroy(socket, new InformationalError('socket idle timeout'))
|
| 755 |
+
}
|
| 756 |
+
}
|
| 757 |
+
|
| 758 |
+
/**
|
| 759 |
+
* @param {import ('./client.js')} client
|
| 760 |
+
* @param {import('net').Socket} socket
|
| 761 |
+
* @returns
|
| 762 |
+
*/
|
| 763 |
+
async function connectH1 (client, socket) {
|
| 764 |
+
client[kSocket] = socket
|
| 765 |
+
|
| 766 |
+
if (!llhttpInstance) {
|
| 767 |
+
llhttpInstance = lazyllhttp()
|
| 768 |
+
}
|
| 769 |
+
|
| 770 |
+
if (socket.errored) {
|
| 771 |
+
throw socket.errored
|
| 772 |
+
}
|
| 773 |
+
|
| 774 |
+
if (socket.destroyed) {
|
| 775 |
+
throw new SocketError('destroyed')
|
| 776 |
+
}
|
| 777 |
+
|
| 778 |
+
socket[kNoRef] = false
|
| 779 |
+
socket[kWriting] = false
|
| 780 |
+
socket[kReset] = false
|
| 781 |
+
socket[kBlocking] = false
|
| 782 |
+
socket[kParser] = new Parser(client, socket, llhttpInstance)
|
| 783 |
+
|
| 784 |
+
util.addListener(socket, 'error', onHttpSocketError)
|
| 785 |
+
util.addListener(socket, 'readable', onHttpSocketReadable)
|
| 786 |
+
util.addListener(socket, 'end', onHttpSocketEnd)
|
| 787 |
+
util.addListener(socket, 'close', onHttpSocketClose)
|
| 788 |
+
|
| 789 |
+
socket[kClosed] = false
|
| 790 |
+
socket.on('close', onSocketClose)
|
| 791 |
+
|
| 792 |
+
return {
|
| 793 |
+
version: 'h1',
|
| 794 |
+
defaultPipelining: 1,
|
| 795 |
+
write (request) {
|
| 796 |
+
return writeH1(client, request)
|
| 797 |
+
},
|
| 798 |
+
resume () {
|
| 799 |
+
resumeH1(client)
|
| 800 |
+
},
|
| 801 |
+
/**
|
| 802 |
+
* @param {Error|undefined} err
|
| 803 |
+
* @param {() => void} callback
|
| 804 |
+
*/
|
| 805 |
+
destroy (err, callback) {
|
| 806 |
+
if (socket[kClosed]) {
|
| 807 |
+
queueMicrotask(callback)
|
| 808 |
+
} else {
|
| 809 |
+
socket.on('close', callback)
|
| 810 |
+
socket.destroy(err)
|
| 811 |
+
}
|
| 812 |
+
},
|
| 813 |
+
/**
|
| 814 |
+
* @returns {boolean}
|
| 815 |
+
*/
|
| 816 |
+
get destroyed () {
|
| 817 |
+
return socket.destroyed
|
| 818 |
+
},
|
| 819 |
+
/**
|
| 820 |
+
* @param {import('../core/request.js')} request
|
| 821 |
+
* @returns {boolean}
|
| 822 |
+
*/
|
| 823 |
+
busy (request) {
|
| 824 |
+
if (socket[kWriting] || socket[kReset] || socket[kBlocking]) {
|
| 825 |
+
return true
|
| 826 |
+
}
|
| 827 |
+
|
| 828 |
+
if (request) {
|
| 829 |
+
if (client[kRunning] > 0 && !request.idempotent) {
|
| 830 |
+
// Non-idempotent request cannot be retried.
|
| 831 |
+
// Ensure that no other requests are inflight and
|
| 832 |
+
// could cause failure.
|
| 833 |
+
return true
|
| 834 |
+
}
|
| 835 |
+
|
| 836 |
+
if (client[kRunning] > 0 && (request.upgrade || request.method === 'CONNECT')) {
|
| 837 |
+
// Don't dispatch an upgrade until all preceding requests have completed.
|
| 838 |
+
// A misbehaving server might upgrade the connection before all pipelined
|
| 839 |
+
// request has completed.
|
| 840 |
+
return true
|
| 841 |
+
}
|
| 842 |
+
|
| 843 |
+
if (client[kRunning] > 0 && util.bodyLength(request.body) !== 0 &&
|
| 844 |
+
(util.isStream(request.body) || util.isAsyncIterable(request.body) || util.isFormDataLike(request.body))) {
|
| 845 |
+
// Request with stream or iterator body can error while other requests
|
| 846 |
+
// are inflight and indirectly error those as well.
|
| 847 |
+
// Ensure this doesn't happen by waiting for inflight
|
| 848 |
+
// to complete before dispatching.
|
| 849 |
+
|
| 850 |
+
// Request with stream or iterator body cannot be retried.
|
| 851 |
+
// Ensure that no other requests are inflight and
|
| 852 |
+
// could cause failure.
|
| 853 |
+
return true
|
| 854 |
+
}
|
| 855 |
+
}
|
| 856 |
+
|
| 857 |
+
return false
|
| 858 |
+
}
|
| 859 |
+
}
|
| 860 |
+
}
|
| 861 |
+
|
| 862 |
+
function onHttpSocketError (err) {
|
| 863 |
+
assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')
|
| 864 |
+
|
| 865 |
+
const parser = this[kParser]
|
| 866 |
+
|
| 867 |
+
// On Mac OS, we get an ECONNRESET even if there is a full body to be forwarded
|
| 868 |
+
// to the user.
|
| 869 |
+
if (err.code === 'ECONNRESET' && parser.statusCode && !parser.shouldKeepAlive) {
|
| 870 |
+
// We treat all incoming data so for as a valid response.
|
| 871 |
+
parser.onMessageComplete()
|
| 872 |
+
return
|
| 873 |
+
}
|
| 874 |
+
|
| 875 |
+
this[kError] = err
|
| 876 |
+
|
| 877 |
+
this[kClient][kOnError](err)
|
| 878 |
+
}
|
| 879 |
+
|
| 880 |
+
function onHttpSocketReadable () {
|
| 881 |
+
this[kParser]?.readMore()
|
| 882 |
+
}
|
| 883 |
+
|
| 884 |
+
function onHttpSocketEnd () {
|
| 885 |
+
const parser = this[kParser]
|
| 886 |
+
|
| 887 |
+
if (parser.statusCode && !parser.shouldKeepAlive) {
|
| 888 |
+
// We treat all incoming data so far as a valid response.
|
| 889 |
+
parser.onMessageComplete()
|
| 890 |
+
return
|
| 891 |
+
}
|
| 892 |
+
|
| 893 |
+
util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this)))
|
| 894 |
+
}
|
| 895 |
+
|
| 896 |
+
function onHttpSocketClose () {
|
| 897 |
+
const parser = this[kParser]
|
| 898 |
+
|
| 899 |
+
if (parser) {
|
| 900 |
+
if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) {
|
| 901 |
+
// We treat all incoming data so far as a valid response.
|
| 902 |
+
parser.onMessageComplete()
|
| 903 |
+
}
|
| 904 |
+
|
| 905 |
+
this[kParser].destroy()
|
| 906 |
+
this[kParser] = null
|
| 907 |
+
}
|
| 908 |
+
|
| 909 |
+
const err = this[kError] || new SocketError('closed', util.getSocketInfo(this))
|
| 910 |
+
|
| 911 |
+
const client = this[kClient]
|
| 912 |
+
|
| 913 |
+
client[kSocket] = null
|
| 914 |
+
client[kHTTPContext] = null // TODO (fix): This is hacky...
|
| 915 |
+
|
| 916 |
+
if (client.destroyed) {
|
| 917 |
+
assert(client[kPending] === 0)
|
| 918 |
+
|
| 919 |
+
// Fail entire queue.
|
| 920 |
+
const requests = client[kQueue].splice(client[kRunningIdx])
|
| 921 |
+
for (let i = 0; i < requests.length; i++) {
|
| 922 |
+
const request = requests[i]
|
| 923 |
+
util.errorRequest(client, request, err)
|
| 924 |
+
}
|
| 925 |
+
} else if (client[kRunning] > 0 && err.code !== 'UND_ERR_INFO') {
|
| 926 |
+
// Fail head of pipeline.
|
| 927 |
+
const request = client[kQueue][client[kRunningIdx]]
|
| 928 |
+
client[kQueue][client[kRunningIdx]++] = null
|
| 929 |
+
|
| 930 |
+
util.errorRequest(client, request, err)
|
| 931 |
+
}
|
| 932 |
+
|
| 933 |
+
client[kPendingIdx] = client[kRunningIdx]
|
| 934 |
+
|
| 935 |
+
assert(client[kRunning] === 0)
|
| 936 |
+
|
| 937 |
+
client.emit('disconnect', client[kUrl], [client], err)
|
| 938 |
+
|
| 939 |
+
client[kResume]()
|
| 940 |
+
}
|
| 941 |
+
|
| 942 |
+
function onSocketClose () {
|
| 943 |
+
this[kClosed] = true
|
| 944 |
+
}
|
| 945 |
+
|
| 946 |
+
/**
|
| 947 |
+
* @param {import('./client.js')} client
|
| 948 |
+
*/
|
| 949 |
+
function resumeH1 (client) {
|
| 950 |
+
const socket = client[kSocket]
|
| 951 |
+
|
| 952 |
+
if (socket && !socket.destroyed) {
|
| 953 |
+
if (client[kSize] === 0) {
|
| 954 |
+
if (!socket[kNoRef] && socket.unref) {
|
| 955 |
+
socket.unref()
|
| 956 |
+
socket[kNoRef] = true
|
| 957 |
+
}
|
| 958 |
+
} else if (socket[kNoRef] && socket.ref) {
|
| 959 |
+
socket.ref()
|
| 960 |
+
socket[kNoRef] = false
|
| 961 |
+
}
|
| 962 |
+
|
| 963 |
+
if (client[kSize] === 0) {
|
| 964 |
+
if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) {
|
| 965 |
+
socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE)
|
| 966 |
+
}
|
| 967 |
+
} else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) {
|
| 968 |
+
if (socket[kParser].timeoutType !== TIMEOUT_HEADERS) {
|
| 969 |
+
const request = client[kQueue][client[kRunningIdx]]
|
| 970 |
+
const headersTimeout = request.headersTimeout != null
|
| 971 |
+
? request.headersTimeout
|
| 972 |
+
: client[kHeadersTimeout]
|
| 973 |
+
socket[kParser].setTimeout(headersTimeout, TIMEOUT_HEADERS)
|
| 974 |
+
}
|
| 975 |
+
}
|
| 976 |
+
}
|
| 977 |
+
}
|
| 978 |
+
|
| 979 |
+
// https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2
|
| 980 |
+
function shouldSendContentLength (method) {
|
| 981 |
+
return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT'
|
| 982 |
+
}
|
| 983 |
+
|
| 984 |
+
/**
|
| 985 |
+
* @param {import('./client.js')} client
|
| 986 |
+
* @param {import('../core/request.js')} request
|
| 987 |
+
* @returns
|
| 988 |
+
*/
|
| 989 |
+
function writeH1 (client, request) {
|
| 990 |
+
const { method, path, host, upgrade, blocking, reset } = request
|
| 991 |
+
|
| 992 |
+
let { body, headers, contentLength } = request
|
| 993 |
+
|
| 994 |
+
// https://tools.ietf.org/html/rfc7231#section-4.3.1
|
| 995 |
+
// https://tools.ietf.org/html/rfc7231#section-4.3.2
|
| 996 |
+
// https://tools.ietf.org/html/rfc7231#section-4.3.5
|
| 997 |
+
|
| 998 |
+
// Sending a payload body on a request that does not
|
| 999 |
+
// expect it can cause undefined behavior on some
|
| 1000 |
+
// servers and corrupt connection state. Do not
|
| 1001 |
+
// re-use the connection for further requests.
|
| 1002 |
+
|
| 1003 |
+
const expectsPayload = (
|
| 1004 |
+
method === 'PUT' ||
|
| 1005 |
+
method === 'POST' ||
|
| 1006 |
+
method === 'PATCH' ||
|
| 1007 |
+
method === 'QUERY' ||
|
| 1008 |
+
method === 'PROPFIND' ||
|
| 1009 |
+
method === 'PROPPATCH'
|
| 1010 |
+
)
|
| 1011 |
+
|
| 1012 |
+
if (util.isFormDataLike(body)) {
|
| 1013 |
+
if (!extractBody) {
|
| 1014 |
+
extractBody = require('../web/fetch/body.js').extractBody
|
| 1015 |
+
}
|
| 1016 |
+
|
| 1017 |
+
const [bodyStream, contentType] = extractBody(body)
|
| 1018 |
+
if (request.contentType == null) {
|
| 1019 |
+
headers.push('content-type', contentType)
|
| 1020 |
+
}
|
| 1021 |
+
body = bodyStream.stream
|
| 1022 |
+
contentLength = bodyStream.length
|
| 1023 |
+
} else if (util.isBlobLike(body) && request.contentType == null && body.type) {
|
| 1024 |
+
headers.push('content-type', body.type)
|
| 1025 |
+
}
|
| 1026 |
+
|
| 1027 |
+
if (body && typeof body.read === 'function') {
|
| 1028 |
+
// Try to read EOF in order to get length.
|
| 1029 |
+
body.read(0)
|
| 1030 |
+
}
|
| 1031 |
+
|
| 1032 |
+
const bodyLength = util.bodyLength(body)
|
| 1033 |
+
|
| 1034 |
+
contentLength = bodyLength ?? contentLength
|
| 1035 |
+
|
| 1036 |
+
if (contentLength === null) {
|
| 1037 |
+
contentLength = request.contentLength
|
| 1038 |
+
}
|
| 1039 |
+
|
| 1040 |
+
if (contentLength === 0 && !expectsPayload) {
|
| 1041 |
+
// https://tools.ietf.org/html/rfc7230#section-3.3.2
|
| 1042 |
+
// A user agent SHOULD NOT send a Content-Length header field when
|
| 1043 |
+
// the request message does not contain a payload body and the method
|
| 1044 |
+
// semantics do not anticipate such a body.
|
| 1045 |
+
|
| 1046 |
+
contentLength = null
|
| 1047 |
+
}
|
| 1048 |
+
|
| 1049 |
+
// https://github.com/nodejs/undici/issues/2046
|
| 1050 |
+
// A user agent may send a Content-Length header with 0 value, this should be allowed.
|
| 1051 |
+
if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength !== null && request.contentLength !== contentLength) {
|
| 1052 |
+
if (client[kStrictContentLength]) {
|
| 1053 |
+
util.errorRequest(client, request, new RequestContentLengthMismatchError())
|
| 1054 |
+
return false
|
| 1055 |
+
}
|
| 1056 |
+
|
| 1057 |
+
process.emitWarning(new RequestContentLengthMismatchError())
|
| 1058 |
+
}
|
| 1059 |
+
|
| 1060 |
+
const socket = client[kSocket]
|
| 1061 |
+
|
| 1062 |
+
/**
|
| 1063 |
+
* @param {Error} [err]
|
| 1064 |
+
* @returns {void}
|
| 1065 |
+
*/
|
| 1066 |
+
const abort = (err) => {
|
| 1067 |
+
if (request.aborted || request.completed) {
|
| 1068 |
+
return
|
| 1069 |
+
}
|
| 1070 |
+
|
| 1071 |
+
util.errorRequest(client, request, err || new RequestAbortedError())
|
| 1072 |
+
|
| 1073 |
+
util.destroy(body)
|
| 1074 |
+
util.destroy(socket, new InformationalError('aborted'))
|
| 1075 |
+
}
|
| 1076 |
+
|
| 1077 |
+
try {
|
| 1078 |
+
request.onConnect(abort)
|
| 1079 |
+
} catch (err) {
|
| 1080 |
+
util.errorRequest(client, request, err)
|
| 1081 |
+
}
|
| 1082 |
+
|
| 1083 |
+
if (request.aborted) {
|
| 1084 |
+
return false
|
| 1085 |
+
}
|
| 1086 |
+
|
| 1087 |
+
if (method === 'HEAD') {
|
| 1088 |
+
// https://github.com/mcollina/undici/issues/258
|
| 1089 |
+
// Close after a HEAD request to interop with misbehaving servers
|
| 1090 |
+
// that may send a body in the response.
|
| 1091 |
+
|
| 1092 |
+
socket[kReset] = true
|
| 1093 |
+
}
|
| 1094 |
+
|
| 1095 |
+
if (upgrade || method === 'CONNECT') {
|
| 1096 |
+
// On CONNECT or upgrade, block pipeline from dispatching further
|
| 1097 |
+
// requests on this connection.
|
| 1098 |
+
|
| 1099 |
+
socket[kReset] = true
|
| 1100 |
+
}
|
| 1101 |
+
|
| 1102 |
+
if (reset != null) {
|
| 1103 |
+
socket[kReset] = reset
|
| 1104 |
+
}
|
| 1105 |
+
|
| 1106 |
+
if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) {
|
| 1107 |
+
socket[kReset] = true
|
| 1108 |
+
}
|
| 1109 |
+
|
| 1110 |
+
if (blocking) {
|
| 1111 |
+
socket[kBlocking] = true
|
| 1112 |
+
}
|
| 1113 |
+
|
| 1114 |
+
let header = `${method} ${path} HTTP/1.1\r\n`
|
| 1115 |
+
|
| 1116 |
+
if (typeof host === 'string') {
|
| 1117 |
+
header += `host: ${host}\r\n`
|
| 1118 |
+
} else {
|
| 1119 |
+
header += client[kHostHeader]
|
| 1120 |
+
}
|
| 1121 |
+
|
| 1122 |
+
if (upgrade) {
|
| 1123 |
+
header += `connection: upgrade\r\nupgrade: ${upgrade}\r\n`
|
| 1124 |
+
} else if (client[kPipelining] && !socket[kReset]) {
|
| 1125 |
+
header += 'connection: keep-alive\r\n'
|
| 1126 |
+
} else {
|
| 1127 |
+
header += 'connection: close\r\n'
|
| 1128 |
+
}
|
| 1129 |
+
|
| 1130 |
+
if (Array.isArray(headers)) {
|
| 1131 |
+
for (let n = 0; n < headers.length; n += 2) {
|
| 1132 |
+
const key = headers[n + 0]
|
| 1133 |
+
const val = headers[n + 1]
|
| 1134 |
+
|
| 1135 |
+
if (Array.isArray(val)) {
|
| 1136 |
+
for (let i = 0; i < val.length; i++) {
|
| 1137 |
+
header += `${key}: ${val[i]}\r\n`
|
| 1138 |
+
}
|
| 1139 |
+
} else {
|
| 1140 |
+
header += `${key}: ${val}\r\n`
|
| 1141 |
+
}
|
| 1142 |
+
}
|
| 1143 |
+
}
|
| 1144 |
+
|
| 1145 |
+
if (channels.sendHeaders.hasSubscribers) {
|
| 1146 |
+
channels.sendHeaders.publish({ request, headers: header, socket })
|
| 1147 |
+
}
|
| 1148 |
+
|
| 1149 |
+
/* istanbul ignore else: assertion */
|
| 1150 |
+
if (!body || bodyLength === 0) {
|
| 1151 |
+
writeBuffer(abort, null, client, request, socket, contentLength, header, expectsPayload)
|
| 1152 |
+
} else if (util.isBuffer(body)) {
|
| 1153 |
+
writeBuffer(abort, body, client, request, socket, contentLength, header, expectsPayload)
|
| 1154 |
+
} else if (util.isBlobLike(body)) {
|
| 1155 |
+
if (typeof body.stream === 'function') {
|
| 1156 |
+
writeIterable(abort, body.stream(), client, request, socket, contentLength, header, expectsPayload)
|
| 1157 |
+
} else {
|
| 1158 |
+
writeBlob(abort, body, client, request, socket, contentLength, header, expectsPayload)
|
| 1159 |
+
}
|
| 1160 |
+
} else if (util.isStream(body)) {
|
| 1161 |
+
writeStream(abort, body, client, request, socket, contentLength, header, expectsPayload)
|
| 1162 |
+
} else if (util.isIterable(body)) {
|
| 1163 |
+
writeIterable(abort, body, client, request, socket, contentLength, header, expectsPayload)
|
| 1164 |
+
} else {
|
| 1165 |
+
assert(false)
|
| 1166 |
+
}
|
| 1167 |
+
|
| 1168 |
+
return true
|
| 1169 |
+
}
|
| 1170 |
+
|
| 1171 |
+
/**
|
| 1172 |
+
* @param {AbortCallback} abort
|
| 1173 |
+
* @param {import('stream').Stream} body
|
| 1174 |
+
* @param {import('./client.js')} client
|
| 1175 |
+
* @param {import('../core/request.js')} request
|
| 1176 |
+
* @param {import('net').Socket} socket
|
| 1177 |
+
* @param {number} contentLength
|
| 1178 |
+
* @param {string} header
|
| 1179 |
+
* @param {boolean} expectsPayload
|
| 1180 |
+
*/
|
| 1181 |
+
function writeStream (abort, body, client, request, socket, contentLength, header, expectsPayload) {
|
| 1182 |
+
assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined')
|
| 1183 |
+
|
| 1184 |
+
let finished = false
|
| 1185 |
+
|
| 1186 |
+
const writer = new AsyncWriter({ abort, socket, request, contentLength, client, expectsPayload, header })
|
| 1187 |
+
|
| 1188 |
+
/**
|
| 1189 |
+
* @param {Buffer} chunk
|
| 1190 |
+
* @returns {void}
|
| 1191 |
+
*/
|
| 1192 |
+
const onData = function (chunk) {
|
| 1193 |
+
if (finished) {
|
| 1194 |
+
return
|
| 1195 |
+
}
|
| 1196 |
+
|
| 1197 |
+
try {
|
| 1198 |
+
if (!writer.write(chunk) && this.pause) {
|
| 1199 |
+
this.pause()
|
| 1200 |
+
}
|
| 1201 |
+
} catch (err) {
|
| 1202 |
+
util.destroy(this, err)
|
| 1203 |
+
}
|
| 1204 |
+
}
|
| 1205 |
+
|
| 1206 |
+
/**
|
| 1207 |
+
* @returns {void}
|
| 1208 |
+
*/
|
| 1209 |
+
const onDrain = function () {
|
| 1210 |
+
if (finished) {
|
| 1211 |
+
return
|
| 1212 |
+
}
|
| 1213 |
+
|
| 1214 |
+
if (body.resume) {
|
| 1215 |
+
body.resume()
|
| 1216 |
+
}
|
| 1217 |
+
}
|
| 1218 |
+
|
| 1219 |
+
/**
|
| 1220 |
+
* @returns {void}
|
| 1221 |
+
*/
|
| 1222 |
+
const onClose = function () {
|
| 1223 |
+
// 'close' might be emitted *before* 'error' for
|
| 1224 |
+
// broken streams. Wait a tick to avoid this case.
|
| 1225 |
+
queueMicrotask(() => {
|
| 1226 |
+
// It's only safe to remove 'error' listener after
|
| 1227 |
+
// 'close'.
|
| 1228 |
+
body.removeListener('error', onFinished)
|
| 1229 |
+
})
|
| 1230 |
+
|
| 1231 |
+
if (!finished) {
|
| 1232 |
+
const err = new RequestAbortedError()
|
| 1233 |
+
queueMicrotask(() => onFinished(err))
|
| 1234 |
+
}
|
| 1235 |
+
}
|
| 1236 |
+
|
| 1237 |
+
/**
|
| 1238 |
+
* @param {Error} [err]
|
| 1239 |
+
* @returns
|
| 1240 |
+
*/
|
| 1241 |
+
const onFinished = function (err) {
|
| 1242 |
+
if (finished) {
|
| 1243 |
+
return
|
| 1244 |
+
}
|
| 1245 |
+
|
| 1246 |
+
finished = true
|
| 1247 |
+
|
| 1248 |
+
assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1))
|
| 1249 |
+
|
| 1250 |
+
socket
|
| 1251 |
+
.off('drain', onDrain)
|
| 1252 |
+
.off('error', onFinished)
|
| 1253 |
+
|
| 1254 |
+
body
|
| 1255 |
+
.removeListener('data', onData)
|
| 1256 |
+
.removeListener('end', onFinished)
|
| 1257 |
+
.removeListener('close', onClose)
|
| 1258 |
+
|
| 1259 |
+
if (!err) {
|
| 1260 |
+
try {
|
| 1261 |
+
writer.end()
|
| 1262 |
+
} catch (er) {
|
| 1263 |
+
err = er
|
| 1264 |
+
}
|
| 1265 |
+
}
|
| 1266 |
+
|
| 1267 |
+
writer.destroy(err)
|
| 1268 |
+
|
| 1269 |
+
if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) {
|
| 1270 |
+
util.destroy(body, err)
|
| 1271 |
+
} else {
|
| 1272 |
+
util.destroy(body)
|
| 1273 |
+
}
|
| 1274 |
+
}
|
| 1275 |
+
|
| 1276 |
+
body
|
| 1277 |
+
.on('data', onData)
|
| 1278 |
+
.on('end', onFinished)
|
| 1279 |
+
.on('error', onFinished)
|
| 1280 |
+
.on('close', onClose)
|
| 1281 |
+
|
| 1282 |
+
if (body.resume) {
|
| 1283 |
+
body.resume()
|
| 1284 |
+
}
|
| 1285 |
+
|
| 1286 |
+
socket
|
| 1287 |
+
.on('drain', onDrain)
|
| 1288 |
+
.on('error', onFinished)
|
| 1289 |
+
|
| 1290 |
+
if (body.errorEmitted ?? body.errored) {
|
| 1291 |
+
setImmediate(onFinished, body.errored)
|
| 1292 |
+
} else if (body.endEmitted ?? body.readableEnded) {
|
| 1293 |
+
setImmediate(onFinished, null)
|
| 1294 |
+
}
|
| 1295 |
+
|
| 1296 |
+
if (body.closeEmitted ?? body.closed) {
|
| 1297 |
+
setImmediate(onClose)
|
| 1298 |
+
}
|
| 1299 |
+
}
|
| 1300 |
+
|
| 1301 |
+
/**
|
| 1302 |
+
* @typedef AbortCallback
|
| 1303 |
+
* @type {Function}
|
| 1304 |
+
* @param {Error} [err]
|
| 1305 |
+
* @returns {void}
|
| 1306 |
+
*/
|
| 1307 |
+
|
| 1308 |
+
/**
|
| 1309 |
+
* @param {AbortCallback} abort
|
| 1310 |
+
* @param {Uint8Array|null} body
|
| 1311 |
+
* @param {import('./client.js')} client
|
| 1312 |
+
* @param {import('../core/request.js')} request
|
| 1313 |
+
* @param {import('net').Socket} socket
|
| 1314 |
+
* @param {number} contentLength
|
| 1315 |
+
* @param {string} header
|
| 1316 |
+
* @param {boolean} expectsPayload
|
| 1317 |
+
* @returns {void}
|
| 1318 |
+
*/
|
| 1319 |
+
function writeBuffer (abort, body, client, request, socket, contentLength, header, expectsPayload) {
|
| 1320 |
+
try {
|
| 1321 |
+
if (!body) {
|
| 1322 |
+
if (contentLength === 0) {
|
| 1323 |
+
socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1')
|
| 1324 |
+
} else {
|
| 1325 |
+
assert(contentLength === null, 'no body must not have content length')
|
| 1326 |
+
socket.write(`${header}\r\n`, 'latin1')
|
| 1327 |
+
}
|
| 1328 |
+
} else if (util.isBuffer(body)) {
|
| 1329 |
+
assert(contentLength === body.byteLength, 'buffer body must have content length')
|
| 1330 |
+
|
| 1331 |
+
socket.cork()
|
| 1332 |
+
socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
|
| 1333 |
+
socket.write(body)
|
| 1334 |
+
socket.uncork()
|
| 1335 |
+
request.onBodySent(body)
|
| 1336 |
+
|
| 1337 |
+
if (!expectsPayload && request.reset !== false) {
|
| 1338 |
+
socket[kReset] = true
|
| 1339 |
+
}
|
| 1340 |
+
}
|
| 1341 |
+
request.onRequestSent()
|
| 1342 |
+
|
| 1343 |
+
client[kResume]()
|
| 1344 |
+
} catch (err) {
|
| 1345 |
+
abort(err)
|
| 1346 |
+
}
|
| 1347 |
+
}
|
| 1348 |
+
|
| 1349 |
+
/**
|
| 1350 |
+
* @param {AbortCallback} abort
|
| 1351 |
+
* @param {Blob} body
|
| 1352 |
+
* @param {import('./client.js')} client
|
| 1353 |
+
* @param {import('../core/request.js')} request
|
| 1354 |
+
* @param {import('net').Socket} socket
|
| 1355 |
+
* @param {number} contentLength
|
| 1356 |
+
* @param {string} header
|
| 1357 |
+
* @param {boolean} expectsPayload
|
| 1358 |
+
* @returns {Promise<void>}
|
| 1359 |
+
*/
|
| 1360 |
+
async function writeBlob (abort, body, client, request, socket, contentLength, header, expectsPayload) {
|
| 1361 |
+
assert(contentLength === body.size, 'blob body must have content length')
|
| 1362 |
+
|
| 1363 |
+
try {
|
| 1364 |
+
if (contentLength != null && contentLength !== body.size) {
|
| 1365 |
+
throw new RequestContentLengthMismatchError()
|
| 1366 |
+
}
|
| 1367 |
+
|
| 1368 |
+
const buffer = Buffer.from(await body.arrayBuffer())
|
| 1369 |
+
|
| 1370 |
+
socket.cork()
|
| 1371 |
+
socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
|
| 1372 |
+
socket.write(buffer)
|
| 1373 |
+
socket.uncork()
|
| 1374 |
+
|
| 1375 |
+
request.onBodySent(buffer)
|
| 1376 |
+
request.onRequestSent()
|
| 1377 |
+
|
| 1378 |
+
if (!expectsPayload && request.reset !== false) {
|
| 1379 |
+
socket[kReset] = true
|
| 1380 |
+
}
|
| 1381 |
+
|
| 1382 |
+
client[kResume]()
|
| 1383 |
+
} catch (err) {
|
| 1384 |
+
abort(err)
|
| 1385 |
+
}
|
| 1386 |
+
}
|
| 1387 |
+
|
| 1388 |
+
/**
|
| 1389 |
+
* @param {AbortCallback} abort
|
| 1390 |
+
* @param {Iterable} body
|
| 1391 |
+
* @param {import('./client.js')} client
|
| 1392 |
+
* @param {import('../core/request.js')} request
|
| 1393 |
+
* @param {import('net').Socket} socket
|
| 1394 |
+
* @param {number} contentLength
|
| 1395 |
+
* @param {string} header
|
| 1396 |
+
* @param {boolean} expectsPayload
|
| 1397 |
+
* @returns {Promise<void>}
|
| 1398 |
+
*/
|
| 1399 |
+
async function writeIterable (abort, body, client, request, socket, contentLength, header, expectsPayload) {
|
| 1400 |
+
assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined')
|
| 1401 |
+
|
| 1402 |
+
let callback = null
|
| 1403 |
+
function onDrain () {
|
| 1404 |
+
if (callback) {
|
| 1405 |
+
const cb = callback
|
| 1406 |
+
callback = null
|
| 1407 |
+
cb()
|
| 1408 |
+
}
|
| 1409 |
+
}
|
| 1410 |
+
|
| 1411 |
+
const waitForDrain = () => new Promise((resolve, reject) => {
|
| 1412 |
+
assert(callback === null)
|
| 1413 |
+
|
| 1414 |
+
if (socket[kError]) {
|
| 1415 |
+
reject(socket[kError])
|
| 1416 |
+
} else {
|
| 1417 |
+
callback = resolve
|
| 1418 |
+
}
|
| 1419 |
+
})
|
| 1420 |
+
|
| 1421 |
+
socket
|
| 1422 |
+
.on('close', onDrain)
|
| 1423 |
+
.on('drain', onDrain)
|
| 1424 |
+
|
| 1425 |
+
const writer = new AsyncWriter({ abort, socket, request, contentLength, client, expectsPayload, header })
|
| 1426 |
+
try {
|
| 1427 |
+
// It's up to the user to somehow abort the async iterable.
|
| 1428 |
+
for await (const chunk of body) {
|
| 1429 |
+
if (socket[kError]) {
|
| 1430 |
+
throw socket[kError]
|
| 1431 |
+
}
|
| 1432 |
+
|
| 1433 |
+
if (!writer.write(chunk)) {
|
| 1434 |
+
await waitForDrain()
|
| 1435 |
+
}
|
| 1436 |
+
}
|
| 1437 |
+
|
| 1438 |
+
writer.end()
|
| 1439 |
+
} catch (err) {
|
| 1440 |
+
writer.destroy(err)
|
| 1441 |
+
} finally {
|
| 1442 |
+
socket
|
| 1443 |
+
.off('close', onDrain)
|
| 1444 |
+
.off('drain', onDrain)
|
| 1445 |
+
}
|
| 1446 |
+
}
|
| 1447 |
+
|
| 1448 |
+
class AsyncWriter {
|
| 1449 |
+
/**
|
| 1450 |
+
*
|
| 1451 |
+
* @param {object} arg
|
| 1452 |
+
* @param {AbortCallback} arg.abort
|
| 1453 |
+
* @param {import('net').Socket} arg.socket
|
| 1454 |
+
* @param {import('../core/request.js')} arg.request
|
| 1455 |
+
* @param {number} arg.contentLength
|
| 1456 |
+
* @param {import('./client.js')} arg.client
|
| 1457 |
+
* @param {boolean} arg.expectsPayload
|
| 1458 |
+
* @param {string} arg.header
|
| 1459 |
+
*/
|
| 1460 |
+
constructor ({ abort, socket, request, contentLength, client, expectsPayload, header }) {
|
| 1461 |
+
this.socket = socket
|
| 1462 |
+
this.request = request
|
| 1463 |
+
this.contentLength = contentLength
|
| 1464 |
+
this.client = client
|
| 1465 |
+
this.bytesWritten = 0
|
| 1466 |
+
this.expectsPayload = expectsPayload
|
| 1467 |
+
this.header = header
|
| 1468 |
+
this.abort = abort
|
| 1469 |
+
|
| 1470 |
+
socket[kWriting] = true
|
| 1471 |
+
}
|
| 1472 |
+
|
| 1473 |
+
/**
|
| 1474 |
+
* @param {Buffer} chunk
|
| 1475 |
+
* @returns
|
| 1476 |
+
*/
|
| 1477 |
+
write (chunk) {
|
| 1478 |
+
const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this
|
| 1479 |
+
|
| 1480 |
+
if (socket[kError]) {
|
| 1481 |
+
throw socket[kError]
|
| 1482 |
+
}
|
| 1483 |
+
|
| 1484 |
+
if (socket.destroyed) {
|
| 1485 |
+
return false
|
| 1486 |
+
}
|
| 1487 |
+
|
| 1488 |
+
const len = Buffer.byteLength(chunk)
|
| 1489 |
+
if (!len) {
|
| 1490 |
+
return true
|
| 1491 |
+
}
|
| 1492 |
+
|
| 1493 |
+
// We should defer writing chunks.
|
| 1494 |
+
if (contentLength !== null && bytesWritten + len > contentLength) {
|
| 1495 |
+
if (client[kStrictContentLength]) {
|
| 1496 |
+
throw new RequestContentLengthMismatchError()
|
| 1497 |
+
}
|
| 1498 |
+
|
| 1499 |
+
process.emitWarning(new RequestContentLengthMismatchError())
|
| 1500 |
+
}
|
| 1501 |
+
|
| 1502 |
+
socket.cork()
|
| 1503 |
+
|
| 1504 |
+
if (bytesWritten === 0) {
|
| 1505 |
+
if (!expectsPayload && request.reset !== false) {
|
| 1506 |
+
socket[kReset] = true
|
| 1507 |
+
}
|
| 1508 |
+
|
| 1509 |
+
if (contentLength === null) {
|
| 1510 |
+
socket.write(`${header}transfer-encoding: chunked\r\n`, 'latin1')
|
| 1511 |
+
} else {
|
| 1512 |
+
socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
|
| 1513 |
+
}
|
| 1514 |
+
}
|
| 1515 |
+
|
| 1516 |
+
if (contentLength === null) {
|
| 1517 |
+
socket.write(`\r\n${len.toString(16)}\r\n`, 'latin1')
|
| 1518 |
+
}
|
| 1519 |
+
|
| 1520 |
+
this.bytesWritten += len
|
| 1521 |
+
|
| 1522 |
+
const ret = socket.write(chunk)
|
| 1523 |
+
|
| 1524 |
+
socket.uncork()
|
| 1525 |
+
|
| 1526 |
+
request.onBodySent(chunk)
|
| 1527 |
+
|
| 1528 |
+
if (!ret) {
|
| 1529 |
+
if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
|
| 1530 |
+
// istanbul ignore else: only for jest
|
| 1531 |
+
if (socket[kParser].timeout.refresh) {
|
| 1532 |
+
socket[kParser].timeout.refresh()
|
| 1533 |
+
}
|
| 1534 |
+
}
|
| 1535 |
+
}
|
| 1536 |
+
|
| 1537 |
+
return ret
|
| 1538 |
+
}
|
| 1539 |
+
|
| 1540 |
+
/**
|
| 1541 |
+
* @returns {void}
|
| 1542 |
+
*/
|
| 1543 |
+
end () {
|
| 1544 |
+
const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this
|
| 1545 |
+
request.onRequestSent()
|
| 1546 |
+
|
| 1547 |
+
socket[kWriting] = false
|
| 1548 |
+
|
| 1549 |
+
if (socket[kError]) {
|
| 1550 |
+
throw socket[kError]
|
| 1551 |
+
}
|
| 1552 |
+
|
| 1553 |
+
if (socket.destroyed) {
|
| 1554 |
+
return
|
| 1555 |
+
}
|
| 1556 |
+
|
| 1557 |
+
if (bytesWritten === 0) {
|
| 1558 |
+
if (expectsPayload) {
|
| 1559 |
+
// https://tools.ietf.org/html/rfc7230#section-3.3.2
|
| 1560 |
+
// A user agent SHOULD send a Content-Length in a request message when
|
| 1561 |
+
// no Transfer-Encoding is sent and the request method defines a meaning
|
| 1562 |
+
// for an enclosed payload body.
|
| 1563 |
+
|
| 1564 |
+
socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1')
|
| 1565 |
+
} else {
|
| 1566 |
+
socket.write(`${header}\r\n`, 'latin1')
|
| 1567 |
+
}
|
| 1568 |
+
} else if (contentLength === null) {
|
| 1569 |
+
socket.write('\r\n0\r\n\r\n', 'latin1')
|
| 1570 |
+
}
|
| 1571 |
+
|
| 1572 |
+
if (contentLength !== null && bytesWritten !== contentLength) {
|
| 1573 |
+
if (client[kStrictContentLength]) {
|
| 1574 |
+
throw new RequestContentLengthMismatchError()
|
| 1575 |
+
} else {
|
| 1576 |
+
process.emitWarning(new RequestContentLengthMismatchError())
|
| 1577 |
+
}
|
| 1578 |
+
}
|
| 1579 |
+
|
| 1580 |
+
if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
|
| 1581 |
+
// istanbul ignore else: only for jest
|
| 1582 |
+
if (socket[kParser].timeout.refresh) {
|
| 1583 |
+
socket[kParser].timeout.refresh()
|
| 1584 |
+
}
|
| 1585 |
+
}
|
| 1586 |
+
|
| 1587 |
+
client[kResume]()
|
| 1588 |
+
}
|
| 1589 |
+
|
| 1590 |
+
/**
|
| 1591 |
+
* @param {Error} [err]
|
| 1592 |
+
* @returns {void}
|
| 1593 |
+
*/
|
| 1594 |
+
destroy (err) {
|
| 1595 |
+
const { socket, client, abort } = this
|
| 1596 |
+
|
| 1597 |
+
socket[kWriting] = false
|
| 1598 |
+
|
| 1599 |
+
if (err) {
|
| 1600 |
+
assert(client[kRunning] <= 1, 'pipeline should only contain this request')
|
| 1601 |
+
abort(err)
|
| 1602 |
+
}
|
| 1603 |
+
}
|
| 1604 |
+
}
|
| 1605 |
+
|
| 1606 |
+
module.exports = connectH1
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/dispatcher/client-h2.js
ADDED
|
@@ -0,0 +1,798 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'use strict'
|
| 2 |
+
|
| 3 |
+
const assert = require('node:assert')
|
| 4 |
+
const { pipeline } = require('node:stream')
|
| 5 |
+
const util = require('../core/util.js')
|
| 6 |
+
const {
|
| 7 |
+
RequestContentLengthMismatchError,
|
| 8 |
+
RequestAbortedError,
|
| 9 |
+
SocketError,
|
| 10 |
+
InformationalError
|
| 11 |
+
} = require('../core/errors.js')
|
| 12 |
+
const {
|
| 13 |
+
kUrl,
|
| 14 |
+
kReset,
|
| 15 |
+
kClient,
|
| 16 |
+
kRunning,
|
| 17 |
+
kPending,
|
| 18 |
+
kQueue,
|
| 19 |
+
kPendingIdx,
|
| 20 |
+
kRunningIdx,
|
| 21 |
+
kError,
|
| 22 |
+
kSocket,
|
| 23 |
+
kStrictContentLength,
|
| 24 |
+
kOnError,
|
| 25 |
+
kMaxConcurrentStreams,
|
| 26 |
+
kHTTP2Session,
|
| 27 |
+
kResume,
|
| 28 |
+
kSize,
|
| 29 |
+
kHTTPContext,
|
| 30 |
+
kClosed,
|
| 31 |
+
kBodyTimeout
|
| 32 |
+
} = require('../core/symbols.js')
|
| 33 |
+
const { channels } = require('../core/diagnostics.js')
|
| 34 |
+
|
| 35 |
+
const kOpenStreams = Symbol('open streams')
|
| 36 |
+
|
| 37 |
+
let extractBody
|
| 38 |
+
|
| 39 |
+
/** @type {import('http2')} */
|
| 40 |
+
let http2
|
| 41 |
+
try {
|
| 42 |
+
http2 = require('node:http2')
|
| 43 |
+
} catch {
|
| 44 |
+
// @ts-ignore
|
| 45 |
+
http2 = { constants: {} }
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
const {
|
| 49 |
+
constants: {
|
| 50 |
+
HTTP2_HEADER_AUTHORITY,
|
| 51 |
+
HTTP2_HEADER_METHOD,
|
| 52 |
+
HTTP2_HEADER_PATH,
|
| 53 |
+
HTTP2_HEADER_SCHEME,
|
| 54 |
+
HTTP2_HEADER_CONTENT_LENGTH,
|
| 55 |
+
HTTP2_HEADER_EXPECT,
|
| 56 |
+
HTTP2_HEADER_STATUS
|
| 57 |
+
}
|
| 58 |
+
} = http2
|
| 59 |
+
|
| 60 |
+
function parseH2Headers (headers) {
|
| 61 |
+
const result = []
|
| 62 |
+
|
| 63 |
+
for (const [name, value] of Object.entries(headers)) {
|
| 64 |
+
// h2 may concat the header value by array
|
| 65 |
+
// e.g. Set-Cookie
|
| 66 |
+
if (Array.isArray(value)) {
|
| 67 |
+
for (const subvalue of value) {
|
| 68 |
+
// we need to provide each header value of header name
|
| 69 |
+
// because the headers handler expect name-value pair
|
| 70 |
+
result.push(Buffer.from(name), Buffer.from(subvalue))
|
| 71 |
+
}
|
| 72 |
+
} else {
|
| 73 |
+
result.push(Buffer.from(name), Buffer.from(value))
|
| 74 |
+
}
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
return result
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
async function connectH2 (client, socket) {
|
| 81 |
+
client[kSocket] = socket
|
| 82 |
+
|
| 83 |
+
const session = http2.connect(client[kUrl], {
|
| 84 |
+
createConnection: () => socket,
|
| 85 |
+
peerMaxConcurrentStreams: client[kMaxConcurrentStreams],
|
| 86 |
+
settings: {
|
| 87 |
+
// TODO(metcoder95): add support for PUSH
|
| 88 |
+
enablePush: false
|
| 89 |
+
}
|
| 90 |
+
})
|
| 91 |
+
|
| 92 |
+
session[kOpenStreams] = 0
|
| 93 |
+
session[kClient] = client
|
| 94 |
+
session[kSocket] = socket
|
| 95 |
+
session[kHTTP2Session] = null
|
| 96 |
+
|
| 97 |
+
util.addListener(session, 'error', onHttp2SessionError)
|
| 98 |
+
util.addListener(session, 'frameError', onHttp2FrameError)
|
| 99 |
+
util.addListener(session, 'end', onHttp2SessionEnd)
|
| 100 |
+
util.addListener(session, 'goaway', onHttp2SessionGoAway)
|
| 101 |
+
util.addListener(session, 'close', onHttp2SessionClose)
|
| 102 |
+
|
| 103 |
+
session.unref()
|
| 104 |
+
|
| 105 |
+
client[kHTTP2Session] = session
|
| 106 |
+
socket[kHTTP2Session] = session
|
| 107 |
+
|
| 108 |
+
util.addListener(socket, 'error', onHttp2SocketError)
|
| 109 |
+
util.addListener(socket, 'end', onHttp2SocketEnd)
|
| 110 |
+
util.addListener(socket, 'close', onHttp2SocketClose)
|
| 111 |
+
|
| 112 |
+
socket[kClosed] = false
|
| 113 |
+
socket.on('close', onSocketClose)
|
| 114 |
+
|
| 115 |
+
return {
|
| 116 |
+
version: 'h2',
|
| 117 |
+
defaultPipelining: Infinity,
|
| 118 |
+
write (request) {
|
| 119 |
+
return writeH2(client, request)
|
| 120 |
+
},
|
| 121 |
+
resume () {
|
| 122 |
+
resumeH2(client)
|
| 123 |
+
},
|
| 124 |
+
destroy (err, callback) {
|
| 125 |
+
if (socket[kClosed]) {
|
| 126 |
+
queueMicrotask(callback)
|
| 127 |
+
} else {
|
| 128 |
+
socket.destroy(err).on('close', callback)
|
| 129 |
+
}
|
| 130 |
+
},
|
| 131 |
+
get destroyed () {
|
| 132 |
+
return socket.destroyed
|
| 133 |
+
},
|
| 134 |
+
busy () {
|
| 135 |
+
return false
|
| 136 |
+
}
|
| 137 |
+
}
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
function resumeH2 (client) {
|
| 141 |
+
const socket = client[kSocket]
|
| 142 |
+
|
| 143 |
+
if (socket?.destroyed === false) {
|
| 144 |
+
if (client[kSize] === 0 || client[kMaxConcurrentStreams] === 0) {
|
| 145 |
+
socket.unref()
|
| 146 |
+
client[kHTTP2Session].unref()
|
| 147 |
+
} else {
|
| 148 |
+
socket.ref()
|
| 149 |
+
client[kHTTP2Session].ref()
|
| 150 |
+
}
|
| 151 |
+
}
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
function onHttp2SessionError (err) {
|
| 155 |
+
assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')
|
| 156 |
+
|
| 157 |
+
this[kSocket][kError] = err
|
| 158 |
+
this[kClient][kOnError](err)
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
function onHttp2FrameError (type, code, id) {
|
| 162 |
+
if (id === 0) {
|
| 163 |
+
const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`)
|
| 164 |
+
this[kSocket][kError] = err
|
| 165 |
+
this[kClient][kOnError](err)
|
| 166 |
+
}
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
function onHttp2SessionEnd () {
|
| 170 |
+
const err = new SocketError('other side closed', util.getSocketInfo(this[kSocket]))
|
| 171 |
+
this.destroy(err)
|
| 172 |
+
util.destroy(this[kSocket], err)
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
/**
|
| 176 |
+
* This is the root cause of #3011
|
| 177 |
+
* We need to handle GOAWAY frames properly, and trigger the session close
|
| 178 |
+
* along with the socket right away
|
| 179 |
+
*
|
| 180 |
+
* @this {import('http2').ClientHttp2Session}
|
| 181 |
+
* @param {number} errorCode
|
| 182 |
+
*/
|
| 183 |
+
function onHttp2SessionGoAway (errorCode) {
|
| 184 |
+
// TODO(mcollina): Verify if GOAWAY implements the spec correctly:
|
| 185 |
+
// https://datatracker.ietf.org/doc/html/rfc7540#section-6.8
|
| 186 |
+
// Specifically, we do not verify the "valid" stream id.
|
| 187 |
+
|
| 188 |
+
const err = this[kError] || new SocketError(`HTTP/2: "GOAWAY" frame received with code ${errorCode}`, util.getSocketInfo(this[kSocket]))
|
| 189 |
+
const client = this[kClient]
|
| 190 |
+
|
| 191 |
+
client[kSocket] = null
|
| 192 |
+
client[kHTTPContext] = null
|
| 193 |
+
|
| 194 |
+
// this is an HTTP2 session
|
| 195 |
+
this.close()
|
| 196 |
+
this[kHTTP2Session] = null
|
| 197 |
+
|
| 198 |
+
util.destroy(this[kSocket], err)
|
| 199 |
+
|
| 200 |
+
// Fail head of pipeline.
|
| 201 |
+
if (client[kRunningIdx] < client[kQueue].length) {
|
| 202 |
+
const request = client[kQueue][client[kRunningIdx]]
|
| 203 |
+
client[kQueue][client[kRunningIdx]++] = null
|
| 204 |
+
util.errorRequest(client, request, err)
|
| 205 |
+
client[kPendingIdx] = client[kRunningIdx]
|
| 206 |
+
}
|
| 207 |
+
|
| 208 |
+
assert(client[kRunning] === 0)
|
| 209 |
+
|
| 210 |
+
client.emit('disconnect', client[kUrl], [client], err)
|
| 211 |
+
client.emit('connectionError', client[kUrl], [client], err)
|
| 212 |
+
|
| 213 |
+
client[kResume]()
|
| 214 |
+
}
|
| 215 |
+
|
| 216 |
+
function onHttp2SessionClose () {
|
| 217 |
+
const { [kClient]: client } = this
|
| 218 |
+
const { [kSocket]: socket } = client
|
| 219 |
+
|
| 220 |
+
const err = this[kSocket][kError] || this[kError] || new SocketError('closed', util.getSocketInfo(socket))
|
| 221 |
+
|
| 222 |
+
client[kSocket] = null
|
| 223 |
+
client[kHTTPContext] = null
|
| 224 |
+
|
| 225 |
+
if (client.destroyed) {
|
| 226 |
+
assert(client[kPending] === 0)
|
| 227 |
+
|
| 228 |
+
// Fail entire queue.
|
| 229 |
+
const requests = client[kQueue].splice(client[kRunningIdx])
|
| 230 |
+
for (let i = 0; i < requests.length; i++) {
|
| 231 |
+
const request = requests[i]
|
| 232 |
+
util.errorRequest(client, request, err)
|
| 233 |
+
}
|
| 234 |
+
}
|
| 235 |
+
}
|
| 236 |
+
|
| 237 |
+
function onHttp2SocketClose () {
|
| 238 |
+
const err = this[kError] || new SocketError('closed', util.getSocketInfo(this))
|
| 239 |
+
|
| 240 |
+
const client = this[kHTTP2Session][kClient]
|
| 241 |
+
|
| 242 |
+
client[kSocket] = null
|
| 243 |
+
client[kHTTPContext] = null
|
| 244 |
+
|
| 245 |
+
if (this[kHTTP2Session] !== null) {
|
| 246 |
+
this[kHTTP2Session].destroy(err)
|
| 247 |
+
}
|
| 248 |
+
|
| 249 |
+
client[kPendingIdx] = client[kRunningIdx]
|
| 250 |
+
|
| 251 |
+
assert(client[kRunning] === 0)
|
| 252 |
+
|
| 253 |
+
client.emit('disconnect', client[kUrl], [client], err)
|
| 254 |
+
|
| 255 |
+
client[kResume]()
|
| 256 |
+
}
|
| 257 |
+
|
| 258 |
+
function onHttp2SocketError (err) {
|
| 259 |
+
assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')
|
| 260 |
+
|
| 261 |
+
this[kError] = err
|
| 262 |
+
|
| 263 |
+
this[kClient][kOnError](err)
|
| 264 |
+
}
|
| 265 |
+
|
| 266 |
+
function onHttp2SocketEnd () {
|
| 267 |
+
util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this)))
|
| 268 |
+
}
|
| 269 |
+
|
| 270 |
+
function onSocketClose () {
|
| 271 |
+
this[kClosed] = true
|
| 272 |
+
}
|
| 273 |
+
|
| 274 |
+
// https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2
|
| 275 |
+
function shouldSendContentLength (method) {
|
| 276 |
+
return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT'
|
| 277 |
+
}
|
| 278 |
+
|
| 279 |
+
function writeH2 (client, request) {
|
| 280 |
+
const requestTimeout = request.bodyTimeout ?? client[kBodyTimeout]
|
| 281 |
+
const session = client[kHTTP2Session]
|
| 282 |
+
const { method, path, host, upgrade, expectContinue, signal, headers: reqHeaders } = request
|
| 283 |
+
let { body } = request
|
| 284 |
+
|
| 285 |
+
if (upgrade) {
|
| 286 |
+
util.errorRequest(client, request, new Error('Upgrade not supported for H2'))
|
| 287 |
+
return false
|
| 288 |
+
}
|
| 289 |
+
|
| 290 |
+
const headers = {}
|
| 291 |
+
for (let n = 0; n < reqHeaders.length; n += 2) {
|
| 292 |
+
const key = reqHeaders[n + 0]
|
| 293 |
+
const val = reqHeaders[n + 1]
|
| 294 |
+
|
| 295 |
+
if (Array.isArray(val)) {
|
| 296 |
+
for (let i = 0; i < val.length; i++) {
|
| 297 |
+
if (headers[key]) {
|
| 298 |
+
headers[key] += `, ${val[i]}`
|
| 299 |
+
} else {
|
| 300 |
+
headers[key] = val[i]
|
| 301 |
+
}
|
| 302 |
+
}
|
| 303 |
+
} else if (headers[key]) {
|
| 304 |
+
headers[key] += `, ${val}`
|
| 305 |
+
} else {
|
| 306 |
+
headers[key] = val
|
| 307 |
+
}
|
| 308 |
+
}
|
| 309 |
+
|
| 310 |
+
/** @type {import('node:http2').ClientHttp2Stream} */
|
| 311 |
+
let stream = null
|
| 312 |
+
|
| 313 |
+
const { hostname, port } = client[kUrl]
|
| 314 |
+
|
| 315 |
+
headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ''}`
|
| 316 |
+
headers[HTTP2_HEADER_METHOD] = method
|
| 317 |
+
|
| 318 |
+
const abort = (err) => {
|
| 319 |
+
if (request.aborted || request.completed) {
|
| 320 |
+
return
|
| 321 |
+
}
|
| 322 |
+
|
| 323 |
+
err = err || new RequestAbortedError()
|
| 324 |
+
|
| 325 |
+
util.errorRequest(client, request, err)
|
| 326 |
+
|
| 327 |
+
if (stream != null) {
|
| 328 |
+
// Some chunks might still come after abort,
|
| 329 |
+
// let's ignore them
|
| 330 |
+
stream.removeAllListeners('data')
|
| 331 |
+
|
| 332 |
+
// On Abort, we close the stream to send RST_STREAM frame
|
| 333 |
+
stream.close()
|
| 334 |
+
|
| 335 |
+
// We move the running index to the next request
|
| 336 |
+
client[kOnError](err)
|
| 337 |
+
client[kResume]()
|
| 338 |
+
}
|
| 339 |
+
|
| 340 |
+
// We do not destroy the socket as we can continue using the session
|
| 341 |
+
// the stream gets destroyed and the session remains to create new streams
|
| 342 |
+
util.destroy(body, err)
|
| 343 |
+
}
|
| 344 |
+
|
| 345 |
+
try {
|
| 346 |
+
// We are already connected, streams are pending.
|
| 347 |
+
// We can call on connect, and wait for abort
|
| 348 |
+
request.onConnect(abort)
|
| 349 |
+
} catch (err) {
|
| 350 |
+
util.errorRequest(client, request, err)
|
| 351 |
+
}
|
| 352 |
+
|
| 353 |
+
if (request.aborted) {
|
| 354 |
+
return false
|
| 355 |
+
}
|
| 356 |
+
|
| 357 |
+
if (method === 'CONNECT') {
|
| 358 |
+
session.ref()
|
| 359 |
+
// We are already connected, streams are pending, first request
|
| 360 |
+
// will create a new stream. We trigger a request to create the stream and wait until
|
| 361 |
+
// `ready` event is triggered
|
| 362 |
+
// We disabled endStream to allow the user to write to the stream
|
| 363 |
+
stream = session.request(headers, { endStream: false, signal })
|
| 364 |
+
|
| 365 |
+
if (!stream.pending) {
|
| 366 |
+
request.onUpgrade(null, null, stream)
|
| 367 |
+
++session[kOpenStreams]
|
| 368 |
+
client[kQueue][client[kRunningIdx]++] = null
|
| 369 |
+
} else {
|
| 370 |
+
stream.once('ready', () => {
|
| 371 |
+
request.onUpgrade(null, null, stream)
|
| 372 |
+
++session[kOpenStreams]
|
| 373 |
+
client[kQueue][client[kRunningIdx]++] = null
|
| 374 |
+
})
|
| 375 |
+
}
|
| 376 |
+
|
| 377 |
+
stream.once('close', () => {
|
| 378 |
+
session[kOpenStreams] -= 1
|
| 379 |
+
if (session[kOpenStreams] === 0) session.unref()
|
| 380 |
+
})
|
| 381 |
+
stream.setTimeout(requestTimeout)
|
| 382 |
+
|
| 383 |
+
return true
|
| 384 |
+
}
|
| 385 |
+
|
| 386 |
+
// https://tools.ietf.org/html/rfc7540#section-8.3
|
| 387 |
+
// :path and :scheme headers must be omitted when sending CONNECT
|
| 388 |
+
|
| 389 |
+
headers[HTTP2_HEADER_PATH] = path
|
| 390 |
+
headers[HTTP2_HEADER_SCHEME] = 'https'
|
| 391 |
+
|
| 392 |
+
// https://tools.ietf.org/html/rfc7231#section-4.3.1
|
| 393 |
+
// https://tools.ietf.org/html/rfc7231#section-4.3.2
|
| 394 |
+
// https://tools.ietf.org/html/rfc7231#section-4.3.5
|
| 395 |
+
|
| 396 |
+
// Sending a payload body on a request that does not
|
| 397 |
+
// expect it can cause undefined behavior on some
|
| 398 |
+
// servers and corrupt connection state. Do not
|
| 399 |
+
// re-use the connection for further requests.
|
| 400 |
+
|
| 401 |
+
const expectsPayload = (
|
| 402 |
+
method === 'PUT' ||
|
| 403 |
+
method === 'POST' ||
|
| 404 |
+
method === 'PATCH'
|
| 405 |
+
)
|
| 406 |
+
|
| 407 |
+
if (body && typeof body.read === 'function') {
|
| 408 |
+
// Try to read EOF in order to get length.
|
| 409 |
+
body.read(0)
|
| 410 |
+
}
|
| 411 |
+
|
| 412 |
+
let contentLength = util.bodyLength(body)
|
| 413 |
+
|
| 414 |
+
if (util.isFormDataLike(body)) {
|
| 415 |
+
extractBody ??= require('../web/fetch/body.js').extractBody
|
| 416 |
+
|
| 417 |
+
const [bodyStream, contentType] = extractBody(body)
|
| 418 |
+
headers['content-type'] = contentType
|
| 419 |
+
|
| 420 |
+
body = bodyStream.stream
|
| 421 |
+
contentLength = bodyStream.length
|
| 422 |
+
}
|
| 423 |
+
|
| 424 |
+
if (contentLength == null) {
|
| 425 |
+
contentLength = request.contentLength
|
| 426 |
+
}
|
| 427 |
+
|
| 428 |
+
if (contentLength === 0 || !expectsPayload) {
|
| 429 |
+
// https://tools.ietf.org/html/rfc7230#section-3.3.2
|
| 430 |
+
// A user agent SHOULD NOT send a Content-Length header field when
|
| 431 |
+
// the request message does not contain a payload body and the method
|
| 432 |
+
// semantics do not anticipate such a body.
|
| 433 |
+
|
| 434 |
+
contentLength = null
|
| 435 |
+
}
|
| 436 |
+
|
| 437 |
+
// https://github.com/nodejs/undici/issues/2046
|
| 438 |
+
// A user agent may send a Content-Length header with 0 value, this should be allowed.
|
| 439 |
+
if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength != null && request.contentLength !== contentLength) {
|
| 440 |
+
if (client[kStrictContentLength]) {
|
| 441 |
+
util.errorRequest(client, request, new RequestContentLengthMismatchError())
|
| 442 |
+
return false
|
| 443 |
+
}
|
| 444 |
+
|
| 445 |
+
process.emitWarning(new RequestContentLengthMismatchError())
|
| 446 |
+
}
|
| 447 |
+
|
| 448 |
+
if (contentLength != null) {
|
| 449 |
+
assert(body, 'no body must not have content length')
|
| 450 |
+
headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}`
|
| 451 |
+
}
|
| 452 |
+
|
| 453 |
+
session.ref()
|
| 454 |
+
|
| 455 |
+
if (channels.sendHeaders.hasSubscribers) {
|
| 456 |
+
let header = ''
|
| 457 |
+
for (const key in headers) {
|
| 458 |
+
header += `${key}: ${headers[key]}\r\n`
|
| 459 |
+
}
|
| 460 |
+
channels.sendHeaders.publish({ request, headers: header, socket: session[kSocket] })
|
| 461 |
+
}
|
| 462 |
+
|
| 463 |
+
// TODO(metcoder95): add support for sending trailers
|
| 464 |
+
const shouldEndStream = method === 'GET' || method === 'HEAD' || body === null
|
| 465 |
+
if (expectContinue) {
|
| 466 |
+
headers[HTTP2_HEADER_EXPECT] = '100-continue'
|
| 467 |
+
stream = session.request(headers, { endStream: shouldEndStream, signal })
|
| 468 |
+
|
| 469 |
+
stream.once('continue', writeBodyH2)
|
| 470 |
+
} else {
|
| 471 |
+
stream = session.request(headers, {
|
| 472 |
+
endStream: shouldEndStream,
|
| 473 |
+
signal
|
| 474 |
+
})
|
| 475 |
+
|
| 476 |
+
writeBodyH2()
|
| 477 |
+
}
|
| 478 |
+
|
| 479 |
+
// Increment counter as we have new streams open
|
| 480 |
+
++session[kOpenStreams]
|
| 481 |
+
stream.setTimeout(requestTimeout)
|
| 482 |
+
|
| 483 |
+
stream.once('response', headers => {
|
| 484 |
+
const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers
|
| 485 |
+
request.onResponseStarted()
|
| 486 |
+
|
| 487 |
+
// Due to the stream nature, it is possible we face a race condition
|
| 488 |
+
// where the stream has been assigned, but the request has been aborted
|
| 489 |
+
// the request remains in-flight and headers hasn't been received yet
|
| 490 |
+
// for those scenarios, best effort is to destroy the stream immediately
|
| 491 |
+
// as there's no value to keep it open.
|
| 492 |
+
if (request.aborted) {
|
| 493 |
+
stream.removeAllListeners('data')
|
| 494 |
+
return
|
| 495 |
+
}
|
| 496 |
+
|
| 497 |
+
if (request.onHeaders(Number(statusCode), parseH2Headers(realHeaders), stream.resume.bind(stream), '') === false) {
|
| 498 |
+
stream.pause()
|
| 499 |
+
}
|
| 500 |
+
})
|
| 501 |
+
|
| 502 |
+
stream.on('data', (chunk) => {
|
| 503 |
+
if (request.onData(chunk) === false) {
|
| 504 |
+
stream.pause()
|
| 505 |
+
}
|
| 506 |
+
})
|
| 507 |
+
|
| 508 |
+
stream.once('end', (err) => {
|
| 509 |
+
stream.removeAllListeners('data')
|
| 510 |
+
// When state is null, it means we haven't consumed body and the stream still do not have
|
| 511 |
+
// a state.
|
| 512 |
+
// Present specially when using pipeline or stream
|
| 513 |
+
if (stream.state?.state == null || stream.state.state < 6) {
|
| 514 |
+
// Do not complete the request if it was aborted
|
| 515 |
+
// Not prone to happen for as safety net to avoid race conditions with 'trailers'
|
| 516 |
+
if (!request.aborted && !request.completed) {
|
| 517 |
+
request.onComplete({})
|
| 518 |
+
}
|
| 519 |
+
|
| 520 |
+
client[kQueue][client[kRunningIdx]++] = null
|
| 521 |
+
client[kResume]()
|
| 522 |
+
} else {
|
| 523 |
+
// Stream is closed or half-closed-remote (6), decrement counter and cleanup
|
| 524 |
+
// It does not have sense to continue working with the stream as we do not
|
| 525 |
+
// have yet RST_STREAM support on client-side
|
| 526 |
+
--session[kOpenStreams]
|
| 527 |
+
if (session[kOpenStreams] === 0) {
|
| 528 |
+
session.unref()
|
| 529 |
+
}
|
| 530 |
+
|
| 531 |
+
abort(err ?? new InformationalError('HTTP/2: stream half-closed (remote)'))
|
| 532 |
+
client[kQueue][client[kRunningIdx]++] = null
|
| 533 |
+
client[kPendingIdx] = client[kRunningIdx]
|
| 534 |
+
client[kResume]()
|
| 535 |
+
}
|
| 536 |
+
})
|
| 537 |
+
|
| 538 |
+
stream.once('close', () => {
|
| 539 |
+
stream.removeAllListeners('data')
|
| 540 |
+
session[kOpenStreams] -= 1
|
| 541 |
+
if (session[kOpenStreams] === 0) {
|
| 542 |
+
session.unref()
|
| 543 |
+
}
|
| 544 |
+
})
|
| 545 |
+
|
| 546 |
+
stream.once('error', function (err) {
|
| 547 |
+
stream.removeAllListeners('data')
|
| 548 |
+
abort(err)
|
| 549 |
+
})
|
| 550 |
+
|
| 551 |
+
stream.once('frameError', (type, code) => {
|
| 552 |
+
stream.removeAllListeners('data')
|
| 553 |
+
abort(new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`))
|
| 554 |
+
})
|
| 555 |
+
|
| 556 |
+
stream.on('aborted', () => {
|
| 557 |
+
stream.removeAllListeners('data')
|
| 558 |
+
})
|
| 559 |
+
|
| 560 |
+
stream.on('timeout', () => {
|
| 561 |
+
const err = new InformationalError(`HTTP/2: "stream timeout after ${requestTimeout}"`)
|
| 562 |
+
stream.removeAllListeners('data')
|
| 563 |
+
session[kOpenStreams] -= 1
|
| 564 |
+
|
| 565 |
+
if (session[kOpenStreams] === 0) {
|
| 566 |
+
session.unref()
|
| 567 |
+
}
|
| 568 |
+
|
| 569 |
+
abort(err)
|
| 570 |
+
})
|
| 571 |
+
|
| 572 |
+
stream.once('trailers', trailers => {
|
| 573 |
+
if (request.aborted || request.completed) {
|
| 574 |
+
return
|
| 575 |
+
}
|
| 576 |
+
|
| 577 |
+
request.onComplete(trailers)
|
| 578 |
+
})
|
| 579 |
+
|
| 580 |
+
return true
|
| 581 |
+
|
| 582 |
+
function writeBodyH2 () {
|
| 583 |
+
/* istanbul ignore else: assertion */
|
| 584 |
+
if (!body || contentLength === 0) {
|
| 585 |
+
writeBuffer(
|
| 586 |
+
abort,
|
| 587 |
+
stream,
|
| 588 |
+
null,
|
| 589 |
+
client,
|
| 590 |
+
request,
|
| 591 |
+
client[kSocket],
|
| 592 |
+
contentLength,
|
| 593 |
+
expectsPayload
|
| 594 |
+
)
|
| 595 |
+
} else if (util.isBuffer(body)) {
|
| 596 |
+
writeBuffer(
|
| 597 |
+
abort,
|
| 598 |
+
stream,
|
| 599 |
+
body,
|
| 600 |
+
client,
|
| 601 |
+
request,
|
| 602 |
+
client[kSocket],
|
| 603 |
+
contentLength,
|
| 604 |
+
expectsPayload
|
| 605 |
+
)
|
| 606 |
+
} else if (util.isBlobLike(body)) {
|
| 607 |
+
if (typeof body.stream === 'function') {
|
| 608 |
+
writeIterable(
|
| 609 |
+
abort,
|
| 610 |
+
stream,
|
| 611 |
+
body.stream(),
|
| 612 |
+
client,
|
| 613 |
+
request,
|
| 614 |
+
client[kSocket],
|
| 615 |
+
contentLength,
|
| 616 |
+
expectsPayload
|
| 617 |
+
)
|
| 618 |
+
} else {
|
| 619 |
+
writeBlob(
|
| 620 |
+
abort,
|
| 621 |
+
stream,
|
| 622 |
+
body,
|
| 623 |
+
client,
|
| 624 |
+
request,
|
| 625 |
+
client[kSocket],
|
| 626 |
+
contentLength,
|
| 627 |
+
expectsPayload
|
| 628 |
+
)
|
| 629 |
+
}
|
| 630 |
+
} else if (util.isStream(body)) {
|
| 631 |
+
writeStream(
|
| 632 |
+
abort,
|
| 633 |
+
client[kSocket],
|
| 634 |
+
expectsPayload,
|
| 635 |
+
stream,
|
| 636 |
+
body,
|
| 637 |
+
client,
|
| 638 |
+
request,
|
| 639 |
+
contentLength
|
| 640 |
+
)
|
| 641 |
+
} else if (util.isIterable(body)) {
|
| 642 |
+
writeIterable(
|
| 643 |
+
abort,
|
| 644 |
+
stream,
|
| 645 |
+
body,
|
| 646 |
+
client,
|
| 647 |
+
request,
|
| 648 |
+
client[kSocket],
|
| 649 |
+
contentLength,
|
| 650 |
+
expectsPayload
|
| 651 |
+
)
|
| 652 |
+
} else {
|
| 653 |
+
assert(false)
|
| 654 |
+
}
|
| 655 |
+
}
|
| 656 |
+
}
|
| 657 |
+
|
| 658 |
+
function writeBuffer (abort, h2stream, body, client, request, socket, contentLength, expectsPayload) {
|
| 659 |
+
try {
|
| 660 |
+
if (body != null && util.isBuffer(body)) {
|
| 661 |
+
assert(contentLength === body.byteLength, 'buffer body must have content length')
|
| 662 |
+
h2stream.cork()
|
| 663 |
+
h2stream.write(body)
|
| 664 |
+
h2stream.uncork()
|
| 665 |
+
h2stream.end()
|
| 666 |
+
|
| 667 |
+
request.onBodySent(body)
|
| 668 |
+
}
|
| 669 |
+
|
| 670 |
+
if (!expectsPayload) {
|
| 671 |
+
socket[kReset] = true
|
| 672 |
+
}
|
| 673 |
+
|
| 674 |
+
request.onRequestSent()
|
| 675 |
+
client[kResume]()
|
| 676 |
+
} catch (error) {
|
| 677 |
+
abort(error)
|
| 678 |
+
}
|
| 679 |
+
}
|
| 680 |
+
|
| 681 |
+
function writeStream (abort, socket, expectsPayload, h2stream, body, client, request, contentLength) {
|
| 682 |
+
assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined')
|
| 683 |
+
|
| 684 |
+
// For HTTP/2, is enough to pipe the stream
|
| 685 |
+
const pipe = pipeline(
|
| 686 |
+
body,
|
| 687 |
+
h2stream,
|
| 688 |
+
(err) => {
|
| 689 |
+
if (err) {
|
| 690 |
+
util.destroy(pipe, err)
|
| 691 |
+
abort(err)
|
| 692 |
+
} else {
|
| 693 |
+
util.removeAllListeners(pipe)
|
| 694 |
+
request.onRequestSent()
|
| 695 |
+
|
| 696 |
+
if (!expectsPayload) {
|
| 697 |
+
socket[kReset] = true
|
| 698 |
+
}
|
| 699 |
+
|
| 700 |
+
client[kResume]()
|
| 701 |
+
}
|
| 702 |
+
}
|
| 703 |
+
)
|
| 704 |
+
|
| 705 |
+
util.addListener(pipe, 'data', onPipeData)
|
| 706 |
+
|
| 707 |
+
function onPipeData (chunk) {
|
| 708 |
+
request.onBodySent(chunk)
|
| 709 |
+
}
|
| 710 |
+
}
|
| 711 |
+
|
| 712 |
+
async function writeBlob (abort, h2stream, body, client, request, socket, contentLength, expectsPayload) {
|
| 713 |
+
assert(contentLength === body.size, 'blob body must have content length')
|
| 714 |
+
|
| 715 |
+
try {
|
| 716 |
+
if (contentLength != null && contentLength !== body.size) {
|
| 717 |
+
throw new RequestContentLengthMismatchError()
|
| 718 |
+
}
|
| 719 |
+
|
| 720 |
+
const buffer = Buffer.from(await body.arrayBuffer())
|
| 721 |
+
|
| 722 |
+
h2stream.cork()
|
| 723 |
+
h2stream.write(buffer)
|
| 724 |
+
h2stream.uncork()
|
| 725 |
+
h2stream.end()
|
| 726 |
+
|
| 727 |
+
request.onBodySent(buffer)
|
| 728 |
+
request.onRequestSent()
|
| 729 |
+
|
| 730 |
+
if (!expectsPayload) {
|
| 731 |
+
socket[kReset] = true
|
| 732 |
+
}
|
| 733 |
+
|
| 734 |
+
client[kResume]()
|
| 735 |
+
} catch (err) {
|
| 736 |
+
abort(err)
|
| 737 |
+
}
|
| 738 |
+
}
|
| 739 |
+
|
| 740 |
+
async function writeIterable (abort, h2stream, body, client, request, socket, contentLength, expectsPayload) {
|
| 741 |
+
assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined')
|
| 742 |
+
|
| 743 |
+
let callback = null
|
| 744 |
+
function onDrain () {
|
| 745 |
+
if (callback) {
|
| 746 |
+
const cb = callback
|
| 747 |
+
callback = null
|
| 748 |
+
cb()
|
| 749 |
+
}
|
| 750 |
+
}
|
| 751 |
+
|
| 752 |
+
const waitForDrain = () => new Promise((resolve, reject) => {
|
| 753 |
+
assert(callback === null)
|
| 754 |
+
|
| 755 |
+
if (socket[kError]) {
|
| 756 |
+
reject(socket[kError])
|
| 757 |
+
} else {
|
| 758 |
+
callback = resolve
|
| 759 |
+
}
|
| 760 |
+
})
|
| 761 |
+
|
| 762 |
+
h2stream
|
| 763 |
+
.on('close', onDrain)
|
| 764 |
+
.on('drain', onDrain)
|
| 765 |
+
|
| 766 |
+
try {
|
| 767 |
+
// It's up to the user to somehow abort the async iterable.
|
| 768 |
+
for await (const chunk of body) {
|
| 769 |
+
if (socket[kError]) {
|
| 770 |
+
throw socket[kError]
|
| 771 |
+
}
|
| 772 |
+
|
| 773 |
+
const res = h2stream.write(chunk)
|
| 774 |
+
request.onBodySent(chunk)
|
| 775 |
+
if (!res) {
|
| 776 |
+
await waitForDrain()
|
| 777 |
+
}
|
| 778 |
+
}
|
| 779 |
+
|
| 780 |
+
h2stream.end()
|
| 781 |
+
|
| 782 |
+
request.onRequestSent()
|
| 783 |
+
|
| 784 |
+
if (!expectsPayload) {
|
| 785 |
+
socket[kReset] = true
|
| 786 |
+
}
|
| 787 |
+
|
| 788 |
+
client[kResume]()
|
| 789 |
+
} catch (err) {
|
| 790 |
+
abort(err)
|
| 791 |
+
} finally {
|
| 792 |
+
h2stream
|
| 793 |
+
.off('close', onDrain)
|
| 794 |
+
.off('drain', onDrain)
|
| 795 |
+
}
|
| 796 |
+
}
|
| 797 |
+
|
| 798 |
+
module.exports = connectH2
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/dispatcher/client.js
ADDED
|
@@ -0,0 +1,614 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'use strict'
|
| 2 |
+
|
| 3 |
+
const assert = require('node:assert')
|
| 4 |
+
const net = require('node:net')
|
| 5 |
+
const http = require('node:http')
|
| 6 |
+
const util = require('../core/util.js')
|
| 7 |
+
const { ClientStats } = require('../util/stats.js')
|
| 8 |
+
const { channels } = require('../core/diagnostics.js')
|
| 9 |
+
const Request = require('../core/request.js')
|
| 10 |
+
const DispatcherBase = require('./dispatcher-base')
|
| 11 |
+
const {
|
| 12 |
+
InvalidArgumentError,
|
| 13 |
+
InformationalError,
|
| 14 |
+
ClientDestroyedError
|
| 15 |
+
} = require('../core/errors.js')
|
| 16 |
+
const buildConnector = require('../core/connect.js')
|
| 17 |
+
const {
|
| 18 |
+
kUrl,
|
| 19 |
+
kServerName,
|
| 20 |
+
kClient,
|
| 21 |
+
kBusy,
|
| 22 |
+
kConnect,
|
| 23 |
+
kResuming,
|
| 24 |
+
kRunning,
|
| 25 |
+
kPending,
|
| 26 |
+
kSize,
|
| 27 |
+
kQueue,
|
| 28 |
+
kConnected,
|
| 29 |
+
kConnecting,
|
| 30 |
+
kNeedDrain,
|
| 31 |
+
kKeepAliveDefaultTimeout,
|
| 32 |
+
kHostHeader,
|
| 33 |
+
kPendingIdx,
|
| 34 |
+
kRunningIdx,
|
| 35 |
+
kError,
|
| 36 |
+
kPipelining,
|
| 37 |
+
kKeepAliveTimeoutValue,
|
| 38 |
+
kMaxHeadersSize,
|
| 39 |
+
kKeepAliveMaxTimeout,
|
| 40 |
+
kKeepAliveTimeoutThreshold,
|
| 41 |
+
kHeadersTimeout,
|
| 42 |
+
kBodyTimeout,
|
| 43 |
+
kStrictContentLength,
|
| 44 |
+
kConnector,
|
| 45 |
+
kMaxRequests,
|
| 46 |
+
kCounter,
|
| 47 |
+
kClose,
|
| 48 |
+
kDestroy,
|
| 49 |
+
kDispatch,
|
| 50 |
+
kLocalAddress,
|
| 51 |
+
kMaxResponseSize,
|
| 52 |
+
kOnError,
|
| 53 |
+
kHTTPContext,
|
| 54 |
+
kMaxConcurrentStreams,
|
| 55 |
+
kResume
|
| 56 |
+
} = require('../core/symbols.js')
|
| 57 |
+
const connectH1 = require('./client-h1.js')
|
| 58 |
+
const connectH2 = require('./client-h2.js')
|
| 59 |
+
|
| 60 |
+
const kClosedResolve = Symbol('kClosedResolve')
|
| 61 |
+
|
| 62 |
+
const getDefaultNodeMaxHeaderSize = http &&
|
| 63 |
+
http.maxHeaderSize &&
|
| 64 |
+
Number.isInteger(http.maxHeaderSize) &&
|
| 65 |
+
http.maxHeaderSize > 0
|
| 66 |
+
? () => http.maxHeaderSize
|
| 67 |
+
: () => { throw new InvalidArgumentError('http module not available or http.maxHeaderSize invalid') }
|
| 68 |
+
|
| 69 |
+
const noop = () => {}
|
| 70 |
+
|
| 71 |
+
function getPipelining (client) {
|
| 72 |
+
return client[kPipelining] ?? client[kHTTPContext]?.defaultPipelining ?? 1
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
/**
|
| 76 |
+
* @type {import('../../types/client.js').default}
|
| 77 |
+
*/
|
| 78 |
+
class Client extends DispatcherBase {
|
| 79 |
+
/**
|
| 80 |
+
*
|
| 81 |
+
* @param {string|URL} url
|
| 82 |
+
* @param {import('../../types/client.js').Client.Options} options
|
| 83 |
+
*/
|
| 84 |
+
constructor (url, {
|
| 85 |
+
maxHeaderSize,
|
| 86 |
+
headersTimeout,
|
| 87 |
+
socketTimeout,
|
| 88 |
+
requestTimeout,
|
| 89 |
+
connectTimeout,
|
| 90 |
+
bodyTimeout,
|
| 91 |
+
idleTimeout,
|
| 92 |
+
keepAlive,
|
| 93 |
+
keepAliveTimeout,
|
| 94 |
+
maxKeepAliveTimeout,
|
| 95 |
+
keepAliveMaxTimeout,
|
| 96 |
+
keepAliveTimeoutThreshold,
|
| 97 |
+
socketPath,
|
| 98 |
+
pipelining,
|
| 99 |
+
tls,
|
| 100 |
+
strictContentLength,
|
| 101 |
+
maxCachedSessions,
|
| 102 |
+
connect,
|
| 103 |
+
maxRequestsPerClient,
|
| 104 |
+
localAddress,
|
| 105 |
+
maxResponseSize,
|
| 106 |
+
autoSelectFamily,
|
| 107 |
+
autoSelectFamilyAttemptTimeout,
|
| 108 |
+
// h2
|
| 109 |
+
maxConcurrentStreams,
|
| 110 |
+
allowH2
|
| 111 |
+
} = {}) {
|
| 112 |
+
if (keepAlive !== undefined) {
|
| 113 |
+
throw new InvalidArgumentError('unsupported keepAlive, use pipelining=0 instead')
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
if (socketTimeout !== undefined) {
|
| 117 |
+
throw new InvalidArgumentError('unsupported socketTimeout, use headersTimeout & bodyTimeout instead')
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
if (requestTimeout !== undefined) {
|
| 121 |
+
throw new InvalidArgumentError('unsupported requestTimeout, use headersTimeout & bodyTimeout instead')
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
if (idleTimeout !== undefined) {
|
| 125 |
+
throw new InvalidArgumentError('unsupported idleTimeout, use keepAliveTimeout instead')
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
if (maxKeepAliveTimeout !== undefined) {
|
| 129 |
+
throw new InvalidArgumentError('unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead')
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
if (maxHeaderSize != null) {
|
| 133 |
+
if (!Number.isInteger(maxHeaderSize) || maxHeaderSize < 1) {
|
| 134 |
+
throw new InvalidArgumentError('invalid maxHeaderSize')
|
| 135 |
+
}
|
| 136 |
+
} else {
|
| 137 |
+
// If maxHeaderSize is not provided, use the default value from the http module
|
| 138 |
+
// or if that is not available, throw an error.
|
| 139 |
+
maxHeaderSize = getDefaultNodeMaxHeaderSize()
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
if (socketPath != null && typeof socketPath !== 'string') {
|
| 143 |
+
throw new InvalidArgumentError('invalid socketPath')
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) {
|
| 147 |
+
throw new InvalidArgumentError('invalid connectTimeout')
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) {
|
| 151 |
+
throw new InvalidArgumentError('invalid keepAliveTimeout')
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) {
|
| 155 |
+
throw new InvalidArgumentError('invalid keepAliveMaxTimeout')
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) {
|
| 159 |
+
throw new InvalidArgumentError('invalid keepAliveTimeoutThreshold')
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) {
|
| 163 |
+
throw new InvalidArgumentError('headersTimeout must be a positive integer or zero')
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) {
|
| 167 |
+
throw new InvalidArgumentError('bodyTimeout must be a positive integer or zero')
|
| 168 |
+
}
|
| 169 |
+
|
| 170 |
+
if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {
|
| 171 |
+
throw new InvalidArgumentError('connect must be a function or an object')
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) {
|
| 175 |
+
throw new InvalidArgumentError('maxRequestsPerClient must be a positive number')
|
| 176 |
+
}
|
| 177 |
+
|
| 178 |
+
if (localAddress != null && (typeof localAddress !== 'string' || net.isIP(localAddress) === 0)) {
|
| 179 |
+
throw new InvalidArgumentError('localAddress must be valid string IP address')
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) {
|
| 183 |
+
throw new InvalidArgumentError('maxResponseSize must be a positive number')
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
if (
|
| 187 |
+
autoSelectFamilyAttemptTimeout != null &&
|
| 188 |
+
(!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1)
|
| 189 |
+
) {
|
| 190 |
+
throw new InvalidArgumentError('autoSelectFamilyAttemptTimeout must be a positive number')
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
// h2
|
| 194 |
+
if (allowH2 != null && typeof allowH2 !== 'boolean') {
|
| 195 |
+
throw new InvalidArgumentError('allowH2 must be a valid boolean value')
|
| 196 |
+
}
|
| 197 |
+
|
| 198 |
+
if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== 'number' || maxConcurrentStreams < 1)) {
|
| 199 |
+
throw new InvalidArgumentError('maxConcurrentStreams must be a positive integer, greater than 0')
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
super()
|
| 203 |
+
|
| 204 |
+
if (typeof connect !== 'function') {
|
| 205 |
+
connect = buildConnector({
|
| 206 |
+
...tls,
|
| 207 |
+
maxCachedSessions,
|
| 208 |
+
allowH2,
|
| 209 |
+
socketPath,
|
| 210 |
+
timeout: connectTimeout,
|
| 211 |
+
...(typeof autoSelectFamily === 'boolean' ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined),
|
| 212 |
+
...connect
|
| 213 |
+
})
|
| 214 |
+
}
|
| 215 |
+
|
| 216 |
+
this[kUrl] = util.parseOrigin(url)
|
| 217 |
+
this[kConnector] = connect
|
| 218 |
+
this[kPipelining] = pipelining != null ? pipelining : 1
|
| 219 |
+
this[kMaxHeadersSize] = maxHeaderSize
|
| 220 |
+
this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout
|
| 221 |
+
this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 600e3 : keepAliveMaxTimeout
|
| 222 |
+
this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 2e3 : keepAliveTimeoutThreshold
|
| 223 |
+
this[kKeepAliveTimeoutValue] = this[kKeepAliveDefaultTimeout]
|
| 224 |
+
this[kServerName] = null
|
| 225 |
+
this[kLocalAddress] = localAddress != null ? localAddress : null
|
| 226 |
+
this[kResuming] = 0 // 0, idle, 1, scheduled, 2 resuming
|
| 227 |
+
this[kNeedDrain] = 0 // 0, idle, 1, scheduled, 2 resuming
|
| 228 |
+
this[kHostHeader] = `host: ${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}\r\n`
|
| 229 |
+
this[kBodyTimeout] = bodyTimeout != null ? bodyTimeout : 300e3
|
| 230 |
+
this[kHeadersTimeout] = headersTimeout != null ? headersTimeout : 300e3
|
| 231 |
+
this[kStrictContentLength] = strictContentLength == null ? true : strictContentLength
|
| 232 |
+
this[kMaxRequests] = maxRequestsPerClient
|
| 233 |
+
this[kClosedResolve] = null
|
| 234 |
+
this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1
|
| 235 |
+
this[kMaxConcurrentStreams] = maxConcurrentStreams != null ? maxConcurrentStreams : 100 // Max peerConcurrentStreams for a Node h2 server
|
| 236 |
+
this[kHTTPContext] = null
|
| 237 |
+
|
| 238 |
+
// kQueue is built up of 3 sections separated by
|
| 239 |
+
// the kRunningIdx and kPendingIdx indices.
|
| 240 |
+
// | complete | running | pending |
|
| 241 |
+
// ^ kRunningIdx ^ kPendingIdx ^ kQueue.length
|
| 242 |
+
// kRunningIdx points to the first running element.
|
| 243 |
+
// kPendingIdx points to the first pending element.
|
| 244 |
+
// This implements a fast queue with an amortized
|
| 245 |
+
// time of O(1).
|
| 246 |
+
|
| 247 |
+
this[kQueue] = []
|
| 248 |
+
this[kRunningIdx] = 0
|
| 249 |
+
this[kPendingIdx] = 0
|
| 250 |
+
|
| 251 |
+
this[kResume] = (sync) => resume(this, sync)
|
| 252 |
+
this[kOnError] = (err) => onError(this, err)
|
| 253 |
+
}
|
| 254 |
+
|
| 255 |
+
get pipelining () {
|
| 256 |
+
return this[kPipelining]
|
| 257 |
+
}
|
| 258 |
+
|
| 259 |
+
set pipelining (value) {
|
| 260 |
+
this[kPipelining] = value
|
| 261 |
+
this[kResume](true)
|
| 262 |
+
}
|
| 263 |
+
|
| 264 |
+
get stats () {
|
| 265 |
+
return new ClientStats(this)
|
| 266 |
+
}
|
| 267 |
+
|
| 268 |
+
get [kPending] () {
|
| 269 |
+
return this[kQueue].length - this[kPendingIdx]
|
| 270 |
+
}
|
| 271 |
+
|
| 272 |
+
get [kRunning] () {
|
| 273 |
+
return this[kPendingIdx] - this[kRunningIdx]
|
| 274 |
+
}
|
| 275 |
+
|
| 276 |
+
get [kSize] () {
|
| 277 |
+
return this[kQueue].length - this[kRunningIdx]
|
| 278 |
+
}
|
| 279 |
+
|
| 280 |
+
get [kConnected] () {
|
| 281 |
+
return !!this[kHTTPContext] && !this[kConnecting] && !this[kHTTPContext].destroyed
|
| 282 |
+
}
|
| 283 |
+
|
| 284 |
+
get [kBusy] () {
|
| 285 |
+
return Boolean(
|
| 286 |
+
this[kHTTPContext]?.busy(null) ||
|
| 287 |
+
(this[kSize] >= (getPipelining(this) || 1)) ||
|
| 288 |
+
this[kPending] > 0
|
| 289 |
+
)
|
| 290 |
+
}
|
| 291 |
+
|
| 292 |
+
/* istanbul ignore: only used for test */
|
| 293 |
+
[kConnect] (cb) {
|
| 294 |
+
connect(this)
|
| 295 |
+
this.once('connect', cb)
|
| 296 |
+
}
|
| 297 |
+
|
| 298 |
+
[kDispatch] (opts, handler) {
|
| 299 |
+
const origin = opts.origin || this[kUrl].origin
|
| 300 |
+
const request = new Request(origin, opts, handler)
|
| 301 |
+
|
| 302 |
+
this[kQueue].push(request)
|
| 303 |
+
if (this[kResuming]) {
|
| 304 |
+
// Do nothing.
|
| 305 |
+
} else if (util.bodyLength(request.body) == null && util.isIterable(request.body)) {
|
| 306 |
+
// Wait a tick in case stream/iterator is ended in the same tick.
|
| 307 |
+
this[kResuming] = 1
|
| 308 |
+
queueMicrotask(() => resume(this))
|
| 309 |
+
} else {
|
| 310 |
+
this[kResume](true)
|
| 311 |
+
}
|
| 312 |
+
|
| 313 |
+
if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) {
|
| 314 |
+
this[kNeedDrain] = 2
|
| 315 |
+
}
|
| 316 |
+
|
| 317 |
+
return this[kNeedDrain] < 2
|
| 318 |
+
}
|
| 319 |
+
|
| 320 |
+
async [kClose] () {
|
| 321 |
+
// TODO: for H2 we need to gracefully flush the remaining enqueued
|
| 322 |
+
// request and close each stream.
|
| 323 |
+
return new Promise((resolve) => {
|
| 324 |
+
if (this[kSize]) {
|
| 325 |
+
this[kClosedResolve] = resolve
|
| 326 |
+
} else {
|
| 327 |
+
resolve(null)
|
| 328 |
+
}
|
| 329 |
+
})
|
| 330 |
+
}
|
| 331 |
+
|
| 332 |
+
async [kDestroy] (err) {
|
| 333 |
+
return new Promise((resolve) => {
|
| 334 |
+
const requests = this[kQueue].splice(this[kPendingIdx])
|
| 335 |
+
for (let i = 0; i < requests.length; i++) {
|
| 336 |
+
const request = requests[i]
|
| 337 |
+
util.errorRequest(this, request, err)
|
| 338 |
+
}
|
| 339 |
+
|
| 340 |
+
const callback = () => {
|
| 341 |
+
if (this[kClosedResolve]) {
|
| 342 |
+
// TODO (fix): Should we error here with ClientDestroyedError?
|
| 343 |
+
this[kClosedResolve]()
|
| 344 |
+
this[kClosedResolve] = null
|
| 345 |
+
}
|
| 346 |
+
resolve(null)
|
| 347 |
+
}
|
| 348 |
+
|
| 349 |
+
if (this[kHTTPContext]) {
|
| 350 |
+
this[kHTTPContext].destroy(err, callback)
|
| 351 |
+
this[kHTTPContext] = null
|
| 352 |
+
} else {
|
| 353 |
+
queueMicrotask(callback)
|
| 354 |
+
}
|
| 355 |
+
|
| 356 |
+
this[kResume]()
|
| 357 |
+
})
|
| 358 |
+
}
|
| 359 |
+
}
|
| 360 |
+
|
| 361 |
+
function onError (client, err) {
|
| 362 |
+
if (
|
| 363 |
+
client[kRunning] === 0 &&
|
| 364 |
+
err.code !== 'UND_ERR_INFO' &&
|
| 365 |
+
err.code !== 'UND_ERR_SOCKET'
|
| 366 |
+
) {
|
| 367 |
+
// Error is not caused by running request and not a recoverable
|
| 368 |
+
// socket error.
|
| 369 |
+
|
| 370 |
+
assert(client[kPendingIdx] === client[kRunningIdx])
|
| 371 |
+
|
| 372 |
+
const requests = client[kQueue].splice(client[kRunningIdx])
|
| 373 |
+
|
| 374 |
+
for (let i = 0; i < requests.length; i++) {
|
| 375 |
+
const request = requests[i]
|
| 376 |
+
util.errorRequest(client, request, err)
|
| 377 |
+
}
|
| 378 |
+
assert(client[kSize] === 0)
|
| 379 |
+
}
|
| 380 |
+
}
|
| 381 |
+
|
| 382 |
+
/**
|
| 383 |
+
* @param {Client} client
|
| 384 |
+
* @returns
|
| 385 |
+
*/
|
| 386 |
+
async function connect (client) {
|
| 387 |
+
assert(!client[kConnecting])
|
| 388 |
+
assert(!client[kHTTPContext])
|
| 389 |
+
|
| 390 |
+
let { host, hostname, protocol, port } = client[kUrl]
|
| 391 |
+
|
| 392 |
+
// Resolve ipv6
|
| 393 |
+
if (hostname[0] === '[') {
|
| 394 |
+
const idx = hostname.indexOf(']')
|
| 395 |
+
|
| 396 |
+
assert(idx !== -1)
|
| 397 |
+
const ip = hostname.substring(1, idx)
|
| 398 |
+
|
| 399 |
+
assert(net.isIPv6(ip))
|
| 400 |
+
hostname = ip
|
| 401 |
+
}
|
| 402 |
+
|
| 403 |
+
client[kConnecting] = true
|
| 404 |
+
|
| 405 |
+
if (channels.beforeConnect.hasSubscribers) {
|
| 406 |
+
channels.beforeConnect.publish({
|
| 407 |
+
connectParams: {
|
| 408 |
+
host,
|
| 409 |
+
hostname,
|
| 410 |
+
protocol,
|
| 411 |
+
port,
|
| 412 |
+
version: client[kHTTPContext]?.version,
|
| 413 |
+
servername: client[kServerName],
|
| 414 |
+
localAddress: client[kLocalAddress]
|
| 415 |
+
},
|
| 416 |
+
connector: client[kConnector]
|
| 417 |
+
})
|
| 418 |
+
}
|
| 419 |
+
|
| 420 |
+
try {
|
| 421 |
+
const socket = await new Promise((resolve, reject) => {
|
| 422 |
+
client[kConnector]({
|
| 423 |
+
host,
|
| 424 |
+
hostname,
|
| 425 |
+
protocol,
|
| 426 |
+
port,
|
| 427 |
+
servername: client[kServerName],
|
| 428 |
+
localAddress: client[kLocalAddress]
|
| 429 |
+
}, (err, socket) => {
|
| 430 |
+
if (err) {
|
| 431 |
+
reject(err)
|
| 432 |
+
} else {
|
| 433 |
+
resolve(socket)
|
| 434 |
+
}
|
| 435 |
+
})
|
| 436 |
+
})
|
| 437 |
+
|
| 438 |
+
if (client.destroyed) {
|
| 439 |
+
util.destroy(socket.on('error', noop), new ClientDestroyedError())
|
| 440 |
+
return
|
| 441 |
+
}
|
| 442 |
+
|
| 443 |
+
assert(socket)
|
| 444 |
+
|
| 445 |
+
try {
|
| 446 |
+
client[kHTTPContext] = socket.alpnProtocol === 'h2'
|
| 447 |
+
? await connectH2(client, socket)
|
| 448 |
+
: await connectH1(client, socket)
|
| 449 |
+
} catch (err) {
|
| 450 |
+
socket.destroy().on('error', noop)
|
| 451 |
+
throw err
|
| 452 |
+
}
|
| 453 |
+
|
| 454 |
+
client[kConnecting] = false
|
| 455 |
+
|
| 456 |
+
socket[kCounter] = 0
|
| 457 |
+
socket[kMaxRequests] = client[kMaxRequests]
|
| 458 |
+
socket[kClient] = client
|
| 459 |
+
socket[kError] = null
|
| 460 |
+
|
| 461 |
+
if (channels.connected.hasSubscribers) {
|
| 462 |
+
channels.connected.publish({
|
| 463 |
+
connectParams: {
|
| 464 |
+
host,
|
| 465 |
+
hostname,
|
| 466 |
+
protocol,
|
| 467 |
+
port,
|
| 468 |
+
version: client[kHTTPContext]?.version,
|
| 469 |
+
servername: client[kServerName],
|
| 470 |
+
localAddress: client[kLocalAddress]
|
| 471 |
+
},
|
| 472 |
+
connector: client[kConnector],
|
| 473 |
+
socket
|
| 474 |
+
})
|
| 475 |
+
}
|
| 476 |
+
client.emit('connect', client[kUrl], [client])
|
| 477 |
+
} catch (err) {
|
| 478 |
+
if (client.destroyed) {
|
| 479 |
+
return
|
| 480 |
+
}
|
| 481 |
+
|
| 482 |
+
client[kConnecting] = false
|
| 483 |
+
|
| 484 |
+
if (channels.connectError.hasSubscribers) {
|
| 485 |
+
channels.connectError.publish({
|
| 486 |
+
connectParams: {
|
| 487 |
+
host,
|
| 488 |
+
hostname,
|
| 489 |
+
protocol,
|
| 490 |
+
port,
|
| 491 |
+
version: client[kHTTPContext]?.version,
|
| 492 |
+
servername: client[kServerName],
|
| 493 |
+
localAddress: client[kLocalAddress]
|
| 494 |
+
},
|
| 495 |
+
connector: client[kConnector],
|
| 496 |
+
error: err
|
| 497 |
+
})
|
| 498 |
+
}
|
| 499 |
+
|
| 500 |
+
if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') {
|
| 501 |
+
assert(client[kRunning] === 0)
|
| 502 |
+
while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) {
|
| 503 |
+
const request = client[kQueue][client[kPendingIdx]++]
|
| 504 |
+
util.errorRequest(client, request, err)
|
| 505 |
+
}
|
| 506 |
+
} else {
|
| 507 |
+
onError(client, err)
|
| 508 |
+
}
|
| 509 |
+
|
| 510 |
+
client.emit('connectionError', client[kUrl], [client], err)
|
| 511 |
+
}
|
| 512 |
+
|
| 513 |
+
client[kResume]()
|
| 514 |
+
}
|
| 515 |
+
|
| 516 |
+
function emitDrain (client) {
|
| 517 |
+
client[kNeedDrain] = 0
|
| 518 |
+
client.emit('drain', client[kUrl], [client])
|
| 519 |
+
}
|
| 520 |
+
|
| 521 |
+
function resume (client, sync) {
|
| 522 |
+
if (client[kResuming] === 2) {
|
| 523 |
+
return
|
| 524 |
+
}
|
| 525 |
+
|
| 526 |
+
client[kResuming] = 2
|
| 527 |
+
|
| 528 |
+
_resume(client, sync)
|
| 529 |
+
client[kResuming] = 0
|
| 530 |
+
|
| 531 |
+
if (client[kRunningIdx] > 256) {
|
| 532 |
+
client[kQueue].splice(0, client[kRunningIdx])
|
| 533 |
+
client[kPendingIdx] -= client[kRunningIdx]
|
| 534 |
+
client[kRunningIdx] = 0
|
| 535 |
+
}
|
| 536 |
+
}
|
| 537 |
+
|
| 538 |
+
function _resume (client, sync) {
|
| 539 |
+
while (true) {
|
| 540 |
+
if (client.destroyed) {
|
| 541 |
+
assert(client[kPending] === 0)
|
| 542 |
+
return
|
| 543 |
+
}
|
| 544 |
+
|
| 545 |
+
if (client[kClosedResolve] && !client[kSize]) {
|
| 546 |
+
client[kClosedResolve]()
|
| 547 |
+
client[kClosedResolve] = null
|
| 548 |
+
return
|
| 549 |
+
}
|
| 550 |
+
|
| 551 |
+
if (client[kHTTPContext]) {
|
| 552 |
+
client[kHTTPContext].resume()
|
| 553 |
+
}
|
| 554 |
+
|
| 555 |
+
if (client[kBusy]) {
|
| 556 |
+
client[kNeedDrain] = 2
|
| 557 |
+
} else if (client[kNeedDrain] === 2) {
|
| 558 |
+
if (sync) {
|
| 559 |
+
client[kNeedDrain] = 1
|
| 560 |
+
queueMicrotask(() => emitDrain(client))
|
| 561 |
+
} else {
|
| 562 |
+
emitDrain(client)
|
| 563 |
+
}
|
| 564 |
+
continue
|
| 565 |
+
}
|
| 566 |
+
|
| 567 |
+
if (client[kPending] === 0) {
|
| 568 |
+
return
|
| 569 |
+
}
|
| 570 |
+
|
| 571 |
+
if (client[kRunning] >= (getPipelining(client) || 1)) {
|
| 572 |
+
return
|
| 573 |
+
}
|
| 574 |
+
|
| 575 |
+
const request = client[kQueue][client[kPendingIdx]]
|
| 576 |
+
|
| 577 |
+
if (client[kUrl].protocol === 'https:' && client[kServerName] !== request.servername) {
|
| 578 |
+
if (client[kRunning] > 0) {
|
| 579 |
+
return
|
| 580 |
+
}
|
| 581 |
+
|
| 582 |
+
client[kServerName] = request.servername
|
| 583 |
+
client[kHTTPContext]?.destroy(new InformationalError('servername changed'), () => {
|
| 584 |
+
client[kHTTPContext] = null
|
| 585 |
+
resume(client)
|
| 586 |
+
})
|
| 587 |
+
}
|
| 588 |
+
|
| 589 |
+
if (client[kConnecting]) {
|
| 590 |
+
return
|
| 591 |
+
}
|
| 592 |
+
|
| 593 |
+
if (!client[kHTTPContext]) {
|
| 594 |
+
connect(client)
|
| 595 |
+
return
|
| 596 |
+
}
|
| 597 |
+
|
| 598 |
+
if (client[kHTTPContext].destroyed) {
|
| 599 |
+
return
|
| 600 |
+
}
|
| 601 |
+
|
| 602 |
+
if (client[kHTTPContext].busy(request)) {
|
| 603 |
+
return
|
| 604 |
+
}
|
| 605 |
+
|
| 606 |
+
if (!request.aborted && client[kHTTPContext].write(request)) {
|
| 607 |
+
client[kPendingIdx]++
|
| 608 |
+
} else {
|
| 609 |
+
client[kQueue].splice(client[kPendingIdx], 1)
|
| 610 |
+
}
|
| 611 |
+
}
|
| 612 |
+
}
|
| 613 |
+
|
| 614 |
+
module.exports = Client
|
platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/undici/lib/dispatcher/dispatcher-base.js
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'use strict'
|
| 2 |
+
|
| 3 |
+
const Dispatcher = require('./dispatcher')
|
| 4 |
+
const UnwrapHandler = require('../handler/unwrap-handler')
|
| 5 |
+
const {
|
| 6 |
+
ClientDestroyedError,
|
| 7 |
+
ClientClosedError,
|
| 8 |
+
InvalidArgumentError
|
| 9 |
+
} = require('../core/errors')
|
| 10 |
+
const { kDestroy, kClose, kClosed, kDestroyed, kDispatch } = require('../core/symbols')
|
| 11 |
+
|
| 12 |
+
const kOnDestroyed = Symbol('onDestroyed')
|
| 13 |
+
const kOnClosed = Symbol('onClosed')
|
| 14 |
+
|
| 15 |
+
class DispatcherBase extends Dispatcher {
|
| 16 |
+
constructor () {
|
| 17 |
+
super()
|
| 18 |
+
|
| 19 |
+
this[kDestroyed] = false
|
| 20 |
+
this[kOnDestroyed] = null
|
| 21 |
+
this[kClosed] = false
|
| 22 |
+
this[kOnClosed] = []
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
get destroyed () {
|
| 26 |
+
return this[kDestroyed]
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
get closed () {
|
| 30 |
+
return this[kClosed]
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
close (callback) {
|
| 34 |
+
if (callback === undefined) {
|
| 35 |
+
return new Promise((resolve, reject) => {
|
| 36 |
+
this.close((err, data) => {
|
| 37 |
+
return err ? reject(err) : resolve(data)
|
| 38 |
+
})
|
| 39 |
+
})
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
if (typeof callback !== 'function') {
|
| 43 |
+
throw new InvalidArgumentError('invalid callback')
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
if (this[kDestroyed]) {
|
| 47 |
+
queueMicrotask(() => callback(new ClientDestroyedError(), null))
|
| 48 |
+
return
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
if (this[kClosed]) {
|
| 52 |
+
if (this[kOnClosed]) {
|
| 53 |
+
this[kOnClosed].push(callback)
|
| 54 |
+
} else {
|
| 55 |
+
queueMicrotask(() => callback(null, null))
|
| 56 |
+
}
|
| 57 |
+
return
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
this[kClosed] = true
|
| 61 |
+
this[kOnClosed].push(callback)
|
| 62 |
+
|
| 63 |
+
const onClosed = () => {
|
| 64 |
+
const callbacks = this[kOnClosed]
|
| 65 |
+
this[kOnClosed] = null
|
| 66 |
+
for (let i = 0; i < callbacks.length; i++) {
|
| 67 |
+
callbacks[i](null, null)
|
| 68 |
+
}
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
// Should not error.
|
| 72 |
+
this[kClose]()
|
| 73 |
+
.then(() => this.destroy())
|
| 74 |
+
.then(() => {
|
| 75 |
+
queueMicrotask(onClosed)
|
| 76 |
+
})
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
destroy (err, callback) {
|
| 80 |
+
if (typeof err === 'function') {
|
| 81 |
+
callback = err
|
| 82 |
+
err = null
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
if (callback === undefined) {
|
| 86 |
+
return new Promise((resolve, reject) => {
|
| 87 |
+
this.destroy(err, (err, data) => {
|
| 88 |
+
return err ? /* istanbul ignore next: should never error */ reject(err) : resolve(data)
|
| 89 |
+
})
|
| 90 |
+
})
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
if (typeof callback !== 'function') {
|
| 94 |
+
throw new InvalidArgumentError('invalid callback')
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
if (this[kDestroyed]) {
|
| 98 |
+
if (this[kOnDestroyed]) {
|
| 99 |
+
this[kOnDestroyed].push(callback)
|
| 100 |
+
} else {
|
| 101 |
+
queueMicrotask(() => callback(null, null))
|
| 102 |
+
}
|
| 103 |
+
return
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
if (!err) {
|
| 107 |
+
err = new ClientDestroyedError()
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
this[kDestroyed] = true
|
| 111 |
+
this[kOnDestroyed] = this[kOnDestroyed] || []
|
| 112 |
+
this[kOnDestroyed].push(callback)
|
| 113 |
+
|
| 114 |
+
const onDestroyed = () => {
|
| 115 |
+
const callbacks = this[kOnDestroyed]
|
| 116 |
+
this[kOnDestroyed] = null
|
| 117 |
+
for (let i = 0; i < callbacks.length; i++) {
|
| 118 |
+
callbacks[i](null, null)
|
| 119 |
+
}
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
// Should not error.
|
| 123 |
+
this[kDestroy](err).then(() => {
|
| 124 |
+
queueMicrotask(onDestroyed)
|
| 125 |
+
})
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
dispatch (opts, handler) {
|
| 129 |
+
if (!handler || typeof handler !== 'object') {
|
| 130 |
+
throw new InvalidArgumentError('handler must be an object')
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
handler = UnwrapHandler.unwrap(handler)
|
| 134 |
+
|
| 135 |
+
try {
|
| 136 |
+
if (!opts || typeof opts !== 'object') {
|
| 137 |
+
throw new InvalidArgumentError('opts must be an object.')
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
if (this[kDestroyed] || this[kOnDestroyed]) {
|
| 141 |
+
throw new ClientDestroyedError()
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
if (this[kClosed]) {
|
| 145 |
+
throw new ClientClosedError()
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
return this[kDispatch](opts, handler)
|
| 149 |
+
} catch (err) {
|
| 150 |
+
if (typeof handler.onError !== 'function') {
|
| 151 |
+
throw err
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
handler.onError(err)
|
| 155 |
+
|
| 156 |
+
return false
|
| 157 |
+
}
|
| 158 |
+
}
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
module.exports = DispatcherBase
|