node_modules ignore

This commit is contained in:
2025-05-08 23:43:47 +02:00
parent e19d52f172
commit 4574544c9f
65041 changed files with 10593536 additions and 0 deletions

21
server/node_modules/get-it/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
The MIT License
Copyright (c) 2025, Sanity.io <hello@sanity.io>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.

197
server/node_modules/get-it/README.md generated vendored Normal file
View File

@@ -0,0 +1,197 @@
# get-it
[![npm stat](https://img.shields.io/npm/dm/get-it.svg?style=flat-square)](https://npm-stat.com/charts.html?package=get-it)
[![npm version](https://img.shields.io/npm/v/get-it.svg?style=flat-square)](https://www.npmjs.com/package/get-it)
[![gzip size][gzip-badge]][bundlephobia]
[![size][size-badge]][bundlephobia]
Generic HTTP request library for node.js (>= 14) and [modern browsers].
## Motivation
We wanted an HTTP request library that worked transparently in Node.js and browsers with a small browser bundle footprint.
To be able to use the same library in a range of different applications with varying requirements, but still keep the bundle size down, we took inspiration from [http-client](https://github.com/mjackson/http-client) which cleverly composes functionality into the client.
## Features
Using a middleware approach, `get-it` has the following feature set:
- Promise, observable and low-level event-emitter patterns
- Automatic retrying with customizable number of attempts and filtering functionality
- Cancellation of requests
- Configurable connect/socket timeouts
- Automatic parsing of JSON responses
- Automatic stringifying of JSON request bodies
- Automatic gzip unwrapping in Node
- Automatically prepend base URL
- Automatically follow redirects (configurable number of retries)
- Upload/download progress events
- Treat HTTP status codes >=400 as errors
- Debug requests with environment variables/localStorage setting
## Usage
How `get-it` behaves depends on which middleware you've loaded, but common to all approaches is the setup process.
```js
// Import the core get-it package, which is used to generate a requester
import {getIt} from 'get-it'
// And import whatever middleware you want to use
import {base, jsonResponse, promise} from 'get-it/middleware'
// Now compose the middleware you want to use
const request = getIt([base('https://api.your.service/v1'), jsonResponse()])
// You can also register middleware using `.use(middleware)`
request.use(promise())
// Now you're ready to use the requester:
request({url: '/projects'})
.then((response) => console.log(response.body))
.catch((err) => console.error(err))
```
In most larger projects, you'd probably make a `httpClient.js` or similar, where you would instantiate the requester and export it for other modules to reuse.
## Options
- `url` - URL to the resource you want to reach.
- `method` - HTTP method to use for request. Default: `GET`, unless a body is provided, in which case the default is `POST`.
- `headers` - Object of HTTP headers to send. Note that cross-origin requests in IE9 will not be able to set these headers.
- `body` - The request body. If the `jsonRequest` middleware is used, it will serialize to a JSON string before sending. Otherwise, it tries to send whatever is passed to it using the underlying adapter. Supported types:
- _Browser_: `string`, `ArrayBufferView`, `Blob`, `Document`, `FormData` (deprecated: `ArrayBuffer`)
- _Node_: `string`, `Buffer`, `Iterable`, `AsyncIterable`, `stream.Readable`
- `bodySize` - Size of body, in bytes. Only used in Node when passing a `ReadStream` as body, in order for progress events to emit status on upload progress.
- `timeout` - Timeout in millisecond for the request. Takes an object with `connect` and `socket` properties.
- `maxRedirects` - Maximum number of redirects to follow before giving up. Note that this is only used in Node, as browsers have built-in redirect handling which cannot be adjusted. Default: `5`
- `rawBody` - Set to `true` to return the raw value of the response body, instead of a string. The type returned differs based on the underlying adapter:
- _Browser_: `ArrayBuffer`
- _Node_: `Buffer`
## Return values
By default, `get-it` will return an object of single-channel event emitters. This is done in order to provide a low-level API surface that others can build upon, which is what the `promise` and `observable` middlewares do. Unless you really know what you're doing, you'll probably want to use those middlewares.
## Response objects
`get-it` does not expose the low-level primitives such as the `XMLHttpRequest` or `http.IncomingMessage` instances. Instead, it provides a response object with the following properties:
```js
{
// body is `string` by default. When `rawBody` is set to true, will return `ArrayBuffer` in browsers and `Buffer` in Node.js.
body: 'Response body'
// The final URL, after following redirects (configure `maxRedirects` to change the number of redirects to follow)
url: 'http://foo.bar/baz',
method: 'GET',
statusCode: 200,
statusMessage: 'OK',
headers: {
'Date': 'Fri, 09 Dec 2016 14:55:32 GMT',
'Cache-Control': 'public, max-age=120'
}
}
```
## Promise API
For the most part, you simply have to register the middleware and you should be good to go. Sometimes you only need the response body, in which case you can set the `onlyBody` option to `true`. Otherwise the promise will be resolved with the response object mentioned earlier.
```js
import {getIt} from 'get-it'
import {promise} from 'get-it/middleware'
const request = getIt([promise({onlyBody: true})])
request({url: 'http://foo.bar/api/projects'})
.then((projects) => console.log(projects))
.catch((err) => console.error(err))
```
### Cancelling promise-based requests
With the Promise API, you can cancel requests using a _cancel token_. This API is based on the [Cancelable Promises proposal](https://github.com/tc39/proposal-cancelable-promises), which was at Stage 1 before it was withdrawn.
You can create a cancel token using the `CancelToken.source` factory as shown below:
```js
import {promise} from 'get-it/middleware'
const request = getIt([promise()])
const source = promise.CancelToken.source()
request
.get({
url: 'http://foo.bar/baz',
cancelToken: source.token,
})
.catch((err) => {
if (promise.isCancel(err)) {
console.log('Request canceled', err.message)
} else {
// handle error
}
})
// Cancel the request (the message parameter is optional)
source.cancel('Operation canceled by the user')
```
## Observable API
The observable API requires you to pass an Observable-implementation that you want to use. Optionally, you can register it under the global `Observable`, but this is not recommended.
```js
import {getIt} from 'get-it'
import {observable} from 'get-it/middleware'
import {Observable as RxjsObservable} from 'rxjs'
const request = getIt()
request.use(
observable({
implementation: RxjsObservable,
}),
)
const observer = request({url: 'http://foo.bar/baz'})
.filter((ev) => ev.type === 'response')
.subscribe({
next: (res) => console.log(res.body),
error: (err) => console.error(err),
})
// If you want to cancel the request, simply unsubscribe:
observer.unsubscribe()
```
It's important to note that the observable middleware does not only emit `response` objects, but also `progress` events. You should always filter to specify what you're interested in receiving. Every emitted value has a `type` property.
## Prior art
This module was inspired by the great work of others:
- [got](https://github.com/sindresorhus/got)
- [simple-get](https://github.com/feross/simple-get)
- [xhr](https://github.com/naugtur/xhr)
- [Axios](https://github.com/mzabriskie/axios/)
- [http-client](https://github.com/mjackson/http-client)
- [request](https://github.com/request/request)
## License
MIT-licensed. See LICENSE.
## Release new version
Run the ["CI & Release" workflow](https://github.com/sanity-io/get-it/actions).
Make sure to select the main branch and check "Release new version".
Semantic release will only release on configured branches, so it is safe to run release on any branch.
[gzip-badge]: https://img.shields.io/bundlephobia/minzip/get-it?label=gzip%20size&style=flat-square
[size-badge]: https://img.shields.io/bundlephobia/min/get-it?label=size&style=flat-square
[bundlephobia]: https://bundlephobia.com/package/get-it
[modern browsers]: https://browsersl.ist/#q=%3E+0.2%25+and+supports+es6-module+and+supports+es6-module-dynamic-import+and+not+dead+and+not+IE+11

View File

@@ -0,0 +1 @@
"use strict";const e=!(typeof navigator>"u")&&"ReactNative"===navigator.product,t={timeout:e?6e4:12e4};function r(e){return decodeURIComponent(e.replace(/\+/g," "))}function o(e){if(!1===e||0===e)return!1;if(e.connect||e.socket)return e;const r=Number(e);return isNaN(r)?o(t.timeout):{connect:r,socket:r}}const n=/^https?:\/\//i;exports.g=function(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e},exports.p=function(n){const s={...t,..."string"==typeof n?{url:n}:n};if(s.timeout=o(s.timeout),s.query){const{url:t,searchParams:o}=function(t){const o=t.indexOf("?");if(-1===o)return{url:t,searchParams:new URLSearchParams};const n=t.slice(0,o),s=t.slice(o+1);if(!e)return{url:n,searchParams:new URLSearchParams(s)};if("function"!=typeof decodeURIComponent)throw new Error("Broken `URLSearchParams` implementation, and `decodeURIComponent` is not defined");const a=new URLSearchParams;for(const e of s.split("&")){const[t,o]=e.split("=");t&&a.append(r(t),r(o||""))}return{url:n,searchParams:a}}(s.url);for(const[e,r]of Object.entries(s.query)){if(void 0!==r)if(Array.isArray(r))for(const t of r)o.append(e,t);else o.append(e,r);const n=o.toString();n&&(s.url=`${t}?${n}`)}}return s.method=s.body&&!s.method?"POST":(s.method||"GET").toUpperCase(),s},exports.v=function(e){if(!n.test(e.url))throw new Error(`"${e.url}" is not a valid URL`)};//# sourceMappingURL=_commonjsHelpers.cjs.map

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
const e=!(typeof navigator>"u")&&"ReactNative"===navigator.product,t={timeout:e?6e4:12e4},r=function(r){const a={...t,..."string"==typeof r?{url:r}:r};if(a.timeout=n(a.timeout),a.query){const{url:t,searchParams:r}=function(t){const r=t.indexOf("?");if(-1===r)return{url:t,searchParams:new URLSearchParams};const n=t.slice(0,r),a=t.slice(r+1);if(!e)return{url:n,searchParams:new URLSearchParams(a)};if("function"!=typeof decodeURIComponent)throw new Error("Broken `URLSearchParams` implementation, and `decodeURIComponent` is not defined");const s=new URLSearchParams;for(const e of a.split("&")){const[t,r]=e.split("=");t&&s.append(o(t),o(r||""))}return{url:n,searchParams:s}}(a.url);for(const[e,o]of Object.entries(a.query)){if(void 0!==o)if(Array.isArray(o))for(const t of o)r.append(e,t);else r.append(e,o);const n=r.toString();n&&(a.url=`${t}?${n}`)}}return a.method=a.body&&!a.method?"POST":(a.method||"GET").toUpperCase(),a};function o(e){return decodeURIComponent(e.replace(/\+/g," "))}function n(e){if(!1===e||0===e)return!1;if(e.connect||e.socket)return e;const r=Number(e);return isNaN(r)?n(t.timeout):{connect:r,socket:r}}const a=/^https?:\/\//i,s=function(e){if(!a.test(e.url))throw new Error(`"${e.url}" is not a valid URL`)};function c(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}export{c as g,r as p,s as v};//# sourceMappingURL=_commonjsHelpers.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
import{v as e,p as t}from"./defaultOptionsValidator.js";const r=["request","response","progress","error","abort"],o=["processOptions","validateOptions","interceptRequest","finalizeOptions","onRequest","onResponse","onError","onReturn","onHeaders"];function n(s,i){const u=[],a=o.reduce(((e,t)=>(e[t]=e[t]||[],e)),{processOptions:[t],validateOptions:[e]});function c(e){const t=r.reduce(((e,t)=>(e[t]=function(){const e=/* @__PURE__ */Object.create(null);let t=0;return{publish:function(t){for(const r in e)e[r](t)},subscribe:function(r){const o=t++;return e[o]=r,function(){delete e[o]}}}}(),e)),{}),o=(e=>function(t,r,...o){const n="onError"===t;let s=r;for(let r=0;r<e[t].length&&(s=(0,e[t][r])(s,...o),!n||s);r++);return s})(a),n=o("processOptions",e);o("validateOptions",n);const s={options:n,channels:t,applyMiddleware:o};let u;const c=t.request.subscribe((e=>{u=i(e,((r,n)=>((e,r,n)=>{let s=e,i=r;if(!s)try{i=o("onResponse",r,n)}catch(e){i=null,s=e}s=s&&o("onError",s,n),s?t.error.publish(s):i&&t.response.publish(i)})(r,n,e)))}));t.abort.subscribe((()=>{c(),u&&u.abort()}));const l=o("onReturn",t,s);return l===t&&t.request.publish(s),l}return c.use=function(e){if(!e)throw new Error("Tried to add middleware that resolved to falsey value");if("function"==typeof e)throw new Error("Tried to add middleware that was a function. It probably expects you to pass options to it.");if(e.onReturn&&a.onReturn.length>0)throw new Error("Tried to add new middleware with `onReturn` handler, but another handler has already been registered for this event");return o.forEach((t=>{e[t]&&a[t].push(e[t])})),u.push(e),c},c.clone=()=>n(u,i),s.forEach(c.use),c}export{n as c};//# sourceMappingURL=createRequester.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
const e=!(typeof navigator>"u")&&"ReactNative"===navigator.product,t={timeout:e?6e4:12e4},r=function(r){const a={...t,..."string"==typeof r?{url:r}:r};if(a.timeout=o(a.timeout),a.query){const{url:t,searchParams:r}=function(t){const r=t.indexOf("?");if(-1===r)return{url:t,searchParams:new URLSearchParams};const o=t.slice(0,r),a=t.slice(r+1);if(!e)return{url:o,searchParams:new URLSearchParams(a)};if("function"!=typeof decodeURIComponent)throw new Error("Broken `URLSearchParams` implementation, and `decodeURIComponent` is not defined");const s=new URLSearchParams;for(const e of a.split("&")){const[t,r]=e.split("=");t&&s.append(n(t),n(r||""))}return{url:o,searchParams:s}}(a.url);for(const[e,n]of Object.entries(a.query)){if(void 0!==n)if(Array.isArray(n))for(const t of n)r.append(e,t);else r.append(e,n);const o=r.toString();o&&(a.url=`${t}?${o}`)}}return a.method=a.body&&!a.method?"POST":(a.method||"GET").toUpperCase(),a};function n(e){return decodeURIComponent(e.replace(/\+/g," "))}function o(e){if(!1===e||0===e)return!1;if(e.connect||e.socket)return e;const r=Number(e);return isNaN(r)?o(t.timeout):{connect:r,socket:r}}const a=/^https?:\/\//i,s=function(e){if(!a.test(e.url))throw new Error(`"${e.url}" is not a valid URL`)};export{r as p,s as v};//# sourceMappingURL=defaultOptionsValidator.js.map

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

1
server/node_modules/get-it/dist/index.browser.cjs generated vendored Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

236
server/node_modules/get-it/dist/index.browser.d.cts generated vendored Normal file
View File

@@ -0,0 +1,236 @@
import type {IncomingHttpHeaders} from 'http'
import type {IncomingMessage} from 'http'
import type {Transform} from 'stream'
import type {UrlWithStringQuery} from 'url'
/**
* Use fetch if it's available, non-browser environments such as Deno, Edge Runtime and more provide fetch as a global but doesn't provide xhr
* @public
*/
export declare const adapter: 'xhr' | 'fetch'
/** @public */
export declare type ApplyMiddleware = <T extends keyof MiddlewareHooks>(
hook: T,
value: MiddlewareHooks[T] extends (defaultValue: infer V, ...rest: any[]) => any ? V : never,
...args: MiddlewareHooks[T] extends (defaultValue: any, ...rest: infer P) => any ? P : never
) => ReturnType<MiddlewareHooks[T]>
/** @public */
export declare type DefineApplyMiddleware = (middleware: MiddlewareReducer) => ApplyMiddleware
/** @public */
export declare const environment = 'browser'
/**
* Reports the environment as either "node" or "browser", depending on what entry point was used to aid bundler debugging.
* If 'browser' is used, then the globally available `fetch` class is used. While `node` will always use either `node:https` or `node:http` depending on the protocol.
* @public
*/
export declare type ExportEnv = 'node' | 'react-server' | 'browser'
/** @public */
export declare interface FinalizeNodeOptionsPayload extends UrlWithStringQuery {
method: RequestOptions['method']
headers: RequestOptions['headers']
maxRedirects: RequestOptions['maxRedirects']
agent?: any
cert?: any
key?: any
ca?: any
}
/** @public */
export declare const getIt: (initMiddleware?: Middlewares, httpRequest?: HttpRequest) => Requester
/** @public */
export declare type HookOnRequestEvent = HookOnRequestEventNode | HookOnRequestEventBrowser
/** @public */
export declare interface HookOnRequestEventBase {
options: RequestOptions
context: HttpContext
request: any
}
/** @public */
export declare interface HookOnRequestEventBrowser extends HookOnRequestEventBase {
adapter: Omit<RequestAdapter, 'node'>
progress?: undefined
}
/** @public */
export declare interface HookOnRequestEventNode extends HookOnRequestEventBase {
adapter: 'node'
progress: any
}
/** @public */
export declare interface HttpContext {
options: RequestOptions
channels: MiddlewareChannels
applyMiddleware: ApplyMiddleware
}
/**
* request-node in node, browser-request in browsers
* @public
*/
export declare type HttpRequest = (
context: HttpContext,
callback: (err: Error | null, response?: MiddlewareResponse) => void,
) => HttpRequestOngoing
/** @public */
export declare interface HttpRequestOngoing {
abort: () => void
}
/** @public */
export declare type Middleware = Partial<MiddlewareHooks>
/** @public */
export declare interface MiddlewareChannels {
request: PubSub<HttpContext>
response: PubSub<unknown>
progress: PubSub<unknown>
error: PubSub<unknown>
abort: PubSub<void>
}
/** @public */
export declare type MiddlewareHookName = keyof MiddlewareHooks
/** @public */
export declare interface MiddlewareHooks {
processOptions: (options: RequestOptions) => RequestOptions
validateOptions: (options: RequestOptions) => void | undefined
interceptRequest: (
prevValue: MiddlewareResponse | undefined,
event: {
adapter: RequestAdapter
context: HttpContext
},
) => MiddlewareResponse | undefined | void
finalizeOptions: (
options: FinalizeNodeOptionsPayload | RequestOptions,
) => FinalizeNodeOptionsPayload | RequestOptions
onRequest: (evt: HookOnRequestEvent) => void
onResponse: (response: MiddlewareResponse, context: HttpContext) => MiddlewareResponse
onError: (err: Error | null, context: HttpContext) => any
onReturn: (channels: MiddlewareChannels, context: HttpContext) => any
onHeaders: (
response: IncomingMessage,
evt: {
headers: IncomingHttpHeaders
adapter: RequestAdapter
context: HttpContext
},
) => ProgressStream
}
/** @public */
export declare type MiddlewareReducer = {
[T in keyof MiddlewareHooks]: ((
...args: Parameters<MiddlewareHooks[T]>
) => ReturnType<MiddlewareHooks[T]>)[]
}
/** @public */
export declare interface MiddlewareRequest {}
/** @public */
export declare interface MiddlewareResponse {
body: any
url: string
method: string
headers: any
statusCode: number
statusMessage: string
}
/** @public */
export declare type Middlewares = Middleware[]
declare interface Progress {
percentage: number
transferred: number
length: number
remaining: number
eta: number
runtime: number
delta: number
speed: number
}
declare interface ProgressStream extends Transform {
progress(): Progress
}
/** @public */
export declare interface PubSub<Message> {
publish: (message: Message) => void
subscribe: (subscriber: Subscriber<Message>) => () => void
}
/**
* Reports the request adapter in use. `node` is only available if `ExportEnv` is also `node`.
* When `ExportEnv` is `browser` then the adapter can be either `xhr` or `fetch`.
* In the future `fetch` will be available in `node` as well.
* @public
*/
export declare type RequestAdapter = 'node' | 'xhr' | 'fetch'
/** @public */
export declare type Requester = {
use: (middleware: Middleware) => Requester
clone: () => Requester
(options: RequestOptions | string): any
}
/** @public */
export declare interface RequestOptions {
url: string
body?: any
bodySize?: number
cancelToken?: any
compress?: boolean
headers?: any
maxRedirects?: number
maxRetries?: number
retryDelay?: (attemptNumber: number) => number
method?: string
proxy?: any
query?: any
rawBody?: boolean
shouldRetry?: any
stream?: boolean
timeout?: any
tunnel?: boolean
debug?: any
requestId?: number
attemptNumber?: number
withCredentials?: boolean
/**
* Enables using the native `fetch` API instead of the default `http` module, and allows setting its options like `cache`
*/
fetch?: boolean | Omit<RequestInit, 'method'>
/**
* Some frameworks have special behavior for `fetch` when an `AbortSignal` is used, and may want to disable it unless userland specifically opts-in.
*/
useAbortSignal?: boolean
}
/** @public */
export declare interface RetryOptions {
shouldRetry: (err: any, num: number, options: any) => boolean
maxRetries?: number
retryDelay?: (attemptNumber: number) => number
}
/** @public */
export declare interface Subscriber<Event> {
(event: Event): void
}
export {}

236
server/node_modules/get-it/dist/index.browser.d.ts generated vendored Normal file
View File

@@ -0,0 +1,236 @@
import type {IncomingHttpHeaders} from 'http'
import type {IncomingMessage} from 'http'
import type {Transform} from 'stream'
import type {UrlWithStringQuery} from 'url'
/**
* Use fetch if it's available, non-browser environments such as Deno, Edge Runtime and more provide fetch as a global but doesn't provide xhr
* @public
*/
export declare const adapter: 'xhr' | 'fetch'
/** @public */
export declare type ApplyMiddleware = <T extends keyof MiddlewareHooks>(
hook: T,
value: MiddlewareHooks[T] extends (defaultValue: infer V, ...rest: any[]) => any ? V : never,
...args: MiddlewareHooks[T] extends (defaultValue: any, ...rest: infer P) => any ? P : never
) => ReturnType<MiddlewareHooks[T]>
/** @public */
export declare type DefineApplyMiddleware = (middleware: MiddlewareReducer) => ApplyMiddleware
/** @public */
export declare const environment = 'browser'
/**
* Reports the environment as either "node" or "browser", depending on what entry point was used to aid bundler debugging.
* If 'browser' is used, then the globally available `fetch` class is used. While `node` will always use either `node:https` or `node:http` depending on the protocol.
* @public
*/
export declare type ExportEnv = 'node' | 'react-server' | 'browser'
/** @public */
export declare interface FinalizeNodeOptionsPayload extends UrlWithStringQuery {
method: RequestOptions['method']
headers: RequestOptions['headers']
maxRedirects: RequestOptions['maxRedirects']
agent?: any
cert?: any
key?: any
ca?: any
}
/** @public */
export declare const getIt: (initMiddleware?: Middlewares, httpRequest?: HttpRequest) => Requester
/** @public */
export declare type HookOnRequestEvent = HookOnRequestEventNode | HookOnRequestEventBrowser
/** @public */
export declare interface HookOnRequestEventBase {
options: RequestOptions
context: HttpContext
request: any
}
/** @public */
export declare interface HookOnRequestEventBrowser extends HookOnRequestEventBase {
adapter: Omit<RequestAdapter, 'node'>
progress?: undefined
}
/** @public */
export declare interface HookOnRequestEventNode extends HookOnRequestEventBase {
adapter: 'node'
progress: any
}
/** @public */
export declare interface HttpContext {
options: RequestOptions
channels: MiddlewareChannels
applyMiddleware: ApplyMiddleware
}
/**
* request-node in node, browser-request in browsers
* @public
*/
export declare type HttpRequest = (
context: HttpContext,
callback: (err: Error | null, response?: MiddlewareResponse) => void,
) => HttpRequestOngoing
/** @public */
export declare interface HttpRequestOngoing {
abort: () => void
}
/** @public */
export declare type Middleware = Partial<MiddlewareHooks>
/** @public */
export declare interface MiddlewareChannels {
request: PubSub<HttpContext>
response: PubSub<unknown>
progress: PubSub<unknown>
error: PubSub<unknown>
abort: PubSub<void>
}
/** @public */
export declare type MiddlewareHookName = keyof MiddlewareHooks
/** @public */
export declare interface MiddlewareHooks {
processOptions: (options: RequestOptions) => RequestOptions
validateOptions: (options: RequestOptions) => void | undefined
interceptRequest: (
prevValue: MiddlewareResponse | undefined,
event: {
adapter: RequestAdapter
context: HttpContext
},
) => MiddlewareResponse | undefined | void
finalizeOptions: (
options: FinalizeNodeOptionsPayload | RequestOptions,
) => FinalizeNodeOptionsPayload | RequestOptions
onRequest: (evt: HookOnRequestEvent) => void
onResponse: (response: MiddlewareResponse, context: HttpContext) => MiddlewareResponse
onError: (err: Error | null, context: HttpContext) => any
onReturn: (channels: MiddlewareChannels, context: HttpContext) => any
onHeaders: (
response: IncomingMessage,
evt: {
headers: IncomingHttpHeaders
adapter: RequestAdapter
context: HttpContext
},
) => ProgressStream
}
/** @public */
export declare type MiddlewareReducer = {
[T in keyof MiddlewareHooks]: ((
...args: Parameters<MiddlewareHooks[T]>
) => ReturnType<MiddlewareHooks[T]>)[]
}
/** @public */
export declare interface MiddlewareRequest {}
/** @public */
export declare interface MiddlewareResponse {
body: any
url: string
method: string
headers: any
statusCode: number
statusMessage: string
}
/** @public */
export declare type Middlewares = Middleware[]
declare interface Progress {
percentage: number
transferred: number
length: number
remaining: number
eta: number
runtime: number
delta: number
speed: number
}
declare interface ProgressStream extends Transform {
progress(): Progress
}
/** @public */
export declare interface PubSub<Message> {
publish: (message: Message) => void
subscribe: (subscriber: Subscriber<Message>) => () => void
}
/**
* Reports the request adapter in use. `node` is only available if `ExportEnv` is also `node`.
* When `ExportEnv` is `browser` then the adapter can be either `xhr` or `fetch`.
* In the future `fetch` will be available in `node` as well.
* @public
*/
export declare type RequestAdapter = 'node' | 'xhr' | 'fetch'
/** @public */
export declare type Requester = {
use: (middleware: Middleware) => Requester
clone: () => Requester
(options: RequestOptions | string): any
}
/** @public */
export declare interface RequestOptions {
url: string
body?: any
bodySize?: number
cancelToken?: any
compress?: boolean
headers?: any
maxRedirects?: number
maxRetries?: number
retryDelay?: (attemptNumber: number) => number
method?: string
proxy?: any
query?: any
rawBody?: boolean
shouldRetry?: any
stream?: boolean
timeout?: any
tunnel?: boolean
debug?: any
requestId?: number
attemptNumber?: number
withCredentials?: boolean
/**
* Enables using the native `fetch` API instead of the default `http` module, and allows setting its options like `cache`
*/
fetch?: boolean | Omit<RequestInit, 'method'>
/**
* Some frameworks have special behavior for `fetch` when an `AbortSignal` is used, and may want to disable it unless userland specifically opts-in.
*/
useAbortSignal?: boolean
}
/** @public */
export declare interface RetryOptions {
shouldRetry: (err: any, num: number, options: any) => boolean
maxRetries?: number
retryDelay?: (attemptNumber: number) => number
}
/** @public */
export declare interface Subscriber<Event> {
(event: Event): void
}
export {}

1
server/node_modules/get-it/dist/index.browser.js generated vendored Normal file

File diff suppressed because one or more lines are too long

1
server/node_modules/get-it/dist/index.browser.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

1
server/node_modules/get-it/dist/index.cjs generated vendored Normal file
View File

@@ -0,0 +1 @@
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("./_chunks-cjs/node-request.cjs");const t=["request","response","progress","error","abort"],r=["processOptions","validateOptions","interceptRequest","finalizeOptions","onRequest","onResponse","onError","onReturn","onHeaders"];function n(o,s){const i=[],u=r.reduce(((e,t)=>(e[t]=e[t]||[],e)),{processOptions:[e.p],validateOptions:[e.v]});function a(e){const r=t.reduce(((e,t)=>(e[t]=function(){const e=/* @__PURE__ */Object.create(null);let t=0;return{publish:function(t){for(const r in e)e[r](t)},subscribe:function(r){const n=t++;return e[n]=r,function(){delete e[n]}}}}(),e)),{}),n=(e=>function(t,r,...n){const o="onError"===t;let s=r;for(let r=0;r<e[t].length&&(s=(0,e[t][r])(s,...n),!o||s);r++);return s})(u),o=n("processOptions",e);n("validateOptions",o);const i={options:o,channels:r,applyMiddleware:n};let a;const c=r.request.subscribe((e=>{a=s(e,((t,o)=>((e,t,o)=>{let s=e,i=t;if(!s)try{i=n("onResponse",t,o)}catch(e){i=null,s=e}s=s&&n("onError",s,o),s?r.error.publish(s):i&&r.response.publish(i)})(t,o,e)))}));r.abort.subscribe((()=>{c(),a&&a.abort()}));const p=n("onReturn",r,i);return p===r&&r.request.publish(i),p}return a.use=function(e){if(!e)throw new Error("Tried to add middleware that resolved to falsey value");if("function"==typeof e)throw new Error("Tried to add middleware that was a function. It probably expects you to pass options to it.");if(e.onReturn&&u.onReturn.length>0)throw new Error("Tried to add new middleware with `onReturn` handler, but another handler has already been registered for this event");return r.forEach((t=>{e[t]&&u[t].push(e[t])})),i.push(e),a},a.clone=()=>n(i,s),o.forEach(a.use),a}exports.adapter=e.a,exports.environment="node",exports.getIt=(t=[],r=e.h)=>n(t,r);//# sourceMappingURL=index.cjs.map

1
server/node_modules/get-it/dist/index.cjs.map generated vendored Normal file

File diff suppressed because one or more lines are too long

234
server/node_modules/get-it/dist/index.d.cts generated vendored Normal file
View File

@@ -0,0 +1,234 @@
import type {IncomingHttpHeaders} from 'http'
import type {IncomingMessage} from 'http'
import {RequestAdapter as RequestAdapter_2} from '../types'
import type {Transform} from 'stream'
import type {UrlWithStringQuery} from 'url'
/** @public */
export declare const adapter: RequestAdapter_2
/** @public */
export declare type ApplyMiddleware = <T extends keyof MiddlewareHooks>(
hook: T,
value: MiddlewareHooks[T] extends (defaultValue: infer V, ...rest: any[]) => any ? V : never,
...args: MiddlewareHooks[T] extends (defaultValue: any, ...rest: infer P) => any ? P : never
) => ReturnType<MiddlewareHooks[T]>
/** @public */
export declare type DefineApplyMiddleware = (middleware: MiddlewareReducer) => ApplyMiddleware
/** @public */
export declare const environment: ExportEnv
/**
* Reports the environment as either "node" or "browser", depending on what entry point was used to aid bundler debugging.
* If 'browser' is used, then the globally available `fetch` class is used. While `node` will always use either `node:https` or `node:http` depending on the protocol.
* @public
*/
export declare type ExportEnv = 'node' | 'react-server' | 'browser'
/** @public */
export declare interface FinalizeNodeOptionsPayload extends UrlWithStringQuery {
method: RequestOptions['method']
headers: RequestOptions['headers']
maxRedirects: RequestOptions['maxRedirects']
agent?: any
cert?: any
key?: any
ca?: any
}
/** @public */
export declare const getIt: (initMiddleware?: Middlewares, httpRequest?: HttpRequest) => Requester
/** @public */
export declare type HookOnRequestEvent = HookOnRequestEventNode | HookOnRequestEventBrowser
/** @public */
export declare interface HookOnRequestEventBase {
options: RequestOptions
context: HttpContext
request: any
}
/** @public */
export declare interface HookOnRequestEventBrowser extends HookOnRequestEventBase {
adapter: Omit<RequestAdapter, 'node'>
progress?: undefined
}
/** @public */
export declare interface HookOnRequestEventNode extends HookOnRequestEventBase {
adapter: 'node'
progress: any
}
/** @public */
export declare interface HttpContext {
options: RequestOptions
channels: MiddlewareChannels
applyMiddleware: ApplyMiddleware
}
/**
* request-node in node, browser-request in browsers
* @public
*/
export declare type HttpRequest = (
context: HttpContext,
callback: (err: Error | null, response?: MiddlewareResponse) => void,
) => HttpRequestOngoing
/** @public */
export declare interface HttpRequestOngoing {
abort: () => void
}
/** @public */
export declare type Middleware = Partial<MiddlewareHooks>
/** @public */
export declare interface MiddlewareChannels {
request: PubSub<HttpContext>
response: PubSub<unknown>
progress: PubSub<unknown>
error: PubSub<unknown>
abort: PubSub<void>
}
/** @public */
export declare type MiddlewareHookName = keyof MiddlewareHooks
/** @public */
export declare interface MiddlewareHooks {
processOptions: (options: RequestOptions) => RequestOptions
validateOptions: (options: RequestOptions) => void | undefined
interceptRequest: (
prevValue: MiddlewareResponse | undefined,
event: {
adapter: RequestAdapter
context: HttpContext
},
) => MiddlewareResponse | undefined | void
finalizeOptions: (
options: FinalizeNodeOptionsPayload | RequestOptions,
) => FinalizeNodeOptionsPayload | RequestOptions
onRequest: (evt: HookOnRequestEvent) => void
onResponse: (response: MiddlewareResponse, context: HttpContext) => MiddlewareResponse
onError: (err: Error | null, context: HttpContext) => any
onReturn: (channels: MiddlewareChannels, context: HttpContext) => any
onHeaders: (
response: IncomingMessage,
evt: {
headers: IncomingHttpHeaders
adapter: RequestAdapter
context: HttpContext
},
) => ProgressStream
}
/** @public */
export declare type MiddlewareReducer = {
[T in keyof MiddlewareHooks]: ((
...args: Parameters<MiddlewareHooks[T]>
) => ReturnType<MiddlewareHooks[T]>)[]
}
/** @public */
export declare interface MiddlewareRequest {}
/** @public */
export declare interface MiddlewareResponse {
body: any
url: string
method: string
headers: any
statusCode: number
statusMessage: string
}
/** @public */
export declare type Middlewares = Middleware[]
declare interface Progress {
percentage: number
transferred: number
length: number
remaining: number
eta: number
runtime: number
delta: number
speed: number
}
declare interface ProgressStream extends Transform {
progress(): Progress
}
/** @public */
export declare interface PubSub<Message> {
publish: (message: Message) => void
subscribe: (subscriber: Subscriber<Message>) => () => void
}
/**
* Reports the request adapter in use. `node` is only available if `ExportEnv` is also `node`.
* When `ExportEnv` is `browser` then the adapter can be either `xhr` or `fetch`.
* In the future `fetch` will be available in `node` as well.
* @public
*/
export declare type RequestAdapter = 'node' | 'xhr' | 'fetch'
/** @public */
export declare type Requester = {
use: (middleware: Middleware) => Requester
clone: () => Requester
(options: RequestOptions | string): any
}
/** @public */
export declare interface RequestOptions {
url: string
body?: any
bodySize?: number
cancelToken?: any
compress?: boolean
headers?: any
maxRedirects?: number
maxRetries?: number
retryDelay?: (attemptNumber: number) => number
method?: string
proxy?: any
query?: any
rawBody?: boolean
shouldRetry?: any
stream?: boolean
timeout?: any
tunnel?: boolean
debug?: any
requestId?: number
attemptNumber?: number
withCredentials?: boolean
/**
* Enables using the native `fetch` API instead of the default `http` module, and allows setting its options like `cache`
*/
fetch?: boolean | Omit<RequestInit, 'method'>
/**
* Some frameworks have special behavior for `fetch` when an `AbortSignal` is used, and may want to disable it unless userland specifically opts-in.
*/
useAbortSignal?: boolean
}
/** @public */
export declare interface RetryOptions {
shouldRetry: (err: any, num: number, options: any) => boolean
maxRetries?: number
retryDelay?: (attemptNumber: number) => number
}
/** @public */
export declare interface Subscriber<Event> {
(event: Event): void
}
export {}

234
server/node_modules/get-it/dist/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,234 @@
import type {IncomingHttpHeaders} from 'http'
import type {IncomingMessage} from 'http'
import {RequestAdapter as RequestAdapter_2} from '../types'
import type {Transform} from 'stream'
import type {UrlWithStringQuery} from 'url'
/** @public */
export declare const adapter: RequestAdapter_2
/** @public */
export declare type ApplyMiddleware = <T extends keyof MiddlewareHooks>(
hook: T,
value: MiddlewareHooks[T] extends (defaultValue: infer V, ...rest: any[]) => any ? V : never,
...args: MiddlewareHooks[T] extends (defaultValue: any, ...rest: infer P) => any ? P : never
) => ReturnType<MiddlewareHooks[T]>
/** @public */
export declare type DefineApplyMiddleware = (middleware: MiddlewareReducer) => ApplyMiddleware
/** @public */
export declare const environment: ExportEnv
/**
* Reports the environment as either "node" or "browser", depending on what entry point was used to aid bundler debugging.
* If 'browser' is used, then the globally available `fetch` class is used. While `node` will always use either `node:https` or `node:http` depending on the protocol.
* @public
*/
export declare type ExportEnv = 'node' | 'react-server' | 'browser'
/** @public */
export declare interface FinalizeNodeOptionsPayload extends UrlWithStringQuery {
method: RequestOptions['method']
headers: RequestOptions['headers']
maxRedirects: RequestOptions['maxRedirects']
agent?: any
cert?: any
key?: any
ca?: any
}
/** @public */
export declare const getIt: (initMiddleware?: Middlewares, httpRequest?: HttpRequest) => Requester
/** @public */
export declare type HookOnRequestEvent = HookOnRequestEventNode | HookOnRequestEventBrowser
/** @public */
export declare interface HookOnRequestEventBase {
options: RequestOptions
context: HttpContext
request: any
}
/** @public */
export declare interface HookOnRequestEventBrowser extends HookOnRequestEventBase {
adapter: Omit<RequestAdapter, 'node'>
progress?: undefined
}
/** @public */
export declare interface HookOnRequestEventNode extends HookOnRequestEventBase {
adapter: 'node'
progress: any
}
/** @public */
export declare interface HttpContext {
options: RequestOptions
channels: MiddlewareChannels
applyMiddleware: ApplyMiddleware
}
/**
* request-node in node, browser-request in browsers
* @public
*/
export declare type HttpRequest = (
context: HttpContext,
callback: (err: Error | null, response?: MiddlewareResponse) => void,
) => HttpRequestOngoing
/** @public */
export declare interface HttpRequestOngoing {
abort: () => void
}
/** @public */
export declare type Middleware = Partial<MiddlewareHooks>
/** @public */
export declare interface MiddlewareChannels {
request: PubSub<HttpContext>
response: PubSub<unknown>
progress: PubSub<unknown>
error: PubSub<unknown>
abort: PubSub<void>
}
/** @public */
export declare type MiddlewareHookName = keyof MiddlewareHooks
/** @public */
export declare interface MiddlewareHooks {
processOptions: (options: RequestOptions) => RequestOptions
validateOptions: (options: RequestOptions) => void | undefined
interceptRequest: (
prevValue: MiddlewareResponse | undefined,
event: {
adapter: RequestAdapter
context: HttpContext
},
) => MiddlewareResponse | undefined | void
finalizeOptions: (
options: FinalizeNodeOptionsPayload | RequestOptions,
) => FinalizeNodeOptionsPayload | RequestOptions
onRequest: (evt: HookOnRequestEvent) => void
onResponse: (response: MiddlewareResponse, context: HttpContext) => MiddlewareResponse
onError: (err: Error | null, context: HttpContext) => any
onReturn: (channels: MiddlewareChannels, context: HttpContext) => any
onHeaders: (
response: IncomingMessage,
evt: {
headers: IncomingHttpHeaders
adapter: RequestAdapter
context: HttpContext
},
) => ProgressStream
}
/** @public */
export declare type MiddlewareReducer = {
[T in keyof MiddlewareHooks]: ((
...args: Parameters<MiddlewareHooks[T]>
) => ReturnType<MiddlewareHooks[T]>)[]
}
/** @public */
export declare interface MiddlewareRequest {}
/** @public */
export declare interface MiddlewareResponse {
body: any
url: string
method: string
headers: any
statusCode: number
statusMessage: string
}
/** @public */
export declare type Middlewares = Middleware[]
declare interface Progress {
percentage: number
transferred: number
length: number
remaining: number
eta: number
runtime: number
delta: number
speed: number
}
declare interface ProgressStream extends Transform {
progress(): Progress
}
/** @public */
export declare interface PubSub<Message> {
publish: (message: Message) => void
subscribe: (subscriber: Subscriber<Message>) => () => void
}
/**
* Reports the request adapter in use. `node` is only available if `ExportEnv` is also `node`.
* When `ExportEnv` is `browser` then the adapter can be either `xhr` or `fetch`.
* In the future `fetch` will be available in `node` as well.
* @public
*/
export declare type RequestAdapter = 'node' | 'xhr' | 'fetch'
/** @public */
export declare type Requester = {
use: (middleware: Middleware) => Requester
clone: () => Requester
(options: RequestOptions | string): any
}
/** @public */
export declare interface RequestOptions {
url: string
body?: any
bodySize?: number
cancelToken?: any
compress?: boolean
headers?: any
maxRedirects?: number
maxRetries?: number
retryDelay?: (attemptNumber: number) => number
method?: string
proxy?: any
query?: any
rawBody?: boolean
shouldRetry?: any
stream?: boolean
timeout?: any
tunnel?: boolean
debug?: any
requestId?: number
attemptNumber?: number
withCredentials?: boolean
/**
* Enables using the native `fetch` API instead of the default `http` module, and allows setting its options like `cache`
*/
fetch?: boolean | Omit<RequestInit, 'method'>
/**
* Some frameworks have special behavior for `fetch` when an `AbortSignal` is used, and may want to disable it unless userland specifically opts-in.
*/
useAbortSignal?: boolean
}
/** @public */
export declare interface RetryOptions {
shouldRetry: (err: any, num: number, options: any) => boolean
maxRetries?: number
retryDelay?: (attemptNumber: number) => number
}
/** @public */
export declare interface Subscriber<Event> {
(event: Event): void
}
export {}

1
server/node_modules/get-it/dist/index.js generated vendored Normal file
View File

@@ -0,0 +1 @@
import{c as e}from"./_chunks-es/createRequester.js";import{h as s}from"./_chunks-es/node-request.js";import{a as r}from"./_chunks-es/node-request.js";const o=(r=[],o=s)=>e(r,o),t="node";export{r as adapter,t as environment,o as getIt};//# sourceMappingURL=index.js.map

1
server/node_modules/get-it/dist/index.js.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sources":["../src/index.ts"],"sourcesContent":["import {createRequester} from './createRequester'\nimport {httpRequester} from './request/node-request'\nimport type {ExportEnv, HttpRequest, Middlewares, Requester} from './types'\n\nexport type * from './types'\n\n/** @public */\nexport const getIt = (\n initMiddleware: Middlewares = [],\n httpRequest: HttpRequest = httpRequester,\n): Requester => createRequester(initMiddleware, httpRequest)\n\n/** @public */\nexport const environment: ExportEnv = 'node'\n\n/** @public */\nexport {adapter} from './request/node-request'\n"],"names":["getIt","initMiddleware","httpRequest","httpRequester","createRequester","environment"],"mappings":"sJAOa,MAAAA,EAAQ,CACnBC,EAA8B,GAC9BC,EAA2BC,IACbC,EAAgBH,EAAgBC,GAGnCG,EAAyB"}

236
server/node_modules/get-it/dist/index.react-server.d.ts generated vendored Normal file
View File

@@ -0,0 +1,236 @@
import type {IncomingHttpHeaders} from 'http'
import type {IncomingMessage} from 'http'
import type {Transform} from 'stream'
import type {UrlWithStringQuery} from 'url'
/**
* Use fetch if it's available, non-browser environments such as Deno, Edge Runtime and more provide fetch as a global but doesn't provide xhr
* @public
*/
export declare const adapter: 'xhr' | 'fetch'
/** @public */
export declare type ApplyMiddleware = <T extends keyof MiddlewareHooks>(
hook: T,
value: MiddlewareHooks[T] extends (defaultValue: infer V, ...rest: any[]) => any ? V : never,
...args: MiddlewareHooks[T] extends (defaultValue: any, ...rest: infer P) => any ? P : never
) => ReturnType<MiddlewareHooks[T]>
/** @public */
export declare type DefineApplyMiddleware = (middleware: MiddlewareReducer) => ApplyMiddleware
/** @public */
export declare const environment = 'react-server'
/**
* Reports the environment as either "node" or "browser", depending on what entry point was used to aid bundler debugging.
* If 'browser' is used, then the globally available `fetch` class is used. While `node` will always use either `node:https` or `node:http` depending on the protocol.
* @public
*/
export declare type ExportEnv = 'node' | 'react-server' | 'browser'
/** @public */
export declare interface FinalizeNodeOptionsPayload extends UrlWithStringQuery {
method: RequestOptions['method']
headers: RequestOptions['headers']
maxRedirects: RequestOptions['maxRedirects']
agent?: any
cert?: any
key?: any
ca?: any
}
/** @public */
export declare const getIt: (initMiddleware?: Middlewares, httpRequest?: HttpRequest) => Requester
/** @public */
export declare type HookOnRequestEvent = HookOnRequestEventNode | HookOnRequestEventBrowser
/** @public */
export declare interface HookOnRequestEventBase {
options: RequestOptions
context: HttpContext
request: any
}
/** @public */
export declare interface HookOnRequestEventBrowser extends HookOnRequestEventBase {
adapter: Omit<RequestAdapter, 'node'>
progress?: undefined
}
/** @public */
export declare interface HookOnRequestEventNode extends HookOnRequestEventBase {
adapter: 'node'
progress: any
}
/** @public */
export declare interface HttpContext {
options: RequestOptions
channels: MiddlewareChannels
applyMiddleware: ApplyMiddleware
}
/**
* request-node in node, browser-request in browsers
* @public
*/
export declare type HttpRequest = (
context: HttpContext,
callback: (err: Error | null, response?: MiddlewareResponse) => void,
) => HttpRequestOngoing
/** @public */
export declare interface HttpRequestOngoing {
abort: () => void
}
/** @public */
export declare type Middleware = Partial<MiddlewareHooks>
/** @public */
export declare interface MiddlewareChannels {
request: PubSub<HttpContext>
response: PubSub<unknown>
progress: PubSub<unknown>
error: PubSub<unknown>
abort: PubSub<void>
}
/** @public */
export declare type MiddlewareHookName = keyof MiddlewareHooks
/** @public */
export declare interface MiddlewareHooks {
processOptions: (options: RequestOptions) => RequestOptions
validateOptions: (options: RequestOptions) => void | undefined
interceptRequest: (
prevValue: MiddlewareResponse | undefined,
event: {
adapter: RequestAdapter
context: HttpContext
},
) => MiddlewareResponse | undefined | void
finalizeOptions: (
options: FinalizeNodeOptionsPayload | RequestOptions,
) => FinalizeNodeOptionsPayload | RequestOptions
onRequest: (evt: HookOnRequestEvent) => void
onResponse: (response: MiddlewareResponse, context: HttpContext) => MiddlewareResponse
onError: (err: Error | null, context: HttpContext) => any
onReturn: (channels: MiddlewareChannels, context: HttpContext) => any
onHeaders: (
response: IncomingMessage,
evt: {
headers: IncomingHttpHeaders
adapter: RequestAdapter
context: HttpContext
},
) => ProgressStream
}
/** @public */
export declare type MiddlewareReducer = {
[T in keyof MiddlewareHooks]: ((
...args: Parameters<MiddlewareHooks[T]>
) => ReturnType<MiddlewareHooks[T]>)[]
}
/** @public */
export declare interface MiddlewareRequest {}
/** @public */
export declare interface MiddlewareResponse {
body: any
url: string
method: string
headers: any
statusCode: number
statusMessage: string
}
/** @public */
export declare type Middlewares = Middleware[]
declare interface Progress {
percentage: number
transferred: number
length: number
remaining: number
eta: number
runtime: number
delta: number
speed: number
}
declare interface ProgressStream extends Transform {
progress(): Progress
}
/** @public */
export declare interface PubSub<Message> {
publish: (message: Message) => void
subscribe: (subscriber: Subscriber<Message>) => () => void
}
/**
* Reports the request adapter in use. `node` is only available if `ExportEnv` is also `node`.
* When `ExportEnv` is `browser` then the adapter can be either `xhr` or `fetch`.
* In the future `fetch` will be available in `node` as well.
* @public
*/
export declare type RequestAdapter = 'node' | 'xhr' | 'fetch'
/** @public */
export declare type Requester = {
use: (middleware: Middleware) => Requester
clone: () => Requester
(options: RequestOptions | string): any
}
/** @public */
export declare interface RequestOptions {
url: string
body?: any
bodySize?: number
cancelToken?: any
compress?: boolean
headers?: any
maxRedirects?: number
maxRetries?: number
retryDelay?: (attemptNumber: number) => number
method?: string
proxy?: any
query?: any
rawBody?: boolean
shouldRetry?: any
stream?: boolean
timeout?: any
tunnel?: boolean
debug?: any
requestId?: number
attemptNumber?: number
withCredentials?: boolean
/**
* Enables using the native `fetch` API instead of the default `http` module, and allows setting its options like `cache`
*/
fetch?: boolean | Omit<RequestInit, 'method'>
/**
* Some frameworks have special behavior for `fetch` when an `AbortSignal` is used, and may want to disable it unless userland specifically opts-in.
*/
useAbortSignal?: boolean
}
/** @public */
export declare interface RetryOptions {
shouldRetry: (err: any, num: number, options: any) => boolean
maxRetries?: number
retryDelay?: (attemptNumber: number) => number
}
/** @public */
export declare interface Subscriber<Event> {
(event: Event): void
}
export {}

View File

@@ -0,0 +1 @@
import{c as e}from"./_chunks-es/createRequester.js";import{g as t}from"./_chunks-es/_commonjsHelpers.js";var r,o,s=/* @__PURE__ */t(function(){if(o)return r;o=1;var e=function(e){return e.replace(/^\s+|\s+$/g,"")};return r=function(t){if(!t)return{};for(var r={},o=e(t).split("\n"),s=0;s<o.length;s++){var n=o[s],a=n.indexOf(":"),i=e(n.slice(0,a)).toLowerCase(),u=e(n.slice(a+1));typeof r[i]>"u"?r[i]=u:(l=r[i],"[object Array]"===Object.prototype.toString.call(l)?r[i].push(u):r[i]=[r[i],u])}var l;return r}}());class n{onabort;onerror;onreadystatechange;ontimeout;readyState=0;response;responseText="";responseType="";status;statusText;withCredentials;#e;#t;#r;#o={};#s;#n={};#a;open(e,t,r){this.#e=e,this.#t=t,this.#r="",this.readyState=1,this.onreadystatechange?.(),this.#s=void 0}abort(){this.#s&&this.#s.abort()}getAllResponseHeaders(){return this.#r}setRequestHeader(e,t){this.#o[e]=t}setInit(e,t=!0){this.#n=e,this.#a=t}send(e){const t="arraybuffer"!==this.responseType,r={...this.#n,method:this.#e,headers:this.#o,body:e};"function"==typeof AbortController&&this.#a&&(this.#s=new AbortController,typeof EventTarget<"u"&&this.#s.signal instanceof EventTarget&&(r.signal=this.#s.signal)),typeof document<"u"&&(r.credentials=this.withCredentials?"include":"omit"),fetch(this.#t,r).then((e=>(e.headers.forEach(((e,t)=>{this.#r+=`${t}: ${e}\r\n`})),this.status=e.status,this.statusText=e.statusText,this.readyState=3,this.onreadystatechange?.(),t?e.text():e.arrayBuffer()))).then((e=>{"string"==typeof e?this.responseText=e:this.response=e,this.readyState=4,this.onreadystatechange?.()})).catch((e=>{"AbortError"!==e.name?this.onerror?.(e):this.onabort?.()}))}}const a="function"==typeof XMLHttpRequest?"xhr":"fetch",i="xhr"===a?XMLHttpRequest:n,u=(e,t)=>{const r=e.options,o=e.applyMiddleware("finalizeOptions",r),u={},l=e.applyMiddleware("interceptRequest",void 0,{adapter:a,context:e});if(l){const e=setTimeout(t,0,null,l);return{abort:()=>clearTimeout(e)}}let c=new i;c instanceof n&&"object"==typeof o.fetch&&c.setInit(o.fetch,o.useAbortSignal??!0);const h=o.headers,d=o.timeout;let p=!1,f=!1,y=!1;if(c.onerror=e=>{g(c instanceof n?e instanceof Error?e:new Error(`Request error while attempting to reach is ${o.url}`,{cause:e}):new Error(`Request error while attempting to reach is ${o.url}${e.lengthComputable?`(${e.loaded} of ${e.total} bytes transferred)`:""}`))},c.ontimeout=e=>{g(new Error(`Request timeout while attempting to reach ${o.url}${e.lengthComputable?`(${e.loaded} of ${e.total} bytes transferred)`:""}`))},c.onabort=()=>{b(!0),p=!0},c.onreadystatechange=function(){d&&(b(),u.socket=setTimeout((()=>m("ESOCKETTIMEDOUT")),d.socket)),!p&&c&&4===c.readyState&&0!==c.status&&function(){if(!(p||f||y)){if(0===c.status)return void g(new Error("Unknown XHR error"));b(),f=!0,t(null,{body:c.response||(""===c.responseType||"text"===c.responseType?c.responseText:""),url:o.url,method:o.method,headers:s(c.getAllResponseHeaders()),statusCode:c.status,statusMessage:c.statusText})}}()},c.open(o.method,o.url,!0),c.withCredentials=!!o.withCredentials,h&&c.setRequestHeader)for(const e in h)h.hasOwnProperty(e)&&c.setRequestHeader(e,h[e]);return o.rawBody&&(c.responseType="arraybuffer"),e.applyMiddleware("onRequest",{options:o,adapter:a,request:c,context:e}),c.send(o.body||null),d&&(u.connect=setTimeout((()=>m("ETIMEDOUT")),d.connect)),{abort:function(){p=!0,c&&c.abort()}};function m(t){y=!0,c.abort();const r=new Error("ESOCKETTIMEDOUT"===t?`Socket timed out on request to ${o.url}`:`Connection timed out on request to ${o.url}`);r.code=t,e.channels.error.publish(r)}function b(e){(e||p||c&&c.readyState>=2&&u.connect)&&clearTimeout(u.connect),u.socket&&clearTimeout(u.socket)}function g(e){if(f)return;b(!0),f=!0,c=null;const r=e||new Error(`Network error while attempting to reach ${o.url}`);r.isNetworkError=!0,r.request=o,t(r)}},l=(t=[],r=u)=>e(t,r),c="react-server";export{a as adapter,c as environment,l as getIt};//# sourceMappingURL=index.react-server.js.map

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,355 @@
import {FinalizeNodeOptionsPayload as FinalizeNodeOptionsPayload_2} from 'get-it'
import {HookOnRequestEvent} from 'get-it'
import {HttpContext} from 'get-it'
import type {IncomingHttpHeaders} from 'http'
import type {IncomingMessage} from 'http'
import {MiddlewareChannels as MiddlewareChannels_2} from 'get-it'
import {MiddlewareResponse} from 'get-it'
import {RequestAdapter as RequestAdapter_2} from 'get-it'
import {RequestOptions} from 'get-it'
import type {Transform} from 'stream'
import type {UrlWithStringQuery} from 'url'
/**
* This middleware only has an effect in Node.js.
* @public
*/
export declare function agent(_opts?: any): any
/** @public */
declare type ApplyMiddleware = <T extends keyof MiddlewareHooks>(
hook: T,
value: MiddlewareHooks[T] extends (defaultValue: infer V, ...rest: any[]) => any ? V : never,
...args: MiddlewareHooks[T] extends (defaultValue: any, ...rest: infer P) => any ? P : never
) => ReturnType<MiddlewareHooks[T]>
/** @public */
export declare function base(baseUrl: string): {
processOptions: (options: RequestOptions) => RequestOptions
}
/**
* The cancel token API is based on the [cancelable promises proposal](https://github.com/tc39/proposal-cancelable-promises), which is currently at Stage 1.
*
* Code shamelessly stolen/borrowed from MIT-licensed [axios](https://github.com/mzabriskie/axios). Thanks to [Nick Uraltsev](https://github.com/nickuraltsev), [Matt Zabriskie](https://github.com/mzabriskie) and the other contributors of that project!
*/
/** @public */
export declare class Cancel {
__CANCEL__: boolean
message: string | undefined
constructor(message: string | undefined)
toString(): string
}
/** @public */
export declare class CancelToken {
promise: Promise<any>
reason?: Cancel
constructor(executor: (cb: (message?: string) => void) => void)
static source: () => {
token: CancelToken
cancel: (message?: string) => void
}
}
/** @public */
declare function debug_2(opts?: any): {
processOptions: (options: RequestOptions) => RequestOptions
onRequest: (event: HookOnRequestEvent) => HookOnRequestEvent
onResponse: (res: MiddlewareResponse, context: HttpContext) => MiddlewareResponse
onError: (err: Error | null, context: HttpContext) => Error | null
}
export {debug_2 as debug}
/** @public */
declare interface FinalizeNodeOptionsPayload extends UrlWithStringQuery {
method: RequestOptions_2['method']
headers: RequestOptions_2['headers']
maxRedirects: RequestOptions_2['maxRedirects']
agent?: any
cert?: any
key?: any
ca?: any
}
/** @public */
export declare function headers(
_headers: any,
opts?: any,
): {
processOptions: (options: RequestOptions) => RequestOptions
}
/** @public */
declare type HookOnRequestEvent_2 = HookOnRequestEventNode | HookOnRequestEventBrowser
/** @public */
declare interface HookOnRequestEventBase {
options: RequestOptions_2
context: HttpContext_2
request: any
}
/** @public */
declare interface HookOnRequestEventBrowser extends HookOnRequestEventBase {
adapter: Omit<RequestAdapter, 'node'>
progress?: undefined
}
/** @public */
declare interface HookOnRequestEventNode extends HookOnRequestEventBase {
adapter: 'node'
progress: any
}
/** @public */
declare interface HttpContext_2 {
options: RequestOptions_2
channels: MiddlewareChannels
applyMiddleware: ApplyMiddleware
}
/** @public */
export declare function httpErrors(): {
onResponse: (res: MiddlewareResponse, ctx: HttpContext) => MiddlewareResponse
}
/** @public */
export declare function injectResponse(opts?: {
inject: (
event: Parameters<MiddlewareHooks['interceptRequest']>[1],
prevValue: Parameters<MiddlewareHooks['interceptRequest']>[0],
) => Partial<MiddlewareResponse_2 | undefined | void>
}): {
interceptRequest: (
prevValue: MiddlewareResponse_2 | undefined,
event: {
adapter: RequestAdapter_2
context: HttpContext
},
) => MiddlewareResponse_2 | undefined
}
/** @public */
export declare function jsonRequest(): {
processOptions: (options: RequestOptions) => RequestOptions
}
/** @public */
export declare function jsonResponse(opts?: any): {
onResponse: (response: MiddlewareResponse) => MiddlewareResponse
processOptions: (options: RequestOptions) => RequestOptions & {
headers: any
}
}
/** @public */
export declare const keepAlive: (config?: {
ms?: number
maxFree?: number
maxRetries?: number
}) => any
/** @public */
declare interface MiddlewareChannels {
request: PubSub<HttpContext_2>
response: PubSub<unknown>
progress: PubSub<unknown>
error: PubSub<unknown>
abort: PubSub<void>
}
/** @public */
declare interface MiddlewareHooks {
processOptions: (options: RequestOptions_2) => RequestOptions_2
validateOptions: (options: RequestOptions_2) => void | undefined
interceptRequest: (
prevValue: MiddlewareResponse_2 | undefined,
event: {
adapter: RequestAdapter
context: HttpContext_2
},
) => MiddlewareResponse_2 | undefined | void
finalizeOptions: (
options: FinalizeNodeOptionsPayload | RequestOptions_2,
) => FinalizeNodeOptionsPayload | RequestOptions_2
onRequest: (evt: HookOnRequestEvent_2) => void
onResponse: (response: MiddlewareResponse_2, context: HttpContext_2) => MiddlewareResponse_2
onError: (err: Error | null, context: HttpContext_2) => any
onReturn: (channels: MiddlewareChannels, context: HttpContext_2) => any
onHeaders: (
response: IncomingMessage,
evt: {
headers: IncomingHttpHeaders
adapter: RequestAdapter
context: HttpContext_2
},
) => ProgressStream
}
/** @public */
declare interface MiddlewareResponse_2 {
body: any
url: string
method: string
headers: any
statusCode: number
statusMessage: string
}
/** @public */
export declare function mtls(config?: any): {
finalizeOptions: (options: RequestOptions | FinalizeNodeOptionsPayload_2) =>
| RequestOptions
| (FinalizeNodeOptionsPayload_2 & {
cert: any
key: any
ca: any
})
}
/** @public */
export declare function observable(opts?: {implementation?: any}): {
onReturn: (channels: MiddlewareChannels_2, context: HttpContext) => any
}
/** @public */
export declare const processOptions: (opts: RequestOptions_2) => {
url: string
body?: any
bodySize?: number
cancelToken?: any
compress?: boolean
headers?: any
maxRedirects?: number
maxRetries?: number
retryDelay?: (attemptNumber: number) => number
method?: string
proxy?: any
query?: any
rawBody?: boolean
shouldRetry?: any
stream?: boolean
timeout: any
tunnel?: boolean
debug?: any
requestId?: number
attemptNumber?: number
withCredentials?: boolean
fetch?: boolean | Omit<RequestInit, 'method'>
useAbortSignal?: boolean
}
declare interface Progress {
percentage: number
transferred: number
length: number
remaining: number
eta: number
runtime: number
delta: number
speed: number
}
/** @public */
export declare function progress(): {
onRequest: (evt: HookOnRequestEvent) => void
}
declare interface ProgressStream extends Transform {
progress(): Progress
}
/** @public */
export declare const promise: {
(options?: {onlyBody?: boolean; implementation?: PromiseConstructor}): {
onReturn: (channels: MiddlewareChannels_2, context: HttpContext) => Promise<unknown>
}
Cancel: typeof Cancel
CancelToken: typeof CancelToken
isCancel: (value: any) => value is Cancel
}
/** @public */
export declare function proxy(_proxy: any): {
processOptions: (options: RequestOptions) => {
proxy: any
} & RequestOptions
}
/** @public */
declare interface PubSub<Message> {
publish: (message: Message) => void
subscribe: (subscriber: Subscriber<Message>) => () => void
}
/**
* Reports the request adapter in use. `node` is only available if `ExportEnv` is also `node`.
* When `ExportEnv` is `browser` then the adapter can be either `xhr` or `fetch`.
* In the future `fetch` will be available in `node` as well.
* @public
*/
declare type RequestAdapter = 'node' | 'xhr' | 'fetch'
/** @public */
declare interface RequestOptions_2 {
url: string
body?: any
bodySize?: number
cancelToken?: any
compress?: boolean
headers?: any
maxRedirects?: number
maxRetries?: number
retryDelay?: (attemptNumber: number) => number
method?: string
proxy?: any
query?: any
rawBody?: boolean
shouldRetry?: any
stream?: boolean
timeout?: any
tunnel?: boolean
debug?: any
requestId?: number
attemptNumber?: number
withCredentials?: boolean
/**
* Enables using the native `fetch` API instead of the default `http` module, and allows setting its options like `cache`
*/
fetch?: boolean | Omit<RequestInit, 'method'>
/**
* Some frameworks have special behavior for `fetch` when an `AbortSignal` is used, and may want to disable it unless userland specifically opts-in.
*/
useAbortSignal?: boolean
}
/** @public */
export declare const retry: {
(opts?: Partial<RetryOptions>): {
onError: (err: Error | null, context: HttpContext) => Error | null
}
shouldRetry: (err: any, _attempt: any, options: any) => any
}
/** @public */
declare interface RetryOptions {
shouldRetry: (err: any, num: number, options: any) => boolean
maxRetries?: number
retryDelay?: (attemptNumber: number) => number
}
/** @public */
declare interface Subscriber<Event> {
(event: Event): void
}
/** @public */
export declare function urlEncoded(): {
processOptions: (options: RequestOptions) => RequestOptions
}
/** @public */
export declare const validateOptions: (options: RequestOptions) => void
export {}

355
server/node_modules/get-it/dist/middleware.browser.d.ts generated vendored Normal file
View File

@@ -0,0 +1,355 @@
import {FinalizeNodeOptionsPayload as FinalizeNodeOptionsPayload_2} from 'get-it'
import {HookOnRequestEvent} from 'get-it'
import {HttpContext} from 'get-it'
import type {IncomingHttpHeaders} from 'http'
import type {IncomingMessage} from 'http'
import {MiddlewareChannels as MiddlewareChannels_2} from 'get-it'
import {MiddlewareResponse} from 'get-it'
import {RequestAdapter as RequestAdapter_2} from 'get-it'
import {RequestOptions} from 'get-it'
import type {Transform} from 'stream'
import type {UrlWithStringQuery} from 'url'
/**
* This middleware only has an effect in Node.js.
* @public
*/
export declare function agent(_opts?: any): any
/** @public */
declare type ApplyMiddleware = <T extends keyof MiddlewareHooks>(
hook: T,
value: MiddlewareHooks[T] extends (defaultValue: infer V, ...rest: any[]) => any ? V : never,
...args: MiddlewareHooks[T] extends (defaultValue: any, ...rest: infer P) => any ? P : never
) => ReturnType<MiddlewareHooks[T]>
/** @public */
export declare function base(baseUrl: string): {
processOptions: (options: RequestOptions) => RequestOptions
}
/**
* The cancel token API is based on the [cancelable promises proposal](https://github.com/tc39/proposal-cancelable-promises), which is currently at Stage 1.
*
* Code shamelessly stolen/borrowed from MIT-licensed [axios](https://github.com/mzabriskie/axios). Thanks to [Nick Uraltsev](https://github.com/nickuraltsev), [Matt Zabriskie](https://github.com/mzabriskie) and the other contributors of that project!
*/
/** @public */
export declare class Cancel {
__CANCEL__: boolean
message: string | undefined
constructor(message: string | undefined)
toString(): string
}
/** @public */
export declare class CancelToken {
promise: Promise<any>
reason?: Cancel
constructor(executor: (cb: (message?: string) => void) => void)
static source: () => {
token: CancelToken
cancel: (message?: string) => void
}
}
/** @public */
declare function debug_2(opts?: any): {
processOptions: (options: RequestOptions) => RequestOptions
onRequest: (event: HookOnRequestEvent) => HookOnRequestEvent
onResponse: (res: MiddlewareResponse, context: HttpContext) => MiddlewareResponse
onError: (err: Error | null, context: HttpContext) => Error | null
}
export {debug_2 as debug}
/** @public */
declare interface FinalizeNodeOptionsPayload extends UrlWithStringQuery {
method: RequestOptions_2['method']
headers: RequestOptions_2['headers']
maxRedirects: RequestOptions_2['maxRedirects']
agent?: any
cert?: any
key?: any
ca?: any
}
/** @public */
export declare function headers(
_headers: any,
opts?: any,
): {
processOptions: (options: RequestOptions) => RequestOptions
}
/** @public */
declare type HookOnRequestEvent_2 = HookOnRequestEventNode | HookOnRequestEventBrowser
/** @public */
declare interface HookOnRequestEventBase {
options: RequestOptions_2
context: HttpContext_2
request: any
}
/** @public */
declare interface HookOnRequestEventBrowser extends HookOnRequestEventBase {
adapter: Omit<RequestAdapter, 'node'>
progress?: undefined
}
/** @public */
declare interface HookOnRequestEventNode extends HookOnRequestEventBase {
adapter: 'node'
progress: any
}
/** @public */
declare interface HttpContext_2 {
options: RequestOptions_2
channels: MiddlewareChannels
applyMiddleware: ApplyMiddleware
}
/** @public */
export declare function httpErrors(): {
onResponse: (res: MiddlewareResponse, ctx: HttpContext) => MiddlewareResponse
}
/** @public */
export declare function injectResponse(opts?: {
inject: (
event: Parameters<MiddlewareHooks['interceptRequest']>[1],
prevValue: Parameters<MiddlewareHooks['interceptRequest']>[0],
) => Partial<MiddlewareResponse_2 | undefined | void>
}): {
interceptRequest: (
prevValue: MiddlewareResponse_2 | undefined,
event: {
adapter: RequestAdapter_2
context: HttpContext
},
) => MiddlewareResponse_2 | undefined
}
/** @public */
export declare function jsonRequest(): {
processOptions: (options: RequestOptions) => RequestOptions
}
/** @public */
export declare function jsonResponse(opts?: any): {
onResponse: (response: MiddlewareResponse) => MiddlewareResponse
processOptions: (options: RequestOptions) => RequestOptions & {
headers: any
}
}
/** @public */
export declare const keepAlive: (config?: {
ms?: number
maxFree?: number
maxRetries?: number
}) => any
/** @public */
declare interface MiddlewareChannels {
request: PubSub<HttpContext_2>
response: PubSub<unknown>
progress: PubSub<unknown>
error: PubSub<unknown>
abort: PubSub<void>
}
/** @public */
declare interface MiddlewareHooks {
processOptions: (options: RequestOptions_2) => RequestOptions_2
validateOptions: (options: RequestOptions_2) => void | undefined
interceptRequest: (
prevValue: MiddlewareResponse_2 | undefined,
event: {
adapter: RequestAdapter
context: HttpContext_2
},
) => MiddlewareResponse_2 | undefined | void
finalizeOptions: (
options: FinalizeNodeOptionsPayload | RequestOptions_2,
) => FinalizeNodeOptionsPayload | RequestOptions_2
onRequest: (evt: HookOnRequestEvent_2) => void
onResponse: (response: MiddlewareResponse_2, context: HttpContext_2) => MiddlewareResponse_2
onError: (err: Error | null, context: HttpContext_2) => any
onReturn: (channels: MiddlewareChannels, context: HttpContext_2) => any
onHeaders: (
response: IncomingMessage,
evt: {
headers: IncomingHttpHeaders
adapter: RequestAdapter
context: HttpContext_2
},
) => ProgressStream
}
/** @public */
declare interface MiddlewareResponse_2 {
body: any
url: string
method: string
headers: any
statusCode: number
statusMessage: string
}
/** @public */
export declare function mtls(config?: any): {
finalizeOptions: (options: RequestOptions | FinalizeNodeOptionsPayload_2) =>
| RequestOptions
| (FinalizeNodeOptionsPayload_2 & {
cert: any
key: any
ca: any
})
}
/** @public */
export declare function observable(opts?: {implementation?: any}): {
onReturn: (channels: MiddlewareChannels_2, context: HttpContext) => any
}
/** @public */
export declare const processOptions: (opts: RequestOptions_2) => {
url: string
body?: any
bodySize?: number
cancelToken?: any
compress?: boolean
headers?: any
maxRedirects?: number
maxRetries?: number
retryDelay?: (attemptNumber: number) => number
method?: string
proxy?: any
query?: any
rawBody?: boolean
shouldRetry?: any
stream?: boolean
timeout: any
tunnel?: boolean
debug?: any
requestId?: number
attemptNumber?: number
withCredentials?: boolean
fetch?: boolean | Omit<RequestInit, 'method'>
useAbortSignal?: boolean
}
declare interface Progress {
percentage: number
transferred: number
length: number
remaining: number
eta: number
runtime: number
delta: number
speed: number
}
/** @public */
export declare function progress(): {
onRequest: (evt: HookOnRequestEvent) => void
}
declare interface ProgressStream extends Transform {
progress(): Progress
}
/** @public */
export declare const promise: {
(options?: {onlyBody?: boolean; implementation?: PromiseConstructor}): {
onReturn: (channels: MiddlewareChannels_2, context: HttpContext) => Promise<unknown>
}
Cancel: typeof Cancel
CancelToken: typeof CancelToken
isCancel: (value: any) => value is Cancel
}
/** @public */
export declare function proxy(_proxy: any): {
processOptions: (options: RequestOptions) => {
proxy: any
} & RequestOptions
}
/** @public */
declare interface PubSub<Message> {
publish: (message: Message) => void
subscribe: (subscriber: Subscriber<Message>) => () => void
}
/**
* Reports the request adapter in use. `node` is only available if `ExportEnv` is also `node`.
* When `ExportEnv` is `browser` then the adapter can be either `xhr` or `fetch`.
* In the future `fetch` will be available in `node` as well.
* @public
*/
declare type RequestAdapter = 'node' | 'xhr' | 'fetch'
/** @public */
declare interface RequestOptions_2 {
url: string
body?: any
bodySize?: number
cancelToken?: any
compress?: boolean
headers?: any
maxRedirects?: number
maxRetries?: number
retryDelay?: (attemptNumber: number) => number
method?: string
proxy?: any
query?: any
rawBody?: boolean
shouldRetry?: any
stream?: boolean
timeout?: any
tunnel?: boolean
debug?: any
requestId?: number
attemptNumber?: number
withCredentials?: boolean
/**
* Enables using the native `fetch` API instead of the default `http` module, and allows setting its options like `cache`
*/
fetch?: boolean | Omit<RequestInit, 'method'>
/**
* Some frameworks have special behavior for `fetch` when an `AbortSignal` is used, and may want to disable it unless userland specifically opts-in.
*/
useAbortSignal?: boolean
}
/** @public */
export declare const retry: {
(opts?: Partial<RetryOptions>): {
onError: (err: Error | null, context: HttpContext) => Error | null
}
shouldRetry: (err: any, _attempt: any, options: any) => any
}
/** @public */
declare interface RetryOptions {
shouldRetry: (err: any, num: number, options: any) => boolean
maxRetries?: number
retryDelay?: (attemptNumber: number) => number
}
/** @public */
declare interface Subscriber<Event> {
(event: Event): void
}
/** @public */
export declare function urlEncoded(): {
processOptions: (options: RequestOptions) => RequestOptions
}
/** @public */
export declare const validateOptions: (options: RequestOptions) => void
export {}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

1
server/node_modules/get-it/dist/middleware.cjs generated vendored Normal file

File diff suppressed because one or more lines are too long

1
server/node_modules/get-it/dist/middleware.cjs.map generated vendored Normal file

File diff suppressed because one or more lines are too long

369
server/node_modules/get-it/dist/middleware.d.cts generated vendored Normal file
View File

@@ -0,0 +1,369 @@
import {AgentOptions} from 'http'
import {FinalizeNodeOptionsPayload as FinalizeNodeOptionsPayload_2} from 'get-it'
import {HookOnRequestEvent} from 'get-it'
import {HttpContext} from 'get-it'
import {IncomingHttpHeaders} from 'http'
import {IncomingMessage} from 'http'
import {MiddlewareChannels as MiddlewareChannels_2} from 'get-it'
import {MiddlewareResponse} from 'get-it'
import {ProgressStream as ProgressStream_2} from '../../util/progress-stream'
import {RequestAdapter as RequestAdapter_2} from 'get-it'
import {RequestOptions} from 'get-it'
import type {Transform} from 'stream'
import type {UrlWithStringQuery} from 'url'
/**
* Constructs a http.Agent and uses it for all requests.
* This can be used to override settings such as `maxSockets`, `maxTotalSockets` (to limit concurrency) or change the `timeout`.
* @public
*/
export declare function agent(opts?: AgentOptions): {
finalizeOptions: (options: any) => any
}
/** @public */
declare type ApplyMiddleware = <T extends keyof MiddlewareHooks>(
hook: T,
value: MiddlewareHooks[T] extends (defaultValue: infer V, ...rest: any[]) => any ? V : never,
...args: MiddlewareHooks[T] extends (defaultValue: any, ...rest: infer P) => any ? P : never
) => ReturnType<MiddlewareHooks[T]>
/** @public */
export declare function base(baseUrl: string): {
processOptions: (options: RequestOptions) => RequestOptions
}
/**
* The cancel token API is based on the [cancelable promises proposal](https://github.com/tc39/proposal-cancelable-promises), which is currently at Stage 1.
*
* Code shamelessly stolen/borrowed from MIT-licensed [axios](https://github.com/mzabriskie/axios). Thanks to [Nick Uraltsev](https://github.com/nickuraltsev), [Matt Zabriskie](https://github.com/mzabriskie) and the other contributors of that project!
*/
/** @public */
export declare class Cancel {
__CANCEL__: boolean
message: string | undefined
constructor(message: string | undefined)
toString(): string
}
/** @public */
export declare class CancelToken {
promise: Promise<any>
reason?: Cancel
constructor(executor: (cb: (message?: string) => void) => void)
static source: () => {
token: CancelToken
cancel: (message?: string) => void
}
}
/** @public */
declare function debug_2(opts?: any): {
processOptions: (options: RequestOptions) => RequestOptions
onRequest: (event: HookOnRequestEvent) => HookOnRequestEvent
onResponse: (res: MiddlewareResponse, context: HttpContext) => MiddlewareResponse
onError: (err: Error | null, context: HttpContext) => Error | null
}
export {debug_2 as debug}
/** @public */
declare interface FinalizeNodeOptionsPayload extends UrlWithStringQuery {
method: RequestOptions_2['method']
headers: RequestOptions_2['headers']
maxRedirects: RequestOptions_2['maxRedirects']
agent?: any
cert?: any
key?: any
ca?: any
}
/** @public */
export declare function headers(
_headers: any,
opts?: any,
): {
processOptions: (options: RequestOptions) => RequestOptions
}
/** @public */
declare type HookOnRequestEvent_2 = HookOnRequestEventNode | HookOnRequestEventBrowser
/** @public */
declare interface HookOnRequestEventBase {
options: RequestOptions_2
context: HttpContext_2
request: any
}
/** @public */
declare interface HookOnRequestEventBrowser extends HookOnRequestEventBase {
adapter: Omit<RequestAdapter, 'node'>
progress?: undefined
}
/** @public */
declare interface HookOnRequestEventNode extends HookOnRequestEventBase {
adapter: 'node'
progress: any
}
/** @public */
declare interface HttpContext_2 {
options: RequestOptions_2
channels: MiddlewareChannels
applyMiddleware: ApplyMiddleware
}
/** @public */
export declare function httpErrors(): {
onResponse: (res: MiddlewareResponse, ctx: HttpContext) => MiddlewareResponse
}
/** @public */
export declare function injectResponse(opts?: {
inject: (
event: Parameters<MiddlewareHooks['interceptRequest']>[1],
prevValue: Parameters<MiddlewareHooks['interceptRequest']>[0],
) => Partial<MiddlewareResponse_2 | undefined | void>
}): {
interceptRequest: (
prevValue: MiddlewareResponse_2 | undefined,
event: {
adapter: RequestAdapter_2
context: HttpContext
},
) => MiddlewareResponse_2 | undefined
}
/** @public */
export declare function jsonRequest(): {
processOptions: (options: RequestOptions) => RequestOptions
}
/** @public */
export declare function jsonResponse(opts?: any): {
onResponse: (response: MiddlewareResponse) => MiddlewareResponse
processOptions: (options: RequestOptions) => RequestOptions & {
headers: any
}
}
/** @public */
export declare const keepAlive: (config?: {
ms?: number
maxFree?: number
maxRetries?: number
}) => any
/** @public */
declare interface MiddlewareChannels {
request: PubSub<HttpContext_2>
response: PubSub<unknown>
progress: PubSub<unknown>
error: PubSub<unknown>
abort: PubSub<void>
}
/** @public */
declare interface MiddlewareHooks {
processOptions: (options: RequestOptions_2) => RequestOptions_2
validateOptions: (options: RequestOptions_2) => void | undefined
interceptRequest: (
prevValue: MiddlewareResponse_2 | undefined,
event: {
adapter: RequestAdapter
context: HttpContext_2
},
) => MiddlewareResponse_2 | undefined | void
finalizeOptions: (
options: FinalizeNodeOptionsPayload | RequestOptions_2,
) => FinalizeNodeOptionsPayload | RequestOptions_2
onRequest: (evt: HookOnRequestEvent_2) => void
onResponse: (response: MiddlewareResponse_2, context: HttpContext_2) => MiddlewareResponse_2
onError: (err: Error | null, context: HttpContext_2) => any
onReturn: (channels: MiddlewareChannels, context: HttpContext_2) => any
onHeaders: (
response: IncomingMessage,
evt: {
headers: IncomingHttpHeaders
adapter: RequestAdapter
context: HttpContext_2
},
) => ProgressStream
}
/** @public */
declare interface MiddlewareResponse_2 {
body: any
url: string
method: string
headers: any
statusCode: number
statusMessage: string
}
/** @public */
export declare function mtls(config?: any): {
finalizeOptions: (options: RequestOptions | FinalizeNodeOptionsPayload_2) =>
| RequestOptions
| (FinalizeNodeOptionsPayload_2 & {
cert: any
key: any
ca: any
})
}
/** @public */
export declare function observable(opts?: {implementation?: any}): {
onReturn: (channels: MiddlewareChannels_2, context: HttpContext) => any
}
/** @public */
export declare const processOptions: (opts: RequestOptions_2) => {
url: string
body?: any
bodySize?: number
cancelToken?: any
compress?: boolean
headers?: any
maxRedirects?: number
maxRetries?: number
retryDelay?: (attemptNumber: number) => number
method?: string
proxy?: any
query?: any
rawBody?: boolean
shouldRetry?: any
stream?: boolean
timeout: any
tunnel?: boolean
debug?: any
requestId?: number
attemptNumber?: number
withCredentials?: boolean
fetch?: boolean | Omit<RequestInit, 'method'>
useAbortSignal?: boolean
}
declare interface Progress {
percentage: number
transferred: number
length: number
remaining: number
eta: number
runtime: number
delta: number
speed: number
}
/** @public */
export declare function progress(): {
onHeaders: (
response: IncomingMessage,
evt: {
headers: IncomingHttpHeaders
adapter: RequestAdapter_2
context: HttpContext
},
) => ProgressStream_2
onRequest: (evt: HookOnRequestEvent) => void
onResponse: (res: MiddlewareResponse, evt: HttpContext) => MiddlewareResponse
}
declare interface ProgressStream extends Transform {
progress(): Progress
}
/** @public */
export declare const promise: {
(options?: {onlyBody?: boolean; implementation?: PromiseConstructor}): {
onReturn: (channels: MiddlewareChannels_2, context: HttpContext) => Promise<unknown>
}
Cancel: typeof Cancel
CancelToken: typeof CancelToken
isCancel: (value: any) => value is Cancel
}
/** @public */
export declare function proxy(_proxy: any): {
processOptions: (options: RequestOptions) => {
proxy: any
} & RequestOptions
}
/** @public */
declare interface PubSub<Message> {
publish: (message: Message) => void
subscribe: (subscriber: Subscriber<Message>) => () => void
}
/**
* Reports the request adapter in use. `node` is only available if `ExportEnv` is also `node`.
* When `ExportEnv` is `browser` then the adapter can be either `xhr` or `fetch`.
* In the future `fetch` will be available in `node` as well.
* @public
*/
declare type RequestAdapter = 'node' | 'xhr' | 'fetch'
/** @public */
declare interface RequestOptions_2 {
url: string
body?: any
bodySize?: number
cancelToken?: any
compress?: boolean
headers?: any
maxRedirects?: number
maxRetries?: number
retryDelay?: (attemptNumber: number) => number
method?: string
proxy?: any
query?: any
rawBody?: boolean
shouldRetry?: any
stream?: boolean
timeout?: any
tunnel?: boolean
debug?: any
requestId?: number
attemptNumber?: number
withCredentials?: boolean
/**
* Enables using the native `fetch` API instead of the default `http` module, and allows setting its options like `cache`
*/
fetch?: boolean | Omit<RequestInit, 'method'>
/**
* Some frameworks have special behavior for `fetch` when an `AbortSignal` is used, and may want to disable it unless userland specifically opts-in.
*/
useAbortSignal?: boolean
}
/** @public */
export declare const retry: {
(opts?: Partial<RetryOptions>): {
onError: (err: Error | null, context: HttpContext) => Error | null
}
shouldRetry: (err: any, _num: number, options: any) => boolean
}
/** @public */
declare interface RetryOptions {
shouldRetry: (err: any, num: number, options: any) => boolean
maxRetries?: number
retryDelay?: (attemptNumber: number) => number
}
/** @public */
declare interface Subscriber<Event> {
(event: Event): void
}
/** @public */
export declare function urlEncoded(): {
processOptions: (options: RequestOptions) => RequestOptions
}
/** @public */
export declare const validateOptions: (options: RequestOptions) => void
export {}

369
server/node_modules/get-it/dist/middleware.d.ts generated vendored Normal file
View File

@@ -0,0 +1,369 @@
import {AgentOptions} from 'http'
import {FinalizeNodeOptionsPayload as FinalizeNodeOptionsPayload_2} from 'get-it'
import {HookOnRequestEvent} from 'get-it'
import {HttpContext} from 'get-it'
import {IncomingHttpHeaders} from 'http'
import {IncomingMessage} from 'http'
import {MiddlewareChannels as MiddlewareChannels_2} from 'get-it'
import {MiddlewareResponse} from 'get-it'
import {ProgressStream as ProgressStream_2} from '../../util/progress-stream'
import {RequestAdapter as RequestAdapter_2} from 'get-it'
import {RequestOptions} from 'get-it'
import type {Transform} from 'stream'
import type {UrlWithStringQuery} from 'url'
/**
* Constructs a http.Agent and uses it for all requests.
* This can be used to override settings such as `maxSockets`, `maxTotalSockets` (to limit concurrency) or change the `timeout`.
* @public
*/
export declare function agent(opts?: AgentOptions): {
finalizeOptions: (options: any) => any
}
/** @public */
declare type ApplyMiddleware = <T extends keyof MiddlewareHooks>(
hook: T,
value: MiddlewareHooks[T] extends (defaultValue: infer V, ...rest: any[]) => any ? V : never,
...args: MiddlewareHooks[T] extends (defaultValue: any, ...rest: infer P) => any ? P : never
) => ReturnType<MiddlewareHooks[T]>
/** @public */
export declare function base(baseUrl: string): {
processOptions: (options: RequestOptions) => RequestOptions
}
/**
* The cancel token API is based on the [cancelable promises proposal](https://github.com/tc39/proposal-cancelable-promises), which is currently at Stage 1.
*
* Code shamelessly stolen/borrowed from MIT-licensed [axios](https://github.com/mzabriskie/axios). Thanks to [Nick Uraltsev](https://github.com/nickuraltsev), [Matt Zabriskie](https://github.com/mzabriskie) and the other contributors of that project!
*/
/** @public */
export declare class Cancel {
__CANCEL__: boolean
message: string | undefined
constructor(message: string | undefined)
toString(): string
}
/** @public */
export declare class CancelToken {
promise: Promise<any>
reason?: Cancel
constructor(executor: (cb: (message?: string) => void) => void)
static source: () => {
token: CancelToken
cancel: (message?: string) => void
}
}
/** @public */
declare function debug_2(opts?: any): {
processOptions: (options: RequestOptions) => RequestOptions
onRequest: (event: HookOnRequestEvent) => HookOnRequestEvent
onResponse: (res: MiddlewareResponse, context: HttpContext) => MiddlewareResponse
onError: (err: Error | null, context: HttpContext) => Error | null
}
export {debug_2 as debug}
/** @public */
declare interface FinalizeNodeOptionsPayload extends UrlWithStringQuery {
method: RequestOptions_2['method']
headers: RequestOptions_2['headers']
maxRedirects: RequestOptions_2['maxRedirects']
agent?: any
cert?: any
key?: any
ca?: any
}
/** @public */
export declare function headers(
_headers: any,
opts?: any,
): {
processOptions: (options: RequestOptions) => RequestOptions
}
/** @public */
declare type HookOnRequestEvent_2 = HookOnRequestEventNode | HookOnRequestEventBrowser
/** @public */
declare interface HookOnRequestEventBase {
options: RequestOptions_2
context: HttpContext_2
request: any
}
/** @public */
declare interface HookOnRequestEventBrowser extends HookOnRequestEventBase {
adapter: Omit<RequestAdapter, 'node'>
progress?: undefined
}
/** @public */
declare interface HookOnRequestEventNode extends HookOnRequestEventBase {
adapter: 'node'
progress: any
}
/** @public */
declare interface HttpContext_2 {
options: RequestOptions_2
channels: MiddlewareChannels
applyMiddleware: ApplyMiddleware
}
/** @public */
export declare function httpErrors(): {
onResponse: (res: MiddlewareResponse, ctx: HttpContext) => MiddlewareResponse
}
/** @public */
export declare function injectResponse(opts?: {
inject: (
event: Parameters<MiddlewareHooks['interceptRequest']>[1],
prevValue: Parameters<MiddlewareHooks['interceptRequest']>[0],
) => Partial<MiddlewareResponse_2 | undefined | void>
}): {
interceptRequest: (
prevValue: MiddlewareResponse_2 | undefined,
event: {
adapter: RequestAdapter_2
context: HttpContext
},
) => MiddlewareResponse_2 | undefined
}
/** @public */
export declare function jsonRequest(): {
processOptions: (options: RequestOptions) => RequestOptions
}
/** @public */
export declare function jsonResponse(opts?: any): {
onResponse: (response: MiddlewareResponse) => MiddlewareResponse
processOptions: (options: RequestOptions) => RequestOptions & {
headers: any
}
}
/** @public */
export declare const keepAlive: (config?: {
ms?: number
maxFree?: number
maxRetries?: number
}) => any
/** @public */
declare interface MiddlewareChannels {
request: PubSub<HttpContext_2>
response: PubSub<unknown>
progress: PubSub<unknown>
error: PubSub<unknown>
abort: PubSub<void>
}
/** @public */
declare interface MiddlewareHooks {
processOptions: (options: RequestOptions_2) => RequestOptions_2
validateOptions: (options: RequestOptions_2) => void | undefined
interceptRequest: (
prevValue: MiddlewareResponse_2 | undefined,
event: {
adapter: RequestAdapter
context: HttpContext_2
},
) => MiddlewareResponse_2 | undefined | void
finalizeOptions: (
options: FinalizeNodeOptionsPayload | RequestOptions_2,
) => FinalizeNodeOptionsPayload | RequestOptions_2
onRequest: (evt: HookOnRequestEvent_2) => void
onResponse: (response: MiddlewareResponse_2, context: HttpContext_2) => MiddlewareResponse_2
onError: (err: Error | null, context: HttpContext_2) => any
onReturn: (channels: MiddlewareChannels, context: HttpContext_2) => any
onHeaders: (
response: IncomingMessage,
evt: {
headers: IncomingHttpHeaders
adapter: RequestAdapter
context: HttpContext_2
},
) => ProgressStream
}
/** @public */
declare interface MiddlewareResponse_2 {
body: any
url: string
method: string
headers: any
statusCode: number
statusMessage: string
}
/** @public */
export declare function mtls(config?: any): {
finalizeOptions: (options: RequestOptions | FinalizeNodeOptionsPayload_2) =>
| RequestOptions
| (FinalizeNodeOptionsPayload_2 & {
cert: any
key: any
ca: any
})
}
/** @public */
export declare function observable(opts?: {implementation?: any}): {
onReturn: (channels: MiddlewareChannels_2, context: HttpContext) => any
}
/** @public */
export declare const processOptions: (opts: RequestOptions_2) => {
url: string
body?: any
bodySize?: number
cancelToken?: any
compress?: boolean
headers?: any
maxRedirects?: number
maxRetries?: number
retryDelay?: (attemptNumber: number) => number
method?: string
proxy?: any
query?: any
rawBody?: boolean
shouldRetry?: any
stream?: boolean
timeout: any
tunnel?: boolean
debug?: any
requestId?: number
attemptNumber?: number
withCredentials?: boolean
fetch?: boolean | Omit<RequestInit, 'method'>
useAbortSignal?: boolean
}
declare interface Progress {
percentage: number
transferred: number
length: number
remaining: number
eta: number
runtime: number
delta: number
speed: number
}
/** @public */
export declare function progress(): {
onHeaders: (
response: IncomingMessage,
evt: {
headers: IncomingHttpHeaders
adapter: RequestAdapter_2
context: HttpContext
},
) => ProgressStream_2
onRequest: (evt: HookOnRequestEvent) => void
onResponse: (res: MiddlewareResponse, evt: HttpContext) => MiddlewareResponse
}
declare interface ProgressStream extends Transform {
progress(): Progress
}
/** @public */
export declare const promise: {
(options?: {onlyBody?: boolean; implementation?: PromiseConstructor}): {
onReturn: (channels: MiddlewareChannels_2, context: HttpContext) => Promise<unknown>
}
Cancel: typeof Cancel
CancelToken: typeof CancelToken
isCancel: (value: any) => value is Cancel
}
/** @public */
export declare function proxy(_proxy: any): {
processOptions: (options: RequestOptions) => {
proxy: any
} & RequestOptions
}
/** @public */
declare interface PubSub<Message> {
publish: (message: Message) => void
subscribe: (subscriber: Subscriber<Message>) => () => void
}
/**
* Reports the request adapter in use. `node` is only available if `ExportEnv` is also `node`.
* When `ExportEnv` is `browser` then the adapter can be either `xhr` or `fetch`.
* In the future `fetch` will be available in `node` as well.
* @public
*/
declare type RequestAdapter = 'node' | 'xhr' | 'fetch'
/** @public */
declare interface RequestOptions_2 {
url: string
body?: any
bodySize?: number
cancelToken?: any
compress?: boolean
headers?: any
maxRedirects?: number
maxRetries?: number
retryDelay?: (attemptNumber: number) => number
method?: string
proxy?: any
query?: any
rawBody?: boolean
shouldRetry?: any
stream?: boolean
timeout?: any
tunnel?: boolean
debug?: any
requestId?: number
attemptNumber?: number
withCredentials?: boolean
/**
* Enables using the native `fetch` API instead of the default `http` module, and allows setting its options like `cache`
*/
fetch?: boolean | Omit<RequestInit, 'method'>
/**
* Some frameworks have special behavior for `fetch` when an `AbortSignal` is used, and may want to disable it unless userland specifically opts-in.
*/
useAbortSignal?: boolean
}
/** @public */
export declare const retry: {
(opts?: Partial<RetryOptions>): {
onError: (err: Error | null, context: HttpContext) => Error | null
}
shouldRetry: (err: any, _num: number, options: any) => boolean
}
/** @public */
declare interface RetryOptions {
shouldRetry: (err: any, num: number, options: any) => boolean
maxRetries?: number
retryDelay?: (attemptNumber: number) => number
}
/** @public */
declare interface Subscriber<Event> {
(event: Event): void
}
/** @public */
export declare function urlEncoded(): {
processOptions: (options: RequestOptions) => RequestOptions
}
/** @public */
export declare const validateOptions: (options: RequestOptions) => void
export {}

1
server/node_modules/get-it/dist/middleware.js generated vendored Normal file

File diff suppressed because one or more lines are too long

1
server/node_modules/get-it/dist/middleware.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

2
server/node_modules/get-it/middleware.js generated vendored Normal file
View File

@@ -0,0 +1,2 @@
// Necessary for `get-it/middleware` imports to work with setups not setup to be ESM native, like older `jest` configs.
module.exports = require('./dist/middleware.cjs') // eslint-disable-line @typescript-eslint/no-require-imports

View File

@@ -0,0 +1,38 @@
# Developer's Certificate of Origin 1.1
By making a contribution to this project, I certify that:
* (a) The contribution was created in whole or in part by me and I
have the right to submit it under the open source license
indicated in the file; or
* (b) The contribution is based upon previous work that, to the best
of my knowledge, is covered under an appropriate open source
license and I have the right under that license to submit that
work with modifications, whether created in whole or in part
by me, under the same open source license (unless I am
permitted to submit under a different license), as indicated
in the file; or
* (c) The contribution was provided directly to me by some other
person who certified (a), (b) or (c) and I have not modified
it.
* (d) I understand and agree that this project and the contribution
are public and that a record of the contribution (including all
personal information I submit with it, including my sign-off) is
maintained indefinitely and may be redistributed consistent with
this project or the open source license(s) involved.
## Moderation Policy
The [Node.js Moderation Policy] applies to this WG.
## Code of Conduct
The [Node.js Code of Conduct][] applies to this WG.
[Node.js Code of Conduct]:
https://github.com/nodejs/node/blob/master/CODE_OF_CONDUCT.md
[Node.js Moderation Policy]:
https://github.com/nodejs/TSC/blob/master/Moderation-Policy.md

View File

@@ -0,0 +1,136 @@
### Streams Working Group
The Node.js Streams is jointly governed by a Working Group
(WG)
that is responsible for high-level guidance of the project.
The WG has final authority over this project including:
* Technical direction
* Project governance and process (including this policy)
* Contribution policy
* GitHub repository hosting
* Conduct guidelines
* Maintaining the list of additional Collaborators
For the current list of WG members, see the project
[README.md](./README.md#current-project-team-members).
### Collaborators
The readable-stream GitHub repository is
maintained by the WG and additional Collaborators who are added by the
WG on an ongoing basis.
Individuals making significant and valuable contributions are made
Collaborators and given commit-access to the project. These
individuals are identified by the WG and their addition as
Collaborators is discussed during the WG meeting.
_Note:_ If you make a significant contribution and are not considered
for commit-access log an issue or contact a WG member directly and it
will be brought up in the next WG meeting.
Modifications of the contents of the readable-stream repository are
made on
a collaborative basis. Anybody with a GitHub account may propose a
modification via pull request and it will be considered by the project
Collaborators. All pull requests must be reviewed and accepted by a
Collaborator with sufficient expertise who is able to take full
responsibility for the change. In the case of pull requests proposed
by an existing Collaborator, an additional Collaborator is required
for sign-off. Consensus should be sought if additional Collaborators
participate and there is disagreement around a particular
modification. See _Consensus Seeking Process_ below for further detail
on the consensus model used for governance.
Collaborators may opt to elevate significant or controversial
modifications, or modifications that have not found consensus to the
WG for discussion by assigning the ***WG-agenda*** tag to a pull
request or issue. The WG should serve as the final arbiter where
required.
For the current list of Collaborators, see the project
[README.md](./README.md#members).
### WG Membership
WG seats are not time-limited. There is no fixed size of the WG.
However, the expected target is between 6 and 12, to ensure adequate
coverage of important areas of expertise, balanced with the ability to
make decisions efficiently.
There is no specific set of requirements or qualifications for WG
membership beyond these rules.
The WG may add additional members to the WG by unanimous consensus.
A WG member may be removed from the WG by voluntary resignation, or by
unanimous consensus of all other WG members.
Changes to WG membership should be posted in the agenda, and may be
suggested as any other agenda item (see "WG Meetings" below).
If an addition or removal is proposed during a meeting, and the full
WG is not in attendance to participate, then the addition or removal
is added to the agenda for the subsequent meeting. This is to ensure
that all members are given the opportunity to participate in all
membership decisions. If a WG member is unable to attend a meeting
where a planned membership decision is being made, then their consent
is assumed.
No more than 1/3 of the WG members may be affiliated with the same
employer. If removal or resignation of a WG member, or a change of
employment by a WG member, creates a situation where more than 1/3 of
the WG membership shares an employer, then the situation must be
immediately remedied by the resignation or removal of one or more WG
members affiliated with the over-represented employer(s).
### WG Meetings
The WG meets occasionally on a Google Hangout On Air. A designated moderator
approved by the WG runs the meeting. Each meeting should be
published to YouTube.
Items are added to the WG agenda that are considered contentious or
are modifications of governance, contribution policy, WG membership,
or release process.
The intention of the agenda is not to approve or review all patches;
that should happen continuously on GitHub and be handled by the larger
group of Collaborators.
Any community member or contributor can ask that something be added to
the next meeting's agenda by logging a GitHub Issue. Any Collaborator,
WG member or the moderator can add the item to the agenda by adding
the ***WG-agenda*** tag to the issue.
Prior to each WG meeting the moderator will share the Agenda with
members of the WG. WG members can add any items they like to the
agenda at the beginning of each meeting. The moderator and the WG
cannot veto or remove items.
The WG may invite persons or representatives from certain projects to
participate in a non-voting capacity.
The moderator is responsible for summarizing the discussion of each
agenda item and sends it as a pull request after the meeting.
### Consensus Seeking Process
The WG follows a
[Consensus
Seeking](http://en.wikipedia.org/wiki/Consensus-seeking_decision-making)
decision-making model.
When an agenda item has appeared to reach a consensus the moderator
will ask "Does anyone object?" as a final call for dissent from the
consensus.
If an agenda item cannot reach a consensus a WG member can call for
either a closing vote or a vote to table the issue to the next
meeting. The call for a vote must be seconded by a majority of the WG
or else the discussion will continue. Simple majority wins.
Note that changes to WG membership require a majority consensus. See
"WG Membership" above.

View File

@@ -0,0 +1,47 @@
Node.js is licensed for use as follows:
"""
Copyright Node.js contributors. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
"""
This license applies to parts of Node.js originating from the
https://github.com/joyent/node repository:
"""
Copyright Joyent, Inc. and other Node contributors. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
"""

View File

@@ -0,0 +1,106 @@
# readable-stream
***Node.js core streams for userland*** [![Build Status](https://travis-ci.com/nodejs/readable-stream.svg?branch=master)](https://travis-ci.com/nodejs/readable-stream)
[![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/)
[![NPM](https://nodei.co/npm-dl/readable-stream.png?&months=6&height=3)](https://nodei.co/npm/readable-stream/)
[![Sauce Test Status](https://saucelabs.com/browser-matrix/readabe-stream.svg)](https://saucelabs.com/u/readabe-stream)
```bash
npm install --save readable-stream
```
This package is a mirror of the streams implementations in Node.js.
Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v10.18.1/docs/api/stream.html).
If you want to guarantee a stable streams base, regardless of what version of
Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core, for background see [this blogpost](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html).
As of version 2.0.0 **readable-stream** uses semantic versioning.
## Version 3.x.x
v3.x.x of `readable-stream` is a cut from Node 10. This version supports Node 6, 8, and 10, as well as evergreen browsers, IE 11 and latest Safari. The breaking changes introduced by v3 are composed by the combined breaking changes in [Node v9](https://nodejs.org/en/blog/release/v9.0.0/) and [Node v10](https://nodejs.org/en/blog/release/v10.0.0/), as follows:
1. Error codes: https://github.com/nodejs/node/pull/13310,
https://github.com/nodejs/node/pull/13291,
https://github.com/nodejs/node/pull/16589,
https://github.com/nodejs/node/pull/15042,
https://github.com/nodejs/node/pull/15665,
https://github.com/nodejs/readable-stream/pull/344
2. 'readable' have precedence over flowing
https://github.com/nodejs/node/pull/18994
3. make virtual methods errors consistent
https://github.com/nodejs/node/pull/18813
4. updated streams error handling
https://github.com/nodejs/node/pull/18438
5. writable.end should return this.
https://github.com/nodejs/node/pull/18780
6. readable continues to read when push('')
https://github.com/nodejs/node/pull/18211
7. add custom inspect to BufferList
https://github.com/nodejs/node/pull/17907
8. always defer 'readable' with nextTick
https://github.com/nodejs/node/pull/17979
## Version 2.x.x
v2.x.x of `readable-stream` is a cut of the stream module from Node 8 (there have been no semver-major changes from Node 4 to 8). This version supports all Node.js versions from 0.8, as well as evergreen browsers and IE 10 & 11.
### Big Thanks
Cross-browser Testing Platform and Open Source <3 Provided by [Sauce Labs][sauce]
# Usage
You can swap your `require('stream')` with `require('readable-stream')`
without any changes, if you are just using one of the main classes and
functions.
```js
const {
Readable,
Writable,
Transform,
Duplex,
pipeline,
finished
} = require('readable-stream')
````
Note that `require('stream')` will return `Stream`, while
`require('readable-stream')` will return `Readable`. We discourage using
whatever is exported directly, but rather use one of the properties as
shown in the example above.
# Streams Working Group
`readable-stream` is maintained by the Streams Working Group, which
oversees the development and maintenance of the Streams API within
Node.js. The responsibilities of the Streams Working Group include:
* Addressing stream issues on the Node.js issue tracker.
* Authoring and editing stream documentation within the Node.js project.
* Reviewing changes to stream subclasses within the Node.js project.
* Redirecting changes to streams from the Node.js project to this
project.
* Assisting in the implementation of stream providers within Node.js.
* Recommending versions of `readable-stream` to be included in Node.js.
* Messaging about the future of streams to give the community advance
notice of changes.
<a name="members"></a>
## Team Members
* **Calvin Metcalf** ([@calvinmetcalf](https://github.com/calvinmetcalf)) &lt;calvin.metcalf@gmail.com&gt;
- Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242
* **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) &lt;mathiasbuus@gmail.com&gt;
* **Matteo Collina** ([@mcollina](https://github.com/mcollina)) &lt;matteo.collina@gmail.com&gt;
- Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E
* **Irina Shestak** ([@lrlna](https://github.com/lrlna)) &lt;shestak.irina@gmail.com&gt;
* **Yoshua Wyuts** ([@yoshuawuyts](https://github.com/yoshuawuyts)) &lt;yoshuawuyts@gmail.com&gt;
[sauce]: https://saucelabs.com

View File

@@ -0,0 +1,127 @@
'use strict';
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var codes = {};
function createErrorType(code, message, Base) {
if (!Base) {
Base = Error;
}
function getMessage(arg1, arg2, arg3) {
if (typeof message === 'string') {
return message;
} else {
return message(arg1, arg2, arg3);
}
}
var NodeError =
/*#__PURE__*/
function (_Base) {
_inheritsLoose(NodeError, _Base);
function NodeError(arg1, arg2, arg3) {
return _Base.call(this, getMessage(arg1, arg2, arg3)) || this;
}
return NodeError;
}(Base);
NodeError.prototype.name = Base.name;
NodeError.prototype.code = code;
codes[code] = NodeError;
} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js
function oneOf(expected, thing) {
if (Array.isArray(expected)) {
var len = expected.length;
expected = expected.map(function (i) {
return String(i);
});
if (len > 2) {
return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1];
} else if (len === 2) {
return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]);
} else {
return "of ".concat(thing, " ").concat(expected[0]);
}
} else {
return "of ".concat(thing, " ").concat(String(expected));
}
} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
function startsWith(str, search, pos) {
return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
function endsWith(str, search, this_len) {
if (this_len === undefined || this_len > str.length) {
this_len = str.length;
}
return str.substring(this_len - search.length, this_len) === search;
} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
function includes(str, search, start) {
if (typeof start !== 'number') {
start = 0;
}
if (start + search.length > str.length) {
return false;
} else {
return str.indexOf(search, start) !== -1;
}
}
createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {
return 'The value "' + value + '" is invalid for option "' + name + '"';
}, TypeError);
createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {
// determiner: 'must be' or 'must not be'
var determiner;
if (typeof expected === 'string' && startsWith(expected, 'not ')) {
determiner = 'must not be';
expected = expected.replace(/^not /, '');
} else {
determiner = 'must be';
}
var msg;
if (endsWith(name, ' argument')) {
// For cases like 'first argument'
msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
} else {
var type = includes(name, '.') ? 'property' : 'argument';
msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
}
msg += ". Received type ".concat(typeof actual);
return msg;
}, TypeError);
createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');
createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {
return 'The ' + name + ' method is not implemented';
});
createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');
createErrorType('ERR_STREAM_DESTROYED', function (name) {
return 'Cannot call ' + name + ' after a stream was destroyed';
});
createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');
createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');
createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');
createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);
createErrorType('ERR_UNKNOWN_ENCODING', function (arg) {
return 'Unknown encoding: ' + arg;
}, TypeError);
createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');
module.exports.codes = codes;

View File

@@ -0,0 +1,116 @@
'use strict';
const codes = {};
function createErrorType(code, message, Base) {
if (!Base) {
Base = Error
}
function getMessage (arg1, arg2, arg3) {
if (typeof message === 'string') {
return message
} else {
return message(arg1, arg2, arg3)
}
}
class NodeError extends Base {
constructor (arg1, arg2, arg3) {
super(getMessage(arg1, arg2, arg3));
}
}
NodeError.prototype.name = Base.name;
NodeError.prototype.code = code;
codes[code] = NodeError;
}
// https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js
function oneOf(expected, thing) {
if (Array.isArray(expected)) {
const len = expected.length;
expected = expected.map((i) => String(i));
if (len > 2) {
return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` +
expected[len - 1];
} else if (len === 2) {
return `one of ${thing} ${expected[0]} or ${expected[1]}`;
} else {
return `of ${thing} ${expected[0]}`;
}
} else {
return `of ${thing} ${String(expected)}`;
}
}
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
function startsWith(str, search, pos) {
return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
}
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
function endsWith(str, search, this_len) {
if (this_len === undefined || this_len > str.length) {
this_len = str.length;
}
return str.substring(this_len - search.length, this_len) === search;
}
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
function includes(str, search, start) {
if (typeof start !== 'number') {
start = 0;
}
if (start + search.length > str.length) {
return false;
} else {
return str.indexOf(search, start) !== -1;
}
}
createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {
return 'The value "' + value + '" is invalid for option "' + name + '"'
}, TypeError);
createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {
// determiner: 'must be' or 'must not be'
let determiner;
if (typeof expected === 'string' && startsWith(expected, 'not ')) {
determiner = 'must not be';
expected = expected.replace(/^not /, '');
} else {
determiner = 'must be';
}
let msg;
if (endsWith(name, ' argument')) {
// For cases like 'first argument'
msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`;
} else {
const type = includes(name, '.') ? 'property' : 'argument';
msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`;
}
msg += `. Received type ${typeof actual}`;
return msg;
}, TypeError);
createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');
createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {
return 'The ' + name + ' method is not implemented'
});
createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');
createErrorType('ERR_STREAM_DESTROYED', function (name) {
return 'Cannot call ' + name + ' after a stream was destroyed';
});
createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');
createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');
createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');
createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);
createErrorType('ERR_UNKNOWN_ENCODING', function (arg) {
return 'Unknown encoding: ' + arg
}, TypeError);
createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');
module.exports.codes = codes;

View File

@@ -0,0 +1,17 @@
'use strict'
var experimentalWarnings = new Set();
function emitExperimentalWarning(feature) {
if (experimentalWarnings.has(feature)) return;
var msg = feature + ' is an experimental feature. This feature could ' +
'change at any time';
experimentalWarnings.add(feature);
process.emitWarning(msg, 'ExperimentalWarning');
}
function noop() {}
module.exports.emitExperimentalWarning = process.emitWarning
? emitExperimentalWarning
: noop;

View File

@@ -0,0 +1,126 @@
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// a duplex stream is just a stream that is both readable and writable.
// Since JS doesn't have multiple prototypal inheritance, this class
// prototypally inherits from Readable, and then parasitically from
// Writable.
'use strict';
/*<replacement>*/
var objectKeys = Object.keys || function (obj) {
var keys = [];
for (var key in obj) keys.push(key);
return keys;
};
/*</replacement>*/
module.exports = Duplex;
var Readable = require('./_stream_readable');
var Writable = require('./_stream_writable');
require('inherits')(Duplex, Readable);
{
// Allow the keys array to be GC'ed.
var keys = objectKeys(Writable.prototype);
for (var v = 0; v < keys.length; v++) {
var method = keys[v];
if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
}
}
function Duplex(options) {
if (!(this instanceof Duplex)) return new Duplex(options);
Readable.call(this, options);
Writable.call(this, options);
this.allowHalfOpen = true;
if (options) {
if (options.readable === false) this.readable = false;
if (options.writable === false) this.writable = false;
if (options.allowHalfOpen === false) {
this.allowHalfOpen = false;
this.once('end', onend);
}
}
}
Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function get() {
return this._writableState.highWaterMark;
}
});
Object.defineProperty(Duplex.prototype, 'writableBuffer', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function get() {
return this._writableState && this._writableState.getBuffer();
}
});
Object.defineProperty(Duplex.prototype, 'writableLength', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function get() {
return this._writableState.length;
}
});
// the no-half-open enforcer
function onend() {
// If the writable side ended, then we're ok.
if (this._writableState.ended) return;
// no more data can be written.
// But allow more writes to happen in this tick.
process.nextTick(onEndNT, this);
}
function onEndNT(self) {
self.end();
}
Object.defineProperty(Duplex.prototype, 'destroyed', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function get() {
if (this._readableState === undefined || this._writableState === undefined) {
return false;
}
return this._readableState.destroyed && this._writableState.destroyed;
},
set: function set(value) {
// we ignore the value if the stream
// has not been initialized yet
if (this._readableState === undefined || this._writableState === undefined) {
return;
}
// backward compatibility, the user is explicitly
// managing destroyed
this._readableState.destroyed = value;
this._writableState.destroyed = value;
}
});

View File

@@ -0,0 +1,37 @@
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// a passthrough stream.
// basically just the most minimal sort of Transform stream.
// Every written chunk gets output as-is.
'use strict';
module.exports = PassThrough;
var Transform = require('./_stream_transform');
require('inherits')(PassThrough, Transform);
function PassThrough(options) {
if (!(this instanceof PassThrough)) return new PassThrough(options);
Transform.call(this, options);
}
PassThrough.prototype._transform = function (chunk, encoding, cb) {
cb(null, chunk);
};

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,190 @@
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// a transform stream is a readable/writable stream where you do
// something with the data. Sometimes it's called a "filter",
// but that's not a great name for it, since that implies a thing where
// some bits pass through, and others are simply ignored. (That would
// be a valid example of a transform, of course.)
//
// While the output is causally related to the input, it's not a
// necessarily symmetric or synchronous transformation. For example,
// a zlib stream might take multiple plain-text writes(), and then
// emit a single compressed chunk some time in the future.
//
// Here's how this works:
//
// The Transform stream has all the aspects of the readable and writable
// stream classes. When you write(chunk), that calls _write(chunk,cb)
// internally, and returns false if there's a lot of pending writes
// buffered up. When you call read(), that calls _read(n) until
// there's enough pending readable data buffered up.
//
// In a transform stream, the written data is placed in a buffer. When
// _read(n) is called, it transforms the queued up data, calling the
// buffered _write cb's as it consumes chunks. If consuming a single
// written chunk would result in multiple output chunks, then the first
// outputted bit calls the readcb, and subsequent chunks just go into
// the read buffer, and will cause it to emit 'readable' if necessary.
//
// This way, back-pressure is actually determined by the reading side,
// since _read has to be called to start processing a new chunk. However,
// a pathological inflate type of transform can cause excessive buffering
// here. For example, imagine a stream where every byte of input is
// interpreted as an integer from 0-255, and then results in that many
// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
// 1kb of data being output. In this case, you could write a very small
// amount of input, and end up with a very large amount of output. In
// such a pathological inflating mechanism, there'd be no way to tell
// the system to stop doing the transform. A single 4MB write could
// cause the system to run out of memory.
//
// However, even in such a pathological case, only a single written chunk
// would be consumed, and then the rest would wait (un-transformed) until
// the results of the previous transformed chunk were consumed.
'use strict';
module.exports = Transform;
var _require$codes = require('../errors').codes,
ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,
ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;
var Duplex = require('./_stream_duplex');
require('inherits')(Transform, Duplex);
function afterTransform(er, data) {
var ts = this._transformState;
ts.transforming = false;
var cb = ts.writecb;
if (cb === null) {
return this.emit('error', new ERR_MULTIPLE_CALLBACK());
}
ts.writechunk = null;
ts.writecb = null;
if (data != null)
// single equals check for both `null` and `undefined`
this.push(data);
cb(er);
var rs = this._readableState;
rs.reading = false;
if (rs.needReadable || rs.length < rs.highWaterMark) {
this._read(rs.highWaterMark);
}
}
function Transform(options) {
if (!(this instanceof Transform)) return new Transform(options);
Duplex.call(this, options);
this._transformState = {
afterTransform: afterTransform.bind(this),
needTransform: false,
transforming: false,
writecb: null,
writechunk: null,
writeencoding: null
};
// start out asking for a readable event once data is transformed.
this._readableState.needReadable = true;
// we have implemented the _read method, and done the other things
// that Readable wants before the first _read call, so unset the
// sync guard flag.
this._readableState.sync = false;
if (options) {
if (typeof options.transform === 'function') this._transform = options.transform;
if (typeof options.flush === 'function') this._flush = options.flush;
}
// When the writable side finishes, then flush out anything remaining.
this.on('prefinish', prefinish);
}
function prefinish() {
var _this = this;
if (typeof this._flush === 'function' && !this._readableState.destroyed) {
this._flush(function (er, data) {
done(_this, er, data);
});
} else {
done(this, null, null);
}
}
Transform.prototype.push = function (chunk, encoding) {
this._transformState.needTransform = false;
return Duplex.prototype.push.call(this, chunk, encoding);
};
// This is the part where you do stuff!
// override this function in implementation classes.
// 'chunk' is an input chunk.
//
// Call `push(newChunk)` to pass along transformed output
// to the readable side. You may call 'push' zero or more times.
//
// Call `cb(err)` when you are done with this chunk. If you pass
// an error, then that'll put the hurt on the whole operation. If you
// never call cb(), then you'll never get another chunk.
Transform.prototype._transform = function (chunk, encoding, cb) {
cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));
};
Transform.prototype._write = function (chunk, encoding, cb) {
var ts = this._transformState;
ts.writecb = cb;
ts.writechunk = chunk;
ts.writeencoding = encoding;
if (!ts.transforming) {
var rs = this._readableState;
if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
}
};
// Doesn't matter what the args are here.
// _transform does all the work.
// That we got here means that the readable side wants more data.
Transform.prototype._read = function (n) {
var ts = this._transformState;
if (ts.writechunk !== null && !ts.transforming) {
ts.transforming = true;
this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
} else {
// mark that we need a transform, so that any data that comes in
// will get processed, now that we've asked for it.
ts.needTransform = true;
}
};
Transform.prototype._destroy = function (err, cb) {
Duplex.prototype._destroy.call(this, err, function (err2) {
cb(err2);
});
};
function done(stream, er, data) {
if (er) return stream.emit('error', er);
if (data != null)
// single equals check for both `null` and `undefined`
stream.push(data);
// TODO(BridgeAR): Write a test for these two error cases
// if there's nothing in the write buffer, then that means
// that nothing more will ever be provided
if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();
if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();
return stream.push(null);
}

View File

@@ -0,0 +1,641 @@
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// A bit simpler than readable streams.
// Implement an async ._write(chunk, encoding, cb), and it'll handle all
// the drain event emission and buffering.
'use strict';
module.exports = Writable;
/* <replacement> */
function WriteReq(chunk, encoding, cb) {
this.chunk = chunk;
this.encoding = encoding;
this.callback = cb;
this.next = null;
}
// It seems a linked list but it is not
// there will be only 2 of these for each stream
function CorkedRequest(state) {
var _this = this;
this.next = null;
this.entry = null;
this.finish = function () {
onCorkedFinish(_this, state);
};
}
/* </replacement> */
/*<replacement>*/
var Duplex;
/*</replacement>*/
Writable.WritableState = WritableState;
/*<replacement>*/
var internalUtil = {
deprecate: require('util-deprecate')
};
/*</replacement>*/
/*<replacement>*/
var Stream = require('./internal/streams/stream');
/*</replacement>*/
var Buffer = require('buffer').Buffer;
var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};
function _uint8ArrayToBuffer(chunk) {
return Buffer.from(chunk);
}
function _isUint8Array(obj) {
return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
}
var destroyImpl = require('./internal/streams/destroy');
var _require = require('./internal/streams/state'),
getHighWaterMark = _require.getHighWaterMark;
var _require$codes = require('../errors').codes,
ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,
ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,
ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,
ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,
ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;
var errorOrDestroy = destroyImpl.errorOrDestroy;
require('inherits')(Writable, Stream);
function nop() {}
function WritableState(options, stream, isDuplex) {
Duplex = Duplex || require('./_stream_duplex');
options = options || {};
// Duplex streams are both readable and writable, but share
// the same options object.
// However, some cases require setting options to different
// values for the readable and the writable sides of the duplex stream,
// e.g. options.readableObjectMode vs. options.writableObjectMode, etc.
if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex;
// object stream flag to indicate whether or not this stream
// contains buffers or objects.
this.objectMode = !!options.objectMode;
if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
// the point at which write() starts returning false
// Note: 0 is a valid value, means that we always return false if
// the entire buffer is not flushed immediately on write()
this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex);
// if _final has been called
this.finalCalled = false;
// drain event flag.
this.needDrain = false;
// at the start of calling end()
this.ending = false;
// when end() has been called, and returned
this.ended = false;
// when 'finish' is emitted
this.finished = false;
// has it been destroyed
this.destroyed = false;
// should we decode strings into buffers before passing to _write?
// this is here so that some node-core streams can optimize string
// handling at a lower level.
var noDecode = options.decodeStrings === false;
this.decodeStrings = !noDecode;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// not an actual buffer we keep track of, but a measurement
// of how much we're waiting to get pushed to some underlying
// socket or file.
this.length = 0;
// a flag to see when we're in the middle of a write.
this.writing = false;
// when true all writes will be buffered until .uncork() call
this.corked = 0;
// a flag to be able to tell if the onwrite cb is called immediately,
// or on a later tick. We set this to true at first, because any
// actions that shouldn't happen until "later" should generally also
// not happen before the first write call.
this.sync = true;
// a flag to know if we're processing previously buffered items, which
// may call the _write() callback in the same tick, so that we don't
// end up in an overlapped onwrite situation.
this.bufferProcessing = false;
// the callback that's passed to _write(chunk,cb)
this.onwrite = function (er) {
onwrite(stream, er);
};
// the callback that the user supplies to write(chunk,encoding,cb)
this.writecb = null;
// the amount that is being written when _write is called.
this.writelen = 0;
this.bufferedRequest = null;
this.lastBufferedRequest = null;
// number of pending user-supplied write callbacks
// this must be 0 before 'finish' can be emitted
this.pendingcb = 0;
// emit prefinish if the only thing we're waiting for is _write cbs
// This is relevant for synchronous Transform streams
this.prefinished = false;
// True if the error was already emitted and should not be thrown again
this.errorEmitted = false;
// Should close be emitted on destroy. Defaults to true.
this.emitClose = options.emitClose !== false;
// Should .destroy() be called after 'finish' (and potentially 'end')
this.autoDestroy = !!options.autoDestroy;
// count buffered requests
this.bufferedRequestCount = 0;
// allocate the first CorkedRequest, there is always
// one allocated and free to use, and we maintain at most two
this.corkedRequestsFree = new CorkedRequest(this);
}
WritableState.prototype.getBuffer = function getBuffer() {
var current = this.bufferedRequest;
var out = [];
while (current) {
out.push(current);
current = current.next;
}
return out;
};
(function () {
try {
Object.defineProperty(WritableState.prototype, 'buffer', {
get: internalUtil.deprecate(function writableStateBufferGetter() {
return this.getBuffer();
}, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
});
} catch (_) {}
})();
// Test _writableState for inheritance to account for Duplex streams,
// whose prototype chain only points to Readable.
var realHasInstance;
if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
realHasInstance = Function.prototype[Symbol.hasInstance];
Object.defineProperty(Writable, Symbol.hasInstance, {
value: function value(object) {
if (realHasInstance.call(this, object)) return true;
if (this !== Writable) return false;
return object && object._writableState instanceof WritableState;
}
});
} else {
realHasInstance = function realHasInstance(object) {
return object instanceof this;
};
}
function Writable(options) {
Duplex = Duplex || require('./_stream_duplex');
// Writable ctor is applied to Duplexes, too.
// `realHasInstance` is necessary because using plain `instanceof`
// would return false, as no `_writableState` property is attached.
// Trying to use the custom `instanceof` for Writable here will also break the
// Node.js LazyTransform implementation, which has a non-trivial getter for
// `_writableState` that would lead to infinite recursion.
// Checking for a Stream.Duplex instance is faster here instead of inside
// the WritableState constructor, at least with V8 6.5
var isDuplex = this instanceof Duplex;
if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);
this._writableState = new WritableState(options, this, isDuplex);
// legacy.
this.writable = true;
if (options) {
if (typeof options.write === 'function') this._write = options.write;
if (typeof options.writev === 'function') this._writev = options.writev;
if (typeof options.destroy === 'function') this._destroy = options.destroy;
if (typeof options.final === 'function') this._final = options.final;
}
Stream.call(this);
}
// Otherwise people can pipe Writable streams, which is just wrong.
Writable.prototype.pipe = function () {
errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());
};
function writeAfterEnd(stream, cb) {
var er = new ERR_STREAM_WRITE_AFTER_END();
// TODO: defer error events consistently everywhere, not just the cb
errorOrDestroy(stream, er);
process.nextTick(cb, er);
}
// Checks that a user-supplied chunk is valid, especially for the particular
// mode the stream is in. Currently this means that `null` is never accepted
// and undefined/non-string values are only allowed in object mode.
function validChunk(stream, state, chunk, cb) {
var er;
if (chunk === null) {
er = new ERR_STREAM_NULL_VALUES();
} else if (typeof chunk !== 'string' && !state.objectMode) {
er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
}
if (er) {
errorOrDestroy(stream, er);
process.nextTick(cb, er);
return false;
}
return true;
}
Writable.prototype.write = function (chunk, encoding, cb) {
var state = this._writableState;
var ret = false;
var isBuf = !state.objectMode && _isUint8Array(chunk);
if (isBuf && !Buffer.isBuffer(chunk)) {
chunk = _uint8ArrayToBuffer(chunk);
}
if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
if (typeof cb !== 'function') cb = nop;
if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
state.pendingcb++;
ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
}
return ret;
};
Writable.prototype.cork = function () {
this._writableState.corked++;
};
Writable.prototype.uncork = function () {
var state = this._writableState;
if (state.corked) {
state.corked--;
if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
}
};
Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
// node::ParseEncoding() requires lower case.
if (typeof encoding === 'string') encoding = encoding.toLowerCase();
if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding);
this._writableState.defaultEncoding = encoding;
return this;
};
Object.defineProperty(Writable.prototype, 'writableBuffer', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function get() {
return this._writableState && this._writableState.getBuffer();
}
});
function decodeChunk(state, chunk, encoding) {
if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
chunk = Buffer.from(chunk, encoding);
}
return chunk;
}
Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function get() {
return this._writableState.highWaterMark;
}
});
// if we're already writing something, then just put this
// in the queue, and wait our turn. Otherwise, call _write
// If we return false, then we need a drain event, so set that flag.
function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
if (!isBuf) {
var newChunk = decodeChunk(state, chunk, encoding);
if (chunk !== newChunk) {
isBuf = true;
encoding = 'buffer';
chunk = newChunk;
}
}
var len = state.objectMode ? 1 : chunk.length;
state.length += len;
var ret = state.length < state.highWaterMark;
// we must ensure that previous needDrain will not be reset to false.
if (!ret) state.needDrain = true;
if (state.writing || state.corked) {
var last = state.lastBufferedRequest;
state.lastBufferedRequest = {
chunk: chunk,
encoding: encoding,
isBuf: isBuf,
callback: cb,
next: null
};
if (last) {
last.next = state.lastBufferedRequest;
} else {
state.bufferedRequest = state.lastBufferedRequest;
}
state.bufferedRequestCount += 1;
} else {
doWrite(stream, state, false, len, chunk, encoding, cb);
}
return ret;
}
function doWrite(stream, state, writev, len, chunk, encoding, cb) {
state.writelen = len;
state.writecb = cb;
state.writing = true;
state.sync = true;
if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
state.sync = false;
}
function onwriteError(stream, state, sync, er, cb) {
--state.pendingcb;
if (sync) {
// defer the callback if we are being called synchronously
// to avoid piling up things on the stack
process.nextTick(cb, er);
// this can emit finish, and it will always happen
// after error
process.nextTick(finishMaybe, stream, state);
stream._writableState.errorEmitted = true;
errorOrDestroy(stream, er);
} else {
// the caller expect this to happen before if
// it is async
cb(er);
stream._writableState.errorEmitted = true;
errorOrDestroy(stream, er);
// this can emit finish, but finish must
// always follow error
finishMaybe(stream, state);
}
}
function onwriteStateUpdate(state) {
state.writing = false;
state.writecb = null;
state.length -= state.writelen;
state.writelen = 0;
}
function onwrite(stream, er) {
var state = stream._writableState;
var sync = state.sync;
var cb = state.writecb;
if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();
onwriteStateUpdate(state);
if (er) onwriteError(stream, state, sync, er, cb);else {
// Check if we're actually ready to finish, but don't emit yet
var finished = needFinish(state) || stream.destroyed;
if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
clearBuffer(stream, state);
}
if (sync) {
process.nextTick(afterWrite, stream, state, finished, cb);
} else {
afterWrite(stream, state, finished, cb);
}
}
}
function afterWrite(stream, state, finished, cb) {
if (!finished) onwriteDrain(stream, state);
state.pendingcb--;
cb();
finishMaybe(stream, state);
}
// Must force callback to be called on nextTick, so that we don't
// emit 'drain' before the write() consumer gets the 'false' return
// value, and has a chance to attach a 'drain' listener.
function onwriteDrain(stream, state) {
if (state.length === 0 && state.needDrain) {
state.needDrain = false;
stream.emit('drain');
}
}
// if there's something in the buffer waiting, then process it
function clearBuffer(stream, state) {
state.bufferProcessing = true;
var entry = state.bufferedRequest;
if (stream._writev && entry && entry.next) {
// Fast case, write everything using _writev()
var l = state.bufferedRequestCount;
var buffer = new Array(l);
var holder = state.corkedRequestsFree;
holder.entry = entry;
var count = 0;
var allBuffers = true;
while (entry) {
buffer[count] = entry;
if (!entry.isBuf) allBuffers = false;
entry = entry.next;
count += 1;
}
buffer.allBuffers = allBuffers;
doWrite(stream, state, true, state.length, buffer, '', holder.finish);
// doWrite is almost always async, defer these to save a bit of time
// as the hot path ends with doWrite
state.pendingcb++;
state.lastBufferedRequest = null;
if (holder.next) {
state.corkedRequestsFree = holder.next;
holder.next = null;
} else {
state.corkedRequestsFree = new CorkedRequest(state);
}
state.bufferedRequestCount = 0;
} else {
// Slow case, write chunks one-by-one
while (entry) {
var chunk = entry.chunk;
var encoding = entry.encoding;
var cb = entry.callback;
var len = state.objectMode ? 1 : chunk.length;
doWrite(stream, state, false, len, chunk, encoding, cb);
entry = entry.next;
state.bufferedRequestCount--;
// if we didn't call the onwrite immediately, then
// it means that we need to wait until it does.
// also, that means that the chunk and cb are currently
// being processed, so move the buffer counter past them.
if (state.writing) {
break;
}
}
if (entry === null) state.lastBufferedRequest = null;
}
state.bufferedRequest = entry;
state.bufferProcessing = false;
}
Writable.prototype._write = function (chunk, encoding, cb) {
cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));
};
Writable.prototype._writev = null;
Writable.prototype.end = function (chunk, encoding, cb) {
var state = this._writableState;
if (typeof chunk === 'function') {
cb = chunk;
chunk = null;
encoding = null;
} else if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
// .end() fully uncorks
if (state.corked) {
state.corked = 1;
this.uncork();
}
// ignore unnecessary end() calls.
if (!state.ending) endWritable(this, state, cb);
return this;
};
Object.defineProperty(Writable.prototype, 'writableLength', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function get() {
return this._writableState.length;
}
});
function needFinish(state) {
return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
}
function callFinal(stream, state) {
stream._final(function (err) {
state.pendingcb--;
if (err) {
errorOrDestroy(stream, err);
}
state.prefinished = true;
stream.emit('prefinish');
finishMaybe(stream, state);
});
}
function prefinish(stream, state) {
if (!state.prefinished && !state.finalCalled) {
if (typeof stream._final === 'function' && !state.destroyed) {
state.pendingcb++;
state.finalCalled = true;
process.nextTick(callFinal, stream, state);
} else {
state.prefinished = true;
stream.emit('prefinish');
}
}
}
function finishMaybe(stream, state) {
var need = needFinish(state);
if (need) {
prefinish(stream, state);
if (state.pendingcb === 0) {
state.finished = true;
stream.emit('finish');
if (state.autoDestroy) {
// In case of duplex streams we need a way to detect
// if the readable side is ready for autoDestroy as well
var rState = stream._readableState;
if (!rState || rState.autoDestroy && rState.endEmitted) {
stream.destroy();
}
}
}
}
return need;
}
function endWritable(stream, state, cb) {
state.ending = true;
finishMaybe(stream, state);
if (cb) {
if (state.finished) process.nextTick(cb);else stream.once('finish', cb);
}
state.ended = true;
stream.writable = false;
}
function onCorkedFinish(corkReq, state, err) {
var entry = corkReq.entry;
corkReq.entry = null;
while (entry) {
var cb = entry.callback;
state.pendingcb--;
cb(err);
entry = entry.next;
}
// reuse the free corkReq.
state.corkedRequestsFree.next = corkReq;
}
Object.defineProperty(Writable.prototype, 'destroyed', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function get() {
if (this._writableState === undefined) {
return false;
}
return this._writableState.destroyed;
},
set: function set(value) {
// we ignore the value if the stream
// has not been initialized yet
if (!this._writableState) {
return;
}
// backward compatibility, the user is explicitly
// managing destroyed
this._writableState.destroyed = value;
}
});
Writable.prototype.destroy = destroyImpl.destroy;
Writable.prototype._undestroy = destroyImpl.undestroy;
Writable.prototype._destroy = function (err, cb) {
cb(err);
};

View File

@@ -0,0 +1,180 @@
'use strict';
var _Object$setPrototypeO;
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
var finished = require('./end-of-stream');
var kLastResolve = Symbol('lastResolve');
var kLastReject = Symbol('lastReject');
var kError = Symbol('error');
var kEnded = Symbol('ended');
var kLastPromise = Symbol('lastPromise');
var kHandlePromise = Symbol('handlePromise');
var kStream = Symbol('stream');
function createIterResult(value, done) {
return {
value: value,
done: done
};
}
function readAndResolve(iter) {
var resolve = iter[kLastResolve];
if (resolve !== null) {
var data = iter[kStream].read();
// we defer if data is null
// we can be expecting either 'end' or
// 'error'
if (data !== null) {
iter[kLastPromise] = null;
iter[kLastResolve] = null;
iter[kLastReject] = null;
resolve(createIterResult(data, false));
}
}
}
function onReadable(iter) {
// we wait for the next tick, because it might
// emit an error with process.nextTick
process.nextTick(readAndResolve, iter);
}
function wrapForNext(lastPromise, iter) {
return function (resolve, reject) {
lastPromise.then(function () {
if (iter[kEnded]) {
resolve(createIterResult(undefined, true));
return;
}
iter[kHandlePromise](resolve, reject);
}, reject);
};
}
var AsyncIteratorPrototype = Object.getPrototypeOf(function () {});
var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {
get stream() {
return this[kStream];
},
next: function next() {
var _this = this;
// if we have detected an error in the meanwhile
// reject straight away
var error = this[kError];
if (error !== null) {
return Promise.reject(error);
}
if (this[kEnded]) {
return Promise.resolve(createIterResult(undefined, true));
}
if (this[kStream].destroyed) {
// We need to defer via nextTick because if .destroy(err) is
// called, the error will be emitted via nextTick, and
// we cannot guarantee that there is no error lingering around
// waiting to be emitted.
return new Promise(function (resolve, reject) {
process.nextTick(function () {
if (_this[kError]) {
reject(_this[kError]);
} else {
resolve(createIterResult(undefined, true));
}
});
});
}
// if we have multiple next() calls
// we will wait for the previous Promise to finish
// this logic is optimized to support for await loops,
// where next() is only called once at a time
var lastPromise = this[kLastPromise];
var promise;
if (lastPromise) {
promise = new Promise(wrapForNext(lastPromise, this));
} else {
// fast path needed to support multiple this.push()
// without triggering the next() queue
var data = this[kStream].read();
if (data !== null) {
return Promise.resolve(createIterResult(data, false));
}
promise = new Promise(this[kHandlePromise]);
}
this[kLastPromise] = promise;
return promise;
}
}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {
return this;
}), _defineProperty(_Object$setPrototypeO, "return", function _return() {
var _this2 = this;
// destroy(err, cb) is a private API
// we can guarantee we have that here, because we control the
// Readable class this is attached to
return new Promise(function (resolve, reject) {
_this2[kStream].destroy(null, function (err) {
if (err) {
reject(err);
return;
}
resolve(createIterResult(undefined, true));
});
});
}), _Object$setPrototypeO), AsyncIteratorPrototype);
var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {
var _Object$create;
var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {
value: stream,
writable: true
}), _defineProperty(_Object$create, kLastResolve, {
value: null,
writable: true
}), _defineProperty(_Object$create, kLastReject, {
value: null,
writable: true
}), _defineProperty(_Object$create, kError, {
value: null,
writable: true
}), _defineProperty(_Object$create, kEnded, {
value: stream._readableState.endEmitted,
writable: true
}), _defineProperty(_Object$create, kHandlePromise, {
value: function value(resolve, reject) {
var data = iterator[kStream].read();
if (data) {
iterator[kLastPromise] = null;
iterator[kLastResolve] = null;
iterator[kLastReject] = null;
resolve(createIterResult(data, false));
} else {
iterator[kLastResolve] = resolve;
iterator[kLastReject] = reject;
}
},
writable: true
}), _Object$create));
iterator[kLastPromise] = null;
finished(stream, function (err) {
if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
var reject = iterator[kLastReject];
// reject if we are waiting for data in the Promise
// returned by next() and store the error
if (reject !== null) {
iterator[kLastPromise] = null;
iterator[kLastResolve] = null;
iterator[kLastReject] = null;
reject(err);
}
iterator[kError] = err;
return;
}
var resolve = iterator[kLastResolve];
if (resolve !== null) {
iterator[kLastPromise] = null;
iterator[kLastResolve] = null;
iterator[kLastReject] = null;
resolve(createIterResult(undefined, true));
}
iterator[kEnded] = true;
});
stream.on('readable', onReadable.bind(null, iterator));
return iterator;
};
module.exports = createReadableStreamAsyncIterator;

View File

@@ -0,0 +1,183 @@
'use strict';
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
var _require = require('buffer'),
Buffer = _require.Buffer;
var _require2 = require('util'),
inspect = _require2.inspect;
var custom = inspect && inspect.custom || 'inspect';
function copyBuffer(src, target, offset) {
Buffer.prototype.copy.call(src, target, offset);
}
module.exports = /*#__PURE__*/function () {
function BufferList() {
_classCallCheck(this, BufferList);
this.head = null;
this.tail = null;
this.length = 0;
}
_createClass(BufferList, [{
key: "push",
value: function push(v) {
var entry = {
data: v,
next: null
};
if (this.length > 0) this.tail.next = entry;else this.head = entry;
this.tail = entry;
++this.length;
}
}, {
key: "unshift",
value: function unshift(v) {
var entry = {
data: v,
next: this.head
};
if (this.length === 0) this.tail = entry;
this.head = entry;
++this.length;
}
}, {
key: "shift",
value: function shift() {
if (this.length === 0) return;
var ret = this.head.data;
if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
--this.length;
return ret;
}
}, {
key: "clear",
value: function clear() {
this.head = this.tail = null;
this.length = 0;
}
}, {
key: "join",
value: function join(s) {
if (this.length === 0) return '';
var p = this.head;
var ret = '' + p.data;
while (p = p.next) ret += s + p.data;
return ret;
}
}, {
key: "concat",
value: function concat(n) {
if (this.length === 0) return Buffer.alloc(0);
var ret = Buffer.allocUnsafe(n >>> 0);
var p = this.head;
var i = 0;
while (p) {
copyBuffer(p.data, ret, i);
i += p.data.length;
p = p.next;
}
return ret;
}
// Consumes a specified amount of bytes or characters from the buffered data.
}, {
key: "consume",
value: function consume(n, hasStrings) {
var ret;
if (n < this.head.data.length) {
// `slice` is the same for buffers and strings.
ret = this.head.data.slice(0, n);
this.head.data = this.head.data.slice(n);
} else if (n === this.head.data.length) {
// First chunk is a perfect match.
ret = this.shift();
} else {
// Result spans more than one buffer.
ret = hasStrings ? this._getString(n) : this._getBuffer(n);
}
return ret;
}
}, {
key: "first",
value: function first() {
return this.head.data;
}
// Consumes a specified amount of characters from the buffered data.
}, {
key: "_getString",
value: function _getString(n) {
var p = this.head;
var c = 1;
var ret = p.data;
n -= ret.length;
while (p = p.next) {
var str = p.data;
var nb = n > str.length ? str.length : n;
if (nb === str.length) ret += str;else ret += str.slice(0, n);
n -= nb;
if (n === 0) {
if (nb === str.length) {
++c;
if (p.next) this.head = p.next;else this.head = this.tail = null;
} else {
this.head = p;
p.data = str.slice(nb);
}
break;
}
++c;
}
this.length -= c;
return ret;
}
// Consumes a specified amount of bytes from the buffered data.
}, {
key: "_getBuffer",
value: function _getBuffer(n) {
var ret = Buffer.allocUnsafe(n);
var p = this.head;
var c = 1;
p.data.copy(ret);
n -= p.data.length;
while (p = p.next) {
var buf = p.data;
var nb = n > buf.length ? buf.length : n;
buf.copy(ret, ret.length - n, 0, nb);
n -= nb;
if (n === 0) {
if (nb === buf.length) {
++c;
if (p.next) this.head = p.next;else this.head = this.tail = null;
} else {
this.head = p;
p.data = buf.slice(nb);
}
break;
}
++c;
}
this.length -= c;
return ret;
}
// Make sure the linked list only shows the minimal necessary information.
}, {
key: custom,
value: function value(_, options) {
return inspect(this, _objectSpread(_objectSpread({}, options), {}, {
// Only inspect one level.
depth: 0,
// It should not recurse.
customInspect: false
}));
}
}]);
return BufferList;
}();

View File

@@ -0,0 +1,96 @@
'use strict';
// undocumented cb() API, needed for core, not for public API
function destroy(err, cb) {
var _this = this;
var readableDestroyed = this._readableState && this._readableState.destroyed;
var writableDestroyed = this._writableState && this._writableState.destroyed;
if (readableDestroyed || writableDestroyed) {
if (cb) {
cb(err);
} else if (err) {
if (!this._writableState) {
process.nextTick(emitErrorNT, this, err);
} else if (!this._writableState.errorEmitted) {
this._writableState.errorEmitted = true;
process.nextTick(emitErrorNT, this, err);
}
}
return this;
}
// we set destroyed to true before firing error callbacks in order
// to make it re-entrance safe in case destroy() is called within callbacks
if (this._readableState) {
this._readableState.destroyed = true;
}
// if this is a duplex stream mark the writable part as destroyed as well
if (this._writableState) {
this._writableState.destroyed = true;
}
this._destroy(err || null, function (err) {
if (!cb && err) {
if (!_this._writableState) {
process.nextTick(emitErrorAndCloseNT, _this, err);
} else if (!_this._writableState.errorEmitted) {
_this._writableState.errorEmitted = true;
process.nextTick(emitErrorAndCloseNT, _this, err);
} else {
process.nextTick(emitCloseNT, _this);
}
} else if (cb) {
process.nextTick(emitCloseNT, _this);
cb(err);
} else {
process.nextTick(emitCloseNT, _this);
}
});
return this;
}
function emitErrorAndCloseNT(self, err) {
emitErrorNT(self, err);
emitCloseNT(self);
}
function emitCloseNT(self) {
if (self._writableState && !self._writableState.emitClose) return;
if (self._readableState && !self._readableState.emitClose) return;
self.emit('close');
}
function undestroy() {
if (this._readableState) {
this._readableState.destroyed = false;
this._readableState.reading = false;
this._readableState.ended = false;
this._readableState.endEmitted = false;
}
if (this._writableState) {
this._writableState.destroyed = false;
this._writableState.ended = false;
this._writableState.ending = false;
this._writableState.finalCalled = false;
this._writableState.prefinished = false;
this._writableState.finished = false;
this._writableState.errorEmitted = false;
}
}
function emitErrorNT(self, err) {
self.emit('error', err);
}
function errorOrDestroy(stream, err) {
// We have tests that rely on errors being emitted
// in the same tick, so changing this is semver major.
// For now when you opt-in to autoDestroy we allow
// the error to be emitted nextTick. In a future
// semver major update we should change the default to this.
var rState = stream._readableState;
var wState = stream._writableState;
if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);
}
module.exports = {
destroy: destroy,
undestroy: undestroy,
errorOrDestroy: errorOrDestroy
};

View File

@@ -0,0 +1,86 @@
// Ported from https://github.com/mafintosh/end-of-stream with
// permission from the author, Mathias Buus (@mafintosh).
'use strict';
var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE;
function once(callback) {
var called = false;
return function () {
if (called) return;
called = true;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
callback.apply(this, args);
};
}
function noop() {}
function isRequest(stream) {
return stream.setHeader && typeof stream.abort === 'function';
}
function eos(stream, opts, callback) {
if (typeof opts === 'function') return eos(stream, null, opts);
if (!opts) opts = {};
callback = once(callback || noop);
var readable = opts.readable || opts.readable !== false && stream.readable;
var writable = opts.writable || opts.writable !== false && stream.writable;
var onlegacyfinish = function onlegacyfinish() {
if (!stream.writable) onfinish();
};
var writableEnded = stream._writableState && stream._writableState.finished;
var onfinish = function onfinish() {
writable = false;
writableEnded = true;
if (!readable) callback.call(stream);
};
var readableEnded = stream._readableState && stream._readableState.endEmitted;
var onend = function onend() {
readable = false;
readableEnded = true;
if (!writable) callback.call(stream);
};
var onerror = function onerror(err) {
callback.call(stream, err);
};
var onclose = function onclose() {
var err;
if (readable && !readableEnded) {
if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
return callback.call(stream, err);
}
if (writable && !writableEnded) {
if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
return callback.call(stream, err);
}
};
var onrequest = function onrequest() {
stream.req.on('finish', onfinish);
};
if (isRequest(stream)) {
stream.on('complete', onfinish);
stream.on('abort', onclose);
if (stream.req) onrequest();else stream.on('request', onrequest);
} else if (writable && !stream._writableState) {
// legacy streams
stream.on('end', onlegacyfinish);
stream.on('close', onlegacyfinish);
}
stream.on('end', onend);
stream.on('finish', onfinish);
if (opts.error !== false) stream.on('error', onerror);
stream.on('close', onclose);
return function () {
stream.removeListener('complete', onfinish);
stream.removeListener('abort', onclose);
stream.removeListener('request', onrequest);
if (stream.req) stream.req.removeListener('finish', onfinish);
stream.removeListener('end', onlegacyfinish);
stream.removeListener('close', onlegacyfinish);
stream.removeListener('finish', onfinish);
stream.removeListener('end', onend);
stream.removeListener('error', onerror);
stream.removeListener('close', onclose);
};
}
module.exports = eos;

View File

@@ -0,0 +1,3 @@
module.exports = function () {
throw new Error('Readable.from is not available in the browser')
};

View File

@@ -0,0 +1,52 @@
'use strict';
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
var ERR_INVALID_ARG_TYPE = require('../../../errors').codes.ERR_INVALID_ARG_TYPE;
function from(Readable, iterable, opts) {
var iterator;
if (iterable && typeof iterable.next === 'function') {
iterator = iterable;
} else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable);
var readable = new Readable(_objectSpread({
objectMode: true
}, opts));
// Reading boolean to protect against _read
// being called before last iteration completion.
var reading = false;
readable._read = function () {
if (!reading) {
reading = true;
next();
}
};
function next() {
return _next2.apply(this, arguments);
}
function _next2() {
_next2 = _asyncToGenerator(function* () {
try {
var _yield$iterator$next = yield iterator.next(),
value = _yield$iterator$next.value,
done = _yield$iterator$next.done;
if (done) {
readable.push(null);
} else if (readable.push(yield value)) {
next();
} else {
reading = false;
}
} catch (err) {
readable.destroy(err);
}
});
return _next2.apply(this, arguments);
}
return readable;
}
module.exports = from;

View File

@@ -0,0 +1,86 @@
// Ported from https://github.com/mafintosh/pump with
// permission from the author, Mathias Buus (@mafintosh).
'use strict';
var eos;
function once(callback) {
var called = false;
return function () {
if (called) return;
called = true;
callback.apply(void 0, arguments);
};
}
var _require$codes = require('../../../errors').codes,
ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,
ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;
function noop(err) {
// Rethrow the error if it exists to avoid swallowing it
if (err) throw err;
}
function isRequest(stream) {
return stream.setHeader && typeof stream.abort === 'function';
}
function destroyer(stream, reading, writing, callback) {
callback = once(callback);
var closed = false;
stream.on('close', function () {
closed = true;
});
if (eos === undefined) eos = require('./end-of-stream');
eos(stream, {
readable: reading,
writable: writing
}, function (err) {
if (err) return callback(err);
closed = true;
callback();
});
var destroyed = false;
return function (err) {
if (closed) return;
if (destroyed) return;
destroyed = true;
// request.destroy just do .end - .abort is what we want
if (isRequest(stream)) return stream.abort();
if (typeof stream.destroy === 'function') return stream.destroy();
callback(err || new ERR_STREAM_DESTROYED('pipe'));
};
}
function call(fn) {
fn();
}
function pipe(from, to) {
return from.pipe(to);
}
function popCallback(streams) {
if (!streams.length) return noop;
if (typeof streams[streams.length - 1] !== 'function') return noop;
return streams.pop();
}
function pipeline() {
for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {
streams[_key] = arguments[_key];
}
var callback = popCallback(streams);
if (Array.isArray(streams[0])) streams = streams[0];
if (streams.length < 2) {
throw new ERR_MISSING_ARGS('streams');
}
var error;
var destroys = streams.map(function (stream, i) {
var reading = i < streams.length - 1;
var writing = i > 0;
return destroyer(stream, reading, writing, function (err) {
if (!error) error = err;
if (err) destroys.forEach(call);
if (reading) return;
destroys.forEach(call);
callback(error);
});
});
return streams.reduce(pipe);
}
module.exports = pipeline;

View File

@@ -0,0 +1,22 @@
'use strict';
var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE;
function highWaterMarkFrom(options, isDuplex, duplexKey) {
return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
}
function getHighWaterMark(state, options, duplexKey, isDuplex) {
var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
if (hwm != null) {
if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {
var name = isDuplex ? duplexKey : 'highWaterMark';
throw new ERR_INVALID_OPT_VALUE(name, hwm);
}
return Math.floor(hwm);
}
// Default value
return state.objectMode ? 16 : 16 * 1024;
}
module.exports = {
getHighWaterMark: getHighWaterMark
};

View File

@@ -0,0 +1 @@
module.exports = require('events').EventEmitter;

View File

@@ -0,0 +1 @@
module.exports = require('stream');

View File

@@ -0,0 +1,68 @@
{
"name": "readable-stream",
"version": "3.6.2",
"description": "Streams3, a user-land copy of the stream library from Node.js",
"main": "readable.js",
"engines": {
"node": ">= 6"
},
"dependencies": {
"inherits": "^2.0.3",
"string_decoder": "^1.1.1",
"util-deprecate": "^1.0.1"
},
"devDependencies": {
"@babel/cli": "^7.2.0",
"@babel/core": "^7.2.0",
"@babel/polyfill": "^7.0.0",
"@babel/preset-env": "^7.2.0",
"airtap": "0.0.9",
"assert": "^1.4.0",
"bl": "^2.0.0",
"deep-strict-equal": "^0.2.0",
"events.once": "^2.0.2",
"glob": "^7.1.2",
"gunzip-maybe": "^1.4.1",
"hyperquest": "^2.1.3",
"lolex": "^2.6.0",
"nyc": "^11.0.0",
"pump": "^3.0.0",
"rimraf": "^2.6.2",
"tap": "^12.0.0",
"tape": "^4.9.0",
"tar-fs": "^1.16.2",
"util-promisify": "^2.1.0"
},
"scripts": {
"test": "tap -J --no-esm test/parallel/*.js test/ours/*.js",
"ci": "TAP=1 tap --no-esm test/parallel/*.js test/ours/*.js | tee test.tap",
"test-browsers": "airtap --sauce-connect --loopback airtap.local -- test/browser.js",
"test-browser-local": "airtap --open --local -- test/browser.js",
"cover": "nyc npm test",
"report": "nyc report --reporter=lcov",
"update-browser-errors": "babel -o errors-browser.js errors.js"
},
"repository": {
"type": "git",
"url": "git://github.com/nodejs/readable-stream"
},
"keywords": [
"readable",
"stream",
"pipe"
],
"browser": {
"util": false,
"worker_threads": false,
"./errors": "./errors-browser.js",
"./readable.js": "./readable-browser.js",
"./lib/internal/streams/from.js": "./lib/internal/streams/from-browser.js",
"./lib/internal/streams/stream.js": "./lib/internal/streams/stream-browser.js"
},
"nyc": {
"include": [
"lib/**.js"
]
},
"license": "MIT"
}

View File

@@ -0,0 +1,9 @@
exports = module.exports = require('./lib/_stream_readable.js');
exports.Stream = exports;
exports.Readable = exports;
exports.Writable = require('./lib/_stream_writable.js');
exports.Duplex = require('./lib/_stream_duplex.js');
exports.Transform = require('./lib/_stream_transform.js');
exports.PassThrough = require('./lib/_stream_passthrough.js');
exports.finished = require('./lib/internal/streams/end-of-stream.js');
exports.pipeline = require('./lib/internal/streams/pipeline.js');

View File

@@ -0,0 +1,16 @@
var Stream = require('stream');
if (process.env.READABLE_STREAM === 'disable' && Stream) {
module.exports = Stream.Readable;
Object.assign(module.exports, Stream);
module.exports.Stream = Stream;
} else {
exports = module.exports = require('./lib/_stream_readable.js');
exports.Stream = Stream || exports;
exports.Readable = exports;
exports.Writable = require('./lib/_stream_writable.js');
exports.Duplex = require('./lib/_stream_duplex.js');
exports.Transform = require('./lib/_stream_transform.js');
exports.PassThrough = require('./lib/_stream_passthrough.js');
exports.finished = require('./lib/internal/streams/end-of-stream.js');
exports.pipeline = require('./lib/internal/streams/pipeline.js');
}

View File

@@ -0,0 +1,48 @@
Node.js is licensed for use as follows:
"""
Copyright Node.js contributors. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
"""
This license applies to parts of Node.js originating from the
https://github.com/joyent/node repository:
"""
Copyright Joyent, Inc. and other Node contributors. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
"""

View File

@@ -0,0 +1,47 @@
# string_decoder
***Node-core v8.9.4 string_decoder for userland***
[![NPM](https://nodei.co/npm/string_decoder.png?downloads=true&downloadRank=true)](https://nodei.co/npm/string_decoder/)
[![NPM](https://nodei.co/npm-dl/string_decoder.png?&months=6&height=3)](https://nodei.co/npm/string_decoder/)
```bash
npm install --save string_decoder
```
***Node-core string_decoder for userland***
This package is a mirror of the string_decoder implementation in Node-core.
Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v8.9.4/docs/api/).
As of version 1.0.0 **string_decoder** uses semantic versioning.
## Previous versions
Previous version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10.
## Update
The *build/* directory contains a build script that will scrape the source from the [nodejs/node](https://github.com/nodejs/node) repo given a specific Node version.
## Streams Working Group
`string_decoder` is maintained by the Streams Working Group, which
oversees the development and maintenance of the Streams API within
Node.js. The responsibilities of the Streams Working Group include:
* Addressing stream issues on the Node.js issue tracker.
* Authoring and editing stream documentation within the Node.js project.
* Reviewing changes to stream subclasses within the Node.js project.
* Redirecting changes to streams from the Node.js project to this
project.
* Assisting in the implementation of stream providers within Node.js.
* Recommending versions of `readable-stream` to be included in Node.js.
* Messaging about the future of streams to give the community advance
notice of changes.
See [readable-stream](https://github.com/nodejs/readable-stream) for
more details.

View File

@@ -0,0 +1,296 @@
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
/*<replacement>*/
var Buffer = require('safe-buffer').Buffer;
/*</replacement>*/
var isEncoding = Buffer.isEncoding || function (encoding) {
encoding = '' + encoding;
switch (encoding && encoding.toLowerCase()) {
case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':
return true;
default:
return false;
}
};
function _normalizeEncoding(enc) {
if (!enc) return 'utf8';
var retried;
while (true) {
switch (enc) {
case 'utf8':
case 'utf-8':
return 'utf8';
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return 'utf16le';
case 'latin1':
case 'binary':
return 'latin1';
case 'base64':
case 'ascii':
case 'hex':
return enc;
default:
if (retried) return; // undefined
enc = ('' + enc).toLowerCase();
retried = true;
}
}
};
// Do not cache `Buffer.isEncoding` when checking encoding names as some
// modules monkey-patch it to support additional encodings
function normalizeEncoding(enc) {
var nenc = _normalizeEncoding(enc);
if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
return nenc || enc;
}
// StringDecoder provides an interface for efficiently splitting a series of
// buffers into a series of JS strings without breaking apart multi-byte
// characters.
exports.StringDecoder = StringDecoder;
function StringDecoder(encoding) {
this.encoding = normalizeEncoding(encoding);
var nb;
switch (this.encoding) {
case 'utf16le':
this.text = utf16Text;
this.end = utf16End;
nb = 4;
break;
case 'utf8':
this.fillLast = utf8FillLast;
nb = 4;
break;
case 'base64':
this.text = base64Text;
this.end = base64End;
nb = 3;
break;
default:
this.write = simpleWrite;
this.end = simpleEnd;
return;
}
this.lastNeed = 0;
this.lastTotal = 0;
this.lastChar = Buffer.allocUnsafe(nb);
}
StringDecoder.prototype.write = function (buf) {
if (buf.length === 0) return '';
var r;
var i;
if (this.lastNeed) {
r = this.fillLast(buf);
if (r === undefined) return '';
i = this.lastNeed;
this.lastNeed = 0;
} else {
i = 0;
}
if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
return r || '';
};
StringDecoder.prototype.end = utf8End;
// Returns only complete characters in a Buffer
StringDecoder.prototype.text = utf8Text;
// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
StringDecoder.prototype.fillLast = function (buf) {
if (this.lastNeed <= buf.length) {
buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
return this.lastChar.toString(this.encoding, 0, this.lastTotal);
}
buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
this.lastNeed -= buf.length;
};
// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
// continuation byte. If an invalid byte is detected, -2 is returned.
function utf8CheckByte(byte) {
if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
return byte >> 6 === 0x02 ? -1 : -2;
}
// Checks at most 3 bytes at the end of a Buffer in order to detect an
// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
// needed to complete the UTF-8 character (if applicable) are returned.
function utf8CheckIncomplete(self, buf, i) {
var j = buf.length - 1;
if (j < i) return 0;
var nb = utf8CheckByte(buf[j]);
if (nb >= 0) {
if (nb > 0) self.lastNeed = nb - 1;
return nb;
}
if (--j < i || nb === -2) return 0;
nb = utf8CheckByte(buf[j]);
if (nb >= 0) {
if (nb > 0) self.lastNeed = nb - 2;
return nb;
}
if (--j < i || nb === -2) return 0;
nb = utf8CheckByte(buf[j]);
if (nb >= 0) {
if (nb > 0) {
if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
}
return nb;
}
return 0;
}
// Validates as many continuation bytes for a multi-byte UTF-8 character as
// needed or are available. If we see a non-continuation byte where we expect
// one, we "replace" the validated continuation bytes we've seen so far with
// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
// behavior. The continuation byte check is included three times in the case
// where all of the continuation bytes for a character exist in the same buffer.
// It is also done this way as a slight performance increase instead of using a
// loop.
function utf8CheckExtraBytes(self, buf, p) {
if ((buf[0] & 0xC0) !== 0x80) {
self.lastNeed = 0;
return '\ufffd';
}
if (self.lastNeed > 1 && buf.length > 1) {
if ((buf[1] & 0xC0) !== 0x80) {
self.lastNeed = 1;
return '\ufffd';
}
if (self.lastNeed > 2 && buf.length > 2) {
if ((buf[2] & 0xC0) !== 0x80) {
self.lastNeed = 2;
return '\ufffd';
}
}
}
}
// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
function utf8FillLast(buf) {
var p = this.lastTotal - this.lastNeed;
var r = utf8CheckExtraBytes(this, buf, p);
if (r !== undefined) return r;
if (this.lastNeed <= buf.length) {
buf.copy(this.lastChar, p, 0, this.lastNeed);
return this.lastChar.toString(this.encoding, 0, this.lastTotal);
}
buf.copy(this.lastChar, p, 0, buf.length);
this.lastNeed -= buf.length;
}
// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
// partial character, the character's bytes are buffered until the required
// number of bytes are available.
function utf8Text(buf, i) {
var total = utf8CheckIncomplete(this, buf, i);
if (!this.lastNeed) return buf.toString('utf8', i);
this.lastTotal = total;
var end = buf.length - (total - this.lastNeed);
buf.copy(this.lastChar, 0, end);
return buf.toString('utf8', i, end);
}
// For UTF-8, a replacement character is added when ending on a partial
// character.
function utf8End(buf) {
var r = buf && buf.length ? this.write(buf) : '';
if (this.lastNeed) return r + '\ufffd';
return r;
}
// UTF-16LE typically needs two bytes per character, but even if we have an even
// number of bytes available, we need to check if we end on a leading/high
// surrogate. In that case, we need to wait for the next two bytes in order to
// decode the last character properly.
function utf16Text(buf, i) {
if ((buf.length - i) % 2 === 0) {
var r = buf.toString('utf16le', i);
if (r) {
var c = r.charCodeAt(r.length - 1);
if (c >= 0xD800 && c <= 0xDBFF) {
this.lastNeed = 2;
this.lastTotal = 4;
this.lastChar[0] = buf[buf.length - 2];
this.lastChar[1] = buf[buf.length - 1];
return r.slice(0, -1);
}
}
return r;
}
this.lastNeed = 1;
this.lastTotal = 2;
this.lastChar[0] = buf[buf.length - 1];
return buf.toString('utf16le', i, buf.length - 1);
}
// For UTF-16LE we do not explicitly append special replacement characters if we
// end on a partial character, we simply let v8 handle that.
function utf16End(buf) {
var r = buf && buf.length ? this.write(buf) : '';
if (this.lastNeed) {
var end = this.lastTotal - this.lastNeed;
return r + this.lastChar.toString('utf16le', 0, end);
}
return r;
}
function base64Text(buf, i) {
var n = (buf.length - i) % 3;
if (n === 0) return buf.toString('base64', i);
this.lastNeed = 3 - n;
this.lastTotal = 3;
if (n === 1) {
this.lastChar[0] = buf[buf.length - 1];
} else {
this.lastChar[0] = buf[buf.length - 2];
this.lastChar[1] = buf[buf.length - 1];
}
return buf.toString('base64', i, buf.length - n);
}
function base64End(buf) {
var r = buf && buf.length ? this.write(buf) : '';
if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
return r;
}
// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
function simpleWrite(buf) {
return buf.toString(this.encoding);
}
function simpleEnd(buf) {
return buf && buf.length ? this.write(buf) : '';
}

View File

@@ -0,0 +1,34 @@
{
"name": "string_decoder",
"version": "1.3.0",
"description": "The string_decoder module from Node core",
"main": "lib/string_decoder.js",
"files": [
"lib"
],
"dependencies": {
"safe-buffer": "~5.2.0"
},
"devDependencies": {
"babel-polyfill": "^6.23.0",
"core-util-is": "^1.0.2",
"inherits": "^2.0.3",
"tap": "~0.4.8"
},
"scripts": {
"test": "tap test/parallel/*.js && node test/verify-dependencies",
"ci": "tap test/parallel/*.js test/ours/*.js --tap | tee test.tap && node test/verify-dependencies.js"
},
"repository": {
"type": "git",
"url": "git://github.com/nodejs/string_decoder.git"
},
"homepage": "https://github.com/nodejs/string_decoder",
"keywords": [
"string",
"decoder",
"browser",
"browserify"
],
"license": "MIT"
}

View File

@@ -0,0 +1,9 @@
# The MIT License (MIT)
**Copyright (c) Rod Vagg (the "Original Author") and additional contributors**
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,140 @@
# through2
![Build & Test](https://github.com/rvagg/through2/workflows/Build%20&%20Test/badge.svg)
[![NPM](https://nodei.co/npm/through2.png?downloads&downloadRank)](https://nodei.co/npm/through2/)
**A tiny wrapper around Node.js streams.Transform (Streams2/3) to avoid explicit subclassing noise**
Inspired by [Dominic Tarr](https://github.com/dominictarr)'s [through](https://github.com/dominictarr/through) in that it's so much easier to make a stream out of a function than it is to set up the prototype chain properly: `through(function (chunk) { ... })`.
```js
fs.createReadStream('ex.txt')
.pipe(through2(function (chunk, enc, callback) {
for (let i = 0; i < chunk.length; i++)
if (chunk[i] == 97)
chunk[i] = 122 // swap 'a' for 'z'
this.push(chunk)
callback()
}))
.pipe(fs.createWriteStream('out.txt'))
.on('finish', () => doSomethingSpecial())
```
Or object streams:
```js
const all = []
fs.createReadStream('data.csv')
.pipe(csv2())
.pipe(through2.obj(function (chunk, enc, callback) {
const data = {
name : chunk[0]
, address : chunk[3]
, phone : chunk[10]
}
this.push(data)
callback()
}))
.on('data', (data) => {
all.push(data)
})
.on('end', () => {
doSomethingSpecial(all)
})
```
Note that `through2.obj(fn)` is a convenience wrapper around `through2({ objectMode: true }, fn)`.
## Do you need this?
Since Node.js introduced [Simplified Stream Construction](https://nodejs.org/api/stream.html#stream_simplified_construction), many uses of **through2** have become redundant. Consider whether you really need to use **through2** or just want to use the `'readable-stream'` package, or the core `'stream'` package (which is derived from `'readable-stream'`):
```js
const { Transform } = require('readable-stream')
const transformer = new Transform({
transform(chunk, enc, callback) {
// ...
}
})
```
## API
<b><code>through2([ options, ] [ transformFunction ] [, flushFunction ])</code></b>
Consult the **[stream.Transform](https://nodejs.org/docs/latest/api/stream.html#stream_class_stream_transform)** documentation for the exact rules of the `transformFunction` (i.e. `this._transform`) and the optional `flushFunction` (i.e. `this._flush`).
### options
The options argument is optional and is passed straight through to `stream.Transform`. So you can use `objectMode:true` if you are processing non-binary streams (or just use `through2.obj()`).
The `options` argument is first, unlike standard convention, because if I'm passing in an anonymous function then I'd prefer for the options argument to not get lost at the end of the call:
```js
fs.createReadStream('/tmp/important.dat')
.pipe(through2({ objectMode: true, allowHalfOpen: false },
(chunk, enc, cb) => {
cb(null, 'wut?') // note we can use the second argument on the callback
// to provide data as an alternative to this.push('wut?')
}
))
.pipe(fs.createWriteStream('/tmp/wut.txt'))
```
### transformFunction
The `transformFunction` must have the following signature: `function (chunk, encoding, callback) {}`. A minimal implementation should call the `callback` function to indicate that the transformation is done, even if that transformation means discarding the chunk.
To queue a new chunk, call `this.push(chunk)`&mdash;this can be called as many times as required before the `callback()` if you have multiple pieces to send on.
Alternatively, you may use `callback(err, chunk)` as shorthand for emitting a single chunk or an error.
If you **do not provide a `transformFunction`** then you will get a simple pass-through stream.
### flushFunction
The optional `flushFunction` is provided as the last argument (2nd or 3rd, depending on whether you've supplied options) is called just prior to the stream ending. Can be used to finish up any processing that may be in progress.
```js
fs.createReadStream('/tmp/important.dat')
.pipe(through2(
(chunk, enc, cb) => cb(null, chunk), // transform is a noop
function (cb) { // flush function
this.push('tacking on an extra buffer to the end');
cb();
}
))
.pipe(fs.createWriteStream('/tmp/wut.txt'));
```
<b><code>through2.ctor([ options, ] transformFunction[, flushFunction ])</code></b>
Instead of returning a `stream.Transform` instance, `through2.ctor()` returns a **constructor** for a custom Transform. This is useful when you want to use the same transform logic in multiple instances.
```js
const FToC = through2.ctor({objectMode: true}, function (record, encoding, callback) {
if (record.temp != null && record.unit == "F") {
record.temp = ( ( record.temp - 32 ) * 5 ) / 9
record.unit = "C"
}
this.push(record)
callback()
})
// Create instances of FToC like so:
const converter = new FToC()
// Or:
const converter = FToC()
// Or specify/override options when you instantiate, if you prefer:
const converter = FToC({objectMode: true})
```
## License
**through2** is Copyright &copy; Rod Vagg and additional contributors and licensed under the MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE file for more details.

View File

@@ -0,0 +1,38 @@
{
"name": "through2",
"version": "4.0.2",
"description": "A tiny wrapper around Node.js streams.Transform (Streams2/3) to avoid explicit subclassing noise",
"main": "through2.js",
"scripts": {
"test:node": "hundreds mocha test/test.js",
"test:browser": "node -e 'process.exit(process.version.startsWith(\"v8.\") ? 0 : 1)' || polendina --cleanup --runner=mocha test/test.js",
"test": "npm run lint && npm run test:node && npm run test:browser",
"lint": "standard",
"coverage": "c8 --reporter=text --reporter=html mocha test/test.js && npx st -d coverage -p 8888"
},
"repository": {
"type": "git",
"url": "https://github.com/rvagg/through2.git"
},
"keywords": [
"stream",
"streams2",
"through",
"transform"
],
"author": "Rod Vagg <r@va.gg> (https://github.com/rvagg)",
"license": "MIT",
"dependencies": {
"readable-stream": "3"
},
"devDependencies": {
"bl": "^4.0.2",
"buffer": "^5.6.0",
"chai": "^4.2.0",
"hundreds": "~0.0.7",
"mocha": "^7.2.0",
"polendina": "^1.0.0",
"standard": "^14.3.4",
"stream-spigot": "^3.0.6"
}
}

View File

@@ -0,0 +1,83 @@
const { Transform } = require('readable-stream')
function inherits (fn, sup) {
fn.super_ = sup
fn.prototype = Object.create(sup.prototype, {
constructor: { value: fn, enumerable: false, writable: true, configurable: true }
})
}
// create a new export function, used by both the main export and
// the .ctor export, contains common logic for dealing with arguments
function through2 (construct) {
return (options, transform, flush) => {
if (typeof options === 'function') {
flush = transform
transform = options
options = {}
}
if (typeof transform !== 'function') {
// noop
transform = (chunk, enc, cb) => cb(null, chunk)
}
if (typeof flush !== 'function') {
flush = null
}
return construct(options, transform, flush)
}
}
// main export, just make me a transform stream!
const make = through2((options, transform, flush) => {
const t2 = new Transform(options)
t2._transform = transform
if (flush) {
t2._flush = flush
}
return t2
})
// make me a reusable prototype that I can `new`, or implicitly `new`
// with a constructor call
const ctor = through2((options, transform, flush) => {
function Through2 (override) {
if (!(this instanceof Through2)) {
return new Through2(override)
}
this.options = Object.assign({}, options, override)
Transform.call(this, this.options)
this._transform = transform
if (flush) {
this._flush = flush
}
}
inherits(Through2, Transform)
return Through2
})
const obj = through2(function (options, transform, flush) {
const t2 = new Transform(Object.assign({ objectMode: true, highWaterMark: 16 }, options))
t2._transform = transform
if (flush) {
t2._flush = flush
}
return t2
})
module.exports = make
module.exports.ctor = ctor
module.exports.obj = obj

150
server/node_modules/get-it/package.json generated vendored Normal file
View File

@@ -0,0 +1,150 @@
{
"name": "get-it",
"version": "8.6.8",
"description": "Generic HTTP request library for node, browsers and workers",
"keywords": [
"request",
"http",
"fetch"
],
"homepage": "https://github.com/sanity-io/get-it#readme",
"bugs": {
"url": "https://github.com/sanity-io/get-it/issues"
},
"repository": {
"type": "git",
"url": "git+https://github.com/sanity-io/get-it.git"
},
"license": "MIT",
"author": "Sanity.io <hello@sanity.io>",
"sideEffects": false,
"type": "module",
"exports": {
".": {
"source": "./src/index.ts",
"browser": {
"source": "./src/index.browser.ts",
"import": "./dist/index.browser.js",
"require": "./dist/index.browser.cjs"
},
"react-native": {
"import": "./dist/index.browser.js",
"require": "./dist/index.browser.cjs"
},
"react-server": "./dist/index.react-server.js",
"bun": "./dist/index.browser.js",
"deno": "./dist/index.browser.js",
"edge-light": "./dist/index.browser.js",
"worker": "./dist/index.browser.js",
"sanity-function": "./dist/index.browser.js",
"import": "./dist/index.js",
"require": "./dist/index.cjs",
"default": "./dist/index.js"
},
"./middleware": {
"source": "./src/middleware.ts",
"browser": {
"source": "./src/middleware.browser.ts",
"import": "./dist/middleware.browser.js",
"require": "./dist/middleware.browser.cjs"
},
"react-native": {
"import": "./dist/middleware.browser.js",
"require": "./dist/middleware.browser.cjs"
},
"react-server": "./dist/middleware.browser.js",
"bun": "./dist/middleware.browser.js",
"deno": "./dist/middleware.browser.js",
"edge-light": "./dist/middleware.browser.js",
"worker": "./dist/middleware.browser.js",
"sanity-function": "./dist/middleware.browser.js",
"import": "./dist/middleware.js",
"require": "./dist/middleware.cjs",
"default": "./dist/middleware.js"
},
"./package.json": "./package.json"
},
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"browser": {
"./dist/index.cjs": "./dist/index.browser.cjs",
"./dist/index.js": "./dist/index.browser.js",
"./dist/middleware.cjs": "./dist/middleware.browser.cjs",
"./dist/middleware.js": "./dist/middleware.browser.js"
},
"types": "./dist/index.d.ts",
"typesVersions": {
"*": {
"middleware": [
"./dist/middleware.d.ts"
]
}
},
"files": [
"dist",
"src",
"middleware.js"
],
"scripts": {
"build": "pkg build --strict --check --clean",
"coverage": "vitest run --coverage",
"lint": "eslint . --ext .cjs,.js,.ts --report-unused-disable-directives",
"prepublishOnly": "npm run build",
"test": "vitest",
"test:browser": "npm test -- --config ./vitest.browser.config.ts --dom",
"test:edge-runtime": "npm test -- --config ./vitest.edge.config.ts",
"test:esm": "(cd test-esm && node --test) | faucet",
"test:esm:browser": "node -C browser --test test-esm/test.mjs | faucet",
"test:esm:deno": "deno test --allow-read --allow-net --allow-env --import-map=test-deno/import_map.json test-deno",
"test:react-server": "npm test -- --config ./vitest.react-server.config.ts",
"type-check": "tsc --noEmit"
},
"browserslist": "extends @sanity/browserslist-config",
"prettier": "@sanity/prettier-config",
"dependencies": {
"@types/follow-redirects": "^1.14.4",
"decompress-response": "^7.0.0",
"follow-redirects": "^1.15.9",
"is-retry-allowed": "^2.2.0",
"through2": "^4.0.2",
"tunnel-agent": "^0.6.0"
},
"devDependencies": {
"@edge-runtime/vm": "^5.0.0",
"@sanity/pkg-utils": "^7.2.2",
"@sanity/prettier-config": "^1.0.3",
"@sanity/semantic-release-preset": "^5.0.0",
"@types/bun": "^1.1.16",
"@types/debug": "^4.1.12",
"@types/node": "^20.8.8",
"@types/through2": "^2.0.41",
"@types/zen-observable": "^0.8.7",
"@typescript-eslint/eslint-plugin": "^8.31.0",
"@typescript-eslint/parser": "^8.31.0",
"@vitest/coverage-v8": "^3.1.2",
"debug": "4.4.0",
"eslint": "^8.57.1",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-prettier": "^5.2.1",
"eslint-plugin-simple-import-sort": "^12.1.1",
"faucet": "^0.0.4",
"get-uri": "^6.0.4",
"happy-dom": "^17.4.4",
"ls-engines": "^0.9.3",
"node-fetch": "^2.6.7",
"parse-headers": "2.0.5",
"prettier": "^3.4.2",
"semantic-release": "^24.2.1",
"typescript": "5.8.3",
"vite": "^6.3.3",
"vitest": "^3.1.2",
"zen-observable": "^0.10.0"
},
"packageManager": "npm@10.8.2",
"engines": {
"node": ">=14.0.0"
},
"publishConfig": {
"access": "public"
}
}

162
server/node_modules/get-it/src/createRequester.ts generated vendored Normal file
View File

@@ -0,0 +1,162 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import {processOptions} from './middleware/defaultOptionsProcessor'
import {validateOptions} from './middleware/defaultOptionsValidator'
import type {
HttpContext,
HttpRequest,
HttpRequestOngoing,
Middleware,
MiddlewareChannels,
MiddlewareHooks,
MiddlewareReducer,
MiddlewareResponse,
Middlewares,
Requester,
RequestOptions,
} from './types'
import {middlewareReducer} from './util/middlewareReducer'
import {createPubSub} from './util/pubsub'
const channelNames = [
'request',
'response',
'progress',
'error',
'abort',
] satisfies (keyof MiddlewareChannels)[]
const middlehooks = [
'processOptions',
'validateOptions',
'interceptRequest',
'finalizeOptions',
'onRequest',
'onResponse',
'onError',
'onReturn',
'onHeaders',
] satisfies (keyof MiddlewareHooks)[]
/** @public */
export function createRequester(initMiddleware: Middlewares, httpRequest: HttpRequest): Requester {
const loadedMiddleware: Middlewares = []
const middleware: MiddlewareReducer = middlehooks.reduce(
(ware, name) => {
ware[name] = ware[name] || []
return ware
},
{
processOptions: [processOptions],
validateOptions: [validateOptions],
} as any,
)
function request(opts: RequestOptions | string) {
const onResponse = (reqErr: Error | null, res: MiddlewareResponse, ctx: HttpContext) => {
let error = reqErr
let response: MiddlewareResponse | null = res
// We're processing non-errors first, in case a middleware converts the
// response into an error (for instance, status >= 400 == HttpError)
if (!error) {
try {
response = applyMiddleware('onResponse', res, ctx)
} catch (err: any) {
response = null
error = err
}
}
// Apply error middleware - if middleware return the same (or a different) error,
// publish as an error event. If we *don't* return an error, assume it has been handled
error = error && applyMiddleware('onError', error, ctx)
// Figure out if we should publish on error/response channels
if (error) {
channels.error.publish(error)
} else if (response) {
channels.response.publish(response)
}
}
const channels: MiddlewareChannels = channelNames.reduce((target, name) => {
target[name] = createPubSub() as MiddlewareChannels[typeof name]
return target
}, {} as any)
// Prepare a middleware reducer that can be reused throughout the lifecycle
const applyMiddleware = middlewareReducer(middleware)
// Parse the passed options
const options = applyMiddleware('processOptions', opts as RequestOptions)
// Validate the options
applyMiddleware('validateOptions', options)
// Build a context object we can pass to child handlers
const context = {options, channels, applyMiddleware}
// We need to hold a reference to the current, ongoing request,
// in order to allow cancellation. In the case of the retry middleware,
// a new request might be triggered
let ongoingRequest: HttpRequestOngoing | undefined
const unsubscribe = channels.request.subscribe((ctx) => {
// Let request adapters (node/browser) perform the actual request
ongoingRequest = httpRequest(ctx, (err, res) => onResponse(err, res!, ctx))
})
// If we abort the request, prevent further requests from happening,
// and be sure to cancel any ongoing request (obviously)
channels.abort.subscribe(() => {
unsubscribe()
if (ongoingRequest) {
ongoingRequest.abort()
}
})
// See if any middleware wants to modify the return value - for instance
// the promise or observable middlewares
const returnValue = applyMiddleware('onReturn', channels, context)
// If return value has been modified by a middleware, we expect the middleware
// to publish on the 'request' channel. If it hasn't been modified, we want to
// trigger it right away
if (returnValue === channels) {
channels.request.publish(context)
}
return returnValue
}
request.use = function use(newMiddleware: Middleware) {
if (!newMiddleware) {
throw new Error('Tried to add middleware that resolved to falsey value')
}
if (typeof newMiddleware === 'function') {
throw new Error(
'Tried to add middleware that was a function. It probably expects you to pass options to it.',
)
}
if (newMiddleware.onReturn && middleware.onReturn.length > 0) {
throw new Error(
'Tried to add new middleware with `onReturn` handler, but another handler has already been registered for this event',
)
}
middlehooks.forEach((key) => {
if (newMiddleware[key]) {
middleware[key].push(newMiddleware[key] as any)
}
})
loadedMiddleware.push(newMiddleware)
return request
}
request.clone = () => createRequester(loadedMiddleware, httpRequest)
initMiddleware.forEach(request.use)
return request
}

17
server/node_modules/get-it/src/index.browser.ts generated vendored Normal file
View File

@@ -0,0 +1,17 @@
import {createRequester} from './createRequester'
import {httpRequester} from './request/browser-request'
import type {ExportEnv, HttpRequest, Middlewares, Requester} from './types'
export type * from './types'
/** @public */
export const getIt = (
initMiddleware: Middlewares = [],
httpRequest: HttpRequest = httpRequester,
): Requester => createRequester(initMiddleware, httpRequest)
/** @public */
export const environment = 'browser' satisfies ExportEnv
/** @public */
export {adapter} from './request/browser-request'

6
server/node_modules/get-it/src/index.react-server.ts generated vendored Normal file
View File

@@ -0,0 +1,6 @@
import type {ExportEnv} from './types'
export * from './index.browser'
/** @public */
export const environment = 'react-server' satisfies ExportEnv

17
server/node_modules/get-it/src/index.ts generated vendored Normal file
View File

@@ -0,0 +1,17 @@
import {createRequester} from './createRequester'
import {httpRequester} from './request/node-request'
import type {ExportEnv, HttpRequest, Middlewares, Requester} from './types'
export type * from './types'
/** @public */
export const getIt = (
initMiddleware: Middlewares = [],
httpRequest: HttpRequest = httpRequester,
): Requester => createRequester(initMiddleware, httpRequest)
/** @public */
export const environment: ExportEnv = 'node'
/** @public */
export {adapter} from './request/node-request'

22
server/node_modules/get-it/src/middleware.browser.ts generated vendored Normal file
View File

@@ -0,0 +1,22 @@
export * from './middleware/agent/browser-agent'
export * from './middleware/base'
export * from './middleware/debug'
export * from './middleware/defaultOptionsProcessor'
export * from './middleware/defaultOptionsValidator'
export * from './middleware/headers'
export * from './middleware/httpErrors'
export * from './middleware/injectResponse'
export * from './middleware/jsonRequest'
export * from './middleware/jsonResponse'
export * from './middleware/mtls'
export * from './middleware/observable'
export * from './middleware/progress/browser-progress'
export * from './middleware/promise'
export * from './middleware/proxy'
export * from './middleware/retry/browser-retry'
export * from './middleware/urlEncoded'
import {agent} from './middleware/agent/browser-agent'
import {buildKeepAlive} from './middleware/keepAlive'
/** @public */
export const keepAlive = buildKeepAlive(agent)

22
server/node_modules/get-it/src/middleware.ts generated vendored Normal file
View File

@@ -0,0 +1,22 @@
export * from './middleware/agent/node-agent'
export * from './middleware/base'
export * from './middleware/debug'
export * from './middleware/defaultOptionsProcessor'
export * from './middleware/defaultOptionsValidator'
export * from './middleware/headers'
export * from './middleware/httpErrors'
export * from './middleware/injectResponse'
export * from './middleware/jsonRequest'
export * from './middleware/jsonResponse'
export * from './middleware/mtls'
export * from './middleware/observable'
export * from './middleware/progress/node-progress'
export * from './middleware/promise'
export * from './middleware/proxy'
export * from './middleware/retry/node-retry'
export * from './middleware/urlEncoded'
import {agent} from './middleware/agent/node-agent'
import {buildKeepAlive} from './middleware/keepAlive'
/** @public */
export const keepAlive = buildKeepAlive(agent)

View File

@@ -0,0 +1,10 @@
/**
* This middleware only has an effect in Node.js.
* @public
*/
export function agent(
// eslint-disable-next-line @typescript-eslint/no-unused-vars
_opts?: any,
): any {
return {}
}

View File

@@ -0,0 +1,33 @@
import {Agent as HttpAgent, type AgentOptions} from 'http'
import {Agent as HttpsAgent} from 'https'
import {type Middleware} from 'get-it'
const isHttpsProto = /^https:/i
/**
* Constructs a http.Agent and uses it for all requests.
* This can be used to override settings such as `maxSockets`, `maxTotalSockets` (to limit concurrency) or change the `timeout`.
* @public
*/
export function agent(opts?: AgentOptions) {
const httpAgent = new HttpAgent(opts)
const httpsAgent = new HttpsAgent(opts)
const agents = {http: httpAgent, https: httpsAgent}
return {
finalizeOptions: (options: any) => {
if (options.agent) {
return options
}
// When maxRedirects>0 we're using the follow-redirects package and this supports the `agents` option.
if (options.maxRedirects > 0) {
return {...options, agents}
}
// ... otherwise we'll have to detect which agent to use:
const isHttps = isHttpsProto.test(options.href || options.protocol)
return {...options, agent: isHttps ? httpsAgent : httpAgent}
},
} satisfies Middleware
}

19
server/node_modules/get-it/src/middleware/base.ts generated vendored Normal file
View File

@@ -0,0 +1,19 @@
import type {Middleware} from 'get-it'
const leadingSlash = /^\//
const trailingSlash = /\/$/
/** @public */
export function base(baseUrl: string) {
const baseUri = baseUrl.replace(trailingSlash, '')
return {
processOptions: (options) => {
if (/^https?:\/\//i.test(options.url)) {
return options // Already prefixed
}
const url = [baseUri, options.url.replace(leadingSlash, '')].join('/')
return Object.assign({}, options, {url})
},
} satisfies Middleware
}

103
server/node_modules/get-it/src/middleware/debug.ts generated vendored Normal file
View File

@@ -0,0 +1,103 @@
import debugIt from 'debug'
import type {Middleware} from 'get-it'
const SENSITIVE_HEADERS = ['cookie', 'authorization']
const hasOwn = Object.prototype.hasOwnProperty
const redactKeys = (source: any, redacted: any) => {
const target: any = {}
for (const key in source) {
if (hasOwn.call(source, key)) {
target[key] = redacted.indexOf(key.toLowerCase()) > -1 ? '<redacted>' : source[key]
}
}
return target
}
/** @public */
export function debug(opts: any = {}) {
const verbose = opts.verbose
const namespace = opts.namespace || 'get-it'
const defaultLogger = debugIt(namespace)
const log = opts.log || defaultLogger
const shortCircuit = log === defaultLogger && !debugIt.enabled(namespace)
let requestId = 0
return {
processOptions: (options) => {
options.debug = log
options.requestId = options.requestId || ++requestId
return options
},
onRequest: (event) => {
// Short-circuit if not enabled, to save some CPU cycles with formatting stuff
if (shortCircuit || !event) {
return event
}
const options = event.options
log('[%s] HTTP %s %s', options.requestId, options.method, options.url)
if (verbose && options.body && typeof options.body === 'string') {
log('[%s] Request body: %s', options.requestId, options.body)
}
if (verbose && options.headers) {
const headers =
opts.redactSensitiveHeaders === false
? options.headers
: redactKeys(options.headers, SENSITIVE_HEADERS)
log('[%s] Request headers: %s', options.requestId, JSON.stringify(headers, null, 2))
}
return event
},
onResponse: (res, context) => {
// Short-circuit if not enabled, to save some CPU cycles with formatting stuff
if (shortCircuit || !res) {
return res
}
const reqId = context.options.requestId
log('[%s] Response code: %s %s', reqId, res.statusCode, res.statusMessage)
if (verbose && res.body) {
log('[%s] Response body: %s', reqId, stringifyBody(res))
}
return res
},
onError: (err, context) => {
const reqId = context.options.requestId
if (!err) {
log('[%s] Error encountered, but handled by an earlier middleware', reqId)
return err
}
log('[%s] ERROR: %s', reqId, err.message)
return err
},
} satisfies Middleware
}
function stringifyBody(res: any) {
const contentType = (res.headers['content-type'] || '').toLowerCase()
const isJson = contentType.indexOf('application/json') !== -1
return isJson ? tryFormat(res.body) : res.body
}
// Attempt pretty-formatting JSON
function tryFormat(body: any) {
try {
const parsed = typeof body === 'string' ? JSON.parse(body) : body
return JSON.stringify(parsed, null, 2)
} catch {
return body
}
}

View File

@@ -0,0 +1,107 @@
import type {MiddlewareHooks, RequestOptions} from 'get-it'
const isReactNative = typeof navigator === 'undefined' ? false : navigator.product === 'ReactNative'
const defaultOptions = {timeout: isReactNative ? 60000 : 120000} satisfies Partial<RequestOptions>
/** @public */
export const processOptions = function processOptions(opts) {
const options = {
...defaultOptions,
...(typeof opts === 'string' ? {url: opts} : opts),
} satisfies RequestOptions
// Normalize timeouts
options.timeout = normalizeTimeout(options.timeout)
// Shallow-merge (override) existing query params
if (options.query) {
const {url, searchParams} = splitUrl(options.url)
for (const [key, value] of Object.entries(options.query)) {
if (value !== undefined) {
if (Array.isArray(value)) {
for (const v of value) {
searchParams.append(key, v as string)
}
} else {
searchParams.append(key, value as string)
}
}
// Merge back params into url
const search = searchParams.toString()
if (search) {
options.url = `${url}?${search}`
}
}
}
// Implicit POST if we have not specified a method but have a body
options.method =
options.body && !options.method ? 'POST' : (options.method || 'GET').toUpperCase()
return options
} satisfies MiddlewareHooks['processOptions']
/**
* Given a string URL, extracts the query string and URL from each other, and returns them.
* Note that we cannot use the `URL` constructor because of old React Native versions which are
* majorly broken and returns incorrect results:
*
* (`new URL('http://foo/?a=b').toString()` == 'http://foo/?a=b/')
*/
function splitUrl(url: string): {url: string; searchParams: URLSearchParams} {
const qIndex = url.indexOf('?')
if (qIndex === -1) {
return {url, searchParams: new URLSearchParams()}
}
const base = url.slice(0, qIndex)
const qs = url.slice(qIndex + 1)
// React Native's URL and URLSearchParams are broken, so passing a string to URLSearchParams
// does not work, leading to an empty query string. For other environments, this should be enough
if (!isReactNative) {
return {url: base, searchParams: new URLSearchParams(qs)}
}
// Sanity-check; we do not know of any environment where this is the case,
// but if it is, we should not proceed without giving a descriptive error
if (typeof decodeURIComponent !== 'function') {
throw new Error(
'Broken `URLSearchParams` implementation, and `decodeURIComponent` is not defined',
)
}
const params = new URLSearchParams()
for (const pair of qs.split('&')) {
const [key, value] = pair.split('=')
if (key) {
params.append(decodeQueryParam(key), decodeQueryParam(value || ''))
}
}
return {url: base, searchParams: params}
}
function decodeQueryParam(value: string): string {
return decodeURIComponent(value.replace(/\+/g, ' '))
}
function normalizeTimeout(time: RequestOptions['timeout']) {
if (time === false || time === 0) {
return false
}
if (time.connect || time.socket) {
return time
}
const delay = Number(time)
if (isNaN(delay)) {
return normalizeTimeout(defaultOptions.timeout)
}
return {connect: delay, socket: delay}
}

View File

@@ -0,0 +1,10 @@
import type {MiddlewareHooks} from 'get-it'
const validUrl = /^https?:\/\//i
/** @public */
export const validateOptions = function validateOptions(options) {
if (!validUrl.test(options.url)) {
throw new Error(`"${options.url}" is not a valid URL`)
}
} satisfies MiddlewareHooks['validateOptions']

15
server/node_modules/get-it/src/middleware/headers.ts generated vendored Normal file
View File

@@ -0,0 +1,15 @@
import type {Middleware} from 'get-it'
/** @public */
export function headers(_headers: any, opts: any = {}) {
return {
processOptions: (options) => {
const existing = options.headers || {}
options.headers = opts.override
? Object.assign({}, existing, _headers)
: Object.assign({}, _headers, existing)
return options
},
} satisfies Middleware
}

View File

@@ -0,0 +1,30 @@
import type {Middleware} from 'get-it'
class HttpError extends Error {
response: any
request: any
constructor(res: any, ctx: any) {
super()
const truncatedUrl = res.url.length > 400 ? `${res.url.slice(0, 399)}` : res.url
let msg = `${res.method}-request to ${truncatedUrl} resulted in `
msg += `HTTP ${res.statusCode} ${res.statusMessage}`
this.message = msg.trim()
this.response = res
this.request = ctx.options
}
}
/** @public */
export function httpErrors() {
return {
onResponse: (res, ctx) => {
const isHttpError = res.statusCode >= 400
if (!isHttpError) {
return res
}
throw new HttpError(res, ctx)
},
} satisfies Middleware
}

View File

@@ -0,0 +1,37 @@
import type {Middleware, MiddlewareHooks, MiddlewareResponse} from 'get-it'
/** @public */
export function injectResponse(
opts: {
inject: (
event: Parameters<MiddlewareHooks['interceptRequest']>[1],
prevValue: Parameters<MiddlewareHooks['interceptRequest']>[0],
) => Partial<MiddlewareResponse | undefined | void>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} = {} as any,
) {
if (typeof opts.inject !== 'function') {
throw new Error('`injectResponse` middleware requires a `inject` function')
}
const inject = function inject(prevValue, event) {
const response = opts.inject(event, prevValue)
if (!response) {
return prevValue
}
// Merge defaults so we don't have to provide the most basic of details unless we want to
const options = event.context.options
return {
body: '',
url: options.url,
method: options.method!,
headers: {},
statusCode: 200,
statusMessage: 'OK',
...response,
} satisfies MiddlewareResponse
} satisfies Middleware['interceptRequest']
return {interceptRequest: inject} satisfies Middleware
}

View File

@@ -0,0 +1,35 @@
import type {Middleware} from 'get-it'
import {isBuffer} from '../util/isBuffer'
import {isPlainObject} from '../util/isPlainObject'
const serializeTypes = ['boolean', 'string', 'number']
/** @public */
export function jsonRequest() {
return {
processOptions: (options) => {
const body = options.body
if (!body) {
return options
}
const isStream = typeof body.pipe === 'function'
const shouldSerialize =
!isStream &&
!isBuffer(body) &&
(serializeTypes.indexOf(typeof body) !== -1 || Array.isArray(body) || isPlainObject(body))
if (!shouldSerialize) {
return options
}
return Object.assign({}, options, {
body: JSON.stringify(options.body),
headers: Object.assign({}, options.headers, {
'Content-Type': 'application/json',
}),
})
},
} satisfies Middleware
}

View File

@@ -0,0 +1,30 @@
import type {Middleware} from 'get-it'
/** @public */
export function jsonResponse(opts?: any) {
return {
onResponse: (response) => {
const contentType = response.headers['content-type'] || ''
const shouldDecode = (opts && opts.force) || contentType.indexOf('application/json') !== -1
if (!response.body || !contentType || !shouldDecode) {
return response
}
return Object.assign({}, response, {body: tryParse(response.body)})
},
processOptions: (options) =>
Object.assign({}, options, {
headers: Object.assign({Accept: 'application/json'}, options.headers),
}),
} satisfies Middleware
function tryParse(body: any) {
try {
return JSON.parse(body)
} catch (err: any) {
err.message = `Failed to parsed response body as JSON: ${err.message}`
throw err
}
}
}

55
server/node_modules/get-it/src/middleware/keepAlive.ts generated vendored Normal file
View File

@@ -0,0 +1,55 @@
import type {AgentOptions} from 'http'
import type {Middleware} from 'get-it'
import {NodeRequestError} from '../request/node-request'
type KeepAliveOptions = {
ms?: number
maxFree?: number
/**
How many times to retry in case of ECONNRESET error. Default: 3
*/
maxRetries?: number
}
export function buildKeepAlive(agent: (opts: AgentOptions) => Pick<Middleware, 'finalizeOptions'>) {
return function keepAlive(config: KeepAliveOptions = {}): any {
const {maxRetries = 3, ms = 1000, maxFree = 256} = config
const {finalizeOptions} = agent({
keepAlive: true,
keepAliveMsecs: ms,
maxFreeSockets: maxFree,
})
return {
finalizeOptions,
onError: (err, context) => {
// When sending request through a keep-alive enabled agent, the underlying socket might be reused. But if server closes connection at unfortunate time, client may run into a 'ECONNRESET' error.
// We retry three times in case of ECONNRESET error.
// https://nodejs.org/docs/latest-v20.x/api/http.html#requestreusedsocket
if (
(context.options.method === 'GET' || context.options.method === 'POST') &&
err instanceof NodeRequestError &&
err.code === 'ECONNRESET' &&
err.request.reusedSocket
) {
const attemptNumber = context.options.attemptNumber || 0
if (attemptNumber < maxRetries) {
// Create a new context with an increased attempt number, so we can exit if we reach a limit
const newContext = Object.assign({}, context, {
options: Object.assign({}, context.options, {attemptNumber: attemptNumber + 1}),
})
// If this is a reused socket we retry immediately
setImmediate(() => context.channels.request.publish(newContext))
return null
}
}
return err
},
} satisfies Middleware
}
}

31
server/node_modules/get-it/src/middleware/mtls.ts generated vendored Normal file
View File

@@ -0,0 +1,31 @@
import type {Middleware} from 'get-it'
import {isBrowserOptions} from '../util/isBrowserOptions'
/** @public */
export function mtls(config: any = {}) {
if (!config.ca) {
throw new Error('Required mtls option "ca" is missing')
}
if (!config.cert) {
throw new Error('Required mtls option "cert" is missing')
}
if (!config.key) {
throw new Error('Required mtls option "key" is missing')
}
return {
finalizeOptions: (options) => {
if (isBrowserOptions(options)) {
return options
}
const mtlsOpts = {
cert: config.cert,
key: config.key,
ca: config.ca,
}
return Object.assign({}, options, mtlsOpts)
},
} satisfies Middleware
}

View File

@@ -0,0 +1,36 @@
import type {Middleware} from 'get-it'
import global from '../util/global'
/** @public */
export function observable(
opts: {
implementation?: any
} = {},
) {
const Observable =
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- @TODO consider dropping checking for a global Observable since it's not on a standards track
opts.implementation || (global as any).Observable
if (!Observable) {
throw new Error(
'`Observable` is not available in global scope, and no implementation was passed',
)
}
return {
onReturn: (channels, context) =>
new Observable((observer: any) => {
channels.error.subscribe((err) => observer.error(err))
channels.progress.subscribe((event) =>
observer.next(Object.assign({type: 'progress'}, event)),
)
channels.response.subscribe((response) => {
observer.next(Object.assign({type: 'response'}, response))
observer.complete()
})
channels.request.publish(context)
return () => channels.abort.publish()
}),
} satisfies Middleware
}

View File

@@ -0,0 +1,36 @@
import type {Middleware} from 'get-it'
/** @public */
export function progress() {
return {
onRequest: (evt) => {
if (evt.adapter !== 'xhr') {
return
}
const xhr = evt.request
const context = evt.context
if ('upload' in xhr && 'onprogress' in xhr.upload) {
xhr.upload.onprogress = handleProgress('upload')
}
if ('onprogress' in xhr) {
xhr.onprogress = handleProgress('download')
}
function handleProgress(stage: 'download' | 'upload') {
return (event: any) => {
const percent = event.lengthComputable ? (event.loaded / event.total) * 100 : -1
context.channels.progress.publish({
stage,
percent,
total: event.total,
loaded: event.loaded,
lengthComputable: event.lengthComputable,
})
}
}
},
} satisfies Middleware
}

View File

@@ -0,0 +1,47 @@
import type {Middleware} from 'get-it'
import {type Progress, progressStream} from '../../util/progress-stream'
function normalizer(stage: 'download' | 'upload') {
return (prog: Pick<Progress, 'percentage' | 'length' | 'transferred'>) => ({
stage,
percent: prog.percentage,
total: prog.length,
loaded: prog.transferred,
lengthComputable: !(prog.length === 0 && prog.percentage === 0),
})
}
/** @public */
export function progress() {
let didEmitUpload = false
const onDownload = normalizer('download')
const onUpload = normalizer('upload')
return {
onHeaders: (response, evt) => {
const stream = progressStream({time: 32})
stream.on('progress', (prog) => evt.context.channels.progress.publish(onDownload(prog)))
return response.pipe(stream)
},
onRequest: (evt) => {
if (!evt.progress) {
return
}
evt.progress.on('progress', (prog: Progress) => {
didEmitUpload = true
evt.context.channels.progress.publish(onUpload(prog))
})
},
onResponse: (res, evt) => {
if (!didEmitUpload && typeof evt.options.body !== 'undefined') {
evt.channels.progress.publish(onUpload({length: 0, transferred: 0, percentage: 100}))
}
return res
},
} satisfies Middleware
}

104
server/node_modules/get-it/src/middleware/promise.ts generated vendored Normal file
View File

@@ -0,0 +1,104 @@
import type {Middleware} from 'get-it'
/** @public */
export const promise = (
options: {onlyBody?: boolean; implementation?: PromiseConstructor} = {},
) => {
const PromiseImplementation = options.implementation || Promise
if (!PromiseImplementation) {
throw new Error('`Promise` is not available in global scope, and no implementation was passed')
}
return {
onReturn: (channels, context) =>
new PromiseImplementation((resolve, reject) => {
const cancel = context.options.cancelToken
if (cancel) {
cancel.promise.then((reason: any) => {
channels.abort.publish(reason)
reject(reason)
})
}
channels.error.subscribe(reject)
channels.response.subscribe((response) => {
resolve(options.onlyBody ? (response as any).body : response)
})
// Wait until next tick in case cancel has been performed
setTimeout(() => {
try {
channels.request.publish(context)
} catch (err) {
reject(err)
}
}, 0)
}),
} satisfies Middleware
}
/**
* The cancel token API is based on the [cancelable promises proposal](https://github.com/tc39/proposal-cancelable-promises), which is currently at Stage 1.
*
* Code shamelessly stolen/borrowed from MIT-licensed [axios](https://github.com/mzabriskie/axios). Thanks to [Nick Uraltsev](https://github.com/nickuraltsev), [Matt Zabriskie](https://github.com/mzabriskie) and the other contributors of that project!
*/
/** @public */
export class Cancel {
__CANCEL__ = true
message: string | undefined
constructor(message: string | undefined) {
this.message = message
}
toString() {
return `Cancel${this.message ? `: ${this.message}` : ''}`
}
}
/** @public */
export class CancelToken {
promise: Promise<any>
reason?: Cancel
constructor(executor: (cb: (message?: string) => void) => void) {
if (typeof executor !== 'function') {
throw new TypeError('executor must be a function.')
}
let resolvePromise: any = null
this.promise = new Promise((resolve) => {
resolvePromise = resolve
})
executor((message?: string) => {
if (this.reason) {
// Cancellation has already been requested
return
}
this.reason = new Cancel(message)
resolvePromise(this.reason)
})
}
static source = () => {
let cancel: (message?: string) => void
const token = new CancelToken((can) => {
cancel = can
})
return {
token: token,
cancel: cancel!,
}
}
}
const isCancel = (value: any): value is Cancel => !!(value && value?.__CANCEL__)
promise.Cancel = Cancel
promise.CancelToken = CancelToken
promise.isCancel = isCancel

12
server/node_modules/get-it/src/middleware/proxy.ts generated vendored Normal file
View File

@@ -0,0 +1,12 @@
import type {Middleware} from 'get-it'
/** @public */
export function proxy(_proxy: any) {
if (_proxy !== false && (!_proxy || !_proxy.host)) {
throw new Error('Proxy middleware takes an object of host, port and auth properties')
}
return {
processOptions: (options) => Object.assign({proxy: _proxy}, options),
} satisfies Middleware
}

Some files were not shown because too many files have changed in this diff Show More