diff --git a/README.md b/README.md
index 07c531b..c6e6278 100644
--- a/README.md
+++ b/README.md
@@ -107,6 +107,28 @@ Default `true`.
```
+### `skip-cache-restore`
+
+Skip restoring caches at setup time while still allowing caches to be saved in the post step.
+This is useful when you want to force a clean build and publish fresh caches.
+
+Default `false`.
+
+
+ Examples
+
+ #### Build fresh caches
+
+ ```yaml
+ - uses: bazel-contrib/setup-bazel@0.19.0
+ with:
+ bazelisk-cache: true
+ disk-cache: ${{ github.workflow }}
+ repository-cache: true
+ skip-cache-restore: true
+ ```
+
+
### `disk-cache`
Enable [`disk_cache`][2] and store it on GitHub based on contents of `BUILD` files.
diff --git a/action.yml b/action.yml
index fe3ddbf..c7ca0fa 100644
--- a/action.yml
+++ b/action.yml
@@ -17,6 +17,10 @@ inputs:
description: Whether to save caches. Set to false for pull requests to allow restores but prevent saves.
required: false
default: "true"
+ skip-cache-restore:
+ description: Whether to skip restoring caches. Useful for creating fresh caches while still saving at the end.
+ required: false
+ default: "false"
cache-version:
description: Version of all caches
required: false
diff --git a/config.js b/config.js
index 2eddac2..850ba5a 100644
--- a/config.js
+++ b/config.js
@@ -6,6 +6,7 @@ import * as github from '@actions/github'
const bazeliskVersion = core.getInput('bazelisk-version')
const cacheSave = core.getBooleanInput('cache-save')
+const skipCacheRestore = core.getBooleanInput('skip-cache-restore')
const cacheVersion = core.getInput('cache-version')
const moduleRoot = core.getInput('module-root')
@@ -66,6 +67,7 @@ const repositoryCacheConfig = yaml.parse(core.getInput('repository-cache'))
const repositoryCacheEnabled = repositoryCacheConfig !== false
let repositoryCacheFiles = [
`${moduleRoot}/MODULE.bazel`,
+ `${moduleRoot}/MODULE.bazel.lock`,
`${moduleRoot}/WORKSPACE.bazel`,
`${moduleRoot}/WORKSPACE.bzlmod`,
`${moduleRoot}/WORKSPACE`
@@ -142,6 +144,7 @@ export default {
baseCacheKey,
cacheSave,
cacheRestoreTimeoutMs,
+ skipCacheRestore,
bazeliskCache: {
enabled: core.getBooleanInput('bazelisk-cache'),
files: [`${moduleRoot}/.bazelversion`],
diff --git a/dist/main/index.js b/dist/main/index.js
index 31482d6..4ed5679 100644
--- a/dist/main/index.js
+++ b/dist/main/index.js
@@ -56,7 +56,7 @@ const http = __importStar(__nccwpck_require__(8611));
const https = __importStar(__nccwpck_require__(5692));
const pm = __importStar(__nccwpck_require__(3335));
const tunnel = __importStar(__nccwpck_require__(770));
-const undici_1 = __nccwpck_require__(9231);
+const undici_1 = __nccwpck_require__(6752);
var HttpCodes;
(function (HttpCodes) {
HttpCodes[HttpCodes["OK"] = 200] = "OK";
@@ -844,95655 +844,68617 @@ class DecodedURL extends URL {
/***/ }),
-/***/ 9231:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const Client = __nccwpck_require__(2138)
-const Dispatcher = __nccwpck_require__(9784)
-const Pool = __nccwpck_require__(3959)
-const BalancedPool = __nccwpck_require__(2188)
-const Agent = __nccwpck_require__(4332)
-const ProxyAgent = __nccwpck_require__(8349)
-const EnvHttpProxyAgent = __nccwpck_require__(1630)
-const RetryAgent = __nccwpck_require__(7203)
-const errors = __nccwpck_require__(2344)
-const util = __nccwpck_require__(7375)
-const { InvalidArgumentError } = errors
-const api = __nccwpck_require__(436)
-const buildConnector = __nccwpck_require__(5005)
-const MockClient = __nccwpck_require__(9736)
-const MockAgent = __nccwpck_require__(2710)
-const MockPool = __nccwpck_require__(5157)
-const mockErrors = __nccwpck_require__(8024)
-const RetryHandler = __nccwpck_require__(3783)
-const { getGlobalDispatcher, setGlobalDispatcher } = __nccwpck_require__(1088)
-const DecoratorHandler = __nccwpck_require__(9420)
-const RedirectHandler = __nccwpck_require__(7031)
-const createRedirectInterceptor = __nccwpck_require__(6097)
-
-Object.assign(Dispatcher.prototype, api)
+/***/ 8110:
+/***/ ((__unused_webpack_module, exports) => {
-module.exports.Dispatcher = Dispatcher
-module.exports.Client = Client
-module.exports.Pool = Pool
-module.exports.BalancedPool = BalancedPool
-module.exports.Agent = Agent
-module.exports.ProxyAgent = ProxyAgent
-module.exports.EnvHttpProxyAgent = EnvHttpProxyAgent
-module.exports.RetryAgent = RetryAgent
-module.exports.RetryHandler = RetryHandler
-module.exports.DecoratorHandler = DecoratorHandler
-module.exports.RedirectHandler = RedirectHandler
-module.exports.createRedirectInterceptor = createRedirectInterceptor
-module.exports.interceptors = {
- redirect: __nccwpck_require__(5711),
- retry: __nccwpck_require__(2117),
- dump: __nccwpck_require__(5057),
- dns: __nccwpck_require__(5663)
-}
-module.exports.buildConnector = buildConnector
-module.exports.errors = errors
-module.exports.util = {
- parseHeaders: util.parseHeaders,
- headerNameToString: util.headerNameToString
-}
+Object.defineProperty(exports, "__esModule", ({ value: true }));
-function makeDispatcher (fn) {
- return (url, opts, handler) => {
- if (typeof opts === 'function') {
- handler = opts
- opts = null
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+///
+const listenersMap = new WeakMap();
+const abortedMap = new WeakMap();
+/**
+ * An aborter instance implements AbortSignal interface, can abort HTTP requests.
+ *
+ * - Call AbortSignal.none to create a new AbortSignal instance that cannot be cancelled.
+ * Use `AbortSignal.none` when you are required to pass a cancellation token but the operation
+ * cannot or will not ever be cancelled.
+ *
+ * @example
+ * Abort without timeout
+ * ```ts
+ * await doAsyncWork(AbortSignal.none);
+ * ```
+ */
+class AbortSignal {
+ constructor() {
+ /**
+ * onabort event listener.
+ */
+ this.onabort = null;
+ listenersMap.set(this, []);
+ abortedMap.set(this, false);
}
-
- if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) {
- throw new InvalidArgumentError('invalid url')
+ /**
+ * Status of whether aborted or not.
+ *
+ * @readonly
+ */
+ get aborted() {
+ if (!abortedMap.has(this)) {
+ throw new TypeError("Expected `this` to be an instance of AbortSignal.");
+ }
+ return abortedMap.get(this);
}
-
- if (opts != null && typeof opts !== 'object') {
- throw new InvalidArgumentError('invalid opts')
+ /**
+ * Creates a new AbortSignal instance that will never be aborted.
+ *
+ * @readonly
+ */
+ static get none() {
+ return new AbortSignal();
}
-
- if (opts && opts.path != null) {
- if (typeof opts.path !== 'string') {
- throw new InvalidArgumentError('invalid opts.path')
- }
-
- let path = opts.path
- if (!opts.path.startsWith('/')) {
- path = `/${path}`
- }
-
- url = new URL(util.parseOrigin(url).origin + path)
- } else {
- if (!opts) {
- opts = typeof url === 'object' ? url : {}
- }
-
- url = util.parseURL(url)
+ /**
+ * Added new "abort" event listener, only support "abort" event.
+ *
+ * @param _type - Only support "abort" event
+ * @param listener - The listener to be added
+ */
+ addEventListener(
+ // tslint:disable-next-line:variable-name
+ _type, listener) {
+ if (!listenersMap.has(this)) {
+ throw new TypeError("Expected `this` to be an instance of AbortSignal.");
+ }
+ const listeners = listenersMap.get(this);
+ listeners.push(listener);
}
-
- const { agent, dispatcher = getGlobalDispatcher() } = opts
-
- if (agent) {
- throw new InvalidArgumentError('unsupported opts.agent. Did you mean opts.client?')
+ /**
+ * Remove "abort" event listener, only support "abort" event.
+ *
+ * @param _type - Only support "abort" event
+ * @param listener - The listener to be removed
+ */
+ removeEventListener(
+ // tslint:disable-next-line:variable-name
+ _type, listener) {
+ if (!listenersMap.has(this)) {
+ throw new TypeError("Expected `this` to be an instance of AbortSignal.");
+ }
+ const listeners = listenersMap.get(this);
+ const index = listeners.indexOf(listener);
+ if (index > -1) {
+ listeners.splice(index, 1);
+ }
}
-
- return fn.call(dispatcher, {
- ...opts,
- origin: url.origin,
- path: url.search ? `${url.pathname}${url.search}` : url.pathname,
- method: opts.method || (opts.body ? 'PUT' : 'GET')
- }, handler)
- }
-}
-
-module.exports.setGlobalDispatcher = setGlobalDispatcher
-module.exports.getGlobalDispatcher = getGlobalDispatcher
-
-const fetchImpl = (__nccwpck_require__(8033).fetch)
-module.exports.fetch = async function fetch (init, options = undefined) {
- try {
- return await fetchImpl(init, options)
- } catch (err) {
- if (err && typeof err === 'object') {
- Error.captureStackTrace(err)
+ /**
+ * Dispatches a synthetic event to the AbortSignal.
+ */
+ dispatchEvent(_event) {
+ throw new Error("This is a stub dispatchEvent implementation that should not be used. It only exists for type-checking purposes.");
}
-
- throw err
- }
-}
-module.exports.Headers = __nccwpck_require__(1271).Headers
-module.exports.Response = __nccwpck_require__(6678).Response
-module.exports.Request = __nccwpck_require__(7412).Request
-module.exports.FormData = __nccwpck_require__(6443).FormData
-module.exports.File = globalThis.File ?? (__nccwpck_require__(4573).File)
-module.exports.FileReader = __nccwpck_require__(9190).FileReader
-
-const { setGlobalOrigin, getGlobalOrigin } = __nccwpck_require__(7038)
-
-module.exports.setGlobalOrigin = setGlobalOrigin
-module.exports.getGlobalOrigin = getGlobalOrigin
-
-const { CacheStorage } = __nccwpck_require__(3832)
-const { kConstruct } = __nccwpck_require__(3202)
-
-// Cache & CacheStorage are tightly coupled with fetch. Even if it may run
-// in an older version of Node, it doesn't have any use without fetch.
-module.exports.caches = new CacheStorage(kConstruct)
-
-const { deleteCookie, getCookies, getSetCookies, setCookie } = __nccwpck_require__(2778)
-
-module.exports.deleteCookie = deleteCookie
-module.exports.getCookies = getCookies
-module.exports.getSetCookies = getSetCookies
-module.exports.setCookie = setCookie
-
-const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(2121)
-
-module.exports.parseMIMEType = parseMIMEType
-module.exports.serializeAMimeType = serializeAMimeType
-
-const { CloseEvent, ErrorEvent, MessageEvent } = __nccwpck_require__(9617)
-module.exports.WebSocket = __nccwpck_require__(3061).WebSocket
-module.exports.CloseEvent = CloseEvent
-module.exports.ErrorEvent = ErrorEvent
-module.exports.MessageEvent = MessageEvent
-
-module.exports.request = makeDispatcher(api.request)
-module.exports.stream = makeDispatcher(api.stream)
-module.exports.pipeline = makeDispatcher(api.pipeline)
-module.exports.connect = makeDispatcher(api.connect)
-module.exports.upgrade = makeDispatcher(api.upgrade)
-
-module.exports.MockClient = MockClient
-module.exports.MockPool = MockPool
-module.exports.MockAgent = MockAgent
-module.exports.mockErrors = mockErrors
-
-const { EventSource } = __nccwpck_require__(5413)
-
-module.exports.EventSource = EventSource
-
-
-/***/ }),
-
-/***/ 3979:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-const { addAbortListener } = __nccwpck_require__(7375)
-const { RequestAbortedError } = __nccwpck_require__(2344)
-
-const kListener = Symbol('kListener')
-const kSignal = Symbol('kSignal')
-
-function abort (self) {
- if (self.abort) {
- self.abort(self[kSignal]?.reason)
- } else {
- self.reason = self[kSignal]?.reason ?? new RequestAbortedError()
- }
- removeSignal(self)
-}
-
-function addSignal (self, signal) {
- self.reason = null
-
- self[kSignal] = null
- self[kListener] = null
-
- if (!signal) {
- return
- }
-
- if (signal.aborted) {
- abort(self)
- return
- }
-
- self[kSignal] = signal
- self[kListener] = () => {
- abort(self)
- }
-
- addAbortListener(self[kSignal], self[kListener])
}
-
-function removeSignal (self) {
- if (!self[kSignal]) {
- return
- }
-
- if ('removeEventListener' in self[kSignal]) {
- self[kSignal].removeEventListener('abort', self[kListener])
- } else {
- self[kSignal].removeListener('abort', self[kListener])
- }
-
- self[kSignal] = null
- self[kListener] = null
+/**
+ * Helper to trigger an abort event immediately, the onabort and all abort event listeners will be triggered.
+ * Will try to trigger abort event for all linked AbortSignal nodes.
+ *
+ * - If there is a timeout, the timer will be cancelled.
+ * - If aborted is true, nothing will happen.
+ *
+ * @internal
+ */
+// eslint-disable-next-line @azure/azure-sdk/ts-use-interface-parameters
+function abortSignal(signal) {
+ if (signal.aborted) {
+ return;
+ }
+ if (signal.onabort) {
+ signal.onabort.call(signal);
+ }
+ const listeners = listenersMap.get(signal);
+ if (listeners) {
+ // Create a copy of listeners so mutations to the array
+ // (e.g. via removeListener calls) don't affect the listeners
+ // we invoke.
+ listeners.slice().forEach((listener) => {
+ listener.call(signal, { type: "abort" });
+ });
+ }
+ abortedMap.set(signal, true);
}
-module.exports = {
- addSignal,
- removeSignal
+// Copyright (c) Microsoft Corporation.
+/**
+ * This error is thrown when an asynchronous operation has been aborted.
+ * Check for this error by testing the `name` that the name property of the
+ * error matches `"AbortError"`.
+ *
+ * @example
+ * ```ts
+ * const controller = new AbortController();
+ * controller.abort();
+ * try {
+ * doAsyncWork(controller.signal)
+ * } catch (e) {
+ * if (e.name === 'AbortError') {
+ * // handle abort error here.
+ * }
+ * }
+ * ```
+ */
+class AbortError extends Error {
+ constructor(message) {
+ super(message);
+ this.name = "AbortError";
+ }
}
-
-
-/***/ }),
-
-/***/ 1959:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const assert = __nccwpck_require__(4589)
-const { AsyncResource } = __nccwpck_require__(6698)
-const { InvalidArgumentError, SocketError } = __nccwpck_require__(2344)
-const util = __nccwpck_require__(7375)
-const { addSignal, removeSignal } = __nccwpck_require__(3979)
-
-class ConnectHandler extends AsyncResource {
- constructor (opts, callback) {
- if (!opts || typeof opts !== 'object') {
- throw new InvalidArgumentError('invalid opts')
+/**
+ * An AbortController provides an AbortSignal and the associated controls to signal
+ * that an asynchronous operation should be aborted.
+ *
+ * @example
+ * Abort an operation when another event fires
+ * ```ts
+ * const controller = new AbortController();
+ * const signal = controller.signal;
+ * doAsyncWork(signal);
+ * button.addEventListener('click', () => controller.abort());
+ * ```
+ *
+ * @example
+ * Share aborter cross multiple operations in 30s
+ * ```ts
+ * // Upload the same data to 2 different data centers at the same time,
+ * // abort another when any of them is finished
+ * const controller = AbortController.withTimeout(30 * 1000);
+ * doAsyncWork(controller.signal).then(controller.abort);
+ * doAsyncWork(controller.signal).then(controller.abort);
+ *```
+ *
+ * @example
+ * Cascaded aborting
+ * ```ts
+ * // All operations can't take more than 30 seconds
+ * const aborter = Aborter.timeout(30 * 1000);
+ *
+ * // Following 2 operations can't take more than 25 seconds
+ * await doAsyncWork(aborter.withTimeout(25 * 1000));
+ * await doAsyncWork(aborter.withTimeout(25 * 1000));
+ * ```
+ */
+class AbortController {
+ // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
+ constructor(parentSignals) {
+ this._signal = new AbortSignal();
+ if (!parentSignals) {
+ return;
+ }
+ // coerce parentSignals into an array
+ if (!Array.isArray(parentSignals)) {
+ // eslint-disable-next-line prefer-rest-params
+ parentSignals = arguments;
+ }
+ for (const parentSignal of parentSignals) {
+ // if the parent signal has already had abort() called,
+ // then call abort on this signal as well.
+ if (parentSignal.aborted) {
+ this.abort();
+ }
+ else {
+ // when the parent signal aborts, this signal should as well.
+ parentSignal.addEventListener("abort", () => {
+ this.abort();
+ });
+ }
+ }
}
-
- if (typeof callback !== 'function') {
- throw new InvalidArgumentError('invalid callback')
+ /**
+ * The AbortSignal associated with this controller that will signal aborted
+ * when the abort method is called on this controller.
+ *
+ * @readonly
+ */
+ get signal() {
+ return this._signal;
}
-
- const { signal, opaque, responseHeaders } = opts
-
- if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
- throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
+ /**
+ * Signal that any operations passed this controller's associated abort signal
+ * to cancel any remaining work and throw an `AbortError`.
+ */
+ abort() {
+ abortSignal(this._signal);
}
-
- super('UNDICI_CONNECT')
-
- this.opaque = opaque || null
- this.responseHeaders = responseHeaders || null
- this.callback = callback
- this.abort = null
-
- addSignal(this, signal)
- }
-
- onConnect (abort, context) {
- if (this.reason) {
- abort(this.reason)
- return
+ /**
+ * Creates a new AbortSignal instance that will abort after the provided ms.
+ * @param ms - Elapsed time in milliseconds to trigger an abort.
+ */
+ static timeout(ms) {
+ const signal = new AbortSignal();
+ const timer = setTimeout(abortSignal, ms, signal);
+ // Prevent the active Timer from keeping the Node.js event loop active.
+ if (typeof timer.unref === "function") {
+ timer.unref();
+ }
+ return signal;
}
+}
- assert(this.callback)
+exports.AbortController = AbortController;
+exports.AbortError = AbortError;
+exports.AbortSignal = AbortSignal;
+//# sourceMappingURL=index.js.map
- this.abort = abort
- this.context = context
- }
- onHeaders () {
- throw new SocketError('bad connect', null)
- }
+/***/ }),
- onUpgrade (statusCode, rawHeaders, socket) {
- const { callback, opaque, context } = this
+/***/ 5862:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- removeSignal(this)
+var __webpack_unused_export__;
- this.callback = null
- let headers = rawHeaders
- // Indicates is an HTTP2Session
- if (headers != null) {
- headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
- }
+__webpack_unused_export__ = ({ value: true });
- this.runInAsyncScope(callback, null, null, {
- statusCode,
- headers,
- socket,
- opaque,
- context
- })
- }
+var logger$1 = __nccwpck_require__(6515);
+var abortController = __nccwpck_require__(8110);
+var coreUtil = __nccwpck_require__(7779);
- onError (err) {
- const { callback, opaque } = this
+// Copyright (c) Microsoft Corporation.
+/**
+ * The `@azure/logger` configuration for this package.
+ * @internal
+ */
+const logger = logger$1.createClientLogger("core-lro");
- removeSignal(this)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+/**
+ * The default time interval to wait before sending the next polling request.
+ */
+const POLL_INTERVAL_IN_MS = 2000;
+/**
+ * The closed set of terminal states.
+ */
+const terminalStates = ["succeeded", "canceled", "failed"];
- if (callback) {
- this.callback = null
- queueMicrotask(() => {
- this.runInAsyncScope(callback, null, err, { opaque })
- })
+// Copyright (c) Microsoft Corporation.
+/**
+ * Deserializes the state
+ */
+function deserializeState(serializedState) {
+ try {
+ return JSON.parse(serializedState).state;
+ }
+ catch (e) {
+ throw new Error(`Unable to deserialize input state: ${serializedState}`);
}
- }
}
-
-function connect (opts, callback) {
- if (callback === undefined) {
- return new Promise((resolve, reject) => {
- connect.call(this, opts, (err, data) => {
- return err ? reject(err) : resolve(data)
- })
- })
- }
-
- try {
- const connectHandler = new ConnectHandler(opts, callback)
- this.dispatch({ ...opts, method: 'CONNECT' }, connectHandler)
- } catch (err) {
- if (typeof callback !== 'function') {
- throw err
- }
- const opaque = opts?.opaque
- queueMicrotask(() => callback(err, { opaque }))
- }
+function setStateError(inputs) {
+ const { state, stateProxy, isOperationError } = inputs;
+ return (error) => {
+ if (isOperationError(error)) {
+ stateProxy.setError(state, error);
+ stateProxy.setFailed(state);
+ }
+ throw error;
+ };
}
-
-module.exports = connect
-
-
-/***/ }),
-
-/***/ 5483:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const {
- Readable,
- Duplex,
- PassThrough
-} = __nccwpck_require__(7075)
-const {
- InvalidArgumentError,
- InvalidReturnValueError,
- RequestAbortedError
-} = __nccwpck_require__(2344)
-const util = __nccwpck_require__(7375)
-const { AsyncResource } = __nccwpck_require__(6698)
-const { addSignal, removeSignal } = __nccwpck_require__(3979)
-const assert = __nccwpck_require__(4589)
-
-const kResume = Symbol('resume')
-
-class PipelineRequest extends Readable {
- constructor () {
- super({ autoDestroy: true })
-
- this[kResume] = null
- }
-
- _read () {
- const { [kResume]: resume } = this
-
- if (resume) {
- this[kResume] = null
- resume()
+function appendReadableErrorMessage(currentMessage, innerMessage) {
+ let message = currentMessage;
+ if (message.slice(-1) !== ".") {
+ message = message + ".";
}
- }
-
- _destroy (err, callback) {
- this._read()
-
- callback(err)
- }
+ return message + " " + innerMessage;
}
-
-class PipelineResponse extends Readable {
- constructor (resume) {
- super({ autoDestroy: true })
- this[kResume] = resume
- }
-
- _read () {
- this[kResume]()
- }
-
- _destroy (err, callback) {
- if (!err && !this._readableState.endEmitted) {
- err = new RequestAbortedError()
+function simplifyError(err) {
+ let message = err.message;
+ let code = err.code;
+ let curErr = err;
+ while (curErr.innererror) {
+ curErr = curErr.innererror;
+ code = curErr.code;
+ message = appendReadableErrorMessage(message, curErr.message);
}
-
- callback(err)
- }
+ return {
+ code,
+ message,
+ };
}
-
-class PipelineHandler extends AsyncResource {
- constructor (opts, handler) {
- if (!opts || typeof opts !== 'object') {
- throw new InvalidArgumentError('invalid opts')
- }
-
- if (typeof handler !== 'function') {
- throw new InvalidArgumentError('invalid handler')
+function processOperationStatus(result) {
+ const { state, stateProxy, status, isDone, processResult, getError, response, setErrorAsResult } = result;
+ switch (status) {
+ case "succeeded": {
+ stateProxy.setSucceeded(state);
+ break;
+ }
+ case "failed": {
+ const err = getError === null || getError === void 0 ? void 0 : getError(response);
+ let postfix = "";
+ if (err) {
+ const { code, message } = simplifyError(err);
+ postfix = `. ${code}. ${message}`;
+ }
+ const errStr = `The long-running operation has failed${postfix}`;
+ stateProxy.setError(state, new Error(errStr));
+ stateProxy.setFailed(state);
+ logger.warning(errStr);
+ break;
+ }
+ case "canceled": {
+ stateProxy.setCanceled(state);
+ break;
+ }
}
-
- const { signal, method, opaque, onInfo, responseHeaders } = opts
-
- if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
- throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
+ if ((isDone === null || isDone === void 0 ? void 0 : isDone(response, state)) ||
+ (isDone === undefined &&
+ ["succeeded", "canceled"].concat(setErrorAsResult ? [] : ["failed"]).includes(status))) {
+ stateProxy.setResult(state, buildResult({
+ response,
+ state,
+ processResult,
+ }));
}
-
- if (method === 'CONNECT') {
- throw new InvalidArgumentError('invalid method')
+}
+function buildResult(inputs) {
+ const { processResult, response, state } = inputs;
+ return processResult ? processResult(response, state) : response;
+}
+/**
+ * Initiates the long-running operation.
+ */
+async function initOperation(inputs) {
+ const { init, stateProxy, processResult, getOperationStatus, withOperationLocation, setErrorAsResult, } = inputs;
+ const { operationLocation, resourceLocation, metadata, response } = await init();
+ if (operationLocation)
+ withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(operationLocation, false);
+ const config = {
+ metadata,
+ operationLocation,
+ resourceLocation,
+ };
+ logger.verbose(`LRO: Operation description:`, config);
+ const state = stateProxy.initState(config);
+ const status = getOperationStatus({ response, state, operationLocation });
+ processOperationStatus({ state, status, stateProxy, response, setErrorAsResult, processResult });
+ return state;
+}
+async function pollOperationHelper(inputs) {
+ const { poll, state, stateProxy, operationLocation, getOperationStatus, getResourceLocation, isOperationError, options, } = inputs;
+ const response = await poll(operationLocation, options).catch(setStateError({
+ state,
+ stateProxy,
+ isOperationError,
+ }));
+ const status = getOperationStatus(response, state);
+ logger.verbose(`LRO: Status:\n\tPolling from: ${state.config.operationLocation}\n\tOperation status: ${status}\n\tPolling status: ${terminalStates.includes(status) ? "Stopped" : "Running"}`);
+ if (status === "succeeded") {
+ const resourceLocation = getResourceLocation(response, state);
+ if (resourceLocation !== undefined) {
+ return {
+ response: await poll(resourceLocation).catch(setStateError({ state, stateProxy, isOperationError })),
+ status,
+ };
+ }
}
-
- if (onInfo && typeof onInfo !== 'function') {
- throw new InvalidArgumentError('invalid onInfo callback')
+ return { response, status };
+}
+/** Polls the long-running operation. */
+async function pollOperation(inputs) {
+ const { poll, state, stateProxy, options, getOperationStatus, getResourceLocation, getOperationLocation, isOperationError, withOperationLocation, getPollingInterval, processResult, getError, updateState, setDelay, isDone, setErrorAsResult, } = inputs;
+ const { operationLocation } = state.config;
+ if (operationLocation !== undefined) {
+ const { response, status } = await pollOperationHelper({
+ poll,
+ getOperationStatus,
+ state,
+ stateProxy,
+ operationLocation,
+ getResourceLocation,
+ isOperationError,
+ options,
+ });
+ processOperationStatus({
+ status,
+ response,
+ state,
+ stateProxy,
+ isDone,
+ processResult,
+ getError,
+ setErrorAsResult,
+ });
+ if (!terminalStates.includes(status)) {
+ const intervalInMs = getPollingInterval === null || getPollingInterval === void 0 ? void 0 : getPollingInterval(response);
+ if (intervalInMs)
+ setDelay(intervalInMs);
+ const location = getOperationLocation === null || getOperationLocation === void 0 ? void 0 : getOperationLocation(response, state);
+ if (location !== undefined) {
+ const isUpdated = operationLocation !== location;
+ state.config.operationLocation = location;
+ withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(location, isUpdated);
+ }
+ else
+ withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(operationLocation, false);
+ }
+ updateState === null || updateState === void 0 ? void 0 : updateState(state, response);
}
+}
- super('UNDICI_PIPELINE')
-
- this.opaque = opaque || null
- this.responseHeaders = responseHeaders || null
- this.handler = handler
- this.abort = null
- this.context = null
- this.onInfo = onInfo || null
-
- this.req = new PipelineRequest().on('error', util.nop)
-
- this.ret = new Duplex({
- readableObjectMode: opts.objectMode,
- autoDestroy: true,
- read: () => {
- const { body } = this
-
- if (body?.resume) {
- body.resume()
+// Copyright (c) Microsoft Corporation.
+function getOperationLocationPollingUrl(inputs) {
+ const { azureAsyncOperation, operationLocation } = inputs;
+ return operationLocation !== null && operationLocation !== void 0 ? operationLocation : azureAsyncOperation;
+}
+function getLocationHeader(rawResponse) {
+ return rawResponse.headers["location"];
+}
+function getOperationLocationHeader(rawResponse) {
+ return rawResponse.headers["operation-location"];
+}
+function getAzureAsyncOperationHeader(rawResponse) {
+ return rawResponse.headers["azure-asyncoperation"];
+}
+function findResourceLocation(inputs) {
+ var _a;
+ const { location, requestMethod, requestPath, resourceLocationConfig } = inputs;
+ switch (requestMethod) {
+ case "PUT": {
+ return requestPath;
}
- },
- write: (chunk, encoding, callback) => {
- const { req } = this
-
- if (req.push(chunk, encoding) || req._readableState.destroyed) {
- callback()
- } else {
- req[kResume] = callback
+ case "DELETE": {
+ return undefined;
}
- },
- destroy: (err, callback) => {
- const { body, req, res, ret, abort } = this
-
- if (!err && !ret._readableState.endEmitted) {
- err = new RequestAbortedError()
+ case "PATCH": {
+ return (_a = getDefault()) !== null && _a !== void 0 ? _a : requestPath;
}
-
- if (abort && err) {
- abort()
+ default: {
+ return getDefault();
}
-
- util.destroy(body, err)
- util.destroy(req, err)
- util.destroy(res, err)
-
- removeSignal(this)
-
- callback(err)
- }
- }).on('prefinish', () => {
- const { req } = this
-
- // Node < 15 does not call _final in same tick.
- req.push(null)
- })
-
- this.res = null
-
- addSignal(this, signal)
- }
-
- onConnect (abort, context) {
- const { ret, res } = this
-
- if (this.reason) {
- abort(this.reason)
- return
}
-
- assert(!res, 'pipeline cannot be retried')
- assert(!ret.destroyed)
-
- this.abort = abort
- this.context = context
- }
-
- onHeaders (statusCode, rawHeaders, resume) {
- const { opaque, handler, context } = this
-
- if (statusCode < 200) {
- if (this.onInfo) {
- const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
- this.onInfo({ statusCode, headers })
- }
- return
+ function getDefault() {
+ switch (resourceLocationConfig) {
+ case "azure-async-operation": {
+ return undefined;
+ }
+ case "original-uri": {
+ return requestPath;
+ }
+ case "location":
+ default: {
+ return location;
+ }
+ }
}
-
- this.res = new PipelineResponse(resume)
-
- let body
- try {
- this.handler = null
- const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
- body = this.runInAsyncScope(handler, null, {
- statusCode,
- headers,
- opaque,
- body: this.res,
- context
- })
- } catch (err) {
- this.res.on('error', util.nop)
- throw err
+}
+function inferLroMode(inputs) {
+ const { rawResponse, requestMethod, requestPath, resourceLocationConfig } = inputs;
+ const operationLocation = getOperationLocationHeader(rawResponse);
+ const azureAsyncOperation = getAzureAsyncOperationHeader(rawResponse);
+ const pollingUrl = getOperationLocationPollingUrl({ operationLocation, azureAsyncOperation });
+ const location = getLocationHeader(rawResponse);
+ const normalizedRequestMethod = requestMethod === null || requestMethod === void 0 ? void 0 : requestMethod.toLocaleUpperCase();
+ if (pollingUrl !== undefined) {
+ return {
+ mode: "OperationLocation",
+ operationLocation: pollingUrl,
+ resourceLocation: findResourceLocation({
+ requestMethod: normalizedRequestMethod,
+ location,
+ requestPath,
+ resourceLocationConfig,
+ }),
+ };
}
-
- if (!body || typeof body.on !== 'function') {
- throw new InvalidReturnValueError('expected Readable')
+ else if (location !== undefined) {
+ return {
+ mode: "ResourceLocation",
+ operationLocation: location,
+ };
}
-
- body
- .on('data', (chunk) => {
- const { ret, body } = this
-
- if (!ret.push(chunk) && body.pause) {
- body.pause()
- }
- })
- .on('error', (err) => {
- const { ret } = this
-
- util.destroy(ret, err)
- })
- .on('end', () => {
- const { ret } = this
-
- ret.push(null)
- })
- .on('close', () => {
- const { ret } = this
-
- if (!ret._readableState.ended) {
- util.destroy(ret, new RequestAbortedError())
+ else if (normalizedRequestMethod === "PUT" && requestPath) {
+ return {
+ mode: "Body",
+ operationLocation: requestPath,
+ };
+ }
+ else {
+ return undefined;
+ }
+}
+function transformStatus(inputs) {
+ const { status, statusCode } = inputs;
+ if (typeof status !== "string" && status !== undefined) {
+ throw new Error(`Polling was unsuccessful. Expected status to have a string value or no value but it has instead: ${status}. This doesn't necessarily indicate the operation has failed. Check your Azure subscription or resource status for more information.`);
+ }
+ switch (status === null || status === void 0 ? void 0 : status.toLocaleLowerCase()) {
+ case undefined:
+ return toOperationStatus(statusCode);
+ case "succeeded":
+ return "succeeded";
+ case "failed":
+ return "failed";
+ case "running":
+ case "accepted":
+ case "started":
+ case "canceling":
+ case "cancelling":
+ return "running";
+ case "canceled":
+ case "cancelled":
+ return "canceled";
+ default: {
+ logger.verbose(`LRO: unrecognized operation status: ${status}`);
+ return status;
}
- })
-
- this.body = body
- }
-
- onData (chunk) {
- const { res } = this
- return res.push(chunk)
- }
-
- onComplete (trailers) {
- const { res } = this
- res.push(null)
- }
-
- onError (err) {
- const { ret } = this
- this.handler = null
- util.destroy(ret, err)
- }
+ }
}
-
-function pipeline (opts, handler) {
- try {
- const pipelineHandler = new PipelineHandler(opts, handler)
- this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler)
- return pipelineHandler.ret
- } catch (err) {
- return new PassThrough().destroy(err)
- }
+function getStatus(rawResponse) {
+ var _a;
+ const { status } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {};
+ return transformStatus({ status, statusCode: rawResponse.statusCode });
}
-
-module.exports = pipeline
-
-
-/***/ }),
-
-/***/ 2412:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const assert = __nccwpck_require__(4589)
-const { Readable } = __nccwpck_require__(3946)
-const { InvalidArgumentError, RequestAbortedError } = __nccwpck_require__(2344)
-const util = __nccwpck_require__(7375)
-const { getResolveErrorBodyCallback } = __nccwpck_require__(7478)
-const { AsyncResource } = __nccwpck_require__(6698)
-
-class RequestHandler extends AsyncResource {
- constructor (opts, callback) {
- if (!opts || typeof opts !== 'object') {
- throw new InvalidArgumentError('invalid opts')
- }
-
- const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError, highWaterMark } = opts
-
- try {
- if (typeof callback !== 'function') {
- throw new InvalidArgumentError('invalid callback')
- }
-
- if (highWaterMark && (typeof highWaterMark !== 'number' || highWaterMark < 0)) {
- throw new InvalidArgumentError('invalid highWaterMark')
- }
-
- if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
- throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
- }
-
- if (method === 'CONNECT') {
- throw new InvalidArgumentError('invalid method')
- }
-
- if (onInfo && typeof onInfo !== 'function') {
- throw new InvalidArgumentError('invalid onInfo callback')
- }
-
- super('UNDICI_REQUEST')
- } catch (err) {
- if (util.isStream(body)) {
- util.destroy(body.on('error', util.nop), err)
- }
- throw err
- }
-
- this.method = method
- this.responseHeaders = responseHeaders || null
- this.opaque = opaque || null
- this.callback = callback
- this.res = null
- this.abort = null
- this.body = body
- this.trailers = {}
- this.context = null
- this.onInfo = onInfo || null
- this.throwOnError = throwOnError
- this.highWaterMark = highWaterMark
- this.signal = signal
- this.reason = null
- this.removeAbortListener = null
-
- if (util.isStream(body)) {
- body.on('error', (err) => {
- this.onError(err)
- })
- }
-
- if (this.signal) {
- if (this.signal.aborted) {
- this.reason = this.signal.reason ?? new RequestAbortedError()
- } else {
- this.removeAbortListener = util.addAbortListener(this.signal, () => {
- this.reason = this.signal.reason ?? new RequestAbortedError()
- if (this.res) {
- util.destroy(this.res.on('error', util.nop), this.reason)
- } else if (this.abort) {
- this.abort(this.reason)
- }
-
- if (this.removeAbortListener) {
- this.res?.off('close', this.removeAbortListener)
- this.removeAbortListener()
- this.removeAbortListener = null
- }
- })
- }
- }
- }
-
- onConnect (abort, context) {
- if (this.reason) {
- abort(this.reason)
- return
- }
-
- assert(this.callback)
-
- this.abort = abort
- this.context = context
- }
-
- onHeaders (statusCode, rawHeaders, resume, statusMessage) {
- const { callback, opaque, abort, context, responseHeaders, highWaterMark } = this
-
- const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
-
- if (statusCode < 200) {
- if (this.onInfo) {
- this.onInfo({ statusCode, headers })
- }
- return
- }
-
- const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers
- const contentType = parsedHeaders['content-type']
- const contentLength = parsedHeaders['content-length']
- const res = new Readable({
- resume,
- abort,
- contentType,
- contentLength: this.method !== 'HEAD' && contentLength
- ? Number(contentLength)
- : null,
- highWaterMark
- })
-
- if (this.removeAbortListener) {
- res.on('close', this.removeAbortListener)
- }
-
- this.callback = null
- this.res = res
- if (callback !== null) {
- if (this.throwOnError && statusCode >= 400) {
- this.runInAsyncScope(getResolveErrorBodyCallback, null,
- { callback, body: res, contentType, statusCode, statusMessage, headers }
- )
- } else {
- this.runInAsyncScope(callback, null, null, {
- statusCode,
- headers,
- trailers: this.trailers,
- opaque,
- body: res,
- context
- })
- }
- }
- }
-
- onData (chunk) {
- return this.res.push(chunk)
- }
-
- onComplete (trailers) {
- util.parseHeaders(trailers, this.trailers)
- this.res.push(null)
- }
-
- onError (err) {
- const { res, callback, body, opaque } = this
-
- if (callback) {
- // TODO: Does this need queueMicrotask?
- this.callback = null
- queueMicrotask(() => {
- this.runInAsyncScope(callback, null, err, { opaque })
- })
- }
-
- if (res) {
- this.res = null
- // Ensure all queued handlers are invoked before destroying res.
- queueMicrotask(() => {
- util.destroy(res, err)
- })
+function getProvisioningState(rawResponse) {
+ var _a, _b;
+ const { properties, provisioningState } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {};
+ const status = (_b = properties === null || properties === void 0 ? void 0 : properties.provisioningState) !== null && _b !== void 0 ? _b : provisioningState;
+ return transformStatus({ status, statusCode: rawResponse.statusCode });
+}
+function toOperationStatus(statusCode) {
+ if (statusCode === 202) {
+ return "running";
}
-
- if (body) {
- this.body = null
- util.destroy(body, err)
+ else if (statusCode < 300) {
+ return "succeeded";
}
-
- if (this.removeAbortListener) {
- res?.off('close', this.removeAbortListener)
- this.removeAbortListener()
- this.removeAbortListener = null
+ else {
+ return "failed";
}
- }
}
-
-function request (opts, callback) {
- if (callback === undefined) {
- return new Promise((resolve, reject) => {
- request.call(this, opts, (err, data) => {
- return err ? reject(err) : resolve(data)
- })
- })
- }
-
- try {
- this.dispatch(opts, new RequestHandler(opts, callback))
- } catch (err) {
- if (typeof callback !== 'function') {
- throw err
+function parseRetryAfter({ rawResponse }) {
+ const retryAfter = rawResponse.headers["retry-after"];
+ if (retryAfter !== undefined) {
+ // Retry-After header value is either in HTTP date format, or in seconds
+ const retryAfterInSeconds = parseInt(retryAfter);
+ return isNaN(retryAfterInSeconds)
+ ? calculatePollingIntervalFromDate(new Date(retryAfter))
+ : retryAfterInSeconds * 1000;
}
- const opaque = opts?.opaque
- queueMicrotask(() => callback(err, { opaque }))
- }
+ return undefined;
}
-
-module.exports = request
-module.exports.RequestHandler = RequestHandler
-
-
-/***/ }),
-
-/***/ 4685:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const assert = __nccwpck_require__(4589)
-const { finished, PassThrough } = __nccwpck_require__(7075)
-const { InvalidArgumentError, InvalidReturnValueError } = __nccwpck_require__(2344)
-const util = __nccwpck_require__(7375)
-const { getResolveErrorBodyCallback } = __nccwpck_require__(7478)
-const { AsyncResource } = __nccwpck_require__(6698)
-const { addSignal, removeSignal } = __nccwpck_require__(3979)
-
-class StreamHandler extends AsyncResource {
- constructor (opts, factory, callback) {
- if (!opts || typeof opts !== 'object') {
- throw new InvalidArgumentError('invalid opts')
- }
-
- const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError } = opts
-
- try {
- if (typeof callback !== 'function') {
- throw new InvalidArgumentError('invalid callback')
- }
-
- if (typeof factory !== 'function') {
- throw new InvalidArgumentError('invalid factory')
- }
-
- if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
- throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
- }
-
- if (method === 'CONNECT') {
- throw new InvalidArgumentError('invalid method')
- }
-
- if (onInfo && typeof onInfo !== 'function') {
- throw new InvalidArgumentError('invalid onInfo callback')
- }
-
- super('UNDICI_STREAM')
- } catch (err) {
- if (util.isStream(body)) {
- util.destroy(body.on('error', util.nop), err)
- }
- throw err
+function getErrorFromResponse(response) {
+ const error = response.flatResponse.error;
+ if (!error) {
+ logger.warning(`The long-running operation failed but there is no error property in the response's body`);
+ return;
}
-
- this.responseHeaders = responseHeaders || null
- this.opaque = opaque || null
- this.factory = factory
- this.callback = callback
- this.res = null
- this.abort = null
- this.context = null
- this.trailers = null
- this.body = body
- this.onInfo = onInfo || null
- this.throwOnError = throwOnError || false
-
- if (util.isStream(body)) {
- body.on('error', (err) => {
- this.onError(err)
- })
+ if (!error.code || !error.message) {
+ logger.warning(`The long-running operation failed but the error property in the response's body doesn't contain code or message`);
+ return;
}
-
- addSignal(this, signal)
- }
-
- onConnect (abort, context) {
- if (this.reason) {
- abort(this.reason)
- return
+ return error;
+}
+function calculatePollingIntervalFromDate(retryAfterDate) {
+ const timeNow = Math.floor(new Date().getTime());
+ const retryAfterTime = retryAfterDate.getTime();
+ if (timeNow < retryAfterTime) {
+ return retryAfterTime - timeNow;
}
-
- assert(this.callback)
-
- this.abort = abort
- this.context = context
- }
-
- onHeaders (statusCode, rawHeaders, resume, statusMessage) {
- const { factory, opaque, context, callback, responseHeaders } = this
-
- const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
-
- if (statusCode < 200) {
- if (this.onInfo) {
- this.onInfo({ statusCode, headers })
- }
- return
+ return undefined;
+}
+function getStatusFromInitialResponse(inputs) {
+ const { response, state, operationLocation } = inputs;
+ function helper() {
+ var _a;
+ const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"];
+ switch (mode) {
+ case undefined:
+ return toOperationStatus(response.rawResponse.statusCode);
+ case "Body":
+ return getOperationStatus(response, state);
+ default:
+ return "running";
+ }
}
-
- this.factory = null
-
- let res
-
- if (this.throwOnError && statusCode >= 400) {
- const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers
- const contentType = parsedHeaders['content-type']
- res = new PassThrough()
-
- this.callback = null
- this.runInAsyncScope(getResolveErrorBodyCallback, null,
- { callback, body: res, contentType, statusCode, statusMessage, headers }
- )
- } else {
- if (factory === null) {
- return
- }
-
- res = this.runInAsyncScope(factory, null, {
- statusCode,
- headers,
- opaque,
- context
- })
-
- if (
- !res ||
- typeof res.write !== 'function' ||
- typeof res.end !== 'function' ||
- typeof res.on !== 'function'
- ) {
- throw new InvalidReturnValueError('expected Writable')
- }
-
- // TODO: Avoid finished. It registers an unnecessary amount of listeners.
- finished(res, { readable: false }, (err) => {
- const { callback, res, opaque, trailers, abort } = this
-
- this.res = null
- if (err || !res.readable) {
- util.destroy(res, err)
+ const status = helper();
+ return status === "running" && operationLocation === undefined ? "succeeded" : status;
+}
+/**
+ * Initiates the long-running operation.
+ */
+async function initHttpOperation(inputs) {
+ const { stateProxy, resourceLocationConfig, processResult, lro, setErrorAsResult } = inputs;
+ return initOperation({
+ init: async () => {
+ const response = await lro.sendInitialRequest();
+ const config = inferLroMode({
+ rawResponse: response.rawResponse,
+ requestPath: lro.requestPath,
+ requestMethod: lro.requestMethod,
+ resourceLocationConfig,
+ });
+ return Object.assign({ response, operationLocation: config === null || config === void 0 ? void 0 : config.operationLocation, resourceLocation: config === null || config === void 0 ? void 0 : config.resourceLocation }, ((config === null || config === void 0 ? void 0 : config.mode) ? { metadata: { mode: config.mode } } : {}));
+ },
+ stateProxy,
+ processResult: processResult
+ ? ({ flatResponse }, state) => processResult(flatResponse, state)
+ : ({ flatResponse }) => flatResponse,
+ getOperationStatus: getStatusFromInitialResponse,
+ setErrorAsResult,
+ });
+}
+function getOperationLocation({ rawResponse }, state) {
+ var _a;
+ const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"];
+ switch (mode) {
+ case "OperationLocation": {
+ return getOperationLocationPollingUrl({
+ operationLocation: getOperationLocationHeader(rawResponse),
+ azureAsyncOperation: getAzureAsyncOperationHeader(rawResponse),
+ });
}
-
- this.callback = null
- this.runInAsyncScope(callback, null, err || null, { opaque, trailers })
-
- if (err) {
- abort()
+ case "ResourceLocation": {
+ return getLocationHeader(rawResponse);
+ }
+ case "Body":
+ default: {
+ return undefined;
}
- })
- }
-
- res.on('drain', resume)
-
- this.res = res
-
- const needDrain = res.writableNeedDrain !== undefined
- ? res.writableNeedDrain
- : res._writableState?.needDrain
-
- return needDrain !== true
- }
-
- onData (chunk) {
- const { res } = this
-
- return res ? res.write(chunk) : true
- }
-
- onComplete (trailers) {
- const { res } = this
-
- removeSignal(this)
-
- if (!res) {
- return
- }
-
- this.trailers = util.parseHeaders(trailers)
-
- res.end()
- }
-
- onError (err) {
- const { res, callback, opaque, body } = this
-
- removeSignal(this)
-
- this.factory = null
-
- if (res) {
- this.res = null
- util.destroy(res, err)
- } else if (callback) {
- this.callback = null
- queueMicrotask(() => {
- this.runInAsyncScope(callback, null, err, { opaque })
- })
- }
-
- if (body) {
- this.body = null
- util.destroy(body, err)
}
- }
}
-
-function stream (opts, factory, callback) {
- if (callback === undefined) {
- return new Promise((resolve, reject) => {
- stream.call(this, opts, factory, (err, data) => {
- return err ? reject(err) : resolve(data)
- })
- })
- }
-
- try {
- this.dispatch(opts, new StreamHandler(opts, factory, callback))
- } catch (err) {
- if (typeof callback !== 'function') {
- throw err
+function getOperationStatus({ rawResponse }, state) {
+ var _a;
+ const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"];
+ switch (mode) {
+ case "OperationLocation": {
+ return getStatus(rawResponse);
+ }
+ case "ResourceLocation": {
+ return toOperationStatus(rawResponse.statusCode);
+ }
+ case "Body": {
+ return getProvisioningState(rawResponse);
+ }
+ default:
+ throw new Error(`Internal error: Unexpected operation mode: ${mode}`);
}
- const opaque = opts?.opaque
- queueMicrotask(() => callback(err, { opaque }))
- }
+}
+function getResourceLocation({ flatResponse }, state) {
+ if (typeof flatResponse === "object") {
+ const resourceLocation = flatResponse.resourceLocation;
+ if (resourceLocation !== undefined) {
+ state.config.resourceLocation = resourceLocation;
+ }
+ }
+ return state.config.resourceLocation;
+}
+function isOperationError(e) {
+ return e.name === "RestError";
+}
+/** Polls the long-running operation. */
+async function pollHttpOperation(inputs) {
+ const { lro, stateProxy, options, processResult, updateState, setDelay, state, setErrorAsResult, } = inputs;
+ return pollOperation({
+ state,
+ stateProxy,
+ setDelay,
+ processResult: processResult
+ ? ({ flatResponse }, inputState) => processResult(flatResponse, inputState)
+ : ({ flatResponse }) => flatResponse,
+ getError: getErrorFromResponse,
+ updateState,
+ getPollingInterval: parseRetryAfter,
+ getOperationLocation,
+ getOperationStatus,
+ isOperationError,
+ getResourceLocation,
+ options,
+ /**
+ * The expansion here is intentional because `lro` could be an object that
+ * references an inner this, so we need to preserve a reference to it.
+ */
+ poll: async (location, inputOptions) => lro.sendPollRequest(location, inputOptions),
+ setErrorAsResult,
+ });
}
-module.exports = stream
-
-
-/***/ }),
-
-/***/ 4106:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
+// Copyright (c) Microsoft Corporation.
+const createStateProxy$1 = () => ({
+ /**
+ * The state at this point is created to be of type OperationState.
+ * It will be updated later to be of type TState when the
+ * customer-provided callback, `updateState`, is called during polling.
+ */
+ initState: (config) => ({ status: "running", config }),
+ setCanceled: (state) => (state.status = "canceled"),
+ setError: (state, error) => (state.error = error),
+ setResult: (state, result) => (state.result = result),
+ setRunning: (state) => (state.status = "running"),
+ setSucceeded: (state) => (state.status = "succeeded"),
+ setFailed: (state) => (state.status = "failed"),
+ getError: (state) => state.error,
+ getResult: (state) => state.result,
+ isCanceled: (state) => state.status === "canceled",
+ isFailed: (state) => state.status === "failed",
+ isRunning: (state) => state.status === "running",
+ isSucceeded: (state) => state.status === "succeeded",
+});
+/**
+ * Returns a poller factory.
+ */
+function buildCreatePoller(inputs) {
+ const { getOperationLocation, getStatusFromInitialResponse, getStatusFromPollResponse, isOperationError, getResourceLocation, getPollingInterval, getError, resolveOnUnsuccessful, } = inputs;
+ return async ({ init, poll }, options) => {
+ const { processResult, updateState, withOperationLocation: withOperationLocationCallback, intervalInMs = POLL_INTERVAL_IN_MS, restoreFrom, } = options || {};
+ const stateProxy = createStateProxy$1();
+ const withOperationLocation = withOperationLocationCallback
+ ? (() => {
+ let called = false;
+ return (operationLocation, isUpdated) => {
+ if (isUpdated)
+ withOperationLocationCallback(operationLocation);
+ else if (!called)
+ withOperationLocationCallback(operationLocation);
+ called = true;
+ };
+ })()
+ : undefined;
+ const state = restoreFrom
+ ? deserializeState(restoreFrom)
+ : await initOperation({
+ init,
+ stateProxy,
+ processResult,
+ getOperationStatus: getStatusFromInitialResponse,
+ withOperationLocation,
+ setErrorAsResult: !resolveOnUnsuccessful,
+ });
+ let resultPromise;
+ const abortController$1 = new abortController.AbortController();
+ const handlers = new Map();
+ const handleProgressEvents = async () => handlers.forEach((h) => h(state));
+ const cancelErrMsg = "Operation was canceled";
+ let currentPollIntervalInMs = intervalInMs;
+ const poller = {
+ getOperationState: () => state,
+ getResult: () => state.result,
+ isDone: () => ["succeeded", "failed", "canceled"].includes(state.status),
+ isStopped: () => resultPromise === undefined,
+ stopPolling: () => {
+ abortController$1.abort();
+ },
+ toString: () => JSON.stringify({
+ state,
+ }),
+ onProgress: (callback) => {
+ const s = Symbol();
+ handlers.set(s, callback);
+ return () => handlers.delete(s);
+ },
+ pollUntilDone: (pollOptions) => (resultPromise !== null && resultPromise !== void 0 ? resultPromise : (resultPromise = (async () => {
+ const { abortSignal: inputAbortSignal } = pollOptions || {};
+ const { signal: abortSignal } = inputAbortSignal
+ ? new abortController.AbortController([inputAbortSignal, abortController$1.signal])
+ : abortController$1;
+ if (!poller.isDone()) {
+ await poller.poll({ abortSignal });
+ while (!poller.isDone()) {
+ await coreUtil.delay(currentPollIntervalInMs, { abortSignal });
+ await poller.poll({ abortSignal });
+ }
+ }
+ if (resolveOnUnsuccessful) {
+ return poller.getResult();
+ }
+ else {
+ switch (state.status) {
+ case "succeeded":
+ return poller.getResult();
+ case "canceled":
+ throw new Error(cancelErrMsg);
+ case "failed":
+ throw state.error;
+ case "notStarted":
+ case "running":
+ throw new Error(`Polling completed without succeeding or failing`);
+ }
+ }
+ })().finally(() => {
+ resultPromise = undefined;
+ }))),
+ async poll(pollOptions) {
+ if (resolveOnUnsuccessful) {
+ if (poller.isDone())
+ return;
+ }
+ else {
+ switch (state.status) {
+ case "succeeded":
+ return;
+ case "canceled":
+ throw new Error(cancelErrMsg);
+ case "failed":
+ throw state.error;
+ }
+ }
+ await pollOperation({
+ poll,
+ state,
+ stateProxy,
+ getOperationLocation,
+ isOperationError,
+ withOperationLocation,
+ getPollingInterval,
+ getOperationStatus: getStatusFromPollResponse,
+ getResourceLocation,
+ processResult,
+ getError,
+ updateState,
+ options: pollOptions,
+ setDelay: (pollIntervalInMs) => {
+ currentPollIntervalInMs = pollIntervalInMs;
+ },
+ setErrorAsResult: !resolveOnUnsuccessful,
+ });
+ await handleProgressEvents();
+ if (!resolveOnUnsuccessful) {
+ switch (state.status) {
+ case "canceled":
+ throw new Error(cancelErrMsg);
+ case "failed":
+ throw state.error;
+ }
+ }
+ },
+ };
+ return poller;
+ };
+}
-const { InvalidArgumentError, SocketError } = __nccwpck_require__(2344)
-const { AsyncResource } = __nccwpck_require__(6698)
-const util = __nccwpck_require__(7375)
-const { addSignal, removeSignal } = __nccwpck_require__(3979)
-const assert = __nccwpck_require__(4589)
+// Copyright (c) Microsoft Corporation.
+/**
+ * Creates a poller that can be used to poll a long-running operation.
+ * @param lro - Description of the long-running operation
+ * @param options - options to configure the poller
+ * @returns an initialized poller
+ */
+async function createHttpPoller(lro, options) {
+ const { resourceLocationConfig, intervalInMs, processResult, restoreFrom, updateState, withOperationLocation, resolveOnUnsuccessful = false, } = options || {};
+ return buildCreatePoller({
+ getStatusFromInitialResponse,
+ getStatusFromPollResponse: getOperationStatus,
+ isOperationError,
+ getOperationLocation,
+ getResourceLocation,
+ getPollingInterval: parseRetryAfter,
+ getError: getErrorFromResponse,
+ resolveOnUnsuccessful,
+ })({
+ init: async () => {
+ const response = await lro.sendInitialRequest();
+ const config = inferLroMode({
+ rawResponse: response.rawResponse,
+ requestPath: lro.requestPath,
+ requestMethod: lro.requestMethod,
+ resourceLocationConfig,
+ });
+ return Object.assign({ response, operationLocation: config === null || config === void 0 ? void 0 : config.operationLocation, resourceLocation: config === null || config === void 0 ? void 0 : config.resourceLocation }, ((config === null || config === void 0 ? void 0 : config.mode) ? { metadata: { mode: config.mode } } : {}));
+ },
+ poll: lro.sendPollRequest,
+ }, {
+ intervalInMs,
+ withOperationLocation,
+ restoreFrom,
+ updateState,
+ processResult: processResult
+ ? ({ flatResponse }, state) => processResult(flatResponse, state)
+ : ({ flatResponse }) => flatResponse,
+ });
+}
-class UpgradeHandler extends AsyncResource {
- constructor (opts, callback) {
- if (!opts || typeof opts !== 'object') {
- throw new InvalidArgumentError('invalid opts')
+// Copyright (c) Microsoft Corporation.
+const createStateProxy = () => ({
+ initState: (config) => ({ config, isStarted: true }),
+ setCanceled: (state) => (state.isCancelled = true),
+ setError: (state, error) => (state.error = error),
+ setResult: (state, result) => (state.result = result),
+ setRunning: (state) => (state.isStarted = true),
+ setSucceeded: (state) => (state.isCompleted = true),
+ setFailed: () => {
+ /** empty body */
+ },
+ getError: (state) => state.error,
+ getResult: (state) => state.result,
+ isCanceled: (state) => !!state.isCancelled,
+ isFailed: (state) => !!state.error,
+ isRunning: (state) => !!state.isStarted,
+ isSucceeded: (state) => Boolean(state.isCompleted && !state.isCancelled && !state.error),
+});
+class GenericPollOperation {
+ constructor(state, lro, setErrorAsResult, lroResourceLocationConfig, processResult, updateState, isDone) {
+ this.state = state;
+ this.lro = lro;
+ this.setErrorAsResult = setErrorAsResult;
+ this.lroResourceLocationConfig = lroResourceLocationConfig;
+ this.processResult = processResult;
+ this.updateState = updateState;
+ this.isDone = isDone;
}
-
- if (typeof callback !== 'function') {
- throw new InvalidArgumentError('invalid callback')
+ setPollerConfig(pollerConfig) {
+ this.pollerConfig = pollerConfig;
}
-
- const { signal, opaque, responseHeaders } = opts
-
- if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
- throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
+ async update(options) {
+ var _a;
+ const stateProxy = createStateProxy();
+ if (!this.state.isStarted) {
+ this.state = Object.assign(Object.assign({}, this.state), (await initHttpOperation({
+ lro: this.lro,
+ stateProxy,
+ resourceLocationConfig: this.lroResourceLocationConfig,
+ processResult: this.processResult,
+ setErrorAsResult: this.setErrorAsResult,
+ })));
+ }
+ const updateState = this.updateState;
+ const isDone = this.isDone;
+ if (!this.state.isCompleted && this.state.error === undefined) {
+ await pollHttpOperation({
+ lro: this.lro,
+ state: this.state,
+ stateProxy,
+ processResult: this.processResult,
+ updateState: updateState
+ ? (state, { rawResponse }) => updateState(state, rawResponse)
+ : undefined,
+ isDone: isDone
+ ? ({ flatResponse }, state) => isDone(flatResponse, state)
+ : undefined,
+ options,
+ setDelay: (intervalInMs) => {
+ this.pollerConfig.intervalInMs = intervalInMs;
+ },
+ setErrorAsResult: this.setErrorAsResult,
+ });
+ }
+ (_a = options === null || options === void 0 ? void 0 : options.fireProgress) === null || _a === void 0 ? void 0 : _a.call(options, this.state);
+ return this;
}
-
- super('UNDICI_UPGRADE')
-
- this.responseHeaders = responseHeaders || null
- this.opaque = opaque || null
- this.callback = callback
- this.abort = null
- this.context = null
-
- addSignal(this, signal)
- }
-
- onConnect (abort, context) {
- if (this.reason) {
- abort(this.reason)
- return
+ async cancel() {
+ logger.error("`cancelOperation` is deprecated because it wasn't implemented");
+ return this;
}
-
- assert(this.callback)
-
- this.abort = abort
- this.context = null
- }
-
- onHeaders () {
- throw new SocketError('bad upgrade', null)
- }
-
- onUpgrade (statusCode, rawHeaders, socket) {
- assert(statusCode === 101)
-
- const { callback, opaque, context } = this
-
- removeSignal(this)
-
- this.callback = null
- const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
- this.runInAsyncScope(callback, null, null, {
- headers,
- socket,
- opaque,
- context
- })
- }
-
- onError (err) {
- const { callback, opaque } = this
-
- removeSignal(this)
-
- if (callback) {
- this.callback = null
- queueMicrotask(() => {
- this.runInAsyncScope(callback, null, err, { opaque })
- })
+ /**
+ * Serializes the Poller operation.
+ */
+ toString() {
+ return JSON.stringify({
+ state: this.state,
+ });
}
- }
}
-function upgrade (opts, callback) {
- if (callback === undefined) {
- return new Promise((resolve, reject) => {
- upgrade.call(this, opts, (err, data) => {
- return err ? reject(err) : resolve(data)
- })
- })
- }
-
- try {
- const upgradeHandler = new UpgradeHandler(opts, callback)
- this.dispatch({
- ...opts,
- method: opts.method || 'GET',
- upgrade: opts.protocol || 'Websocket'
- }, upgradeHandler)
- } catch (err) {
- if (typeof callback !== 'function') {
- throw err
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+/**
+ * When a poller is manually stopped through the `stopPolling` method,
+ * the poller will be rejected with an instance of the PollerStoppedError.
+ */
+class PollerStoppedError extends Error {
+ constructor(message) {
+ super(message);
+ this.name = "PollerStoppedError";
+ Object.setPrototypeOf(this, PollerStoppedError.prototype);
}
- const opaque = opts?.opaque
- queueMicrotask(() => callback(err, { opaque }))
- }
}
-
-module.exports = upgrade
-
-
-/***/ }),
-
-/***/ 436:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-module.exports.request = __nccwpck_require__(2412)
-module.exports.stream = __nccwpck_require__(4685)
-module.exports.pipeline = __nccwpck_require__(5483)
-module.exports.upgrade = __nccwpck_require__(4106)
-module.exports.connect = __nccwpck_require__(1959)
-
-
-/***/ }),
-
-/***/ 3946:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-// Ported from https://github.com/nodejs/undici/pull/907
-
-
-
-const assert = __nccwpck_require__(4589)
-const { Readable } = __nccwpck_require__(7075)
-const { RequestAbortedError, NotSupportedError, InvalidArgumentError, AbortError } = __nccwpck_require__(2344)
-const util = __nccwpck_require__(7375)
-const { ReadableStreamFrom } = __nccwpck_require__(7375)
-
-const kConsume = Symbol('kConsume')
-const kReading = Symbol('kReading')
-const kBody = Symbol('kBody')
-const kAbort = Symbol('kAbort')
-const kContentType = Symbol('kContentType')
-const kContentLength = Symbol('kContentLength')
-
-const noop = () => {}
-
-class BodyReadable extends Readable {
- constructor ({
- resume,
- abort,
- contentType = '',
- contentLength,
- highWaterMark = 64 * 1024 // Same as nodejs fs streams.
- }) {
- super({
- autoDestroy: true,
- read: resume,
- highWaterMark
- })
-
- this._readableState.dataEmitted = false
-
- this[kAbort] = abort
- this[kConsume] = null
- this[kBody] = null
- this[kContentType] = contentType
- this[kContentLength] = contentLength
-
- // Is stream being consumed through Readable API?
- // This is an optimization so that we avoid checking
- // for 'data' and 'readable' listeners in the hot path
- // inside push().
- this[kReading] = false
- }
-
- destroy (err) {
- if (!err && !this._readableState.endEmitted) {
- err = new RequestAbortedError()
- }
-
- if (err) {
- this[kAbort]()
- }
-
- return super.destroy(err)
- }
-
- _destroy (err, callback) {
- // Workaround for Node "bug". If the stream is destroyed in same
- // tick as it is created, then a user who is waiting for a
- // promise (i.e micro tick) for installing a 'error' listener will
- // never get a chance and will always encounter an unhandled exception.
- if (!this[kReading]) {
- setImmediate(() => {
- callback(err)
- })
- } else {
- callback(err)
- }
- }
-
- on (ev, ...args) {
- if (ev === 'data' || ev === 'readable') {
- this[kReading] = true
+/**
+ * When the operation is cancelled, the poller will be rejected with an instance
+ * of the PollerCancelledError.
+ */
+class PollerCancelledError extends Error {
+ constructor(message) {
+ super(message);
+ this.name = "PollerCancelledError";
+ Object.setPrototypeOf(this, PollerCancelledError.prototype);
}
- return super.on(ev, ...args)
- }
-
- addListener (ev, ...args) {
- return this.on(ev, ...args)
- }
+}
+/**
+ * A class that represents the definition of a program that polls through consecutive requests
+ * until it reaches a state of completion.
+ *
+ * A poller can be executed manually, by polling request by request by calling to the `poll()` method repeatedly, until its operation is completed.
+ * It also provides a way to wait until the operation completes, by calling `pollUntilDone()` and waiting until the operation finishes.
+ * Pollers can also request the cancellation of the ongoing process to whom is providing the underlying long running operation.
+ *
+ * ```ts
+ * const poller = new MyPoller();
+ *
+ * // Polling just once:
+ * await poller.poll();
+ *
+ * // We can try to cancel the request here, by calling:
+ * //
+ * // await poller.cancelOperation();
+ * //
+ *
+ * // Getting the final result:
+ * const result = await poller.pollUntilDone();
+ * ```
+ *
+ * The Poller is defined by two types, a type representing the state of the poller, which
+ * must include a basic set of properties from `PollOperationState`,
+ * and a return type defined by `TResult`, which can be anything.
+ *
+ * The Poller class implements the `PollerLike` interface, which allows poller implementations to avoid having
+ * to export the Poller's class directly, and instead only export the already instantiated poller with the PollerLike type.
+ *
+ * ```ts
+ * class Client {
+ * public async makePoller: PollerLike {
+ * const poller = new MyPoller({});
+ * // It might be preferred to return the poller after the first request is made,
+ * // so that some information can be obtained right away.
+ * await poller.poll();
+ * return poller;
+ * }
+ * }
+ *
+ * const poller: PollerLike = myClient.makePoller();
+ * ```
+ *
+ * A poller can be created through its constructor, then it can be polled until it's completed.
+ * At any point in time, the state of the poller can be obtained without delay through the getOperationState method.
+ * At any point in time, the intermediate forms of the result type can be requested without delay.
+ * Once the underlying operation is marked as completed, the poller will stop and the final value will be returned.
+ *
+ * ```ts
+ * const poller = myClient.makePoller();
+ * const state: MyOperationState = poller.getOperationState();
+ *
+ * // The intermediate result can be obtained at any time.
+ * const result: MyResult | undefined = poller.getResult();
+ *
+ * // The final result can only be obtained after the poller finishes.
+ * const result: MyResult = await poller.pollUntilDone();
+ * ```
+ *
+ */
+// eslint-disable-next-line no-use-before-define
+class Poller {
+ /**
+ * A poller needs to be initialized by passing in at least the basic properties of the `PollOperation`.
+ *
+ * When writing an implementation of a Poller, this implementation needs to deal with the initialization
+ * of any custom state beyond the basic definition of the poller. The basic poller assumes that the poller's
+ * operation has already been defined, at least its basic properties. The code below shows how to approach
+ * the definition of the constructor of a new custom poller.
+ *
+ * ```ts
+ * export class MyPoller extends Poller {
+ * constructor({
+ * // Anything you might need outside of the basics
+ * }) {
+ * let state: MyOperationState = {
+ * privateProperty: private,
+ * publicProperty: public,
+ * };
+ *
+ * const operation = {
+ * state,
+ * update,
+ * cancel,
+ * toString
+ * }
+ *
+ * // Sending the operation to the parent's constructor.
+ * super(operation);
+ *
+ * // You can assign more local properties here.
+ * }
+ * }
+ * ```
+ *
+ * Inside of this constructor, a new promise is created. This will be used to
+ * tell the user when the poller finishes (see `pollUntilDone()`). The promise's
+ * resolve and reject methods are also used internally to control when to resolve
+ * or reject anyone waiting for the poller to finish.
+ *
+ * The constructor of a custom implementation of a poller is where any serialized version of
+ * a previous poller's operation should be deserialized into the operation sent to the
+ * base constructor. For example:
+ *
+ * ```ts
+ * export class MyPoller extends Poller {
+ * constructor(
+ * baseOperation: string | undefined
+ * ) {
+ * let state: MyOperationState = {};
+ * if (baseOperation) {
+ * state = {
+ * ...JSON.parse(baseOperation).state,
+ * ...state
+ * };
+ * }
+ * const operation = {
+ * state,
+ * // ...
+ * }
+ * super(operation);
+ * }
+ * }
+ * ```
+ *
+ * @param operation - Must contain the basic properties of `PollOperation`.
+ */
+ constructor(operation) {
+ /** controls whether to throw an error if the operation failed or was canceled. */
+ this.resolveOnUnsuccessful = false;
+ this.stopped = true;
+ this.pollProgressCallbacks = [];
+ this.operation = operation;
+ this.promise = new Promise((resolve, reject) => {
+ this.resolve = resolve;
+ this.reject = reject;
+ });
+ // This prevents the UnhandledPromiseRejectionWarning in node.js from being thrown.
+ // The above warning would get thrown if `poller.poll` is called, it returns an error,
+ // and pullUntilDone did not have a .catch or await try/catch on it's return value.
+ this.promise.catch(() => {
+ /* intentionally blank */
+ });
+ }
+ /**
+ * Starts a loop that will break only if the poller is done
+ * or if the poller is stopped.
+ */
+ async startPolling(pollOptions = {}) {
+ if (this.stopped) {
+ this.stopped = false;
+ }
+ while (!this.isStopped() && !this.isDone()) {
+ await this.poll(pollOptions);
+ await this.delay();
+ }
+ }
+ /**
+ * pollOnce does one polling, by calling to the update method of the underlying
+ * poll operation to make any relevant change effective.
+ *
+ * It only optionally receives an object with an abortSignal property, from \@azure/abort-controller's AbortSignalLike.
+ *
+ * @param options - Optional properties passed to the operation's update method.
+ */
+ async pollOnce(options = {}) {
+ if (!this.isDone()) {
+ this.operation = await this.operation.update({
+ abortSignal: options.abortSignal,
+ fireProgress: this.fireProgress.bind(this),
+ });
+ }
+ this.processUpdatedState();
+ }
+ /**
+ * fireProgress calls the functions passed in via onProgress the method of the poller.
+ *
+ * It loops over all of the callbacks received from onProgress, and executes them, sending them
+ * the current operation state.
+ *
+ * @param state - The current operation state.
+ */
+ fireProgress(state) {
+ for (const callback of this.pollProgressCallbacks) {
+ callback(state);
+ }
+ }
+ /**
+ * Invokes the underlying operation's cancel method.
+ */
+ async cancelOnce(options = {}) {
+ this.operation = await this.operation.cancel(options);
+ }
+ /**
+ * Returns a promise that will resolve once a single polling request finishes.
+ * It does this by calling the update method of the Poller's operation.
+ *
+ * It only optionally receives an object with an abortSignal property, from \@azure/abort-controller's AbortSignalLike.
+ *
+ * @param options - Optional properties passed to the operation's update method.
+ */
+ poll(options = {}) {
+ if (!this.pollOncePromise) {
+ this.pollOncePromise = this.pollOnce(options);
+ const clearPollOncePromise = () => {
+ this.pollOncePromise = undefined;
+ };
+ this.pollOncePromise.then(clearPollOncePromise, clearPollOncePromise).catch(this.reject);
+ }
+ return this.pollOncePromise;
+ }
+ processUpdatedState() {
+ if (this.operation.state.error) {
+ this.stopped = true;
+ if (!this.resolveOnUnsuccessful) {
+ this.reject(this.operation.state.error);
+ throw this.operation.state.error;
+ }
+ }
+ if (this.operation.state.isCancelled) {
+ this.stopped = true;
+ if (!this.resolveOnUnsuccessful) {
+ const error = new PollerCancelledError("Operation was canceled");
+ this.reject(error);
+ throw error;
+ }
+ }
+ if (this.isDone() && this.resolve) {
+ // If the poller has finished polling, this means we now have a result.
+ // However, it can be the case that TResult is instantiated to void, so
+ // we are not expecting a result anyway. To assert that we might not
+ // have a result eventually after finishing polling, we cast the result
+ // to TResult.
+ this.resolve(this.getResult());
+ }
+ }
+ /**
+ * Returns a promise that will resolve once the underlying operation is completed.
+ */
+ async pollUntilDone(pollOptions = {}) {
+ if (this.stopped) {
+ this.startPolling(pollOptions).catch(this.reject);
+ }
+ // This is needed because the state could have been updated by
+ // `cancelOperation`, e.g. the operation is canceled or an error occurred.
+ this.processUpdatedState();
+ return this.promise;
+ }
+ /**
+ * Invokes the provided callback after each polling is completed,
+ * sending the current state of the poller's operation.
+ *
+ * It returns a method that can be used to stop receiving updates on the given callback function.
+ */
+ onProgress(callback) {
+ this.pollProgressCallbacks.push(callback);
+ return () => {
+ this.pollProgressCallbacks = this.pollProgressCallbacks.filter((c) => c !== callback);
+ };
+ }
+ /**
+ * Returns true if the poller has finished polling.
+ */
+ isDone() {
+ const state = this.operation.state;
+ return Boolean(state.isCompleted || state.isCancelled || state.error);
+ }
+ /**
+ * Stops the poller from continuing to poll.
+ */
+ stopPolling() {
+ if (!this.stopped) {
+ this.stopped = true;
+ if (this.reject) {
+ this.reject(new PollerStoppedError("This poller is already stopped"));
+ }
+ }
+ }
+ /**
+ * Returns true if the poller is stopped.
+ */
+ isStopped() {
+ return this.stopped;
+ }
+ /**
+ * Attempts to cancel the underlying operation.
+ *
+ * It only optionally receives an object with an abortSignal property, from \@azure/abort-controller's AbortSignalLike.
+ *
+ * If it's called again before it finishes, it will throw an error.
+ *
+ * @param options - Optional properties passed to the operation's update method.
+ */
+ cancelOperation(options = {}) {
+ if (!this.cancelPromise) {
+ this.cancelPromise = this.cancelOnce(options);
+ }
+ else if (options.abortSignal) {
+ throw new Error("A cancel request is currently pending");
+ }
+ return this.cancelPromise;
+ }
+ /**
+ * Returns the state of the operation.
+ *
+ * Even though TState will be the same type inside any of the methods of any extension of the Poller class,
+ * implementations of the pollers can customize what's shared with the public by writing their own
+ * version of the `getOperationState` method, and by defining two types, one representing the internal state of the poller
+ * and a public type representing a safe to share subset of the properties of the internal state.
+ * Their definition of getOperationState can then return their public type.
+ *
+ * Example:
+ *
+ * ```ts
+ * // Let's say we have our poller's operation state defined as:
+ * interface MyOperationState extends PollOperationState {
+ * privateProperty?: string;
+ * publicProperty?: string;
+ * }
+ *
+ * // To allow us to have a true separation of public and private state, we have to define another interface:
+ * interface PublicState extends PollOperationState {
+ * publicProperty?: string;
+ * }
+ *
+ * // Then, we define our Poller as follows:
+ * export class MyPoller extends Poller {
+ * // ... More content is needed here ...
+ *
+ * public getOperationState(): PublicState {
+ * const state: PublicState = this.operation.state;
+ * return {
+ * // Properties from PollOperationState
+ * isStarted: state.isStarted,
+ * isCompleted: state.isCompleted,
+ * isCancelled: state.isCancelled,
+ * error: state.error,
+ * result: state.result,
+ *
+ * // The only other property needed by PublicState.
+ * publicProperty: state.publicProperty
+ * }
+ * }
+ * }
+ * ```
+ *
+ * You can see this in the tests of this repository, go to the file:
+ * `../test/utils/testPoller.ts`
+ * and look for the getOperationState implementation.
+ */
+ getOperationState() {
+ return this.operation.state;
+ }
+ /**
+ * Returns the result value of the operation,
+ * regardless of the state of the poller.
+ * It can return undefined or an incomplete form of the final TResult value
+ * depending on the implementation.
+ */
+ getResult() {
+ const state = this.operation.state;
+ return state.result;
+ }
+ /**
+ * Returns a serialized version of the poller's operation
+ * by invoking the operation's toString method.
+ */
+ toString() {
+ return this.operation.toString();
+ }
+}
- off (ev, ...args) {
- const ret = super.off(ev, ...args)
- if (ev === 'data' || ev === 'readable') {
- this[kReading] = (
- this.listenerCount('data') > 0 ||
- this.listenerCount('readable') > 0
- )
+// Copyright (c) Microsoft Corporation.
+/**
+ * The LRO Engine, a class that performs polling.
+ */
+class LroEngine extends Poller {
+ constructor(lro, options) {
+ const { intervalInMs = POLL_INTERVAL_IN_MS, resumeFrom, resolveOnUnsuccessful = false, isDone, lroResourceLocationConfig, processResult, updateState, } = options || {};
+ const state = resumeFrom
+ ? deserializeState(resumeFrom)
+ : {};
+ const operation = new GenericPollOperation(state, lro, !resolveOnUnsuccessful, lroResourceLocationConfig, processResult, updateState, isDone);
+ super(operation);
+ this.resolveOnUnsuccessful = resolveOnUnsuccessful;
+ this.config = { intervalInMs: intervalInMs };
+ operation.setPollerConfig(this.config);
}
- return ret
- }
+ /**
+ * The method used by the poller to wait before attempting to update its operation.
+ */
+ delay() {
+ return new Promise((resolve) => setTimeout(() => resolve(), this.config.intervalInMs));
+ }
+}
- removeListener (ev, ...args) {
- return this.off(ev, ...args)
- }
+__webpack_unused_export__ = LroEngine;
+exports.vu = Poller;
+__webpack_unused_export__ = PollerCancelledError;
+__webpack_unused_export__ = PollerStoppedError;
+__webpack_unused_export__ = createHttpPoller;
+//# sourceMappingURL=index.js.map
- push (chunk) {
- if (this[kConsume] && chunk !== null) {
- consumePush(this[kConsume], chunk)
- return this[kReading] ? super.push(chunk) : true
- }
- return super.push(chunk)
- }
- // https://fetch.spec.whatwg.org/#dom-body-text
- async text () {
- return consume(this, 'text')
- }
+/***/ }),
- // https://fetch.spec.whatwg.org/#dom-body-json
- async json () {
- return consume(this, 'json')
- }
+/***/ 7889:
+/***/ (function(__unused_webpack_module, exports) {
- // https://fetch.spec.whatwg.org/#dom-body-blob
- async blob () {
- return consume(this, 'blob')
- }
- // https://fetch.spec.whatwg.org/#dom-body-bytes
- async bytes () {
- return consume(this, 'bytes')
- }
+var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.ClientStreamingCall = void 0;
+/**
+ * A client streaming RPC call. This means that the clients sends 0, 1, or
+ * more messages to the server, and the server replies with exactly one
+ * message.
+ */
+class ClientStreamingCall {
+ constructor(method, requestHeaders, request, headers, response, status, trailers) {
+ this.method = method;
+ this.requestHeaders = requestHeaders;
+ this.requests = request;
+ this.headers = headers;
+ this.response = response;
+ this.status = status;
+ this.trailers = trailers;
+ }
+ /**
+ * Instead of awaiting the response status and trailers, you can
+ * just as well await this call itself to receive the server outcome.
+ * Note that it may still be valid to send more request messages.
+ */
+ then(onfulfilled, onrejected) {
+ return this.promiseFinished().then(value => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, reason => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason));
+ }
+ promiseFinished() {
+ return __awaiter(this, void 0, void 0, function* () {
+ let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]);
+ return {
+ method: this.method,
+ requestHeaders: this.requestHeaders,
+ headers,
+ response,
+ status,
+ trailers
+ };
+ });
+ }
+}
+exports.ClientStreamingCall = ClientStreamingCall;
- // https://fetch.spec.whatwg.org/#dom-body-arraybuffer
- async arrayBuffer () {
- return consume(this, 'arrayBuffer')
- }
- // https://fetch.spec.whatwg.org/#dom-body-formdata
- async formData () {
- // TODO: Implement.
- throw new NotSupportedError()
- }
+/***/ }),
- // https://fetch.spec.whatwg.org/#dom-body-bodyused
- get bodyUsed () {
- return util.isDisturbed(this)
- }
+/***/ 1409:
+/***/ ((__unused_webpack_module, exports) => {
- // https://fetch.spec.whatwg.org/#dom-body-body
- get body () {
- if (!this[kBody]) {
- this[kBody] = ReadableStreamFrom(this)
- if (this[kConsume]) {
- // TODO: Is this the best way to force a lock?
- this[kBody].getReader() // Ensure stream is locked.
- assert(this[kBody].locked)
- }
- }
- return this[kBody]
- }
-
- async dump (opts) {
- let limit = Number.isFinite(opts?.limit) ? opts.limit : 128 * 1024
- const signal = opts?.signal
- if (signal != null && (typeof signal !== 'object' || !('aborted' in signal))) {
- throw new InvalidArgumentError('signal must be an AbortSignal')
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.Deferred = exports.DeferredState = void 0;
+var DeferredState;
+(function (DeferredState) {
+ DeferredState[DeferredState["PENDING"] = 0] = "PENDING";
+ DeferredState[DeferredState["REJECTED"] = 1] = "REJECTED";
+ DeferredState[DeferredState["RESOLVED"] = 2] = "RESOLVED";
+})(DeferredState = exports.DeferredState || (exports.DeferredState = {}));
+/**
+ * A deferred promise. This is a "controller" for a promise, which lets you
+ * pass a promise around and reject or resolve it from the outside.
+ *
+ * Warning: This class is to be used with care. Using it can make code very
+ * difficult to read. It is intended for use in library code that exposes
+ * promises, not for regular business logic.
+ */
+class Deferred {
+ /**
+ * @param preventUnhandledRejectionWarning - prevents the warning
+ * "Unhandled Promise rejection" by adding a noop rejection handler.
+ * Working with calls returned from the runtime-rpc package in an
+ * async function usually means awaiting one call property after
+ * the other. This means that the "status" is not being awaited when
+ * an earlier await for the "headers" is rejected. This causes the
+ * "unhandled promise reject" warning. A more correct behaviour for
+ * calls might be to become aware whether at least one of the
+ * promises is handled and swallow the rejection warning for the
+ * others.
+ */
+ constructor(preventUnhandledRejectionWarning = true) {
+ this._state = DeferredState.PENDING;
+ this._promise = new Promise((resolve, reject) => {
+ this._resolve = resolve;
+ this._reject = reject;
+ });
+ if (preventUnhandledRejectionWarning) {
+ this._promise.catch(_ => { });
+ }
}
-
- signal?.throwIfAborted()
-
- if (this._readableState.closeEmitted) {
- return null
+ /**
+ * Get the current state of the promise.
+ */
+ get state() {
+ return this._state;
}
+ /**
+ * Get the deferred promise.
+ */
+ get promise() {
+ return this._promise;
+ }
+ /**
+ * Resolve the promise. Throws if the promise is already resolved or rejected.
+ */
+ resolve(value) {
+ if (this.state !== DeferredState.PENDING)
+ throw new Error(`cannot resolve ${DeferredState[this.state].toLowerCase()}`);
+ this._resolve(value);
+ this._state = DeferredState.RESOLVED;
+ }
+ /**
+ * Reject the promise. Throws if the promise is already resolved or rejected.
+ */
+ reject(reason) {
+ if (this.state !== DeferredState.PENDING)
+ throw new Error(`cannot reject ${DeferredState[this.state].toLowerCase()}`);
+ this._reject(reason);
+ this._state = DeferredState.REJECTED;
+ }
+ /**
+ * Resolve the promise. Ignore if not pending.
+ */
+ resolvePending(val) {
+ if (this._state === DeferredState.PENDING)
+ this.resolve(val);
+ }
+ /**
+ * Reject the promise. Ignore if not pending.
+ */
+ rejectPending(reason) {
+ if (this._state === DeferredState.PENDING)
+ this.reject(reason);
+ }
+}
+exports.Deferred = Deferred;
- return await new Promise((resolve, reject) => {
- if (this[kContentLength] > limit) {
- this.destroy(new AbortError())
- }
- const onAbort = () => {
- this.destroy(signal.reason ?? new AbortError())
- }
- signal?.addEventListener('abort', onAbort)
+/***/ }),
- this
- .on('close', function () {
- signal?.removeEventListener('abort', onAbort)
- if (signal?.aborted) {
- reject(signal.reason ?? new AbortError())
- } else {
- resolve(null)
- }
- })
- .on('error', noop)
- .on('data', function (chunk) {
- limit -= chunk.length
- if (limit <= 0) {
- this.destroy()
- }
- })
- .resume()
- })
- }
-}
+/***/ 6826:
+/***/ (function(__unused_webpack_module, exports) {
-// https://streams.spec.whatwg.org/#readablestream-locked
-function isLocked (self) {
- // Consume is an implicit lock.
- return (self[kBody] && self[kBody].locked === true) || self[kConsume]
-}
-// https://fetch.spec.whatwg.org/#body-unusable
-function isUnusable (self) {
- return util.isDisturbed(self) || isLocked(self)
+var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.DuplexStreamingCall = void 0;
+/**
+ * A duplex streaming RPC call. This means that the clients sends an
+ * arbitrary amount of messages to the server, while at the same time,
+ * the server sends an arbitrary amount of messages to the client.
+ */
+class DuplexStreamingCall {
+ constructor(method, requestHeaders, request, headers, response, status, trailers) {
+ this.method = method;
+ this.requestHeaders = requestHeaders;
+ this.requests = request;
+ this.headers = headers;
+ this.responses = response;
+ this.status = status;
+ this.trailers = trailers;
+ }
+ /**
+ * Instead of awaiting the response status and trailers, you can
+ * just as well await this call itself to receive the server outcome.
+ * Note that it may still be valid to send more request messages.
+ */
+ then(onfulfilled, onrejected) {
+ return this.promiseFinished().then(value => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, reason => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason));
+ }
+ promiseFinished() {
+ return __awaiter(this, void 0, void 0, function* () {
+ let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]);
+ return {
+ method: this.method,
+ requestHeaders: this.requestHeaders,
+ headers,
+ status,
+ trailers,
+ };
+ });
+ }
}
+exports.DuplexStreamingCall = DuplexStreamingCall;
-async function consume (stream, type) {
- assert(!stream[kConsume])
-
- return new Promise((resolve, reject) => {
- if (isUnusable(stream)) {
- const rState = stream._readableState
- if (rState.destroyed && rState.closeEmitted === false) {
- stream
- .on('error', err => {
- reject(err)
- })
- .on('close', () => {
- reject(new TypeError('unusable'))
- })
- } else {
- reject(rState.errored ?? new TypeError('unusable'))
- }
- } else {
- queueMicrotask(() => {
- stream[kConsume] = {
- type,
- stream,
- resolve,
- reject,
- length: 0,
- body: []
- }
- stream
- .on('error', function (err) {
- consumeFinish(this[kConsume], err)
- })
- .on('close', function () {
- if (this[kConsume].body !== null) {
- consumeFinish(this[kConsume], new RequestAbortedError())
- }
- })
+/***/ }),
- consumeStart(stream[kConsume])
- })
- }
- })
-}
+/***/ 4420:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-function consumeStart (consume) {
- if (consume.body === null) {
- return
- }
+var __webpack_unused_export__;
- const { _readableState: state } = consume.stream
+// Public API of the rpc runtime.
+// Note: we do not use `export * from ...` to help tree shakers,
+// webpack verbose output hints that this should be useful
+__webpack_unused_export__ = ({ value: true });
+var service_type_1 = __nccwpck_require__(6892);
+Object.defineProperty(exports, "C0", ({ enumerable: true, get: function () { return service_type_1.ServiceType; } }));
+var reflection_info_1 = __nccwpck_require__(2496);
+__webpack_unused_export__ = ({ enumerable: true, get: function () { return reflection_info_1.readMethodOptions; } });
+__webpack_unused_export__ = ({ enumerable: true, get: function () { return reflection_info_1.readMethodOption; } });
+__webpack_unused_export__ = ({ enumerable: true, get: function () { return reflection_info_1.readServiceOption; } });
+var rpc_error_1 = __nccwpck_require__(8636);
+__webpack_unused_export__ = ({ enumerable: true, get: function () { return rpc_error_1.RpcError; } });
+var rpc_options_1 = __nccwpck_require__(8576);
+__webpack_unused_export__ = ({ enumerable: true, get: function () { return rpc_options_1.mergeRpcOptions; } });
+var rpc_output_stream_1 = __nccwpck_require__(2726);
+__webpack_unused_export__ = ({ enumerable: true, get: function () { return rpc_output_stream_1.RpcOutputStreamController; } });
+var test_transport_1 = __nccwpck_require__(9122);
+__webpack_unused_export__ = ({ enumerable: true, get: function () { return test_transport_1.TestTransport; } });
+var deferred_1 = __nccwpck_require__(1409);
+__webpack_unused_export__ = ({ enumerable: true, get: function () { return deferred_1.Deferred; } });
+__webpack_unused_export__ = ({ enumerable: true, get: function () { return deferred_1.DeferredState; } });
+var duplex_streaming_call_1 = __nccwpck_require__(6826);
+__webpack_unused_export__ = ({ enumerable: true, get: function () { return duplex_streaming_call_1.DuplexStreamingCall; } });
+var client_streaming_call_1 = __nccwpck_require__(7889);
+__webpack_unused_export__ = ({ enumerable: true, get: function () { return client_streaming_call_1.ClientStreamingCall; } });
+var server_streaming_call_1 = __nccwpck_require__(6173);
+__webpack_unused_export__ = ({ enumerable: true, get: function () { return server_streaming_call_1.ServerStreamingCall; } });
+var unary_call_1 = __nccwpck_require__(9288);
+__webpack_unused_export__ = ({ enumerable: true, get: function () { return unary_call_1.UnaryCall; } });
+var rpc_interceptor_1 = __nccwpck_require__(2849);
+__webpack_unused_export__ = ({ enumerable: true, get: function () { return rpc_interceptor_1.stackIntercept; } });
+__webpack_unused_export__ = ({ enumerable: true, get: function () { return rpc_interceptor_1.stackDuplexStreamingInterceptors; } });
+__webpack_unused_export__ = ({ enumerable: true, get: function () { return rpc_interceptor_1.stackClientStreamingInterceptors; } });
+__webpack_unused_export__ = ({ enumerable: true, get: function () { return rpc_interceptor_1.stackServerStreamingInterceptors; } });
+__webpack_unused_export__ = ({ enumerable: true, get: function () { return rpc_interceptor_1.stackUnaryInterceptors; } });
+var server_call_context_1 = __nccwpck_require__(3352);
+__webpack_unused_export__ = ({ enumerable: true, get: function () { return server_call_context_1.ServerCallContextController; } });
- if (state.bufferIndex) {
- const start = state.bufferIndex
- const end = state.buffer.length
- for (let n = start; n < end; n++) {
- consumePush(consume, state.buffer[n])
- }
- } else {
- for (const chunk of state.buffer) {
- consumePush(consume, chunk)
- }
- }
- if (state.endEmitted) {
- consumeEnd(this[kConsume])
- } else {
- consume.stream.on('end', function () {
- consumeEnd(this[kConsume])
- })
- }
+/***/ }),
- consume.stream.resume()
+/***/ 2496:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- while (consume.stream.read() != null) {
- // Loop
- }
-}
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.readServiceOption = exports.readMethodOption = exports.readMethodOptions = exports.normalizeMethodInfo = void 0;
+const runtime_1 = __nccwpck_require__(8886);
/**
- * @param {Buffer[]} chunks
- * @param {number} length
+ * Turns PartialMethodInfo into MethodInfo.
*/
-function chunksDecode (chunks, length) {
- if (chunks.length === 0 || length === 0) {
- return ''
- }
- const buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks, length)
- const bufferLength = buffer.length
-
- // Skip BOM.
- const start =
- bufferLength > 2 &&
- buffer[0] === 0xef &&
- buffer[1] === 0xbb &&
- buffer[2] === 0xbf
- ? 3
- : 0
- return buffer.utf8Slice(start, bufferLength)
+function normalizeMethodInfo(method, service) {
+ var _a, _b, _c;
+ let m = method;
+ m.service = service;
+ m.localName = (_a = m.localName) !== null && _a !== void 0 ? _a : runtime_1.lowerCamelCase(m.name);
+ // noinspection PointlessBooleanExpressionJS
+ m.serverStreaming = !!m.serverStreaming;
+ // noinspection PointlessBooleanExpressionJS
+ m.clientStreaming = !!m.clientStreaming;
+ m.options = (_b = m.options) !== null && _b !== void 0 ? _b : {};
+ m.idempotency = (_c = m.idempotency) !== null && _c !== void 0 ? _c : undefined;
+ return m;
}
-
+exports.normalizeMethodInfo = normalizeMethodInfo;
/**
- * @param {Buffer[]} chunks
- * @param {number} length
- * @returns {Uint8Array}
+ * Read custom method options from a generated service client.
+ *
+ * @deprecated use readMethodOption()
*/
-function chunksConcat (chunks, length) {
- if (chunks.length === 0 || length === 0) {
- return new Uint8Array(0)
- }
- if (chunks.length === 1) {
- // fast-path
- return new Uint8Array(chunks[0])
- }
- const buffer = new Uint8Array(Buffer.allocUnsafeSlow(length).buffer)
-
- let offset = 0
- for (let i = 0; i < chunks.length; ++i) {
- const chunk = chunks[i]
- buffer.set(chunk, offset)
- offset += chunk.length
- }
-
- return buffer
+function readMethodOptions(service, methodName, extensionName, extensionType) {
+ var _a;
+ const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options;
+ return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : undefined;
}
-
-function consumeEnd (consume) {
- const { type, body, resolve, stream, length } = consume
-
- try {
- if (type === 'text') {
- resolve(chunksDecode(body, length))
- } else if (type === 'json') {
- resolve(JSON.parse(chunksDecode(body, length)))
- } else if (type === 'arrayBuffer') {
- resolve(chunksConcat(body, length).buffer)
- } else if (type === 'blob') {
- resolve(new Blob(body, { type: stream[kContentType] }))
- } else if (type === 'bytes') {
- resolve(chunksConcat(body, length))
+exports.readMethodOptions = readMethodOptions;
+function readMethodOption(service, methodName, extensionName, extensionType) {
+ var _a;
+ const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options;
+ if (!options) {
+ return undefined;
}
-
- consumeFinish(consume)
- } catch (err) {
- stream.destroy(err)
- }
-}
-
-function consumePush (consume, chunk) {
- consume.length += chunk.length
- consume.body.push(chunk)
+ const optionVal = options[extensionName];
+ if (optionVal === undefined) {
+ return optionVal;
+ }
+ return extensionType ? extensionType.fromJson(optionVal) : optionVal;
}
-
-function consumeFinish (consume, err) {
- if (consume.body === null) {
- return
- }
-
- if (err) {
- consume.reject(err)
- } else {
- consume.resolve()
- }
-
- consume.type = null
- consume.stream = null
- consume.resolve = null
- consume.reject = null
- consume.length = 0
- consume.body = null
+exports.readMethodOption = readMethodOption;
+function readServiceOption(service, extensionName, extensionType) {
+ const options = service.options;
+ if (!options) {
+ return undefined;
+ }
+ const optionVal = options[extensionName];
+ if (optionVal === undefined) {
+ return optionVal;
+ }
+ return extensionType ? extensionType.fromJson(optionVal) : optionVal;
}
-
-module.exports = { Readable: BodyReadable, chunksDecode }
+exports.readServiceOption = readServiceOption;
/***/ }),
-/***/ 7478:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-const assert = __nccwpck_require__(4589)
-const {
- ResponseStatusCodeError
-} = __nccwpck_require__(2344)
-
-const { chunksDecode } = __nccwpck_require__(3946)
-const CHUNK_LIMIT = 128 * 1024
-
-async function getResolveErrorBodyCallback ({ callback, body, contentType, statusCode, statusMessage, headers }) {
- assert(body)
+/***/ 8636:
+/***/ ((__unused_webpack_module, exports) => {
- let chunks = []
- let length = 0
- try {
- for await (const chunk of body) {
- chunks.push(chunk)
- length += chunk.length
- if (length > CHUNK_LIMIT) {
- chunks = []
- length = 0
- break
- }
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.RpcError = void 0;
+/**
+ * An error that occurred while calling a RPC method.
+ */
+class RpcError extends Error {
+ constructor(message, code = 'UNKNOWN', meta) {
+ super(message);
+ this.name = 'RpcError';
+ // see https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#example
+ Object.setPrototypeOf(this, new.target.prototype);
+ this.code = code;
+ this.meta = meta !== null && meta !== void 0 ? meta : {};
}
- } catch {
- chunks = []
- length = 0
- // Do nothing....
- }
+ toString() {
+ const l = [this.name + ': ' + this.message];
+ if (this.code) {
+ l.push('');
+ l.push('Code: ' + this.code);
+ }
+ if (this.serviceName && this.methodName) {
+ l.push('Method: ' + this.serviceName + '/' + this.methodName);
+ }
+ let m = Object.entries(this.meta);
+ if (m.length) {
+ l.push('');
+ l.push('Meta:');
+ for (let [k, v] of m) {
+ l.push(` ${k}: ${v}`);
+ }
+ }
+ return l.join('\n');
+ }
+}
+exports.RpcError = RpcError;
- const message = `Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`
- if (statusCode === 204 || !contentType || !length) {
- queueMicrotask(() => callback(new ResponseStatusCodeError(message, statusCode, headers)))
- return
- }
+/***/ }),
- const stackTraceLimit = Error.stackTraceLimit
- Error.stackTraceLimit = 0
- let payload
+/***/ 2849:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- try {
- if (isContentTypeApplicationJson(contentType)) {
- payload = JSON.parse(chunksDecode(chunks, length))
- } else if (isContentTypeText(contentType)) {
- payload = chunksDecode(chunks, length)
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.stackDuplexStreamingInterceptors = exports.stackClientStreamingInterceptors = exports.stackServerStreamingInterceptors = exports.stackUnaryInterceptors = exports.stackIntercept = void 0;
+const runtime_1 = __nccwpck_require__(8886);
+/**
+ * Creates a "stack" of of all interceptors specified in the given `RpcOptions`.
+ * Used by generated client implementations.
+ * @internal
+ */
+function stackIntercept(kind, transport, method, options, input) {
+ var _a, _b, _c, _d;
+ if (kind == "unary") {
+ let tail = (mtd, inp, opt) => transport.unary(mtd, inp, opt);
+ for (const curr of ((_a = options.interceptors) !== null && _a !== void 0 ? _a : []).filter(i => i.interceptUnary).reverse()) {
+ const next = tail;
+ tail = (mtd, inp, opt) => curr.interceptUnary(next, mtd, inp, opt);
+ }
+ return tail(method, input, options);
}
- } catch {
- // process in a callback to avoid throwing in the microtask queue
- } finally {
- Error.stackTraceLimit = stackTraceLimit
- }
- queueMicrotask(() => callback(new ResponseStatusCodeError(message, statusCode, headers, payload)))
+ if (kind == "serverStreaming") {
+ let tail = (mtd, inp, opt) => transport.serverStreaming(mtd, inp, opt);
+ for (const curr of ((_b = options.interceptors) !== null && _b !== void 0 ? _b : []).filter(i => i.interceptServerStreaming).reverse()) {
+ const next = tail;
+ tail = (mtd, inp, opt) => curr.interceptServerStreaming(next, mtd, inp, opt);
+ }
+ return tail(method, input, options);
+ }
+ if (kind == "clientStreaming") {
+ let tail = (mtd, opt) => transport.clientStreaming(mtd, opt);
+ for (const curr of ((_c = options.interceptors) !== null && _c !== void 0 ? _c : []).filter(i => i.interceptClientStreaming).reverse()) {
+ const next = tail;
+ tail = (mtd, opt) => curr.interceptClientStreaming(next, mtd, opt);
+ }
+ return tail(method, options);
+ }
+ if (kind == "duplex") {
+ let tail = (mtd, opt) => transport.duplex(mtd, opt);
+ for (const curr of ((_d = options.interceptors) !== null && _d !== void 0 ? _d : []).filter(i => i.interceptDuplex).reverse()) {
+ const next = tail;
+ tail = (mtd, opt) => curr.interceptDuplex(next, mtd, opt);
+ }
+ return tail(method, options);
+ }
+ runtime_1.assertNever(kind);
}
-
-const isContentTypeApplicationJson = (contentType) => {
- return (
- contentType.length > 15 &&
- contentType[11] === '/' &&
- contentType[0] === 'a' &&
- contentType[1] === 'p' &&
- contentType[2] === 'p' &&
- contentType[3] === 'l' &&
- contentType[4] === 'i' &&
- contentType[5] === 'c' &&
- contentType[6] === 'a' &&
- contentType[7] === 't' &&
- contentType[8] === 'i' &&
- contentType[9] === 'o' &&
- contentType[10] === 'n' &&
- contentType[12] === 'j' &&
- contentType[13] === 's' &&
- contentType[14] === 'o' &&
- contentType[15] === 'n'
- )
+exports.stackIntercept = stackIntercept;
+/**
+ * @deprecated replaced by `stackIntercept()`, still here to support older generated code
+ */
+function stackUnaryInterceptors(transport, method, input, options) {
+ return stackIntercept("unary", transport, method, options, input);
}
-
-const isContentTypeText = (contentType) => {
- return (
- contentType.length > 4 &&
- contentType[4] === '/' &&
- contentType[0] === 't' &&
- contentType[1] === 'e' &&
- contentType[2] === 'x' &&
- contentType[3] === 't'
- )
+exports.stackUnaryInterceptors = stackUnaryInterceptors;
+/**
+ * @deprecated replaced by `stackIntercept()`, still here to support older generated code
+ */
+function stackServerStreamingInterceptors(transport, method, input, options) {
+ return stackIntercept("serverStreaming", transport, method, options, input);
}
-
-module.exports = {
- getResolveErrorBodyCallback,
- isContentTypeApplicationJson,
- isContentTypeText
+exports.stackServerStreamingInterceptors = stackServerStreamingInterceptors;
+/**
+ * @deprecated replaced by `stackIntercept()`, still here to support older generated code
+ */
+function stackClientStreamingInterceptors(transport, method, options) {
+ return stackIntercept("clientStreaming", transport, method, options);
}
+exports.stackClientStreamingInterceptors = stackClientStreamingInterceptors;
+/**
+ * @deprecated replaced by `stackIntercept()`, still here to support older generated code
+ */
+function stackDuplexStreamingInterceptors(transport, method, options) {
+ return stackIntercept("duplex", transport, method, options);
+}
+exports.stackDuplexStreamingInterceptors = stackDuplexStreamingInterceptors;
/***/ }),
-/***/ 5005:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
+/***/ 8576:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-const net = __nccwpck_require__(7030)
-const assert = __nccwpck_require__(4589)
-const util = __nccwpck_require__(7375)
-const { InvalidArgumentError, ConnectTimeoutError } = __nccwpck_require__(2344)
-const timers = __nccwpck_require__(7256)
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.mergeRpcOptions = void 0;
+const runtime_1 = __nccwpck_require__(8886);
+/**
+ * Merges custom RPC options with defaults. Returns a new instance and keeps
+ * the "defaults" and the "options" unmodified.
+ *
+ * Merges `RpcMetadata` "meta", overwriting values from "defaults" with
+ * values from "options". Does not append values to existing entries.
+ *
+ * Merges "jsonOptions", including "jsonOptions.typeRegistry", by creating
+ * a new array that contains types from "options.jsonOptions.typeRegistry"
+ * first, then types from "defaults.jsonOptions.typeRegistry".
+ *
+ * Merges "binaryOptions".
+ *
+ * Merges "interceptors" by creating a new array that contains interceptors
+ * from "defaults" first, then interceptors from "options".
+ *
+ * Works with objects that extend `RpcOptions`, but only if the added
+ * properties are of type Date, primitive like string, boolean, or Array
+ * of primitives. If you have other property types, you have to merge them
+ * yourself.
+ */
+function mergeRpcOptions(defaults, options) {
+ if (!options)
+ return defaults;
+ let o = {};
+ copy(defaults, o);
+ copy(options, o);
+ for (let key of Object.keys(options)) {
+ let val = options[key];
+ switch (key) {
+ case "jsonOptions":
+ o.jsonOptions = runtime_1.mergeJsonOptions(defaults.jsonOptions, o.jsonOptions);
+ break;
+ case "binaryOptions":
+ o.binaryOptions = runtime_1.mergeBinaryOptions(defaults.binaryOptions, o.binaryOptions);
+ break;
+ case "meta":
+ o.meta = {};
+ copy(defaults.meta, o.meta);
+ copy(options.meta, o.meta);
+ break;
+ case "interceptors":
+ o.interceptors = defaults.interceptors ? defaults.interceptors.concat(val) : val.concat();
+ break;
+ }
+ }
+ return o;
+}
+exports.mergeRpcOptions = mergeRpcOptions;
+function copy(a, into) {
+ if (!a)
+ return;
+ let c = into;
+ for (let [k, v] of Object.entries(a)) {
+ if (v instanceof Date)
+ c[k] = new Date(v.getTime());
+ else if (Array.isArray(v))
+ c[k] = v.concat();
+ else
+ c[k] = v;
+ }
+}
-function noop () {}
-let tls // include tls conditionally since it is not always available
+/***/ }),
-// TODO: session re-use does not wait for the first
-// connection to resolve the session and might therefore
-// resolve the same servername multiple times even when
-// re-use is enabled.
+/***/ 2726:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-let SessionCache
-// FIXME: remove workaround when the Node bug is fixed
-// https://github.com/nodejs/node/issues/49344#issuecomment-1741776308
-if (global.FinalizationRegistry && !(process.env.NODE_V8_COVERAGE || process.env.UNDICI_NO_FG)) {
- SessionCache = class WeakSessionCache {
- constructor (maxCachedSessions) {
- this._maxCachedSessions = maxCachedSessions
- this._sessionCache = new Map()
- this._sessionRegistry = new global.FinalizationRegistry((key) => {
- if (this._sessionCache.size < this._maxCachedSessions) {
- return
- }
- const ref = this._sessionCache.get(key)
- if (ref !== undefined && ref.deref() === undefined) {
- this._sessionCache.delete(key)
- }
- })
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.RpcOutputStreamController = void 0;
+const deferred_1 = __nccwpck_require__(1409);
+const runtime_1 = __nccwpck_require__(8886);
+/**
+ * A `RpcOutputStream` that you control.
+ */
+class RpcOutputStreamController {
+ constructor() {
+ this._lis = {
+ nxt: [],
+ msg: [],
+ err: [],
+ cmp: [],
+ };
+ this._closed = false;
+ // --- RpcOutputStream async iterator API
+ // iterator state.
+ // is undefined when no iterator has been acquired yet.
+ this._itState = { q: [] };
}
-
- get (sessionKey) {
- const ref = this._sessionCache.get(sessionKey)
- return ref ? ref.deref() : null
+ // --- RpcOutputStream callback API
+ onNext(callback) {
+ return this.addLis(callback, this._lis.nxt);
}
-
- set (sessionKey, session) {
- if (this._maxCachedSessions === 0) {
- return
- }
-
- this._sessionCache.set(sessionKey, new WeakRef(session))
- this._sessionRegistry.register(session, sessionKey)
+ onMessage(callback) {
+ return this.addLis(callback, this._lis.msg);
}
- }
-} else {
- SessionCache = class SimpleSessionCache {
- constructor (maxCachedSessions) {
- this._maxCachedSessions = maxCachedSessions
- this._sessionCache = new Map()
+ onError(callback) {
+ return this.addLis(callback, this._lis.err);
}
-
- get (sessionKey) {
- return this._sessionCache.get(sessionKey)
+ onComplete(callback) {
+ return this.addLis(callback, this._lis.cmp);
}
-
- set (sessionKey, session) {
- if (this._maxCachedSessions === 0) {
- return
- }
-
- if (this._sessionCache.size >= this._maxCachedSessions) {
- // remove the oldest session
- const { value: oldestKey } = this._sessionCache.keys().next()
- this._sessionCache.delete(oldestKey)
- }
-
- this._sessionCache.set(sessionKey, session)
+ addLis(callback, list) {
+ list.push(callback);
+ return () => {
+ let i = list.indexOf(callback);
+ if (i >= 0)
+ list.splice(i, 1);
+ };
+ }
+ // remove all listeners
+ clearLis() {
+ for (let l of Object.values(this._lis))
+ l.splice(0, l.length);
+ }
+ // --- Controller API
+ /**
+ * Is this stream already closed by a completion or error?
+ */
+ get closed() {
+ return this._closed !== false;
+ }
+ /**
+ * Emit message, close with error, or close successfully, but only one
+ * at a time.
+ * Can be used to wrap a stream by using the other stream's `onNext`.
+ */
+ notifyNext(message, error, complete) {
+ runtime_1.assert((message ? 1 : 0) + (error ? 1 : 0) + (complete ? 1 : 0) <= 1, 'only one emission at a time');
+ if (message)
+ this.notifyMessage(message);
+ if (error)
+ this.notifyError(error);
+ if (complete)
+ this.notifyComplete();
+ }
+ /**
+ * Emits a new message. Throws if stream is closed.
+ *
+ * Triggers onNext and onMessage callbacks.
+ */
+ notifyMessage(message) {
+ runtime_1.assert(!this.closed, 'stream is closed');
+ this.pushIt({ value: message, done: false });
+ this._lis.msg.forEach(l => l(message));
+ this._lis.nxt.forEach(l => l(message, undefined, false));
+ }
+ /**
+ * Closes the stream with an error. Throws if stream is closed.
+ *
+ * Triggers onNext and onError callbacks.
+ */
+ notifyError(error) {
+ runtime_1.assert(!this.closed, 'stream is closed');
+ this._closed = error;
+ this.pushIt(error);
+ this._lis.err.forEach(l => l(error));
+ this._lis.nxt.forEach(l => l(undefined, error, false));
+ this.clearLis();
+ }
+ /**
+ * Closes the stream successfully. Throws if stream is closed.
+ *
+ * Triggers onNext and onComplete callbacks.
+ */
+ notifyComplete() {
+ runtime_1.assert(!this.closed, 'stream is closed');
+ this._closed = true;
+ this.pushIt({ value: null, done: true });
+ this._lis.cmp.forEach(l => l());
+ this._lis.nxt.forEach(l => l(undefined, undefined, true));
+ this.clearLis();
+ }
+ /**
+ * Creates an async iterator (that can be used with `for await {...}`)
+ * to consume the stream.
+ *
+ * Some things to note:
+ * - If an error occurs, the `for await` will throw it.
+ * - If an error occurred before the `for await` was started, `for await`
+ * will re-throw it.
+ * - If the stream is already complete, the `for await` will be empty.
+ * - If your `for await` consumes slower than the stream produces,
+ * for example because you are relaying messages in a slow operation,
+ * messages are queued.
+ */
+ [Symbol.asyncIterator]() {
+ // if we are closed, we are definitely not receiving any more messages.
+ // but we can't let the iterator get stuck. we want to either:
+ // a) finish the new iterator immediately, because we are completed
+ // b) reject the new iterator, because we errored
+ if (this._closed === true)
+ this.pushIt({ value: null, done: true });
+ else if (this._closed !== false)
+ this.pushIt(this._closed);
+ // the async iterator
+ return {
+ next: () => {
+ let state = this._itState;
+ runtime_1.assert(state, "bad state"); // if we don't have a state here, code is broken
+ // there should be no pending result.
+ // did the consumer call next() before we resolved our previous result promise?
+ runtime_1.assert(!state.p, "iterator contract broken");
+ // did we produce faster than the iterator consumed?
+ // return the oldest result from the queue.
+ let first = state.q.shift();
+ if (first)
+ return ("value" in first) ? Promise.resolve(first) : Promise.reject(first);
+ // we have no result ATM, but we promise one.
+ // as soon as we have a result, we must resolve promise.
+ state.p = new deferred_1.Deferred();
+ return state.p.promise;
+ },
+ };
+ }
+ // "push" a new iterator result.
+ // this either resolves a pending promise, or enqueues the result.
+ pushIt(result) {
+ let state = this._itState;
+ // is the consumer waiting for us?
+ if (state.p) {
+ // yes, consumer is waiting for this promise.
+ const p = state.p;
+ runtime_1.assert(p.state == deferred_1.DeferredState.PENDING, "iterator contract broken");
+ // resolve the promise
+ ("value" in result) ? p.resolve(result) : p.reject(result);
+ // must cleanup, otherwise iterator.next() would pick it up again.
+ delete state.p;
+ }
+ else {
+ // we are producing faster than the iterator consumes.
+ // push result onto queue.
+ state.q.push(result);
+ }
}
- }
}
+exports.RpcOutputStreamController = RpcOutputStreamController;
-function buildConnector ({ allowH2, maxCachedSessions, socketPath, timeout, session: customSession, ...opts }) {
- if (maxCachedSessions != null && (!Number.isInteger(maxCachedSessions) || maxCachedSessions < 0)) {
- throw new InvalidArgumentError('maxCachedSessions must be a positive integer or zero')
- }
- const options = { path: socketPath, ...opts }
- const sessionCache = new SessionCache(maxCachedSessions == null ? 100 : maxCachedSessions)
- timeout = timeout == null ? 10e3 : timeout
- allowH2 = allowH2 != null ? allowH2 : false
- return function connect ({ hostname, host, protocol, port, servername, localAddress, httpSocket }, callback) {
- let socket
- if (protocol === 'https:') {
- if (!tls) {
- tls = __nccwpck_require__(1692)
- }
- servername = servername || options.servername || util.getServerName(host) || null
+/***/ }),
- const sessionKey = servername || hostname
- assert(sessionKey)
+/***/ 3352:
+/***/ ((__unused_webpack_module, exports) => {
- const session = customSession || sessionCache.get(sessionKey) || null
- port = port || 443
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.ServerCallContextController = void 0;
+class ServerCallContextController {
+ constructor(method, headers, deadline, sendResponseHeadersFn, defaultStatus = { code: 'OK', detail: '' }) {
+ this._cancelled = false;
+ this._listeners = [];
+ this.method = method;
+ this.headers = headers;
+ this.deadline = deadline;
+ this.trailers = {};
+ this._sendRH = sendResponseHeadersFn;
+ this.status = defaultStatus;
+ }
+ /**
+ * Set the call cancelled.
+ *
+ * Invokes all callbacks registered with onCancel() and
+ * sets `cancelled = true`.
+ */
+ notifyCancelled() {
+ if (!this._cancelled) {
+ this._cancelled = true;
+ for (let l of this._listeners) {
+ l();
+ }
+ }
+ }
+ /**
+ * Send response headers.
+ */
+ sendResponseHeaders(data) {
+ this._sendRH(data);
+ }
+ /**
+ * Is the call cancelled?
+ *
+ * When the client closes the connection before the server
+ * is done, the call is cancelled.
+ *
+ * If you want to cancel a request on the server, throw a
+ * RpcError with the CANCELLED status code.
+ */
+ get cancelled() {
+ return this._cancelled;
+ }
+ /**
+ * Add a callback for cancellation.
+ */
+ onCancel(callback) {
+ const l = this._listeners;
+ l.push(callback);
+ return () => {
+ let i = l.indexOf(callback);
+ if (i >= 0)
+ l.splice(i, 1);
+ };
+ }
+}
+exports.ServerCallContextController = ServerCallContextController;
- socket = tls.connect({
- highWaterMark: 16384, // TLS in node can't have bigger HWM anyway...
- ...options,
- servername,
- session,
- localAddress,
- // TODO(HTTP/2): Add support for h2c
- ALPNProtocols: allowH2 ? ['http/1.1', 'h2'] : ['http/1.1'],
- socket: httpSocket, // upgrade socket connection
- port,
- host: hostname
- })
- socket
- .on('session', function (session) {
- // TODO (fix): Can a session become invalid once established? Don't think so?
- sessionCache.set(sessionKey, session)
- })
- } else {
- assert(!httpSocket, 'httpSocket can only be sent on TLS update')
+/***/ }),
- port = port || 80
+/***/ 6173:
+/***/ (function(__unused_webpack_module, exports) {
- socket = net.connect({
- highWaterMark: 64 * 1024, // Same as nodejs fs streams.
- ...options,
- localAddress,
- port,
- host: hostname
- })
- }
- // Set TCP keep alive options on the socket here instead of in connect() for the case of assigning the socket
- if (options.keepAlive == null || options.keepAlive) {
- const keepAliveInitialDelay = options.keepAliveInitialDelay === undefined ? 60e3 : options.keepAliveInitialDelay
- socket.setKeepAlive(true, keepAliveInitialDelay)
+var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.ServerStreamingCall = void 0;
+/**
+ * A server streaming RPC call. The client provides exactly one input message
+ * but the server may respond with 0, 1, or more messages.
+ */
+class ServerStreamingCall {
+ constructor(method, requestHeaders, request, headers, response, status, trailers) {
+ this.method = method;
+ this.requestHeaders = requestHeaders;
+ this.request = request;
+ this.headers = headers;
+ this.responses = response;
+ this.status = status;
+ this.trailers = trailers;
+ }
+ /**
+ * Instead of awaiting the response status and trailers, you can
+ * just as well await this call itself to receive the server outcome.
+ * You should first setup some listeners to the `request` to
+ * see the actual messages the server replied with.
+ */
+ then(onfulfilled, onrejected) {
+ return this.promiseFinished().then(value => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, reason => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason));
+ }
+ promiseFinished() {
+ return __awaiter(this, void 0, void 0, function* () {
+ let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]);
+ return {
+ method: this.method,
+ requestHeaders: this.requestHeaders,
+ request: this.request,
+ headers,
+ status,
+ trailers,
+ };
+ });
}
+}
+exports.ServerStreamingCall = ServerStreamingCall;
- const clearConnectTimeout = setupConnectTimeout(new WeakRef(socket), { timeout, hostname, port })
- socket
- .setNoDelay(true)
- .once(protocol === 'https:' ? 'secureConnect' : 'connect', function () {
- queueMicrotask(clearConnectTimeout)
+/***/ }),
- if (callback) {
- const cb = callback
- callback = null
- cb(null, this)
- }
- })
- .on('error', function (err) {
- queueMicrotask(clearConnectTimeout)
+/***/ 6892:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- if (callback) {
- const cb = callback
- callback = null
- cb(err)
- }
- })
- return socket
- }
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.ServiceType = void 0;
+const reflection_info_1 = __nccwpck_require__(2496);
+class ServiceType {
+ constructor(typeName, methods, options) {
+ this.typeName = typeName;
+ this.methods = methods.map(i => reflection_info_1.normalizeMethodInfo(i, this));
+ this.options = options !== null && options !== void 0 ? options : {};
+ }
}
+exports.ServiceType = ServiceType;
+
+
+/***/ }),
+
+/***/ 9122:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+
+var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.TestTransport = void 0;
+const rpc_error_1 = __nccwpck_require__(8636);
+const runtime_1 = __nccwpck_require__(8886);
+const rpc_output_stream_1 = __nccwpck_require__(2726);
+const rpc_options_1 = __nccwpck_require__(8576);
+const unary_call_1 = __nccwpck_require__(9288);
+const server_streaming_call_1 = __nccwpck_require__(6173);
+const client_streaming_call_1 = __nccwpck_require__(7889);
+const duplex_streaming_call_1 = __nccwpck_require__(6826);
/**
- * @param {WeakRef} socketWeakRef
- * @param {object} opts
- * @param {number} opts.timeout
- * @param {string} opts.hostname
- * @param {number} opts.port
- * @returns {() => void}
+ * Transport for testing.
*/
-const setupConnectTimeout = process.platform === 'win32'
- ? (socketWeakRef, opts) => {
- if (!opts.timeout) {
- return noop
- }
-
- let s1 = null
- let s2 = null
- const fastTimer = timers.setFastTimeout(() => {
- // setImmediate is added to make sure that we prioritize socket error events over timeouts
- s1 = setImmediate(() => {
- // Windows needs an extra setImmediate probably due to implementation differences in the socket logic
- s2 = setImmediate(() => onConnectTimeout(socketWeakRef.deref(), opts))
+class TestTransport {
+ /**
+ * Initialize with mock data. Omitted fields have default value.
+ */
+ constructor(data) {
+ /**
+ * Suppress warning / error about uncaught rejections of
+ * "status" and "trailers".
+ */
+ this.suppressUncaughtRejections = true;
+ this.headerDelay = 10;
+ this.responseDelay = 50;
+ this.betweenResponseDelay = 10;
+ this.afterResponseDelay = 10;
+ this.data = data !== null && data !== void 0 ? data : {};
+ }
+ /**
+ * Sent message(s) during the last operation.
+ */
+ get sentMessages() {
+ if (this.lastInput instanceof TestInputStream) {
+ return this.lastInput.sent;
+ }
+ else if (typeof this.lastInput == "object") {
+ return [this.lastInput.single];
+ }
+ return [];
+ }
+ /**
+ * Sending message(s) completed?
+ */
+ get sendComplete() {
+ if (this.lastInput instanceof TestInputStream) {
+ return this.lastInput.completed;
+ }
+ else if (typeof this.lastInput == "object") {
+ return true;
+ }
+ return false;
+ }
+ // Creates a promise for response headers from the mock data.
+ promiseHeaders() {
+ var _a;
+ const headers = (_a = this.data.headers) !== null && _a !== void 0 ? _a : TestTransport.defaultHeaders;
+ return headers instanceof rpc_error_1.RpcError
+ ? Promise.reject(headers)
+ : Promise.resolve(headers);
+ }
+ // Creates a promise for a single, valid, message from the mock data.
+ promiseSingleResponse(method) {
+ if (this.data.response instanceof rpc_error_1.RpcError) {
+ return Promise.reject(this.data.response);
+ }
+ let r;
+ if (Array.isArray(this.data.response)) {
+ runtime_1.assert(this.data.response.length > 0);
+ r = this.data.response[0];
+ }
+ else if (this.data.response !== undefined) {
+ r = this.data.response;
+ }
+ else {
+ r = method.O.create();
+ }
+ runtime_1.assert(method.O.is(r));
+ return Promise.resolve(r);
+ }
+ /**
+ * Pushes response messages from the mock data to the output stream.
+ * If an error response, status or trailers are mocked, the stream is
+ * closed with the respective error.
+ * Otherwise, stream is completed successfully.
+ *
+ * The returned promise resolves when the stream is closed. It should
+ * not reject. If it does, code is broken.
+ */
+ streamResponses(method, stream, abort) {
+ return __awaiter(this, void 0, void 0, function* () {
+ // normalize "data.response" into an array of valid output messages
+ const messages = [];
+ if (this.data.response === undefined) {
+ messages.push(method.O.create());
+ }
+ else if (Array.isArray(this.data.response)) {
+ for (let msg of this.data.response) {
+ runtime_1.assert(method.O.is(msg));
+ messages.push(msg);
+ }
+ }
+ else if (!(this.data.response instanceof rpc_error_1.RpcError)) {
+ runtime_1.assert(method.O.is(this.data.response));
+ messages.push(this.data.response);
+ }
+ // start the stream with an initial delay.
+ // if the request is cancelled, notify() error and exit.
+ try {
+ yield delay(this.responseDelay, abort)(undefined);
+ }
+ catch (error) {
+ stream.notifyError(error);
+ return;
+ }
+ // if error response was mocked, notify() error (stream is now closed with error) and exit.
+ if (this.data.response instanceof rpc_error_1.RpcError) {
+ stream.notifyError(this.data.response);
+ return;
+ }
+ // regular response messages were mocked. notify() them.
+ for (let msg of messages) {
+ stream.notifyMessage(msg);
+ // add a short delay between responses
+ // if the request is cancelled, notify() error and exit.
+ try {
+ yield delay(this.betweenResponseDelay, abort)(undefined);
+ }
+ catch (error) {
+ stream.notifyError(error);
+ return;
+ }
+ }
+ // error status was mocked, notify() error (stream is now closed with error) and exit.
+ if (this.data.status instanceof rpc_error_1.RpcError) {
+ stream.notifyError(this.data.status);
+ return;
+ }
+ // error trailers were mocked, notify() error (stream is now closed with error) and exit.
+ if (this.data.trailers instanceof rpc_error_1.RpcError) {
+ stream.notifyError(this.data.trailers);
+ return;
+ }
+ // stream completed successfully
+ stream.notifyComplete();
+ });
+ }
+ // Creates a promise for response status from the mock data.
+ promiseStatus() {
+ var _a;
+ const status = (_a = this.data.status) !== null && _a !== void 0 ? _a : TestTransport.defaultStatus;
+ return status instanceof rpc_error_1.RpcError
+ ? Promise.reject(status)
+ : Promise.resolve(status);
+ }
+ // Creates a promise for response trailers from the mock data.
+ promiseTrailers() {
+ var _a;
+ const trailers = (_a = this.data.trailers) !== null && _a !== void 0 ? _a : TestTransport.defaultTrailers;
+ return trailers instanceof rpc_error_1.RpcError
+ ? Promise.reject(trailers)
+ : Promise.resolve(trailers);
+ }
+ maybeSuppressUncaught(...promise) {
+ if (this.suppressUncaughtRejections) {
+ for (let p of promise) {
+ p.catch(() => {
+ });
+ }
+ }
+ }
+ mergeOptions(options) {
+ return rpc_options_1.mergeRpcOptions({}, options);
+ }
+ unary(method, input, options) {
+ var _a;
+ const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders()
+ .then(delay(this.headerDelay, options.abort)), responsePromise = headersPromise
+ .catch(_ => {
})
- }, opts.timeout)
- return () => {
- timers.clearFastTimeout(fastTimer)
- clearImmediate(s1)
- clearImmediate(s2)
- }
+ .then(delay(this.responseDelay, options.abort))
+ .then(_ => this.promiseSingleResponse(method)), statusPromise = responsePromise
+ .catch(_ => {
+ })
+ .then(delay(this.afterResponseDelay, options.abort))
+ .then(_ => this.promiseStatus()), trailersPromise = responsePromise
+ .catch(_ => {
+ })
+ .then(delay(this.afterResponseDelay, options.abort))
+ .then(_ => this.promiseTrailers());
+ this.maybeSuppressUncaught(statusPromise, trailersPromise);
+ this.lastInput = { single: input };
+ return new unary_call_1.UnaryCall(method, requestHeaders, input, headersPromise, responsePromise, statusPromise, trailersPromise);
}
- : (socketWeakRef, opts) => {
- if (!opts.timeout) {
- return noop
- }
-
- let s1 = null
- const fastTimer = timers.setFastTimeout(() => {
- // setImmediate is added to make sure that we prioritize socket error events over timeouts
- s1 = setImmediate(() => {
- onConnectTimeout(socketWeakRef.deref(), opts)
+ serverStreaming(method, input, options) {
+ var _a;
+ const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders()
+ .then(delay(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise
+ .then(delay(this.responseDelay, options.abort))
+ .catch(() => {
})
- }, opts.timeout)
- return () => {
- timers.clearFastTimeout(fastTimer)
- clearImmediate(s1)
- }
+ .then(() => this.streamResponses(method, outputStream, options.abort))
+ .then(delay(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise
+ .then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise
+ .then(() => this.promiseTrailers());
+ this.maybeSuppressUncaught(statusPromise, trailersPromise);
+ this.lastInput = { single: input };
+ return new server_streaming_call_1.ServerStreamingCall(method, requestHeaders, input, headersPromise, outputStream, statusPromise, trailersPromise);
+ }
+ clientStreaming(method, options) {
+ var _a;
+ const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders()
+ .then(delay(this.headerDelay, options.abort)), responsePromise = headersPromise
+ .catch(_ => {
+ })
+ .then(delay(this.responseDelay, options.abort))
+ .then(_ => this.promiseSingleResponse(method)), statusPromise = responsePromise
+ .catch(_ => {
+ })
+ .then(delay(this.afterResponseDelay, options.abort))
+ .then(_ => this.promiseStatus()), trailersPromise = responsePromise
+ .catch(_ => {
+ })
+ .then(delay(this.afterResponseDelay, options.abort))
+ .then(_ => this.promiseTrailers());
+ this.maybeSuppressUncaught(statusPromise, trailersPromise);
+ this.lastInput = new TestInputStream(this.data, options.abort);
+ return new client_streaming_call_1.ClientStreamingCall(method, requestHeaders, this.lastInput, headersPromise, responsePromise, statusPromise, trailersPromise);
+ }
+ duplex(method, options) {
+ var _a;
+ const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders()
+ .then(delay(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise
+ .then(delay(this.responseDelay, options.abort))
+ .catch(() => {
+ })
+ .then(() => this.streamResponses(method, outputStream, options.abort))
+ .then(delay(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise
+ .then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise
+ .then(() => this.promiseTrailers());
+ this.maybeSuppressUncaught(statusPromise, trailersPromise);
+ this.lastInput = new TestInputStream(this.data, options.abort);
+ return new duplex_streaming_call_1.DuplexStreamingCall(method, requestHeaders, this.lastInput, headersPromise, outputStream, statusPromise, trailersPromise);
+ }
+}
+exports.TestTransport = TestTransport;
+TestTransport.defaultHeaders = {
+ responseHeader: "test"
+};
+TestTransport.defaultStatus = {
+ code: "OK", detail: "all good"
+};
+TestTransport.defaultTrailers = {
+ responseTrailer: "test"
+};
+function delay(ms, abort) {
+ return (v) => new Promise((resolve, reject) => {
+ if (abort === null || abort === void 0 ? void 0 : abort.aborted) {
+ reject(new rpc_error_1.RpcError("user cancel", "CANCELLED"));
+ }
+ else {
+ const id = setTimeout(() => resolve(v), ms);
+ if (abort) {
+ abort.addEventListener("abort", ev => {
+ clearTimeout(id);
+ reject(new rpc_error_1.RpcError("user cancel", "CANCELLED"));
+ });
+ }
+ }
+ });
+}
+class TestInputStream {
+ constructor(data, abort) {
+ this._completed = false;
+ this._sent = [];
+ this.data = data;
+ this.abort = abort;
+ }
+ get sent() {
+ return this._sent;
+ }
+ get completed() {
+ return this._completed;
+ }
+ send(message) {
+ if (this.data.inputMessage instanceof rpc_error_1.RpcError) {
+ return Promise.reject(this.data.inputMessage);
+ }
+ const delayMs = this.data.inputMessage === undefined
+ ? 10
+ : this.data.inputMessage;
+ return Promise.resolve(undefined)
+ .then(() => {
+ this._sent.push(message);
+ })
+ .then(delay(delayMs, this.abort));
+ }
+ complete() {
+ if (this.data.inputComplete instanceof rpc_error_1.RpcError) {
+ return Promise.reject(this.data.inputComplete);
+ }
+ const delayMs = this.data.inputComplete === undefined
+ ? 10
+ : this.data.inputComplete;
+ return Promise.resolve(undefined)
+ .then(() => {
+ this._completed = true;
+ })
+ .then(delay(delayMs, this.abort));
}
-
-/**
- * @param {net.Socket} socket
- * @param {object} opts
- * @param {number} opts.timeout
- * @param {string} opts.hostname
- * @param {number} opts.port
- */
-function onConnectTimeout (socket, opts) {
- // The socket could be already garbage collected
- if (socket == null) {
- return
- }
-
- let message = 'Connect Timeout Error'
- if (Array.isArray(socket.autoSelectFamilyAttemptedAddresses)) {
- message += ` (attempted addresses: ${socket.autoSelectFamilyAttemptedAddresses.join(', ')},`
- } else {
- message += ` (attempted address: ${opts.hostname}:${opts.port},`
- }
-
- message += ` timeout: ${opts.timeout}ms)`
-
- util.destroy(socket, new ConnectTimeoutError(message))
}
-
-module.exports = buildConnector
/***/ }),
-/***/ 4914:
-/***/ ((module) => {
-
-
+/***/ 9288:
+/***/ (function(__unused_webpack_module, exports) {
-/** @type {Record} */
-const headerNameLowerCasedRecord = {}
-// https://developer.mozilla.org/docs/Web/HTTP/Headers
-const wellknownHeaderNames = [
- 'Accept',
- 'Accept-Encoding',
- 'Accept-Language',
- 'Accept-Ranges',
- 'Access-Control-Allow-Credentials',
- 'Access-Control-Allow-Headers',
- 'Access-Control-Allow-Methods',
- 'Access-Control-Allow-Origin',
- 'Access-Control-Expose-Headers',
- 'Access-Control-Max-Age',
- 'Access-Control-Request-Headers',
- 'Access-Control-Request-Method',
- 'Age',
- 'Allow',
- 'Alt-Svc',
- 'Alt-Used',
- 'Authorization',
- 'Cache-Control',
- 'Clear-Site-Data',
- 'Connection',
- 'Content-Disposition',
- 'Content-Encoding',
- 'Content-Language',
- 'Content-Length',
- 'Content-Location',
- 'Content-Range',
- 'Content-Security-Policy',
- 'Content-Security-Policy-Report-Only',
- 'Content-Type',
- 'Cookie',
- 'Cross-Origin-Embedder-Policy',
- 'Cross-Origin-Opener-Policy',
- 'Cross-Origin-Resource-Policy',
- 'Date',
- 'Device-Memory',
- 'Downlink',
- 'ECT',
- 'ETag',
- 'Expect',
- 'Expect-CT',
- 'Expires',
- 'Forwarded',
- 'From',
- 'Host',
- 'If-Match',
- 'If-Modified-Since',
- 'If-None-Match',
- 'If-Range',
- 'If-Unmodified-Since',
- 'Keep-Alive',
- 'Last-Modified',
- 'Link',
- 'Location',
- 'Max-Forwards',
- 'Origin',
- 'Permissions-Policy',
- 'Pragma',
- 'Proxy-Authenticate',
- 'Proxy-Authorization',
- 'RTT',
- 'Range',
- 'Referer',
- 'Referrer-Policy',
- 'Refresh',
- 'Retry-After',
- 'Sec-WebSocket-Accept',
- 'Sec-WebSocket-Extensions',
- 'Sec-WebSocket-Key',
- 'Sec-WebSocket-Protocol',
- 'Sec-WebSocket-Version',
- 'Server',
- 'Server-Timing',
- 'Service-Worker-Allowed',
- 'Service-Worker-Navigation-Preload',
- 'Set-Cookie',
- 'SourceMap',
- 'Strict-Transport-Security',
- 'Supports-Loading-Mode',
- 'TE',
- 'Timing-Allow-Origin',
- 'Trailer',
- 'Transfer-Encoding',
- 'Upgrade',
- 'Upgrade-Insecure-Requests',
- 'User-Agent',
- 'Vary',
- 'Via',
- 'WWW-Authenticate',
- 'X-Content-Type-Options',
- 'X-DNS-Prefetch-Control',
- 'X-Frame-Options',
- 'X-Permitted-Cross-Domain-Policies',
- 'X-Powered-By',
- 'X-Requested-With',
- 'X-XSS-Protection'
-]
-
-for (let i = 0; i < wellknownHeaderNames.length; ++i) {
- const key = wellknownHeaderNames[i]
- const lowerCasedKey = key.toLowerCase()
- headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] =
- lowerCasedKey
-}
-
-// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`.
-Object.setPrototypeOf(headerNameLowerCasedRecord, null)
-
-module.exports = {
- wellknownHeaderNames,
- headerNameLowerCasedRecord
+var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.UnaryCall = void 0;
+/**
+ * A unary RPC call. Unary means there is exactly one input message and
+ * exactly one output message unless an error occurred.
+ */
+class UnaryCall {
+ constructor(method, requestHeaders, request, headers, response, status, trailers) {
+ this.method = method;
+ this.requestHeaders = requestHeaders;
+ this.request = request;
+ this.headers = headers;
+ this.response = response;
+ this.status = status;
+ this.trailers = trailers;
+ }
+ /**
+ * If you are only interested in the final outcome of this call,
+ * you can await it to receive a `FinishedUnaryCall`.
+ */
+ then(onfulfilled, onrejected) {
+ return this.promiseFinished().then(value => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, reason => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason));
+ }
+ promiseFinished() {
+ return __awaiter(this, void 0, void 0, function* () {
+ let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]);
+ return {
+ method: this.method,
+ requestHeaders: this.requestHeaders,
+ request: this.request,
+ headers,
+ response,
+ status,
+ trailers
+ };
+ });
+ }
}
+exports.UnaryCall = UnaryCall;
/***/ }),
-/***/ 4567:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
+/***/ 8602:
+/***/ ((__unused_webpack_module, exports) => {
-const diagnosticsChannel = __nccwpck_require__(3053)
-const util = __nccwpck_require__(7975)
-const undiciDebugLog = util.debuglog('undici')
-const fetchDebuglog = util.debuglog('fetch')
-const websocketDebuglog = util.debuglog('websocket')
-let isClientSet = false
-const channels = {
- // Client
- beforeConnect: diagnosticsChannel.channel('undici:client:beforeConnect'),
- connected: diagnosticsChannel.channel('undici:client:connected'),
- connectError: diagnosticsChannel.channel('undici:client:connectError'),
- sendHeaders: diagnosticsChannel.channel('undici:client:sendHeaders'),
- // Request
- create: diagnosticsChannel.channel('undici:request:create'),
- bodySent: diagnosticsChannel.channel('undici:request:bodySent'),
- headers: diagnosticsChannel.channel('undici:request:headers'),
- trailers: diagnosticsChannel.channel('undici:request:trailers'),
- error: diagnosticsChannel.channel('undici:request:error'),
- // WebSocket
- open: diagnosticsChannel.channel('undici:websocket:open'),
- close: diagnosticsChannel.channel('undici:websocket:close'),
- socketError: diagnosticsChannel.channel('undici:websocket:socket_error'),
- ping: diagnosticsChannel.channel('undici:websocket:ping'),
- pong: diagnosticsChannel.channel('undici:websocket:pong')
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.assertFloat32 = exports.assertUInt32 = exports.assertInt32 = exports.assertNever = exports.assert = void 0;
+/**
+ * assert that condition is true or throw error (with message)
+ */
+function assert(condition, msg) {
+ if (!condition) {
+ throw new Error(msg);
+ }
}
-
-if (undiciDebugLog.enabled || fetchDebuglog.enabled) {
- const debuglog = fetchDebuglog.enabled ? fetchDebuglog : undiciDebugLog
-
- // Track all Client events
- diagnosticsChannel.channel('undici:client:beforeConnect').subscribe(evt => {
- const {
- connectParams: { version, protocol, port, host }
- } = evt
- debuglog(
- 'connecting to %s using %s%s',
- `${host}${port ? `:${port}` : ''}`,
- protocol,
- version
- )
- })
-
- diagnosticsChannel.channel('undici:client:connected').subscribe(evt => {
- const {
- connectParams: { version, protocol, port, host }
- } = evt
- debuglog(
- 'connected to %s using %s%s',
- `${host}${port ? `:${port}` : ''}`,
- protocol,
- version
- )
- })
-
- diagnosticsChannel.channel('undici:client:connectError').subscribe(evt => {
- const {
- connectParams: { version, protocol, port, host },
- error
- } = evt
- debuglog(
- 'connection to %s using %s%s errored - %s',
- `${host}${port ? `:${port}` : ''}`,
- protocol,
- version,
- error.message
- )
- })
-
- diagnosticsChannel.channel('undici:client:sendHeaders').subscribe(evt => {
- const {
- request: { method, path, origin }
- } = evt
- debuglog('sending request to %s %s/%s', method, origin, path)
- })
-
- // Track Request events
- diagnosticsChannel.channel('undici:request:headers').subscribe(evt => {
- const {
- request: { method, path, origin },
- response: { statusCode }
- } = evt
- debuglog(
- 'received response to %s %s/%s - HTTP %d',
- method,
- origin,
- path,
- statusCode
- )
- })
-
- diagnosticsChannel.channel('undici:request:trailers').subscribe(evt => {
- const {
- request: { method, path, origin }
- } = evt
- debuglog('trailers received from %s %s/%s', method, origin, path)
- })
-
- diagnosticsChannel.channel('undici:request:error').subscribe(evt => {
- const {
- request: { method, path, origin },
- error
- } = evt
- debuglog(
- 'request to %s %s/%s errored - %s',
- method,
- origin,
- path,
- error.message
- )
- })
-
- isClientSet = true
+exports.assert = assert;
+/**
+ * assert that value cannot exist = type `never`. throw runtime error if it does.
+ */
+function assertNever(value, msg) {
+ throw new Error(msg !== null && msg !== void 0 ? msg : 'Unexpected object: ' + value);
}
+exports.assertNever = assertNever;
+const FLOAT32_MAX = 3.4028234663852886e+38, FLOAT32_MIN = -3.4028234663852886e+38, UINT32_MAX = 0xFFFFFFFF, INT32_MAX = 0X7FFFFFFF, INT32_MIN = -0X80000000;
+function assertInt32(arg) {
+ if (typeof arg !== "number")
+ throw new Error('invalid int 32: ' + typeof arg);
+ if (!Number.isInteger(arg) || arg > INT32_MAX || arg < INT32_MIN)
+ throw new Error('invalid int 32: ' + arg);
+}
+exports.assertInt32 = assertInt32;
+function assertUInt32(arg) {
+ if (typeof arg !== "number")
+ throw new Error('invalid uint 32: ' + typeof arg);
+ if (!Number.isInteger(arg) || arg > UINT32_MAX || arg < 0)
+ throw new Error('invalid uint 32: ' + arg);
+}
+exports.assertUInt32 = assertUInt32;
+function assertFloat32(arg) {
+ if (typeof arg !== "number")
+ throw new Error('invalid float 32: ' + typeof arg);
+ if (!Number.isFinite(arg))
+ return;
+ if (arg > FLOAT32_MAX || arg < FLOAT32_MIN)
+ throw new Error('invalid float 32: ' + arg);
+}
+exports.assertFloat32 = assertFloat32;
-if (websocketDebuglog.enabled) {
- if (!isClientSet) {
- const debuglog = undiciDebugLog.enabled ? undiciDebugLog : websocketDebuglog
- diagnosticsChannel.channel('undici:client:beforeConnect').subscribe(evt => {
- const {
- connectParams: { version, protocol, port, host }
- } = evt
- debuglog(
- 'connecting to %s%s using %s%s',
- host,
- port ? `:${port}` : '',
- protocol,
- version
- )
- })
-
- diagnosticsChannel.channel('undici:client:connected').subscribe(evt => {
- const {
- connectParams: { version, protocol, port, host }
- } = evt
- debuglog(
- 'connected to %s%s using %s%s',
- host,
- port ? `:${port}` : '',
- protocol,
- version
- )
- })
-
- diagnosticsChannel.channel('undici:client:connectError').subscribe(evt => {
- const {
- connectParams: { version, protocol, port, host },
- error
- } = evt
- debuglog(
- 'connection to %s%s using %s%s errored - %s',
- host,
- port ? `:${port}` : '',
- protocol,
- version,
- error.message
- )
- })
-
- diagnosticsChannel.channel('undici:client:sendHeaders').subscribe(evt => {
- const {
- request: { method, path, origin }
- } = evt
- debuglog('sending request to %s %s/%s', method, origin, path)
- })
- }
-
- // Track all WebSocket events
- diagnosticsChannel.channel('undici:websocket:open').subscribe(evt => {
- const {
- address: { address, port }
- } = evt
- websocketDebuglog('connection opened %s%s', address, port ? `:${port}` : '')
- })
- diagnosticsChannel.channel('undici:websocket:close').subscribe(evt => {
- const { websocket, code, reason } = evt
- websocketDebuglog(
- 'closed connection to %s - %s %s',
- websocket.url,
- code,
- reason
- )
- })
+/***/ }),
- diagnosticsChannel.channel('undici:websocket:socket_error').subscribe(err => {
- websocketDebuglog('connection errored - %s', err.message)
- })
+/***/ 6335:
+/***/ ((__unused_webpack_module, exports) => {
- diagnosticsChannel.channel('undici:websocket:ping').subscribe(evt => {
- websocketDebuglog('ping received')
- })
- diagnosticsChannel.channel('undici:websocket:pong').subscribe(evt => {
- websocketDebuglog('pong received')
- })
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.base64encode = exports.base64decode = void 0;
+// lookup table from base64 character to byte
+let encTable = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
+// lookup table from base64 character *code* to byte because lookup by number is fast
+let decTable = [];
+for (let i = 0; i < encTable.length; i++)
+ decTable[encTable[i].charCodeAt(0)] = i;
+// support base64url variants
+decTable["-".charCodeAt(0)] = encTable.indexOf("+");
+decTable["_".charCodeAt(0)] = encTable.indexOf("/");
+/**
+ * Decodes a base64 string to a byte array.
+ *
+ * - ignores white-space, including line breaks and tabs
+ * - allows inner padding (can decode concatenated base64 strings)
+ * - does not require padding
+ * - understands base64url encoding:
+ * "-" instead of "+",
+ * "_" instead of "/",
+ * no padding
+ */
+function base64decode(base64Str) {
+ // estimate byte size, not accounting for inner padding and whitespace
+ let es = base64Str.length * 3 / 4;
+ // if (es % 3 !== 0)
+ // throw new Error('invalid base64 string');
+ if (base64Str[base64Str.length - 2] == '=')
+ es -= 2;
+ else if (base64Str[base64Str.length - 1] == '=')
+ es -= 1;
+ let bytes = new Uint8Array(es), bytePos = 0, // position in byte array
+ groupPos = 0, // position in base64 group
+ b, // current byte
+ p = 0 // previous byte
+ ;
+ for (let i = 0; i < base64Str.length; i++) {
+ b = decTable[base64Str.charCodeAt(i)];
+ if (b === undefined) {
+ // noinspection FallThroughInSwitchStatementJS
+ switch (base64Str[i]) {
+ case '=':
+ groupPos = 0; // reset state when padding found
+ case '\n':
+ case '\r':
+ case '\t':
+ case ' ':
+ continue; // skip white-space, and padding
+ default:
+ throw Error(`invalid base64 string.`);
+ }
+ }
+ switch (groupPos) {
+ case 0:
+ p = b;
+ groupPos = 1;
+ break;
+ case 1:
+ bytes[bytePos++] = p << 2 | (b & 48) >> 4;
+ p = b;
+ groupPos = 2;
+ break;
+ case 2:
+ bytes[bytePos++] = (p & 15) << 4 | (b & 60) >> 2;
+ p = b;
+ groupPos = 3;
+ break;
+ case 3:
+ bytes[bytePos++] = (p & 3) << 6 | b;
+ groupPos = 0;
+ break;
+ }
+ }
+ if (groupPos == 1)
+ throw Error(`invalid base64 string.`);
+ return bytes.subarray(0, bytePos);
}
-
-module.exports = {
- channels
+exports.base64decode = base64decode;
+/**
+ * Encodes a byte array to a base64 string.
+ * Adds padding at the end.
+ * Does not insert newlines.
+ */
+function base64encode(bytes) {
+ let base64 = '', groupPos = 0, // position in base64 group
+ b, // current byte
+ p = 0; // carry over from previous byte
+ for (let i = 0; i < bytes.length; i++) {
+ b = bytes[i];
+ switch (groupPos) {
+ case 0:
+ base64 += encTable[b >> 2];
+ p = (b & 3) << 4;
+ groupPos = 1;
+ break;
+ case 1:
+ base64 += encTable[p | b >> 4];
+ p = (b & 15) << 2;
+ groupPos = 2;
+ break;
+ case 2:
+ base64 += encTable[p | b >> 6];
+ base64 += encTable[b & 63];
+ groupPos = 0;
+ break;
+ }
+ }
+ // padding required?
+ if (groupPos) {
+ base64 += encTable[p];
+ base64 += '=';
+ if (groupPos == 1)
+ base64 += '=';
+ }
+ return base64;
}
+exports.base64encode = base64encode;
/***/ }),
-/***/ 2344:
-/***/ ((module) => {
-
-
-
-const kUndiciError = Symbol.for('undici.error.UND_ERR')
-class UndiciError extends Error {
- constructor (message) {
- super(message)
- this.name = 'UndiciError'
- this.code = 'UND_ERR'
- }
-
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kUndiciError] === true
- }
+/***/ 4816:
+/***/ ((__unused_webpack_module, exports) => {
- [kUndiciError] = true
-}
-const kConnectTimeoutError = Symbol.for('undici.error.UND_ERR_CONNECT_TIMEOUT')
-class ConnectTimeoutError extends UndiciError {
- constructor (message) {
- super(message)
- this.name = 'ConnectTimeoutError'
- this.message = message || 'Connect Timeout Error'
- this.code = 'UND_ERR_CONNECT_TIMEOUT'
- }
-
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kConnectTimeoutError] === true
- }
-
- [kConnectTimeoutError] = true
-}
-
-const kHeadersTimeoutError = Symbol.for('undici.error.UND_ERR_HEADERS_TIMEOUT')
-class HeadersTimeoutError extends UndiciError {
- constructor (message) {
- super(message)
- this.name = 'HeadersTimeoutError'
- this.message = message || 'Headers Timeout Error'
- this.code = 'UND_ERR_HEADERS_TIMEOUT'
- }
-
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kHeadersTimeoutError] === true
- }
-
- [kHeadersTimeoutError] = true
-}
-
-const kHeadersOverflowError = Symbol.for('undici.error.UND_ERR_HEADERS_OVERFLOW')
-class HeadersOverflowError extends UndiciError {
- constructor (message) {
- super(message)
- this.name = 'HeadersOverflowError'
- this.message = message || 'Headers Overflow Error'
- this.code = 'UND_ERR_HEADERS_OVERFLOW'
- }
-
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kHeadersOverflowError] === true
- }
-
- [kHeadersOverflowError] = true
-}
-
-const kBodyTimeoutError = Symbol.for('undici.error.UND_ERR_BODY_TIMEOUT')
-class BodyTimeoutError extends UndiciError {
- constructor (message) {
- super(message)
- this.name = 'BodyTimeoutError'
- this.message = message || 'Body Timeout Error'
- this.code = 'UND_ERR_BODY_TIMEOUT'
- }
-
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kBodyTimeoutError] === true
- }
-
- [kBodyTimeoutError] = true
-}
-
-const kResponseStatusCodeError = Symbol.for('undici.error.UND_ERR_RESPONSE_STATUS_CODE')
-class ResponseStatusCodeError extends UndiciError {
- constructor (message, statusCode, headers, body) {
- super(message)
- this.name = 'ResponseStatusCodeError'
- this.message = message || 'Response Status Code Error'
- this.code = 'UND_ERR_RESPONSE_STATUS_CODE'
- this.body = body
- this.status = statusCode
- this.statusCode = statusCode
- this.headers = headers
- }
-
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kResponseStatusCodeError] === true
- }
-
- [kResponseStatusCodeError] = true
-}
-
-const kInvalidArgumentError = Symbol.for('undici.error.UND_ERR_INVALID_ARG')
-class InvalidArgumentError extends UndiciError {
- constructor (message) {
- super(message)
- this.name = 'InvalidArgumentError'
- this.message = message || 'Invalid Argument Error'
- this.code = 'UND_ERR_INVALID_ARG'
- }
-
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kInvalidArgumentError] === true
- }
-
- [kInvalidArgumentError] = true
-}
-
-const kInvalidReturnValueError = Symbol.for('undici.error.UND_ERR_INVALID_RETURN_VALUE')
-class InvalidReturnValueError extends UndiciError {
- constructor (message) {
- super(message)
- this.name = 'InvalidReturnValueError'
- this.message = message || 'Invalid Return Value Error'
- this.code = 'UND_ERR_INVALID_RETURN_VALUE'
- }
-
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kInvalidReturnValueError] === true
- }
-
- [kInvalidReturnValueError] = true
-}
-
-const kAbortError = Symbol.for('undici.error.UND_ERR_ABORT')
-class AbortError extends UndiciError {
- constructor (message) {
- super(message)
- this.name = 'AbortError'
- this.message = message || 'The operation was aborted'
- this.code = 'UND_ERR_ABORT'
- }
-
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kAbortError] === true
- }
-
- [kAbortError] = true
-}
-
-const kRequestAbortedError = Symbol.for('undici.error.UND_ERR_ABORTED')
-class RequestAbortedError extends AbortError {
- constructor (message) {
- super(message)
- this.name = 'AbortError'
- this.message = message || 'Request aborted'
- this.code = 'UND_ERR_ABORTED'
- }
-
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kRequestAbortedError] === true
- }
-
- [kRequestAbortedError] = true
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.WireType = exports.mergeBinaryOptions = exports.UnknownFieldHandler = void 0;
+/**
+ * This handler implements the default behaviour for unknown fields.
+ * When reading data, unknown fields are stored on the message, in a
+ * symbol property.
+ * When writing data, the symbol property is queried and unknown fields
+ * are serialized into the output again.
+ */
+var UnknownFieldHandler;
+(function (UnknownFieldHandler) {
+ /**
+ * The symbol used to store unknown fields for a message.
+ * The property must conform to `UnknownFieldContainer`.
+ */
+ UnknownFieldHandler.symbol = Symbol.for("protobuf-ts/unknown");
+ /**
+ * Store an unknown field during binary read directly on the message.
+ * This method is compatible with `BinaryReadOptions.readUnknownField`.
+ */
+ UnknownFieldHandler.onRead = (typeName, message, fieldNo, wireType, data) => {
+ let container = is(message) ? message[UnknownFieldHandler.symbol] : message[UnknownFieldHandler.symbol] = [];
+ container.push({ no: fieldNo, wireType, data });
+ };
+ /**
+ * Write unknown fields stored for the message to the writer.
+ * This method is compatible with `BinaryWriteOptions.writeUnknownFields`.
+ */
+ UnknownFieldHandler.onWrite = (typeName, message, writer) => {
+ for (let { no, wireType, data } of UnknownFieldHandler.list(message))
+ writer.tag(no, wireType).raw(data);
+ };
+ /**
+ * List unknown fields stored for the message.
+ * Note that there may be multiples fields with the same number.
+ */
+ UnknownFieldHandler.list = (message, fieldNo) => {
+ if (is(message)) {
+ let all = message[UnknownFieldHandler.symbol];
+ return fieldNo ? all.filter(uf => uf.no == fieldNo) : all;
+ }
+ return [];
+ };
+ /**
+ * Returns the last unknown field by field number.
+ */
+ UnknownFieldHandler.last = (message, fieldNo) => UnknownFieldHandler.list(message, fieldNo).slice(-1)[0];
+ const is = (message) => message && Array.isArray(message[UnknownFieldHandler.symbol]);
+})(UnknownFieldHandler = exports.UnknownFieldHandler || (exports.UnknownFieldHandler = {}));
+/**
+ * Merges binary write or read options. Later values override earlier values.
+ */
+function mergeBinaryOptions(a, b) {
+ return Object.assign(Object.assign({}, a), b);
}
+exports.mergeBinaryOptions = mergeBinaryOptions;
+/**
+ * Protobuf binary format wire types.
+ *
+ * A wire type provides just enough information to find the length of the
+ * following value.
+ *
+ * See https://developers.google.com/protocol-buffers/docs/encoding#structure
+ */
+var WireType;
+(function (WireType) {
+ /**
+ * Used for int32, int64, uint32, uint64, sint32, sint64, bool, enum
+ */
+ WireType[WireType["Varint"] = 0] = "Varint";
+ /**
+ * Used for fixed64, sfixed64, double.
+ * Always 8 bytes with little-endian byte order.
+ */
+ WireType[WireType["Bit64"] = 1] = "Bit64";
+ /**
+ * Used for string, bytes, embedded messages, packed repeated fields
+ *
+ * Only repeated numeric types (types which use the varint, 32-bit,
+ * or 64-bit wire types) can be packed. In proto3, such fields are
+ * packed by default.
+ */
+ WireType[WireType["LengthDelimited"] = 2] = "LengthDelimited";
+ /**
+ * Used for groups
+ * @deprecated
+ */
+ WireType[WireType["StartGroup"] = 3] = "StartGroup";
+ /**
+ * Used for groups
+ * @deprecated
+ */
+ WireType[WireType["EndGroup"] = 4] = "EndGroup";
+ /**
+ * Used for fixed32, sfixed32, float.
+ * Always 4 bytes with little-endian byte order.
+ */
+ WireType[WireType["Bit32"] = 5] = "Bit32";
+})(WireType = exports.WireType || (exports.WireType = {}));
-const kInformationalError = Symbol.for('undici.error.UND_ERR_INFO')
-class InformationalError extends UndiciError {
- constructor (message) {
- super(message)
- this.name = 'InformationalError'
- this.message = message || 'Request information'
- this.code = 'UND_ERR_INFO'
- }
-
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kInformationalError] === true
- }
- [kInformationalError] = true
-}
+/***/ }),
-const kRequestContentLengthMismatchError = Symbol.for('undici.error.UND_ERR_REQ_CONTENT_LENGTH_MISMATCH')
-class RequestContentLengthMismatchError extends UndiciError {
- constructor (message) {
- super(message)
- this.name = 'RequestContentLengthMismatchError'
- this.message = message || 'Request body length does not match content-length header'
- this.code = 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH'
- }
+/***/ 2889:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kRequestContentLengthMismatchError] === true
- }
- [kRequestContentLengthMismatchError] = true
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.BinaryReader = exports.binaryReadOptions = void 0;
+const binary_format_contract_1 = __nccwpck_require__(4816);
+const pb_long_1 = __nccwpck_require__(1753);
+const goog_varint_1 = __nccwpck_require__(3223);
+const defaultsRead = {
+ readUnknownField: true,
+ readerFactory: bytes => new BinaryReader(bytes),
+};
+/**
+ * Make options for reading binary data form partial options.
+ */
+function binaryReadOptions(options) {
+ return options ? Object.assign(Object.assign({}, defaultsRead), options) : defaultsRead;
}
-
-const kResponseContentLengthMismatchError = Symbol.for('undici.error.UND_ERR_RES_CONTENT_LENGTH_MISMATCH')
-class ResponseContentLengthMismatchError extends UndiciError {
- constructor (message) {
- super(message)
- this.name = 'ResponseContentLengthMismatchError'
- this.message = message || 'Response body length does not match content-length header'
- this.code = 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH'
- }
-
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kResponseContentLengthMismatchError] === true
- }
-
- [kResponseContentLengthMismatchError] = true
+exports.binaryReadOptions = binaryReadOptions;
+class BinaryReader {
+ constructor(buf, textDecoder) {
+ this.varint64 = goog_varint_1.varint64read; // dirty cast for `this`
+ /**
+ * Read a `uint32` field, an unsigned 32 bit varint.
+ */
+ this.uint32 = goog_varint_1.varint32read; // dirty cast for `this` and access to protected `buf`
+ this.buf = buf;
+ this.len = buf.length;
+ this.pos = 0;
+ this.view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
+ this.textDecoder = textDecoder !== null && textDecoder !== void 0 ? textDecoder : new TextDecoder("utf-8", {
+ fatal: true,
+ ignoreBOM: true,
+ });
+ }
+ /**
+ * Reads a tag - field number and wire type.
+ */
+ tag() {
+ let tag = this.uint32(), fieldNo = tag >>> 3, wireType = tag & 7;
+ if (fieldNo <= 0 || wireType < 0 || wireType > 5)
+ throw new Error("illegal tag: field no " + fieldNo + " wire type " + wireType);
+ return [fieldNo, wireType];
+ }
+ /**
+ * Skip one element on the wire and return the skipped data.
+ * Supports WireType.StartGroup since v2.0.0-alpha.23.
+ */
+ skip(wireType) {
+ let start = this.pos;
+ // noinspection FallThroughInSwitchStatementJS
+ switch (wireType) {
+ case binary_format_contract_1.WireType.Varint:
+ while (this.buf[this.pos++] & 0x80) {
+ // ignore
+ }
+ break;
+ case binary_format_contract_1.WireType.Bit64:
+ this.pos += 4;
+ case binary_format_contract_1.WireType.Bit32:
+ this.pos += 4;
+ break;
+ case binary_format_contract_1.WireType.LengthDelimited:
+ let len = this.uint32();
+ this.pos += len;
+ break;
+ case binary_format_contract_1.WireType.StartGroup:
+ // From descriptor.proto: Group type is deprecated, not supported in proto3.
+ // But we must still be able to parse and treat as unknown.
+ let t;
+ while ((t = this.tag()[1]) !== binary_format_contract_1.WireType.EndGroup) {
+ this.skip(t);
+ }
+ break;
+ default:
+ throw new Error("cant skip wire type " + wireType);
+ }
+ this.assertBounds();
+ return this.buf.subarray(start, this.pos);
+ }
+ /**
+ * Throws error if position in byte array is out of range.
+ */
+ assertBounds() {
+ if (this.pos > this.len)
+ throw new RangeError("premature EOF");
+ }
+ /**
+ * Read a `int32` field, a signed 32 bit varint.
+ */
+ int32() {
+ return this.uint32() | 0;
+ }
+ /**
+ * Read a `sint32` field, a signed, zigzag-encoded 32-bit varint.
+ */
+ sint32() {
+ let zze = this.uint32();
+ // decode zigzag
+ return (zze >>> 1) ^ -(zze & 1);
+ }
+ /**
+ * Read a `int64` field, a signed 64-bit varint.
+ */
+ int64() {
+ return new pb_long_1.PbLong(...this.varint64());
+ }
+ /**
+ * Read a `uint64` field, an unsigned 64-bit varint.
+ */
+ uint64() {
+ return new pb_long_1.PbULong(...this.varint64());
+ }
+ /**
+ * Read a `sint64` field, a signed, zig-zag-encoded 64-bit varint.
+ */
+ sint64() {
+ let [lo, hi] = this.varint64();
+ // decode zig zag
+ let s = -(lo & 1);
+ lo = ((lo >>> 1 | (hi & 1) << 31) ^ s);
+ hi = (hi >>> 1 ^ s);
+ return new pb_long_1.PbLong(lo, hi);
+ }
+ /**
+ * Read a `bool` field, a variant.
+ */
+ bool() {
+ let [lo, hi] = this.varint64();
+ return lo !== 0 || hi !== 0;
+ }
+ /**
+ * Read a `fixed32` field, an unsigned, fixed-length 32-bit integer.
+ */
+ fixed32() {
+ return this.view.getUint32((this.pos += 4) - 4, true);
+ }
+ /**
+ * Read a `sfixed32` field, a signed, fixed-length 32-bit integer.
+ */
+ sfixed32() {
+ return this.view.getInt32((this.pos += 4) - 4, true);
+ }
+ /**
+ * Read a `fixed64` field, an unsigned, fixed-length 64 bit integer.
+ */
+ fixed64() {
+ return new pb_long_1.PbULong(this.sfixed32(), this.sfixed32());
+ }
+ /**
+ * Read a `fixed64` field, a signed, fixed-length 64-bit integer.
+ */
+ sfixed64() {
+ return new pb_long_1.PbLong(this.sfixed32(), this.sfixed32());
+ }
+ /**
+ * Read a `float` field, 32-bit floating point number.
+ */
+ float() {
+ return this.view.getFloat32((this.pos += 4) - 4, true);
+ }
+ /**
+ * Read a `double` field, a 64-bit floating point number.
+ */
+ double() {
+ return this.view.getFloat64((this.pos += 8) - 8, true);
+ }
+ /**
+ * Read a `bytes` field, length-delimited arbitrary data.
+ */
+ bytes() {
+ let len = this.uint32();
+ let start = this.pos;
+ this.pos += len;
+ this.assertBounds();
+ return this.buf.subarray(start, start + len);
+ }
+ /**
+ * Read a `string` field, length-delimited data converted to UTF-8 text.
+ */
+ string() {
+ return this.textDecoder.decode(this.bytes());
+ }
}
+exports.BinaryReader = BinaryReader;
-const kClientDestroyedError = Symbol.for('undici.error.UND_ERR_DESTROYED')
-class ClientDestroyedError extends UndiciError {
- constructor (message) {
- super(message)
- this.name = 'ClientDestroyedError'
- this.message = message || 'The client is destroyed'
- this.code = 'UND_ERR_DESTROYED'
- }
-
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kClientDestroyedError] === true
- }
- [kClientDestroyedError] = true
-}
+/***/ }),
-const kClientClosedError = Symbol.for('undici.error.UND_ERR_CLOSED')
-class ClientClosedError extends UndiciError {
- constructor (message) {
- super(message)
- this.name = 'ClientClosedError'
- this.message = message || 'The client is closed'
- this.code = 'UND_ERR_CLOSED'
- }
+/***/ 3957:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kClientClosedError] === true
- }
- [kClientClosedError] = true
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.BinaryWriter = exports.binaryWriteOptions = void 0;
+const pb_long_1 = __nccwpck_require__(1753);
+const goog_varint_1 = __nccwpck_require__(3223);
+const assert_1 = __nccwpck_require__(8602);
+const defaultsWrite = {
+ writeUnknownFields: true,
+ writerFactory: () => new BinaryWriter(),
+};
+/**
+ * Make options for writing binary data form partial options.
+ */
+function binaryWriteOptions(options) {
+ return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite;
}
-
-const kSocketError = Symbol.for('undici.error.UND_ERR_SOCKET')
-class SocketError extends UndiciError {
- constructor (message, socket) {
- super(message)
- this.name = 'SocketError'
- this.message = message || 'Socket error'
- this.code = 'UND_ERR_SOCKET'
- this.socket = socket
- }
-
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kSocketError] === true
- }
-
- [kSocketError] = true
-}
-
-const kNotSupportedError = Symbol.for('undici.error.UND_ERR_NOT_SUPPORTED')
-class NotSupportedError extends UndiciError {
- constructor (message) {
- super(message)
- this.name = 'NotSupportedError'
- this.message = message || 'Not supported error'
- this.code = 'UND_ERR_NOT_SUPPORTED'
- }
-
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kNotSupportedError] === true
- }
-
- [kNotSupportedError] = true
-}
-
-const kBalancedPoolMissingUpstreamError = Symbol.for('undici.error.UND_ERR_BPL_MISSING_UPSTREAM')
-class BalancedPoolMissingUpstreamError extends UndiciError {
- constructor (message) {
- super(message)
- this.name = 'MissingUpstreamError'
- this.message = message || 'No upstream has been added to the BalancedPool'
- this.code = 'UND_ERR_BPL_MISSING_UPSTREAM'
- }
-
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kBalancedPoolMissingUpstreamError] === true
- }
-
- [kBalancedPoolMissingUpstreamError] = true
-}
-
-const kHTTPParserError = Symbol.for('undici.error.UND_ERR_HTTP_PARSER')
-class HTTPParserError extends Error {
- constructor (message, code, data) {
- super(message)
- this.name = 'HTTPParserError'
- this.code = code ? `HPE_${code}` : undefined
- this.data = data ? data.toString() : undefined
- }
-
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kHTTPParserError] === true
- }
-
- [kHTTPParserError] = true
+exports.binaryWriteOptions = binaryWriteOptions;
+class BinaryWriter {
+ constructor(textEncoder) {
+ /**
+ * Previous fork states.
+ */
+ this.stack = [];
+ this.textEncoder = textEncoder !== null && textEncoder !== void 0 ? textEncoder : new TextEncoder();
+ this.chunks = [];
+ this.buf = [];
+ }
+ /**
+ * Return all bytes written and reset this writer.
+ */
+ finish() {
+ this.chunks.push(new Uint8Array(this.buf)); // flush the buffer
+ let len = 0;
+ for (let i = 0; i < this.chunks.length; i++)
+ len += this.chunks[i].length;
+ let bytes = new Uint8Array(len);
+ let offset = 0;
+ for (let i = 0; i < this.chunks.length; i++) {
+ bytes.set(this.chunks[i], offset);
+ offset += this.chunks[i].length;
+ }
+ this.chunks = [];
+ return bytes;
+ }
+ /**
+ * Start a new fork for length-delimited data like a message
+ * or a packed repeated field.
+ *
+ * Must be joined later with `join()`.
+ */
+ fork() {
+ this.stack.push({ chunks: this.chunks, buf: this.buf });
+ this.chunks = [];
+ this.buf = [];
+ return this;
+ }
+ /**
+ * Join the last fork. Write its length and bytes, then
+ * return to the previous state.
+ */
+ join() {
+ // get chunk of fork
+ let chunk = this.finish();
+ // restore previous state
+ let prev = this.stack.pop();
+ if (!prev)
+ throw new Error('invalid state, fork stack empty');
+ this.chunks = prev.chunks;
+ this.buf = prev.buf;
+ // write length of chunk as varint
+ this.uint32(chunk.byteLength);
+ return this.raw(chunk);
+ }
+ /**
+ * Writes a tag (field number and wire type).
+ *
+ * Equivalent to `uint32( (fieldNo << 3 | type) >>> 0 )`.
+ *
+ * Generated code should compute the tag ahead of time and call `uint32()`.
+ */
+ tag(fieldNo, type) {
+ return this.uint32((fieldNo << 3 | type) >>> 0);
+ }
+ /**
+ * Write a chunk of raw bytes.
+ */
+ raw(chunk) {
+ if (this.buf.length) {
+ this.chunks.push(new Uint8Array(this.buf));
+ this.buf = [];
+ }
+ this.chunks.push(chunk);
+ return this;
+ }
+ /**
+ * Write a `uint32` value, an unsigned 32 bit varint.
+ */
+ uint32(value) {
+ assert_1.assertUInt32(value);
+ // write value as varint 32, inlined for speed
+ while (value > 0x7f) {
+ this.buf.push((value & 0x7f) | 0x80);
+ value = value >>> 7;
+ }
+ this.buf.push(value);
+ return this;
+ }
+ /**
+ * Write a `int32` value, a signed 32 bit varint.
+ */
+ int32(value) {
+ assert_1.assertInt32(value);
+ goog_varint_1.varint32write(value, this.buf);
+ return this;
+ }
+ /**
+ * Write a `bool` value, a variant.
+ */
+ bool(value) {
+ this.buf.push(value ? 1 : 0);
+ return this;
+ }
+ /**
+ * Write a `bytes` value, length-delimited arbitrary data.
+ */
+ bytes(value) {
+ this.uint32(value.byteLength); // write length of chunk as varint
+ return this.raw(value);
+ }
+ /**
+ * Write a `string` value, length-delimited data converted to UTF-8 text.
+ */
+ string(value) {
+ let chunk = this.textEncoder.encode(value);
+ this.uint32(chunk.byteLength); // write length of chunk as varint
+ return this.raw(chunk);
+ }
+ /**
+ * Write a `float` value, 32-bit floating point number.
+ */
+ float(value) {
+ assert_1.assertFloat32(value);
+ let chunk = new Uint8Array(4);
+ new DataView(chunk.buffer).setFloat32(0, value, true);
+ return this.raw(chunk);
+ }
+ /**
+ * Write a `double` value, a 64-bit floating point number.
+ */
+ double(value) {
+ let chunk = new Uint8Array(8);
+ new DataView(chunk.buffer).setFloat64(0, value, true);
+ return this.raw(chunk);
+ }
+ /**
+ * Write a `fixed32` value, an unsigned, fixed-length 32-bit integer.
+ */
+ fixed32(value) {
+ assert_1.assertUInt32(value);
+ let chunk = new Uint8Array(4);
+ new DataView(chunk.buffer).setUint32(0, value, true);
+ return this.raw(chunk);
+ }
+ /**
+ * Write a `sfixed32` value, a signed, fixed-length 32-bit integer.
+ */
+ sfixed32(value) {
+ assert_1.assertInt32(value);
+ let chunk = new Uint8Array(4);
+ new DataView(chunk.buffer).setInt32(0, value, true);
+ return this.raw(chunk);
+ }
+ /**
+ * Write a `sint32` value, a signed, zigzag-encoded 32-bit varint.
+ */
+ sint32(value) {
+ assert_1.assertInt32(value);
+ // zigzag encode
+ value = ((value << 1) ^ (value >> 31)) >>> 0;
+ goog_varint_1.varint32write(value, this.buf);
+ return this;
+ }
+ /**
+ * Write a `fixed64` value, a signed, fixed-length 64-bit integer.
+ */
+ sfixed64(value) {
+ let chunk = new Uint8Array(8);
+ let view = new DataView(chunk.buffer);
+ let long = pb_long_1.PbLong.from(value);
+ view.setInt32(0, long.lo, true);
+ view.setInt32(4, long.hi, true);
+ return this.raw(chunk);
+ }
+ /**
+ * Write a `fixed64` value, an unsigned, fixed-length 64 bit integer.
+ */
+ fixed64(value) {
+ let chunk = new Uint8Array(8);
+ let view = new DataView(chunk.buffer);
+ let long = pb_long_1.PbULong.from(value);
+ view.setInt32(0, long.lo, true);
+ view.setInt32(4, long.hi, true);
+ return this.raw(chunk);
+ }
+ /**
+ * Write a `int64` value, a signed 64-bit varint.
+ */
+ int64(value) {
+ let long = pb_long_1.PbLong.from(value);
+ goog_varint_1.varint64write(long.lo, long.hi, this.buf);
+ return this;
+ }
+ /**
+ * Write a `sint64` value, a signed, zig-zag-encoded 64-bit varint.
+ */
+ sint64(value) {
+ let long = pb_long_1.PbLong.from(value),
+ // zigzag encode
+ sign = long.hi >> 31, lo = (long.lo << 1) ^ sign, hi = ((long.hi << 1) | (long.lo >>> 31)) ^ sign;
+ goog_varint_1.varint64write(lo, hi, this.buf);
+ return this;
+ }
+ /**
+ * Write a `uint64` value, an unsigned 64-bit varint.
+ */
+ uint64(value) {
+ let long = pb_long_1.PbULong.from(value);
+ goog_varint_1.varint64write(long.lo, long.hi, this.buf);
+ return this;
+ }
}
+exports.BinaryWriter = BinaryWriter;
-const kResponseExceededMaxSizeError = Symbol.for('undici.error.UND_ERR_RES_EXCEEDED_MAX_SIZE')
-class ResponseExceededMaxSizeError extends UndiciError {
- constructor (message) {
- super(message)
- this.name = 'ResponseExceededMaxSizeError'
- this.message = message || 'Response content exceeded max size'
- this.code = 'UND_ERR_RES_EXCEEDED_MAX_SIZE'
- }
-
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kResponseExceededMaxSizeError] === true
- }
- [kResponseExceededMaxSizeError] = true
-}
+/***/ }),
-const kRequestRetryError = Symbol.for('undici.error.UND_ERR_REQ_RETRY')
-class RequestRetryError extends UndiciError {
- constructor (message, code, { headers, data }) {
- super(message)
- this.name = 'RequestRetryError'
- this.message = message || 'Request retry error'
- this.code = 'UND_ERR_REQ_RETRY'
- this.statusCode = code
- this.data = data
- this.headers = headers
- }
+/***/ 257:
+/***/ ((__unused_webpack_module, exports) => {
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kRequestRetryError] === true
- }
- [kRequestRetryError] = true
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.listEnumNumbers = exports.listEnumNames = exports.listEnumValues = exports.isEnumObject = void 0;
+/**
+ * Is this a lookup object generated by Typescript, for a Typescript enum
+ * generated by protobuf-ts?
+ *
+ * - No `const enum` (enum must not be inlined, we need reverse mapping).
+ * - No string enum (we need int32 for protobuf).
+ * - Must have a value for 0 (otherwise, we would need to support custom default values).
+ */
+function isEnumObject(arg) {
+ if (typeof arg != 'object' || arg === null) {
+ return false;
+ }
+ if (!arg.hasOwnProperty(0)) {
+ return false;
+ }
+ for (let k of Object.keys(arg)) {
+ let num = parseInt(k);
+ if (!Number.isNaN(num)) {
+ // is there a name for the number?
+ let nam = arg[num];
+ if (nam === undefined)
+ return false;
+ // does the name resolve back to the number?
+ if (arg[nam] !== num)
+ return false;
+ }
+ else {
+ // is there a number for the name?
+ let num = arg[k];
+ if (num === undefined)
+ return false;
+ // is it a string enum?
+ if (typeof num !== 'number')
+ return false;
+ // do we know the number?
+ if (arg[num] === undefined)
+ return false;
+ }
+ }
+ return true;
}
-
-const kResponseError = Symbol.for('undici.error.UND_ERR_RESPONSE')
-class ResponseError extends UndiciError {
- constructor (message, code, { headers, data }) {
- super(message)
- this.name = 'ResponseError'
- this.message = message || 'Response error'
- this.code = 'UND_ERR_RESPONSE'
- this.statusCode = code
- this.data = data
- this.headers = headers
- }
-
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kResponseError] === true
- }
-
- [kResponseError] = true
+exports.isEnumObject = isEnumObject;
+/**
+ * Lists all values of a Typescript enum, as an array of objects with a "name"
+ * property and a "number" property.
+ *
+ * Note that it is possible that a number appears more than once, because it is
+ * possible to have aliases in an enum.
+ *
+ * Throws if the enum does not adhere to the rules of enums generated by
+ * protobuf-ts. See `isEnumObject()`.
+ */
+function listEnumValues(enumObject) {
+ if (!isEnumObject(enumObject))
+ throw new Error("not a typescript enum object");
+ let values = [];
+ for (let [name, number] of Object.entries(enumObject))
+ if (typeof number == "number")
+ values.push({ name, number });
+ return values;
}
-
-const kSecureProxyConnectionError = Symbol.for('undici.error.UND_ERR_PRX_TLS')
-class SecureProxyConnectionError extends UndiciError {
- constructor (cause, message, options) {
- super(message, { cause, ...(options ?? {}) })
- this.name = 'SecureProxyConnectionError'
- this.message = message || 'Secure Proxy Connection failed'
- this.code = 'UND_ERR_PRX_TLS'
- this.cause = cause
- }
-
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kSecureProxyConnectionError] === true
- }
-
- [kSecureProxyConnectionError] = true
+exports.listEnumValues = listEnumValues;
+/**
+ * Lists the names of a Typescript enum.
+ *
+ * Throws if the enum does not adhere to the rules of enums generated by
+ * protobuf-ts. See `isEnumObject()`.
+ */
+function listEnumNames(enumObject) {
+ return listEnumValues(enumObject).map(val => val.name);
}
-
-module.exports = {
- AbortError,
- HTTPParserError,
- UndiciError,
- HeadersTimeoutError,
- HeadersOverflowError,
- BodyTimeoutError,
- RequestContentLengthMismatchError,
- ConnectTimeoutError,
- ResponseStatusCodeError,
- InvalidArgumentError,
- InvalidReturnValueError,
- RequestAbortedError,
- ClientDestroyedError,
- ClientClosedError,
- InformationalError,
- SocketError,
- NotSupportedError,
- ResponseContentLengthMismatchError,
- BalancedPoolMissingUpstreamError,
- ResponseExceededMaxSizeError,
- RequestRetryError,
- ResponseError,
- SecureProxyConnectionError
+exports.listEnumNames = listEnumNames;
+/**
+ * Lists the numbers of a Typescript enum.
+ *
+ * Throws if the enum does not adhere to the rules of enums generated by
+ * protobuf-ts. See `isEnumObject()`.
+ */
+function listEnumNumbers(enumObject) {
+ return listEnumValues(enumObject)
+ .map(val => val.number)
+ .filter((num, index, arr) => arr.indexOf(num) == index);
}
+exports.listEnumNumbers = listEnumNumbers;
/***/ }),
-/***/ 6265:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const {
- InvalidArgumentError,
- NotSupportedError
-} = __nccwpck_require__(2344)
-const assert = __nccwpck_require__(4589)
-const {
- isValidHTTPToken,
- isValidHeaderValue,
- isStream,
- destroy,
- isBuffer,
- isFormDataLike,
- isIterable,
- isBlobLike,
- buildURL,
- validateHandler,
- getServerName,
- normalizedMethodRecords
-} = __nccwpck_require__(7375)
-const { channels } = __nccwpck_require__(4567)
-const { headerNameLowerCasedRecord } = __nccwpck_require__(4914)
-
-// Verifies that a given path is valid does not contain control chars \x00 to \x20
-const invalidPathRegex = /[^\u0021-\u00ff]/
-
-const kHandler = Symbol('handler')
-
-class Request {
- constructor (origin, {
- path,
- method,
- body,
- headers,
- query,
- idempotent,
- blocking,
- upgrade,
- headersTimeout,
- bodyTimeout,
- reset,
- throwOnError,
- expectContinue,
- servername
- }, handler) {
- if (typeof path !== 'string') {
- throw new InvalidArgumentError('path must be a string')
- } else if (
- path[0] !== '/' &&
- !(path.startsWith('http://') || path.startsWith('https://')) &&
- method !== 'CONNECT'
- ) {
- throw new InvalidArgumentError('path must be an absolute URL or start with a slash')
- } else if (invalidPathRegex.test(path)) {
- throw new InvalidArgumentError('invalid request path')
- }
-
- if (typeof method !== 'string') {
- throw new InvalidArgumentError('method must be a string')
- } else if (normalizedMethodRecords[method] === undefined && !isValidHTTPToken(method)) {
- throw new InvalidArgumentError('invalid request method')
- }
-
- if (upgrade && typeof upgrade !== 'string') {
- throw new InvalidArgumentError('upgrade must be a string')
- }
+/***/ 3223:
+/***/ ((__unused_webpack_module, exports) => {
- if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) {
- throw new InvalidArgumentError('invalid headersTimeout')
- }
- if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) {
- throw new InvalidArgumentError('invalid bodyTimeout')
- }
-
- if (reset != null && typeof reset !== 'boolean') {
- throw new InvalidArgumentError('invalid reset')
+// Copyright 2008 Google Inc. All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+//
+// Code generated by the Protocol Buffer compiler is owned by the owner
+// of the input file used when generating it. This code is not
+// standalone and requires a support library to be linked with it. This
+// support library is itself covered by the above license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.varint32read = exports.varint32write = exports.int64toString = exports.int64fromString = exports.varint64write = exports.varint64read = void 0;
+/**
+ * Read a 64 bit varint as two JS numbers.
+ *
+ * Returns tuple:
+ * [0]: low bits
+ * [0]: high bits
+ *
+ * Copyright 2008 Google Inc. All rights reserved.
+ *
+ * See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/buffer_decoder.js#L175
+ */
+function varint64read() {
+ let lowBits = 0;
+ let highBits = 0;
+ for (let shift = 0; shift < 28; shift += 7) {
+ let b = this.buf[this.pos++];
+ lowBits |= (b & 0x7F) << shift;
+ if ((b & 0x80) == 0) {
+ this.assertBounds();
+ return [lowBits, highBits];
+ }
}
-
- if (expectContinue != null && typeof expectContinue !== 'boolean') {
- throw new InvalidArgumentError('invalid expectContinue')
+ let middleByte = this.buf[this.pos++];
+ // last four bits of the first 32 bit number
+ lowBits |= (middleByte & 0x0F) << 28;
+ // 3 upper bits are part of the next 32 bit number
+ highBits = (middleByte & 0x70) >> 4;
+ if ((middleByte & 0x80) == 0) {
+ this.assertBounds();
+ return [lowBits, highBits];
}
-
- this.headersTimeout = headersTimeout
-
- this.bodyTimeout = bodyTimeout
-
- this.throwOnError = throwOnError === true
-
- this.method = method
-
- this.abort = null
-
- if (body == null) {
- this.body = null
- } else if (isStream(body)) {
- this.body = body
-
- const rState = this.body._readableState
- if (!rState || !rState.autoDestroy) {
- this.endHandler = function autoDestroy () {
- destroy(this)
- }
- this.body.on('end', this.endHandler)
- }
-
- this.errorHandler = err => {
- if (this.abort) {
- this.abort(err)
- } else {
- this.error = err
+ for (let shift = 3; shift <= 31; shift += 7) {
+ let b = this.buf[this.pos++];
+ highBits |= (b & 0x7F) << shift;
+ if ((b & 0x80) == 0) {
+ this.assertBounds();
+ return [lowBits, highBits];
}
- }
- this.body.on('error', this.errorHandler)
- } else if (isBuffer(body)) {
- this.body = body.byteLength ? body : null
- } else if (ArrayBuffer.isView(body)) {
- this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null
- } else if (body instanceof ArrayBuffer) {
- this.body = body.byteLength ? Buffer.from(body) : null
- } else if (typeof body === 'string') {
- this.body = body.length ? Buffer.from(body) : null
- } else if (isFormDataLike(body) || isIterable(body) || isBlobLike(body)) {
- this.body = body
- } else {
- throw new InvalidArgumentError('body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable')
}
-
- this.completed = false
-
- this.aborted = false
-
- this.upgrade = upgrade || null
-
- this.path = query ? buildURL(path, query) : path
-
- this.origin = origin
-
- this.idempotent = idempotent == null
- ? method === 'HEAD' || method === 'GET'
- : idempotent
-
- this.blocking = blocking == null ? false : blocking
-
- this.reset = reset == null ? null : reset
-
- this.host = null
-
- this.contentLength = null
-
- this.contentType = null
-
- this.headers = []
-
- // Only for H2
- this.expectContinue = expectContinue != null ? expectContinue : false
-
- if (Array.isArray(headers)) {
- if (headers.length % 2 !== 0) {
- throw new InvalidArgumentError('headers array must be even')
- }
- for (let i = 0; i < headers.length; i += 2) {
- processHeader(this, headers[i], headers[i + 1])
- }
- } else if (headers && typeof headers === 'object') {
- if (headers[Symbol.iterator]) {
- for (const header of headers) {
- if (!Array.isArray(header) || header.length !== 2) {
- throw new InvalidArgumentError('headers must be in key-value pair format')
- }
- processHeader(this, header[0], header[1])
- }
- } else {
- const keys = Object.keys(headers)
- for (let i = 0; i < keys.length; ++i) {
- processHeader(this, keys[i], headers[keys[i]])
+ throw new Error('invalid varint');
+}
+exports.varint64read = varint64read;
+/**
+ * Write a 64 bit varint, given as two JS numbers, to the given bytes array.
+ *
+ * Copyright 2008 Google Inc. All rights reserved.
+ *
+ * See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/writer.js#L344
+ */
+function varint64write(lo, hi, bytes) {
+ for (let i = 0; i < 28; i = i + 7) {
+ const shift = lo >>> i;
+ const hasNext = !((shift >>> 7) == 0 && hi == 0);
+ const byte = (hasNext ? shift | 0x80 : shift) & 0xFF;
+ bytes.push(byte);
+ if (!hasNext) {
+ return;
}
- }
- } else if (headers != null) {
- throw new InvalidArgumentError('headers must be an object or an array')
- }
-
- validateHandler(handler, method, upgrade)
-
- this.servername = servername || getServerName(this.host)
-
- this[kHandler] = handler
-
- if (channels.create.hasSubscribers) {
- channels.create.publish({ request: this })
}
- }
-
- onBodySent (chunk) {
- if (this[kHandler].onBodySent) {
- try {
- return this[kHandler].onBodySent(chunk)
- } catch (err) {
- this.abort(err)
- }
+ const splitBits = ((lo >>> 28) & 0x0F) | ((hi & 0x07) << 4);
+ const hasMoreBits = !((hi >> 3) == 0);
+ bytes.push((hasMoreBits ? splitBits | 0x80 : splitBits) & 0xFF);
+ if (!hasMoreBits) {
+ return;
}
- }
-
- onRequestSent () {
- if (channels.bodySent.hasSubscribers) {
- channels.bodySent.publish({ request: this })
+ for (let i = 3; i < 31; i = i + 7) {
+ const shift = hi >>> i;
+ const hasNext = !((shift >>> 7) == 0);
+ const byte = (hasNext ? shift | 0x80 : shift) & 0xFF;
+ bytes.push(byte);
+ if (!hasNext) {
+ return;
+ }
}
-
- if (this[kHandler].onRequestSent) {
- try {
- return this[kHandler].onRequestSent()
- } catch (err) {
- this.abort(err)
- }
+ bytes.push((hi >>> 31) & 0x01);
+}
+exports.varint64write = varint64write;
+// constants for binary math
+const TWO_PWR_32_DBL = (1 << 16) * (1 << 16);
+/**
+ * Parse decimal string of 64 bit integer value as two JS numbers.
+ *
+ * Returns tuple:
+ * [0]: minus sign?
+ * [1]: low bits
+ * [2]: high bits
+ *
+ * Copyright 2008 Google Inc.
+ */
+function int64fromString(dec) {
+ // Check for minus sign.
+ let minus = dec[0] == '-';
+ if (minus)
+ dec = dec.slice(1);
+ // Work 6 decimal digits at a time, acting like we're converting base 1e6
+ // digits to binary. This is safe to do with floating point math because
+ // Number.isSafeInteger(ALL_32_BITS * 1e6) == true.
+ const base = 1e6;
+ let lowBits = 0;
+ let highBits = 0;
+ function add1e6digit(begin, end) {
+ // Note: Number('') is 0.
+ const digit1e6 = Number(dec.slice(begin, end));
+ highBits *= base;
+ lowBits = lowBits * base + digit1e6;
+ // Carry bits from lowBits to highBits
+ if (lowBits >= TWO_PWR_32_DBL) {
+ highBits = highBits + ((lowBits / TWO_PWR_32_DBL) | 0);
+ lowBits = lowBits % TWO_PWR_32_DBL;
+ }
}
- }
-
- onConnect (abort) {
- assert(!this.aborted)
- assert(!this.completed)
-
- if (this.error) {
- abort(this.error)
- } else {
- this.abort = abort
- return this[kHandler].onConnect(abort)
+ add1e6digit(-24, -18);
+ add1e6digit(-18, -12);
+ add1e6digit(-12, -6);
+ add1e6digit(-6);
+ return [minus, lowBits, highBits];
+}
+exports.int64fromString = int64fromString;
+/**
+ * Format 64 bit integer value (as two JS numbers) to decimal string.
+ *
+ * Copyright 2008 Google Inc.
+ */
+function int64toString(bitsLow, bitsHigh) {
+ // Skip the expensive conversion if the number is small enough to use the
+ // built-in conversions.
+ if ((bitsHigh >>> 0) <= 0x1FFFFF) {
+ return '' + (TWO_PWR_32_DBL * bitsHigh + (bitsLow >>> 0));
}
- }
-
- onResponseStarted () {
- return this[kHandler].onResponseStarted?.()
- }
-
- onHeaders (statusCode, headers, resume, statusText) {
- assert(!this.aborted)
- assert(!this.completed)
-
- if (channels.headers.hasSubscribers) {
- channels.headers.publish({ request: this, response: { statusCode, headers, statusText } })
+ // What this code is doing is essentially converting the input number from
+ // base-2 to base-1e7, which allows us to represent the 64-bit range with
+ // only 3 (very large) digits. Those digits are then trivial to convert to
+ // a base-10 string.
+ // The magic numbers used here are -
+ // 2^24 = 16777216 = (1,6777216) in base-1e7.
+ // 2^48 = 281474976710656 = (2,8147497,6710656) in base-1e7.
+ // Split 32:32 representation into 16:24:24 representation so our
+ // intermediate digits don't overflow.
+ let low = bitsLow & 0xFFFFFF;
+ let mid = (((bitsLow >>> 24) | (bitsHigh << 8)) >>> 0) & 0xFFFFFF;
+ let high = (bitsHigh >> 16) & 0xFFFF;
+ // Assemble our three base-1e7 digits, ignoring carries. The maximum
+ // value in a digit at this step is representable as a 48-bit integer, which
+ // can be stored in a 64-bit floating point number.
+ let digitA = low + (mid * 6777216) + (high * 6710656);
+ let digitB = mid + (high * 8147497);
+ let digitC = (high * 2);
+ // Apply carries from A to B and from B to C.
+ let base = 10000000;
+ if (digitA >= base) {
+ digitB += Math.floor(digitA / base);
+ digitA %= base;
}
-
- try {
- return this[kHandler].onHeaders(statusCode, headers, resume, statusText)
- } catch (err) {
- this.abort(err)
+ if (digitB >= base) {
+ digitC += Math.floor(digitB / base);
+ digitB %= base;
}
- }
-
- onData (chunk) {
- assert(!this.aborted)
- assert(!this.completed)
-
- try {
- return this[kHandler].onData(chunk)
- } catch (err) {
- this.abort(err)
- return false
+ // Convert base-1e7 digits to base-10, with optional leading zeroes.
+ function decimalFrom1e7(digit1e7, needLeadingZeros) {
+ let partial = digit1e7 ? String(digit1e7) : '';
+ if (needLeadingZeros) {
+ return '0000000'.slice(partial.length) + partial;
+ }
+ return partial;
}
- }
-
- onUpgrade (statusCode, headers, socket) {
- assert(!this.aborted)
- assert(!this.completed)
-
- return this[kHandler].onUpgrade(statusCode, headers, socket)
- }
-
- onComplete (trailers) {
- this.onFinally()
-
- assert(!this.aborted)
-
- this.completed = true
- if (channels.trailers.hasSubscribers) {
- channels.trailers.publish({ request: this, trailers })
+ return decimalFrom1e7(digitC, /*needLeadingZeros=*/ 0) +
+ decimalFrom1e7(digitB, /*needLeadingZeros=*/ digitC) +
+ // If the final 1e7 digit didn't need leading zeros, we would have
+ // returned via the trivial code path at the top.
+ decimalFrom1e7(digitA, /*needLeadingZeros=*/ 1);
+}
+exports.int64toString = int64toString;
+/**
+ * Write a 32 bit varint, signed or unsigned. Same as `varint64write(0, value, bytes)`
+ *
+ * Copyright 2008 Google Inc. All rights reserved.
+ *
+ * See https://github.com/protocolbuffers/protobuf/blob/1b18833f4f2a2f681f4e4a25cdf3b0a43115ec26/js/binary/encoder.js#L144
+ */
+function varint32write(value, bytes) {
+ if (value >= 0) {
+ // write value as varint 32
+ while (value > 0x7f) {
+ bytes.push((value & 0x7f) | 0x80);
+ value = value >>> 7;
+ }
+ bytes.push(value);
}
-
- try {
- return this[kHandler].onComplete(trailers)
- } catch (err) {
- // TODO (fix): This might be a bad idea?
- this.onError(err)
+ else {
+ for (let i = 0; i < 9; i++) {
+ bytes.push(value & 127 | 128);
+ value = value >> 7;
+ }
+ bytes.push(1);
}
- }
-
- onError (error) {
- this.onFinally()
-
- if (channels.error.hasSubscribers) {
- channels.error.publish({ request: this, error })
+}
+exports.varint32write = varint32write;
+/**
+ * Read an unsigned 32 bit varint.
+ *
+ * See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/buffer_decoder.js#L220
+ */
+function varint32read() {
+ let b = this.buf[this.pos++];
+ let result = b & 0x7F;
+ if ((b & 0x80) == 0) {
+ this.assertBounds();
+ return result;
}
-
- if (this.aborted) {
- return
+ b = this.buf[this.pos++];
+ result |= (b & 0x7F) << 7;
+ if ((b & 0x80) == 0) {
+ this.assertBounds();
+ return result;
}
- this.aborted = true
-
- return this[kHandler].onError(error)
- }
-
- onFinally () {
- if (this.errorHandler) {
- this.body.off('error', this.errorHandler)
- this.errorHandler = null
+ b = this.buf[this.pos++];
+ result |= (b & 0x7F) << 14;
+ if ((b & 0x80) == 0) {
+ this.assertBounds();
+ return result;
}
-
- if (this.endHandler) {
- this.body.off('end', this.endHandler)
- this.endHandler = null
+ b = this.buf[this.pos++];
+ result |= (b & 0x7F) << 21;
+ if ((b & 0x80) == 0) {
+ this.assertBounds();
+ return result;
}
- }
-
- addHeader (key, value) {
- processHeader(this, key, value)
- return this
- }
+ // Extract only last 4 bits
+ b = this.buf[this.pos++];
+ result |= (b & 0x0F) << 28;
+ for (let readBytes = 5; ((b & 0x80) !== 0) && readBytes < 10; readBytes++)
+ b = this.buf[this.pos++];
+ if ((b & 0x80) != 0)
+ throw new Error('invalid varint');
+ this.assertBounds();
+ // Result can have 32 bits, convert it to unsigned
+ return result >>> 0;
}
+exports.varint32read = varint32read;
-function processHeader (request, key, val) {
- if (val && (typeof val === 'object' && !Array.isArray(val))) {
- throw new InvalidArgumentError(`invalid ${key} header`)
- } else if (val === undefined) {
- return
- }
- let headerName = headerNameLowerCasedRecord[key]
+/***/ }),
- if (headerName === undefined) {
- headerName = key.toLowerCase()
- if (headerNameLowerCasedRecord[headerName] === undefined && !isValidHTTPToken(headerName)) {
- throw new InvalidArgumentError('invalid header key')
- }
- }
+/***/ 8886:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- if (Array.isArray(val)) {
- const arr = []
- for (let i = 0; i < val.length; i++) {
- if (typeof val[i] === 'string') {
- if (!isValidHeaderValue(val[i])) {
- throw new InvalidArgumentError(`invalid ${key} header`)
- }
- arr.push(val[i])
- } else if (val[i] === null) {
- arr.push('')
- } else if (typeof val[i] === 'object') {
- throw new InvalidArgumentError(`invalid ${key} header`)
- } else {
- arr.push(`${val[i]}`)
- }
- }
- val = arr
- } else if (typeof val === 'string') {
- if (!isValidHeaderValue(val)) {
- throw new InvalidArgumentError(`invalid ${key} header`)
- }
- } else if (val === null) {
- val = ''
- } else {
- val = `${val}`
- }
-
- if (request.host === null && headerName === 'host') {
- if (typeof val !== 'string') {
- throw new InvalidArgumentError('invalid host header')
- }
- // Consumed by Client
- request.host = val
- } else if (request.contentLength === null && headerName === 'content-length') {
- request.contentLength = parseInt(val, 10)
- if (!Number.isFinite(request.contentLength)) {
- throw new InvalidArgumentError('invalid content-length header')
- }
- } else if (request.contentType === null && headerName === 'content-type') {
- request.contentType = val
- request.headers.push(key, val)
- } else if (headerName === 'transfer-encoding' || headerName === 'keep-alive' || headerName === 'upgrade') {
- throw new InvalidArgumentError(`invalid ${headerName} header`)
- } else if (headerName === 'connection') {
- const value = typeof val === 'string' ? val.toLowerCase() : null
- if (value !== 'close' && value !== 'keep-alive') {
- throw new InvalidArgumentError('invalid connection header')
- }
-
- if (value === 'close') {
- request.reset = true
- }
- } else if (headerName === 'expect') {
- throw new NotSupportedError('expect header not supported')
- } else {
- request.headers.push(key, val)
- }
-}
-module.exports = Request
+// Public API of the protobuf-ts runtime.
+// Note: we do not use `export * from ...` to help tree shakers,
+// webpack verbose output hints that this should be useful
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+// Convenience JSON typings and corresponding type guards
+var json_typings_1 = __nccwpck_require__(9999);
+Object.defineProperty(exports, "typeofJsonValue", ({ enumerable: true, get: function () { return json_typings_1.typeofJsonValue; } }));
+Object.defineProperty(exports, "isJsonObject", ({ enumerable: true, get: function () { return json_typings_1.isJsonObject; } }));
+// Base 64 encoding
+var base64_1 = __nccwpck_require__(6335);
+Object.defineProperty(exports, "base64decode", ({ enumerable: true, get: function () { return base64_1.base64decode; } }));
+Object.defineProperty(exports, "base64encode", ({ enumerable: true, get: function () { return base64_1.base64encode; } }));
+// UTF8 encoding
+var protobufjs_utf8_1 = __nccwpck_require__(8950);
+Object.defineProperty(exports, "utf8read", ({ enumerable: true, get: function () { return protobufjs_utf8_1.utf8read; } }));
+// Binary format contracts, options for reading and writing, for example
+var binary_format_contract_1 = __nccwpck_require__(4816);
+Object.defineProperty(exports, "WireType", ({ enumerable: true, get: function () { return binary_format_contract_1.WireType; } }));
+Object.defineProperty(exports, "mergeBinaryOptions", ({ enumerable: true, get: function () { return binary_format_contract_1.mergeBinaryOptions; } }));
+Object.defineProperty(exports, "UnknownFieldHandler", ({ enumerable: true, get: function () { return binary_format_contract_1.UnknownFieldHandler; } }));
+// Standard IBinaryReader implementation
+var binary_reader_1 = __nccwpck_require__(2889);
+Object.defineProperty(exports, "BinaryReader", ({ enumerable: true, get: function () { return binary_reader_1.BinaryReader; } }));
+Object.defineProperty(exports, "binaryReadOptions", ({ enumerable: true, get: function () { return binary_reader_1.binaryReadOptions; } }));
+// Standard IBinaryWriter implementation
+var binary_writer_1 = __nccwpck_require__(3957);
+Object.defineProperty(exports, "BinaryWriter", ({ enumerable: true, get: function () { return binary_writer_1.BinaryWriter; } }));
+Object.defineProperty(exports, "binaryWriteOptions", ({ enumerable: true, get: function () { return binary_writer_1.binaryWriteOptions; } }));
+// Int64 and UInt64 implementations required for the binary format
+var pb_long_1 = __nccwpck_require__(1753);
+Object.defineProperty(exports, "PbLong", ({ enumerable: true, get: function () { return pb_long_1.PbLong; } }));
+Object.defineProperty(exports, "PbULong", ({ enumerable: true, get: function () { return pb_long_1.PbULong; } }));
+// JSON format contracts, options for reading and writing, for example
+var json_format_contract_1 = __nccwpck_require__(9367);
+Object.defineProperty(exports, "jsonReadOptions", ({ enumerable: true, get: function () { return json_format_contract_1.jsonReadOptions; } }));
+Object.defineProperty(exports, "jsonWriteOptions", ({ enumerable: true, get: function () { return json_format_contract_1.jsonWriteOptions; } }));
+Object.defineProperty(exports, "mergeJsonOptions", ({ enumerable: true, get: function () { return json_format_contract_1.mergeJsonOptions; } }));
+// Message type contract
+var message_type_contract_1 = __nccwpck_require__(3785);
+Object.defineProperty(exports, "MESSAGE_TYPE", ({ enumerable: true, get: function () { return message_type_contract_1.MESSAGE_TYPE; } }));
+// Message type implementation via reflection
+var message_type_1 = __nccwpck_require__(5106);
+Object.defineProperty(exports, "MessageType", ({ enumerable: true, get: function () { return message_type_1.MessageType; } }));
+// Reflection info, generated by the plugin, exposed to the user, used by reflection ops
+var reflection_info_1 = __nccwpck_require__(7910);
+Object.defineProperty(exports, "ScalarType", ({ enumerable: true, get: function () { return reflection_info_1.ScalarType; } }));
+Object.defineProperty(exports, "LongType", ({ enumerable: true, get: function () { return reflection_info_1.LongType; } }));
+Object.defineProperty(exports, "RepeatType", ({ enumerable: true, get: function () { return reflection_info_1.RepeatType; } }));
+Object.defineProperty(exports, "normalizeFieldInfo", ({ enumerable: true, get: function () { return reflection_info_1.normalizeFieldInfo; } }));
+Object.defineProperty(exports, "readFieldOptions", ({ enumerable: true, get: function () { return reflection_info_1.readFieldOptions; } }));
+Object.defineProperty(exports, "readFieldOption", ({ enumerable: true, get: function () { return reflection_info_1.readFieldOption; } }));
+Object.defineProperty(exports, "readMessageOption", ({ enumerable: true, get: function () { return reflection_info_1.readMessageOption; } }));
+// Message operations via reflection
+var reflection_type_check_1 = __nccwpck_require__(5167);
+Object.defineProperty(exports, "ReflectionTypeCheck", ({ enumerable: true, get: function () { return reflection_type_check_1.ReflectionTypeCheck; } }));
+var reflection_create_1 = __nccwpck_require__(5726);
+Object.defineProperty(exports, "reflectionCreate", ({ enumerable: true, get: function () { return reflection_create_1.reflectionCreate; } }));
+var reflection_scalar_default_1 = __nccwpck_require__(9526);
+Object.defineProperty(exports, "reflectionScalarDefault", ({ enumerable: true, get: function () { return reflection_scalar_default_1.reflectionScalarDefault; } }));
+var reflection_merge_partial_1 = __nccwpck_require__(8044);
+Object.defineProperty(exports, "reflectionMergePartial", ({ enumerable: true, get: function () { return reflection_merge_partial_1.reflectionMergePartial; } }));
+var reflection_equals_1 = __nccwpck_require__(4827);
+Object.defineProperty(exports, "reflectionEquals", ({ enumerable: true, get: function () { return reflection_equals_1.reflectionEquals; } }));
+var reflection_binary_reader_1 = __nccwpck_require__(9611);
+Object.defineProperty(exports, "ReflectionBinaryReader", ({ enumerable: true, get: function () { return reflection_binary_reader_1.ReflectionBinaryReader; } }));
+var reflection_binary_writer_1 = __nccwpck_require__(6907);
+Object.defineProperty(exports, "ReflectionBinaryWriter", ({ enumerable: true, get: function () { return reflection_binary_writer_1.ReflectionBinaryWriter; } }));
+var reflection_json_reader_1 = __nccwpck_require__(6790);
+Object.defineProperty(exports, "ReflectionJsonReader", ({ enumerable: true, get: function () { return reflection_json_reader_1.ReflectionJsonReader; } }));
+var reflection_json_writer_1 = __nccwpck_require__(1094);
+Object.defineProperty(exports, "ReflectionJsonWriter", ({ enumerable: true, get: function () { return reflection_json_writer_1.ReflectionJsonWriter; } }));
+var reflection_contains_message_type_1 = __nccwpck_require__(9946);
+Object.defineProperty(exports, "containsMessageType", ({ enumerable: true, get: function () { return reflection_contains_message_type_1.containsMessageType; } }));
+// Oneof helpers
+var oneof_1 = __nccwpck_require__(8063);
+Object.defineProperty(exports, "isOneofGroup", ({ enumerable: true, get: function () { return oneof_1.isOneofGroup; } }));
+Object.defineProperty(exports, "setOneofValue", ({ enumerable: true, get: function () { return oneof_1.setOneofValue; } }));
+Object.defineProperty(exports, "getOneofValue", ({ enumerable: true, get: function () { return oneof_1.getOneofValue; } }));
+Object.defineProperty(exports, "clearOneofValue", ({ enumerable: true, get: function () { return oneof_1.clearOneofValue; } }));
+Object.defineProperty(exports, "getSelectedOneofValue", ({ enumerable: true, get: function () { return oneof_1.getSelectedOneofValue; } }));
+// Enum object type guard and reflection util, may be interesting to the user.
+var enum_object_1 = __nccwpck_require__(257);
+Object.defineProperty(exports, "listEnumValues", ({ enumerable: true, get: function () { return enum_object_1.listEnumValues; } }));
+Object.defineProperty(exports, "listEnumNames", ({ enumerable: true, get: function () { return enum_object_1.listEnumNames; } }));
+Object.defineProperty(exports, "listEnumNumbers", ({ enumerable: true, get: function () { return enum_object_1.listEnumNumbers; } }));
+Object.defineProperty(exports, "isEnumObject", ({ enumerable: true, get: function () { return enum_object_1.isEnumObject; } }));
+// lowerCamelCase() is exported for plugin, rpc-runtime and other rpc packages
+var lower_camel_case_1 = __nccwpck_require__(4073);
+Object.defineProperty(exports, "lowerCamelCase", ({ enumerable: true, get: function () { return lower_camel_case_1.lowerCamelCase; } }));
+// assertion functions are exported for plugin, may also be useful to user
+var assert_1 = __nccwpck_require__(8602);
+Object.defineProperty(exports, "assert", ({ enumerable: true, get: function () { return assert_1.assert; } }));
+Object.defineProperty(exports, "assertNever", ({ enumerable: true, get: function () { return assert_1.assertNever; } }));
+Object.defineProperty(exports, "assertInt32", ({ enumerable: true, get: function () { return assert_1.assertInt32; } }));
+Object.defineProperty(exports, "assertUInt32", ({ enumerable: true, get: function () { return assert_1.assertUInt32; } }));
+Object.defineProperty(exports, "assertFloat32", ({ enumerable: true, get: function () { return assert_1.assertFloat32; } }));
/***/ }),
-/***/ 6130:
-/***/ ((module) => {
+/***/ 9367:
+/***/ ((__unused_webpack_module, exports) => {
-module.exports = {
- kClose: Symbol('close'),
- kDestroy: Symbol('destroy'),
- kDispatch: Symbol('dispatch'),
- kUrl: Symbol('url'),
- kWriting: Symbol('writing'),
- kResuming: Symbol('resuming'),
- kQueue: Symbol('queue'),
- kConnect: Symbol('connect'),
- kConnecting: Symbol('connecting'),
- kKeepAliveDefaultTimeout: Symbol('default keep alive timeout'),
- kKeepAliveMaxTimeout: Symbol('max keep alive timeout'),
- kKeepAliveTimeoutThreshold: Symbol('keep alive timeout threshold'),
- kKeepAliveTimeoutValue: Symbol('keep alive timeout'),
- kKeepAlive: Symbol('keep alive'),
- kHeadersTimeout: Symbol('headers timeout'),
- kBodyTimeout: Symbol('body timeout'),
- kServerName: Symbol('server name'),
- kLocalAddress: Symbol('local address'),
- kHost: Symbol('host'),
- kNoRef: Symbol('no ref'),
- kBodyUsed: Symbol('used'),
- kBody: Symbol('abstracted request body'),
- kRunning: Symbol('running'),
- kBlocking: Symbol('blocking'),
- kPending: Symbol('pending'),
- kSize: Symbol('size'),
- kBusy: Symbol('busy'),
- kQueued: Symbol('queued'),
- kFree: Symbol('free'),
- kConnected: Symbol('connected'),
- kClosed: Symbol('closed'),
- kNeedDrain: Symbol('need drain'),
- kReset: Symbol('reset'),
- kDestroyed: Symbol.for('nodejs.stream.destroyed'),
- kResume: Symbol('resume'),
- kOnError: Symbol('on error'),
- kMaxHeadersSize: Symbol('max headers size'),
- kRunningIdx: Symbol('running index'),
- kPendingIdx: Symbol('pending index'),
- kError: Symbol('error'),
- kClients: Symbol('clients'),
- kClient: Symbol('client'),
- kParser: Symbol('parser'),
- kOnDestroyed: Symbol('destroy callbacks'),
- kPipelining: Symbol('pipelining'),
- kSocket: Symbol('socket'),
- kHostHeader: Symbol('host header'),
- kConnector: Symbol('connector'),
- kStrictContentLength: Symbol('strict content length'),
- kMaxRedirections: Symbol('maxRedirections'),
- kMaxRequests: Symbol('maxRequestsPerClient'),
- kProxy: Symbol('proxy agent options'),
- kCounter: Symbol('socket request counter'),
- kInterceptors: Symbol('dispatch interceptors'),
- kMaxResponseSize: Symbol('max response size'),
- kHTTP2Session: Symbol('http2Session'),
- kHTTP2SessionState: Symbol('http2Session state'),
- kRetryHandlerDefaultRetry: Symbol('retry agent default retry'),
- kConstruct: Symbol('constructable'),
- kListeners: Symbol('listeners'),
- kHTTPContext: Symbol('http context'),
- kMaxConcurrentStreams: Symbol('max concurrent streams'),
- kNoProxyAgent: Symbol('no proxy agent'),
- kHttpProxyAgent: Symbol('http proxy agent'),
- kHttpsProxyAgent: Symbol('https proxy agent')
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.mergeJsonOptions = exports.jsonWriteOptions = exports.jsonReadOptions = void 0;
+const defaultsWrite = {
+ emitDefaultValues: false,
+ enumAsInteger: false,
+ useProtoFieldName: false,
+ prettySpaces: 0,
+}, defaultsRead = {
+ ignoreUnknownFields: false,
+};
+/**
+ * Make options for reading JSON data from partial options.
+ */
+function jsonReadOptions(options) {
+ return options ? Object.assign(Object.assign({}, defaultsRead), options) : defaultsRead;
+}
+exports.jsonReadOptions = jsonReadOptions;
+/**
+ * Make options for writing JSON data from partial options.
+ */
+function jsonWriteOptions(options) {
+ return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite;
+}
+exports.jsonWriteOptions = jsonWriteOptions;
+/**
+ * Merges JSON write or read options. Later values override earlier values. Type registries are merged.
+ */
+function mergeJsonOptions(a, b) {
+ var _a, _b;
+ let c = Object.assign(Object.assign({}, a), b);
+ c.typeRegistry = [...((_a = a === null || a === void 0 ? void 0 : a.typeRegistry) !== null && _a !== void 0 ? _a : []), ...((_b = b === null || b === void 0 ? void 0 : b.typeRegistry) !== null && _b !== void 0 ? _b : [])];
+ return c;
}
+exports.mergeJsonOptions = mergeJsonOptions;
/***/ }),
-/***/ 6675:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const {
- wellknownHeaderNames,
- headerNameLowerCasedRecord
-} = __nccwpck_require__(4914)
-
-class TstNode {
- /** @type {any} */
- value = null
- /** @type {null | TstNode} */
- left = null
- /** @type {null | TstNode} */
- middle = null
- /** @type {null | TstNode} */
- right = null
- /** @type {number} */
- code
- /**
- * @param {string} key
- * @param {any} value
- * @param {number} index
- */
- constructor (key, value, index) {
- if (index === undefined || index >= key.length) {
- throw new TypeError('Unreachable')
- }
- const code = this.code = key.charCodeAt(index)
- // check code is ascii string
- if (code > 0x7F) {
- throw new TypeError('key must be ascii string')
- }
- if (key.length !== ++index) {
- this.middle = new TstNode(key, value, index)
- } else {
- this.value = value
- }
- }
+/***/ 9999:
+/***/ ((__unused_webpack_module, exports) => {
- /**
- * @param {string} key
- * @param {any} value
- */
- add (key, value) {
- const length = key.length
- if (length === 0) {
- throw new TypeError('Unreachable')
- }
- let index = 0
- let node = this
- while (true) {
- const code = key.charCodeAt(index)
- // check code is ascii string
- if (code > 0x7F) {
- throw new TypeError('key must be ascii string')
- }
- if (node.code === code) {
- if (length === ++index) {
- node.value = value
- break
- } else if (node.middle !== null) {
- node = node.middle
- } else {
- node.middle = new TstNode(key, value, index)
- break
- }
- } else if (node.code < code) {
- if (node.left !== null) {
- node = node.left
- } else {
- node.left = new TstNode(key, value, index)
- break
- }
- } else if (node.right !== null) {
- node = node.right
- } else {
- node.right = new TstNode(key, value, index)
- break
- }
- }
- }
- /**
- * @param {Uint8Array} key
- * @return {TstNode | null}
- */
- search (key) {
- const keylength = key.length
- let index = 0
- let node = this
- while (node !== null && index < keylength) {
- let code = key[index]
- // A-Z
- // First check if it is bigger than 0x5a.
- // Lowercase letters have higher char codes than uppercase ones.
- // Also we assume that headers will mostly contain lowercase characters.
- if (code <= 0x5a && code >= 0x41) {
- // Lowercase for uppercase.
- code |= 32
- }
- while (node !== null) {
- if (code === node.code) {
- if (keylength === ++index) {
- // Returns Node since it is the last key.
- return node
- }
- node = node.middle
- break
- }
- node = node.code < code ? node.left : node.right
- }
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.isJsonObject = exports.typeofJsonValue = void 0;
+/**
+ * Get the type of a JSON value.
+ * Distinguishes between array, null and object.
+ */
+function typeofJsonValue(value) {
+ let t = typeof value;
+ if (t == "object") {
+ if (Array.isArray(value))
+ return "array";
+ if (value === null)
+ return "null";
}
- return null
- }
+ return t;
}
+exports.typeofJsonValue = typeofJsonValue;
+/**
+ * Is this a JSON object (instead of an array or null)?
+ */
+function isJsonObject(value) {
+ return value !== null && typeof value == "object" && !Array.isArray(value);
+}
+exports.isJsonObject = isJsonObject;
-class TernarySearchTree {
- /** @type {TstNode | null} */
- node = null
-
- /**
- * @param {string} key
- * @param {any} value
- * */
- insert (key, value) {
- if (this.node === null) {
- this.node = new TstNode(key, value, 0)
- } else {
- this.node.add(key, value)
- }
- }
- /**
- * @param {Uint8Array} key
- * @return {any}
- */
- lookup (key) {
- return this.node?.search(key)?.value ?? null
- }
-}
+/***/ }),
-const tree = new TernarySearchTree()
+/***/ 4073:
+/***/ ((__unused_webpack_module, exports) => {
-for (let i = 0; i < wellknownHeaderNames.length; ++i) {
- const key = headerNameLowerCasedRecord[wellknownHeaderNames[i]]
- tree.insert(key, key)
-}
-module.exports = {
- TernarySearchTree,
- tree
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.lowerCamelCase = void 0;
+/**
+ * Converts snake_case to lowerCamelCase.
+ *
+ * Should behave like protoc:
+ * https://github.com/protocolbuffers/protobuf/blob/e8ae137c96444ea313485ed1118c5e43b2099cf1/src/google/protobuf/compiler/java/java_helpers.cc#L118
+ */
+function lowerCamelCase(snakeCase) {
+ let capNext = false;
+ const sb = [];
+ for (let i = 0; i < snakeCase.length; i++) {
+ let next = snakeCase.charAt(i);
+ if (next == '_') {
+ capNext = true;
+ }
+ else if (/\d/.test(next)) {
+ sb.push(next);
+ capNext = true;
+ }
+ else if (capNext) {
+ sb.push(next.toUpperCase());
+ capNext = false;
+ }
+ else if (i == 0) {
+ sb.push(next.toLowerCase());
+ }
+ else {
+ sb.push(next);
+ }
+ }
+ return sb.join('');
}
+exports.lowerCamelCase = lowerCamelCase;
/***/ }),
-/***/ 7375:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
+/***/ 3785:
+/***/ ((__unused_webpack_module, exports) => {
-const assert = __nccwpck_require__(4589)
-const { kDestroyed, kBodyUsed, kListeners, kBody } = __nccwpck_require__(6130)
-const { IncomingMessage } = __nccwpck_require__(7067)
-const stream = __nccwpck_require__(7075)
-const net = __nccwpck_require__(7030)
-const { Blob } = __nccwpck_require__(4573)
-const nodeUtil = __nccwpck_require__(7975)
-const { stringify } = __nccwpck_require__(1792)
-const { EventEmitter: EE } = __nccwpck_require__(8474)
-const { InvalidArgumentError } = __nccwpck_require__(2344)
-const { headerNameLowerCasedRecord } = __nccwpck_require__(4914)
-const { tree } = __nccwpck_require__(6675)
-const [nodeMajor, nodeMinor] = process.versions.node.split('.').map(v => Number(v))
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.MESSAGE_TYPE = void 0;
+/**
+ * The symbol used as a key on message objects to store the message type.
+ *
+ * Note that this is an experimental feature - it is here to stay, but
+ * implementation details may change without notice.
+ */
+exports.MESSAGE_TYPE = Symbol.for("protobuf-ts/message-type");
-class BodyAsyncIterable {
- constructor (body) {
- this[kBody] = body
- this[kBodyUsed] = false
- }
- async * [Symbol.asyncIterator] () {
- assert(!this[kBodyUsed], 'disturbed')
- this[kBodyUsed] = true
- yield * this[kBody]
- }
-}
+/***/ }),
-function wrapRequestBody (body) {
- if (isStream(body)) {
- // TODO (fix): Provide some way for the user to cache the file to e.g. /tmp
- // so that it can be dispatched again?
- // TODO (fix): Do we need 100-expect support to provide a way to do this properly?
- if (bodyLength(body) === 0) {
- body
- .on('data', function () {
- assert(false)
- })
- }
+/***/ 5106:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- if (typeof body.readableDidRead !== 'boolean') {
- body[kBodyUsed] = false
- EE.prototype.on.call(body, 'data', function () {
- this[kBodyUsed] = true
- })
- }
- return body
- } else if (body && typeof body.pipeTo === 'function') {
- // TODO (fix): We can't access ReadableStream internal state
- // to determine whether or not it has been disturbed. This is just
- // a workaround.
- return new BodyAsyncIterable(body)
- } else if (
- body &&
- typeof body !== 'string' &&
- !ArrayBuffer.isView(body) &&
- isIterable(body)
- ) {
- // TODO: Should we allow re-using iterable if !this.opts.idempotent
- // or through some other flag?
- return new BodyAsyncIterable(body)
- } else {
- return body
- }
-}
-
-function nop () {}
-
-function isStream (obj) {
- return obj && typeof obj === 'object' && typeof obj.pipe === 'function' && typeof obj.on === 'function'
-}
-
-// based on https://github.com/node-fetch/fetch-blob/blob/8ab587d34080de94140b54f07168451e7d0b655e/index.js#L229-L241 (MIT License)
-function isBlobLike (object) {
- if (object === null) {
- return false
- } else if (object instanceof Blob) {
- return true
- } else if (typeof object !== 'object') {
- return false
- } else {
- const sTag = object[Symbol.toStringTag]
-
- return (sTag === 'Blob' || sTag === 'File') && (
- ('stream' in object && typeof object.stream === 'function') ||
- ('arrayBuffer' in object && typeof object.arrayBuffer === 'function')
- )
- }
-}
-
-function buildURL (url, queryParams) {
- if (url.includes('?') || url.includes('#')) {
- throw new Error('Query params cannot be passed when url already contains "?" or "#".')
- }
-
- const stringified = stringify(queryParams)
-
- if (stringified) {
- url += '?' + stringified
- }
-
- return url
-}
-
-function isValidPort (port) {
- const value = parseInt(port, 10)
- return (
- value === Number(port) &&
- value >= 0 &&
- value <= 65535
- )
-}
-
-function isHttpOrHttpsPrefixed (value) {
- return (
- value != null &&
- value[0] === 'h' &&
- value[1] === 't' &&
- value[2] === 't' &&
- value[3] === 'p' &&
- (
- value[4] === ':' ||
- (
- value[4] === 's' &&
- value[5] === ':'
- )
- )
- )
-}
-
-function parseURL (url) {
- if (typeof url === 'string') {
- url = new URL(url)
-
- if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) {
- throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.MessageType = void 0;
+const message_type_contract_1 = __nccwpck_require__(3785);
+const reflection_info_1 = __nccwpck_require__(7910);
+const reflection_type_check_1 = __nccwpck_require__(5167);
+const reflection_json_reader_1 = __nccwpck_require__(6790);
+const reflection_json_writer_1 = __nccwpck_require__(1094);
+const reflection_binary_reader_1 = __nccwpck_require__(9611);
+const reflection_binary_writer_1 = __nccwpck_require__(6907);
+const reflection_create_1 = __nccwpck_require__(5726);
+const reflection_merge_partial_1 = __nccwpck_require__(8044);
+const json_typings_1 = __nccwpck_require__(9999);
+const json_format_contract_1 = __nccwpck_require__(9367);
+const reflection_equals_1 = __nccwpck_require__(4827);
+const binary_writer_1 = __nccwpck_require__(3957);
+const binary_reader_1 = __nccwpck_require__(2889);
+const baseDescriptors = Object.getOwnPropertyDescriptors(Object.getPrototypeOf({}));
+const messageTypeDescriptor = baseDescriptors[message_type_contract_1.MESSAGE_TYPE] = {};
+/**
+ * This standard message type provides reflection-based
+ * operations to work with a message.
+ */
+class MessageType {
+ constructor(name, fields, options) {
+ this.defaultCheckDepth = 16;
+ this.typeName = name;
+ this.fields = fields.map(reflection_info_1.normalizeFieldInfo);
+ this.options = options !== null && options !== void 0 ? options : {};
+ messageTypeDescriptor.value = this;
+ this.messagePrototype = Object.create(null, baseDescriptors);
+ this.refTypeCheck = new reflection_type_check_1.ReflectionTypeCheck(this);
+ this.refJsonReader = new reflection_json_reader_1.ReflectionJsonReader(this);
+ this.refJsonWriter = new reflection_json_writer_1.ReflectionJsonWriter(this);
+ this.refBinReader = new reflection_binary_reader_1.ReflectionBinaryReader(this);
+ this.refBinWriter = new reflection_binary_writer_1.ReflectionBinaryWriter(this);
}
-
- return url
- }
-
- if (!url || typeof url !== 'object') {
- throw new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.')
- }
-
- if (!(url instanceof URL)) {
- if (url.port != null && url.port !== '' && isValidPort(url.port) === false) {
- throw new InvalidArgumentError('Invalid URL: port must be a valid integer or a string representation of an integer.')
+ create(value) {
+ let message = reflection_create_1.reflectionCreate(this);
+ if (value !== undefined) {
+ reflection_merge_partial_1.reflectionMergePartial(this, message, value);
+ }
+ return message;
}
-
- if (url.path != null && typeof url.path !== 'string') {
- throw new InvalidArgumentError('Invalid URL path: the path must be a string or null/undefined.')
+ /**
+ * Clone the message.
+ *
+ * Unknown fields are discarded.
+ */
+ clone(message) {
+ let copy = this.create();
+ reflection_merge_partial_1.reflectionMergePartial(this, copy, message);
+ return copy;
}
-
- if (url.pathname != null && typeof url.pathname !== 'string') {
- throw new InvalidArgumentError('Invalid URL pathname: the pathname must be a string or null/undefined.')
+ /**
+ * Determines whether two message of the same type have the same field values.
+ * Checks for deep equality, traversing repeated fields, oneof groups, maps
+ * and messages recursively.
+ * Will also return true if both messages are `undefined`.
+ */
+ equals(a, b) {
+ return reflection_equals_1.reflectionEquals(this, a, b);
}
-
- if (url.hostname != null && typeof url.hostname !== 'string') {
- throw new InvalidArgumentError('Invalid URL hostname: the hostname must be a string or null/undefined.')
+ /**
+ * Is the given value assignable to our message type
+ * and contains no [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)?
+ */
+ is(arg, depth = this.defaultCheckDepth) {
+ return this.refTypeCheck.is(arg, depth, false);
}
-
- if (url.origin != null && typeof url.origin !== 'string') {
- throw new InvalidArgumentError('Invalid URL origin: the origin must be a string or null/undefined.')
+ /**
+ * Is the given value assignable to our message type,
+ * regardless of [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)?
+ */
+ isAssignable(arg, depth = this.defaultCheckDepth) {
+ return this.refTypeCheck.is(arg, depth, true);
}
-
- if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) {
- throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')
+ /**
+ * Copy partial data into the target message.
+ */
+ mergePartial(target, source) {
+ reflection_merge_partial_1.reflectionMergePartial(this, target, source);
}
-
- const port = url.port != null
- ? url.port
- : (url.protocol === 'https:' ? 443 : 80)
- let origin = url.origin != null
- ? url.origin
- : `${url.protocol || ''}//${url.hostname || ''}:${port}`
- let path = url.path != null
- ? url.path
- : `${url.pathname || ''}${url.search || ''}`
-
- if (origin[origin.length - 1] === '/') {
- origin = origin.slice(0, origin.length - 1)
+ /**
+ * Create a new message from binary format.
+ */
+ fromBinary(data, options) {
+ let opt = binary_reader_1.binaryReadOptions(options);
+ return this.internalBinaryRead(opt.readerFactory(data), data.byteLength, opt);
}
-
- if (path && path[0] !== '/') {
- path = `/${path}`
+ /**
+ * Read a new message from a JSON value.
+ */
+ fromJson(json, options) {
+ return this.internalJsonRead(json, json_format_contract_1.jsonReadOptions(options));
+ }
+ /**
+ * Read a new message from a JSON string.
+ * This is equivalent to `T.fromJson(JSON.parse(json))`.
+ */
+ fromJsonString(json, options) {
+ let value = JSON.parse(json);
+ return this.fromJson(value, options);
+ }
+ /**
+ * Write the message to canonical JSON value.
+ */
+ toJson(message, options) {
+ return this.internalJsonWrite(message, json_format_contract_1.jsonWriteOptions(options));
+ }
+ /**
+ * Convert the message to canonical JSON string.
+ * This is equivalent to `JSON.stringify(T.toJson(t))`
+ */
+ toJsonString(message, options) {
+ var _a;
+ let value = this.toJson(message, options);
+ return JSON.stringify(value, null, (_a = options === null || options === void 0 ? void 0 : options.prettySpaces) !== null && _a !== void 0 ? _a : 0);
+ }
+ /**
+ * Write the message to binary format.
+ */
+ toBinary(message, options) {
+ let opt = binary_writer_1.binaryWriteOptions(options);
+ return this.internalBinaryWrite(message, opt.writerFactory(), opt).finish();
+ }
+ /**
+ * This is an internal method. If you just want to read a message from
+ * JSON, use `fromJson()` or `fromJsonString()`.
+ *
+ * Reads JSON value and merges the fields into the target
+ * according to protobuf rules. If the target is omitted,
+ * a new instance is created first.
+ */
+ internalJsonRead(json, options, target) {
+ if (json !== null && typeof json == "object" && !Array.isArray(json)) {
+ let message = target !== null && target !== void 0 ? target : this.create();
+ this.refJsonReader.read(json, message, options);
+ return message;
+ }
+ throw new Error(`Unable to parse message ${this.typeName} from JSON ${json_typings_1.typeofJsonValue(json)}.`);
+ }
+ /**
+ * This is an internal method. If you just want to write a message
+ * to JSON, use `toJson()` or `toJsonString().
+ *
+ * Writes JSON value and returns it.
+ */
+ internalJsonWrite(message, options) {
+ return this.refJsonWriter.write(message, options);
+ }
+ /**
+ * This is an internal method. If you just want to write a message
+ * in binary format, use `toBinary()`.
+ *
+ * Serializes the message in binary format and appends it to the given
+ * writer. Returns passed writer.
+ */
+ internalBinaryWrite(message, writer, options) {
+ this.refBinWriter.write(message, writer, options);
+ return writer;
+ }
+ /**
+ * This is an internal method. If you just want to read a message from
+ * binary data, use `fromBinary()`.
+ *
+ * Reads data from binary format and merges the fields into
+ * the target according to protobuf rules. If the target is
+ * omitted, a new instance is created first.
+ */
+ internalBinaryRead(reader, length, options, target) {
+ let message = target !== null && target !== void 0 ? target : this.create();
+ this.refBinReader.read(reader, message, options, length);
+ return message;
}
- // new URL(path, origin) is unsafe when `path` contains an absolute URL
- // From https://developer.mozilla.org/en-US/docs/Web/API/URL/URL:
- // If first parameter is a relative URL, second param is required, and will be used as the base URL.
- // If first parameter is an absolute URL, a given second param will be ignored.
- return new URL(`${origin}${path}`)
- }
-
- if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) {
- throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')
- }
-
- return url
-}
-
-function parseOrigin (url) {
- url = parseURL(url)
-
- if (url.pathname !== '/' || url.search || url.hash) {
- throw new InvalidArgumentError('invalid url')
- }
-
- return url
-}
-
-function getHostname (host) {
- if (host[0] === '[') {
- const idx = host.indexOf(']')
-
- assert(idx !== -1)
- return host.substring(1, idx)
- }
-
- const idx = host.indexOf(':')
- if (idx === -1) return host
-
- return host.substring(0, idx)
-}
-
-// IP addresses are not valid server names per RFC6066
-// > Currently, the only server names supported are DNS hostnames
-function getServerName (host) {
- if (!host) {
- return null
- }
-
- assert(typeof host === 'string')
-
- const servername = getHostname(host)
- if (net.isIP(servername)) {
- return ''
- }
-
- return servername
}
+exports.MessageType = MessageType;
-function deepClone (obj) {
- return JSON.parse(JSON.stringify(obj))
-}
-function isAsyncIterable (obj) {
- return !!(obj != null && typeof obj[Symbol.asyncIterator] === 'function')
-}
+/***/ }),
-function isIterable (obj) {
- return !!(obj != null && (typeof obj[Symbol.iterator] === 'function' || typeof obj[Symbol.asyncIterator] === 'function'))
-}
+/***/ 8063:
+/***/ ((__unused_webpack_module, exports) => {
-function bodyLength (body) {
- if (body == null) {
- return 0
- } else if (isStream(body)) {
- const state = body._readableState
- return state && state.objectMode === false && state.ended === true && Number.isFinite(state.length)
- ? state.length
- : null
- } else if (isBlobLike(body)) {
- return body.size != null ? body.size : null
- } else if (isBuffer(body)) {
- return body.byteLength
- }
- return null
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.getSelectedOneofValue = exports.clearOneofValue = exports.setUnknownOneofValue = exports.setOneofValue = exports.getOneofValue = exports.isOneofGroup = void 0;
+/**
+ * Is the given value a valid oneof group?
+ *
+ * We represent protobuf `oneof` as algebraic data types (ADT) in generated
+ * code. But when working with messages of unknown type, the ADT does not
+ * help us.
+ *
+ * This type guard checks if the given object adheres to the ADT rules, which
+ * are as follows:
+ *
+ * 1) Must be an object.
+ *
+ * 2) Must have a "oneofKind" discriminator property.
+ *
+ * 3) If "oneofKind" is `undefined`, no member field is selected. The object
+ * must not have any other properties.
+ *
+ * 4) If "oneofKind" is a `string`, the member field with this name is
+ * selected.
+ *
+ * 5) If a member field is selected, the object must have a second property
+ * with this name. The property must not be `undefined`.
+ *
+ * 6) No extra properties are allowed. The object has either one property
+ * (no selection) or two properties (selection).
+ *
+ */
+function isOneofGroup(any) {
+ if (typeof any != 'object' || any === null || !any.hasOwnProperty('oneofKind')) {
+ return false;
+ }
+ switch (typeof any.oneofKind) {
+ case "string":
+ if (any[any.oneofKind] === undefined)
+ return false;
+ return Object.keys(any).length == 2;
+ case "undefined":
+ return Object.keys(any).length == 1;
+ default:
+ return false;
+ }
}
-
-function isDestroyed (body) {
- return body && !!(body.destroyed || body[kDestroyed] || (stream.isDestroyed?.(body)))
+exports.isOneofGroup = isOneofGroup;
+/**
+ * Returns the value of the given field in a oneof group.
+ */
+function getOneofValue(oneof, kind) {
+ return oneof[kind];
}
-
-function destroy (stream, err) {
- if (stream == null || !isStream(stream) || isDestroyed(stream)) {
- return
- }
-
- if (typeof stream.destroy === 'function') {
- if (Object.getPrototypeOf(stream).constructor === IncomingMessage) {
- // See: https://github.com/nodejs/node/pull/38505/files
- stream.socket = null
+exports.getOneofValue = getOneofValue;
+function setOneofValue(oneof, kind, value) {
+ if (oneof.oneofKind !== undefined) {
+ delete oneof[oneof.oneofKind];
+ }
+ oneof.oneofKind = kind;
+ if (value !== undefined) {
+ oneof[kind] = value;
}
-
- stream.destroy(err)
- } else if (err) {
- queueMicrotask(() => {
- stream.emit('error', err)
- })
- }
-
- if (stream.destroyed !== true) {
- stream[kDestroyed] = true
- }
}
-
-const KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/
-function parseKeepAliveTimeout (val) {
- const m = val.toString().match(KEEPALIVE_TIMEOUT_EXPR)
- return m ? parseInt(m[1], 10) * 1000 : null
+exports.setOneofValue = setOneofValue;
+function setUnknownOneofValue(oneof, kind, value) {
+ if (oneof.oneofKind !== undefined) {
+ delete oneof[oneof.oneofKind];
+ }
+ oneof.oneofKind = kind;
+ if (value !== undefined && kind !== undefined) {
+ oneof[kind] = value;
+ }
}
-
+exports.setUnknownOneofValue = setUnknownOneofValue;
/**
- * Retrieves a header name and returns its lowercase value.
- * @param {string | Buffer} value Header name
- * @returns {string}
+ * Removes the selected field in a oneof group.
+ *
+ * Note that the recommended way to modify a oneof group is to set
+ * a new object:
+ *
+ * ```ts
+ * message.result = { oneofKind: undefined };
+ * ```
*/
-function headerNameToString (value) {
- return typeof value === 'string'
- ? headerNameLowerCasedRecord[value] ?? value.toLowerCase()
- : tree.lookup(value) ?? value.toString('latin1').toLowerCase()
+function clearOneofValue(oneof) {
+ if (oneof.oneofKind !== undefined) {
+ delete oneof[oneof.oneofKind];
+ }
+ oneof.oneofKind = undefined;
}
-
+exports.clearOneofValue = clearOneofValue;
/**
- * Receive the buffer as a string and return its lowercase value.
- * @param {Buffer} value Header name
- * @returns {string}
+ * Returns the selected value of the given oneof group.
+ *
+ * Not that the recommended way to access a oneof group is to check
+ * the "oneofKind" property and let TypeScript narrow down the union
+ * type for you:
+ *
+ * ```ts
+ * if (message.result.oneofKind === "error") {
+ * message.result.error; // string
+ * }
+ * ```
+ *
+ * In the rare case you just need the value, and do not care about
+ * which protobuf field is selected, you can use this function
+ * for convenience.
*/
-function bufferToLowerCasedHeaderName (value) {
- return tree.lookup(value) ?? value.toString('latin1').toLowerCase()
+function getSelectedOneofValue(oneof) {
+ if (oneof.oneofKind === undefined) {
+ return undefined;
+ }
+ return oneof[oneof.oneofKind];
}
+exports.getSelectedOneofValue = getSelectedOneofValue;
-/**
- * @param {Record | (Buffer | string | (Buffer | string)[])[]} headers
- * @param {Record} [obj]
- * @returns {Record}
- */
-function parseHeaders (headers, obj) {
- if (obj === undefined) obj = {}
- for (let i = 0; i < headers.length; i += 2) {
- const key = headerNameToString(headers[i])
- let val = obj[key]
-
- if (val) {
- if (typeof val === 'string') {
- val = [val]
- obj[key] = val
- }
- val.push(headers[i + 1].toString('utf8'))
- } else {
- const headersValue = headers[i + 1]
- if (typeof headersValue === 'string') {
- obj[key] = headersValue
- } else {
- obj[key] = Array.isArray(headersValue) ? headersValue.map(x => x.toString('utf8')) : headersValue.toString('utf8')
- }
- }
- }
-
- // See https://github.com/nodejs/node/pull/46528
- if ('content-length' in obj && 'content-disposition' in obj) {
- obj['content-disposition'] = Buffer.from(obj['content-disposition']).toString('latin1')
- }
-
- return obj
-}
-
-function parseRawHeaders (headers) {
- const len = headers.length
- const ret = new Array(len)
- let hasContentLength = false
- let contentDispositionIdx = -1
- let key
- let val
- let kLen = 0
-
- for (let n = 0; n < headers.length; n += 2) {
- key = headers[n]
- val = headers[n + 1]
-
- typeof key !== 'string' && (key = key.toString())
- typeof val !== 'string' && (val = val.toString('utf8'))
+/***/ }),
- kLen = key.length
- if (kLen === 14 && key[7] === '-' && (key === 'content-length' || key.toLowerCase() === 'content-length')) {
- hasContentLength = true
- } else if (kLen === 19 && key[7] === '-' && (key === 'content-disposition' || key.toLowerCase() === 'content-disposition')) {
- contentDispositionIdx = n + 1
- }
- ret[n] = key
- ret[n + 1] = val
- }
+/***/ 1753:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // See https://github.com/nodejs/node/pull/46528
- if (hasContentLength && contentDispositionIdx !== -1) {
- ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString('latin1')
- }
- return ret
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.PbLong = exports.PbULong = exports.detectBi = void 0;
+const goog_varint_1 = __nccwpck_require__(3223);
+let BI;
+function detectBi() {
+ const dv = new DataView(new ArrayBuffer(8));
+ const ok = globalThis.BigInt !== undefined
+ && typeof dv.getBigInt64 === "function"
+ && typeof dv.getBigUint64 === "function"
+ && typeof dv.setBigInt64 === "function"
+ && typeof dv.setBigUint64 === "function";
+ BI = ok ? {
+ MIN: BigInt("-9223372036854775808"),
+ MAX: BigInt("9223372036854775807"),
+ UMIN: BigInt("0"),
+ UMAX: BigInt("18446744073709551615"),
+ C: BigInt,
+ V: dv,
+ } : undefined;
}
-
-function isBuffer (buffer) {
- // See, https://github.com/mcollina/undici/pull/319
- return buffer instanceof Uint8Array || Buffer.isBuffer(buffer)
+exports.detectBi = detectBi;
+detectBi();
+function assertBi(bi) {
+ if (!bi)
+ throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support");
}
-
-function validateHandler (handler, method, upgrade) {
- if (!handler || typeof handler !== 'object') {
- throw new InvalidArgumentError('handler must be an object')
- }
-
- if (typeof handler.onConnect !== 'function') {
- throw new InvalidArgumentError('invalid onConnect method')
- }
-
- if (typeof handler.onError !== 'function') {
- throw new InvalidArgumentError('invalid onError method')
- }
-
- if (typeof handler.onBodySent !== 'function' && handler.onBodySent !== undefined) {
- throw new InvalidArgumentError('invalid onBodySent method')
- }
-
- if (upgrade || method === 'CONNECT') {
- if (typeof handler.onUpgrade !== 'function') {
- throw new InvalidArgumentError('invalid onUpgrade method')
+// used to validate from(string) input (when bigint is unavailable)
+const RE_DECIMAL_STR = /^-?[0-9]+$/;
+// constants for binary math
+const TWO_PWR_32_DBL = 0x100000000;
+const HALF_2_PWR_32 = 0x080000000;
+// base class for PbLong and PbULong provides shared code
+class SharedPbLong {
+ /**
+ * Create a new instance with the given bits.
+ */
+ constructor(lo, hi) {
+ this.lo = lo | 0;
+ this.hi = hi | 0;
}
- } else {
- if (typeof handler.onHeaders !== 'function') {
- throw new InvalidArgumentError('invalid onHeaders method')
+ /**
+ * Is this instance equal to 0?
+ */
+ isZero() {
+ return this.lo == 0 && this.hi == 0;
}
-
- if (typeof handler.onData !== 'function') {
- throw new InvalidArgumentError('invalid onData method')
+ /**
+ * Convert to a native number.
+ */
+ toNumber() {
+ let result = this.hi * TWO_PWR_32_DBL + (this.lo >>> 0);
+ if (!Number.isSafeInteger(result))
+ throw new Error("cannot convert to safe number");
+ return result;
}
-
- if (typeof handler.onComplete !== 'function') {
- throw new InvalidArgumentError('invalid onComplete method')
+}
+/**
+ * 64-bit unsigned integer as two 32-bit values.
+ * Converts between `string`, `number` and `bigint` representations.
+ */
+class PbULong extends SharedPbLong {
+ /**
+ * Create instance from a `string`, `number` or `bigint`.
+ */
+ static from(value) {
+ if (BI)
+ // noinspection FallThroughInSwitchStatementJS
+ switch (typeof value) {
+ case "string":
+ if (value == "0")
+ return this.ZERO;
+ if (value == "")
+ throw new Error('string is no integer');
+ value = BI.C(value);
+ case "number":
+ if (value === 0)
+ return this.ZERO;
+ value = BI.C(value);
+ case "bigint":
+ if (!value)
+ return this.ZERO;
+ if (value < BI.UMIN)
+ throw new Error('signed value for ulong');
+ if (value > BI.UMAX)
+ throw new Error('ulong too large');
+ BI.V.setBigUint64(0, value, true);
+ return new PbULong(BI.V.getInt32(0, true), BI.V.getInt32(4, true));
+ }
+ else
+ switch (typeof value) {
+ case "string":
+ if (value == "0")
+ return this.ZERO;
+ value = value.trim();
+ if (!RE_DECIMAL_STR.test(value))
+ throw new Error('string is no integer');
+ let [minus, lo, hi] = goog_varint_1.int64fromString(value);
+ if (minus)
+ throw new Error('signed value for ulong');
+ return new PbULong(lo, hi);
+ case "number":
+ if (value == 0)
+ return this.ZERO;
+ if (!Number.isSafeInteger(value))
+ throw new Error('number is no integer');
+ if (value < 0)
+ throw new Error('signed value for ulong');
+ return new PbULong(value, value / TWO_PWR_32_DBL);
+ }
+ throw new Error('unknown value ' + typeof value);
+ }
+ /**
+ * Convert to decimal string.
+ */
+ toString() {
+ return BI ? this.toBigInt().toString() : goog_varint_1.int64toString(this.lo, this.hi);
+ }
+ /**
+ * Convert to native bigint.
+ */
+ toBigInt() {
+ assertBi(BI);
+ BI.V.setInt32(0, this.lo, true);
+ BI.V.setInt32(4, this.hi, true);
+ return BI.V.getBigUint64(0, true);
}
- }
}
-
-// A body is disturbed if it has been read from and it cannot
-// be re-used without losing state or data.
-function isDisturbed (body) {
- // TODO (fix): Why is body[kBodyUsed] needed?
- return !!(body && (stream.isDisturbed(body) || body[kBodyUsed]))
+exports.PbULong = PbULong;
+/**
+ * ulong 0 singleton.
+ */
+PbULong.ZERO = new PbULong(0, 0);
+/**
+ * 64-bit signed integer as two 32-bit values.
+ * Converts between `string`, `number` and `bigint` representations.
+ */
+class PbLong extends SharedPbLong {
+ /**
+ * Create instance from a `string`, `number` or `bigint`.
+ */
+ static from(value) {
+ if (BI)
+ // noinspection FallThroughInSwitchStatementJS
+ switch (typeof value) {
+ case "string":
+ if (value == "0")
+ return this.ZERO;
+ if (value == "")
+ throw new Error('string is no integer');
+ value = BI.C(value);
+ case "number":
+ if (value === 0)
+ return this.ZERO;
+ value = BI.C(value);
+ case "bigint":
+ if (!value)
+ return this.ZERO;
+ if (value < BI.MIN)
+ throw new Error('signed long too small');
+ if (value > BI.MAX)
+ throw new Error('signed long too large');
+ BI.V.setBigInt64(0, value, true);
+ return new PbLong(BI.V.getInt32(0, true), BI.V.getInt32(4, true));
+ }
+ else
+ switch (typeof value) {
+ case "string":
+ if (value == "0")
+ return this.ZERO;
+ value = value.trim();
+ if (!RE_DECIMAL_STR.test(value))
+ throw new Error('string is no integer');
+ let [minus, lo, hi] = goog_varint_1.int64fromString(value);
+ if (minus) {
+ if (hi > HALF_2_PWR_32 || (hi == HALF_2_PWR_32 && lo != 0))
+ throw new Error('signed long too small');
+ }
+ else if (hi >= HALF_2_PWR_32)
+ throw new Error('signed long too large');
+ let pbl = new PbLong(lo, hi);
+ return minus ? pbl.negate() : pbl;
+ case "number":
+ if (value == 0)
+ return this.ZERO;
+ if (!Number.isSafeInteger(value))
+ throw new Error('number is no integer');
+ return value > 0
+ ? new PbLong(value, value / TWO_PWR_32_DBL)
+ : new PbLong(-value, -value / TWO_PWR_32_DBL).negate();
+ }
+ throw new Error('unknown value ' + typeof value);
+ }
+ /**
+ * Do we have a minus sign?
+ */
+ isNegative() {
+ return (this.hi & HALF_2_PWR_32) !== 0;
+ }
+ /**
+ * Negate two's complement.
+ * Invert all the bits and add one to the result.
+ */
+ negate() {
+ let hi = ~this.hi, lo = this.lo;
+ if (lo)
+ lo = ~lo + 1;
+ else
+ hi += 1;
+ return new PbLong(lo, hi);
+ }
+ /**
+ * Convert to decimal string.
+ */
+ toString() {
+ if (BI)
+ return this.toBigInt().toString();
+ if (this.isNegative()) {
+ let n = this.negate();
+ return '-' + goog_varint_1.int64toString(n.lo, n.hi);
+ }
+ return goog_varint_1.int64toString(this.lo, this.hi);
+ }
+ /**
+ * Convert to native bigint.
+ */
+ toBigInt() {
+ assertBi(BI);
+ BI.V.setInt32(0, this.lo, true);
+ BI.V.setInt32(4, this.hi, true);
+ return BI.V.getBigInt64(0, true);
+ }
}
+exports.PbLong = PbLong;
+/**
+ * long 0 singleton.
+ */
+PbLong.ZERO = new PbLong(0, 0);
-function isErrored (body) {
- return !!(body && stream.isErrored(body))
-}
-function isReadable (body) {
- return !!(body && stream.isReadable(body))
-}
+/***/ }),
-function getSocketInfo (socket) {
- return {
- localAddress: socket.localAddress,
- localPort: socket.localPort,
- remoteAddress: socket.remoteAddress,
- remotePort: socket.remotePort,
- remoteFamily: socket.remoteFamily,
- timeout: socket.timeout,
- bytesWritten: socket.bytesWritten,
- bytesRead: socket.bytesRead
- }
-}
+/***/ 8950:
+/***/ ((__unused_webpack_module, exports) => {
-/** @type {globalThis['ReadableStream']} */
-function ReadableStreamFrom (iterable) {
- // We cannot use ReadableStream.from here because it does not return a byte stream.
- let iterator
- return new ReadableStream(
- {
- async start () {
- iterator = iterable[Symbol.asyncIterator]()
- },
- async pull (controller) {
- const { done, value } = await iterator.next()
- if (done) {
- queueMicrotask(() => {
- controller.close()
- controller.byobRequest?.respond(0)
- })
- } else {
- const buf = Buffer.isBuffer(value) ? value : Buffer.from(value)
- if (buf.byteLength) {
- controller.enqueue(new Uint8Array(buf))
- }
+// Copyright (c) 2016, Daniel Wirtz All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above copyright
+// notice, this list of conditions and the following disclaimer in the
+// documentation and/or other materials provided with the distribution.
+// * Neither the name of its author, nor the names of its contributors
+// may be used to endorse or promote products derived from this software
+// without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.utf8read = void 0;
+const fromCharCodes = (chunk) => String.fromCharCode.apply(String, chunk);
+/**
+ * @deprecated This function will no longer be exported with the next major
+ * release, since protobuf-ts has switch to TextDecoder API. If you need this
+ * function, please migrate to @protobufjs/utf8. For context, see
+ * https://github.com/timostamm/protobuf-ts/issues/184
+ *
+ * Reads UTF8 bytes as a string.
+ *
+ * See [protobufjs / utf8](https://github.com/protobufjs/protobuf.js/blob/9893e35b854621cce64af4bf6be2cff4fb892796/lib/utf8/index.js#L40)
+ *
+ * Copyright (c) 2016, Daniel Wirtz
+ */
+function utf8read(bytes) {
+ if (bytes.length < 1)
+ return "";
+ let pos = 0, // position in bytes
+ parts = [], chunk = [], i = 0, // char offset
+ t; // temporary
+ let len = bytes.length;
+ while (pos < len) {
+ t = bytes[pos++];
+ if (t < 128)
+ chunk[i++] = t;
+ else if (t > 191 && t < 224)
+ chunk[i++] = (t & 31) << 6 | bytes[pos++] & 63;
+ else if (t > 239 && t < 365) {
+ t = ((t & 7) << 18 | (bytes[pos++] & 63) << 12 | (bytes[pos++] & 63) << 6 | bytes[pos++] & 63) - 0x10000;
+ chunk[i++] = 0xD800 + (t >> 10);
+ chunk[i++] = 0xDC00 + (t & 1023);
+ }
+ else
+ chunk[i++] = (t & 15) << 12 | (bytes[pos++] & 63) << 6 | bytes[pos++] & 63;
+ if (i > 8191) {
+ parts.push(fromCharCodes(chunk));
+ i = 0;
}
- return controller.desiredSize > 0
- },
- async cancel (reason) {
- await iterator.return()
- },
- type: 'bytes'
}
- )
-}
-
-// The chunk should be a FormData instance and contains
-// all the required methods.
-function isFormDataLike (object) {
- return (
- object &&
- typeof object === 'object' &&
- typeof object.append === 'function' &&
- typeof object.delete === 'function' &&
- typeof object.get === 'function' &&
- typeof object.getAll === 'function' &&
- typeof object.has === 'function' &&
- typeof object.set === 'function' &&
- object[Symbol.toStringTag] === 'FormData'
- )
+ if (parts.length) {
+ if (i)
+ parts.push(fromCharCodes(chunk.slice(0, i)));
+ return parts.join("");
+ }
+ return fromCharCodes(chunk.slice(0, i));
}
+exports.utf8read = utf8read;
-function addAbortListener (signal, listener) {
- if ('addEventListener' in signal) {
- signal.addEventListener('abort', listener, { once: true })
- return () => signal.removeEventListener('abort', listener)
- }
- signal.addListener('abort', listener)
- return () => signal.removeListener('abort', listener)
-}
-const hasToWellFormed = typeof String.prototype.toWellFormed === 'function'
-const hasIsWellFormed = typeof String.prototype.isWellFormed === 'function'
+/***/ }),
-/**
- * @param {string} val
- */
-function toUSVString (val) {
- return hasToWellFormed ? `${val}`.toWellFormed() : nodeUtil.toUSVString(val)
-}
+/***/ 9611:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-/**
- * @param {string} val
- */
-// TODO: move this to webidl
-function isUSVString (val) {
- return hasIsWellFormed ? `${val}`.isWellFormed() : toUSVString(val) === `${val}`
-}
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.ReflectionBinaryReader = void 0;
+const binary_format_contract_1 = __nccwpck_require__(4816);
+const reflection_info_1 = __nccwpck_require__(7910);
+const reflection_long_convert_1 = __nccwpck_require__(3402);
+const reflection_scalar_default_1 = __nccwpck_require__(9526);
/**
- * @see https://tools.ietf.org/html/rfc7230#section-3.2.6
- * @param {number} c
+ * Reads proto3 messages in binary format using reflection information.
+ *
+ * https://developers.google.com/protocol-buffers/docs/encoding
*/
-function isTokenCharCode (c) {
- switch (c) {
- case 0x22:
- case 0x28:
- case 0x29:
- case 0x2c:
- case 0x2f:
- case 0x3a:
- case 0x3b:
- case 0x3c:
- case 0x3d:
- case 0x3e:
- case 0x3f:
- case 0x40:
- case 0x5b:
- case 0x5c:
- case 0x5d:
- case 0x7b:
- case 0x7d:
- // DQUOTE and "(),/:;<=>?@[\]{}"
- return false
- default:
- // VCHAR %x21-7E
- return c >= 0x21 && c <= 0x7e
- }
-}
-
-/**
- * @param {string} characters
- */
-function isValidHTTPToken (characters) {
- if (characters.length === 0) {
- return false
- }
- for (let i = 0; i < characters.length; ++i) {
- if (!isTokenCharCode(characters.charCodeAt(i))) {
- return false
+class ReflectionBinaryReader {
+ constructor(info) {
+ this.info = info;
+ }
+ prepare() {
+ var _a;
+ if (!this.fieldNoToField) {
+ const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : [];
+ this.fieldNoToField = new Map(fieldsInput.map(field => [field.no, field]));
+ }
+ }
+ /**
+ * Reads a message from binary format into the target message.
+ *
+ * Repeated fields are appended. Map entries are added, overwriting
+ * existing keys.
+ *
+ * If a message field is already present, it will be merged with the
+ * new data.
+ */
+ read(reader, message, options, length) {
+ this.prepare();
+ const end = length === undefined ? reader.len : reader.pos + length;
+ while (reader.pos < end) {
+ // read the tag and find the field
+ const [fieldNo, wireType] = reader.tag(), field = this.fieldNoToField.get(fieldNo);
+ if (!field) {
+ let u = options.readUnknownField;
+ if (u == "throw")
+ throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.info.typeName}`);
+ let d = reader.skip(wireType);
+ if (u !== false)
+ (u === true ? binary_format_contract_1.UnknownFieldHandler.onRead : u)(this.info.typeName, message, fieldNo, wireType, d);
+ continue;
+ }
+ // target object for the field we are reading
+ let target = message, repeated = field.repeat, localName = field.localName;
+ // if field is member of oneof ADT, use ADT as target
+ if (field.oneof) {
+ target = target[field.oneof];
+ // if other oneof member selected, set new ADT
+ if (target.oneofKind !== localName)
+ target = message[field.oneof] = {
+ oneofKind: localName
+ };
+ }
+ // we have handled oneof above, we just have read the value into `target[localName]`
+ switch (field.kind) {
+ case "scalar":
+ case "enum":
+ let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T;
+ let L = field.kind == "scalar" ? field.L : undefined;
+ if (repeated) {
+ let arr = target[localName]; // safe to assume presence of array, oneof cannot contain repeated values
+ if (wireType == binary_format_contract_1.WireType.LengthDelimited && T != reflection_info_1.ScalarType.STRING && T != reflection_info_1.ScalarType.BYTES) {
+ let e = reader.uint32() + reader.pos;
+ while (reader.pos < e)
+ arr.push(this.scalar(reader, T, L));
+ }
+ else
+ arr.push(this.scalar(reader, T, L));
+ }
+ else
+ target[localName] = this.scalar(reader, T, L);
+ break;
+ case "message":
+ if (repeated) {
+ let arr = target[localName]; // safe to assume presence of array, oneof cannot contain repeated values
+ let msg = field.T().internalBinaryRead(reader, reader.uint32(), options);
+ arr.push(msg);
+ }
+ else
+ target[localName] = field.T().internalBinaryRead(reader, reader.uint32(), options, target[localName]);
+ break;
+ case "map":
+ let [mapKey, mapVal] = this.mapEntry(field, reader, options);
+ // safe to assume presence of map object, oneof cannot contain repeated values
+ target[localName][mapKey] = mapVal;
+ break;
+ }
+ }
+ }
+ /**
+ * Read a map field, expecting key field = 1, value field = 2
+ */
+ mapEntry(field, reader, options) {
+ let length = reader.uint32();
+ let end = reader.pos + length;
+ let key = undefined; // javascript only allows number or string for object properties
+ let val = undefined;
+ while (reader.pos < end) {
+ let [fieldNo, wireType] = reader.tag();
+ switch (fieldNo) {
+ case 1:
+ if (field.K == reflection_info_1.ScalarType.BOOL)
+ key = reader.bool().toString();
+ else
+ // long types are read as string, number types are okay as number
+ key = this.scalar(reader, field.K, reflection_info_1.LongType.STRING);
+ break;
+ case 2:
+ switch (field.V.kind) {
+ case "scalar":
+ val = this.scalar(reader, field.V.T, field.V.L);
+ break;
+ case "enum":
+ val = reader.int32();
+ break;
+ case "message":
+ val = field.V.T().internalBinaryRead(reader, reader.uint32(), options);
+ break;
+ }
+ break;
+ default:
+ throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) in map entry for ${this.info.typeName}#${field.name}`);
+ }
+ }
+ if (key === undefined) {
+ let keyRaw = reflection_scalar_default_1.reflectionScalarDefault(field.K);
+ key = field.K == reflection_info_1.ScalarType.BOOL ? keyRaw.toString() : keyRaw;
+ }
+ if (val === undefined)
+ switch (field.V.kind) {
+ case "scalar":
+ val = reflection_scalar_default_1.reflectionScalarDefault(field.V.T, field.V.L);
+ break;
+ case "enum":
+ val = 0;
+ break;
+ case "message":
+ val = field.V.T().create();
+ break;
+ }
+ return [key, val];
+ }
+ scalar(reader, type, longType) {
+ switch (type) {
+ case reflection_info_1.ScalarType.INT32:
+ return reader.int32();
+ case reflection_info_1.ScalarType.STRING:
+ return reader.string();
+ case reflection_info_1.ScalarType.BOOL:
+ return reader.bool();
+ case reflection_info_1.ScalarType.DOUBLE:
+ return reader.double();
+ case reflection_info_1.ScalarType.FLOAT:
+ return reader.float();
+ case reflection_info_1.ScalarType.INT64:
+ return reflection_long_convert_1.reflectionLongConvert(reader.int64(), longType);
+ case reflection_info_1.ScalarType.UINT64:
+ return reflection_long_convert_1.reflectionLongConvert(reader.uint64(), longType);
+ case reflection_info_1.ScalarType.FIXED64:
+ return reflection_long_convert_1.reflectionLongConvert(reader.fixed64(), longType);
+ case reflection_info_1.ScalarType.FIXED32:
+ return reader.fixed32();
+ case reflection_info_1.ScalarType.BYTES:
+ return reader.bytes();
+ case reflection_info_1.ScalarType.UINT32:
+ return reader.uint32();
+ case reflection_info_1.ScalarType.SFIXED32:
+ return reader.sfixed32();
+ case reflection_info_1.ScalarType.SFIXED64:
+ return reflection_long_convert_1.reflectionLongConvert(reader.sfixed64(), longType);
+ case reflection_info_1.ScalarType.SINT32:
+ return reader.sint32();
+ case reflection_info_1.ScalarType.SINT64:
+ return reflection_long_convert_1.reflectionLongConvert(reader.sint64(), longType);
+ }
}
- }
- return true
}
+exports.ReflectionBinaryReader = ReflectionBinaryReader;
-// headerCharRegex have been lifted from
-// https://github.com/nodejs/node/blob/main/lib/_http_common.js
-/**
- * Matches if val contains an invalid field-vchar
- * field-value = *( field-content / obs-fold )
- * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
- * field-vchar = VCHAR / obs-text
- */
-const headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/
+/***/ }),
+
+/***/ 6907:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.ReflectionBinaryWriter = void 0;
+const binary_format_contract_1 = __nccwpck_require__(4816);
+const reflection_info_1 = __nccwpck_require__(7910);
+const assert_1 = __nccwpck_require__(8602);
+const pb_long_1 = __nccwpck_require__(1753);
/**
- * @param {string} characters
+ * Writes proto3 messages in binary format using reflection information.
+ *
+ * https://developers.google.com/protocol-buffers/docs/encoding
*/
-function isValidHeaderValue (characters) {
- return !headerCharRegex.test(characters)
+class ReflectionBinaryWriter {
+ constructor(info) {
+ this.info = info;
+ }
+ prepare() {
+ if (!this.fields) {
+ const fieldsInput = this.info.fields ? this.info.fields.concat() : [];
+ this.fields = fieldsInput.sort((a, b) => a.no - b.no);
+ }
+ }
+ /**
+ * Writes the message to binary format.
+ */
+ write(message, writer, options) {
+ this.prepare();
+ for (const field of this.fields) {
+ let value, // this will be our field value, whether it is member of a oneof or not
+ emitDefault, // whether we emit the default value (only true for oneof members)
+ repeated = field.repeat, localName = field.localName;
+ // handle oneof ADT
+ if (field.oneof) {
+ const group = message[field.oneof];
+ if (group.oneofKind !== localName)
+ continue; // if field is not selected, skip
+ value = group[localName];
+ emitDefault = true;
+ }
+ else {
+ value = message[localName];
+ emitDefault = false;
+ }
+ // we have handled oneof above. we just have to honor `emitDefault`.
+ switch (field.kind) {
+ case "scalar":
+ case "enum":
+ let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T;
+ if (repeated) {
+ assert_1.assert(Array.isArray(value));
+ if (repeated == reflection_info_1.RepeatType.PACKED)
+ this.packed(writer, T, field.no, value);
+ else
+ for (const item of value)
+ this.scalar(writer, T, field.no, item, true);
+ }
+ else if (value === undefined)
+ assert_1.assert(field.opt);
+ else
+ this.scalar(writer, T, field.no, value, emitDefault || field.opt);
+ break;
+ case "message":
+ if (repeated) {
+ assert_1.assert(Array.isArray(value));
+ for (const item of value)
+ this.message(writer, options, field.T(), field.no, item);
+ }
+ else {
+ this.message(writer, options, field.T(), field.no, value);
+ }
+ break;
+ case "map":
+ assert_1.assert(typeof value == 'object' && value !== null);
+ for (const [key, val] of Object.entries(value))
+ this.mapEntry(writer, options, field, key, val);
+ break;
+ }
+ }
+ let u = options.writeUnknownFields;
+ if (u !== false)
+ (u === true ? binary_format_contract_1.UnknownFieldHandler.onWrite : u)(this.info.typeName, message, writer);
+ }
+ mapEntry(writer, options, field, key, value) {
+ writer.tag(field.no, binary_format_contract_1.WireType.LengthDelimited);
+ writer.fork();
+ // javascript only allows number or string for object properties
+ // we convert from our representation to the protobuf type
+ let keyValue = key;
+ switch (field.K) {
+ case reflection_info_1.ScalarType.INT32:
+ case reflection_info_1.ScalarType.FIXED32:
+ case reflection_info_1.ScalarType.UINT32:
+ case reflection_info_1.ScalarType.SFIXED32:
+ case reflection_info_1.ScalarType.SINT32:
+ keyValue = Number.parseInt(key);
+ break;
+ case reflection_info_1.ScalarType.BOOL:
+ assert_1.assert(key == 'true' || key == 'false');
+ keyValue = key == 'true';
+ break;
+ }
+ // write key, expecting key field number = 1
+ this.scalar(writer, field.K, 1, keyValue, true);
+ // write value, expecting value field number = 2
+ switch (field.V.kind) {
+ case 'scalar':
+ this.scalar(writer, field.V.T, 2, value, true);
+ break;
+ case 'enum':
+ this.scalar(writer, reflection_info_1.ScalarType.INT32, 2, value, true);
+ break;
+ case 'message':
+ this.message(writer, options, field.V.T(), 2, value);
+ break;
+ }
+ writer.join();
+ }
+ message(writer, options, handler, fieldNo, value) {
+ if (value === undefined)
+ return;
+ handler.internalBinaryWrite(value, writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited).fork(), options);
+ writer.join();
+ }
+ /**
+ * Write a single scalar value.
+ */
+ scalar(writer, type, fieldNo, value, emitDefault) {
+ let [wireType, method, isDefault] = this.scalarInfo(type, value);
+ if (!isDefault || emitDefault) {
+ writer.tag(fieldNo, wireType);
+ writer[method](value);
+ }
+ }
+ /**
+ * Write an array of scalar values in packed format.
+ */
+ packed(writer, type, fieldNo, value) {
+ if (!value.length)
+ return;
+ assert_1.assert(type !== reflection_info_1.ScalarType.BYTES && type !== reflection_info_1.ScalarType.STRING);
+ // write tag
+ writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited);
+ // begin length-delimited
+ writer.fork();
+ // write values without tags
+ let [, method,] = this.scalarInfo(type);
+ for (let i = 0; i < value.length; i++)
+ writer[method](value[i]);
+ // end length delimited
+ writer.join();
+ }
+ /**
+ * Get information for writing a scalar value.
+ *
+ * Returns tuple:
+ * [0]: appropriate WireType
+ * [1]: name of the appropriate method of IBinaryWriter
+ * [2]: whether the given value is a default value
+ *
+ * If argument `value` is omitted, [2] is always false.
+ */
+ scalarInfo(type, value) {
+ let t = binary_format_contract_1.WireType.Varint;
+ let m;
+ let i = value === undefined;
+ let d = value === 0;
+ switch (type) {
+ case reflection_info_1.ScalarType.INT32:
+ m = "int32";
+ break;
+ case reflection_info_1.ScalarType.STRING:
+ d = i || !value.length;
+ t = binary_format_contract_1.WireType.LengthDelimited;
+ m = "string";
+ break;
+ case reflection_info_1.ScalarType.BOOL:
+ d = value === false;
+ m = "bool";
+ break;
+ case reflection_info_1.ScalarType.UINT32:
+ m = "uint32";
+ break;
+ case reflection_info_1.ScalarType.DOUBLE:
+ t = binary_format_contract_1.WireType.Bit64;
+ m = "double";
+ break;
+ case reflection_info_1.ScalarType.FLOAT:
+ t = binary_format_contract_1.WireType.Bit32;
+ m = "float";
+ break;
+ case reflection_info_1.ScalarType.INT64:
+ d = i || pb_long_1.PbLong.from(value).isZero();
+ m = "int64";
+ break;
+ case reflection_info_1.ScalarType.UINT64:
+ d = i || pb_long_1.PbULong.from(value).isZero();
+ m = "uint64";
+ break;
+ case reflection_info_1.ScalarType.FIXED64:
+ d = i || pb_long_1.PbULong.from(value).isZero();
+ t = binary_format_contract_1.WireType.Bit64;
+ m = "fixed64";
+ break;
+ case reflection_info_1.ScalarType.BYTES:
+ d = i || !value.byteLength;
+ t = binary_format_contract_1.WireType.LengthDelimited;
+ m = "bytes";
+ break;
+ case reflection_info_1.ScalarType.FIXED32:
+ t = binary_format_contract_1.WireType.Bit32;
+ m = "fixed32";
+ break;
+ case reflection_info_1.ScalarType.SFIXED32:
+ t = binary_format_contract_1.WireType.Bit32;
+ m = "sfixed32";
+ break;
+ case reflection_info_1.ScalarType.SFIXED64:
+ d = i || pb_long_1.PbLong.from(value).isZero();
+ t = binary_format_contract_1.WireType.Bit64;
+ m = "sfixed64";
+ break;
+ case reflection_info_1.ScalarType.SINT32:
+ m = "sint32";
+ break;
+ case reflection_info_1.ScalarType.SINT64:
+ d = i || pb_long_1.PbLong.from(value).isZero();
+ m = "sint64";
+ break;
+ }
+ return [t, m, i || d];
+ }
}
+exports.ReflectionBinaryWriter = ReflectionBinaryWriter;
-// Parsed accordingly to RFC 9110
-// https://www.rfc-editor.org/rfc/rfc9110#field.content-range
-function parseRangeHeader (range) {
- if (range == null || range === '') return { start: 0, end: null, size: null }
- const m = range ? range.match(/^bytes (\d+)-(\d+)\/(\d+)?$/) : null
- return m
- ? {
- start: parseInt(m[1]),
- end: m[2] ? parseInt(m[2]) : null,
- size: m[3] ? parseInt(m[3]) : null
- }
- : null
-}
+/***/ }),
-function addListener (obj, name, listener) {
- const listeners = (obj[kListeners] ??= [])
- listeners.push([name, listener])
- obj.on(name, listener)
- return obj
-}
+/***/ 9946:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-function removeAllListeners (obj) {
- for (const [name, listener] of obj[kListeners] ?? []) {
- obj.removeListener(name, listener)
- }
- obj[kListeners] = null
-}
-function errorRequest (client, request, err) {
- try {
- request.onError(err)
- assert(request.aborted)
- } catch (err) {
- client.emit('error', err)
- }
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.containsMessageType = void 0;
+const message_type_contract_1 = __nccwpck_require__(3785);
+/**
+ * Check if the provided object is a proto message.
+ *
+ * Note that this is an experimental feature - it is here to stay, but
+ * implementation details may change without notice.
+ */
+function containsMessageType(msg) {
+ return msg[message_type_contract_1.MESSAGE_TYPE] != null;
}
+exports.containsMessageType = containsMessageType;
-const kEnumerableProperty = Object.create(null)
-kEnumerableProperty.enumerable = true
-const normalizedMethodRecordsBase = {
- delete: 'DELETE',
- DELETE: 'DELETE',
- get: 'GET',
- GET: 'GET',
- head: 'HEAD',
- HEAD: 'HEAD',
- options: 'OPTIONS',
- OPTIONS: 'OPTIONS',
- post: 'POST',
- POST: 'POST',
- put: 'PUT',
- PUT: 'PUT'
-}
+/***/ }),
-const normalizedMethodRecords = {
- ...normalizedMethodRecordsBase,
- patch: 'patch',
- PATCH: 'PATCH'
-}
+/***/ 5726:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`.
-Object.setPrototypeOf(normalizedMethodRecordsBase, null)
-Object.setPrototypeOf(normalizedMethodRecords, null)
-module.exports = {
- kEnumerableProperty,
- nop,
- isDisturbed,
- isErrored,
- isReadable,
- toUSVString,
- isUSVString,
- isBlobLike,
- parseOrigin,
- parseURL,
- getServerName,
- isStream,
- isIterable,
- isAsyncIterable,
- isDestroyed,
- headerNameToString,
- bufferToLowerCasedHeaderName,
- addListener,
- removeAllListeners,
- errorRequest,
- parseRawHeaders,
- parseHeaders,
- parseKeepAliveTimeout,
- destroy,
- bodyLength,
- deepClone,
- ReadableStreamFrom,
- isBuffer,
- validateHandler,
- getSocketInfo,
- isFormDataLike,
- buildURL,
- addAbortListener,
- isValidHTTPToken,
- isValidHeaderValue,
- isTokenCharCode,
- parseRangeHeader,
- normalizedMethodRecordsBase,
- normalizedMethodRecords,
- isValidPort,
- isHttpOrHttpsPrefixed,
- nodeMajor,
- nodeMinor,
- safeHTTPMethods: ['GET', 'HEAD', 'OPTIONS', 'TRACE'],
- wrapRequestBody
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.reflectionCreate = void 0;
+const reflection_scalar_default_1 = __nccwpck_require__(9526);
+const message_type_contract_1 = __nccwpck_require__(3785);
+/**
+ * Creates an instance of the generic message, using the field
+ * information.
+ */
+function reflectionCreate(type) {
+ /**
+ * This ternary can be removed in the next major version.
+ * The `Object.create()` code path utilizes a new `messagePrototype`
+ * property on the `IMessageType` which has this same `MESSAGE_TYPE`
+ * non-enumerable property on it. Doing it this way means that we only
+ * pay the cost of `Object.defineProperty()` once per `IMessageType`
+ * class of once per "instance". The falsy code path is only provided
+ * for backwards compatibility in cases where the runtime library is
+ * updated without also updating the generated code.
+ */
+ const msg = type.messagePrototype
+ ? Object.create(type.messagePrototype)
+ : Object.defineProperty({}, message_type_contract_1.MESSAGE_TYPE, { value: type });
+ for (let field of type.fields) {
+ let name = field.localName;
+ if (field.opt)
+ continue;
+ if (field.oneof)
+ msg[field.oneof] = { oneofKind: undefined };
+ else if (field.repeat)
+ msg[name] = [];
+ else
+ switch (field.kind) {
+ case "scalar":
+ msg[name] = reflection_scalar_default_1.reflectionScalarDefault(field.T, field.L);
+ break;
+ case "enum":
+ // we require 0 to be default value for all enums
+ msg[name] = 0;
+ break;
+ case "map":
+ msg[name] = {};
+ break;
+ }
+ }
+ return msg;
}
+exports.reflectionCreate = reflectionCreate;
/***/ }),
-/***/ 4332:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const { InvalidArgumentError } = __nccwpck_require__(2344)
-const { kClients, kRunning, kClose, kDestroy, kDispatch, kInterceptors } = __nccwpck_require__(6130)
-const DispatcherBase = __nccwpck_require__(2540)
-const Pool = __nccwpck_require__(3959)
-const Client = __nccwpck_require__(2138)
-const util = __nccwpck_require__(7375)
-const createRedirectInterceptor = __nccwpck_require__(6097)
-
-const kOnConnect = Symbol('onConnect')
-const kOnDisconnect = Symbol('onDisconnect')
-const kOnConnectionError = Symbol('onConnectionError')
-const kMaxRedirections = Symbol('maxRedirections')
-const kOnDrain = Symbol('onDrain')
-const kFactory = Symbol('factory')
-const kOptions = Symbol('options')
-
-function defaultFactory (origin, opts) {
- return opts && opts.connections === 1
- ? new Client(origin, opts)
- : new Pool(origin, opts)
-}
-
-class Agent extends DispatcherBase {
- constructor ({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) {
- super()
-
- if (typeof factory !== 'function') {
- throw new InvalidArgumentError('factory must be a function.')
- }
-
- if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {
- throw new InvalidArgumentError('connect must be a function or an object')
- }
-
- if (!Number.isInteger(maxRedirections) || maxRedirections < 0) {
- throw new InvalidArgumentError('maxRedirections must be a positive number')
- }
-
- if (connect && typeof connect !== 'function') {
- connect = { ...connect }
- }
-
- this[kInterceptors] = options.interceptors?.Agent && Array.isArray(options.interceptors.Agent)
- ? options.interceptors.Agent
- : [createRedirectInterceptor({ maxRedirections })]
-
- this[kOptions] = { ...util.deepClone(options), connect }
- this[kOptions].interceptors = options.interceptors
- ? { ...options.interceptors }
- : undefined
- this[kMaxRedirections] = maxRedirections
- this[kFactory] = factory
- this[kClients] = new Map()
-
- this[kOnDrain] = (origin, targets) => {
- this.emit('drain', origin, [this, ...targets])
- }
-
- this[kOnConnect] = (origin, targets) => {
- this.emit('connect', origin, [this, ...targets])
- }
+/***/ 4827:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- this[kOnDisconnect] = (origin, targets, err) => {
- this.emit('disconnect', origin, [this, ...targets], err)
- }
- this[kOnConnectionError] = (origin, targets, err) => {
- this.emit('connectionError', origin, [this, ...targets], err)
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.reflectionEquals = void 0;
+const reflection_info_1 = __nccwpck_require__(7910);
+/**
+ * Determines whether two message of the same type have the same field values.
+ * Checks for deep equality, traversing repeated fields, oneof groups, maps
+ * and messages recursively.
+ * Will also return true if both messages are `undefined`.
+ */
+function reflectionEquals(info, a, b) {
+ if (a === b)
+ return true;
+ if (!a || !b)
+ return false;
+ for (let field of info.fields) {
+ let localName = field.localName;
+ let val_a = field.oneof ? a[field.oneof][localName] : a[localName];
+ let val_b = field.oneof ? b[field.oneof][localName] : b[localName];
+ switch (field.kind) {
+ case "enum":
+ case "scalar":
+ let t = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T;
+ if (!(field.repeat
+ ? repeatedPrimitiveEq(t, val_a, val_b)
+ : primitiveEq(t, val_a, val_b)))
+ return false;
+ break;
+ case "map":
+ if (!(field.V.kind == "message"
+ ? repeatedMsgEq(field.V.T(), objectValues(val_a), objectValues(val_b))
+ : repeatedPrimitiveEq(field.V.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.V.T, objectValues(val_a), objectValues(val_b))))
+ return false;
+ break;
+ case "message":
+ let T = field.T();
+ if (!(field.repeat
+ ? repeatedMsgEq(T, val_a, val_b)
+ : T.equals(val_a, val_b)))
+ return false;
+ break;
+ }
}
- }
+ return true;
+}
+exports.reflectionEquals = reflectionEquals;
+const objectValues = Object.values;
+function primitiveEq(type, a, b) {
+ if (a === b)
+ return true;
+ if (type !== reflection_info_1.ScalarType.BYTES)
+ return false;
+ let ba = a;
+ let bb = b;
+ if (ba.length !== bb.length)
+ return false;
+ for (let i = 0; i < ba.length; i++)
+ if (ba[i] != bb[i])
+ return false;
+ return true;
+}
+function repeatedPrimitiveEq(type, a, b) {
+ if (a.length !== b.length)
+ return false;
+ for (let i = 0; i < a.length; i++)
+ if (!primitiveEq(type, a[i], b[i]))
+ return false;
+ return true;
+}
+function repeatedMsgEq(type, a, b) {
+ if (a.length !== b.length)
+ return false;
+ for (let i = 0; i < a.length; i++)
+ if (!type.equals(a[i], b[i]))
+ return false;
+ return true;
+}
- get [kRunning] () {
- let ret = 0
- for (const client of this[kClients].values()) {
- ret += client[kRunning]
- }
- return ret
- }
- [kDispatch] (opts, handler) {
- let key
- if (opts.origin && (typeof opts.origin === 'string' || opts.origin instanceof URL)) {
- key = String(opts.origin)
- } else {
- throw new InvalidArgumentError('opts.origin must be a non-empty string or URL.')
- }
+/***/ }),
- let dispatcher = this[kClients].get(key)
+/***/ 7910:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- if (!dispatcher) {
- dispatcher = this[kFactory](opts.origin, this[kOptions])
- .on('drain', this[kOnDrain])
- .on('connect', this[kOnConnect])
- .on('disconnect', this[kOnDisconnect])
- .on('connectionError', this[kOnConnectionError])
- // This introduces a tiny memory leak, as dispatchers are never removed from the map.
- // TODO(mcollina): remove te timer when the client/pool do not have any more
- // active connections.
- this[kClients].set(key, dispatcher)
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.readMessageOption = exports.readFieldOption = exports.readFieldOptions = exports.normalizeFieldInfo = exports.RepeatType = exports.LongType = exports.ScalarType = void 0;
+const lower_camel_case_1 = __nccwpck_require__(4073);
+/**
+ * Scalar value types. This is a subset of field types declared by protobuf
+ * enum google.protobuf.FieldDescriptorProto.Type The types GROUP and MESSAGE
+ * are omitted, but the numerical values are identical.
+ */
+var ScalarType;
+(function (ScalarType) {
+ // 0 is reserved for errors.
+ // Order is weird for historical reasons.
+ ScalarType[ScalarType["DOUBLE"] = 1] = "DOUBLE";
+ ScalarType[ScalarType["FLOAT"] = 2] = "FLOAT";
+ // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if
+ // negative values are likely.
+ ScalarType[ScalarType["INT64"] = 3] = "INT64";
+ ScalarType[ScalarType["UINT64"] = 4] = "UINT64";
+ // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if
+ // negative values are likely.
+ ScalarType[ScalarType["INT32"] = 5] = "INT32";
+ ScalarType[ScalarType["FIXED64"] = 6] = "FIXED64";
+ ScalarType[ScalarType["FIXED32"] = 7] = "FIXED32";
+ ScalarType[ScalarType["BOOL"] = 8] = "BOOL";
+ ScalarType[ScalarType["STRING"] = 9] = "STRING";
+ // Tag-delimited aggregate.
+ // Group type is deprecated and not supported in proto3. However, Proto3
+ // implementations should still be able to parse the group wire format and
+ // treat group fields as unknown fields.
+ // TYPE_GROUP = 10,
+ // TYPE_MESSAGE = 11, // Length-delimited aggregate.
+ // New in version 2.
+ ScalarType[ScalarType["BYTES"] = 12] = "BYTES";
+ ScalarType[ScalarType["UINT32"] = 13] = "UINT32";
+ // TYPE_ENUM = 14,
+ ScalarType[ScalarType["SFIXED32"] = 15] = "SFIXED32";
+ ScalarType[ScalarType["SFIXED64"] = 16] = "SFIXED64";
+ ScalarType[ScalarType["SINT32"] = 17] = "SINT32";
+ ScalarType[ScalarType["SINT64"] = 18] = "SINT64";
+})(ScalarType = exports.ScalarType || (exports.ScalarType = {}));
+/**
+ * JavaScript representation of 64 bit integral types. Equivalent to the
+ * field option "jstype".
+ *
+ * By default, protobuf-ts represents 64 bit types as `bigint`.
+ *
+ * You can change the default behaviour by enabling the plugin parameter
+ * `long_type_string`, which will represent 64 bit types as `string`.
+ *
+ * Alternatively, you can change the behaviour for individual fields
+ * with the field option "jstype":
+ *
+ * ```protobuf
+ * uint64 my_field = 1 [jstype = JS_STRING];
+ * uint64 other_field = 2 [jstype = JS_NUMBER];
+ * ```
+ */
+var LongType;
+(function (LongType) {
+ /**
+ * Use JavaScript `bigint`.
+ *
+ * Field option `[jstype = JS_NORMAL]`.
+ */
+ LongType[LongType["BIGINT"] = 0] = "BIGINT";
+ /**
+ * Use JavaScript `string`.
+ *
+ * Field option `[jstype = JS_STRING]`.
+ */
+ LongType[LongType["STRING"] = 1] = "STRING";
+ /**
+ * Use JavaScript `number`.
+ *
+ * Large values will loose precision.
+ *
+ * Field option `[jstype = JS_NUMBER]`.
+ */
+ LongType[LongType["NUMBER"] = 2] = "NUMBER";
+})(LongType = exports.LongType || (exports.LongType = {}));
+/**
+ * Protobuf 2.1.0 introduced packed repeated fields.
+ * Setting the field option `[packed = true]` enables packing.
+ *
+ * In proto3, all repeated fields are packed by default.
+ * Setting the field option `[packed = false]` disables packing.
+ *
+ * Packed repeated fields are encoded with a single tag,
+ * then a length-delimiter, then the element values.
+ *
+ * Unpacked repeated fields are encoded with a tag and
+ * value for each element.
+ *
+ * `bytes` and `string` cannot be packed.
+ */
+var RepeatType;
+(function (RepeatType) {
+ /**
+ * The field is not repeated.
+ */
+ RepeatType[RepeatType["NO"] = 0] = "NO";
+ /**
+ * The field is repeated and should be packed.
+ * Invalid for `bytes` and `string`, they cannot be packed.
+ */
+ RepeatType[RepeatType["PACKED"] = 1] = "PACKED";
+ /**
+ * The field is repeated but should not be packed.
+ * The only valid repeat type for repeated `bytes` and `string`.
+ */
+ RepeatType[RepeatType["UNPACKED"] = 2] = "UNPACKED";
+})(RepeatType = exports.RepeatType || (exports.RepeatType = {}));
+/**
+ * Turns PartialFieldInfo into FieldInfo.
+ */
+function normalizeFieldInfo(field) {
+ var _a, _b, _c, _d;
+ field.localName = (_a = field.localName) !== null && _a !== void 0 ? _a : lower_camel_case_1.lowerCamelCase(field.name);
+ field.jsonName = (_b = field.jsonName) !== null && _b !== void 0 ? _b : lower_camel_case_1.lowerCamelCase(field.name);
+ field.repeat = (_c = field.repeat) !== null && _c !== void 0 ? _c : RepeatType.NO;
+ field.opt = (_d = field.opt) !== null && _d !== void 0 ? _d : (field.repeat ? false : field.oneof ? false : field.kind == "message");
+ return field;
+}
+exports.normalizeFieldInfo = normalizeFieldInfo;
+/**
+ * Read custom field options from a generated message type.
+ *
+ * @deprecated use readFieldOption()
+ */
+function readFieldOptions(messageType, fieldName, extensionName, extensionType) {
+ var _a;
+ const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options;
+ return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : undefined;
+}
+exports.readFieldOptions = readFieldOptions;
+function readFieldOption(messageType, fieldName, extensionName, extensionType) {
+ var _a;
+ const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options;
+ if (!options) {
+ return undefined;
}
-
- return dispatcher.dispatch(opts, handler)
- }
-
- async [kClose] () {
- const closePromises = []
- for (const client of this[kClients].values()) {
- closePromises.push(client.close())
+ const optionVal = options[extensionName];
+ if (optionVal === undefined) {
+ return optionVal;
}
- this[kClients].clear()
-
- await Promise.all(closePromises)
- }
-
- async [kDestroy] (err) {
- const destroyPromises = []
- for (const client of this[kClients].values()) {
- destroyPromises.push(client.destroy(err))
+ return extensionType ? extensionType.fromJson(optionVal) : optionVal;
+}
+exports.readFieldOption = readFieldOption;
+function readMessageOption(messageType, extensionName, extensionType) {
+ const options = messageType.options;
+ const optionVal = options[extensionName];
+ if (optionVal === undefined) {
+ return optionVal;
}
- this[kClients].clear()
-
- await Promise.all(destroyPromises)
- }
+ return extensionType ? extensionType.fromJson(optionVal) : optionVal;
}
-
-module.exports = Agent
+exports.readMessageOption = readMessageOption;
/***/ }),
-/***/ 2188:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const {
- BalancedPoolMissingUpstreamError,
- InvalidArgumentError
-} = __nccwpck_require__(2344)
-const {
- PoolBase,
- kClients,
- kNeedDrain,
- kAddClient,
- kRemoveClient,
- kGetDispatcher
-} = __nccwpck_require__(3229)
-const Pool = __nccwpck_require__(3959)
-const { kUrl, kInterceptors } = __nccwpck_require__(6130)
-const { parseOrigin } = __nccwpck_require__(7375)
-const kFactory = Symbol('factory')
+/***/ 6790:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-const kOptions = Symbol('options')
-const kGreatestCommonDivisor = Symbol('kGreatestCommonDivisor')
-const kCurrentWeight = Symbol('kCurrentWeight')
-const kIndex = Symbol('kIndex')
-const kWeight = Symbol('kWeight')
-const kMaxWeightPerServer = Symbol('kMaxWeightPerServer')
-const kErrorPenalty = Symbol('kErrorPenalty')
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.ReflectionJsonReader = void 0;
+const json_typings_1 = __nccwpck_require__(9999);
+const base64_1 = __nccwpck_require__(6335);
+const reflection_info_1 = __nccwpck_require__(7910);
+const pb_long_1 = __nccwpck_require__(1753);
+const assert_1 = __nccwpck_require__(8602);
+const reflection_long_convert_1 = __nccwpck_require__(3402);
/**
- * Calculate the greatest common divisor of two numbers by
- * using the Euclidean algorithm.
+ * Reads proto3 messages in canonical JSON format using reflection information.
*
- * @param {number} a
- * @param {number} b
- * @returns {number}
+ * https://developers.google.com/protocol-buffers/docs/proto3#json
*/
-function getGreatestCommonDivisor (a, b) {
- if (a === 0) return b
-
- while (b !== 0) {
- const t = b
- b = a % b
- a = t
- }
- return a
-}
-
-function defaultFactory (origin, opts) {
- return new Pool(origin, opts)
-}
-
-class BalancedPool extends PoolBase {
- constructor (upstreams = [], { factory = defaultFactory, ...opts } = {}) {
- super()
-
- this[kOptions] = opts
- this[kIndex] = -1
- this[kCurrentWeight] = 0
-
- this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100
- this[kErrorPenalty] = this[kOptions].errorPenalty || 15
-
- if (!Array.isArray(upstreams)) {
- upstreams = [upstreams]
- }
-
- if (typeof factory !== 'function') {
- throw new InvalidArgumentError('factory must be a function.')
- }
-
- this[kInterceptors] = opts.interceptors?.BalancedPool && Array.isArray(opts.interceptors.BalancedPool)
- ? opts.interceptors.BalancedPool
- : []
- this[kFactory] = factory
-
- for (const upstream of upstreams) {
- this.addUpstream(upstream)
- }
- this._updateBalancedPoolStats()
- }
-
- addUpstream (upstream) {
- const upstreamOrigin = parseOrigin(upstream).origin
-
- if (this[kClients].find((pool) => (
- pool[kUrl].origin === upstreamOrigin &&
- pool.closed !== true &&
- pool.destroyed !== true
- ))) {
- return this
- }
- const pool = this[kFactory](upstreamOrigin, Object.assign({}, this[kOptions]))
-
- this[kAddClient](pool)
- pool.on('connect', () => {
- pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty])
- })
-
- pool.on('connectionError', () => {
- pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty])
- this._updateBalancedPoolStats()
- })
-
- pool.on('disconnect', (...args) => {
- const err = args[2]
- if (err && err.code === 'UND_ERR_SOCKET') {
- // decrease the weight of the pool.
- pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty])
- this._updateBalancedPoolStats()
- }
- })
-
- for (const client of this[kClients]) {
- client[kWeight] = this[kMaxWeightPerServer]
- }
-
- this._updateBalancedPoolStats()
-
- return this
- }
-
- _updateBalancedPoolStats () {
- let result = 0
- for (let i = 0; i < this[kClients].length; i++) {
- result = getGreatestCommonDivisor(this[kClients][i][kWeight], result)
+class ReflectionJsonReader {
+ constructor(info) {
+ this.info = info;
}
-
- this[kGreatestCommonDivisor] = result
- }
-
- removeUpstream (upstream) {
- const upstreamOrigin = parseOrigin(upstream).origin
-
- const pool = this[kClients].find((pool) => (
- pool[kUrl].origin === upstreamOrigin &&
- pool.closed !== true &&
- pool.destroyed !== true
- ))
-
- if (pool) {
- this[kRemoveClient](pool)
+ prepare() {
+ var _a;
+ if (this.fMap === undefined) {
+ this.fMap = {};
+ const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : [];
+ for (const field of fieldsInput) {
+ this.fMap[field.name] = field;
+ this.fMap[field.jsonName] = field;
+ this.fMap[field.localName] = field;
+ }
+ }
}
-
- return this
- }
-
- get upstreams () {
- return this[kClients]
- .filter(dispatcher => dispatcher.closed !== true && dispatcher.destroyed !== true)
- .map((p) => p[kUrl].origin)
- }
-
- [kGetDispatcher] () {
- // We validate that pools is greater than 0,
- // otherwise we would have to wait until an upstream
- // is added, which might never happen.
- if (this[kClients].length === 0) {
- throw new BalancedPoolMissingUpstreamError()
+ // Cannot parse JSON for #.
+ assert(condition, fieldName, jsonValue) {
+ if (!condition) {
+ let what = json_typings_1.typeofJsonValue(jsonValue);
+ if (what == "number" || what == "boolean")
+ what = jsonValue.toString();
+ throw new Error(`Cannot parse JSON ${what} for ${this.info.typeName}#${fieldName}`);
+ }
}
-
- const dispatcher = this[kClients].find(dispatcher => (
- !dispatcher[kNeedDrain] &&
- dispatcher.closed !== true &&
- dispatcher.destroyed !== true
- ))
-
- if (!dispatcher) {
- return
+ /**
+ * Reads a message from canonical JSON format into the target message.
+ *
+ * Repeated fields are appended. Map entries are added, overwriting
+ * existing keys.
+ *
+ * If a message field is already present, it will be merged with the
+ * new data.
+ */
+ read(input, message, options) {
+ this.prepare();
+ const oneofsHandled = [];
+ for (const [jsonKey, jsonValue] of Object.entries(input)) {
+ const field = this.fMap[jsonKey];
+ if (!field) {
+ if (!options.ignoreUnknownFields)
+ throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${jsonKey}`);
+ continue;
+ }
+ const localName = field.localName;
+ // handle oneof ADT
+ let target; // this will be the target for the field value, whether it is member of a oneof or not
+ if (field.oneof) {
+ if (jsonValue === null && (field.kind !== 'enum' || field.T()[0] !== 'google.protobuf.NullValue')) {
+ continue;
+ }
+ // since json objects are unordered by specification, it is not possible to take the last of multiple oneofs
+ if (oneofsHandled.includes(field.oneof))
+ throw new Error(`Multiple members of the oneof group "${field.oneof}" of ${this.info.typeName} are present in JSON.`);
+ oneofsHandled.push(field.oneof);
+ target = message[field.oneof] = {
+ oneofKind: localName
+ };
+ }
+ else {
+ target = message;
+ }
+ // we have handled oneof above. we just have read the value into `target`.
+ if (field.kind == 'map') {
+ if (jsonValue === null) {
+ continue;
+ }
+ // check input
+ this.assert(json_typings_1.isJsonObject(jsonValue), field.name, jsonValue);
+ // our target to put map entries into
+ const fieldObj = target[localName];
+ // read entries
+ for (const [jsonObjKey, jsonObjValue] of Object.entries(jsonValue)) {
+ this.assert(jsonObjValue !== null, field.name + " map value", null);
+ // read value
+ let val;
+ switch (field.V.kind) {
+ case "message":
+ val = field.V.T().internalJsonRead(jsonObjValue, options);
+ break;
+ case "enum":
+ val = this.enum(field.V.T(), jsonObjValue, field.name, options.ignoreUnknownFields);
+ if (val === false)
+ continue;
+ break;
+ case "scalar":
+ val = this.scalar(jsonObjValue, field.V.T, field.V.L, field.name);
+ break;
+ }
+ this.assert(val !== undefined, field.name + " map value", jsonObjValue);
+ // read key
+ let key = jsonObjKey;
+ if (field.K == reflection_info_1.ScalarType.BOOL)
+ key = key == "true" ? true : key == "false" ? false : key;
+ key = this.scalar(key, field.K, reflection_info_1.LongType.STRING, field.name).toString();
+ fieldObj[key] = val;
+ }
+ }
+ else if (field.repeat) {
+ if (jsonValue === null)
+ continue;
+ // check input
+ this.assert(Array.isArray(jsonValue), field.name, jsonValue);
+ // our target to put array entries into
+ const fieldArr = target[localName];
+ // read array entries
+ for (const jsonItem of jsonValue) {
+ this.assert(jsonItem !== null, field.name, null);
+ let val;
+ switch (field.kind) {
+ case "message":
+ val = field.T().internalJsonRead(jsonItem, options);
+ break;
+ case "enum":
+ val = this.enum(field.T(), jsonItem, field.name, options.ignoreUnknownFields);
+ if (val === false)
+ continue;
+ break;
+ case "scalar":
+ val = this.scalar(jsonItem, field.T, field.L, field.name);
+ break;
+ }
+ this.assert(val !== undefined, field.name, jsonValue);
+ fieldArr.push(val);
+ }
+ }
+ else {
+ switch (field.kind) {
+ case "message":
+ if (jsonValue === null && field.T().typeName != 'google.protobuf.Value') {
+ this.assert(field.oneof === undefined, field.name + " (oneof member)", null);
+ continue;
+ }
+ target[localName] = field.T().internalJsonRead(jsonValue, options, target[localName]);
+ break;
+ case "enum":
+ if (jsonValue === null)
+ continue;
+ let val = this.enum(field.T(), jsonValue, field.name, options.ignoreUnknownFields);
+ if (val === false)
+ continue;
+ target[localName] = val;
+ break;
+ case "scalar":
+ if (jsonValue === null)
+ continue;
+ target[localName] = this.scalar(jsonValue, field.T, field.L, field.name);
+ break;
+ }
+ }
+ }
}
-
- const allClientsBusy = this[kClients].map(pool => pool[kNeedDrain]).reduce((a, b) => a && b, true)
-
- if (allClientsBusy) {
- return
+ /**
+ * Returns `false` for unrecognized string representations.
+ *
+ * google.protobuf.NullValue accepts only JSON `null` (or the old `"NULL_VALUE"`).
+ */
+ enum(type, json, fieldName, ignoreUnknownFields) {
+ if (type[0] == 'google.protobuf.NullValue')
+ assert_1.assert(json === null || json === "NULL_VALUE", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type[0]} only accepts null.`);
+ if (json === null)
+ // we require 0 to be default value for all enums
+ return 0;
+ switch (typeof json) {
+ case "number":
+ assert_1.assert(Number.isInteger(json), `Unable to parse field ${this.info.typeName}#${fieldName}, enum can only be integral number, got ${json}.`);
+ return json;
+ case "string":
+ let localEnumName = json;
+ if (type[2] && json.substring(0, type[2].length) === type[2])
+ // lookup without the shared prefix
+ localEnumName = json.substring(type[2].length);
+ let enumNumber = type[1][localEnumName];
+ if (typeof enumNumber === 'undefined' && ignoreUnknownFields) {
+ return false;
+ }
+ assert_1.assert(typeof enumNumber == "number", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type[0]} has no value for "${json}".`);
+ return enumNumber;
+ }
+ assert_1.assert(false, `Unable to parse field ${this.info.typeName}#${fieldName}, cannot parse enum value from ${typeof json}".`);
}
-
- let counter = 0
-
- let maxWeightIndex = this[kClients].findIndex(pool => !pool[kNeedDrain])
-
- while (counter++ < this[kClients].length) {
- this[kIndex] = (this[kIndex] + 1) % this[kClients].length
- const pool = this[kClients][this[kIndex]]
-
- // find pool index with the largest weight
- if (pool[kWeight] > this[kClients][maxWeightIndex][kWeight] && !pool[kNeedDrain]) {
- maxWeightIndex = this[kIndex]
- }
-
- // decrease the current weight every `this[kClients].length`.
- if (this[kIndex] === 0) {
- // Set the current weight to the next lower weight.
- this[kCurrentWeight] = this[kCurrentWeight] - this[kGreatestCommonDivisor]
-
- if (this[kCurrentWeight] <= 0) {
- this[kCurrentWeight] = this[kMaxWeightPerServer]
+ scalar(json, type, longType, fieldName) {
+ let e;
+ try {
+ switch (type) {
+ // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity".
+ // Either numbers or strings are accepted. Exponent notation is also accepted.
+ case reflection_info_1.ScalarType.DOUBLE:
+ case reflection_info_1.ScalarType.FLOAT:
+ if (json === null)
+ return .0;
+ if (json === "NaN")
+ return Number.NaN;
+ if (json === "Infinity")
+ return Number.POSITIVE_INFINITY;
+ if (json === "-Infinity")
+ return Number.NEGATIVE_INFINITY;
+ if (json === "") {
+ e = "empty string";
+ break;
+ }
+ if (typeof json == "string" && json.trim().length !== json.length) {
+ e = "extra whitespace";
+ break;
+ }
+ if (typeof json != "string" && typeof json != "number") {
+ break;
+ }
+ let float = Number(json);
+ if (Number.isNaN(float)) {
+ e = "not a number";
+ break;
+ }
+ if (!Number.isFinite(float)) {
+ // infinity and -infinity are handled by string representation above, so this is an error
+ e = "too large or small";
+ break;
+ }
+ if (type == reflection_info_1.ScalarType.FLOAT)
+ assert_1.assertFloat32(float);
+ return float;
+ // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted.
+ case reflection_info_1.ScalarType.INT32:
+ case reflection_info_1.ScalarType.FIXED32:
+ case reflection_info_1.ScalarType.SFIXED32:
+ case reflection_info_1.ScalarType.SINT32:
+ case reflection_info_1.ScalarType.UINT32:
+ if (json === null)
+ return 0;
+ let int32;
+ if (typeof json == "number")
+ int32 = json;
+ else if (json === "")
+ e = "empty string";
+ else if (typeof json == "string") {
+ if (json.trim().length !== json.length)
+ e = "extra whitespace";
+ else
+ int32 = Number(json);
+ }
+ if (int32 === undefined)
+ break;
+ if (type == reflection_info_1.ScalarType.UINT32)
+ assert_1.assertUInt32(int32);
+ else
+ assert_1.assertInt32(int32);
+ return int32;
+ // int64, fixed64, uint64: JSON value will be a decimal string. Either numbers or strings are accepted.
+ case reflection_info_1.ScalarType.INT64:
+ case reflection_info_1.ScalarType.SFIXED64:
+ case reflection_info_1.ScalarType.SINT64:
+ if (json === null)
+ return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType);
+ if (typeof json != "number" && typeof json != "string")
+ break;
+ return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.from(json), longType);
+ case reflection_info_1.ScalarType.FIXED64:
+ case reflection_info_1.ScalarType.UINT64:
+ if (json === null)
+ return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType);
+ if (typeof json != "number" && typeof json != "string")
+ break;
+ return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.from(json), longType);
+ // bool:
+ case reflection_info_1.ScalarType.BOOL:
+ if (json === null)
+ return false;
+ if (typeof json !== "boolean")
+ break;
+ return json;
+ // string:
+ case reflection_info_1.ScalarType.STRING:
+ if (json === null)
+ return "";
+ if (typeof json !== "string") {
+ e = "extra whitespace";
+ break;
+ }
+ try {
+ encodeURIComponent(json);
+ }
+ catch (e) {
+ e = "invalid UTF8";
+ break;
+ }
+ return json;
+ // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings.
+ // Either standard or URL-safe base64 encoding with/without paddings are accepted.
+ case reflection_info_1.ScalarType.BYTES:
+ if (json === null || json === "")
+ return new Uint8Array(0);
+ if (typeof json !== 'string')
+ break;
+ return base64_1.base64decode(json);
+ }
}
- }
- if (pool[kWeight] >= this[kCurrentWeight] && (!pool[kNeedDrain])) {
- return pool
- }
+ catch (error) {
+ e = error.message;
+ }
+ this.assert(false, fieldName + (e ? " - " + e : ""), json);
}
-
- this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight]
- this[kIndex] = maxWeightIndex
- return this[kClients][maxWeightIndex]
- }
}
-
-module.exports = BalancedPool
+exports.ReflectionJsonReader = ReflectionJsonReader;
/***/ }),
-/***/ 5580:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-/* global WebAssembly */
-
-const assert = __nccwpck_require__(4589)
-const util = __nccwpck_require__(7375)
-const { channels } = __nccwpck_require__(4567)
-const timers = __nccwpck_require__(7256)
-const {
- RequestContentLengthMismatchError,
- ResponseContentLengthMismatchError,
- RequestAbortedError,
- HeadersTimeoutError,
- HeadersOverflowError,
- SocketError,
- InformationalError,
- BodyTimeoutError,
- HTTPParserError,
- ResponseExceededMaxSizeError
-} = __nccwpck_require__(2344)
-const {
- kUrl,
- kReset,
- kClient,
- kParser,
- kBlocking,
- kRunning,
- kPending,
- kSize,
- kWriting,
- kQueue,
- kNoRef,
- kKeepAliveDefaultTimeout,
- kHostHeader,
- kPendingIdx,
- kRunningIdx,
- kError,
- kPipelining,
- kSocket,
- kKeepAliveTimeoutValue,
- kMaxHeadersSize,
- kKeepAliveMaxTimeout,
- kKeepAliveTimeoutThreshold,
- kHeadersTimeout,
- kBodyTimeout,
- kStrictContentLength,
- kMaxRequests,
- kCounter,
- kMaxResponseSize,
- kOnError,
- kResume,
- kHTTPContext
-} = __nccwpck_require__(6130)
-
-const constants = __nccwpck_require__(2529)
-const EMPTY_BUF = Buffer.alloc(0)
-const FastBuffer = Buffer[Symbol.species]
-const addListener = util.addListener
-const removeAllListeners = util.removeAllListeners
-
-let extractBody
-
-async function lazyllhttp () {
- const llhttpWasmData = process.env.JEST_WORKER_ID ? __nccwpck_require__(7635) : undefined
-
- let mod
- try {
- mod = await WebAssembly.compile(__nccwpck_require__(5593))
- } catch (e) {
- /* istanbul ignore next */
-
- // We could check if the error was caused by the simd option not
- // being enabled, but the occurring of this other error
- // * https://github.com/emscripten-core/emscripten/issues/11495
- // got me to remove that check to avoid breaking Node 12.
- mod = await WebAssembly.compile(llhttpWasmData || __nccwpck_require__(7635))
- }
+/***/ 1094:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- return await WebAssembly.instantiate(mod, {
- env: {
- /* eslint-disable camelcase */
- wasm_on_url: (p, at, len) => {
- /* istanbul ignore next */
- return 0
- },
- wasm_on_status: (p, at, len) => {
- assert(currentParser.ptr === p)
- const start = at - currentBufferPtr + currentBufferRef.byteOffset
- return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
- },
- wasm_on_message_begin: (p) => {
- assert(currentParser.ptr === p)
- return currentParser.onMessageBegin() || 0
- },
- wasm_on_header_field: (p, at, len) => {
- assert(currentParser.ptr === p)
- const start = at - currentBufferPtr + currentBufferRef.byteOffset
- return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
- },
- wasm_on_header_value: (p, at, len) => {
- assert(currentParser.ptr === p)
- const start = at - currentBufferPtr + currentBufferRef.byteOffset
- return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
- },
- wasm_on_headers_complete: (p, statusCode, upgrade, shouldKeepAlive) => {
- assert(currentParser.ptr === p)
- return currentParser.onHeadersComplete(statusCode, Boolean(upgrade), Boolean(shouldKeepAlive)) || 0
- },
- wasm_on_body: (p, at, len) => {
- assert(currentParser.ptr === p)
- const start = at - currentBufferPtr + currentBufferRef.byteOffset
- return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
- },
- wasm_on_message_complete: (p) => {
- assert(currentParser.ptr === p)
- return currentParser.onMessageComplete() || 0
- }
-
- /* eslint-enable camelcase */
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.ReflectionJsonWriter = void 0;
+const base64_1 = __nccwpck_require__(6335);
+const pb_long_1 = __nccwpck_require__(1753);
+const reflection_info_1 = __nccwpck_require__(7910);
+const assert_1 = __nccwpck_require__(8602);
+/**
+ * Writes proto3 messages in canonical JSON format using reflection
+ * information.
+ *
+ * https://developers.google.com/protocol-buffers/docs/proto3#json
+ */
+class ReflectionJsonWriter {
+ constructor(info) {
+ var _a;
+ this.fields = (_a = info.fields) !== null && _a !== void 0 ? _a : [];
+ }
+ /**
+ * Converts the message to a JSON object, based on the field descriptors.
+ */
+ write(message, options) {
+ const json = {}, source = message;
+ for (const field of this.fields) {
+ // field is not part of a oneof, simply write as is
+ if (!field.oneof) {
+ let jsonValue = this.field(field, source[field.localName], options);
+ if (jsonValue !== undefined)
+ json[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue;
+ continue;
+ }
+ // field is part of a oneof
+ const group = source[field.oneof];
+ if (group.oneofKind !== field.localName)
+ continue; // not selected, skip
+ const opt = field.kind == 'scalar' || field.kind == 'enum'
+ ? Object.assign(Object.assign({}, options), { emitDefaultValues: true }) : options;
+ let jsonValue = this.field(field, group[field.localName], opt);
+ assert_1.assert(jsonValue !== undefined);
+ json[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue;
+ }
+ return json;
+ }
+ field(field, value, options) {
+ let jsonValue = undefined;
+ if (field.kind == 'map') {
+ assert_1.assert(typeof value == "object" && value !== null);
+ const jsonObj = {};
+ switch (field.V.kind) {
+ case "scalar":
+ for (const [entryKey, entryValue] of Object.entries(value)) {
+ const val = this.scalar(field.V.T, entryValue, field.name, false, true);
+ assert_1.assert(val !== undefined);
+ jsonObj[entryKey.toString()] = val; // JSON standard allows only (double quoted) string as property key
+ }
+ break;
+ case "message":
+ const messageType = field.V.T();
+ for (const [entryKey, entryValue] of Object.entries(value)) {
+ const val = this.message(messageType, entryValue, field.name, options);
+ assert_1.assert(val !== undefined);
+ jsonObj[entryKey.toString()] = val; // JSON standard allows only (double quoted) string as property key
+ }
+ break;
+ case "enum":
+ const enumInfo = field.V.T();
+ for (const [entryKey, entryValue] of Object.entries(value)) {
+ assert_1.assert(entryValue === undefined || typeof entryValue == 'number');
+ const val = this.enum(enumInfo, entryValue, field.name, false, true, options.enumAsInteger);
+ assert_1.assert(val !== undefined);
+ jsonObj[entryKey.toString()] = val; // JSON standard allows only (double quoted) string as property key
+ }
+ break;
+ }
+ if (options.emitDefaultValues || Object.keys(jsonObj).length > 0)
+ jsonValue = jsonObj;
+ }
+ else if (field.repeat) {
+ assert_1.assert(Array.isArray(value));
+ const jsonArr = [];
+ switch (field.kind) {
+ case "scalar":
+ for (let i = 0; i < value.length; i++) {
+ const val = this.scalar(field.T, value[i], field.name, field.opt, true);
+ assert_1.assert(val !== undefined);
+ jsonArr.push(val);
+ }
+ break;
+ case "enum":
+ const enumInfo = field.T();
+ for (let i = 0; i < value.length; i++) {
+ assert_1.assert(value[i] === undefined || typeof value[i] == 'number');
+ const val = this.enum(enumInfo, value[i], field.name, field.opt, true, options.enumAsInteger);
+ assert_1.assert(val !== undefined);
+ jsonArr.push(val);
+ }
+ break;
+ case "message":
+ const messageType = field.T();
+ for (let i = 0; i < value.length; i++) {
+ const val = this.message(messageType, value[i], field.name, options);
+ assert_1.assert(val !== undefined);
+ jsonArr.push(val);
+ }
+ break;
+ }
+ // add converted array to json output
+ if (options.emitDefaultValues || jsonArr.length > 0 || options.emitDefaultValues)
+ jsonValue = jsonArr;
+ }
+ else {
+ switch (field.kind) {
+ case "scalar":
+ jsonValue = this.scalar(field.T, value, field.name, field.opt, options.emitDefaultValues);
+ break;
+ case "enum":
+ jsonValue = this.enum(field.T(), value, field.name, field.opt, options.emitDefaultValues, options.enumAsInteger);
+ break;
+ case "message":
+ jsonValue = this.message(field.T(), value, field.name, options);
+ break;
+ }
+ }
+ return jsonValue;
+ }
+ /**
+ * Returns `null` as the default for google.protobuf.NullValue.
+ */
+ enum(type, value, fieldName, optional, emitDefaultValues, enumAsInteger) {
+ if (type[0] == 'google.protobuf.NullValue')
+ return !emitDefaultValues && !optional ? undefined : null;
+ if (value === undefined) {
+ assert_1.assert(optional);
+ return undefined;
+ }
+ if (value === 0 && !emitDefaultValues && !optional)
+ // we require 0 to be default value for all enums
+ return undefined;
+ assert_1.assert(typeof value == 'number');
+ assert_1.assert(Number.isInteger(value));
+ if (enumAsInteger || !type[1].hasOwnProperty(value))
+ // if we don't now the enum value, just return the number
+ return value;
+ if (type[2])
+ // restore the dropped prefix
+ return type[2] + type[1][value];
+ return type[1][value];
+ }
+ message(type, value, fieldName, options) {
+ if (value === undefined)
+ return options.emitDefaultValues ? null : undefined;
+ return type.internalJsonWrite(value, options);
+ }
+ scalar(type, value, fieldName, optional, emitDefaultValues) {
+ if (value === undefined) {
+ assert_1.assert(optional);
+ return undefined;
+ }
+ const ed = emitDefaultValues || optional;
+ // noinspection FallThroughInSwitchStatementJS
+ switch (type) {
+ // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted.
+ case reflection_info_1.ScalarType.INT32:
+ case reflection_info_1.ScalarType.SFIXED32:
+ case reflection_info_1.ScalarType.SINT32:
+ if (value === 0)
+ return ed ? 0 : undefined;
+ assert_1.assertInt32(value);
+ return value;
+ case reflection_info_1.ScalarType.FIXED32:
+ case reflection_info_1.ScalarType.UINT32:
+ if (value === 0)
+ return ed ? 0 : undefined;
+ assert_1.assertUInt32(value);
+ return value;
+ // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity".
+ // Either numbers or strings are accepted. Exponent notation is also accepted.
+ case reflection_info_1.ScalarType.FLOAT:
+ assert_1.assertFloat32(value);
+ case reflection_info_1.ScalarType.DOUBLE:
+ if (value === 0)
+ return ed ? 0 : undefined;
+ assert_1.assert(typeof value == 'number');
+ if (Number.isNaN(value))
+ return 'NaN';
+ if (value === Number.POSITIVE_INFINITY)
+ return 'Infinity';
+ if (value === Number.NEGATIVE_INFINITY)
+ return '-Infinity';
+ return value;
+ // string:
+ case reflection_info_1.ScalarType.STRING:
+ if (value === "")
+ return ed ? '' : undefined;
+ assert_1.assert(typeof value == 'string');
+ return value;
+ // bool:
+ case reflection_info_1.ScalarType.BOOL:
+ if (value === false)
+ return ed ? false : undefined;
+ assert_1.assert(typeof value == 'boolean');
+ return value;
+ // JSON value will be a decimal string. Either numbers or strings are accepted.
+ case reflection_info_1.ScalarType.UINT64:
+ case reflection_info_1.ScalarType.FIXED64:
+ assert_1.assert(typeof value == 'number' || typeof value == 'string' || typeof value == 'bigint');
+ let ulong = pb_long_1.PbULong.from(value);
+ if (ulong.isZero() && !ed)
+ return undefined;
+ return ulong.toString();
+ // JSON value will be a decimal string. Either numbers or strings are accepted.
+ case reflection_info_1.ScalarType.INT64:
+ case reflection_info_1.ScalarType.SFIXED64:
+ case reflection_info_1.ScalarType.SINT64:
+ assert_1.assert(typeof value == 'number' || typeof value == 'string' || typeof value == 'bigint');
+ let long = pb_long_1.PbLong.from(value);
+ if (long.isZero() && !ed)
+ return undefined;
+ return long.toString();
+ // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings.
+ // Either standard or URL-safe base64 encoding with/without paddings are accepted.
+ case reflection_info_1.ScalarType.BYTES:
+ assert_1.assert(value instanceof Uint8Array);
+ if (!value.byteLength)
+ return ed ? "" : undefined;
+ return base64_1.base64encode(value);
+ }
}
- })
}
+exports.ReflectionJsonWriter = ReflectionJsonWriter;
-let llhttpInstance = null
-let llhttpPromise = lazyllhttp()
-llhttpPromise.catch()
-
-let currentParser = null
-let currentBufferRef = null
-let currentBufferSize = 0
-let currentBufferPtr = null
-const USE_NATIVE_TIMER = 0
-const USE_FAST_TIMER = 1
+/***/ }),
-// Use fast timers for headers and body to take eventual event loop
-// latency into account.
-const TIMEOUT_HEADERS = 2 | USE_FAST_TIMER
-const TIMEOUT_BODY = 4 | USE_FAST_TIMER
+/***/ 3402:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-// Use native timers to ignore event loop latency for keep-alive
-// handling.
-const TIMEOUT_KEEP_ALIVE = 8 | USE_NATIVE_TIMER
-class Parser {
- constructor (client, socket, { exports }) {
- assert(Number.isFinite(client[kMaxHeadersSize]) && client[kMaxHeadersSize] > 0)
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.reflectionLongConvert = void 0;
+const reflection_info_1 = __nccwpck_require__(7910);
+/**
+ * Utility method to convert a PbLong or PbUlong to a JavaScript
+ * representation during runtime.
+ *
+ * Works with generated field information, `undefined` is equivalent
+ * to `STRING`.
+ */
+function reflectionLongConvert(long, type) {
+ switch (type) {
+ case reflection_info_1.LongType.BIGINT:
+ return long.toBigInt();
+ case reflection_info_1.LongType.NUMBER:
+ return long.toNumber();
+ default:
+ // case undefined:
+ // case LongType.STRING:
+ return long.toString();
+ }
+}
+exports.reflectionLongConvert = reflectionLongConvert;
- this.llhttp = exports
- this.ptr = this.llhttp.llhttp_alloc(constants.TYPE.RESPONSE)
- this.client = client
- this.socket = socket
- this.timeout = null
- this.timeoutValue = null
- this.timeoutType = null
- this.statusCode = null
- this.statusText = ''
- this.upgrade = false
- this.headers = []
- this.headersSize = 0
- this.headersMaxSize = client[kMaxHeadersSize]
- this.shouldKeepAlive = false
- this.paused = false
- this.resume = this.resume.bind(this)
- this.bytesRead = 0
+/***/ }),
- this.keepAlive = ''
- this.contentLength = ''
- this.connection = ''
- this.maxResponseSize = client[kMaxResponseSize]
- }
+/***/ 8044:
+/***/ ((__unused_webpack_module, exports) => {
- setTimeout (delay, type) {
- // If the existing timer and the new timer are of different timer type
- // (fast or native) or have different delay, we need to clear the existing
- // timer and set a new one.
- if (
- delay !== this.timeoutValue ||
- (type & USE_FAST_TIMER) ^ (this.timeoutType & USE_FAST_TIMER)
- ) {
- // If a timeout is already set, clear it with clearTimeout of the fast
- // timer implementation, as it can clear fast and native timers.
- if (this.timeout) {
- timers.clearTimeout(this.timeout)
- this.timeout = null
- }
- if (delay) {
- if (type & USE_FAST_TIMER) {
- this.timeout = timers.setFastTimeout(onParserTimeout, delay, new WeakRef(this))
- } else {
- this.timeout = setTimeout(onParserTimeout, delay, new WeakRef(this))
- this.timeout.unref()
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.reflectionMergePartial = void 0;
+/**
+ * Copy partial data into the target message.
+ *
+ * If a singular scalar or enum field is present in the source, it
+ * replaces the field in the target.
+ *
+ * If a singular message field is present in the source, it is merged
+ * with the target field by calling mergePartial() of the responsible
+ * message type.
+ *
+ * If a repeated field is present in the source, its values replace
+ * all values in the target array, removing extraneous values.
+ * Repeated message fields are copied, not merged.
+ *
+ * If a map field is present in the source, entries are added to the
+ * target map, replacing entries with the same key. Entries that only
+ * exist in the target remain. Entries with message values are copied,
+ * not merged.
+ *
+ * Note that this function differs from protobuf merge semantics,
+ * which appends repeated fields.
+ */
+function reflectionMergePartial(info, target, source) {
+ let fieldValue, // the field value we are working with
+ input = source, output; // where we want our field value to go
+ for (let field of info.fields) {
+ let name = field.localName;
+ if (field.oneof) {
+ const group = input[field.oneof]; // this is the oneof`s group in the source
+ if ((group === null || group === void 0 ? void 0 : group.oneofKind) == undefined) { // the user is free to omit
+ continue; // we skip this field, and all other members too
+ }
+ fieldValue = group[name]; // our value comes from the the oneof group of the source
+ output = target[field.oneof]; // and our output is the oneof group of the target
+ output.oneofKind = group.oneofKind; // always update discriminator
+ if (fieldValue == undefined) {
+ delete output[name]; // remove any existing value
+ continue; // skip further work on field
+ }
+ }
+ else {
+ fieldValue = input[name]; // we are using the source directly
+ output = target; // we want our field value to go directly into the target
+ if (fieldValue == undefined) {
+ continue; // skip further work on field, existing value is used as is
+ }
+ }
+ if (field.repeat)
+ output[name].length = fieldValue.length; // resize target array to match source array
+ // now we just work with `fieldValue` and `output` to merge the value
+ switch (field.kind) {
+ case "scalar":
+ case "enum":
+ if (field.repeat)
+ for (let i = 0; i < fieldValue.length; i++)
+ output[name][i] = fieldValue[i]; // not a reference type
+ else
+ output[name] = fieldValue; // not a reference type
+ break;
+ case "message":
+ let T = field.T();
+ if (field.repeat)
+ for (let i = 0; i < fieldValue.length; i++)
+ output[name][i] = T.create(fieldValue[i]);
+ else if (output[name] === undefined)
+ output[name] = T.create(fieldValue); // nothing to merge with
+ else
+ T.mergePartial(output[name], fieldValue);
+ break;
+ case "map":
+ // Map and repeated fields are simply overwritten, not appended or merged
+ switch (field.V.kind) {
+ case "scalar":
+ case "enum":
+ Object.assign(output[name], fieldValue); // elements are not reference types
+ break;
+ case "message":
+ let T = field.V.T();
+ for (let k of Object.keys(fieldValue))
+ output[name][k] = T.create(fieldValue[k]);
+ break;
+ }
+ break;
}
- }
-
- this.timeoutValue = delay
- } else if (this.timeout) {
- // istanbul ignore else: only for jest
- if (this.timeout.refresh) {
- this.timeout.refresh()
- }
}
+}
+exports.reflectionMergePartial = reflectionMergePartial;
- this.timeoutType = type
- }
- resume () {
- if (this.socket.destroyed || !this.paused) {
- return
- }
+/***/ }),
- assert(this.ptr != null)
- assert(currentParser == null)
+/***/ 9526:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- this.llhttp.llhttp_resume(this.ptr)
- assert(this.timeoutType === TIMEOUT_BODY)
- if (this.timeout) {
- // istanbul ignore else: only for jest
- if (this.timeout.refresh) {
- this.timeout.refresh()
- }
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.reflectionScalarDefault = void 0;
+const reflection_info_1 = __nccwpck_require__(7910);
+const reflection_long_convert_1 = __nccwpck_require__(3402);
+const pb_long_1 = __nccwpck_require__(1753);
+/**
+ * Creates the default value for a scalar type.
+ */
+function reflectionScalarDefault(type, longType = reflection_info_1.LongType.STRING) {
+ switch (type) {
+ case reflection_info_1.ScalarType.BOOL:
+ return false;
+ case reflection_info_1.ScalarType.UINT64:
+ case reflection_info_1.ScalarType.FIXED64:
+ return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType);
+ case reflection_info_1.ScalarType.INT64:
+ case reflection_info_1.ScalarType.SFIXED64:
+ case reflection_info_1.ScalarType.SINT64:
+ return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType);
+ case reflection_info_1.ScalarType.DOUBLE:
+ case reflection_info_1.ScalarType.FLOAT:
+ return 0.0;
+ case reflection_info_1.ScalarType.BYTES:
+ return new Uint8Array(0);
+ case reflection_info_1.ScalarType.STRING:
+ return "";
+ default:
+ // case ScalarType.INT32:
+ // case ScalarType.UINT32:
+ // case ScalarType.SINT32:
+ // case ScalarType.FIXED32:
+ // case ScalarType.SFIXED32:
+ return 0;
}
+}
+exports.reflectionScalarDefault = reflectionScalarDefault;
- this.paused = false
- this.execute(this.socket.read() || EMPTY_BUF) // Flush parser.
- this.readMore()
- }
- readMore () {
- while (!this.paused && this.ptr) {
- const chunk = this.socket.read()
- if (chunk === null) {
- break
- }
- this.execute(chunk)
- }
- }
+/***/ }),
- execute (data) {
- assert(this.ptr != null)
- assert(currentParser == null)
- assert(!this.paused)
+/***/ 5167:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- const { socket, llhttp } = this
- if (data.length > currentBufferSize) {
- if (currentBufferPtr) {
- llhttp.free(currentBufferPtr)
- }
- currentBufferSize = Math.ceil(data.length / 4096) * 4096
- currentBufferPtr = llhttp.malloc(currentBufferSize)
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.ReflectionTypeCheck = void 0;
+const reflection_info_1 = __nccwpck_require__(7910);
+const oneof_1 = __nccwpck_require__(8063);
+// noinspection JSMethodCanBeStatic
+class ReflectionTypeCheck {
+ constructor(info) {
+ var _a;
+ this.fields = (_a = info.fields) !== null && _a !== void 0 ? _a : [];
}
-
- new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(data)
-
- // Call `execute` on the wasm parser.
- // We pass the `llhttp_parser` pointer address, the pointer address of buffer view data,
- // and finally the length of bytes to parse.
- // The return value is an error code or `constants.ERROR.OK`.
- try {
- let ret
-
- try {
- currentBufferRef = data
- currentParser = this
- ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, data.length)
- /* eslint-disable-next-line no-useless-catch */
- } catch (err) {
- /* istanbul ignore next: difficult to make a test case for */
- throw err
- } finally {
- currentParser = null
- currentBufferRef = null
- }
-
- const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr
-
- if (ret === constants.ERROR.PAUSED_UPGRADE) {
- this.onUpgrade(data.slice(offset))
- } else if (ret === constants.ERROR.PAUSED) {
- this.paused = true
- socket.unshift(data.slice(offset))
- } else if (ret !== constants.ERROR.OK) {
- const ptr = llhttp.llhttp_get_error_reason(this.ptr)
- let message = ''
- /* istanbul ignore else: difficult to make a test case for */
- if (ptr) {
- const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0)
- message =
- 'Response does not match the HTTP/1.1 protocol (' +
- Buffer.from(llhttp.memory.buffer, ptr, len).toString() +
- ')'
+ prepare() {
+ if (this.data)
+ return;
+ const req = [], known = [], oneofs = [];
+ for (let field of this.fields) {
+ if (field.oneof) {
+ if (!oneofs.includes(field.oneof)) {
+ oneofs.push(field.oneof);
+ req.push(field.oneof);
+ known.push(field.oneof);
+ }
+ }
+ else {
+ known.push(field.localName);
+ switch (field.kind) {
+ case "scalar":
+ case "enum":
+ if (!field.opt || field.repeat)
+ req.push(field.localName);
+ break;
+ case "message":
+ if (field.repeat)
+ req.push(field.localName);
+ break;
+ case "map":
+ req.push(field.localName);
+ break;
+ }
+ }
}
- throw new HTTPParserError(message, constants.ERROR[ret], data.slice(offset))
- }
- } catch (err) {
- util.destroy(socket, err)
+ this.data = { req, known, oneofs: Object.values(oneofs) };
}
- }
-
- destroy () {
- assert(this.ptr != null)
- assert(currentParser == null)
-
- this.llhttp.llhttp_free(this.ptr)
- this.ptr = null
-
- this.timeout && timers.clearTimeout(this.timeout)
- this.timeout = null
- this.timeoutValue = null
- this.timeoutType = null
-
- this.paused = false
- }
-
- onStatus (buf) {
- this.statusText = buf.toString()
- }
-
- onMessageBegin () {
- const { socket, client } = this
-
- /* istanbul ignore next: difficult to make a test case for */
- if (socket.destroyed) {
- return -1
+ /**
+ * Is the argument a valid message as specified by the
+ * reflection information?
+ *
+ * Checks all field types recursively. The `depth`
+ * specifies how deep into the structure the check will be.
+ *
+ * With a depth of 0, only the presence of fields
+ * is checked.
+ *
+ * With a depth of 1 or more, the field types are checked.
+ *
+ * With a depth of 2 or more, the members of map, repeated
+ * and message fields are checked.
+ *
+ * Message fields will be checked recursively with depth - 1.
+ *
+ * The number of map entries / repeated values being checked
+ * is < depth.
+ */
+ is(message, depth, allowExcessProperties = false) {
+ if (depth < 0)
+ return true;
+ if (message === null || message === undefined || typeof message != 'object')
+ return false;
+ this.prepare();
+ let keys = Object.keys(message), data = this.data;
+ // if a required field is missing in arg, this cannot be a T
+ if (keys.length < data.req.length || data.req.some(n => !keys.includes(n)))
+ return false;
+ if (!allowExcessProperties) {
+ // if the arg contains a key we dont know, this is not a literal T
+ if (keys.some(k => !data.known.includes(k)))
+ return false;
+ }
+ // "With a depth of 0, only the presence and absence of fields is checked."
+ // "With a depth of 1 or more, the field types are checked."
+ if (depth < 1) {
+ return true;
+ }
+ // check oneof group
+ for (const name of data.oneofs) {
+ const group = message[name];
+ if (!oneof_1.isOneofGroup(group))
+ return false;
+ if (group.oneofKind === undefined)
+ continue;
+ const field = this.fields.find(f => f.localName === group.oneofKind);
+ if (!field)
+ return false; // we found no field, but have a kind, something is wrong
+ if (!this.field(group[group.oneofKind], field, allowExcessProperties, depth))
+ return false;
+ }
+ // check types
+ for (const field of this.fields) {
+ if (field.oneof !== undefined)
+ continue;
+ if (!this.field(message[field.localName], field, allowExcessProperties, depth))
+ return false;
+ }
+ return true;
}
-
- const request = client[kQueue][client[kRunningIdx]]
- if (!request) {
- return -1
+ field(arg, field, allowExcessProperties, depth) {
+ let repeated = field.repeat;
+ switch (field.kind) {
+ case "scalar":
+ if (arg === undefined)
+ return field.opt;
+ if (repeated)
+ return this.scalars(arg, field.T, depth, field.L);
+ return this.scalar(arg, field.T, field.L);
+ case "enum":
+ if (arg === undefined)
+ return field.opt;
+ if (repeated)
+ return this.scalars(arg, reflection_info_1.ScalarType.INT32, depth);
+ return this.scalar(arg, reflection_info_1.ScalarType.INT32);
+ case "message":
+ if (arg === undefined)
+ return true;
+ if (repeated)
+ return this.messages(arg, field.T(), allowExcessProperties, depth);
+ return this.message(arg, field.T(), allowExcessProperties, depth);
+ case "map":
+ if (typeof arg != 'object' || arg === null)
+ return false;
+ if (depth < 2)
+ return true;
+ if (!this.mapKeys(arg, field.K, depth))
+ return false;
+ switch (field.V.kind) {
+ case "scalar":
+ return this.scalars(Object.values(arg), field.V.T, depth, field.V.L);
+ case "enum":
+ return this.scalars(Object.values(arg), reflection_info_1.ScalarType.INT32, depth);
+ case "message":
+ return this.messages(Object.values(arg), field.V.T(), allowExcessProperties, depth);
+ }
+ break;
+ }
+ return true;
}
- request.onResponseStarted()
- }
-
- onHeaderField (buf) {
- const len = this.headers.length
-
- if ((len & 1) === 0) {
- this.headers.push(buf)
- } else {
- this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf])
+ message(arg, type, allowExcessProperties, depth) {
+ if (allowExcessProperties) {
+ return type.isAssignable(arg, depth);
+ }
+ return type.is(arg, depth);
}
-
- this.trackHeader(buf.length)
- }
-
- onHeaderValue (buf) {
- let len = this.headers.length
-
- if ((len & 1) === 1) {
- this.headers.push(buf)
- len += 1
- } else {
- this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf])
+ messages(arg, type, allowExcessProperties, depth) {
+ if (!Array.isArray(arg))
+ return false;
+ if (depth < 2)
+ return true;
+ if (allowExcessProperties) {
+ for (let i = 0; i < arg.length && i < depth; i++)
+ if (!type.isAssignable(arg[i], depth - 1))
+ return false;
+ }
+ else {
+ for (let i = 0; i < arg.length && i < depth; i++)
+ if (!type.is(arg[i], depth - 1))
+ return false;
+ }
+ return true;
}
-
- const key = this.headers[len - 2]
- if (key.length === 10) {
- const headerName = util.bufferToLowerCasedHeaderName(key)
- if (headerName === 'keep-alive') {
- this.keepAlive += buf.toString()
- } else if (headerName === 'connection') {
- this.connection += buf.toString()
- }
- } else if (key.length === 14 && util.bufferToLowerCasedHeaderName(key) === 'content-length') {
- this.contentLength += buf.toString()
+ scalar(arg, type, longType) {
+ let argType = typeof arg;
+ switch (type) {
+ case reflection_info_1.ScalarType.UINT64:
+ case reflection_info_1.ScalarType.FIXED64:
+ case reflection_info_1.ScalarType.INT64:
+ case reflection_info_1.ScalarType.SFIXED64:
+ case reflection_info_1.ScalarType.SINT64:
+ switch (longType) {
+ case reflection_info_1.LongType.BIGINT:
+ return argType == "bigint";
+ case reflection_info_1.LongType.NUMBER:
+ return argType == "number" && !isNaN(arg);
+ default:
+ return argType == "string";
+ }
+ case reflection_info_1.ScalarType.BOOL:
+ return argType == 'boolean';
+ case reflection_info_1.ScalarType.STRING:
+ return argType == 'string';
+ case reflection_info_1.ScalarType.BYTES:
+ return arg instanceof Uint8Array;
+ case reflection_info_1.ScalarType.DOUBLE:
+ case reflection_info_1.ScalarType.FLOAT:
+ return argType == 'number' && !isNaN(arg);
+ default:
+ // case ScalarType.UINT32:
+ // case ScalarType.FIXED32:
+ // case ScalarType.INT32:
+ // case ScalarType.SINT32:
+ // case ScalarType.SFIXED32:
+ return argType == 'number' && Number.isInteger(arg);
+ }
}
-
- this.trackHeader(buf.length)
- }
-
- trackHeader (len) {
- this.headersSize += len
- if (this.headersSize >= this.headersMaxSize) {
- util.destroy(this.socket, new HeadersOverflowError())
+ scalars(arg, type, depth, longType) {
+ if (!Array.isArray(arg))
+ return false;
+ if (depth < 2)
+ return true;
+ if (Array.isArray(arg))
+ for (let i = 0; i < arg.length && i < depth; i++)
+ if (!this.scalar(arg[i], type, longType))
+ return false;
+ return true;
}
- }
-
- onUpgrade (head) {
- const { upgrade, client, socket, headers, statusCode } = this
-
- assert(upgrade)
- assert(client[kSocket] === socket)
- assert(!socket.destroyed)
- assert(!this.paused)
- assert((headers.length & 1) === 0)
-
- const request = client[kQueue][client[kRunningIdx]]
- assert(request)
- assert(request.upgrade || request.method === 'CONNECT')
-
- this.statusCode = null
- this.statusText = ''
- this.shouldKeepAlive = null
-
- this.headers = []
- this.headersSize = 0
-
- socket.unshift(head)
-
- socket[kParser].destroy()
- socket[kParser] = null
-
- socket[kClient] = null
- socket[kError] = null
-
- removeAllListeners(socket)
-
- client[kSocket] = null
- client[kHTTPContext] = null // TODO (fix): This is hacky...
- client[kQueue][client[kRunningIdx]++] = null
- client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade'))
-
- try {
- request.onUpgrade(statusCode, headers, socket)
- } catch (err) {
- util.destroy(socket, err)
+ mapKeys(map, type, depth) {
+ let keys = Object.keys(map);
+ switch (type) {
+ case reflection_info_1.ScalarType.INT32:
+ case reflection_info_1.ScalarType.FIXED32:
+ case reflection_info_1.ScalarType.SFIXED32:
+ case reflection_info_1.ScalarType.SINT32:
+ case reflection_info_1.ScalarType.UINT32:
+ return this.scalars(keys.slice(0, depth).map(k => parseInt(k)), type, depth);
+ case reflection_info_1.ScalarType.BOOL:
+ return this.scalars(keys.slice(0, depth).map(k => k == 'true' ? true : k == 'false' ? false : k), type, depth);
+ default:
+ return this.scalars(keys, type, depth, reflection_info_1.LongType.STRING);
+ }
}
+}
+exports.ReflectionTypeCheck = ReflectionTypeCheck;
- client[kResume]()
- }
- onHeadersComplete (statusCode, upgrade, shouldKeepAlive) {
- const { client, socket, headers, statusText } = this
+/***/ }),
- /* istanbul ignore next: difficult to make a test case for */
- if (socket.destroyed) {
- return -1
- }
+/***/ 5183:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
- const request = client[kQueue][client[kRunningIdx]]
- /* istanbul ignore next: difficult to make a test case for */
- if (!request) {
- return -1
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
}
-
- assert(!this.upgrade)
- assert(this.statusCode < 200)
-
- if (statusCode === 100) {
- util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket)))
- return -1
+ Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+ __setModuleDefault(result, mod);
+ return result;
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.req = exports.json = exports.toBuffer = void 0;
+const http = __importStar(__nccwpck_require__(8611));
+const https = __importStar(__nccwpck_require__(5692));
+async function toBuffer(stream) {
+ let length = 0;
+ const chunks = [];
+ for await (const chunk of stream) {
+ length += chunk.length;
+ chunks.push(chunk);
}
-
- /* this can only happen if server is misbehaving */
- if (upgrade && !request.upgrade) {
- util.destroy(socket, new SocketError('bad upgrade', util.getSocketInfo(socket)))
- return -1
+ return Buffer.concat(chunks, length);
+}
+exports.toBuffer = toBuffer;
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+async function json(stream) {
+ const buf = await toBuffer(stream);
+ const str = buf.toString('utf8');
+ try {
+ return JSON.parse(str);
+ }
+ catch (_err) {
+ const err = _err;
+ err.message += ` (input: ${str})`;
+ throw err;
}
+}
+exports.json = json;
+function req(url, opts = {}) {
+ const href = typeof url === 'string' ? url : url.href;
+ const req = (href.startsWith('https:') ? https : http).request(url, opts);
+ const promise = new Promise((resolve, reject) => {
+ req
+ .once('response', resolve)
+ .once('error', reject)
+ .end();
+ });
+ req.then = promise.then.bind(promise);
+ return req;
+}
+exports.req = req;
+//# sourceMappingURL=helpers.js.map
- assert(this.timeoutType === TIMEOUT_HEADERS)
+/***/ }),
- this.statusCode = statusCode
- this.shouldKeepAlive = (
- shouldKeepAlive ||
- // Override llhttp value which does not allow keepAlive for HEAD.
- (request.method === 'HEAD' && !socket[kReset] && this.connection.toLowerCase() === 'keep-alive')
- )
+/***/ 8894:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
- if (this.statusCode >= 200) {
- const bodyTimeout = request.bodyTimeout != null
- ? request.bodyTimeout
- : client[kBodyTimeout]
- this.setTimeout(bodyTimeout, TIMEOUT_BODY)
- } else if (this.timeout) {
- // istanbul ignore else: only for jest
- if (this.timeout.refresh) {
- this.timeout.refresh()
- }
- }
- if (request.method === 'CONNECT') {
- assert(client[kRunning] === 1)
- this.upgrade = true
- return 2
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
}
-
- if (upgrade) {
- assert(client[kRunning] === 1)
- this.upgrade = true
- return 2
+ Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+ __setModuleDefault(result, mod);
+ return result;
+};
+var __exportStar = (this && this.__exportStar) || function(m, exports) {
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.Agent = void 0;
+const net = __importStar(__nccwpck_require__(9278));
+const http = __importStar(__nccwpck_require__(8611));
+const https_1 = __nccwpck_require__(5692);
+__exportStar(__nccwpck_require__(5183), exports);
+const INTERNAL = Symbol('AgentBaseInternalState');
+class Agent extends http.Agent {
+ constructor(opts) {
+ super(opts);
+ this[INTERNAL] = {};
}
-
- assert((this.headers.length & 1) === 0)
- this.headers = []
- this.headersSize = 0
-
- if (this.shouldKeepAlive && client[kPipelining]) {
- const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null
-
- if (keepAliveTimeout != null) {
- const timeout = Math.min(
- keepAliveTimeout - client[kKeepAliveTimeoutThreshold],
- client[kKeepAliveMaxTimeout]
- )
- if (timeout <= 0) {
- socket[kReset] = true
- } else {
- client[kKeepAliveTimeoutValue] = timeout
+ /**
+ * Determine whether this is an `http` or `https` request.
+ */
+ isSecureEndpoint(options) {
+ if (options) {
+ // First check the `secureEndpoint` property explicitly, since this
+ // means that a parent `Agent` is "passing through" to this instance.
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ if (typeof options.secureEndpoint === 'boolean') {
+ return options.secureEndpoint;
+ }
+ // If no explicit `secure` endpoint, check if `protocol` property is
+ // set. This will usually be the case since using a full string URL
+ // or `URL` instance should be the most common usage.
+ if (typeof options.protocol === 'string') {
+ return options.protocol === 'https:';
+ }
}
- } else {
- client[kKeepAliveTimeoutValue] = client[kKeepAliveDefaultTimeout]
- }
- } else {
- // Stop more requests from being dispatched.
- socket[kReset] = true
+ // Finally, if no `protocol` property was set, then fall back to
+ // checking the stack trace of the current call stack, and try to
+ // detect the "https" module.
+ const { stack } = new Error();
+ if (typeof stack !== 'string')
+ return false;
+ return stack
+ .split('\n')
+ .some((l) => l.indexOf('(https.js:') !== -1 ||
+ l.indexOf('node:https:') !== -1);
}
-
- const pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false
-
- if (request.aborted) {
- return -1
+ // In order to support async signatures in `connect()` and Node's native
+ // connection pooling in `http.Agent`, the array of sockets for each origin
+ // has to be updated synchronously. This is so the length of the array is
+ // accurate when `addRequest()` is next called. We achieve this by creating a
+ // fake socket and adding it to `sockets[origin]` and incrementing
+ // `totalSocketCount`.
+ incrementSockets(name) {
+ // If `maxSockets` and `maxTotalSockets` are both Infinity then there is no
+ // need to create a fake socket because Node.js native connection pooling
+ // will never be invoked.
+ if (this.maxSockets === Infinity && this.maxTotalSockets === Infinity) {
+ return null;
+ }
+ // All instances of `sockets` are expected TypeScript errors. The
+ // alternative is to add it as a private property of this class but that
+ // will break TypeScript subclassing.
+ if (!this.sockets[name]) {
+ // @ts-expect-error `sockets` is readonly in `@types/node`
+ this.sockets[name] = [];
+ }
+ const fakeSocket = new net.Socket({ writable: false });
+ this.sockets[name].push(fakeSocket);
+ // @ts-expect-error `totalSocketCount` isn't defined in `@types/node`
+ this.totalSocketCount++;
+ return fakeSocket;
}
-
- if (request.method === 'HEAD') {
- return 1
+ decrementSockets(name, socket) {
+ if (!this.sockets[name] || socket === null) {
+ return;
+ }
+ const sockets = this.sockets[name];
+ const index = sockets.indexOf(socket);
+ if (index !== -1) {
+ sockets.splice(index, 1);
+ // @ts-expect-error `totalSocketCount` isn't defined in `@types/node`
+ this.totalSocketCount--;
+ if (sockets.length === 0) {
+ // @ts-expect-error `sockets` is readonly in `@types/node`
+ delete this.sockets[name];
+ }
+ }
}
-
- if (statusCode < 200) {
- return 1
+ // In order to properly update the socket pool, we need to call `getName()` on
+ // the core `https.Agent` if it is a secureEndpoint.
+ getName(options) {
+ const secureEndpoint = this.isSecureEndpoint(options);
+ if (secureEndpoint) {
+ // @ts-expect-error `getName()` isn't defined in `@types/node`
+ return https_1.Agent.prototype.getName.call(this, options);
+ }
+ // @ts-expect-error `getName()` isn't defined in `@types/node`
+ return super.getName(options);
}
-
- if (socket[kBlocking]) {
- socket[kBlocking] = false
- client[kResume]()
+ createSocket(req, options, cb) {
+ const connectOpts = {
+ ...options,
+ secureEndpoint: this.isSecureEndpoint(options),
+ };
+ const name = this.getName(connectOpts);
+ const fakeSocket = this.incrementSockets(name);
+ Promise.resolve()
+ .then(() => this.connect(req, connectOpts))
+ .then((socket) => {
+ this.decrementSockets(name, fakeSocket);
+ if (socket instanceof http.Agent) {
+ try {
+ // @ts-expect-error `addRequest()` isn't defined in `@types/node`
+ return socket.addRequest(req, connectOpts);
+ }
+ catch (err) {
+ return cb(err);
+ }
+ }
+ this[INTERNAL].currentSocket = socket;
+ // @ts-expect-error `createSocket()` isn't defined in `@types/node`
+ super.createSocket(req, options, cb);
+ }, (err) => {
+ this.decrementSockets(name, fakeSocket);
+ cb(err);
+ });
}
-
- return pause ? constants.ERROR.PAUSED : 0
- }
-
- onBody (buf) {
- const { client, socket, statusCode, maxResponseSize } = this
-
- if (socket.destroyed) {
- return -1
+ createConnection() {
+ const socket = this[INTERNAL].currentSocket;
+ this[INTERNAL].currentSocket = undefined;
+ if (!socket) {
+ throw new Error('No socket was returned in the `connect()` function');
+ }
+ return socket;
}
-
- const request = client[kQueue][client[kRunningIdx]]
- assert(request)
-
- assert(this.timeoutType === TIMEOUT_BODY)
- if (this.timeout) {
- // istanbul ignore else: only for jest
- if (this.timeout.refresh) {
- this.timeout.refresh()
- }
+ get defaultPort() {
+ return (this[INTERNAL].defaultPort ??
+ (this.protocol === 'https:' ? 443 : 80));
}
-
- assert(statusCode >= 200)
-
- if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) {
- util.destroy(socket, new ResponseExceededMaxSizeError())
- return -1
+ set defaultPort(v) {
+ if (this[INTERNAL]) {
+ this[INTERNAL].defaultPort = v;
+ }
}
-
- this.bytesRead += buf.length
-
- if (request.onData(buf) === false) {
- return constants.ERROR.PAUSED
+ get protocol() {
+ return (this[INTERNAL].protocol ??
+ (this.isSecureEndpoint() ? 'https:' : 'http:'));
}
- }
+ set protocol(v) {
+ if (this[INTERNAL]) {
+ this[INTERNAL].protocol = v;
+ }
+ }
+}
+exports.Agent = Agent;
+//# sourceMappingURL=index.js.map
- onMessageComplete () {
- const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this
+/***/ }),
- if (socket.destroyed && (!statusCode || shouldKeepAlive)) {
- return -1
- }
+/***/ 9380:
+/***/ ((module) => {
- if (upgrade) {
- return
- }
- assert(statusCode >= 100)
- assert((this.headers.length & 1) === 0)
+module.exports = balanced;
+function balanced(a, b, str) {
+ if (a instanceof RegExp) a = maybeMatch(a, str);
+ if (b instanceof RegExp) b = maybeMatch(b, str);
- const request = client[kQueue][client[kRunningIdx]]
- assert(request)
+ var r = range(a, b, str);
- this.statusCode = null
- this.statusText = ''
- this.bytesRead = 0
- this.contentLength = ''
- this.keepAlive = ''
- this.connection = ''
+ return r && {
+ start: r[0],
+ end: r[1],
+ pre: str.slice(0, r[0]),
+ body: str.slice(r[0] + a.length, r[1]),
+ post: str.slice(r[1] + b.length)
+ };
+}
- this.headers = []
- this.headersSize = 0
+function maybeMatch(reg, str) {
+ var m = str.match(reg);
+ return m ? m[0] : null;
+}
- if (statusCode < 200) {
- return
- }
+balanced.range = range;
+function range(a, b, str) {
+ var begs, beg, left, right, result;
+ var ai = str.indexOf(a);
+ var bi = str.indexOf(b, ai + 1);
+ var i = ai;
- /* istanbul ignore next: should be handled by llhttp? */
- if (request.method !== 'HEAD' && contentLength && bytesRead !== parseInt(contentLength, 10)) {
- util.destroy(socket, new ResponseContentLengthMismatchError())
- return -1
+ if (ai >= 0 && bi > 0) {
+ if(a===b) {
+ return [ai, bi];
}
+ begs = [];
+ left = str.length;
- request.onComplete(headers)
+ while (i >= 0 && !result) {
+ if (i == ai) {
+ begs.push(i);
+ ai = str.indexOf(a, i + 1);
+ } else if (begs.length == 1) {
+ result = [ begs.pop(), bi ];
+ } else {
+ beg = begs.pop();
+ if (beg < left) {
+ left = beg;
+ right = bi;
+ }
- client[kQueue][client[kRunningIdx]++] = null
+ bi = str.indexOf(b, i + 1);
+ }
- if (socket[kWriting]) {
- assert(client[kRunning] === 0)
- // Response completed before request.
- util.destroy(socket, new InformationalError('reset'))
- return constants.ERROR.PAUSED
- } else if (!shouldKeepAlive) {
- util.destroy(socket, new InformationalError('reset'))
- return constants.ERROR.PAUSED
- } else if (socket[kReset] && client[kRunning] === 0) {
- // Destroy socket once all requests have completed.
- // The request at the tail of the pipeline is the one
- // that requested reset and no further requests should
- // have been queued since then.
- util.destroy(socket, new InformationalError('reset'))
- return constants.ERROR.PAUSED
- } else if (client[kPipelining] == null || client[kPipelining] === 1) {
- // We must wait a full event loop cycle to reuse this socket to make sure
- // that non-spec compliant servers are not closing the connection even if they
- // said they won't.
- setImmediate(() => client[kResume]())
- } else {
- client[kResume]()
+ i = ai < bi && ai >= 0 ? ai : bi;
}
- }
-}
-function onParserTimeout (parser) {
- const { socket, timeoutType, client, paused } = parser.deref()
-
- /* istanbul ignore else */
- if (timeoutType === TIMEOUT_HEADERS) {
- if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) {
- assert(!paused, 'cannot be paused while waiting for headers')
- util.destroy(socket, new HeadersTimeoutError())
- }
- } else if (timeoutType === TIMEOUT_BODY) {
- if (!paused) {
- util.destroy(socket, new BodyTimeoutError())
+ if (begs.length) {
+ result = [ left, right ];
}
- } else if (timeoutType === TIMEOUT_KEEP_ALIVE) {
- assert(client[kRunning] === 0 && client[kKeepAliveTimeoutValue])
- util.destroy(socket, new InformationalError('socket idle timeout'))
}
+
+ return result;
}
-async function connectH1 (client, socket) {
- client[kSocket] = socket
- if (!llhttpInstance) {
- llhttpInstance = await llhttpPromise
- llhttpPromise = null
- }
+/***/ }),
- socket[kNoRef] = false
- socket[kWriting] = false
- socket[kReset] = false
- socket[kBlocking] = false
- socket[kParser] = new Parser(client, socket, llhttpInstance)
+/***/ 4691:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- addListener(socket, 'error', function (err) {
- assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')
+var concatMap = __nccwpck_require__(7087);
+var balanced = __nccwpck_require__(9380);
- const parser = this[kParser]
+module.exports = expandTop;
- // On Mac OS, we get an ECONNRESET even if there is a full body to be forwarded
- // to the user.
- if (err.code === 'ECONNRESET' && parser.statusCode && !parser.shouldKeepAlive) {
- // We treat all incoming data so for as a valid response.
- parser.onMessageComplete()
- return
- }
+var escSlash = '\0SLASH'+Math.random()+'\0';
+var escOpen = '\0OPEN'+Math.random()+'\0';
+var escClose = '\0CLOSE'+Math.random()+'\0';
+var escComma = '\0COMMA'+Math.random()+'\0';
+var escPeriod = '\0PERIOD'+Math.random()+'\0';
- this[kError] = err
+function numeric(str) {
+ return parseInt(str, 10) == str
+ ? parseInt(str, 10)
+ : str.charCodeAt(0);
+}
- this[kClient][kOnError](err)
- })
- addListener(socket, 'readable', function () {
- const parser = this[kParser]
+function escapeBraces(str) {
+ return str.split('\\\\').join(escSlash)
+ .split('\\{').join(escOpen)
+ .split('\\}').join(escClose)
+ .split('\\,').join(escComma)
+ .split('\\.').join(escPeriod);
+}
- if (parser) {
- parser.readMore()
- }
- })
- addListener(socket, 'end', function () {
- const parser = this[kParser]
+function unescapeBraces(str) {
+ return str.split(escSlash).join('\\')
+ .split(escOpen).join('{')
+ .split(escClose).join('}')
+ .split(escComma).join(',')
+ .split(escPeriod).join('.');
+}
- if (parser.statusCode && !parser.shouldKeepAlive) {
- // We treat all incoming data so far as a valid response.
- parser.onMessageComplete()
- return
- }
- util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this)))
- })
- addListener(socket, 'close', function () {
- const client = this[kClient]
- const parser = this[kParser]
+// Basically just str.split(","), but handling cases
+// where we have nested braced sections, which should be
+// treated as individual members, like {a,{b,c},d}
+function parseCommaParts(str) {
+ if (!str)
+ return [''];
- if (parser) {
- if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) {
- // We treat all incoming data so far as a valid response.
- parser.onMessageComplete()
- }
+ var parts = [];
+ var m = balanced('{', '}', str);
- this[kParser].destroy()
- this[kParser] = null
- }
+ if (!m)
+ return str.split(',');
- const err = this[kError] || new SocketError('closed', util.getSocketInfo(this))
+ var pre = m.pre;
+ var body = m.body;
+ var post = m.post;
+ var p = pre.split(',');
- client[kSocket] = null
- client[kHTTPContext] = null // TODO (fix): This is hacky...
+ p[p.length-1] += '{' + body + '}';
+ var postParts = parseCommaParts(post);
+ if (post.length) {
+ p[p.length-1] += postParts.shift();
+ p.push.apply(p, postParts);
+ }
- if (client.destroyed) {
- assert(client[kPending] === 0)
+ parts.push.apply(parts, p);
- // Fail entire queue.
- const requests = client[kQueue].splice(client[kRunningIdx])
- for (let i = 0; i < requests.length; i++) {
- const request = requests[i]
- util.errorRequest(client, request, err)
- }
- } else if (client[kRunning] > 0 && err.code !== 'UND_ERR_INFO') {
- // Fail head of pipeline.
- const request = client[kQueue][client[kRunningIdx]]
- client[kQueue][client[kRunningIdx]++] = null
+ return parts;
+}
- util.errorRequest(client, request, err)
- }
+function expandTop(str) {
+ if (!str)
+ return [];
- client[kPendingIdx] = client[kRunningIdx]
+ // I don't know why Bash 4.3 does this, but it does.
+ // Anything starting with {} will have the first two bytes preserved
+ // but *only* at the top level, so {},a}b will not expand to anything,
+ // but a{},b}c will be expanded to [a}c,abc].
+ // One could argue that this is a bug in Bash, but since the goal of
+ // this module is to match Bash's rules, we escape a leading {}
+ if (str.substr(0, 2) === '{}') {
+ str = '\\{\\}' + str.substr(2);
+ }
- assert(client[kRunning] === 0)
+ return expand(escapeBraces(str), true).map(unescapeBraces);
+}
- client.emit('disconnect', client[kUrl], [client], err)
+function identity(e) {
+ return e;
+}
- client[kResume]()
- })
+function embrace(str) {
+ return '{' + str + '}';
+}
+function isPadded(el) {
+ return /^-?0\d/.test(el);
+}
- let closed = false
- socket.on('close', () => {
- closed = true
- })
+function lte(i, y) {
+ return i <= y;
+}
+function gte(i, y) {
+ return i >= y;
+}
- return {
- version: 'h1',
- defaultPipelining: 1,
- write (...args) {
- return writeH1(client, ...args)
- },
- resume () {
- resumeH1(client)
- },
- destroy (err, callback) {
- if (closed) {
- queueMicrotask(callback)
- } else {
- socket.destroy(err).on('close', callback)
- }
- },
- get destroyed () {
- return socket.destroyed
- },
- busy (request) {
- if (socket[kWriting] || socket[kReset] || socket[kBlocking]) {
- return true
- }
-
- if (request) {
- if (client[kRunning] > 0 && !request.idempotent) {
- // Non-idempotent request cannot be retried.
- // Ensure that no other requests are inflight and
- // could cause failure.
- return true
- }
-
- if (client[kRunning] > 0 && (request.upgrade || request.method === 'CONNECT')) {
- // Don't dispatch an upgrade until all preceding requests have completed.
- // A misbehaving server might upgrade the connection before all pipelined
- // request has completed.
- return true
- }
-
- if (client[kRunning] > 0 && util.bodyLength(request.body) !== 0 &&
- (util.isStream(request.body) || util.isAsyncIterable(request.body) || util.isFormDataLike(request.body))) {
- // Request with stream or iterator body can error while other requests
- // are inflight and indirectly error those as well.
- // Ensure this doesn't happen by waiting for inflight
- // to complete before dispatching.
+function expand(str, isTop) {
+ var expansions = [];
- // Request with stream or iterator body cannot be retried.
- // Ensure that no other requests are inflight and
- // could cause failure.
- return true
- }
- }
+ var m = balanced('{', '}', str);
+ if (!m || /\$$/.test(m.pre)) return [str];
- return false
+ var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
+ var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
+ var isSequence = isNumericSequence || isAlphaSequence;
+ var isOptions = m.body.indexOf(',') >= 0;
+ if (!isSequence && !isOptions) {
+ // {a},b}
+ if (m.post.match(/,.*\}/)) {
+ str = m.pre + '{' + m.body + escClose + m.post;
+ return expand(str);
}
+ return [str];
}
-}
-function resumeH1 (client) {
- const socket = client[kSocket]
-
- if (socket && !socket.destroyed) {
- if (client[kSize] === 0) {
- if (!socket[kNoRef] && socket.unref) {
- socket.unref()
- socket[kNoRef] = true
- }
- } else if (socket[kNoRef] && socket.ref) {
- socket.ref()
- socket[kNoRef] = false
- }
-
- if (client[kSize] === 0) {
- if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) {
- socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE)
- }
- } else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) {
- if (socket[kParser].timeoutType !== TIMEOUT_HEADERS) {
- const request = client[kQueue][client[kRunningIdx]]
- const headersTimeout = request.headersTimeout != null
- ? request.headersTimeout
- : client[kHeadersTimeout]
- socket[kParser].setTimeout(headersTimeout, TIMEOUT_HEADERS)
+ var n;
+ if (isSequence) {
+ n = m.body.split(/\.\./);
+ } else {
+ n = parseCommaParts(m.body);
+ if (n.length === 1) {
+ // x{{a,b}}y ==> x{a}y x{b}y
+ n = expand(n[0], false).map(embrace);
+ if (n.length === 1) {
+ var post = m.post.length
+ ? expand(m.post, false)
+ : [''];
+ return post.map(function(p) {
+ return m.pre + n[0] + p;
+ });
}
}
}
-}
-
-// https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2
-function shouldSendContentLength (method) {
- return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT'
-}
-
-function writeH1 (client, request) {
- const { method, path, host, upgrade, blocking, reset } = request
-
- let { body, headers, contentLength } = request
- // https://tools.ietf.org/html/rfc7231#section-4.3.1
- // https://tools.ietf.org/html/rfc7231#section-4.3.2
- // https://tools.ietf.org/html/rfc7231#section-4.3.5
+ // at this point, n is the parts, and we know it's not a comma set
+ // with a single entry.
- // Sending a payload body on a request that does not
- // expect it can cause undefined behavior on some
- // servers and corrupt connection state. Do not
- // re-use the connection for further requests.
+ // no need to expand pre, since it is guaranteed to be free of brace-sets
+ var pre = m.pre;
+ var post = m.post.length
+ ? expand(m.post, false)
+ : [''];
- const expectsPayload = (
- method === 'PUT' ||
- method === 'POST' ||
- method === 'PATCH' ||
- method === 'QUERY' ||
- method === 'PROPFIND' ||
- method === 'PROPPATCH'
- )
+ var N;
- if (util.isFormDataLike(body)) {
- if (!extractBody) {
- extractBody = (__nccwpck_require__(3278).extractBody)
+ if (isSequence) {
+ var x = numeric(n[0]);
+ var y = numeric(n[1]);
+ var width = Math.max(n[0].length, n[1].length)
+ var incr = n.length == 3
+ ? Math.abs(numeric(n[2]))
+ : 1;
+ var test = lte;
+ var reverse = y < x;
+ if (reverse) {
+ incr *= -1;
+ test = gte;
}
+ var pad = n.some(isPadded);
- const [bodyStream, contentType] = extractBody(body)
- if (request.contentType == null) {
- headers.push('content-type', contentType)
+ N = [];
+
+ for (var i = x; test(i, y); i += incr) {
+ var c;
+ if (isAlphaSequence) {
+ c = String.fromCharCode(i);
+ if (c === '\\')
+ c = '';
+ } else {
+ c = String(i);
+ if (pad) {
+ var need = width - c.length;
+ if (need > 0) {
+ var z = new Array(need + 1).join('0');
+ if (i < 0)
+ c = '-' + z + c.slice(1);
+ else
+ c = z + c;
+ }
+ }
+ }
+ N.push(c);
}
- body = bodyStream.stream
- contentLength = bodyStream.length
- } else if (util.isBlobLike(body) && request.contentType == null && body.type) {
- headers.push('content-type', body.type)
+ } else {
+ N = concatMap(n, function(el) { return expand(el, false) });
}
- if (body && typeof body.read === 'function') {
- // Try to read EOF in order to get length.
- body.read(0)
+ for (var j = 0; j < N.length; j++) {
+ for (var k = 0; k < post.length; k++) {
+ var expansion = pre + N[j] + post[k];
+ if (!isTop || isSequence || expansion)
+ expansions.push(expansion);
+ }
}
- const bodyLength = util.bodyLength(body)
+ return expansions;
+}
- contentLength = bodyLength ?? contentLength
- if (contentLength === null) {
- contentLength = request.contentLength
- }
- if (contentLength === 0 && !expectsPayload) {
- // https://tools.ietf.org/html/rfc7230#section-3.3.2
- // A user agent SHOULD NOT send a Content-Length header field when
- // the request message does not contain a payload body and the method
- // semantics do not anticipate such a body.
+/***/ }),
- contentLength = null
- }
+/***/ 7087:
+/***/ ((module) => {
- // https://github.com/nodejs/undici/issues/2046
- // A user agent may send a Content-Length header with 0 value, this should be allowed.
- if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength !== null && request.contentLength !== contentLength) {
- if (client[kStrictContentLength]) {
- util.errorRequest(client, request, new RequestContentLengthMismatchError())
- return false
+module.exports = function (xs, fn) {
+ var res = [];
+ for (var i = 0; i < xs.length; i++) {
+ var x = fn(xs[i], i);
+ if (isArray(x)) res.push.apply(res, x);
+ else res.push(x);
}
+ return res;
+};
- process.emitWarning(new RequestContentLengthMismatchError())
- }
-
- const socket = client[kSocket]
+var isArray = Array.isArray || function (xs) {
+ return Object.prototype.toString.call(xs) === '[object Array]';
+};
- const abort = (err) => {
- if (request.aborted || request.completed) {
- return
- }
- util.errorRequest(client, request, err || new RequestAbortedError())
+/***/ }),
- util.destroy(body)
- util.destroy(socket, new InformationalError('aborted'))
- }
+/***/ 6110:
+/***/ ((module, exports, __nccwpck_require__) => {
- try {
- request.onConnect(abort)
- } catch (err) {
- util.errorRequest(client, request, err)
- }
+/* eslint-env browser */
- if (request.aborted) {
- return false
- }
+/**
+ * This is the web browser implementation of `debug()`.
+ */
- if (method === 'HEAD') {
- // https://github.com/mcollina/undici/issues/258
- // Close after a HEAD request to interop with misbehaving servers
- // that may send a body in the response.
+exports.formatArgs = formatArgs;
+exports.save = save;
+exports.load = load;
+exports.useColors = useColors;
+exports.storage = localstorage();
+exports.destroy = (() => {
+ let warned = false;
- socket[kReset] = true
- }
+ return () => {
+ if (!warned) {
+ warned = true;
+ console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
+ }
+ };
+})();
- if (upgrade || method === 'CONNECT') {
- // On CONNECT or upgrade, block pipeline from dispatching further
- // requests on this connection.
+/**
+ * Colors.
+ */
- socket[kReset] = true
- }
+exports.colors = [
+ '#0000CC',
+ '#0000FF',
+ '#0033CC',
+ '#0033FF',
+ '#0066CC',
+ '#0066FF',
+ '#0099CC',
+ '#0099FF',
+ '#00CC00',
+ '#00CC33',
+ '#00CC66',
+ '#00CC99',
+ '#00CCCC',
+ '#00CCFF',
+ '#3300CC',
+ '#3300FF',
+ '#3333CC',
+ '#3333FF',
+ '#3366CC',
+ '#3366FF',
+ '#3399CC',
+ '#3399FF',
+ '#33CC00',
+ '#33CC33',
+ '#33CC66',
+ '#33CC99',
+ '#33CCCC',
+ '#33CCFF',
+ '#6600CC',
+ '#6600FF',
+ '#6633CC',
+ '#6633FF',
+ '#66CC00',
+ '#66CC33',
+ '#9900CC',
+ '#9900FF',
+ '#9933CC',
+ '#9933FF',
+ '#99CC00',
+ '#99CC33',
+ '#CC0000',
+ '#CC0033',
+ '#CC0066',
+ '#CC0099',
+ '#CC00CC',
+ '#CC00FF',
+ '#CC3300',
+ '#CC3333',
+ '#CC3366',
+ '#CC3399',
+ '#CC33CC',
+ '#CC33FF',
+ '#CC6600',
+ '#CC6633',
+ '#CC9900',
+ '#CC9933',
+ '#CCCC00',
+ '#CCCC33',
+ '#FF0000',
+ '#FF0033',
+ '#FF0066',
+ '#FF0099',
+ '#FF00CC',
+ '#FF00FF',
+ '#FF3300',
+ '#FF3333',
+ '#FF3366',
+ '#FF3399',
+ '#FF33CC',
+ '#FF33FF',
+ '#FF6600',
+ '#FF6633',
+ '#FF9900',
+ '#FF9933',
+ '#FFCC00',
+ '#FFCC33'
+];
- if (reset != null) {
- socket[kReset] = reset
- }
+/**
+ * Currently only WebKit-based Web Inspectors, Firefox >= v31,
+ * and the Firebug extension (any Firefox version) are known
+ * to support "%c" CSS customizations.
+ *
+ * TODO: add a `localStorage` variable to explicitly enable/disable colors
+ */
- if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) {
- socket[kReset] = true
- }
+// eslint-disable-next-line complexity
+function useColors() {
+ // NB: In an Electron preload script, document will be defined but not fully
+ // initialized. Since we know we're in Chrome, we'll just detect this case
+ // explicitly
+ if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
+ return true;
+ }
- if (blocking) {
- socket[kBlocking] = true
- }
+ // Internet Explorer and Edge do not support colors.
+ if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
+ return false;
+ }
- let header = `${method} ${path} HTTP/1.1\r\n`
+ let m;
- if (typeof host === 'string') {
- header += `host: ${host}\r\n`
- } else {
- header += client[kHostHeader]
- }
+ // Is webkit? http://stackoverflow.com/a/16459606/376773
+ // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
+ // eslint-disable-next-line no-return-assign
+ return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
+ // Is firebug? http://stackoverflow.com/a/398120/376773
+ (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
+ // Is firefox >= v31?
+ // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
+ (typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31) ||
+ // Double check webkit in userAgent just in case we are in a worker
+ (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
+}
- if (upgrade) {
- header += `connection: upgrade\r\nupgrade: ${upgrade}\r\n`
- } else if (client[kPipelining] && !socket[kReset]) {
- header += 'connection: keep-alive\r\n'
- } else {
- header += 'connection: close\r\n'
- }
+/**
+ * Colorize log arguments if enabled.
+ *
+ * @api public
+ */
- if (Array.isArray(headers)) {
- for (let n = 0; n < headers.length; n += 2) {
- const key = headers[n + 0]
- const val = headers[n + 1]
+function formatArgs(args) {
+ args[0] = (this.useColors ? '%c' : '') +
+ this.namespace +
+ (this.useColors ? ' %c' : ' ') +
+ args[0] +
+ (this.useColors ? '%c ' : ' ') +
+ '+' + module.exports.humanize(this.diff);
- if (Array.isArray(val)) {
- for (let i = 0; i < val.length; i++) {
- header += `${key}: ${val[i]}\r\n`
- }
- } else {
- header += `${key}: ${val}\r\n`
- }
- }
- }
+ if (!this.useColors) {
+ return;
+ }
- if (channels.sendHeaders.hasSubscribers) {
- channels.sendHeaders.publish({ request, headers: header, socket })
- }
+ const c = 'color: ' + this.color;
+ args.splice(1, 0, c, 'color: inherit');
- /* istanbul ignore else: assertion */
- if (!body || bodyLength === 0) {
- writeBuffer(abort, null, client, request, socket, contentLength, header, expectsPayload)
- } else if (util.isBuffer(body)) {
- writeBuffer(abort, body, client, request, socket, contentLength, header, expectsPayload)
- } else if (util.isBlobLike(body)) {
- if (typeof body.stream === 'function') {
- writeIterable(abort, body.stream(), client, request, socket, contentLength, header, expectsPayload)
- } else {
- writeBlob(abort, body, client, request, socket, contentLength, header, expectsPayload)
- }
- } else if (util.isStream(body)) {
- writeStream(abort, body, client, request, socket, contentLength, header, expectsPayload)
- } else if (util.isIterable(body)) {
- writeIterable(abort, body, client, request, socket, contentLength, header, expectsPayload)
- } else {
- assert(false)
- }
+ // The final "%c" is somewhat tricky, because there could be other
+ // arguments passed either before or after the %c, so we need to
+ // figure out the correct index to insert the CSS into
+ let index = 0;
+ let lastC = 0;
+ args[0].replace(/%[a-zA-Z%]/g, match => {
+ if (match === '%%') {
+ return;
+ }
+ index++;
+ if (match === '%c') {
+ // We only are interested in the *last* %c
+ // (the user may have provided their own)
+ lastC = index;
+ }
+ });
- return true
+ args.splice(lastC, 0, c);
}
-function writeStream (abort, body, client, request, socket, contentLength, header, expectsPayload) {
- assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined')
-
- let finished = false
-
- const writer = new AsyncWriter({ abort, socket, request, contentLength, client, expectsPayload, header })
-
- const onData = function (chunk) {
- if (finished) {
- return
- }
+/**
+ * Invokes `console.debug()` when available.
+ * No-op when `console.debug` is not a "function".
+ * If `console.debug` is not available, falls back
+ * to `console.log`.
+ *
+ * @api public
+ */
+exports.log = console.debug || console.log || (() => {});
- try {
- if (!writer.write(chunk) && this.pause) {
- this.pause()
- }
- } catch (err) {
- util.destroy(this, err)
- }
- }
- const onDrain = function () {
- if (finished) {
- return
- }
+/**
+ * Save `namespaces`.
+ *
+ * @param {String} namespaces
+ * @api private
+ */
+function save(namespaces) {
+ try {
+ if (namespaces) {
+ exports.storage.setItem('debug', namespaces);
+ } else {
+ exports.storage.removeItem('debug');
+ }
+ } catch (error) {
+ // Swallow
+ // XXX (@Qix-) should we be logging these?
+ }
+}
- if (body.resume) {
- body.resume()
- }
- }
- const onClose = function () {
- // 'close' might be emitted *before* 'error' for
- // broken streams. Wait a tick to avoid this case.
- queueMicrotask(() => {
- // It's only safe to remove 'error' listener after
- // 'close'.
- body.removeListener('error', onFinished)
- })
+/**
+ * Load `namespaces`.
+ *
+ * @return {String} returns the previously persisted debug modes
+ * @api private
+ */
+function load() {
+ let r;
+ try {
+ r = exports.storage.getItem('debug') || exports.storage.getItem('DEBUG') ;
+ } catch (error) {
+ // Swallow
+ // XXX (@Qix-) should we be logging these?
+ }
- if (!finished) {
- const err = new RequestAbortedError()
- queueMicrotask(() => onFinished(err))
- }
- }
- const onFinished = function (err) {
- if (finished) {
- return
- }
+ // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
+ if (!r && typeof process !== 'undefined' && 'env' in process) {
+ r = process.env.DEBUG;
+ }
- finished = true
+ return r;
+}
- assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1))
+/**
+ * Localstorage attempts to return the localstorage.
+ *
+ * This is necessary because safari throws
+ * when a user disables cookies/localstorage
+ * and you attempt to access it.
+ *
+ * @return {LocalStorage}
+ * @api private
+ */
- socket
- .off('drain', onDrain)
- .off('error', onFinished)
+function localstorage() {
+ try {
+ // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
+ // The Browser also has localStorage in the global context.
+ return localStorage;
+ } catch (error) {
+ // Swallow
+ // XXX (@Qix-) should we be logging these?
+ }
+}
- body
- .removeListener('data', onData)
- .removeListener('end', onFinished)
- .removeListener('close', onClose)
+module.exports = __nccwpck_require__(897)(exports);
- if (!err) {
- try {
- writer.end()
- } catch (er) {
- err = er
- }
- }
+const {formatters} = module.exports;
- writer.destroy(err)
+/**
+ * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
+ */
- if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) {
- util.destroy(body, err)
- } else {
- util.destroy(body)
- }
- }
+formatters.j = function (v) {
+ try {
+ return JSON.stringify(v);
+ } catch (error) {
+ return '[UnexpectedJSONParseError]: ' + error.message;
+ }
+};
- body
- .on('data', onData)
- .on('end', onFinished)
- .on('error', onFinished)
- .on('close', onClose)
- if (body.resume) {
- body.resume()
- }
+/***/ }),
- socket
- .on('drain', onDrain)
- .on('error', onFinished)
+/***/ 897:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- if (body.errorEmitted ?? body.errored) {
- setImmediate(() => onFinished(body.errored))
- } else if (body.endEmitted ?? body.readableEnded) {
- setImmediate(() => onFinished(null))
- }
- if (body.closeEmitted ?? body.closed) {
- setImmediate(onClose)
- }
-}
+/**
+ * This is the common logic for both the Node.js and web browser
+ * implementations of `debug()`.
+ */
-function writeBuffer (abort, body, client, request, socket, contentLength, header, expectsPayload) {
- try {
- if (!body) {
- if (contentLength === 0) {
- socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1')
- } else {
- assert(contentLength === null, 'no body must not have content length')
- socket.write(`${header}\r\n`, 'latin1')
- }
- } else if (util.isBuffer(body)) {
- assert(contentLength === body.byteLength, 'buffer body must have content length')
+function setup(env) {
+ createDebug.debug = createDebug;
+ createDebug.default = createDebug;
+ createDebug.coerce = coerce;
+ createDebug.disable = disable;
+ createDebug.enable = enable;
+ createDebug.enabled = enabled;
+ createDebug.humanize = __nccwpck_require__(744);
+ createDebug.destroy = destroy;
- socket.cork()
- socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
- socket.write(body)
- socket.uncork()
- request.onBodySent(body)
+ Object.keys(env).forEach(key => {
+ createDebug[key] = env[key];
+ });
- if (!expectsPayload && request.reset !== false) {
- socket[kReset] = true
- }
- }
- request.onRequestSent()
+ /**
+ * The currently active debug mode names, and names to skip.
+ */
- client[kResume]()
- } catch (err) {
- abort(err)
- }
-}
+ createDebug.names = [];
+ createDebug.skips = [];
-async function writeBlob (abort, body, client, request, socket, contentLength, header, expectsPayload) {
- assert(contentLength === body.size, 'blob body must have content length')
+ /**
+ * Map of special "%n" handling functions, for the debug "format" argument.
+ *
+ * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
+ */
+ createDebug.formatters = {};
- try {
- if (contentLength != null && contentLength !== body.size) {
- throw new RequestContentLengthMismatchError()
- }
+ /**
+ * Selects a color for a debug namespace
+ * @param {String} namespace The namespace string for the debug instance to be colored
+ * @return {Number|String} An ANSI color code for the given namespace
+ * @api private
+ */
+ function selectColor(namespace) {
+ let hash = 0;
- const buffer = Buffer.from(await body.arrayBuffer())
+ for (let i = 0; i < namespace.length; i++) {
+ hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
+ hash |= 0; // Convert to 32bit integer
+ }
- socket.cork()
- socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
- socket.write(buffer)
- socket.uncork()
+ return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
+ }
+ createDebug.selectColor = selectColor;
- request.onBodySent(buffer)
- request.onRequestSent()
+ /**
+ * Create a debugger with the given `namespace`.
+ *
+ * @param {String} namespace
+ * @return {Function}
+ * @api public
+ */
+ function createDebug(namespace) {
+ let prevTime;
+ let enableOverride = null;
+ let namespacesCache;
+ let enabledCache;
- if (!expectsPayload && request.reset !== false) {
- socket[kReset] = true
- }
+ function debug(...args) {
+ // Disabled?
+ if (!debug.enabled) {
+ return;
+ }
- client[kResume]()
- } catch (err) {
- abort(err)
- }
-}
+ const self = debug;
-async function writeIterable (abort, body, client, request, socket, contentLength, header, expectsPayload) {
- assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined')
+ // Set `diff` timestamp
+ const curr = Number(new Date());
+ const ms = curr - (prevTime || curr);
+ self.diff = ms;
+ self.prev = prevTime;
+ self.curr = curr;
+ prevTime = curr;
- let callback = null
- function onDrain () {
- if (callback) {
- const cb = callback
- callback = null
- cb()
- }
- }
+ args[0] = createDebug.coerce(args[0]);
- const waitForDrain = () => new Promise((resolve, reject) => {
- assert(callback === null)
+ if (typeof args[0] !== 'string') {
+ // Anything else let's inspect with %O
+ args.unshift('%O');
+ }
- if (socket[kError]) {
- reject(socket[kError])
- } else {
- callback = resolve
- }
- })
+ // Apply any `formatters` transformations
+ let index = 0;
+ args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
+ // If we encounter an escaped % then don't increase the array index
+ if (match === '%%') {
+ return '%';
+ }
+ index++;
+ const formatter = createDebug.formatters[format];
+ if (typeof formatter === 'function') {
+ const val = args[index];
+ match = formatter.call(self, val);
- socket
- .on('close', onDrain)
- .on('drain', onDrain)
+ // Now we need to remove `args[index]` since it's inlined in the `format`
+ args.splice(index, 1);
+ index--;
+ }
+ return match;
+ });
- const writer = new AsyncWriter({ abort, socket, request, contentLength, client, expectsPayload, header })
- try {
- // It's up to the user to somehow abort the async iterable.
- for await (const chunk of body) {
- if (socket[kError]) {
- throw socket[kError]
- }
+ // Apply env-specific formatting (colors, etc.)
+ createDebug.formatArgs.call(self, args);
- if (!writer.write(chunk)) {
- await waitForDrain()
- }
- }
+ const logFn = self.log || createDebug.log;
+ logFn.apply(self, args);
+ }
- writer.end()
- } catch (err) {
- writer.destroy(err)
- } finally {
- socket
- .off('close', onDrain)
- .off('drain', onDrain)
- }
-}
+ debug.namespace = namespace;
+ debug.useColors = createDebug.useColors();
+ debug.color = createDebug.selectColor(namespace);
+ debug.extend = extend;
+ debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
-class AsyncWriter {
- constructor ({ abort, socket, request, contentLength, client, expectsPayload, header }) {
- this.socket = socket
- this.request = request
- this.contentLength = contentLength
- this.client = client
- this.bytesWritten = 0
- this.expectsPayload = expectsPayload
- this.header = header
- this.abort = abort
+ Object.defineProperty(debug, 'enabled', {
+ enumerable: true,
+ configurable: false,
+ get: () => {
+ if (enableOverride !== null) {
+ return enableOverride;
+ }
+ if (namespacesCache !== createDebug.namespaces) {
+ namespacesCache = createDebug.namespaces;
+ enabledCache = createDebug.enabled(namespace);
+ }
- socket[kWriting] = true
- }
+ return enabledCache;
+ },
+ set: v => {
+ enableOverride = v;
+ }
+ });
- write (chunk) {
- const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this
+ // Env-specific initialization logic for debug instances
+ if (typeof createDebug.init === 'function') {
+ createDebug.init(debug);
+ }
- if (socket[kError]) {
- throw socket[kError]
- }
+ return debug;
+ }
- if (socket.destroyed) {
- return false
- }
+ function extend(namespace, delimiter) {
+ const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
+ newDebug.log = this.log;
+ return newDebug;
+ }
- const len = Buffer.byteLength(chunk)
- if (!len) {
- return true
- }
+ /**
+ * Enables a debug mode by namespaces. This can include modes
+ * separated by a colon and wildcards.
+ *
+ * @param {String} namespaces
+ * @api public
+ */
+ function enable(namespaces) {
+ createDebug.save(namespaces);
+ createDebug.namespaces = namespaces;
- // We should defer writing chunks.
- if (contentLength !== null && bytesWritten + len > contentLength) {
- if (client[kStrictContentLength]) {
- throw new RequestContentLengthMismatchError()
- }
+ createDebug.names = [];
+ createDebug.skips = [];
- process.emitWarning(new RequestContentLengthMismatchError())
- }
+ const split = (typeof namespaces === 'string' ? namespaces : '')
+ .trim()
+ .replace(/\s+/g, ',')
+ .split(',')
+ .filter(Boolean);
- socket.cork()
+ for (const ns of split) {
+ if (ns[0] === '-') {
+ createDebug.skips.push(ns.slice(1));
+ } else {
+ createDebug.names.push(ns);
+ }
+ }
+ }
- if (bytesWritten === 0) {
- if (!expectsPayload && request.reset !== false) {
- socket[kReset] = true
- }
+ /**
+ * Checks if the given string matches a namespace template, honoring
+ * asterisks as wildcards.
+ *
+ * @param {String} search
+ * @param {String} template
+ * @return {Boolean}
+ */
+ function matchesTemplate(search, template) {
+ let searchIndex = 0;
+ let templateIndex = 0;
+ let starIndex = -1;
+ let matchIndex = 0;
- if (contentLength === null) {
- socket.write(`${header}transfer-encoding: chunked\r\n`, 'latin1')
- } else {
- socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
- }
- }
+ while (searchIndex < search.length) {
+ if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) {
+ // Match character or proceed with wildcard
+ if (template[templateIndex] === '*') {
+ starIndex = templateIndex;
+ matchIndex = searchIndex;
+ templateIndex++; // Skip the '*'
+ } else {
+ searchIndex++;
+ templateIndex++;
+ }
+ } else if (starIndex !== -1) { // eslint-disable-line no-negated-condition
+ // Backtrack to the last '*' and try to match more characters
+ templateIndex = starIndex + 1;
+ matchIndex++;
+ searchIndex = matchIndex;
+ } else {
+ return false; // No match
+ }
+ }
- if (contentLength === null) {
- socket.write(`\r\n${len.toString(16)}\r\n`, 'latin1')
- }
+ // Handle trailing '*' in template
+ while (templateIndex < template.length && template[templateIndex] === '*') {
+ templateIndex++;
+ }
- this.bytesWritten += len
+ return templateIndex === template.length;
+ }
- const ret = socket.write(chunk)
+ /**
+ * Disable debug output.
+ *
+ * @return {String} namespaces
+ * @api public
+ */
+ function disable() {
+ const namespaces = [
+ ...createDebug.names,
+ ...createDebug.skips.map(namespace => '-' + namespace)
+ ].join(',');
+ createDebug.enable('');
+ return namespaces;
+ }
- socket.uncork()
+ /**
+ * Returns true if the given mode name is enabled, false otherwise.
+ *
+ * @param {String} name
+ * @return {Boolean}
+ * @api public
+ */
+ function enabled(name) {
+ for (const skip of createDebug.skips) {
+ if (matchesTemplate(name, skip)) {
+ return false;
+ }
+ }
- request.onBodySent(chunk)
+ for (const ns of createDebug.names) {
+ if (matchesTemplate(name, ns)) {
+ return true;
+ }
+ }
- if (!ret) {
- if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
- // istanbul ignore else: only for jest
- if (socket[kParser].timeout.refresh) {
- socket[kParser].timeout.refresh()
- }
- }
- }
+ return false;
+ }
- return ret
- }
-
- end () {
- const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this
- request.onRequestSent()
-
- socket[kWriting] = false
-
- if (socket[kError]) {
- throw socket[kError]
- }
+ /**
+ * Coerce `val`.
+ *
+ * @param {Mixed} val
+ * @return {Mixed}
+ * @api private
+ */
+ function coerce(val) {
+ if (val instanceof Error) {
+ return val.stack || val.message;
+ }
+ return val;
+ }
- if (socket.destroyed) {
- return
- }
+ /**
+ * XXX DO NOT USE. This is a temporary stub function.
+ * XXX It WILL be removed in the next major release.
+ */
+ function destroy() {
+ console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
+ }
- if (bytesWritten === 0) {
- if (expectsPayload) {
- // https://tools.ietf.org/html/rfc7230#section-3.3.2
- // A user agent SHOULD send a Content-Length in a request message when
- // no Transfer-Encoding is sent and the request method defines a meaning
- // for an enclosed payload body.
+ createDebug.enable(createDebug.load());
- socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1')
- } else {
- socket.write(`${header}\r\n`, 'latin1')
- }
- } else if (contentLength === null) {
- socket.write('\r\n0\r\n\r\n', 'latin1')
- }
+ return createDebug;
+}
- if (contentLength !== null && bytesWritten !== contentLength) {
- if (client[kStrictContentLength]) {
- throw new RequestContentLengthMismatchError()
- } else {
- process.emitWarning(new RequestContentLengthMismatchError())
- }
- }
+module.exports = setup;
- if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
- // istanbul ignore else: only for jest
- if (socket[kParser].timeout.refresh) {
- socket[kParser].timeout.refresh()
- }
- }
- client[kResume]()
- }
+/***/ }),
- destroy (err) {
- const { socket, client, abort } = this
+/***/ 2830:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- socket[kWriting] = false
+/**
+ * Detect Electron renderer / nwjs process, which is node, but we should
+ * treat as a browser.
+ */
- if (err) {
- assert(client[kRunning] <= 1, 'pipeline should only contain this request')
- abort(err)
- }
- }
+if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
+ module.exports = __nccwpck_require__(6110);
+} else {
+ module.exports = __nccwpck_require__(5108);
}
-module.exports = connectH1
-
/***/ }),
-/***/ 3045:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 5108:
+/***/ ((module, exports, __nccwpck_require__) => {
+/**
+ * Module dependencies.
+ */
+const tty = __nccwpck_require__(2018);
+const util = __nccwpck_require__(9023);
-const assert = __nccwpck_require__(4589)
-const { pipeline } = __nccwpck_require__(7075)
-const util = __nccwpck_require__(7375)
-const {
- RequestContentLengthMismatchError,
- RequestAbortedError,
- SocketError,
- InformationalError
-} = __nccwpck_require__(2344)
-const {
- kUrl,
- kReset,
- kClient,
- kRunning,
- kPending,
- kQueue,
- kPendingIdx,
- kRunningIdx,
- kError,
- kSocket,
- kStrictContentLength,
- kOnError,
- kMaxConcurrentStreams,
- kHTTP2Session,
- kResume,
- kSize,
- kHTTPContext
-} = __nccwpck_require__(6130)
+/**
+ * This is the Node.js implementation of `debug()`.
+ */
-const kOpenStreams = Symbol('open streams')
+exports.init = init;
+exports.log = log;
+exports.formatArgs = formatArgs;
+exports.save = save;
+exports.load = load;
+exports.useColors = useColors;
+exports.destroy = util.deprecate(
+ () => {},
+ 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'
+);
-let extractBody
+/**
+ * Colors.
+ */
-// Experimental
-let h2ExperimentalWarned = false
+exports.colors = [6, 2, 3, 4, 5, 1];
-/** @type {import('http2')} */
-let http2
try {
- http2 = __nccwpck_require__(2467)
-} catch {
- // @ts-ignore
- http2 = { constants: {} }
-}
-
-const {
- constants: {
- HTTP2_HEADER_AUTHORITY,
- HTTP2_HEADER_METHOD,
- HTTP2_HEADER_PATH,
- HTTP2_HEADER_SCHEME,
- HTTP2_HEADER_CONTENT_LENGTH,
- HTTP2_HEADER_EXPECT,
- HTTP2_HEADER_STATUS
- }
-} = http2
-
-function parseH2Headers (headers) {
- const result = []
-
- for (const [name, value] of Object.entries(headers)) {
- // h2 may concat the header value by array
- // e.g. Set-Cookie
- if (Array.isArray(value)) {
- for (const subvalue of value) {
- // we need to provide each header value of header name
- // because the headers handler expect name-value pair
- result.push(Buffer.from(name), Buffer.from(subvalue))
- }
- } else {
- result.push(Buffer.from(name), Buffer.from(value))
- }
- }
+ // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
+ // eslint-disable-next-line import/no-extraneous-dependencies
+ const supportsColor = __nccwpck_require__(75);
- return result
+ if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
+ exports.colors = [
+ 20,
+ 21,
+ 26,
+ 27,
+ 32,
+ 33,
+ 38,
+ 39,
+ 40,
+ 41,
+ 42,
+ 43,
+ 44,
+ 45,
+ 56,
+ 57,
+ 62,
+ 63,
+ 68,
+ 69,
+ 74,
+ 75,
+ 76,
+ 77,
+ 78,
+ 79,
+ 80,
+ 81,
+ 92,
+ 93,
+ 98,
+ 99,
+ 112,
+ 113,
+ 128,
+ 129,
+ 134,
+ 135,
+ 148,
+ 149,
+ 160,
+ 161,
+ 162,
+ 163,
+ 164,
+ 165,
+ 166,
+ 167,
+ 168,
+ 169,
+ 170,
+ 171,
+ 172,
+ 173,
+ 178,
+ 179,
+ 184,
+ 185,
+ 196,
+ 197,
+ 198,
+ 199,
+ 200,
+ 201,
+ 202,
+ 203,
+ 204,
+ 205,
+ 206,
+ 207,
+ 208,
+ 209,
+ 214,
+ 215,
+ 220,
+ 221
+ ];
+ }
+} catch (error) {
+ // Swallow - we only care if `supports-color` is available; it doesn't have to be.
}
-async function connectH2 (client, socket) {
- client[kSocket] = socket
-
- if (!h2ExperimentalWarned) {
- h2ExperimentalWarned = true
- process.emitWarning('H2 support is experimental, expect them to change at any time.', {
- code: 'UNDICI-H2'
- })
- }
+/**
+ * Build up the default `inspectOpts` object from the environment variables.
+ *
+ * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
+ */
- const session = http2.connect(client[kUrl], {
- createConnection: () => socket,
- peerMaxConcurrentStreams: client[kMaxConcurrentStreams]
- })
+exports.inspectOpts = Object.keys(process.env).filter(key => {
+ return /^debug_/i.test(key);
+}).reduce((obj, key) => {
+ // Camel-case
+ const prop = key
+ .substring(6)
+ .toLowerCase()
+ .replace(/_([a-z])/g, (_, k) => {
+ return k.toUpperCase();
+ });
- session[kOpenStreams] = 0
- session[kClient] = client
- session[kSocket] = socket
+ // Coerce string value into JS value
+ let val = process.env[key];
+ if (/^(yes|on|true|enabled)$/i.test(val)) {
+ val = true;
+ } else if (/^(no|off|false|disabled)$/i.test(val)) {
+ val = false;
+ } else if (val === 'null') {
+ val = null;
+ } else {
+ val = Number(val);
+ }
- util.addListener(session, 'error', onHttp2SessionError)
- util.addListener(session, 'frameError', onHttp2FrameError)
- util.addListener(session, 'end', onHttp2SessionEnd)
- util.addListener(session, 'goaway', onHTTP2GoAway)
- util.addListener(session, 'close', function () {
- const { [kClient]: client } = this
- const { [kSocket]: socket } = client
+ obj[prop] = val;
+ return obj;
+}, {});
- const err = this[kSocket][kError] || this[kError] || new SocketError('closed', util.getSocketInfo(socket))
+/**
+ * Is stdout a TTY? Colored output is enabled when `true`.
+ */
- client[kHTTP2Session] = null
+function useColors() {
+ return 'colors' in exports.inspectOpts ?
+ Boolean(exports.inspectOpts.colors) :
+ tty.isatty(process.stderr.fd);
+}
- if (client.destroyed) {
- assert(client[kPending] === 0)
+/**
+ * Adds ANSI color escape codes if enabled.
+ *
+ * @api public
+ */
- // Fail entire queue.
- const requests = client[kQueue].splice(client[kRunningIdx])
- for (let i = 0; i < requests.length; i++) {
- const request = requests[i]
- util.errorRequest(client, request, err)
- }
- }
- })
+function formatArgs(args) {
+ const {namespace: name, useColors} = this;
- session.unref()
+ if (useColors) {
+ const c = this.color;
+ const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c);
+ const prefix = ` ${colorCode};1m${name} \u001B[0m`;
- client[kHTTP2Session] = session
- socket[kHTTP2Session] = session
+ args[0] = prefix + args[0].split('\n').join('\n' + prefix);
+ args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m');
+ } else {
+ args[0] = getDate() + name + ' ' + args[0];
+ }
+}
- util.addListener(socket, 'error', function (err) {
- assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')
+function getDate() {
+ if (exports.inspectOpts.hideDate) {
+ return '';
+ }
+ return new Date().toISOString() + ' ';
+}
- this[kError] = err
+/**
+ * Invokes `util.formatWithOptions()` with the specified arguments and writes to stderr.
+ */
- this[kClient][kOnError](err)
- })
+function log(...args) {
+ return process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...args) + '\n');
+}
- util.addListener(socket, 'end', function () {
- util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this)))
- })
+/**
+ * Save `namespaces`.
+ *
+ * @param {String} namespaces
+ * @api private
+ */
+function save(namespaces) {
+ if (namespaces) {
+ process.env.DEBUG = namespaces;
+ } else {
+ // If you set a process.env field to null or undefined, it gets cast to the
+ // string 'null' or 'undefined'. Just delete instead.
+ delete process.env.DEBUG;
+ }
+}
- util.addListener(socket, 'close', function () {
- const err = this[kError] || new SocketError('closed', util.getSocketInfo(this))
+/**
+ * Load `namespaces`.
+ *
+ * @return {String} returns the previously persisted debug modes
+ * @api private
+ */
- client[kSocket] = null
+function load() {
+ return process.env.DEBUG;
+}
- if (this[kHTTP2Session] != null) {
- this[kHTTP2Session].destroy(err)
- }
+/**
+ * Init logic for `debug` instances.
+ *
+ * Create a new `inspectOpts` object in case `useColors` is set
+ * differently for a particular `debug` instance.
+ */
- client[kPendingIdx] = client[kRunningIdx]
+function init(debug) {
+ debug.inspectOpts = {};
- assert(client[kRunning] === 0)
+ const keys = Object.keys(exports.inspectOpts);
+ for (let i = 0; i < keys.length; i++) {
+ debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
+ }
+}
- client.emit('disconnect', client[kUrl], [client], err)
+module.exports = __nccwpck_require__(897)(exports);
- client[kResume]()
- })
+const {formatters} = module.exports;
- let closed = false
- socket.on('close', () => {
- closed = true
- })
+/**
+ * Map %o to `util.inspect()`, all on a single line.
+ */
- return {
- version: 'h2',
- defaultPipelining: Infinity,
- write (...args) {
- return writeH2(client, ...args)
- },
- resume () {
- resumeH2(client)
- },
- destroy (err, callback) {
- if (closed) {
- queueMicrotask(callback)
- } else {
- // Destroying the socket will trigger the session close
- socket.destroy(err).on('close', callback)
- }
- },
- get destroyed () {
- return socket.destroyed
- },
- busy () {
- return false
- }
- }
-}
+formatters.o = function (v) {
+ this.inspectOpts.colors = this.useColors;
+ return util.inspect(v, this.inspectOpts)
+ .split('\n')
+ .map(str => str.trim())
+ .join(' ');
+};
-function resumeH2 (client) {
- const socket = client[kSocket]
+/**
+ * Map %O to `util.inspect()`, allowing multiple lines if needed.
+ */
- if (socket?.destroyed === false) {
- if (client[kSize] === 0 && client[kMaxConcurrentStreams] === 0) {
- socket.unref()
- client[kHTTP2Session].unref()
- } else {
- socket.ref()
- client[kHTTP2Session].ref()
- }
- }
-}
+formatters.O = function (v) {
+ this.inspectOpts.colors = this.useColors;
+ return util.inspect(v, this.inspectOpts);
+};
-function onHttp2SessionError (err) {
- assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')
- this[kSocket][kError] = err
- this[kClient][kOnError](err)
-}
+/***/ }),
-function onHttp2FrameError (type, code, id) {
- if (id === 0) {
- const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`)
- this[kSocket][kError] = err
- this[kClient][kOnError](err)
- }
-}
+/***/ 1970:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
-function onHttp2SessionEnd () {
- const err = new SocketError('other side closed', util.getSocketInfo(this[kSocket]))
- this.destroy(err)
- util.destroy(this[kSocket], err)
-}
-/**
- * This is the root cause of #3011
- * We need to handle GOAWAY frames properly, and trigger the session close
- * along with the socket right away
- */
-function onHTTP2GoAway (code) {
- // We cannot recover, so best to close the session and the socket
- const err = this[kError] || new SocketError(`HTTP/2: "GOAWAY" frame received with code ${code}`, util.getSocketInfo(this))
- const client = this[kClient]
-
- client[kSocket] = null
- client[kHTTPContext] = null
-
- if (this[kHTTP2Session] != null) {
- this[kHTTP2Session].destroy(err)
- this[kHTTP2Session] = null
- }
-
- util.destroy(this[kSocket], err)
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
+ }
+ Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+ __setModuleDefault(result, mod);
+ return result;
+};
+var __importDefault = (this && this.__importDefault) || function (mod) {
+ return (mod && mod.__esModule) ? mod : { "default": mod };
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.HttpProxyAgent = void 0;
+const net = __importStar(__nccwpck_require__(9278));
+const tls = __importStar(__nccwpck_require__(4756));
+const debug_1 = __importDefault(__nccwpck_require__(2830));
+const events_1 = __nccwpck_require__(4434);
+const agent_base_1 = __nccwpck_require__(8894);
+const url_1 = __nccwpck_require__(7016);
+const debug = (0, debug_1.default)('http-proxy-agent');
+/**
+ * The `HttpProxyAgent` implements an HTTP Agent subclass that connects
+ * to the specified "HTTP proxy server" in order to proxy HTTP requests.
+ */
+class HttpProxyAgent extends agent_base_1.Agent {
+ constructor(proxy, opts) {
+ super(opts);
+ this.proxy = typeof proxy === 'string' ? new url_1.URL(proxy) : proxy;
+ this.proxyHeaders = opts?.headers ?? {};
+ debug('Creating new HttpProxyAgent instance: %o', this.proxy.href);
+ // Trim off the brackets from IPv6 addresses
+ const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, '');
+ const port = this.proxy.port
+ ? parseInt(this.proxy.port, 10)
+ : this.proxy.protocol === 'https:'
+ ? 443
+ : 80;
+ this.connectOpts = {
+ ...(opts ? omit(opts, 'headers') : null),
+ host,
+ port,
+ };
+ }
+ addRequest(req, opts) {
+ req._header = null;
+ this.setRequestProps(req, opts);
+ // @ts-expect-error `addRequest()` isn't defined in `@types/node`
+ super.addRequest(req, opts);
+ }
+ setRequestProps(req, opts) {
+ const { proxy } = this;
+ const protocol = opts.secureEndpoint ? 'https:' : 'http:';
+ const hostname = req.getHeader('host') || 'localhost';
+ const base = `${protocol}//${hostname}`;
+ const url = new url_1.URL(req.path, base);
+ if (opts.port !== 80) {
+ url.port = String(opts.port);
+ }
+ // Change the `http.ClientRequest` instance's "path" field
+ // to the absolute path of the URL that will be requested.
+ req.path = String(url);
+ // Inject the `Proxy-Authorization` header if necessary.
+ const headers = typeof this.proxyHeaders === 'function'
+ ? this.proxyHeaders()
+ : { ...this.proxyHeaders };
+ if (proxy.username || proxy.password) {
+ const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;
+ headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`;
+ }
+ if (!headers['Proxy-Connection']) {
+ headers['Proxy-Connection'] = this.keepAlive
+ ? 'Keep-Alive'
+ : 'close';
+ }
+ for (const name of Object.keys(headers)) {
+ const value = headers[name];
+ if (value) {
+ req.setHeader(name, value);
+ }
+ }
+ }
+ async connect(req, opts) {
+ req._header = null;
+ if (!req.path.includes('://')) {
+ this.setRequestProps(req, opts);
+ }
+ // At this point, the http ClientRequest's internal `_header` field
+ // might have already been set. If this is the case then we'll need
+ // to re-generate the string since we just changed the `req.path`.
+ let first;
+ let endOfHeaders;
+ debug('Regenerating stored HTTP header string for request');
+ req._implicitHeader();
+ if (req.outputData && req.outputData.length > 0) {
+ debug('Patching connection write() output buffer with updated header');
+ first = req.outputData[0].data;
+ endOfHeaders = first.indexOf('\r\n\r\n') + 4;
+ req.outputData[0].data =
+ req._header + first.substring(endOfHeaders);
+ debug('Output buffer: %o', req.outputData[0].data);
+ }
+ // Create a socket connection to the proxy server.
+ let socket;
+ if (this.proxy.protocol === 'https:') {
+ debug('Creating `tls.Socket`: %o', this.connectOpts);
+ socket = tls.connect(this.connectOpts);
+ }
+ else {
+ debug('Creating `net.Socket`: %o', this.connectOpts);
+ socket = net.connect(this.connectOpts);
+ }
+ // Wait for the socket's `connect` event, so that this `callback()`
+ // function throws instead of the `http` request machinery. This is
+ // important for i.e. `PacProxyAgent` which determines a failed proxy
+ // connection via the `callback()` function throwing.
+ await (0, events_1.once)(socket, 'connect');
+ return socket;
+ }
+}
+HttpProxyAgent.protocols = ['http', 'https'];
+exports.HttpProxyAgent = HttpProxyAgent;
+function omit(obj, ...keys) {
+ const ret = {};
+ let key;
+ for (key in obj) {
+ if (!keys.includes(key)) {
+ ret[key] = obj[key];
+ }
+ }
+ return ret;
+}
+//# sourceMappingURL=index.js.map
- // Fail head of pipeline.
- if (client[kRunningIdx] < client[kQueue].length) {
- const request = client[kQueue][client[kRunningIdx]]
- client[kQueue][client[kRunningIdx]++] = null
- util.errorRequest(client, request, err)
- client[kPendingIdx] = client[kRunningIdx]
- }
+/***/ }),
- assert(client[kRunning] === 0)
+/***/ 3669:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
- client.emit('disconnect', client[kUrl], [client], err)
- client[kResume]()
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
+ }
+ Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+ __setModuleDefault(result, mod);
+ return result;
+};
+var __importDefault = (this && this.__importDefault) || function (mod) {
+ return (mod && mod.__esModule) ? mod : { "default": mod };
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.HttpsProxyAgent = void 0;
+const net = __importStar(__nccwpck_require__(9278));
+const tls = __importStar(__nccwpck_require__(4756));
+const assert_1 = __importDefault(__nccwpck_require__(2613));
+const debug_1 = __importDefault(__nccwpck_require__(2830));
+const agent_base_1 = __nccwpck_require__(8894);
+const url_1 = __nccwpck_require__(7016);
+const parse_proxy_response_1 = __nccwpck_require__(7943);
+const debug = (0, debug_1.default)('https-proxy-agent');
+const setServernameFromNonIpHost = (options) => {
+ if (options.servername === undefined &&
+ options.host &&
+ !net.isIP(options.host)) {
+ return {
+ ...options,
+ servername: options.host,
+ };
+ }
+ return options;
+};
+/**
+ * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to
+ * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests.
+ *
+ * Outgoing HTTP requests are first tunneled through the proxy server using the
+ * `CONNECT` HTTP request method to establish a connection to the proxy server,
+ * and then the proxy server connects to the destination target and issues the
+ * HTTP request from the proxy server.
+ *
+ * `https:` requests have their socket connection upgraded to TLS once
+ * the connection to the proxy server has been established.
+ */
+class HttpsProxyAgent extends agent_base_1.Agent {
+ constructor(proxy, opts) {
+ super(opts);
+ this.options = { path: undefined };
+ this.proxy = typeof proxy === 'string' ? new url_1.URL(proxy) : proxy;
+ this.proxyHeaders = opts?.headers ?? {};
+ debug('Creating new HttpsProxyAgent instance: %o', this.proxy.href);
+ // Trim off the brackets from IPv6 addresses
+ const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, '');
+ const port = this.proxy.port
+ ? parseInt(this.proxy.port, 10)
+ : this.proxy.protocol === 'https:'
+ ? 443
+ : 80;
+ this.connectOpts = {
+ // Attempt to negotiate http/1.1 for proxy servers that support http/2
+ ALPNProtocols: ['http/1.1'],
+ ...(opts ? omit(opts, 'headers') : null),
+ host,
+ port,
+ };
+ }
+ /**
+ * Called when the node-core HTTP client library is creating a
+ * new HTTP request.
+ */
+ async connect(req, opts) {
+ const { proxy } = this;
+ if (!opts.host) {
+ throw new TypeError('No "host" provided');
+ }
+ // Create a socket connection to the proxy server.
+ let socket;
+ if (proxy.protocol === 'https:') {
+ debug('Creating `tls.Socket`: %o', this.connectOpts);
+ socket = tls.connect(setServernameFromNonIpHost(this.connectOpts));
+ }
+ else {
+ debug('Creating `net.Socket`: %o', this.connectOpts);
+ socket = net.connect(this.connectOpts);
+ }
+ const headers = typeof this.proxyHeaders === 'function'
+ ? this.proxyHeaders()
+ : { ...this.proxyHeaders };
+ const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host;
+ let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r\n`;
+ // Inject the `Proxy-Authorization` header if necessary.
+ if (proxy.username || proxy.password) {
+ const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;
+ headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`;
+ }
+ headers.Host = `${host}:${opts.port}`;
+ if (!headers['Proxy-Connection']) {
+ headers['Proxy-Connection'] = this.keepAlive
+ ? 'Keep-Alive'
+ : 'close';
+ }
+ for (const name of Object.keys(headers)) {
+ payload += `${name}: ${headers[name]}\r\n`;
+ }
+ const proxyResponsePromise = (0, parse_proxy_response_1.parseProxyResponse)(socket);
+ socket.write(`${payload}\r\n`);
+ const { connect, buffered } = await proxyResponsePromise;
+ req.emit('proxyConnect', connect);
+ this.emit('proxyConnect', connect, req);
+ if (connect.statusCode === 200) {
+ req.once('socket', resume);
+ if (opts.secureEndpoint) {
+ // The proxy is connecting to a TLS server, so upgrade
+ // this socket connection to a TLS connection.
+ debug('Upgrading socket connection to TLS');
+ return tls.connect({
+ ...omit(setServernameFromNonIpHost(opts), 'host', 'path', 'port'),
+ socket,
+ });
+ }
+ return socket;
+ }
+ // Some other status code that's not 200... need to re-play the HTTP
+ // header "data" events onto the socket once the HTTP machinery is
+ // attached so that the node core `http` can parse and handle the
+ // error status code.
+ // Close the original socket, and a new "fake" socket is returned
+ // instead, so that the proxy doesn't get the HTTP request
+ // written to it (which may contain `Authorization` headers or other
+ // sensitive data).
+ //
+ // See: https://hackerone.com/reports/541502
+ socket.destroy();
+ const fakeSocket = new net.Socket({ writable: false });
+ fakeSocket.readable = true;
+ // Need to wait for the "socket" event to re-play the "data" events.
+ req.once('socket', (s) => {
+ debug('Replaying proxy buffer for failed request');
+ (0, assert_1.default)(s.listenerCount('data') > 0);
+ // Replay the "buffered" Buffer onto the fake `socket`, since at
+ // this point the HTTP module machinery has been hooked up for
+ // the user.
+ s.push(buffered);
+ s.push(null);
+ });
+ return fakeSocket;
+ }
}
-
-// https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2
-function shouldSendContentLength (method) {
- return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT'
+HttpsProxyAgent.protocols = ['http', 'https'];
+exports.HttpsProxyAgent = HttpsProxyAgent;
+function resume(socket) {
+ socket.resume();
+}
+function omit(obj, ...keys) {
+ const ret = {};
+ let key;
+ for (key in obj) {
+ if (!keys.includes(key)) {
+ ret[key] = obj[key];
+ }
+ }
+ return ret;
}
+//# sourceMappingURL=index.js.map
-function writeH2 (client, request) {
- const session = client[kHTTP2Session]
- const { method, path, host, upgrade, expectContinue, signal, headers: reqHeaders } = request
- let { body } = request
+/***/ }),
- if (upgrade) {
- util.errorRequest(client, request, new Error('Upgrade not supported for H2'))
- return false
- }
+/***/ 7943:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
- const headers = {}
- for (let n = 0; n < reqHeaders.length; n += 2) {
- const key = reqHeaders[n + 0]
- const val = reqHeaders[n + 1]
- if (Array.isArray(val)) {
- for (let i = 0; i < val.length; i++) {
- if (headers[key]) {
- headers[key] += `,${val[i]}`
- } else {
- headers[key] = val[i]
+var __importDefault = (this && this.__importDefault) || function (mod) {
+ return (mod && mod.__esModule) ? mod : { "default": mod };
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.parseProxyResponse = void 0;
+const debug_1 = __importDefault(__nccwpck_require__(2830));
+const debug = (0, debug_1.default)('https-proxy-agent:parse-proxy-response');
+function parseProxyResponse(socket) {
+ return new Promise((resolve, reject) => {
+ // we need to buffer any HTTP traffic that happens with the proxy before we get
+ // the CONNECT response, so that if the response is anything other than an "200"
+ // response code, then we can re-play the "data" events on the socket once the
+ // HTTP parser is hooked up...
+ let buffersLength = 0;
+ const buffers = [];
+ function read() {
+ const b = socket.read();
+ if (b)
+ ondata(b);
+ else
+ socket.once('readable', read);
}
- }
- } else {
- headers[key] = val
- }
- }
+ function cleanup() {
+ socket.removeListener('end', onend);
+ socket.removeListener('error', onerror);
+ socket.removeListener('readable', read);
+ }
+ function onend() {
+ cleanup();
+ debug('onend');
+ reject(new Error('Proxy connection ended before receiving CONNECT response'));
+ }
+ function onerror(err) {
+ cleanup();
+ debug('onerror %o', err);
+ reject(err);
+ }
+ function ondata(b) {
+ buffers.push(b);
+ buffersLength += b.length;
+ const buffered = Buffer.concat(buffers, buffersLength);
+ const endOfHeaders = buffered.indexOf('\r\n\r\n');
+ if (endOfHeaders === -1) {
+ // keep buffering
+ debug('have not received end of HTTP headers yet...');
+ read();
+ return;
+ }
+ const headerParts = buffered
+ .slice(0, endOfHeaders)
+ .toString('ascii')
+ .split('\r\n');
+ const firstLine = headerParts.shift();
+ if (!firstLine) {
+ socket.destroy();
+ return reject(new Error('No header received from proxy CONNECT response'));
+ }
+ const firstLineParts = firstLine.split(' ');
+ const statusCode = +firstLineParts[1];
+ const statusText = firstLineParts.slice(2).join(' ');
+ const headers = {};
+ for (const header of headerParts) {
+ if (!header)
+ continue;
+ const firstColon = header.indexOf(':');
+ if (firstColon === -1) {
+ socket.destroy();
+ return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`));
+ }
+ const key = header.slice(0, firstColon).toLowerCase();
+ const value = header.slice(firstColon + 1).trimStart();
+ const current = headers[key];
+ if (typeof current === 'string') {
+ headers[key] = [current, value];
+ }
+ else if (Array.isArray(current)) {
+ current.push(value);
+ }
+ else {
+ headers[key] = value;
+ }
+ }
+ debug('got proxy server response: %o %o', firstLine, headers);
+ cleanup();
+ resolve({
+ connect: {
+ statusCode,
+ statusText,
+ headers,
+ },
+ buffered,
+ });
+ }
+ socket.on('error', onerror);
+ socket.on('end', onend);
+ read();
+ });
+}
+exports.parseProxyResponse = parseProxyResponse;
+//# sourceMappingURL=parse-proxy-response.js.map
- /** @type {import('node:http2').ClientHttp2Stream} */
- let stream
+/***/ }),
- const { hostname, port } = client[kUrl]
+/***/ 3772:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ''}`
- headers[HTTP2_HEADER_METHOD] = method
+module.exports = minimatch
+minimatch.Minimatch = Minimatch
- const abort = (err) => {
- if (request.aborted || request.completed) {
- return
- }
+var path = (function () { try { return __nccwpck_require__(6928) } catch (e) {}}()) || {
+ sep: '/'
+}
+minimatch.sep = path.sep
- err = err || new RequestAbortedError()
+var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {}
+var expand = __nccwpck_require__(4691)
- util.errorRequest(client, request, err)
+var plTypes = {
+ '!': { open: '(?:(?!(?:', close: '))[^/]*?)'},
+ '?': { open: '(?:', close: ')?' },
+ '+': { open: '(?:', close: ')+' },
+ '*': { open: '(?:', close: ')*' },
+ '@': { open: '(?:', close: ')' }
+}
- if (stream != null) {
- util.destroy(stream, err)
- }
+// any single thing other than /
+// don't need to escape / when using new RegExp()
+var qmark = '[^/]'
- // We do not destroy the socket as we can continue using the session
- // the stream get's destroyed and the session remains to create new streams
- util.destroy(body, err)
- client[kQueue][client[kRunningIdx]++] = null
- client[kResume]()
- }
+// * => any number of characters
+var star = qmark + '*?'
- try {
- // We are already connected, streams are pending.
- // We can call on connect, and wait for abort
- request.onConnect(abort)
- } catch (err) {
- util.errorRequest(client, request, err)
- }
+// ** when dots are allowed. Anything goes, except .. and .
+// not (^ or / followed by one or two dots followed by $ or /),
+// followed by anything, any number of times.
+var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'
- if (request.aborted) {
- return false
- }
+// not a ^ or / followed by a dot,
+// followed by anything, any number of times.
+var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'
- if (method === 'CONNECT') {
- session.ref()
- // We are already connected, streams are pending, first request
- // will create a new stream. We trigger a request to create the stream and wait until
- // `ready` event is triggered
- // We disabled endStream to allow the user to write to the stream
- stream = session.request(headers, { endStream: false, signal })
+// characters that need to be escaped in RegExp.
+var reSpecials = charSet('().*{}+?[]^$\\!')
- if (stream.id && !stream.pending) {
- request.onUpgrade(null, null, stream)
- ++session[kOpenStreams]
- client[kQueue][client[kRunningIdx]++] = null
- } else {
- stream.once('ready', () => {
- request.onUpgrade(null, null, stream)
- ++session[kOpenStreams]
- client[kQueue][client[kRunningIdx]++] = null
- })
- }
+// "abc" -> { a:true, b:true, c:true }
+function charSet (s) {
+ return s.split('').reduce(function (set, c) {
+ set[c] = true
+ return set
+ }, {})
+}
- stream.once('close', () => {
- session[kOpenStreams] -= 1
- if (session[kOpenStreams] === 0) session.unref()
- })
+// normalizes slashes.
+var slashSplit = /\/+/
- return true
+minimatch.filter = filter
+function filter (pattern, options) {
+ options = options || {}
+ return function (p, i, list) {
+ return minimatch(p, pattern, options)
}
+}
- // https://tools.ietf.org/html/rfc7540#section-8.3
- // :path and :scheme headers must be omitted when sending CONNECT
-
- headers[HTTP2_HEADER_PATH] = path
- headers[HTTP2_HEADER_SCHEME] = 'https'
+function ext (a, b) {
+ b = b || {}
+ var t = {}
+ Object.keys(a).forEach(function (k) {
+ t[k] = a[k]
+ })
+ Object.keys(b).forEach(function (k) {
+ t[k] = b[k]
+ })
+ return t
+}
- // https://tools.ietf.org/html/rfc7231#section-4.3.1
- // https://tools.ietf.org/html/rfc7231#section-4.3.2
- // https://tools.ietf.org/html/rfc7231#section-4.3.5
+minimatch.defaults = function (def) {
+ if (!def || typeof def !== 'object' || !Object.keys(def).length) {
+ return minimatch
+ }
- // Sending a payload body on a request that does not
- // expect it can cause undefined behavior on some
- // servers and corrupt connection state. Do not
- // re-use the connection for further requests.
+ var orig = minimatch
- const expectsPayload = (
- method === 'PUT' ||
- method === 'POST' ||
- method === 'PATCH'
- )
+ var m = function minimatch (p, pattern, options) {
+ return orig(p, pattern, ext(def, options))
+ }
- if (body && typeof body.read === 'function') {
- // Try to read EOF in order to get length.
- body.read(0)
+ m.Minimatch = function Minimatch (pattern, options) {
+ return new orig.Minimatch(pattern, ext(def, options))
+ }
+ m.Minimatch.defaults = function defaults (options) {
+ return orig.defaults(ext(def, options)).Minimatch
}
- let contentLength = util.bodyLength(body)
+ m.filter = function filter (pattern, options) {
+ return orig.filter(pattern, ext(def, options))
+ }
- if (util.isFormDataLike(body)) {
- extractBody ??= (__nccwpck_require__(3278).extractBody)
+ m.defaults = function defaults (options) {
+ return orig.defaults(ext(def, options))
+ }
- const [bodyStream, contentType] = extractBody(body)
- headers['content-type'] = contentType
+ m.makeRe = function makeRe (pattern, options) {
+ return orig.makeRe(pattern, ext(def, options))
+ }
- body = bodyStream.stream
- contentLength = bodyStream.length
+ m.braceExpand = function braceExpand (pattern, options) {
+ return orig.braceExpand(pattern, ext(def, options))
}
- if (contentLength == null) {
- contentLength = request.contentLength
+ m.match = function (list, pattern, options) {
+ return orig.match(list, pattern, ext(def, options))
}
- if (contentLength === 0 || !expectsPayload) {
- // https://tools.ietf.org/html/rfc7230#section-3.3.2
- // A user agent SHOULD NOT send a Content-Length header field when
- // the request message does not contain a payload body and the method
- // semantics do not anticipate such a body.
+ return m
+}
- contentLength = null
- }
+Minimatch.defaults = function (def) {
+ return minimatch.defaults(def).Minimatch
+}
- // https://github.com/nodejs/undici/issues/2046
- // A user agent may send a Content-Length header with 0 value, this should be allowed.
- if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength != null && request.contentLength !== contentLength) {
- if (client[kStrictContentLength]) {
- util.errorRequest(client, request, new RequestContentLengthMismatchError())
- return false
- }
+function minimatch (p, pattern, options) {
+ assertValidPattern(pattern)
- process.emitWarning(new RequestContentLengthMismatchError())
- }
+ if (!options) options = {}
- if (contentLength != null) {
- assert(body, 'no body must not have content length')
- headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}`
+ // shortcut: comments match nothing.
+ if (!options.nocomment && pattern.charAt(0) === '#') {
+ return false
}
- session.ref()
-
- const shouldEndStream = method === 'GET' || method === 'HEAD' || body === null
- if (expectContinue) {
- headers[HTTP2_HEADER_EXPECT] = '100-continue'
- stream = session.request(headers, { endStream: shouldEndStream, signal })
+ return new Minimatch(pattern, options).match(p)
+}
- stream.once('continue', writeBodyH2)
- } else {
- stream = session.request(headers, {
- endStream: shouldEndStream,
- signal
- })
- writeBodyH2()
+function Minimatch (pattern, options) {
+ if (!(this instanceof Minimatch)) {
+ return new Minimatch(pattern, options)
}
- // Increment counter as we have new streams open
- ++session[kOpenStreams]
+ assertValidPattern(pattern)
- stream.once('response', headers => {
- const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers
- request.onResponseStarted()
+ if (!options) options = {}
- // Due to the stream nature, it is possible we face a race condition
- // where the stream has been assigned, but the request has been aborted
- // the request remains in-flight and headers hasn't been received yet
- // for those scenarios, best effort is to destroy the stream immediately
- // as there's no value to keep it open.
- if (request.aborted) {
- const err = new RequestAbortedError()
- util.errorRequest(client, request, err)
- util.destroy(stream, err)
- return
- }
+ pattern = pattern.trim()
- if (request.onHeaders(Number(statusCode), parseH2Headers(realHeaders), stream.resume.bind(stream), '') === false) {
- stream.pause()
- }
+ // windows support: need to use /, not \
+ if (!options.allowWindowsEscape && path.sep !== '/') {
+ pattern = pattern.split(path.sep).join('/')
+ }
- stream.on('data', (chunk) => {
- if (request.onData(chunk) === false) {
- stream.pause()
- }
- })
- })
+ this.options = options
+ this.set = []
+ this.pattern = pattern
+ this.regexp = null
+ this.negate = false
+ this.comment = false
+ this.empty = false
+ this.partial = !!options.partial
- stream.once('end', () => {
- // When state is null, it means we haven't consumed body and the stream still do not have
- // a state.
- // Present specially when using pipeline or stream
- if (stream.state?.state == null || stream.state.state < 6) {
- request.onComplete([])
- }
+ // make the set of regexps etc.
+ this.make()
+}
- if (session[kOpenStreams] === 0) {
- // Stream is closed or half-closed-remote (6), decrement counter and cleanup
- // It does not have sense to continue working with the stream as we do not
- // have yet RST_STREAM support on client-side
+Minimatch.prototype.debug = function () {}
- session.unref()
- }
+Minimatch.prototype.make = make
+function make () {
+ var pattern = this.pattern
+ var options = this.options
- abort(new InformationalError('HTTP/2: stream half-closed (remote)'))
- client[kQueue][client[kRunningIdx]++] = null
- client[kPendingIdx] = client[kRunningIdx]
- client[kResume]()
- })
+ // empty patterns and comments match nothing.
+ if (!options.nocomment && pattern.charAt(0) === '#') {
+ this.comment = true
+ return
+ }
+ if (!pattern) {
+ this.empty = true
+ return
+ }
- stream.once('close', () => {
- session[kOpenStreams] -= 1
- if (session[kOpenStreams] === 0) {
- session.unref()
- }
- })
+ // step 1: figure out negation, etc.
+ this.parseNegate()
- stream.once('error', function (err) {
- abort(err)
- })
+ // step 2: expand braces
+ var set = this.globSet = this.braceExpand()
- stream.once('frameError', (type, code) => {
- abort(new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`))
+ if (options.debug) this.debug = function debug() { console.error.apply(console, arguments) }
+
+ this.debug(this.pattern, set)
+
+ // step 3: now we have a set, so turn each one into a series of path-portion
+ // matching patterns.
+ // These will be regexps, except in the case of "**", which is
+ // set to the GLOBSTAR object for globstar behavior,
+ // and will not contain any / characters
+ set = this.globParts = set.map(function (s) {
+ return s.split(slashSplit)
})
- // stream.on('aborted', () => {
- // // TODO(HTTP/2): Support aborted
- // })
+ this.debug(this.pattern, set)
- // stream.on('timeout', () => {
- // // TODO(HTTP/2): Support timeout
- // })
+ // glob --> regexps
+ set = set.map(function (s, si, set) {
+ return s.map(this.parse, this)
+ }, this)
- // stream.on('push', headers => {
- // // TODO(HTTP/2): Support push
- // })
+ this.debug(this.pattern, set)
- // stream.on('trailers', headers => {
- // // TODO(HTTP/2): Support trailers
- // })
+ // filter out everything that didn't compile properly.
+ set = set.filter(function (s) {
+ return s.indexOf(false) === -1
+ })
- return true
+ this.debug(this.pattern, set)
- function writeBodyH2 () {
- /* istanbul ignore else: assertion */
- if (!body || contentLength === 0) {
- writeBuffer(
- abort,
- stream,
- null,
- client,
- request,
- client[kSocket],
- contentLength,
- expectsPayload
- )
- } else if (util.isBuffer(body)) {
- writeBuffer(
- abort,
- stream,
- body,
- client,
- request,
- client[kSocket],
- contentLength,
- expectsPayload
- )
- } else if (util.isBlobLike(body)) {
- if (typeof body.stream === 'function') {
- writeIterable(
- abort,
- stream,
- body.stream(),
- client,
- request,
- client[kSocket],
- contentLength,
- expectsPayload
- )
- } else {
- writeBlob(
- abort,
- stream,
- body,
- client,
- request,
- client[kSocket],
- contentLength,
- expectsPayload
- )
- }
- } else if (util.isStream(body)) {
- writeStream(
- abort,
- client[kSocket],
- expectsPayload,
- stream,
- body,
- client,
- request,
- contentLength
- )
- } else if (util.isIterable(body)) {
- writeIterable(
- abort,
- stream,
- body,
- client,
- request,
- client[kSocket],
- contentLength,
- expectsPayload
- )
- } else {
- assert(false)
- }
- }
+ this.set = set
}
-function writeBuffer (abort, h2stream, body, client, request, socket, contentLength, expectsPayload) {
- try {
- if (body != null && util.isBuffer(body)) {
- assert(contentLength === body.byteLength, 'buffer body must have content length')
- h2stream.cork()
- h2stream.write(body)
- h2stream.uncork()
- h2stream.end()
-
- request.onBodySent(body)
- }
+Minimatch.prototype.parseNegate = parseNegate
+function parseNegate () {
+ var pattern = this.pattern
+ var negate = false
+ var options = this.options
+ var negateOffset = 0
- if (!expectsPayload) {
- socket[kReset] = true
- }
+ if (options.nonegate) return
- request.onRequestSent()
- client[kResume]()
- } catch (error) {
- abort(error)
+ for (var i = 0, l = pattern.length
+ ; i < l && pattern.charAt(i) === '!'
+ ; i++) {
+ negate = !negate
+ negateOffset++
}
-}
-function writeStream (abort, socket, expectsPayload, h2stream, body, client, request, contentLength) {
- assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined')
+ if (negateOffset) this.pattern = pattern.substr(negateOffset)
+ this.negate = negate
+}
- // For HTTP/2, is enough to pipe the stream
- const pipe = pipeline(
- body,
- h2stream,
- (err) => {
- if (err) {
- util.destroy(pipe, err)
- abort(err)
- } else {
- util.removeAllListeners(pipe)
- request.onRequestSent()
+// Brace expansion:
+// a{b,c}d -> abd acd
+// a{b,}c -> abc ac
+// a{0..3}d -> a0d a1d a2d a3d
+// a{b,c{d,e}f}g -> abg acdfg acefg
+// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
+//
+// Invalid sets are not expanded.
+// a{2..}b -> a{2..}b
+// a{b}c -> a{b}c
+minimatch.braceExpand = function (pattern, options) {
+ return braceExpand(pattern, options)
+}
- if (!expectsPayload) {
- socket[kReset] = true
- }
+Minimatch.prototype.braceExpand = braceExpand
- client[kResume]()
- }
+function braceExpand (pattern, options) {
+ if (!options) {
+ if (this instanceof Minimatch) {
+ options = this.options
+ } else {
+ options = {}
}
- )
-
- util.addListener(pipe, 'data', onPipeData)
-
- function onPipeData (chunk) {
- request.onBodySent(chunk)
}
-}
-async function writeBlob (abort, h2stream, body, client, request, socket, contentLength, expectsPayload) {
- assert(contentLength === body.size, 'blob body must have content length')
-
- try {
- if (contentLength != null && contentLength !== body.size) {
- throw new RequestContentLengthMismatchError()
- }
+ pattern = typeof pattern === 'undefined'
+ ? this.pattern : pattern
- const buffer = Buffer.from(await body.arrayBuffer())
+ assertValidPattern(pattern)
- h2stream.cork()
- h2stream.write(buffer)
- h2stream.uncork()
- h2stream.end()
+ // Thanks to Yeting Li for
+ // improving this regexp to avoid a ReDOS vulnerability.
+ if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
+ // shortcut. no need to expand.
+ return [pattern]
+ }
- request.onBodySent(buffer)
- request.onRequestSent()
+ return expand(pattern)
+}
- if (!expectsPayload) {
- socket[kReset] = true
- }
+var MAX_PATTERN_LENGTH = 1024 * 64
+var assertValidPattern = function (pattern) {
+ if (typeof pattern !== 'string') {
+ throw new TypeError('invalid pattern')
+ }
- client[kResume]()
- } catch (err) {
- abort(err)
+ if (pattern.length > MAX_PATTERN_LENGTH) {
+ throw new TypeError('pattern is too long')
}
}
-async function writeIterable (abort, h2stream, body, client, request, socket, contentLength, expectsPayload) {
- assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined')
+// parse a component of the expanded set.
+// At this point, no pattern may contain "/" in it
+// so we're going to return a 2d array, where each entry is the full
+// pattern, split on '/', and then turned into a regular expression.
+// A regexp is made at the end which joins each array with an
+// escaped /, and another full one which joins each regexp with |.
+//
+// Following the lead of Bash 4.1, note that "**" only has special meaning
+// when it is the *only* thing in a path portion. Otherwise, any series
+// of * is equivalent to a single *. Globstar behavior is enabled by
+// default, and can be disabled by setting options.noglobstar.
+Minimatch.prototype.parse = parse
+var SUBPARSE = {}
+function parse (pattern, isSub) {
+ assertValidPattern(pattern)
- let callback = null
- function onDrain () {
- if (callback) {
- const cb = callback
- callback = null
- cb()
- }
+ var options = this.options
+
+ // shortcuts
+ if (pattern === '**') {
+ if (!options.noglobstar)
+ return GLOBSTAR
+ else
+ pattern = '*'
}
+ if (pattern === '') return ''
- const waitForDrain = () => new Promise((resolve, reject) => {
- assert(callback === null)
+ var re = ''
+ var hasMagic = !!options.nocase
+ var escaping = false
+ // ? => one single character
+ var patternListStack = []
+ var negativeLists = []
+ var stateChar
+ var inClass = false
+ var reClassStart = -1
+ var classStart = -1
+ // . and .. never match anything that doesn't start with .,
+ // even when options.dot is set.
+ var patternStart = pattern.charAt(0) === '.' ? '' // anything
+ // not (start or / followed by . or .. followed by / or end)
+ : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))'
+ : '(?!\\.)'
+ var self = this
- if (socket[kError]) {
- reject(socket[kError])
- } else {
- callback = resolve
+ function clearStateChar () {
+ if (stateChar) {
+ // we had some state-tracking character
+ // that wasn't consumed by this pass.
+ switch (stateChar) {
+ case '*':
+ re += star
+ hasMagic = true
+ break
+ case '?':
+ re += qmark
+ hasMagic = true
+ break
+ default:
+ re += '\\' + stateChar
+ break
+ }
+ self.debug('clearStateChar %j %j', stateChar, re)
+ stateChar = false
}
- })
+ }
- h2stream
- .on('close', onDrain)
- .on('drain', onDrain)
+ for (var i = 0, len = pattern.length, c
+ ; (i < len) && (c = pattern.charAt(i))
+ ; i++) {
+ this.debug('%s\t%s %s %j', pattern, i, re, c)
- try {
- // It's up to the user to somehow abort the async iterable.
- for await (const chunk of body) {
- if (socket[kError]) {
- throw socket[kError]
- }
+ // skip over any that are escaped.
+ if (escaping && reSpecials[c]) {
+ re += '\\' + c
+ escaping = false
+ continue
+ }
- const res = h2stream.write(chunk)
- request.onBodySent(chunk)
- if (!res) {
- await waitForDrain()
+ switch (c) {
+ /* istanbul ignore next */
+ case '/': {
+ // completely not allowed, even escaped.
+ // Should already be path-split by now.
+ return false
}
- }
- h2stream.end()
+ case '\\':
+ clearStateChar()
+ escaping = true
+ continue
- request.onRequestSent()
+ // the various stateChar values
+ // for the "extglob" stuff.
+ case '?':
+ case '*':
+ case '+':
+ case '@':
+ case '!':
+ this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c)
- if (!expectsPayload) {
- socket[kReset] = true
- }
+ // all of those are literals inside a class, except that
+ // the glob [!a] means [^a] in regexp
+ if (inClass) {
+ this.debug(' in class')
+ if (c === '!' && i === classStart + 1) c = '^'
+ re += c
+ continue
+ }
- client[kResume]()
- } catch (err) {
- abort(err)
- } finally {
- h2stream
- .off('close', onDrain)
- .off('drain', onDrain)
- }
-}
+ // if we already have a stateChar, then it means
+ // that there was something like ** or +? in there.
+ // Handle the stateChar, then proceed with this one.
+ self.debug('call clearStateChar %j', stateChar)
+ clearStateChar()
+ stateChar = c
+ // if extglob is disabled, then +(asdf|foo) isn't a thing.
+ // just clear the statechar *now*, rather than even diving into
+ // the patternList stuff.
+ if (options.noext) clearStateChar()
+ continue
-module.exports = connectH2
+ case '(':
+ if (inClass) {
+ re += '('
+ continue
+ }
+ if (!stateChar) {
+ re += '\\('
+ continue
+ }
-/***/ }),
+ patternListStack.push({
+ type: stateChar,
+ start: i - 1,
+ reStart: re.length,
+ open: plTypes[stateChar].open,
+ close: plTypes[stateChar].close
+ })
+ // negation is (?:(?!js)[^/]*)
+ re += stateChar === '!' ? '(?:(?!(?:' : '(?:'
+ this.debug('plType %j %j', stateChar, re)
+ stateChar = false
+ continue
-/***/ 2138:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ case ')':
+ if (inClass || !patternListStack.length) {
+ re += '\\)'
+ continue
+ }
-// @ts-check
+ clearStateChar()
+ hasMagic = true
+ var pl = patternListStack.pop()
+ // negation is (?:(?!js)[^/]*)
+ // The others are (?:)
+ re += pl.close
+ if (pl.type === '!') {
+ negativeLists.push(pl)
+ }
+ pl.reEnd = re.length
+ continue
+ case '|':
+ if (inClass || !patternListStack.length || escaping) {
+ re += '\\|'
+ escaping = false
+ continue
+ }
+ clearStateChar()
+ re += '|'
+ continue
-const assert = __nccwpck_require__(4589)
-const net = __nccwpck_require__(7030)
-const http = __nccwpck_require__(7067)
-const util = __nccwpck_require__(7375)
-const { channels } = __nccwpck_require__(4567)
-const Request = __nccwpck_require__(6265)
-const DispatcherBase = __nccwpck_require__(2540)
-const {
- InvalidArgumentError,
- InformationalError,
- ClientDestroyedError
-} = __nccwpck_require__(2344)
-const buildConnector = __nccwpck_require__(5005)
-const {
- kUrl,
- kServerName,
- kClient,
- kBusy,
- kConnect,
- kResuming,
- kRunning,
- kPending,
- kSize,
- kQueue,
- kConnected,
- kConnecting,
- kNeedDrain,
- kKeepAliveDefaultTimeout,
- kHostHeader,
- kPendingIdx,
- kRunningIdx,
- kError,
- kPipelining,
- kKeepAliveTimeoutValue,
- kMaxHeadersSize,
- kKeepAliveMaxTimeout,
- kKeepAliveTimeoutThreshold,
- kHeadersTimeout,
- kBodyTimeout,
- kStrictContentLength,
- kConnector,
- kMaxRedirections,
- kMaxRequests,
- kCounter,
- kClose,
- kDestroy,
- kDispatch,
- kInterceptors,
- kLocalAddress,
- kMaxResponseSize,
- kOnError,
- kHTTPContext,
- kMaxConcurrentStreams,
- kResume
-} = __nccwpck_require__(6130)
-const connectH1 = __nccwpck_require__(5580)
-const connectH2 = __nccwpck_require__(3045)
-let deprecatedInterceptorWarned = false
+ // these are mostly the same in regexp and glob
+ case '[':
+ // swallow any state-tracking char before the [
+ clearStateChar()
-const kClosedResolve = Symbol('kClosedResolve')
+ if (inClass) {
+ re += '\\' + c
+ continue
+ }
-const noop = () => {}
+ inClass = true
+ classStart = i
+ reClassStart = re.length
+ re += c
+ continue
-function getPipelining (client) {
- return client[kPipelining] ?? client[kHTTPContext]?.defaultPipelining ?? 1
-}
+ case ']':
+ // a right bracket shall lose its special
+ // meaning and represent itself in
+ // a bracket expression if it occurs
+ // first in the list. -- POSIX.2 2.8.3.2
+ if (i === classStart + 1 || !inClass) {
+ re += '\\' + c
+ escaping = false
+ continue
+ }
-/**
- * @type {import('../../types/client.js').default}
- */
-class Client extends DispatcherBase {
- /**
- *
- * @param {string|URL} url
- * @param {import('../../types/client.js').Client.Options} options
- */
- constructor (url, {
- interceptors,
- maxHeaderSize,
- headersTimeout,
- socketTimeout,
- requestTimeout,
- connectTimeout,
- bodyTimeout,
- idleTimeout,
- keepAlive,
- keepAliveTimeout,
- maxKeepAliveTimeout,
- keepAliveMaxTimeout,
- keepAliveTimeoutThreshold,
- socketPath,
- pipelining,
- tls,
- strictContentLength,
- maxCachedSessions,
- maxRedirections,
- connect,
- maxRequestsPerClient,
- localAddress,
- maxResponseSize,
- autoSelectFamily,
- autoSelectFamilyAttemptTimeout,
- // h2
- maxConcurrentStreams,
- allowH2
- } = {}) {
- super()
+ // handle the case where we left a class open.
+ // "[z-a]" is valid, equivalent to "\[z-a\]"
+ // split where the last [ was, make sure we don't have
+ // an invalid re. if so, re-walk the contents of the
+ // would-be class to re-translate any characters that
+ // were passed through as-is
+ // TODO: It would probably be faster to determine this
+ // without a try/catch and a new RegExp, but it's tricky
+ // to do safely. For now, this is safe and works.
+ var cs = pattern.substring(classStart + 1, i)
+ try {
+ RegExp('[' + cs + ']')
+ } catch (er) {
+ // not a valid class!
+ var sp = this.parse(cs, SUBPARSE)
+ re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]'
+ hasMagic = hasMagic || sp[1]
+ inClass = false
+ continue
+ }
- if (keepAlive !== undefined) {
- throw new InvalidArgumentError('unsupported keepAlive, use pipelining=0 instead')
- }
+ // finish up the class.
+ hasMagic = true
+ inClass = false
+ re += c
+ continue
- if (socketTimeout !== undefined) {
- throw new InvalidArgumentError('unsupported socketTimeout, use headersTimeout & bodyTimeout instead')
- }
+ default:
+ // swallow any state char that wasn't consumed
+ clearStateChar()
- if (requestTimeout !== undefined) {
- throw new InvalidArgumentError('unsupported requestTimeout, use headersTimeout & bodyTimeout instead')
- }
+ if (escaping) {
+ // no need
+ escaping = false
+ } else if (reSpecials[c]
+ && !(c === '^' && inClass)) {
+ re += '\\'
+ }
- if (idleTimeout !== undefined) {
- throw new InvalidArgumentError('unsupported idleTimeout, use keepAliveTimeout instead')
- }
+ re += c
- if (maxKeepAliveTimeout !== undefined) {
- throw new InvalidArgumentError('unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead')
- }
+ } // switch
+ } // for
- if (maxHeaderSize != null && !Number.isFinite(maxHeaderSize)) {
- throw new InvalidArgumentError('invalid maxHeaderSize')
- }
+ // handle the case where we left a class open.
+ // "[abc" is valid, equivalent to "\[abc"
+ if (inClass) {
+ // split where the last [ was, and escape it
+ // this is a huge pita. We now have to re-walk
+ // the contents of the would-be class to re-translate
+ // any characters that were passed through as-is
+ cs = pattern.substr(classStart + 1)
+ sp = this.parse(cs, SUBPARSE)
+ re = re.substr(0, reClassStart) + '\\[' + sp[0]
+ hasMagic = hasMagic || sp[1]
+ }
- if (socketPath != null && typeof socketPath !== 'string') {
- throw new InvalidArgumentError('invalid socketPath')
- }
+ // handle the case where we had a +( thing at the *end*
+ // of the pattern.
+ // each pattern list stack adds 3 chars, and we need to go through
+ // and escape any | chars that were passed through as-is for the regexp.
+ // Go through and escape them, taking care not to double-escape any
+ // | chars that were already escaped.
+ for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
+ var tail = re.slice(pl.reStart + pl.open.length)
+ this.debug('setting tail', re, pl)
+ // maybe some even number of \, then maybe 1 \, followed by a |
+ tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) {
+ if (!$2) {
+ // the | isn't already escaped, so escape it.
+ $2 = '\\'
+ }
- if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) {
- throw new InvalidArgumentError('invalid connectTimeout')
- }
+ // need to escape all those slashes *again*, without escaping the
+ // one that we need for escaping the | character. As it works out,
+ // escaping an even number of slashes can be done by simply repeating
+ // it exactly after itself. That's why this trick works.
+ //
+ // I am sorry that you have to see this.
+ return $1 + $1 + $2 + '|'
+ })
- if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) {
- throw new InvalidArgumentError('invalid keepAliveTimeout')
- }
+ this.debug('tail=%j\n %s', tail, tail, pl, re)
+ var t = pl.type === '*' ? star
+ : pl.type === '?' ? qmark
+ : '\\' + pl.type
- if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) {
- throw new InvalidArgumentError('invalid keepAliveMaxTimeout')
- }
+ hasMagic = true
+ re = re.slice(0, pl.reStart) + t + '\\(' + tail
+ }
- if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) {
- throw new InvalidArgumentError('invalid keepAliveTimeoutThreshold')
- }
+ // handle trailing things that only matter at the very end.
+ clearStateChar()
+ if (escaping) {
+ // trailing \\
+ re += '\\\\'
+ }
- if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) {
- throw new InvalidArgumentError('headersTimeout must be a positive integer or zero')
- }
+ // only need to apply the nodot start if the re starts with
+ // something that could conceivably capture a dot
+ var addPatternStart = false
+ switch (re.charAt(0)) {
+ case '[': case '.': case '(': addPatternStart = true
+ }
- if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) {
- throw new InvalidArgumentError('bodyTimeout must be a positive integer or zero')
- }
+ // Hack to work around lack of negative lookbehind in JS
+ // A pattern like: *.!(x).!(y|z) needs to ensure that a name
+ // like 'a.xyz.yz' doesn't match. So, the first negative
+ // lookahead, has to look ALL the way ahead, to the end of
+ // the pattern.
+ for (var n = negativeLists.length - 1; n > -1; n--) {
+ var nl = negativeLists[n]
- if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {
- throw new InvalidArgumentError('connect must be a function or an object')
- }
+ var nlBefore = re.slice(0, nl.reStart)
+ var nlFirst = re.slice(nl.reStart, nl.reEnd - 8)
+ var nlLast = re.slice(nl.reEnd - 8, nl.reEnd)
+ var nlAfter = re.slice(nl.reEnd)
- if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {
- throw new InvalidArgumentError('maxRedirections must be a positive number')
- }
+ nlLast += nlAfter
- if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) {
- throw new InvalidArgumentError('maxRequestsPerClient must be a positive number')
+ // Handle nested stuff like *(*.js|!(*.json)), where open parens
+ // mean that we should *not* include the ) in the bit that is considered
+ // "after" the negated section.
+ var openParensBefore = nlBefore.split('(').length - 1
+ var cleanAfter = nlAfter
+ for (i = 0; i < openParensBefore; i++) {
+ cleanAfter = cleanAfter.replace(/\)[+*?]?/, '')
}
+ nlAfter = cleanAfter
- if (localAddress != null && (typeof localAddress !== 'string' || net.isIP(localAddress) === 0)) {
- throw new InvalidArgumentError('localAddress must be valid string IP address')
+ var dollar = ''
+ if (nlAfter === '' && isSub !== SUBPARSE) {
+ dollar = '$'
}
+ var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast
+ re = newRe
+ }
- if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) {
- throw new InvalidArgumentError('maxResponseSize must be a positive number')
- }
+ // if the re is not "" at this point, then we need to make sure
+ // it doesn't match against an empty path part.
+ // Otherwise a/* will match a/, which it should not.
+ if (re !== '' && hasMagic) {
+ re = '(?=.)' + re
+ }
- if (
- autoSelectFamilyAttemptTimeout != null &&
- (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1)
- ) {
- throw new InvalidArgumentError('autoSelectFamilyAttemptTimeout must be a positive number')
- }
+ if (addPatternStart) {
+ re = patternStart + re
+ }
- // h2
- if (allowH2 != null && typeof allowH2 !== 'boolean') {
- throw new InvalidArgumentError('allowH2 must be a valid boolean value')
- }
+ // parsing just a piece of a larger pattern.
+ if (isSub === SUBPARSE) {
+ return [re, hasMagic]
+ }
- if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== 'number' || maxConcurrentStreams < 1)) {
- throw new InvalidArgumentError('maxConcurrentStreams must be a positive integer, greater than 0')
- }
+ // skip the regexp for non-magical patterns
+ // unescape anything in it, though, so that it'll be
+ // an exact match against a file etc.
+ if (!hasMagic) {
+ return globUnescape(pattern)
+ }
- if (typeof connect !== 'function') {
- connect = buildConnector({
- ...tls,
- maxCachedSessions,
- allowH2,
- socketPath,
- timeout: connectTimeout,
- ...(autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined),
- ...connect
- })
- }
-
- if (interceptors?.Client && Array.isArray(interceptors.Client)) {
- this[kInterceptors] = interceptors.Client
- if (!deprecatedInterceptorWarned) {
- deprecatedInterceptorWarned = true
- process.emitWarning('Client.Options#interceptor is deprecated. Use Dispatcher#compose instead.', {
- code: 'UNDICI-CLIENT-INTERCEPTOR-DEPRECATED'
- })
- }
- } else {
- this[kInterceptors] = [createRedirectInterceptor({ maxRedirections })]
- }
-
- this[kUrl] = util.parseOrigin(url)
- this[kConnector] = connect
- this[kPipelining] = pipelining != null ? pipelining : 1
- this[kMaxHeadersSize] = maxHeaderSize || http.maxHeaderSize
- this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout
- this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 600e3 : keepAliveMaxTimeout
- this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 2e3 : keepAliveTimeoutThreshold
- this[kKeepAliveTimeoutValue] = this[kKeepAliveDefaultTimeout]
- this[kServerName] = null
- this[kLocalAddress] = localAddress != null ? localAddress : null
- this[kResuming] = 0 // 0, idle, 1, scheduled, 2 resuming
- this[kNeedDrain] = 0 // 0, idle, 1, scheduled, 2 resuming
- this[kHostHeader] = `host: ${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}\r\n`
- this[kBodyTimeout] = bodyTimeout != null ? bodyTimeout : 300e3
- this[kHeadersTimeout] = headersTimeout != null ? headersTimeout : 300e3
- this[kStrictContentLength] = strictContentLength == null ? true : strictContentLength
- this[kMaxRedirections] = maxRedirections
- this[kMaxRequests] = maxRequestsPerClient
- this[kClosedResolve] = null
- this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1
- this[kMaxConcurrentStreams] = maxConcurrentStreams != null ? maxConcurrentStreams : 100 // Max peerConcurrentStreams for a Node h2 server
- this[kHTTPContext] = null
-
- // kQueue is built up of 3 sections separated by
- // the kRunningIdx and kPendingIdx indices.
- // | complete | running | pending |
- // ^ kRunningIdx ^ kPendingIdx ^ kQueue.length
- // kRunningIdx points to the first running element.
- // kPendingIdx points to the first pending element.
- // This implements a fast queue with an amortized
- // time of O(1).
-
- this[kQueue] = []
- this[kRunningIdx] = 0
- this[kPendingIdx] = 0
-
- this[kResume] = (sync) => resume(this, sync)
- this[kOnError] = (err) => onError(this, err)
- }
-
- get pipelining () {
- return this[kPipelining]
+ var flags = options.nocase ? 'i' : ''
+ try {
+ var regExp = new RegExp('^' + re + '$', flags)
+ } catch (er) /* istanbul ignore next - should be impossible */ {
+ // If it was an invalid regular expression, then it can't match
+ // anything. This trick looks for a character after the end of
+ // the string, which is of course impossible, except in multi-line
+ // mode, but it's not a /m regex.
+ return new RegExp('$.')
}
- set pipelining (value) {
- this[kPipelining] = value
- this[kResume](true)
- }
+ regExp._glob = pattern
+ regExp._src = re
- get [kPending] () {
- return this[kQueue].length - this[kPendingIdx]
- }
+ return regExp
+}
- get [kRunning] () {
- return this[kPendingIdx] - this[kRunningIdx]
- }
+minimatch.makeRe = function (pattern, options) {
+ return new Minimatch(pattern, options || {}).makeRe()
+}
- get [kSize] () {
- return this[kQueue].length - this[kRunningIdx]
- }
+Minimatch.prototype.makeRe = makeRe
+function makeRe () {
+ if (this.regexp || this.regexp === false) return this.regexp
- get [kConnected] () {
- return !!this[kHTTPContext] && !this[kConnecting] && !this[kHTTPContext].destroyed
- }
+ // at this point, this.set is a 2d array of partial
+ // pattern strings, or "**".
+ //
+ // It's better to use .match(). This function shouldn't
+ // be used, really, but it's pretty convenient sometimes,
+ // when you just want to work with a regex.
+ var set = this.set
- get [kBusy] () {
- return Boolean(
- this[kHTTPContext]?.busy(null) ||
- (this[kSize] >= (getPipelining(this) || 1)) ||
- this[kPending] > 0
- )
+ if (!set.length) {
+ this.regexp = false
+ return this.regexp
}
+ var options = this.options
- /* istanbul ignore: only used for test */
- [kConnect] (cb) {
- connect(this)
- this.once('connect', cb)
- }
+ var twoStar = options.noglobstar ? star
+ : options.dot ? twoStarDot
+ : twoStarNoDot
+ var flags = options.nocase ? 'i' : ''
- [kDispatch] (opts, handler) {
- const origin = opts.origin || this[kUrl].origin
- const request = new Request(origin, opts, handler)
+ var re = set.map(function (pattern) {
+ return pattern.map(function (p) {
+ return (p === GLOBSTAR) ? twoStar
+ : (typeof p === 'string') ? regExpEscape(p)
+ : p._src
+ }).join('\\\/')
+ }).join('|')
- this[kQueue].push(request)
- if (this[kResuming]) {
- // Do nothing.
- } else if (util.bodyLength(request.body) == null && util.isIterable(request.body)) {
- // Wait a tick in case stream/iterator is ended in the same tick.
- this[kResuming] = 1
- queueMicrotask(() => resume(this))
- } else {
- this[kResume](true)
- }
+ // must match entire pattern
+ // ending in a * or ** will make it less strict.
+ re = '^(?:' + re + ')$'
- if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) {
- this[kNeedDrain] = 2
- }
+ // can match anything, as long as it's not this.
+ if (this.negate) re = '^(?!' + re + ').*$'
- return this[kNeedDrain] < 2
+ try {
+ this.regexp = new RegExp(re, flags)
+ } catch (ex) /* istanbul ignore next - should be impossible */ {
+ this.regexp = false
}
+ return this.regexp
+}
- async [kClose] () {
- // TODO: for H2 we need to gracefully flush the remaining enqueued
- // request and close each stream.
- return new Promise((resolve) => {
- if (this[kSize]) {
- this[kClosedResolve] = resolve
- } else {
- resolve(null)
- }
- })
+minimatch.match = function (list, pattern, options) {
+ options = options || {}
+ var mm = new Minimatch(pattern, options)
+ list = list.filter(function (f) {
+ return mm.match(f)
+ })
+ if (mm.options.nonull && !list.length) {
+ list.push(pattern)
}
+ return list
+}
- async [kDestroy] (err) {
- return new Promise((resolve) => {
- const requests = this[kQueue].splice(this[kPendingIdx])
- for (let i = 0; i < requests.length; i++) {
- const request = requests[i]
- util.errorRequest(this, request, err)
- }
+Minimatch.prototype.match = function match (f, partial) {
+ if (typeof partial === 'undefined') partial = this.partial
+ this.debug('match', f, this.pattern)
+ // short-circuit in the case of busted things.
+ // comments, etc.
+ if (this.comment) return false
+ if (this.empty) return f === ''
- const callback = () => {
- if (this[kClosedResolve]) {
- // TODO (fix): Should we error here with ClientDestroyedError?
- this[kClosedResolve]()
- this[kClosedResolve] = null
- }
- resolve(null)
- }
+ if (f === '/' && partial) return true
- if (this[kHTTPContext]) {
- this[kHTTPContext].destroy(err, callback)
- this[kHTTPContext] = null
- } else {
- queueMicrotask(callback)
- }
+ var options = this.options
- this[kResume]()
- })
+ // windows: need to use /, not \
+ if (path.sep !== '/') {
+ f = f.split(path.sep).join('/')
}
-}
-const createRedirectInterceptor = __nccwpck_require__(6097)
+ // treat the test path as a set of pathparts.
+ f = f.split(slashSplit)
+ this.debug(this.pattern, 'split', f)
-function onError (client, err) {
- if (
- client[kRunning] === 0 &&
- err.code !== 'UND_ERR_INFO' &&
- err.code !== 'UND_ERR_SOCKET'
- ) {
- // Error is not caused by running request and not a recoverable
- // socket error.
+ // just ONE of the pattern sets in this.set needs to match
+ // in order for it to be valid. If negating, then just one
+ // match means that we have failed.
+ // Either way, return on the first hit.
- assert(client[kPendingIdx] === client[kRunningIdx])
+ var set = this.set
+ this.debug(this.pattern, 'set', set)
- const requests = client[kQueue].splice(client[kRunningIdx])
+ // Find the basename of the path by looking for the last non-empty segment
+ var filename
+ var i
+ for (i = f.length - 1; i >= 0; i--) {
+ filename = f[i]
+ if (filename) break
+ }
- for (let i = 0; i < requests.length; i++) {
- const request = requests[i]
- util.errorRequest(client, request, err)
+ for (i = 0; i < set.length; i++) {
+ var pattern = set[i]
+ var file = f
+ if (options.matchBase && pattern.length === 1) {
+ file = [filename]
+ }
+ var hit = this.matchOne(file, pattern, partial)
+ if (hit) {
+ if (options.flipNegate) return true
+ return !this.negate
}
- assert(client[kSize] === 0)
}
+
+ // didn't get any hits. this is success if it's a negative
+ // pattern, failure otherwise.
+ if (options.flipNegate) return false
+ return this.negate
}
-/**
- * @param {Client} client
- * @returns
- */
-async function connect (client) {
- assert(!client[kConnecting])
- assert(!client[kHTTPContext])
+// set partial to true to test if, for example,
+// "/a/b" matches the start of "/*/b/*/d"
+// Partial means, if you run out of file before you run
+// out of pattern, then that's fine, as long as all
+// the parts match.
+Minimatch.prototype.matchOne = function (file, pattern, partial) {
+ var options = this.options
- let { host, hostname, protocol, port } = client[kUrl]
+ this.debug('matchOne',
+ { 'this': this, file: file, pattern: pattern })
- // Resolve ipv6
- if (hostname[0] === '[') {
- const idx = hostname.indexOf(']')
+ this.debug('matchOne', file.length, pattern.length)
- assert(idx !== -1)
- const ip = hostname.substring(1, idx)
+ for (var fi = 0,
+ pi = 0,
+ fl = file.length,
+ pl = pattern.length
+ ; (fi < fl) && (pi < pl)
+ ; fi++, pi++) {
+ this.debug('matchOne loop')
+ var p = pattern[pi]
+ var f = file[fi]
- assert(net.isIP(ip))
- hostname = ip
- }
+ this.debug(pattern, p, f)
- client[kConnecting] = true
+ // should be impossible.
+ // some invalid regexp stuff in the set.
+ /* istanbul ignore if */
+ if (p === false) return false
- if (channels.beforeConnect.hasSubscribers) {
- channels.beforeConnect.publish({
- connectParams: {
- host,
- hostname,
- protocol,
- port,
- version: client[kHTTPContext]?.version,
- servername: client[kServerName],
- localAddress: client[kLocalAddress]
- },
- connector: client[kConnector]
- })
- }
+ if (p === GLOBSTAR) {
+ this.debug('GLOBSTAR', [pattern, p, f])
- try {
- const socket = await new Promise((resolve, reject) => {
- client[kConnector]({
- host,
- hostname,
- protocol,
- port,
- servername: client[kServerName],
- localAddress: client[kLocalAddress]
- }, (err, socket) => {
- if (err) {
- reject(err)
- } else {
- resolve(socket)
+ // "**"
+ // a/**/b/**/c would match the following:
+ // a/b/x/y/z/c
+ // a/x/y/z/b/c
+ // a/b/x/b/x/c
+ // a/b/c
+ // To do this, take the rest of the pattern after
+ // the **, and see if it would match the file remainder.
+ // If so, return success.
+ // If not, the ** "swallows" a segment, and try again.
+ // This is recursively awful.
+ //
+ // a/**/b/**/c matching a/b/x/y/z/c
+ // - a matches a
+ // - doublestar
+ // - matchOne(b/x/y/z/c, b/**/c)
+ // - b matches b
+ // - doublestar
+ // - matchOne(x/y/z/c, c) -> no
+ // - matchOne(y/z/c, c) -> no
+ // - matchOne(z/c, c) -> no
+ // - matchOne(c, c) yes, hit
+ var fr = fi
+ var pr = pi + 1
+ if (pr === pl) {
+ this.debug('** at the end')
+ // a ** at the end will just swallow the rest.
+ // We have found a match.
+ // however, it will not swallow /.x, unless
+ // options.dot is set.
+ // . and .. are *never* matched by **, for explosively
+ // exponential reasons.
+ for (; fi < fl; fi++) {
+ if (file[fi] === '.' || file[fi] === '..' ||
+ (!options.dot && file[fi].charAt(0) === '.')) return false
}
- })
- })
-
- if (client.destroyed) {
- util.destroy(socket.on('error', noop), new ClientDestroyedError())
- return
- }
-
- assert(socket)
-
- try {
- client[kHTTPContext] = socket.alpnProtocol === 'h2'
- ? await connectH2(client, socket)
- : await connectH1(client, socket)
- } catch (err) {
- socket.destroy().on('error', noop)
- throw err
- }
+ return true
+ }
- client[kConnecting] = false
+ // ok, let's see if we can swallow whatever we can.
+ while (fr < fl) {
+ var swallowee = file[fr]
- socket[kCounter] = 0
- socket[kMaxRequests] = client[kMaxRequests]
- socket[kClient] = client
- socket[kError] = null
+ this.debug('\nglobstar while', file, fr, pattern, pr, swallowee)
- if (channels.connected.hasSubscribers) {
- channels.connected.publish({
- connectParams: {
- host,
- hostname,
- protocol,
- port,
- version: client[kHTTPContext]?.version,
- servername: client[kServerName],
- localAddress: client[kLocalAddress]
- },
- connector: client[kConnector],
- socket
- })
- }
- client.emit('connect', client[kUrl], [client])
- } catch (err) {
- if (client.destroyed) {
- return
- }
+ // XXX remove this slice. Just pass the start index.
+ if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
+ this.debug('globstar found match!', fr, fl, swallowee)
+ // found a match.
+ return true
+ } else {
+ // can't swallow "." or ".." ever.
+ // can only swallow ".foo" when explicitly asked.
+ if (swallowee === '.' || swallowee === '..' ||
+ (!options.dot && swallowee.charAt(0) === '.')) {
+ this.debug('dot detected!', file, fr, pattern, pr)
+ break
+ }
- client[kConnecting] = false
+ // ** swallows a segment, and continue.
+ this.debug('globstar swallow a segment, and continue')
+ fr++
+ }
+ }
- if (channels.connectError.hasSubscribers) {
- channels.connectError.publish({
- connectParams: {
- host,
- hostname,
- protocol,
- port,
- version: client[kHTTPContext]?.version,
- servername: client[kServerName],
- localAddress: client[kLocalAddress]
- },
- connector: client[kConnector],
- error: err
- })
+ // no match was found.
+ // However, in partial mode, we can't say this is necessarily over.
+ // If there's more *pattern* left, then
+ /* istanbul ignore if */
+ if (partial) {
+ // ran out of file
+ this.debug('\n>>> no match, partial?', file, fr, pattern, pr)
+ if (fr === fl) return true
+ }
+ return false
}
- if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') {
- assert(client[kRunning] === 0)
- while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) {
- const request = client[kQueue][client[kPendingIdx]++]
- util.errorRequest(client, request, err)
- }
+ // something other than **
+ // non-magic patterns just have to match exactly
+ // patterns with magic have been turned into regexps.
+ var hit
+ if (typeof p === 'string') {
+ hit = f === p
+ this.debug('string match', p, f, hit)
} else {
- onError(client, err)
+ hit = f.match(p)
+ this.debug('pattern match', p, f, hit)
}
- client.emit('connectionError', client[kUrl], [client], err)
+ if (!hit) return false
}
- client[kResume]()
-}
-
-function emitDrain (client) {
- client[kNeedDrain] = 0
- client.emit('drain', client[kUrl], [client])
-}
+ // Note: ending in / means that we'll get a final ""
+ // at the end of the pattern. This can only match a
+ // corresponding "" at the end of the file.
+ // If the file ends in /, then it can only match a
+ // a pattern that ends in /, unless the pattern just
+ // doesn't have any more for it. But, a/b/ should *not*
+ // match "a/b/*", even though "" matches against the
+ // [^/]*? pattern, except in partial mode, where it might
+ // simply not be reached yet.
+ // However, a/b/ should still satisfy a/*
-function resume (client, sync) {
- if (client[kResuming] === 2) {
- return
+ // now either we fell off the end of the pattern, or we're done.
+ if (fi === fl && pi === pl) {
+ // ran out of pattern and filename at the same time.
+ // an exact hit!
+ return true
+ } else if (fi === fl) {
+ // ran out of file, but still had pattern left.
+ // this is ok if we're doing the match as part of
+ // a glob fs traversal.
+ return partial
+ } else /* istanbul ignore else */ if (pi === pl) {
+ // ran out of pattern, still have file left.
+ // this is only acceptable if we're on the very last
+ // empty segment of a file with a trailing slash.
+ // a/* should match a/b/
+ return (fi === fl - 1) && (file[fi] === '')
}
- client[kResuming] = 2
+ // should be unreachable.
+ /* istanbul ignore next */
+ throw new Error('wtf?')
+}
- _resume(client, sync)
- client[kResuming] = 0
-
- if (client[kRunningIdx] > 256) {
- client[kQueue].splice(0, client[kRunningIdx])
- client[kPendingIdx] -= client[kRunningIdx]
- client[kRunningIdx] = 0
- }
+// replace stuff like \* with *
+function globUnescape (s) {
+ return s.replace(/\\(.)/g, '$1')
}
-function _resume (client, sync) {
- while (true) {
- if (client.destroyed) {
- assert(client[kPending] === 0)
- return
- }
+function regExpEscape (s) {
+ return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
+}
- if (client[kClosedResolve] && !client[kSize]) {
- client[kClosedResolve]()
- client[kClosedResolve] = null
- return
- }
- if (client[kHTTPContext]) {
- client[kHTTPContext].resume()
- }
+/***/ }),
- if (client[kBusy]) {
- client[kNeedDrain] = 2
- } else if (client[kNeedDrain] === 2) {
- if (sync) {
- client[kNeedDrain] = 1
- queueMicrotask(() => emitDrain(client))
- } else {
- emitDrain(client)
- }
- continue
- }
+/***/ 744:
+/***/ ((module) => {
- if (client[kPending] === 0) {
- return
- }
+/**
+ * Helpers.
+ */
- if (client[kRunning] >= (getPipelining(client) || 1)) {
- return
- }
+var s = 1000;
+var m = s * 60;
+var h = m * 60;
+var d = h * 24;
+var w = d * 7;
+var y = d * 365.25;
- const request = client[kQueue][client[kPendingIdx]]
+/**
+ * Parse or format the given `val`.
+ *
+ * Options:
+ *
+ * - `long` verbose formatting [false]
+ *
+ * @param {String|Number} val
+ * @param {Object} [options]
+ * @throws {Error} throw an error if val is not a non-empty string or a number
+ * @return {String|Number}
+ * @api public
+ */
- if (client[kUrl].protocol === 'https:' && client[kServerName] !== request.servername) {
- if (client[kRunning] > 0) {
- return
- }
+module.exports = function (val, options) {
+ options = options || {};
+ var type = typeof val;
+ if (type === 'string' && val.length > 0) {
+ return parse(val);
+ } else if (type === 'number' && isFinite(val)) {
+ return options.long ? fmtLong(val) : fmtShort(val);
+ }
+ throw new Error(
+ 'val is not a non-empty string or a valid number. val=' +
+ JSON.stringify(val)
+ );
+};
- client[kServerName] = request.servername
- client[kHTTPContext]?.destroy(new InformationalError('servername changed'), () => {
- client[kHTTPContext] = null
- resume(client)
- })
- }
+/**
+ * Parse the given `str` and return milliseconds.
+ *
+ * @param {String} str
+ * @return {Number}
+ * @api private
+ */
- if (client[kConnecting]) {
- return
- }
+function parse(str) {
+ str = String(str);
+ if (str.length > 100) {
+ return;
+ }
+ var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
+ str
+ );
+ if (!match) {
+ return;
+ }
+ var n = parseFloat(match[1]);
+ var type = (match[2] || 'ms').toLowerCase();
+ switch (type) {
+ case 'years':
+ case 'year':
+ case 'yrs':
+ case 'yr':
+ case 'y':
+ return n * y;
+ case 'weeks':
+ case 'week':
+ case 'w':
+ return n * w;
+ case 'days':
+ case 'day':
+ case 'd':
+ return n * d;
+ case 'hours':
+ case 'hour':
+ case 'hrs':
+ case 'hr':
+ case 'h':
+ return n * h;
+ case 'minutes':
+ case 'minute':
+ case 'mins':
+ case 'min':
+ case 'm':
+ return n * m;
+ case 'seconds':
+ case 'second':
+ case 'secs':
+ case 'sec':
+ case 's':
+ return n * s;
+ case 'milliseconds':
+ case 'millisecond':
+ case 'msecs':
+ case 'msec':
+ case 'ms':
+ return n;
+ default:
+ return undefined;
+ }
+}
- if (!client[kHTTPContext]) {
- connect(client)
- return
- }
+/**
+ * Short format for `ms`.
+ *
+ * @param {Number} ms
+ * @return {String}
+ * @api private
+ */
- if (client[kHTTPContext].destroyed) {
- return
- }
+function fmtShort(ms) {
+ var msAbs = Math.abs(ms);
+ if (msAbs >= d) {
+ return Math.round(ms / d) + 'd';
+ }
+ if (msAbs >= h) {
+ return Math.round(ms / h) + 'h';
+ }
+ if (msAbs >= m) {
+ return Math.round(ms / m) + 'm';
+ }
+ if (msAbs >= s) {
+ return Math.round(ms / s) + 's';
+ }
+ return ms + 'ms';
+}
- if (client[kHTTPContext].busy(request)) {
- return
- }
+/**
+ * Long format for `ms`.
+ *
+ * @param {Number} ms
+ * @return {String}
+ * @api private
+ */
- if (!request.aborted && client[kHTTPContext].write(request)) {
- client[kPendingIdx]++
- } else {
- client[kQueue].splice(client[kPendingIdx], 1)
- }
+function fmtLong(ms) {
+ var msAbs = Math.abs(ms);
+ if (msAbs >= d) {
+ return plural(ms, msAbs, d, 'day');
}
+ if (msAbs >= h) {
+ return plural(ms, msAbs, h, 'hour');
+ }
+ if (msAbs >= m) {
+ return plural(ms, msAbs, m, 'minute');
+ }
+ if (msAbs >= s) {
+ return plural(ms, msAbs, s, 'second');
+ }
+ return ms + ' ms';
}
-module.exports = Client
+/**
+ * Pluralization helper.
+ */
+
+function plural(ms, msAbs, n, name) {
+ var isPlural = msAbs >= n * 1.5;
+ return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
+}
/***/ }),
-/***/ 2540:
+/***/ 9379:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const Dispatcher = __nccwpck_require__(9784)
-const {
- ClientDestroyedError,
- ClientClosedError,
- InvalidArgumentError
-} = __nccwpck_require__(2344)
-const { kDestroy, kClose, kClosed, kDestroyed, kDispatch, kInterceptors } = __nccwpck_require__(6130)
-
-const kOnDestroyed = Symbol('onDestroyed')
-const kOnClosed = Symbol('onClosed')
-const kInterceptedDispatch = Symbol('Intercepted Dispatch')
-
-class DispatcherBase extends Dispatcher {
- constructor () {
- super()
-
- this[kDestroyed] = false
- this[kOnDestroyed] = null
- this[kClosed] = false
- this[kOnClosed] = []
- }
-
- get destroyed () {
- return this[kDestroyed]
- }
-
- get closed () {
- return this[kClosed]
- }
-
- get interceptors () {
- return this[kInterceptors]
- }
-
- set interceptors (newInterceptors) {
- if (newInterceptors) {
- for (let i = newInterceptors.length - 1; i >= 0; i--) {
- const interceptor = this[kInterceptors][i]
- if (typeof interceptor !== 'function') {
- throw new InvalidArgumentError('interceptor must be an function')
- }
- }
- }
-
- this[kInterceptors] = newInterceptors
+const ANY = Symbol('SemVer ANY')
+// hoisted class for cyclic dependency
+class Comparator {
+ static get ANY () {
+ return ANY
}
- close (callback) {
- if (callback === undefined) {
- return new Promise((resolve, reject) => {
- this.close((err, data) => {
- return err ? reject(err) : resolve(data)
- })
- })
- }
-
- if (typeof callback !== 'function') {
- throw new InvalidArgumentError('invalid callback')
- }
-
- if (this[kDestroyed]) {
- queueMicrotask(() => callback(new ClientDestroyedError(), null))
- return
- }
+ constructor (comp, options) {
+ options = parseOptions(options)
- if (this[kClosed]) {
- if (this[kOnClosed]) {
- this[kOnClosed].push(callback)
+ if (comp instanceof Comparator) {
+ if (comp.loose === !!options.loose) {
+ return comp
} else {
- queueMicrotask(() => callback(null, null))
+ comp = comp.value
}
- return
}
- this[kClosed] = true
- this[kOnClosed].push(callback)
+ comp = comp.trim().split(/\s+/).join(' ')
+ debug('comparator', comp, options)
+ this.options = options
+ this.loose = !!options.loose
+ this.parse(comp)
- const onClosed = () => {
- const callbacks = this[kOnClosed]
- this[kOnClosed] = null
- for (let i = 0; i < callbacks.length; i++) {
- callbacks[i](null, null)
- }
+ if (this.semver === ANY) {
+ this.value = ''
+ } else {
+ this.value = this.operator + this.semver.version
}
- // Should not error.
- this[kClose]()
- .then(() => this.destroy())
- .then(() => {
- queueMicrotask(onClosed)
- })
+ debug('comp', this)
}
- destroy (err, callback) {
- if (typeof err === 'function') {
- callback = err
- err = null
- }
+ parse (comp) {
+ const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]
+ const m = comp.match(r)
- if (callback === undefined) {
- return new Promise((resolve, reject) => {
- this.destroy(err, (err, data) => {
- return err ? /* istanbul ignore next: should never error */ reject(err) : resolve(data)
- })
- })
+ if (!m) {
+ throw new TypeError(`Invalid comparator: ${comp}`)
}
- if (typeof callback !== 'function') {
- throw new InvalidArgumentError('invalid callback')
+ this.operator = m[1] !== undefined ? m[1] : ''
+ if (this.operator === '=') {
+ this.operator = ''
}
- if (this[kDestroyed]) {
- if (this[kOnDestroyed]) {
- this[kOnDestroyed].push(callback)
- } else {
- queueMicrotask(() => callback(null, null))
- }
- return
+ // if it literally is just '>' or '' then allow anything.
+ if (!m[2]) {
+ this.semver = ANY
+ } else {
+ this.semver = new SemVer(m[2], this.options.loose)
}
+ }
- if (!err) {
- err = new ClientDestroyedError()
- }
+ toString () {
+ return this.value
+ }
- this[kDestroyed] = true
- this[kOnDestroyed] = this[kOnDestroyed] || []
- this[kOnDestroyed].push(callback)
+ test (version) {
+ debug('Comparator.test', version, this.options.loose)
- const onDestroyed = () => {
- const callbacks = this[kOnDestroyed]
- this[kOnDestroyed] = null
- for (let i = 0; i < callbacks.length; i++) {
- callbacks[i](null, null)
- }
+ if (this.semver === ANY || version === ANY) {
+ return true
}
- // Should not error.
- this[kDestroy](err).then(() => {
- queueMicrotask(onDestroyed)
- })
- }
-
- [kInterceptedDispatch] (opts, handler) {
- if (!this[kInterceptors] || this[kInterceptors].length === 0) {
- this[kInterceptedDispatch] = this[kDispatch]
- return this[kDispatch](opts, handler)
+ if (typeof version === 'string') {
+ try {
+ version = new SemVer(version, this.options)
+ } catch (er) {
+ return false
+ }
}
- let dispatch = this[kDispatch].bind(this)
- for (let i = this[kInterceptors].length - 1; i >= 0; i--) {
- dispatch = this[kInterceptors][i](dispatch)
- }
- this[kInterceptedDispatch] = dispatch
- return dispatch(opts, handler)
+ return cmp(version, this.operator, this.semver, this.options)
}
- dispatch (opts, handler) {
- if (!handler || typeof handler !== 'object') {
- throw new InvalidArgumentError('handler must be an object')
+ intersects (comp, options) {
+ if (!(comp instanceof Comparator)) {
+ throw new TypeError('a Comparator is required')
}
- try {
- if (!opts || typeof opts !== 'object') {
- throw new InvalidArgumentError('opts must be an object.')
- }
-
- if (this[kDestroyed] || this[kOnDestroyed]) {
- throw new ClientDestroyedError()
- }
-
- if (this[kClosed]) {
- throw new ClientClosedError()
+ if (this.operator === '') {
+ if (this.value === '') {
+ return true
}
-
- return this[kInterceptedDispatch](opts, handler)
- } catch (err) {
- if (typeof handler.onError !== 'function') {
- throw new InvalidArgumentError('invalid onError method')
+ return new Range(comp.value, options).test(this.value)
+ } else if (comp.operator === '') {
+ if (comp.value === '') {
+ return true
}
+ return new Range(this.value, options).test(comp.semver)
+ }
- handler.onError(err)
+ options = parseOptions(options)
+ // Special cases where nothing can possibly be lower
+ if (options.includePrerelease &&
+ (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) {
+ return false
+ }
+ if (!options.includePrerelease &&
+ (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) {
return false
}
+
+ // Same direction increasing (> or >=)
+ if (this.operator.startsWith('>') && comp.operator.startsWith('>')) {
+ return true
+ }
+ // Same direction decreasing (< or <=)
+ if (this.operator.startsWith('<') && comp.operator.startsWith('<')) {
+ return true
+ }
+ // same SemVer and both sides are inclusive (<= or >=)
+ if (
+ (this.semver.version === comp.semver.version) &&
+ this.operator.includes('=') && comp.operator.includes('=')) {
+ return true
+ }
+ // opposite directions less than
+ if (cmp(this.semver, '<', comp.semver, options) &&
+ this.operator.startsWith('>') && comp.operator.startsWith('<')) {
+ return true
+ }
+ // opposite directions greater than
+ if (cmp(this.semver, '>', comp.semver, options) &&
+ this.operator.startsWith('<') && comp.operator.startsWith('>')) {
+ return true
+ }
+ return false
}
}
-module.exports = DispatcherBase
+module.exports = Comparator
+
+const parseOptions = __nccwpck_require__(356)
+const { safeRe: re, t } = __nccwpck_require__(5471)
+const cmp = __nccwpck_require__(8646)
+const debug = __nccwpck_require__(1159)
+const SemVer = __nccwpck_require__(7163)
+const Range = __nccwpck_require__(6782)
/***/ }),
-/***/ 9784:
+/***/ 6782:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const EventEmitter = __nccwpck_require__(8474)
-
-class Dispatcher extends EventEmitter {
- dispatch () {
- throw new Error('not implemented')
- }
-
- close () {
- throw new Error('not implemented')
- }
- destroy () {
- throw new Error('not implemented')
- }
+const SPACE_CHARACTERS = /\s+/g
- compose (...args) {
- // So we handle [interceptor1, interceptor2] or interceptor1, interceptor2, ...
- const interceptors = Array.isArray(args[0]) ? args[0] : args
- let dispatch = this.dispatch.bind(this)
+// hoisted class for cyclic dependency
+class Range {
+ constructor (range, options) {
+ options = parseOptions(options)
- for (const interceptor of interceptors) {
- if (interceptor == null) {
- continue
+ if (range instanceof Range) {
+ if (
+ range.loose === !!options.loose &&
+ range.includePrerelease === !!options.includePrerelease
+ ) {
+ return range
+ } else {
+ return new Range(range.raw, options)
}
+ }
- if (typeof interceptor !== 'function') {
- throw new TypeError(`invalid interceptor, expected function received ${typeof interceptor}`)
- }
+ if (range instanceof Comparator) {
+ // just put it in the set and return
+ this.raw = range.value
+ this.set = [[range]]
+ this.formatted = undefined
+ return this
+ }
- dispatch = interceptor(dispatch)
+ this.options = options
+ this.loose = !!options.loose
+ this.includePrerelease = !!options.includePrerelease
- if (dispatch == null || typeof dispatch !== 'function' || dispatch.length !== 2) {
- throw new TypeError('invalid interceptor')
- }
- }
+ // First reduce all whitespace as much as possible so we do not have to rely
+ // on potentially slow regexes like \s*. This is then stored and used for
+ // future error messages as well.
+ this.raw = range.trim().replace(SPACE_CHARACTERS, ' ')
- return new ComposedDispatcher(this, dispatch)
- }
-}
+ // First, split on ||
+ this.set = this.raw
+ .split('||')
+ // map the range to a 2d array of comparators
+ .map(r => this.parseRange(r.trim()))
+ // throw out any comparator lists that are empty
+ // this generally means that it was not a valid range, which is allowed
+ // in loose mode, but will still throw if the WHOLE range is invalid.
+ .filter(c => c.length)
-class ComposedDispatcher extends Dispatcher {
- #dispatcher = null
- #dispatch = null
+ if (!this.set.length) {
+ throw new TypeError(`Invalid SemVer Range: ${this.raw}`)
+ }
- constructor (dispatcher, dispatch) {
- super()
- this.#dispatcher = dispatcher
- this.#dispatch = dispatch
- }
+ // if we have any that are not the null set, throw out null sets.
+ if (this.set.length > 1) {
+ // keep the first one, in case they're all null sets
+ const first = this.set[0]
+ this.set = this.set.filter(c => !isNullSet(c[0]))
+ if (this.set.length === 0) {
+ this.set = [first]
+ } else if (this.set.length > 1) {
+ // if we have any that are *, then the range is just *
+ for (const c of this.set) {
+ if (c.length === 1 && isAny(c[0])) {
+ this.set = [c]
+ break
+ }
+ }
+ }
+ }
- dispatch (...args) {
- this.#dispatch(...args)
+ this.formatted = undefined
}
- close (...args) {
- return this.#dispatcher.close(...args)
+ get range () {
+ if (this.formatted === undefined) {
+ this.formatted = ''
+ for (let i = 0; i < this.set.length; i++) {
+ if (i > 0) {
+ this.formatted += '||'
+ }
+ const comps = this.set[i]
+ for (let k = 0; k < comps.length; k++) {
+ if (k > 0) {
+ this.formatted += ' '
+ }
+ this.formatted += comps[k].toString().trim()
+ }
+ }
+ }
+ return this.formatted
}
- destroy (...args) {
- return this.#dispatcher.destroy(...args)
+ format () {
+ return this.range
}
-}
-
-module.exports = Dispatcher
+ toString () {
+ return this.range
+ }
-/***/ }),
-
-/***/ 1630:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
+ parseRange (range) {
+ // memoize range parsing for performance.
+ // this is a very hot path, and fully deterministic.
+ const memoOpts =
+ (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) |
+ (this.options.loose && FLAG_LOOSE)
+ const memoKey = memoOpts + ':' + range
+ const cached = cache.get(memoKey)
+ if (cached) {
+ return cached
+ }
+ const loose = this.options.loose
+ // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
+ const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]
+ range = range.replace(hr, hyphenReplace(this.options.includePrerelease))
+ debug('hyphen replace', range)
-const DispatcherBase = __nccwpck_require__(2540)
-const { kClose, kDestroy, kClosed, kDestroyed, kDispatch, kNoProxyAgent, kHttpProxyAgent, kHttpsProxyAgent } = __nccwpck_require__(6130)
-const ProxyAgent = __nccwpck_require__(8349)
-const Agent = __nccwpck_require__(4332)
+ // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
+ range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace)
+ debug('comparator trim', range)
-const DEFAULT_PORTS = {
- 'http:': 80,
- 'https:': 443
-}
+ // `~ 1.2.3` => `~1.2.3`
+ range = range.replace(re[t.TILDETRIM], tildeTrimReplace)
+ debug('tilde trim', range)
-let experimentalWarned = false
+ // `^ 1.2.3` => `^1.2.3`
+ range = range.replace(re[t.CARETTRIM], caretTrimReplace)
+ debug('caret trim', range)
-class EnvHttpProxyAgent extends DispatcherBase {
- #noProxyValue = null
- #noProxyEntries = null
- #opts = null
+ // At this point, the range is completely trimmed and
+ // ready to be split into comparators.
- constructor (opts = {}) {
- super()
- this.#opts = opts
+ let rangeList = range
+ .split(' ')
+ .map(comp => parseComparator(comp, this.options))
+ .join(' ')
+ .split(/\s+/)
+ // >=0.0.0 is equivalent to *
+ .map(comp => replaceGTE0(comp, this.options))
- if (!experimentalWarned) {
- experimentalWarned = true
- process.emitWarning('EnvHttpProxyAgent is experimental, expect them to change at any time.', {
- code: 'UNDICI-EHPA'
+ if (loose) {
+ // in loose mode, throw out any that are not valid comparators
+ rangeList = rangeList.filter(comp => {
+ debug('loose invalid filter', comp, this.options)
+ return !!comp.match(re[t.COMPARATORLOOSE])
})
}
+ debug('range list', rangeList)
- const { httpProxy, httpsProxy, noProxy, ...agentOpts } = opts
-
- this[kNoProxyAgent] = new Agent(agentOpts)
-
- const HTTP_PROXY = httpProxy ?? process.env.http_proxy ?? process.env.HTTP_PROXY
- if (HTTP_PROXY) {
- this[kHttpProxyAgent] = new ProxyAgent({ ...agentOpts, uri: HTTP_PROXY })
- } else {
- this[kHttpProxyAgent] = this[kNoProxyAgent]
+ // if any comparators are the null set, then replace with JUST null set
+ // if more than one comparator, remove any * comparators
+ // also, don't include the same comparator more than once
+ const rangeMap = new Map()
+ const comparators = rangeList.map(comp => new Comparator(comp, this.options))
+ for (const comp of comparators) {
+ if (isNullSet(comp)) {
+ return [comp]
+ }
+ rangeMap.set(comp.value, comp)
}
-
- const HTTPS_PROXY = httpsProxy ?? process.env.https_proxy ?? process.env.HTTPS_PROXY
- if (HTTPS_PROXY) {
- this[kHttpsProxyAgent] = new ProxyAgent({ ...agentOpts, uri: HTTPS_PROXY })
- } else {
- this[kHttpsProxyAgent] = this[kHttpProxyAgent]
+ if (rangeMap.size > 1 && rangeMap.has('')) {
+ rangeMap.delete('')
}
- this.#parseNoProxy()
- }
-
- [kDispatch] (opts, handler) {
- const url = new URL(opts.origin)
- const agent = this.#getProxyAgentForUrl(url)
- return agent.dispatch(opts, handler)
- }
-
- async [kClose] () {
- await this[kNoProxyAgent].close()
- if (!this[kHttpProxyAgent][kClosed]) {
- await this[kHttpProxyAgent].close()
- }
- if (!this[kHttpsProxyAgent][kClosed]) {
- await this[kHttpsProxyAgent].close()
- }
+ const result = [...rangeMap.values()]
+ cache.set(memoKey, result)
+ return result
}
- async [kDestroy] (err) {
- await this[kNoProxyAgent].destroy(err)
- if (!this[kHttpProxyAgent][kDestroyed]) {
- await this[kHttpProxyAgent].destroy(err)
- }
- if (!this[kHttpsProxyAgent][kDestroyed]) {
- await this[kHttpsProxyAgent].destroy(err)
+ intersects (range, options) {
+ if (!(range instanceof Range)) {
+ throw new TypeError('a Range is required')
}
- }
-
- #getProxyAgentForUrl (url) {
- let { protocol, host: hostname, port } = url
- // Stripping ports in this way instead of using parsedUrl.hostname to make
- // sure that the brackets around IPv6 addresses are kept.
- hostname = hostname.replace(/:\d*$/, '').toLowerCase()
- port = Number.parseInt(port, 10) || DEFAULT_PORTS[protocol] || 0
- if (!this.#shouldProxy(hostname, port)) {
- return this[kNoProxyAgent]
- }
- if (protocol === 'https:') {
- return this[kHttpsProxyAgent]
- }
- return this[kHttpProxyAgent]
+ return this.set.some((thisComparators) => {
+ return (
+ isSatisfiable(thisComparators, options) &&
+ range.set.some((rangeComparators) => {
+ return (
+ isSatisfiable(rangeComparators, options) &&
+ thisComparators.every((thisComparator) => {
+ return rangeComparators.every((rangeComparator) => {
+ return thisComparator.intersects(rangeComparator, options)
+ })
+ })
+ )
+ })
+ )
+ })
}
- #shouldProxy (hostname, port) {
- if (this.#noProxyChanged) {
- this.#parseNoProxy()
- }
-
- if (this.#noProxyEntries.length === 0) {
- return true // Always proxy if NO_PROXY is not set or empty.
- }
- if (this.#noProxyValue === '*') {
- return false // Never proxy if wildcard is set.
+ // if ANY of the sets match ALL of its comparators, then pass
+ test (version) {
+ if (!version) {
+ return false
}
- for (let i = 0; i < this.#noProxyEntries.length; i++) {
- const entry = this.#noProxyEntries[i]
- if (entry.port && entry.port !== port) {
- continue // Skip if ports don't match.
- }
- if (!/^[.*]/.test(entry.hostname)) {
- // No wildcards, so don't proxy only if there is not an exact match.
- if (hostname === entry.hostname) {
- return false
- }
- } else {
- // Don't proxy if the hostname ends with the no_proxy host.
- if (hostname.endsWith(entry.hostname.replace(/^\*/, ''))) {
- return false
- }
+ if (typeof version === 'string') {
+ try {
+ version = new SemVer(version, this.options)
+ } catch (er) {
+ return false
}
}
- return true
- }
-
- #parseNoProxy () {
- const noProxyValue = this.#opts.noProxy ?? this.#noProxyEnv
- const noProxySplit = noProxyValue.split(/[,\s]/)
- const noProxyEntries = []
-
- for (let i = 0; i < noProxySplit.length; i++) {
- const entry = noProxySplit[i]
- if (!entry) {
- continue
+ for (let i = 0; i < this.set.length; i++) {
+ if (testSet(this.set[i], version, this.options)) {
+ return true
}
- const parsed = entry.match(/^(.+):(\d+)$/)
- noProxyEntries.push({
- hostname: (parsed ? parsed[1] : entry).toLowerCase(),
- port: parsed ? Number.parseInt(parsed[2], 10) : 0
- })
- }
-
- this.#noProxyValue = noProxyValue
- this.#noProxyEntries = noProxyEntries
- }
-
- get #noProxyChanged () {
- if (this.#opts.noProxy !== undefined) {
- return false
}
- return this.#noProxyValue !== this.#noProxyEnv
- }
-
- get #noProxyEnv () {
- return process.env.no_proxy ?? process.env.NO_PROXY ?? ''
+ return false
}
}
-module.exports = EnvHttpProxyAgent
-
-
-/***/ }),
-
-/***/ 5533:
-/***/ ((module) => {
-
-/* eslint-disable */
-
-
+module.exports = Range
-// Extracted from node/lib/internal/fixed_queue.js
+const LRU = __nccwpck_require__(1383)
+const cache = new LRU()
-// Currently optimal queue size, tested on V8 6.0 - 6.6. Must be power of two.
-const kSize = 2048;
-const kMask = kSize - 1;
+const parseOptions = __nccwpck_require__(356)
+const Comparator = __nccwpck_require__(9379)
+const debug = __nccwpck_require__(1159)
+const SemVer = __nccwpck_require__(7163)
+const {
+ safeRe: re,
+ t,
+ comparatorTrimReplace,
+ tildeTrimReplace,
+ caretTrimReplace,
+} = __nccwpck_require__(5471)
+const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = __nccwpck_require__(5101)
-// The FixedQueue is implemented as a singly-linked list of fixed-size
-// circular buffers. It looks something like this:
-//
-// head tail
-// | |
-// v v
-// +-----------+ <-----\ +-----------+ <------\ +-----------+
-// | [null] | \----- | next | \------- | next |
-// +-----------+ +-----------+ +-----------+
-// | item | <-- bottom | item | <-- bottom | [empty] |
-// | item | | item | | [empty] |
-// | item | | item | | [empty] |
-// | item | | item | | [empty] |
-// | item | | item | bottom --> | item |
-// | item | | item | | item |
-// | ... | | ... | | ... |
-// | item | | item | | item |
-// | item | | item | | item |
-// | [empty] | <-- top | item | | item |
-// | [empty] | | item | | item |
-// | [empty] | | [empty] | <-- top top --> | [empty] |
-// +-----------+ +-----------+ +-----------+
-//
-// Or, if there is only one circular buffer, it looks something
-// like either of these:
-//
-// head tail head tail
-// | | | |
-// v v v v
-// +-----------+ +-----------+
-// | [null] | | [null] |
-// +-----------+ +-----------+
-// | [empty] | | item |
-// | [empty] | | item |
-// | item | <-- bottom top --> | [empty] |
-// | item | | [empty] |
-// | [empty] | <-- top bottom --> | item |
-// | [empty] | | item |
-// +-----------+ +-----------+
-//
-// Adding a value means moving `top` forward by one, removing means
-// moving `bottom` forward by one. After reaching the end, the queue
-// wraps around.
-//
-// When `top === bottom` the current queue is empty and when
-// `top + 1 === bottom` it's full. This wastes a single space of storage
-// but allows much quicker checks.
+const isNullSet = c => c.value === '<0.0.0-0'
+const isAny = c => c.value === ''
-class FixedCircularBuffer {
- constructor() {
- this.bottom = 0;
- this.top = 0;
- this.list = new Array(kSize);
- this.next = null;
- }
+// take a set of comparators and determine whether there
+// exists a version which can satisfy it
+const isSatisfiable = (comparators, options) => {
+ let result = true
+ const remainingComparators = comparators.slice()
+ let testComparator = remainingComparators.pop()
- isEmpty() {
- return this.top === this.bottom;
- }
+ while (result && remainingComparators.length) {
+ result = remainingComparators.every((otherComparator) => {
+ return testComparator.intersects(otherComparator, options)
+ })
- isFull() {
- return ((this.top + 1) & kMask) === this.bottom;
+ testComparator = remainingComparators.pop()
}
- push(data) {
- this.list[this.top] = data;
- this.top = (this.top + 1) & kMask;
- }
+ return result
+}
- shift() {
- const nextItem = this.list[this.bottom];
- if (nextItem === undefined)
- return null;
- this.list[this.bottom] = undefined;
- this.bottom = (this.bottom + 1) & kMask;
- return nextItem;
- }
+// comprised of xranges, tildes, stars, and gtlt's at this point.
+// already replaced the hyphen ranges
+// turn into a set of JUST comparators.
+const parseComparator = (comp, options) => {
+ comp = comp.replace(re[t.BUILD], '')
+ debug('comp', comp, options)
+ comp = replaceCarets(comp, options)
+ debug('caret', comp)
+ comp = replaceTildes(comp, options)
+ debug('tildes', comp)
+ comp = replaceXRanges(comp, options)
+ debug('xrange', comp)
+ comp = replaceStars(comp, options)
+ debug('stars', comp)
+ return comp
}
-module.exports = class FixedQueue {
- constructor() {
- this.head = this.tail = new FixedCircularBuffer();
- }
+const isX = id => !id || id.toLowerCase() === 'x' || id === '*'
- isEmpty() {
- return this.head.isEmpty();
- }
+// ~, ~> --> * (any, kinda silly)
+// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0
+// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0
+// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0
+// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0
+// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0
+// ~0.0.1 --> >=0.0.1 <0.1.0-0
+const replaceTildes = (comp, options) => {
+ return comp
+ .trim()
+ .split(/\s+/)
+ .map((c) => replaceTilde(c, options))
+ .join(' ')
+}
- push(data) {
- if (this.head.isFull()) {
- // Head is full: Creates a new queue, sets the old queue's `.next` to it,
- // and sets it as the new main queue.
- this.head = this.head.next = new FixedCircularBuffer();
- }
- this.head.push(data);
- }
+const replaceTilde = (comp, options) => {
+ const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]
+ return comp.replace(r, (_, M, m, p, pr) => {
+ debug('tilde', comp, _, M, m, p, pr)
+ let ret
- shift() {
- const tail = this.tail;
- const next = tail.shift();
- if (tail.isEmpty() && tail.next !== null) {
- // If there is another queue, it forms the new tail.
- this.tail = tail.next;
+ if (isX(M)) {
+ ret = ''
+ } else if (isX(m)) {
+ ret = `>=${M}.0.0 <${+M + 1}.0.0-0`
+ } else if (isX(p)) {
+ // ~1.2 == >=1.2.0 <1.3.0-0
+ ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`
+ } else if (pr) {
+ debug('replaceTilde pr', pr)
+ ret = `>=${M}.${m}.${p}-${pr
+ } <${M}.${+m + 1}.0-0`
+ } else {
+ // ~1.2.3 == >=1.2.3 <1.3.0-0
+ ret = `>=${M}.${m}.${p
+ } <${M}.${+m + 1}.0-0`
}
- return next;
- }
-};
-
-
-/***/ }),
-
-/***/ 3229:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
+ debug('tilde return', ret)
+ return ret
+ })
+}
-const DispatcherBase = __nccwpck_require__(2540)
-const FixedQueue = __nccwpck_require__(5533)
-const { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = __nccwpck_require__(6130)
-const PoolStats = __nccwpck_require__(429)
-
-const kClients = Symbol('clients')
-const kNeedDrain = Symbol('needDrain')
-const kQueue = Symbol('queue')
-const kClosedResolve = Symbol('closed resolve')
-const kOnDrain = Symbol('onDrain')
-const kOnConnect = Symbol('onConnect')
-const kOnDisconnect = Symbol('onDisconnect')
-const kOnConnectionError = Symbol('onConnectionError')
-const kGetDispatcher = Symbol('get dispatcher')
-const kAddClient = Symbol('add client')
-const kRemoveClient = Symbol('remove client')
-const kStats = Symbol('stats')
-
-class PoolBase extends DispatcherBase {
- constructor () {
- super()
-
- this[kQueue] = new FixedQueue()
- this[kClients] = []
- this[kQueued] = 0
-
- const pool = this
-
- this[kOnDrain] = function onDrain (origin, targets) {
- const queue = pool[kQueue]
+// ^ --> * (any, kinda silly)
+// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0
+// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0
+// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0
+// ^1.2.3 --> >=1.2.3 <2.0.0-0
+// ^1.2.0 --> >=1.2.0 <2.0.0-0
+// ^0.0.1 --> >=0.0.1 <0.0.2-0
+// ^0.1.0 --> >=0.1.0 <0.2.0-0
+const replaceCarets = (comp, options) => {
+ return comp
+ .trim()
+ .split(/\s+/)
+ .map((c) => replaceCaret(c, options))
+ .join(' ')
+}
- let needDrain = false
+const replaceCaret = (comp, options) => {
+ debug('caret', comp, options)
+ const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]
+ const z = options.includePrerelease ? '-0' : ''
+ return comp.replace(r, (_, M, m, p, pr) => {
+ debug('caret', comp, _, M, m, p, pr)
+ let ret
- while (!needDrain) {
- const item = queue.shift()
- if (!item) {
- break
- }
- pool[kQueued]--
- needDrain = !this.dispatch(item.opts, item.handler)
+ if (isX(M)) {
+ ret = ''
+ } else if (isX(m)) {
+ ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`
+ } else if (isX(p)) {
+ if (M === '0') {
+ ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`
+ } else {
+ ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`
}
-
- this[kNeedDrain] = needDrain
-
- if (!this[kNeedDrain] && pool[kNeedDrain]) {
- pool[kNeedDrain] = false
- pool.emit('drain', origin, [pool, ...targets])
+ } else if (pr) {
+ debug('replaceCaret pr', pr)
+ if (M === '0') {
+ if (m === '0') {
+ ret = `>=${M}.${m}.${p}-${pr
+ } <${M}.${m}.${+p + 1}-0`
+ } else {
+ ret = `>=${M}.${m}.${p}-${pr
+ } <${M}.${+m + 1}.0-0`
+ }
+ } else {
+ ret = `>=${M}.${m}.${p}-${pr
+ } <${+M + 1}.0.0-0`
}
-
- if (pool[kClosedResolve] && queue.isEmpty()) {
- Promise
- .all(pool[kClients].map(c => c.close()))
- .then(pool[kClosedResolve])
+ } else {
+ debug('no pr')
+ if (M === '0') {
+ if (m === '0') {
+ ret = `>=${M}.${m}.${p
+ }${z} <${M}.${m}.${+p + 1}-0`
+ } else {
+ ret = `>=${M}.${m}.${p
+ }${z} <${M}.${+m + 1}.0-0`
+ }
+ } else {
+ ret = `>=${M}.${m}.${p
+ } <${+M + 1}.0.0-0`
}
}
- this[kOnConnect] = (origin, targets) => {
- pool.emit('connect', origin, [pool, ...targets])
- }
+ debug('caret return', ret)
+ return ret
+ })
+}
- this[kOnDisconnect] = (origin, targets, err) => {
- pool.emit('disconnect', origin, [pool, ...targets], err)
- }
+const replaceXRanges = (comp, options) => {
+ debug('replaceXRanges', comp, options)
+ return comp
+ .split(/\s+/)
+ .map((c) => replaceXRange(c, options))
+ .join(' ')
+}
- this[kOnConnectionError] = (origin, targets, err) => {
- pool.emit('connectionError', origin, [pool, ...targets], err)
+const replaceXRange = (comp, options) => {
+ comp = comp.trim()
+ const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]
+ return comp.replace(r, (ret, gtlt, M, m, p, pr) => {
+ debug('xRange', comp, ret, gtlt, M, m, p, pr)
+ const xM = isX(M)
+ const xm = xM || isX(m)
+ const xp = xm || isX(p)
+ const anyX = xp
+
+ if (gtlt === '=' && anyX) {
+ gtlt = ''
}
- this[kStats] = new PoolStats(this)
- }
+ // if we're including prereleases in the match, then we need
+ // to fix this to -0, the lowest possible prerelease value
+ pr = options.includePrerelease ? '-0' : ''
- get [kBusy] () {
- return this[kNeedDrain]
- }
+ if (xM) {
+ if (gtlt === '>' || gtlt === '<') {
+ // nothing is allowed
+ ret = '<0.0.0-0'
+ } else {
+ // nothing is forbidden
+ ret = '*'
+ }
+ } else if (gtlt && anyX) {
+ // we know patch is an x, because we have any x at all.
+ // replace X with 0
+ if (xm) {
+ m = 0
+ }
+ p = 0
- get [kConnected] () {
- return this[kClients].filter(client => client[kConnected]).length
- }
+ if (gtlt === '>') {
+ // >1 => >=2.0.0
+ // >1.2 => >=1.3.0
+ gtlt = '>='
+ if (xm) {
+ M = +M + 1
+ m = 0
+ p = 0
+ } else {
+ m = +m + 1
+ p = 0
+ }
+ } else if (gtlt === '<=') {
+ // <=0.7.x is actually <0.8.0, since any 0.7.x should
+ // pass. Similarly, <=7.x is actually <8.0.0, etc.
+ gtlt = '<'
+ if (xm) {
+ M = +M + 1
+ } else {
+ m = +m + 1
+ }
+ }
- get [kFree] () {
- return this[kClients].filter(client => client[kConnected] && !client[kNeedDrain]).length
- }
+ if (gtlt === '<') {
+ pr = '-0'
+ }
- get [kPending] () {
- let ret = this[kQueued]
- for (const { [kPending]: pending } of this[kClients]) {
- ret += pending
+ ret = `${gtlt + M}.${m}.${p}${pr}`
+ } else if (xm) {
+ ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`
+ } else if (xp) {
+ ret = `>=${M}.${m}.0${pr
+ } <${M}.${+m + 1}.0-0`
}
- return ret
- }
- get [kRunning] () {
- let ret = 0
- for (const { [kRunning]: running } of this[kClients]) {
- ret += running
- }
- return ret
- }
+ debug('xRange return', ret)
- get [kSize] () {
- let ret = this[kQueued]
- for (const { [kSize]: size } of this[kClients]) {
- ret += size
- }
return ret
- }
+ })
+}
- get stats () {
- return this[kStats]
- }
+// Because * is AND-ed with everything else in the comparator,
+// and '' means "any version", just remove the *s entirely.
+const replaceStars = (comp, options) => {
+ debug('replaceStars', comp, options)
+ // Looseness is ignored here. star is always as loose as it gets!
+ return comp
+ .trim()
+ .replace(re[t.STAR], '')
+}
- async [kClose] () {
- if (this[kQueue].isEmpty()) {
- await Promise.all(this[kClients].map(c => c.close()))
- } else {
- await new Promise((resolve) => {
- this[kClosedResolve] = resolve
- })
- }
- }
+const replaceGTE0 = (comp, options) => {
+ debug('replaceGTE0', comp, options)
+ return comp
+ .trim()
+ .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')
+}
- async [kDestroy] (err) {
- while (true) {
- const item = this[kQueue].shift()
- if (!item) {
- break
- }
- item.handler.onError(err)
- }
+// This function is passed to string.replace(re[t.HYPHENRANGE])
+// M, m, patch, prerelease, build
+// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
+// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do
+// 1.2 - 3.4 => >=1.2.0 <3.5.0-0
+// TODO build?
+const hyphenReplace = incPr => ($0,
+ from, fM, fm, fp, fpr, fb,
+ to, tM, tm, tp, tpr) => {
+ if (isX(fM)) {
+ from = ''
+ } else if (isX(fm)) {
+ from = `>=${fM}.0.0${incPr ? '-0' : ''}`
+ } else if (isX(fp)) {
+ from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`
+ } else if (fpr) {
+ from = `>=${from}`
+ } else {
+ from = `>=${from}${incPr ? '-0' : ''}`
+ }
- await Promise.all(this[kClients].map(c => c.destroy(err)))
+ if (isX(tM)) {
+ to = ''
+ } else if (isX(tm)) {
+ to = `<${+tM + 1}.0.0-0`
+ } else if (isX(tp)) {
+ to = `<${tM}.${+tm + 1}.0-0`
+ } else if (tpr) {
+ to = `<=${tM}.${tm}.${tp}-${tpr}`
+ } else if (incPr) {
+ to = `<${tM}.${tm}.${+tp + 1}-0`
+ } else {
+ to = `<=${to}`
}
- [kDispatch] (opts, handler) {
- const dispatcher = this[kGetDispatcher]()
+ return `${from} ${to}`.trim()
+}
- if (!dispatcher) {
- this[kNeedDrain] = true
- this[kQueue].push({ opts, handler })
- this[kQueued]++
- } else if (!dispatcher.dispatch(opts, handler)) {
- dispatcher[kNeedDrain] = true
- this[kNeedDrain] = !this[kGetDispatcher]()
+const testSet = (set, version, options) => {
+ for (let i = 0; i < set.length; i++) {
+ if (!set[i].test(version)) {
+ return false
}
-
- return !this[kNeedDrain]
}
- [kAddClient] (client) {
- client
- .on('drain', this[kOnDrain])
- .on('connect', this[kOnConnect])
- .on('disconnect', this[kOnDisconnect])
- .on('connectionError', this[kOnConnectionError])
-
- this[kClients].push(client)
+ if (version.prerelease.length && !options.includePrerelease) {
+ // Find the set of versions that are allowed to have prereleases
+ // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
+ // That should allow `1.2.3-pr.2` to pass.
+ // However, `1.2.4-alpha.notready` should NOT be allowed,
+ // even though it's within the range set by the comparators.
+ for (let i = 0; i < set.length; i++) {
+ debug(set[i].semver)
+ if (set[i].semver === Comparator.ANY) {
+ continue
+ }
- if (this[kNeedDrain]) {
- queueMicrotask(() => {
- if (this[kNeedDrain]) {
- this[kOnDrain](client[kUrl], [this, client])
+ if (set[i].semver.prerelease.length > 0) {
+ const allowed = set[i].semver
+ if (allowed.major === version.major &&
+ allowed.minor === version.minor &&
+ allowed.patch === version.patch) {
+ return true
}
- })
- }
-
- return this
- }
-
- [kRemoveClient] (client) {
- client.close(() => {
- const idx = this[kClients].indexOf(client)
- if (idx !== -1) {
- this[kClients].splice(idx, 1)
}
- })
+ }
- this[kNeedDrain] = this[kClients].some(dispatcher => (
- !dispatcher[kNeedDrain] &&
- dispatcher.closed !== true &&
- dispatcher.destroyed !== true
- ))
+ // Version has a -pre, but it's not one of the ones we like.
+ return false
}
-}
-module.exports = {
- PoolBase,
- kClients,
- kNeedDrain,
- kAddClient,
- kRemoveClient,
- kGetDispatcher
+ return true
}
/***/ }),
-/***/ 429:
+/***/ 7163:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const { kFree, kConnected, kPending, kQueued, kRunning, kSize } = __nccwpck_require__(6130)
-const kPool = Symbol('pool')
-class PoolStats {
- constructor (pool) {
- this[kPool] = pool
- }
- get connected () {
- return this[kPool][kConnected]
- }
+const debug = __nccwpck_require__(1159)
+const { MAX_LENGTH, MAX_SAFE_INTEGER } = __nccwpck_require__(5101)
+const { safeRe: re, t } = __nccwpck_require__(5471)
- get free () {
- return this[kPool][kFree]
- }
+const parseOptions = __nccwpck_require__(356)
+const { compareIdentifiers } = __nccwpck_require__(3348)
+class SemVer {
+ constructor (version, options) {
+ options = parseOptions(options)
- get pending () {
- return this[kPool][kPending]
- }
+ if (version instanceof SemVer) {
+ if (version.loose === !!options.loose &&
+ version.includePrerelease === !!options.includePrerelease) {
+ return version
+ } else {
+ version = version.version
+ }
+ } else if (typeof version !== 'string') {
+ throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`)
+ }
- get queued () {
- return this[kPool][kQueued]
- }
+ if (version.length > MAX_LENGTH) {
+ throw new TypeError(
+ `version is longer than ${MAX_LENGTH} characters`
+ )
+ }
- get running () {
- return this[kPool][kRunning]
- }
+ debug('SemVer', version, options)
+ this.options = options
+ this.loose = !!options.loose
+ // this isn't actually relevant for versions, but keep it so that we
+ // don't run into trouble passing this.options around.
+ this.includePrerelease = !!options.includePrerelease
- get size () {
- return this[kPool][kSize]
- }
-}
+ const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL])
-module.exports = PoolStats
+ if (!m) {
+ throw new TypeError(`Invalid Version: ${version}`)
+ }
+ this.raw = version
-/***/ }),
+ // these are actually numbers
+ this.major = +m[1]
+ this.minor = +m[2]
+ this.patch = +m[3]
-/***/ 3959:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
+ throw new TypeError('Invalid major version')
+ }
+ if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
+ throw new TypeError('Invalid minor version')
+ }
+ if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
+ throw new TypeError('Invalid patch version')
+ }
-const {
- PoolBase,
- kClients,
- kNeedDrain,
- kAddClient,
- kGetDispatcher
-} = __nccwpck_require__(3229)
-const Client = __nccwpck_require__(2138)
-const {
- InvalidArgumentError
-} = __nccwpck_require__(2344)
-const util = __nccwpck_require__(7375)
-const { kUrl, kInterceptors } = __nccwpck_require__(6130)
-const buildConnector = __nccwpck_require__(5005)
+ // numberify any prerelease numeric ids
+ if (!m[4]) {
+ this.prerelease = []
+ } else {
+ this.prerelease = m[4].split('.').map((id) => {
+ if (/^[0-9]+$/.test(id)) {
+ const num = +id
+ if (num >= 0 && num < MAX_SAFE_INTEGER) {
+ return num
+ }
+ }
+ return id
+ })
+ }
-const kOptions = Symbol('options')
-const kConnections = Symbol('connections')
-const kFactory = Symbol('factory')
+ this.build = m[5] ? m[5].split('.') : []
+ this.format()
+ }
-function defaultFactory (origin, opts) {
- return new Client(origin, opts)
-}
+ format () {
+ this.version = `${this.major}.${this.minor}.${this.patch}`
+ if (this.prerelease.length) {
+ this.version += `-${this.prerelease.join('.')}`
+ }
+ return this.version
+ }
-class Pool extends PoolBase {
- constructor (origin, {
- connections,
- factory = defaultFactory,
- connect,
- connectTimeout,
- tls,
- maxCachedSessions,
- socketPath,
- autoSelectFamily,
- autoSelectFamilyAttemptTimeout,
- allowH2,
- ...options
- } = {}) {
- super()
+ toString () {
+ return this.version
+ }
- if (connections != null && (!Number.isFinite(connections) || connections < 0)) {
- throw new InvalidArgumentError('invalid connections')
+ compare (other) {
+ debug('SemVer.compare', this.version, this.options, other)
+ if (!(other instanceof SemVer)) {
+ if (typeof other === 'string' && other === this.version) {
+ return 0
+ }
+ other = new SemVer(other, this.options)
}
- if (typeof factory !== 'function') {
- throw new InvalidArgumentError('factory must be a function.')
+ if (other.version === this.version) {
+ return 0
}
- if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {
- throw new InvalidArgumentError('connect must be a function or an object')
+ return this.compareMain(other) || this.comparePre(other)
+ }
+
+ compareMain (other) {
+ if (!(other instanceof SemVer)) {
+ other = new SemVer(other, this.options)
}
- if (typeof connect !== 'function') {
- connect = buildConnector({
- ...tls,
- maxCachedSessions,
- allowH2,
- socketPath,
- timeout: connectTimeout,
- ...(autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined),
- ...connect
- })
+ if (this.major < other.major) {
+ return -1
+ }
+ if (this.major > other.major) {
+ return 1
+ }
+ if (this.minor < other.minor) {
+ return -1
+ }
+ if (this.minor > other.minor) {
+ return 1
+ }
+ if (this.patch < other.patch) {
+ return -1
+ }
+ if (this.patch > other.patch) {
+ return 1
}
+ return 0
+ }
- this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool)
- ? options.interceptors.Pool
- : []
- this[kConnections] = connections || null
- this[kUrl] = util.parseOrigin(origin)
- this[kOptions] = { ...util.deepClone(options), connect, allowH2 }
- this[kOptions].interceptors = options.interceptors
- ? { ...options.interceptors }
- : undefined
- this[kFactory] = factory
+ comparePre (other) {
+ if (!(other instanceof SemVer)) {
+ other = new SemVer(other, this.options)
+ }
- this.on('connectionError', (origin, targets, error) => {
- // If a connection error occurs, we remove the client from the pool,
- // and emit a connectionError event. They will not be re-used.
- // Fixes https://github.com/nodejs/undici/issues/3895
- for (const target of targets) {
- // Do not use kRemoveClient here, as it will close the client,
- // but the client cannot be closed in this state.
- const idx = this[kClients].indexOf(target)
- if (idx !== -1) {
- this[kClients].splice(idx, 1)
- }
+ // NOT having a prerelease is > having one
+ if (this.prerelease.length && !other.prerelease.length) {
+ return -1
+ } else if (!this.prerelease.length && other.prerelease.length) {
+ return 1
+ } else if (!this.prerelease.length && !other.prerelease.length) {
+ return 0
+ }
+
+ let i = 0
+ do {
+ const a = this.prerelease[i]
+ const b = other.prerelease[i]
+ debug('prerelease compare', i, a, b)
+ if (a === undefined && b === undefined) {
+ return 0
+ } else if (b === undefined) {
+ return 1
+ } else if (a === undefined) {
+ return -1
+ } else if (a === b) {
+ continue
+ } else {
+ return compareIdentifiers(a, b)
}
- })
+ } while (++i)
}
- [kGetDispatcher] () {
- for (const client of this[kClients]) {
- if (!client[kNeedDrain]) {
- return client
+ compareBuild (other) {
+ if (!(other instanceof SemVer)) {
+ other = new SemVer(other, this.options)
+ }
+
+ let i = 0
+ do {
+ const a = this.build[i]
+ const b = other.build[i]
+ debug('build compare', i, a, b)
+ if (a === undefined && b === undefined) {
+ return 0
+ } else if (b === undefined) {
+ return 1
+ } else if (a === undefined) {
+ return -1
+ } else if (a === b) {
+ continue
+ } else {
+ return compareIdentifiers(a, b)
+ }
+ } while (++i)
+ }
+
+ // preminor will bump the version up to the next minor release, and immediately
+ // down to pre-release. premajor and prepatch work the same way.
+ inc (release, identifier, identifierBase) {
+ if (release.startsWith('pre')) {
+ if (!identifier && identifierBase === false) {
+ throw new Error('invalid increment argument: identifier is empty')
+ }
+ // Avoid an invalid semver results
+ if (identifier) {
+ const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE])
+ if (!match || match[1] !== identifier) {
+ throw new Error(`invalid identifier: ${identifier}`)
+ }
}
}
- if (!this[kConnections] || this[kClients].length < this[kConnections]) {
- const dispatcher = this[kFactory](this[kUrl], this[kOptions])
- this[kAddClient](dispatcher)
- return dispatcher
+ switch (release) {
+ case 'premajor':
+ this.prerelease.length = 0
+ this.patch = 0
+ this.minor = 0
+ this.major++
+ this.inc('pre', identifier, identifierBase)
+ break
+ case 'preminor':
+ this.prerelease.length = 0
+ this.patch = 0
+ this.minor++
+ this.inc('pre', identifier, identifierBase)
+ break
+ case 'prepatch':
+ // If this is already a prerelease, it will bump to the next version
+ // drop any prereleases that might already exist, since they are not
+ // relevant at this point.
+ this.prerelease.length = 0
+ this.inc('patch', identifier, identifierBase)
+ this.inc('pre', identifier, identifierBase)
+ break
+ // If the input is a non-prerelease version, this acts the same as
+ // prepatch.
+ case 'prerelease':
+ if (this.prerelease.length === 0) {
+ this.inc('patch', identifier, identifierBase)
+ }
+ this.inc('pre', identifier, identifierBase)
+ break
+ case 'release':
+ if (this.prerelease.length === 0) {
+ throw new Error(`version ${this.raw} is not a prerelease`)
+ }
+ this.prerelease.length = 0
+ break
+
+ case 'major':
+ // If this is a pre-major version, bump up to the same major version.
+ // Otherwise increment major.
+ // 1.0.0-5 bumps to 1.0.0
+ // 1.1.0 bumps to 2.0.0
+ if (
+ this.minor !== 0 ||
+ this.patch !== 0 ||
+ this.prerelease.length === 0
+ ) {
+ this.major++
+ }
+ this.minor = 0
+ this.patch = 0
+ this.prerelease = []
+ break
+ case 'minor':
+ // If this is a pre-minor version, bump up to the same minor version.
+ // Otherwise increment minor.
+ // 1.2.0-5 bumps to 1.2.0
+ // 1.2.1 bumps to 1.3.0
+ if (this.patch !== 0 || this.prerelease.length === 0) {
+ this.minor++
+ }
+ this.patch = 0
+ this.prerelease = []
+ break
+ case 'patch':
+ // If this is not a pre-release version, it will increment the patch.
+ // If it is a pre-release it will bump up to the same patch version.
+ // 1.2.0-5 patches to 1.2.0
+ // 1.2.0 patches to 1.2.1
+ if (this.prerelease.length === 0) {
+ this.patch++
+ }
+ this.prerelease = []
+ break
+ // This probably shouldn't be used publicly.
+ // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
+ case 'pre': {
+ const base = Number(identifierBase) ? 1 : 0
+
+ if (this.prerelease.length === 0) {
+ this.prerelease = [base]
+ } else {
+ let i = this.prerelease.length
+ while (--i >= 0) {
+ if (typeof this.prerelease[i] === 'number') {
+ this.prerelease[i]++
+ i = -2
+ }
+ }
+ if (i === -1) {
+ // didn't increment anything
+ if (identifier === this.prerelease.join('.') && identifierBase === false) {
+ throw new Error('invalid increment argument: identifier already exists')
+ }
+ this.prerelease.push(base)
+ }
+ }
+ if (identifier) {
+ // 1.2.0-beta.1 bumps to 1.2.0-beta.2,
+ // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
+ let prerelease = [identifier, base]
+ if (identifierBase === false) {
+ prerelease = [identifier]
+ }
+ if (compareIdentifiers(this.prerelease[0], identifier) === 0) {
+ if (isNaN(this.prerelease[1])) {
+ this.prerelease = prerelease
+ }
+ } else {
+ this.prerelease = prerelease
+ }
+ }
+ break
+ }
+ default:
+ throw new Error(`invalid increment argument: ${release}`)
+ }
+ this.raw = this.format()
+ if (this.build.length) {
+ this.raw += `+${this.build.join('.')}`
}
+ return this
}
}
-module.exports = Pool
+module.exports = SemVer
/***/ }),
-/***/ 8349:
+/***/ 1799:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const { kProxy, kClose, kDestroy, kDispatch, kInterceptors } = __nccwpck_require__(6130)
-const { URL } = __nccwpck_require__(3136)
-const Agent = __nccwpck_require__(4332)
-const Pool = __nccwpck_require__(3959)
-const DispatcherBase = __nccwpck_require__(2540)
-const { InvalidArgumentError, RequestAbortedError, SecureProxyConnectionError } = __nccwpck_require__(2344)
-const buildConnector = __nccwpck_require__(5005)
-const Client = __nccwpck_require__(2138)
-
-const kAgent = Symbol('proxy agent')
-const kClient = Symbol('proxy client')
-const kProxyHeaders = Symbol('proxy headers')
-const kRequestTls = Symbol('request tls settings')
-const kProxyTls = Symbol('proxy tls settings')
-const kConnectEndpoint = Symbol('connect endpoint function')
-const kTunnelProxy = Symbol('tunnel proxy')
-
-function defaultProtocolPort (protocol) {
- return protocol === 'https:' ? 443 : 80
+const parse = __nccwpck_require__(6353)
+const clean = (version, options) => {
+ const s = parse(version.trim().replace(/^[=v]+/, ''), options)
+ return s ? s.version : null
}
+module.exports = clean
-function defaultFactory (origin, opts) {
- return new Pool(origin, opts)
-}
-const noop = () => {}
+/***/ }),
-function defaultAgentFactory (origin, opts) {
- if (opts.connections === 1) {
- return new Client(origin, opts)
- }
- return new Pool(origin, opts)
-}
+/***/ 8646:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-class Http1ProxyWrapper extends DispatcherBase {
- #client
- constructor (proxyUrl, { headers = {}, connect, factory }) {
- super()
- if (!proxyUrl) {
- throw new InvalidArgumentError('Proxy URL is mandatory')
- }
- this[kProxyHeaders] = headers
- if (factory) {
- this.#client = factory(proxyUrl, { connect })
- } else {
- this.#client = new Client(proxyUrl, { connect })
- }
- }
+const eq = __nccwpck_require__(5082)
+const neq = __nccwpck_require__(4974)
+const gt = __nccwpck_require__(6599)
+const gte = __nccwpck_require__(1236)
+const lt = __nccwpck_require__(3872)
+const lte = __nccwpck_require__(6717)
- [kDispatch] (opts, handler) {
- const onHeaders = handler.onHeaders
- handler.onHeaders = function (statusCode, data, resume) {
- if (statusCode === 407) {
- if (typeof handler.onError === 'function') {
- handler.onError(new InvalidArgumentError('Proxy Authentication Required (407)'))
- }
- return
+const cmp = (a, op, b, loose) => {
+ switch (op) {
+ case '===':
+ if (typeof a === 'object') {
+ a = a.version
}
- if (onHeaders) onHeaders.call(this, statusCode, data, resume)
- }
+ if (typeof b === 'object') {
+ b = b.version
+ }
+ return a === b
- // Rewrite request as an HTTP1 Proxy request, without tunneling.
- const {
- origin,
- path = '/',
- headers = {}
- } = opts
+ case '!==':
+ if (typeof a === 'object') {
+ a = a.version
+ }
+ if (typeof b === 'object') {
+ b = b.version
+ }
+ return a !== b
- opts.path = origin + path
+ case '':
+ case '=':
+ case '==':
+ return eq(a, b, loose)
- if (!('host' in headers) && !('Host' in headers)) {
- const { host } = new URL(origin)
- headers.host = host
- }
- opts.headers = { ...this[kProxyHeaders], ...headers }
+ case '!=':
+ return neq(a, b, loose)
- return this.#client[kDispatch](opts, handler)
- }
+ case '>':
+ return gt(a, b, loose)
- async [kClose] () {
- return this.#client.close()
- }
+ case '>=':
+ return gte(a, b, loose)
- async [kDestroy] (err) {
- return this.#client.destroy(err)
+ case '<':
+ return lt(a, b, loose)
+
+ case '<=':
+ return lte(a, b, loose)
+
+ default:
+ throw new TypeError(`Invalid operator: ${op}`)
}
}
+module.exports = cmp
-class ProxyAgent extends DispatcherBase {
- constructor (opts) {
- super()
- if (!opts || (typeof opts === 'object' && !(opts instanceof URL) && !opts.uri)) {
- throw new InvalidArgumentError('Proxy uri is mandatory')
- }
+/***/ }),
- const { clientFactory = defaultFactory } = opts
- if (typeof clientFactory !== 'function') {
- throw new InvalidArgumentError('Proxy opts.clientFactory must be a function.')
- }
+/***/ 5385:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- const { proxyTunnel = true } = opts
- const url = this.#getUrl(opts)
- const { href, origin, port, protocol, username, password, hostname: proxyHostname } = url
- this[kProxy] = { uri: href, protocol }
- this[kInterceptors] = opts.interceptors?.ProxyAgent && Array.isArray(opts.interceptors.ProxyAgent)
- ? opts.interceptors.ProxyAgent
- : []
- this[kRequestTls] = opts.requestTls
- this[kProxyTls] = opts.proxyTls
- this[kProxyHeaders] = opts.headers || {}
- this[kTunnelProxy] = proxyTunnel
+const SemVer = __nccwpck_require__(7163)
+const parse = __nccwpck_require__(6353)
+const { safeRe: re, t } = __nccwpck_require__(5471)
- if (opts.auth && opts.token) {
- throw new InvalidArgumentError('opts.auth cannot be used in combination with opts.token')
- } else if (opts.auth) {
- /* @deprecated in favour of opts.token */
- this[kProxyHeaders]['proxy-authorization'] = `Basic ${opts.auth}`
- } else if (opts.token) {
- this[kProxyHeaders]['proxy-authorization'] = opts.token
- } else if (username && password) {
- this[kProxyHeaders]['proxy-authorization'] = `Basic ${Buffer.from(`${decodeURIComponent(username)}:${decodeURIComponent(password)}`).toString('base64')}`
- }
+const coerce = (version, options) => {
+ if (version instanceof SemVer) {
+ return version
+ }
- const connect = buildConnector({ ...opts.proxyTls })
- this[kConnectEndpoint] = buildConnector({ ...opts.requestTls })
+ if (typeof version === 'number') {
+ version = String(version)
+ }
- const agentFactory = opts.factory || defaultAgentFactory
- const factory = (origin, options) => {
- const { protocol } = new URL(origin)
- if (!this[kTunnelProxy] && protocol === 'http:' && this[kProxy].protocol === 'http:') {
- return new Http1ProxyWrapper(this[kProxy].uri, {
- headers: this[kProxyHeaders],
- connect,
- factory: agentFactory
- })
- }
- return agentFactory(origin, options)
- }
- this[kClient] = clientFactory(url, { connect })
- this[kAgent] = new Agent({
- ...opts,
- factory,
- connect: async (opts, callback) => {
- let requestedPath = opts.host
- if (!opts.port) {
- requestedPath += `:${defaultProtocolPort(opts.protocol)}`
- }
- try {
- const { socket, statusCode } = await this[kClient].connect({
- origin,
- port,
- path: requestedPath,
- signal: opts.signal,
- headers: {
- ...this[kProxyHeaders],
- host: opts.host
- },
- servername: this[kProxyTls]?.servername || proxyHostname
- })
- if (statusCode !== 200) {
- socket.on('error', noop).destroy()
- callback(new RequestAbortedError(`Proxy response (${statusCode}) !== 200 when HTTP Tunneling`))
- }
- if (opts.protocol !== 'https:') {
- callback(null, socket)
- return
- }
- let servername
- if (this[kRequestTls]) {
- servername = this[kRequestTls].servername
- } else {
- servername = opts.servername
- }
- this[kConnectEndpoint]({ ...opts, servername, httpSocket: socket }, callback)
- } catch (err) {
- if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') {
- // Throw a custom error to avoid loop in client.js#connect
- callback(new SecureProxyConnectionError(err))
- } else {
- callback(err)
- }
- }
- }
- })
+ if (typeof version !== 'string') {
+ return null
}
- dispatch (opts, handler) {
- const headers = buildHeaders(opts.headers)
- throwIfProxyAuthIsSent(headers)
+ options = options || {}
- if (headers && !('host' in headers) && !('Host' in headers)) {
- const { host } = new URL(opts.origin)
- headers.host = host
+ let match = null
+ if (!options.rtl) {
+ match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE])
+ } else {
+ // Find the right-most coercible string that does not share
+ // a terminus with a more left-ward coercible string.
+ // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'
+ // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4'
+ //
+ // Walk through the string checking with a /g regexp
+ // Manually set the index so as to pick up overlapping matches.
+ // Stop when we get a match that ends at the string end, since no
+ // coercible string can be more right-ward without the same terminus.
+ const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL]
+ let next
+ while ((next = coerceRtlRegex.exec(version)) &&
+ (!match || match.index + match[0].length !== version.length)
+ ) {
+ if (!match ||
+ next.index + next[0].length !== match.index + match[0].length) {
+ match = next
+ }
+ coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length
}
+ // leave it in a clean state
+ coerceRtlRegex.lastIndex = -1
+ }
- return this[kAgent].dispatch(
- {
- ...opts,
- headers
- },
- handler
- )
+ if (match === null) {
+ return null
}
- /**
- * @param {import('../types/proxy-agent').ProxyAgent.Options | string | URL} opts
- * @returns {URL}
- */
- #getUrl (opts) {
- if (typeof opts === 'string') {
- return new URL(opts)
- } else if (opts instanceof URL) {
- return opts
- } else {
- return new URL(opts.uri)
- }
- }
-
- async [kClose] () {
- await this[kAgent].close()
- await this[kClient].close()
- }
+ const major = match[2]
+ const minor = match[3] || '0'
+ const patch = match[4] || '0'
+ const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : ''
+ const build = options.includePrerelease && match[6] ? `+${match[6]}` : ''
- async [kDestroy] () {
- await this[kAgent].destroy()
- await this[kClient].destroy()
- }
+ return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options)
}
+module.exports = coerce
-/**
- * @param {string[] | Record} headers
- * @returns {Record}
- */
-function buildHeaders (headers) {
- // When using undici.fetch, the headers list is stored
- // as an array.
- if (Array.isArray(headers)) {
- /** @type {Record} */
- const headersPair = {}
- for (let i = 0; i < headers.length; i += 2) {
- headersPair[headers[i]] = headers[i + 1]
- }
+/***/ }),
- return headersPair
- }
+/***/ 7648:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- return headers
-}
-/**
- * @param {Record} headers
- *
- * Previous versions of ProxyAgent suggests the Proxy-Authorization in request headers
- * Nevertheless, it was changed and to avoid a security vulnerability by end users
- * this check was created.
- * It should be removed in the next major version for performance reasons
- */
-function throwIfProxyAuthIsSent (headers) {
- const existProxyAuth = headers && Object.keys(headers)
- .find((key) => key.toLowerCase() === 'proxy-authorization')
- if (existProxyAuth) {
- throw new InvalidArgumentError('Proxy-Authorization should be sent in ProxyAgent constructor')
- }
+
+const SemVer = __nccwpck_require__(7163)
+const compareBuild = (a, b, loose) => {
+ const versionA = new SemVer(a, loose)
+ const versionB = new SemVer(b, loose)
+ return versionA.compare(versionB) || versionA.compareBuild(versionB)
}
+module.exports = compareBuild
-module.exports = ProxyAgent
+
+/***/ }),
+
+/***/ 6874:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const compare = __nccwpck_require__(8469)
+const compareLoose = (a, b) => compare(a, b, true)
+module.exports = compareLoose
/***/ }),
-/***/ 7203:
+/***/ 8469:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const Dispatcher = __nccwpck_require__(9784)
-const RetryHandler = __nccwpck_require__(3783)
+const SemVer = __nccwpck_require__(7163)
+const compare = (a, b, loose) =>
+ new SemVer(a, loose).compare(new SemVer(b, loose))
-class RetryAgent extends Dispatcher {
- #agent = null
- #options = null
- constructor (agent, options = {}) {
- super(options)
- this.#agent = agent
- this.#options = options
+module.exports = compare
+
+
+/***/ }),
+
+/***/ 711:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const parse = __nccwpck_require__(6353)
+
+const diff = (version1, version2) => {
+ const v1 = parse(version1, null, true)
+ const v2 = parse(version2, null, true)
+ const comparison = v1.compare(v2)
+
+ if (comparison === 0) {
+ return null
}
- dispatch (opts, handler) {
- const retry = new RetryHandler({
- ...opts,
- retryOptions: this.#options
- }, {
- dispatch: this.#agent.dispatch.bind(this.#agent),
- handler
- })
- return this.#agent.dispatch(opts, retry)
+ const v1Higher = comparison > 0
+ const highVersion = v1Higher ? v1 : v2
+ const lowVersion = v1Higher ? v2 : v1
+ const highHasPre = !!highVersion.prerelease.length
+ const lowHasPre = !!lowVersion.prerelease.length
+
+ if (lowHasPre && !highHasPre) {
+ // Going from prerelease -> no prerelease requires some special casing
+
+ // If the low version has only a major, then it will always be a major
+ // Some examples:
+ // 1.0.0-1 -> 1.0.0
+ // 1.0.0-1 -> 1.1.1
+ // 1.0.0-1 -> 2.0.0
+ if (!lowVersion.patch && !lowVersion.minor) {
+ return 'major'
+ }
+
+ // If the main part has no difference
+ if (lowVersion.compareMain(highVersion) === 0) {
+ if (lowVersion.minor && !lowVersion.patch) {
+ return 'minor'
+ }
+ return 'patch'
+ }
}
- close () {
- return this.#agent.close()
+ // add the `pre` prefix if we are going to a prerelease version
+ const prefix = highHasPre ? 'pre' : ''
+
+ if (v1.major !== v2.major) {
+ return prefix + 'major'
}
- destroy () {
- return this.#agent.destroy()
+ if (v1.minor !== v2.minor) {
+ return prefix + 'minor'
+ }
+
+ if (v1.patch !== v2.patch) {
+ return prefix + 'patch'
}
+
+ // high and low are prereleases
+ return 'prerelease'
}
-module.exports = RetryAgent
+module.exports = diff
/***/ }),
-/***/ 1088:
+/***/ 5082:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-// We include a version number for the Dispatcher API. In case of breaking changes,
-// this version number must be increased to avoid conflicts.
-const globalDispatcher = Symbol.for('undici.globalDispatcher.1')
-const { InvalidArgumentError } = __nccwpck_require__(2344)
-const Agent = __nccwpck_require__(4332)
+const compare = __nccwpck_require__(8469)
+const eq = (a, b, loose) => compare(a, b, loose) === 0
+module.exports = eq
-if (getGlobalDispatcher() === undefined) {
- setGlobalDispatcher(new Agent())
-}
-function setGlobalDispatcher (agent) {
- if (!agent || typeof agent.dispatch !== 'function') {
- throw new InvalidArgumentError('Argument agent must implement Agent')
- }
- Object.defineProperty(globalThis, globalDispatcher, {
- value: agent,
- writable: true,
- enumerable: false,
- configurable: false
- })
-}
+/***/ }),
-function getGlobalDispatcher () {
- return globalThis[globalDispatcher]
-}
+/***/ 6599:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-module.exports = {
- setGlobalDispatcher,
- getGlobalDispatcher
-}
-/***/ }),
+const compare = __nccwpck_require__(8469)
+const gt = (a, b, loose) => compare(a, b, loose) > 0
+module.exports = gt
-/***/ 9420:
-/***/ ((module) => {
+/***/ }),
+/***/ 1236:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-module.exports = class DecoratorHandler {
- #handler
- constructor (handler) {
- if (typeof handler !== 'object' || handler === null) {
- throw new TypeError('handler must be an object')
- }
- this.#handler = handler
- }
- onConnect (...args) {
- return this.#handler.onConnect?.(...args)
- }
+const compare = __nccwpck_require__(8469)
+const gte = (a, b, loose) => compare(a, b, loose) >= 0
+module.exports = gte
- onError (...args) {
- return this.#handler.onError?.(...args)
- }
- onUpgrade (...args) {
- return this.#handler.onUpgrade?.(...args)
- }
+/***/ }),
- onResponseStarted (...args) {
- return this.#handler.onResponseStarted?.(...args)
- }
+/***/ 2338:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- onHeaders (...args) {
- return this.#handler.onHeaders?.(...args)
- }
- onData (...args) {
- return this.#handler.onData?.(...args)
- }
- onComplete (...args) {
- return this.#handler.onComplete?.(...args)
+const SemVer = __nccwpck_require__(7163)
+
+const inc = (version, release, options, identifier, identifierBase) => {
+ if (typeof (options) === 'string') {
+ identifierBase = identifier
+ identifier = options
+ options = undefined
}
- onBodySent (...args) {
- return this.#handler.onBodySent?.(...args)
+ try {
+ return new SemVer(
+ version instanceof SemVer ? version.version : version,
+ options
+ ).inc(release, identifier, identifierBase).version
+ } catch (er) {
+ return null
}
}
+module.exports = inc
/***/ }),
-/***/ 7031:
+/***/ 3872:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const util = __nccwpck_require__(7375)
-const { kBodyUsed } = __nccwpck_require__(6130)
-const assert = __nccwpck_require__(4589)
-const { InvalidArgumentError } = __nccwpck_require__(2344)
-const EE = __nccwpck_require__(8474)
+const compare = __nccwpck_require__(8469)
+const lt = (a, b, loose) => compare(a, b, loose) < 0
+module.exports = lt
-const redirectableStatusCodes = [300, 301, 302, 303, 307, 308]
-const kBody = Symbol('body')
+/***/ }),
-class BodyAsyncIterable {
- constructor (body) {
- this[kBody] = body
- this[kBodyUsed] = false
- }
+/***/ 6717:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- async * [Symbol.asyncIterator] () {
- assert(!this[kBodyUsed], 'disturbed')
- this[kBodyUsed] = true
- yield * this[kBody]
- }
-}
-class RedirectHandler {
- constructor (dispatch, maxRedirections, opts, handler) {
- if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {
- throw new InvalidArgumentError('maxRedirections must be a positive number')
- }
- util.validateHandler(handler, opts.method, opts.upgrade)
+const compare = __nccwpck_require__(8469)
+const lte = (a, b, loose) => compare(a, b, loose) <= 0
+module.exports = lte
- this.dispatch = dispatch
- this.location = null
- this.abort = null
- this.opts = { ...opts, maxRedirections: 0 } // opts must be a copy
- this.maxRedirections = maxRedirections
- this.handler = handler
- this.history = []
- this.redirectionLimitReached = false
- if (util.isStream(this.opts.body)) {
- // TODO (fix): Provide some way for the user to cache the file to e.g. /tmp
- // so that it can be dispatched again?
- // TODO (fix): Do we need 100-expect support to provide a way to do this properly?
- if (util.bodyLength(this.opts.body) === 0) {
- this.opts.body
- .on('data', function () {
- assert(false)
- })
- }
+/***/ }),
- if (typeof this.opts.body.readableDidRead !== 'boolean') {
- this.opts.body[kBodyUsed] = false
- EE.prototype.on.call(this.opts.body, 'data', function () {
- this[kBodyUsed] = true
- })
- }
- } else if (this.opts.body && typeof this.opts.body.pipeTo === 'function') {
- // TODO (fix): We can't access ReadableStream internal state
- // to determine whether or not it has been disturbed. This is just
- // a workaround.
- this.opts.body = new BodyAsyncIterable(this.opts.body)
- } else if (
- this.opts.body &&
- typeof this.opts.body !== 'string' &&
- !ArrayBuffer.isView(this.opts.body) &&
- util.isIterable(this.opts.body)
- ) {
- // TODO: Should we allow re-using iterable if !this.opts.idempotent
- // or through some other flag?
- this.opts.body = new BodyAsyncIterable(this.opts.body)
- }
- }
+/***/ 8511:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- onConnect (abort) {
- this.abort = abort
- this.handler.onConnect(abort, { history: this.history })
- }
- onUpgrade (statusCode, headers, socket) {
- this.handler.onUpgrade(statusCode, headers, socket)
- }
- onError (error) {
- this.handler.onError(error)
- }
+const SemVer = __nccwpck_require__(7163)
+const major = (a, loose) => new SemVer(a, loose).major
+module.exports = major
- onHeaders (statusCode, headers, resume, statusText) {
- this.location = this.history.length >= this.maxRedirections || util.isDisturbed(this.opts.body)
- ? null
- : parseLocation(statusCode, headers)
- if (this.opts.throwOnMaxRedirect && this.history.length >= this.maxRedirections) {
- if (this.request) {
- this.request.abort(new Error('max redirects'))
- }
+/***/ }),
- this.redirectionLimitReached = true
- this.abort(new Error('max redirects'))
- return
- }
+/***/ 2603:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- if (this.opts.origin) {
- this.history.push(new URL(this.opts.path, this.opts.origin))
- }
- if (!this.location) {
- return this.handler.onHeaders(statusCode, headers, resume, statusText)
- }
- const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin)))
- const path = search ? `${pathname}${search}` : pathname
+const SemVer = __nccwpck_require__(7163)
+const minor = (a, loose) => new SemVer(a, loose).minor
+module.exports = minor
- // Remove headers referring to the original URL.
- // By default it is Host only, unless it's a 303 (see below), which removes also all Content-* headers.
- // https://tools.ietf.org/html/rfc7231#section-6.4
- this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin)
- this.opts.path = path
- this.opts.origin = origin
- this.opts.maxRedirections = 0
- this.opts.query = null
- // https://tools.ietf.org/html/rfc7231#section-6.4.4
- // In case of HTTP 303, always replace method to be either HEAD or GET
- if (statusCode === 303 && this.opts.method !== 'HEAD') {
- this.opts.method = 'GET'
- this.opts.body = null
- }
- }
+/***/ }),
- onData (chunk) {
- if (this.location) {
- /*
- https://tools.ietf.org/html/rfc7231#section-6.4
+/***/ 4974:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- TLDR: undici always ignores 3xx response bodies.
- Redirection is used to serve the requested resource from another URL, so it is assumes that
- no body is generated (and thus can be ignored). Even though generating a body is not prohibited.
- For status 301, 302, 303, 307 and 308 (the latter from RFC 7238), the specs mention that the body usually
- (which means it's optional and not mandated) contain just an hyperlink to the value of
- the Location response header, so the body can be ignored safely.
+const compare = __nccwpck_require__(8469)
+const neq = (a, b, loose) => compare(a, b, loose) !== 0
+module.exports = neq
- For status 300, which is "Multiple Choices", the spec mentions both generating a Location
- response header AND a response body with the other possible location to follow.
- Since the spec explicitly chooses not to specify a format for such body and leave it to
- servers and browsers implementors, we ignore the body as there is no specified way to eventually parse it.
- */
- } else {
- return this.handler.onData(chunk)
- }
- }
- onComplete (trailers) {
- if (this.location) {
- /*
- https://tools.ietf.org/html/rfc7231#section-6.4
+/***/ }),
- TLDR: undici always ignores 3xx response trailers as they are not expected in case of redirections
- and neither are useful if present.
+/***/ 6353:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- See comment on onData method above for more detailed information.
- */
- this.location = null
- this.abort = null
- this.dispatch(this.opts, this)
- } else {
- this.handler.onComplete(trailers)
- }
+const SemVer = __nccwpck_require__(7163)
+const parse = (version, options, throwErrors = false) => {
+ if (version instanceof SemVer) {
+ return version
}
-
- onBodySent (chunk) {
- if (this.handler.onBodySent) {
- this.handler.onBodySent(chunk)
+ try {
+ return new SemVer(version, options)
+ } catch (er) {
+ if (!throwErrors) {
+ return null
}
+ throw er
}
}
-function parseLocation (statusCode, headers) {
- if (redirectableStatusCodes.indexOf(statusCode) === -1) {
- return null
- }
+module.exports = parse
- for (let i = 0; i < headers.length; i += 2) {
- if (headers[i].length === 8 && util.headerNameToString(headers[i]) === 'location') {
- return headers[i + 1]
- }
- }
-}
-// https://tools.ietf.org/html/rfc7231#section-6.4.4
-function shouldRemoveHeader (header, removeContent, unknownOrigin) {
- if (header.length === 4) {
- return util.headerNameToString(header) === 'host'
- }
- if (removeContent && util.headerNameToString(header).startsWith('content-')) {
- return true
- }
- if (unknownOrigin && (header.length === 13 || header.length === 6 || header.length === 19)) {
- const name = util.headerNameToString(header)
- return name === 'authorization' || name === 'cookie' || name === 'proxy-authorization'
- }
- return false
-}
+/***/ }),
-// https://tools.ietf.org/html/rfc7231#section-6.4
-function cleanRequestHeaders (headers, removeContent, unknownOrigin) {
- const ret = []
- if (Array.isArray(headers)) {
- for (let i = 0; i < headers.length; i += 2) {
- if (!shouldRemoveHeader(headers[i], removeContent, unknownOrigin)) {
- ret.push(headers[i], headers[i + 1])
- }
- }
- } else if (headers && typeof headers === 'object') {
- for (const key of Object.keys(headers)) {
- if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) {
- ret.push(key, headers[key])
- }
- }
- } else {
- assert(headers == null, 'headers must be an object or an array')
- }
- return ret
-}
+/***/ 8756:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-module.exports = RedirectHandler
+
+
+const SemVer = __nccwpck_require__(7163)
+const patch = (a, loose) => new SemVer(a, loose).patch
+module.exports = patch
/***/ }),
-/***/ 3783:
+/***/ 5714:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const assert = __nccwpck_require__(4589)
-
-const { kRetryHandlerDefaultRetry } = __nccwpck_require__(6130)
-const { RequestRetryError } = __nccwpck_require__(2344)
-const {
- isDisturbed,
- parseHeaders,
- parseRangeHeader,
- wrapRequestBody
-} = __nccwpck_require__(7375)
-function calculateRetryAfterHeader (retryAfter) {
- const current = Date.now()
- return new Date(retryAfter).getTime() - current
+const parse = __nccwpck_require__(6353)
+const prerelease = (version, options) => {
+ const parsed = parse(version, options)
+ return (parsed && parsed.prerelease.length) ? parsed.prerelease : null
}
+module.exports = prerelease
-class RetryHandler {
- constructor (opts, handlers) {
- const { retryOptions, ...dispatchOpts } = opts
- const {
- // Retry scoped
- retry: retryFn,
- maxRetries,
- maxTimeout,
- minTimeout,
- timeoutFactor,
- // Response scoped
- methods,
- errorCodes,
- retryAfter,
- statusCodes
- } = retryOptions ?? {}
- this.dispatch = handlers.dispatch
- this.handler = handlers.handler
- this.opts = { ...dispatchOpts, body: wrapRequestBody(opts.body) }
- this.abort = null
- this.aborted = false
- this.retryOpts = {
- retry: retryFn ?? RetryHandler[kRetryHandlerDefaultRetry],
- retryAfter: retryAfter ?? true,
- maxTimeout: maxTimeout ?? 30 * 1000, // 30s,
- minTimeout: minTimeout ?? 500, // .5s
- timeoutFactor: timeoutFactor ?? 2,
- maxRetries: maxRetries ?? 5,
- // What errors we should retry
- methods: methods ?? ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE'],
- // Indicates which errors to retry
- statusCodes: statusCodes ?? [500, 502, 503, 504, 429],
- // List of errors to retry
- errorCodes: errorCodes ?? [
- 'ECONNRESET',
- 'ECONNREFUSED',
- 'ENOTFOUND',
- 'ENETDOWN',
- 'ENETUNREACH',
- 'EHOSTDOWN',
- 'EHOSTUNREACH',
- 'EPIPE',
- 'UND_ERR_SOCKET'
- ]
- }
+/***/ }),
- this.retryCount = 0
- this.retryCountCheckpoint = 0
- this.start = 0
- this.end = null
- this.etag = null
- this.resume = null
+/***/ 2173:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // Handle possible onConnect duplication
- this.handler.onConnect(reason => {
- this.aborted = true
- if (this.abort) {
- this.abort(reason)
- } else {
- this.reason = reason
- }
- })
- }
- onRequestSent () {
- if (this.handler.onRequestSent) {
- this.handler.onRequestSent()
- }
- }
- onUpgrade (statusCode, headers, socket) {
- if (this.handler.onUpgrade) {
- this.handler.onUpgrade(statusCode, headers, socket)
- }
- }
+const compare = __nccwpck_require__(8469)
+const rcompare = (a, b, loose) => compare(b, a, loose)
+module.exports = rcompare
- onConnect (abort) {
- if (this.aborted) {
- abort(this.reason)
- } else {
- this.abort = abort
- }
- }
- onBodySent (chunk) {
- if (this.handler.onBodySent) return this.handler.onBodySent(chunk)
- }
+/***/ }),
- static [kRetryHandlerDefaultRetry] (err, { state, opts }, cb) {
- const { statusCode, code, headers } = err
- const { method, retryOptions } = opts
- const {
- maxRetries,
- minTimeout,
- maxTimeout,
- timeoutFactor,
- statusCodes,
- errorCodes,
- methods
- } = retryOptions
- const { counter } = state
+/***/ 7192:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // Any code that is not a Undici's originated and allowed to retry
- if (code && code !== 'UND_ERR_REQ_RETRY' && !errorCodes.includes(code)) {
- cb(err)
- return
- }
- // If a set of method are provided and the current method is not in the list
- if (Array.isArray(methods) && !methods.includes(method)) {
- cb(err)
- return
- }
- // If a set of status code are provided and the current status code is not in the list
- if (
- statusCode != null &&
- Array.isArray(statusCodes) &&
- !statusCodes.includes(statusCode)
- ) {
- cb(err)
- return
- }
+const compareBuild = __nccwpck_require__(7648)
+const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose))
+module.exports = rsort
- // If we reached the max number of retries
- if (counter > maxRetries) {
- cb(err)
- return
- }
- let retryAfterHeader = headers?.['retry-after']
- if (retryAfterHeader) {
- retryAfterHeader = Number(retryAfterHeader)
- retryAfterHeader = Number.isNaN(retryAfterHeader)
- ? calculateRetryAfterHeader(retryAfterHeader)
- : retryAfterHeader * 1e3 // Retry-After is in seconds
- }
+/***/ }),
- const retryTimeout =
- retryAfterHeader > 0
- ? Math.min(retryAfterHeader, maxTimeout)
- : Math.min(minTimeout * timeoutFactor ** (counter - 1), maxTimeout)
+/***/ 8011:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- setTimeout(() => cb(null), retryTimeout)
+
+
+const Range = __nccwpck_require__(6782)
+const satisfies = (version, range, options) => {
+ try {
+ range = new Range(range, options)
+ } catch (er) {
+ return false
}
+ return range.test(version)
+}
+module.exports = satisfies
- onHeaders (statusCode, rawHeaders, resume, statusMessage) {
- const headers = parseHeaders(rawHeaders)
- this.retryCount += 1
+/***/ }),
- if (statusCode >= 300) {
- if (this.retryOpts.statusCodes.includes(statusCode) === false) {
- return this.handler.onHeaders(
- statusCode,
- rawHeaders,
- resume,
- statusMessage
- )
- } else {
- this.abort(
- new RequestRetryError('Request failed', statusCode, {
- headers,
- data: {
- count: this.retryCount
- }
- })
- )
- return false
- }
- }
+/***/ 9872:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // Checkpoint for resume from where we left it
- if (this.resume != null) {
- this.resume = null
- // Only Partial Content 206 supposed to provide Content-Range,
- // any other status code that partially consumed the payload
- // should not be retry because it would result in downstream
- // wrongly concatanete multiple responses.
- if (statusCode !== 206 && (this.start > 0 || statusCode !== 200)) {
- this.abort(
- new RequestRetryError('server does not support the range header and the payload was partially consumed', statusCode, {
- headers,
- data: { count: this.retryCount }
- })
- )
- return false
- }
- const contentRange = parseRangeHeader(headers['content-range'])
- // If no content range
- if (!contentRange) {
- this.abort(
- new RequestRetryError('Content-Range mismatch', statusCode, {
- headers,
- data: { count: this.retryCount }
- })
- )
- return false
- }
+const compareBuild = __nccwpck_require__(7648)
+const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose))
+module.exports = sort
- // Let's start with a weak etag check
- if (this.etag != null && this.etag !== headers.etag) {
- this.abort(
- new RequestRetryError('ETag mismatch', statusCode, {
- headers,
- data: { count: this.retryCount }
- })
- )
- return false
- }
- const { start, size, end = size - 1 } = contentRange
+/***/ }),
- assert(this.start === start, 'content-range mismatch')
- assert(this.end == null || this.end === end, 'content-range mismatch')
+/***/ 8780:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- this.resume = resume
- return true
- }
- if (this.end == null) {
- if (statusCode === 206) {
- // First time we receive 206
- const range = parseRangeHeader(headers['content-range'])
- if (range == null) {
- return this.handler.onHeaders(
- statusCode,
- rawHeaders,
- resume,
- statusMessage
- )
- }
+const parse = __nccwpck_require__(6353)
+const valid = (version, options) => {
+ const v = parse(version, options)
+ return v ? v.version : null
+}
+module.exports = valid
- const { start, size, end = size - 1 } = range
- assert(
- start != null && Number.isFinite(start),
- 'content-range mismatch'
- )
- assert(end != null && Number.isFinite(end), 'invalid content-length')
- this.start = start
- this.end = end
- }
+/***/ }),
- // We make our best to checkpoint the body for further range headers
- if (this.end == null) {
- const contentLength = headers['content-length']
- this.end = contentLength != null ? Number(contentLength) - 1 : null
- }
+/***/ 2088:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- assert(Number.isFinite(this.start))
- assert(
- this.end == null || Number.isFinite(this.end),
- 'invalid content-length'
- )
- this.resume = resume
- this.etag = headers.etag != null ? headers.etag : null
- // Weak etags are not useful for comparison nor cache
- // for instance not safe to assume if the response is byte-per-byte
- // equal
- if (this.etag != null && this.etag.startsWith('W/')) {
- this.etag = null
- }
+// just pre-load all the stuff that index.js lazily exports
+const internalRe = __nccwpck_require__(5471)
+const constants = __nccwpck_require__(5101)
+const SemVer = __nccwpck_require__(7163)
+const identifiers = __nccwpck_require__(3348)
+const parse = __nccwpck_require__(6353)
+const valid = __nccwpck_require__(8780)
+const clean = __nccwpck_require__(1799)
+const inc = __nccwpck_require__(2338)
+const diff = __nccwpck_require__(711)
+const major = __nccwpck_require__(8511)
+const minor = __nccwpck_require__(2603)
+const patch = __nccwpck_require__(8756)
+const prerelease = __nccwpck_require__(5714)
+const compare = __nccwpck_require__(8469)
+const rcompare = __nccwpck_require__(2173)
+const compareLoose = __nccwpck_require__(6874)
+const compareBuild = __nccwpck_require__(7648)
+const sort = __nccwpck_require__(9872)
+const rsort = __nccwpck_require__(7192)
+const gt = __nccwpck_require__(6599)
+const lt = __nccwpck_require__(3872)
+const eq = __nccwpck_require__(5082)
+const neq = __nccwpck_require__(4974)
+const gte = __nccwpck_require__(1236)
+const lte = __nccwpck_require__(6717)
+const cmp = __nccwpck_require__(8646)
+const coerce = __nccwpck_require__(5385)
+const Comparator = __nccwpck_require__(9379)
+const Range = __nccwpck_require__(6782)
+const satisfies = __nccwpck_require__(8011)
+const toComparators = __nccwpck_require__(4750)
+const maxSatisfying = __nccwpck_require__(5574)
+const minSatisfying = __nccwpck_require__(8595)
+const minVersion = __nccwpck_require__(1866)
+const validRange = __nccwpck_require__(4737)
+const outside = __nccwpck_require__(280)
+const gtr = __nccwpck_require__(2276)
+const ltr = __nccwpck_require__(5213)
+const intersects = __nccwpck_require__(3465)
+const simplifyRange = __nccwpck_require__(2028)
+const subset = __nccwpck_require__(1489)
+module.exports = {
+ parse,
+ valid,
+ clean,
+ inc,
+ diff,
+ major,
+ minor,
+ patch,
+ prerelease,
+ compare,
+ rcompare,
+ compareLoose,
+ compareBuild,
+ sort,
+ rsort,
+ gt,
+ lt,
+ eq,
+ neq,
+ gte,
+ lte,
+ cmp,
+ coerce,
+ Comparator,
+ Range,
+ satisfies,
+ toComparators,
+ maxSatisfying,
+ minSatisfying,
+ minVersion,
+ validRange,
+ outside,
+ gtr,
+ ltr,
+ intersects,
+ simplifyRange,
+ subset,
+ SemVer,
+ re: internalRe.re,
+ src: internalRe.src,
+ tokens: internalRe.t,
+ SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION,
+ RELEASE_TYPES: constants.RELEASE_TYPES,
+ compareIdentifiers: identifiers.compareIdentifiers,
+ rcompareIdentifiers: identifiers.rcompareIdentifiers,
+}
- return this.handler.onHeaders(
- statusCode,
- rawHeaders,
- resume,
- statusMessage
- )
- }
- const err = new RequestRetryError('Request failed', statusCode, {
- headers,
- data: { count: this.retryCount }
- })
+/***/ }),
- this.abort(err)
+/***/ 5101:
+/***/ ((module) => {
- return false
- }
- onData (chunk) {
- this.start += chunk.length
- return this.handler.onData(chunk)
- }
+// Note: this is the semver.org version of the spec that it implements
+// Not necessarily the package version of this code.
+const SEMVER_SPEC_VERSION = '2.0.0'
- onComplete (rawTrailers) {
- this.retryCount = 0
- return this.handler.onComplete(rawTrailers)
- }
+const MAX_LENGTH = 256
+const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
+/* istanbul ignore next */ 9007199254740991
- onError (err) {
- if (this.aborted || isDisturbed(this.opts.body)) {
- return this.handler.onError(err)
- }
+// Max safe segment length for coercion.
+const MAX_SAFE_COMPONENT_LENGTH = 16
- // We reconcile in case of a mix between network errors
- // and server error response
- if (this.retryCount - this.retryCountCheckpoint > 0) {
- // We count the difference between the last checkpoint and the current retry count
- this.retryCount =
- this.retryCountCheckpoint +
- (this.retryCount - this.retryCountCheckpoint)
- } else {
- this.retryCount += 1
- }
+// Max safe length for a build identifier. The max length minus 6 characters for
+// the shortest version with a build 0.0.0+BUILD.
+const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6
- this.retryOpts.retry(
- err,
- {
- state: { counter: this.retryCount },
- opts: { retryOptions: this.retryOpts, ...this.opts }
- },
- onRetry.bind(this)
- )
+const RELEASE_TYPES = [
+ 'major',
+ 'premajor',
+ 'minor',
+ 'preminor',
+ 'patch',
+ 'prepatch',
+ 'prerelease',
+]
- function onRetry (err) {
- if (err != null || this.aborted || isDisturbed(this.opts.body)) {
- return this.handler.onError(err)
- }
+module.exports = {
+ MAX_LENGTH,
+ MAX_SAFE_COMPONENT_LENGTH,
+ MAX_SAFE_BUILD_LENGTH,
+ MAX_SAFE_INTEGER,
+ RELEASE_TYPES,
+ SEMVER_SPEC_VERSION,
+ FLAG_INCLUDE_PRERELEASE: 0b001,
+ FLAG_LOOSE: 0b010,
+}
- if (this.start !== 0) {
- const headers = { range: `bytes=${this.start}-${this.end ?? ''}` }
- // Weak etag check - weak etags will make comparison algorithms never match
- if (this.etag != null) {
- headers['if-match'] = this.etag
- }
+/***/ }),
- this.opts = {
- ...this.opts,
- headers: {
- ...this.opts.headers,
- ...headers
- }
- }
- }
+/***/ 1159:
+/***/ ((module) => {
- try {
- this.retryCountCheckpoint = this.retryCount
- this.dispatch(this.opts, this)
- } catch (err) {
- this.handler.onError(err)
- }
- }
- }
-}
-module.exports = RetryHandler
+const debug = (
+ typeof process === 'object' &&
+ process.env &&
+ process.env.NODE_DEBUG &&
+ /\bsemver\b/i.test(process.env.NODE_DEBUG)
+) ? (...args) => console.error('SEMVER', ...args)
+ : () => {}
-/***/ }),
+module.exports = debug
-/***/ 5663:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ }),
-const { isIP } = __nccwpck_require__(7030)
-const { lookup } = __nccwpck_require__(610)
-const DecoratorHandler = __nccwpck_require__(9420)
-const { InvalidArgumentError, InformationalError } = __nccwpck_require__(2344)
-const maxInt = Math.pow(2, 31) - 1
+/***/ 3348:
+/***/ ((module) => {
-class DNSInstance {
- #maxTTL = 0
- #maxItems = 0
- #records = new Map()
- dualStack = true
- affinity = null
- lookup = null
- pick = null
- constructor (opts) {
- this.#maxTTL = opts.maxTTL
- this.#maxItems = opts.maxItems
- this.dualStack = opts.dualStack
- this.affinity = opts.affinity
- this.lookup = opts.lookup ?? this.#defaultLookup
- this.pick = opts.pick ?? this.#defaultPick
- }
- get full () {
- return this.#records.size === this.#maxItems
+const numeric = /^[0-9]+$/
+const compareIdentifiers = (a, b) => {
+ if (typeof a === 'number' && typeof b === 'number') {
+ return a === b ? 0 : a < b ? -1 : 1
}
- runLookup (origin, opts, cb) {
- const ips = this.#records.get(origin.hostname)
+ const anum = numeric.test(a)
+ const bnum = numeric.test(b)
- // If full, we just return the origin
- if (ips == null && this.full) {
- cb(null, origin.origin)
- return
- }
+ if (anum && bnum) {
+ a = +a
+ b = +b
+ }
- const newOpts = {
- affinity: this.affinity,
- dualStack: this.dualStack,
- lookup: this.lookup,
- pick: this.pick,
- ...opts.dns,
- maxTTL: this.#maxTTL,
- maxItems: this.#maxItems
- }
+ return a === b ? 0
+ : (anum && !bnum) ? -1
+ : (bnum && !anum) ? 1
+ : a < b ? -1
+ : 1
+}
- // If no IPs we lookup
- if (ips == null) {
- this.lookup(origin, newOpts, (err, addresses) => {
- if (err || addresses == null || addresses.length === 0) {
- cb(err ?? new InformationalError('No DNS entries found'))
- return
- }
+const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a)
- this.setRecords(origin, addresses)
- const records = this.#records.get(origin.hostname)
+module.exports = {
+ compareIdentifiers,
+ rcompareIdentifiers,
+}
- const ip = this.pick(
- origin,
- records,
- newOpts.affinity
- )
- let port
- if (typeof ip.port === 'number') {
- port = `:${ip.port}`
- } else if (origin.port !== '') {
- port = `:${origin.port}`
- } else {
- port = ''
- }
+/***/ }),
- cb(
- null,
- `${origin.protocol}//${
- ip.family === 6 ? `[${ip.address}]` : ip.address
- }${port}`
- )
- })
- } else {
- // If there's IPs we pick
- const ip = this.pick(
- origin,
- ips,
- newOpts.affinity
- )
+/***/ 1383:
+/***/ ((module) => {
- // If no IPs we lookup - deleting old records
- if (ip == null) {
- this.#records.delete(origin.hostname)
- this.runLookup(origin, opts, cb)
- return
- }
- let port
- if (typeof ip.port === 'number') {
- port = `:${ip.port}`
- } else if (origin.port !== '') {
- port = `:${origin.port}`
- } else {
- port = ''
- }
- cb(
- null,
- `${origin.protocol}//${
- ip.family === 6 ? `[${ip.address}]` : ip.address
- }${port}`
- )
- }
+class LRUCache {
+ constructor () {
+ this.max = 1000
+ this.map = new Map()
}
- #defaultLookup (origin, opts, cb) {
- lookup(
- origin.hostname,
- {
- all: true,
- family: this.dualStack === false ? this.affinity : 0,
- order: 'ipv4first'
- },
- (err, addresses) => {
- if (err) {
- return cb(err)
- }
-
- const results = new Map()
-
- for (const addr of addresses) {
- // On linux we found duplicates, we attempt to remove them with
- // the latest record
- results.set(`${addr.address}:${addr.family}`, addr)
- }
-
- cb(null, results.values())
- }
- )
+ get (key) {
+ const value = this.map.get(key)
+ if (value === undefined) {
+ return undefined
+ } else {
+ // Remove the key from the map and add it to the end
+ this.map.delete(key)
+ this.map.set(key, value)
+ return value
+ }
}
- #defaultPick (origin, hostnameRecords, affinity) {
- let ip = null
- const { records, offset } = hostnameRecords
+ delete (key) {
+ return this.map.delete(key)
+ }
- let family
- if (this.dualStack) {
- if (affinity == null) {
- // Balance between ip families
- if (offset == null || offset === maxInt) {
- hostnameRecords.offset = 0
- affinity = 4
- } else {
- hostnameRecords.offset++
- affinity = (hostnameRecords.offset & 1) === 1 ? 6 : 4
- }
- }
+ set (key, value) {
+ const deleted = this.delete(key)
- if (records[affinity] != null && records[affinity].ips.length > 0) {
- family = records[affinity]
- } else {
- family = records[affinity === 4 ? 6 : 4]
+ if (!deleted && value !== undefined) {
+ // If cache is full, delete the least recently used item
+ if (this.map.size >= this.max) {
+ const firstKey = this.map.keys().next().value
+ this.delete(firstKey)
}
- } else {
- family = records[affinity]
- }
-
- // If no IPs we return null
- if (family == null || family.ips.length === 0) {
- return ip
- }
- if (family.offset == null || family.offset === maxInt) {
- family.offset = 0
- } else {
- family.offset++
+ this.map.set(key, value)
}
- const position = family.offset % family.ips.length
- ip = family.ips[position] ?? null
+ return this
+ }
+}
- if (ip == null) {
- return ip
- }
+module.exports = LRUCache
- if (Date.now() - ip.timestamp > ip.ttl) { // record TTL is already in ms
- // We delete expired records
- // It is possible that they have different TTL, so we manage them individually
- family.ips.splice(position, 1)
- return this.pick(origin, hostnameRecords, affinity)
- }
- return ip
- }
+/***/ }),
- setRecords (origin, addresses) {
- const timestamp = Date.now()
- const records = { records: { 4: null, 6: null } }
- for (const record of addresses) {
- record.timestamp = timestamp
- if (typeof record.ttl === 'number') {
- // The record TTL is expected to be in ms
- record.ttl = Math.min(record.ttl, this.#maxTTL)
- } else {
- record.ttl = this.#maxTTL
- }
+/***/ 356:
+/***/ ((module) => {
- const familyRecords = records.records[record.family] ?? { ips: [] }
- familyRecords.ips.push(record)
- records.records[record.family] = familyRecords
- }
- this.#records.set(origin.hostname, records)
+// parse out just the options we care about
+const looseOption = Object.freeze({ loose: true })
+const emptyOpts = Object.freeze({ })
+const parseOptions = options => {
+ if (!options) {
+ return emptyOpts
}
- getHandler (meta, opts) {
- return new DNSDispatchHandler(this, meta, opts)
+ if (typeof options !== 'object') {
+ return looseOption
}
+
+ return options
}
+module.exports = parseOptions
-class DNSDispatchHandler extends DecoratorHandler {
- #state = null
- #opts = null
- #dispatch = null
- #handler = null
- #origin = null
- constructor (state, { origin, handler, dispatch }, opts) {
- super(handler)
- this.#origin = origin
- this.#handler = handler
- this.#opts = { ...opts }
- this.#state = state
- this.#dispatch = dispatch
- }
+/***/ }),
- onError (err) {
- switch (err.code) {
- case 'ETIMEDOUT':
- case 'ECONNREFUSED': {
- if (this.#state.dualStack) {
- // We delete the record and retry
- this.#state.runLookup(this.#origin, this.#opts, (err, newOrigin) => {
- if (err) {
- return this.#handler.onError(err)
- }
+/***/ 5471:
+/***/ ((module, exports, __nccwpck_require__) => {
- const dispatchOpts = {
- ...this.#opts,
- origin: newOrigin
- }
- this.#dispatch(dispatchOpts, this)
- })
- // if dual-stack disabled, we error out
- return
- }
+const {
+ MAX_SAFE_COMPONENT_LENGTH,
+ MAX_SAFE_BUILD_LENGTH,
+ MAX_LENGTH,
+} = __nccwpck_require__(5101)
+const debug = __nccwpck_require__(1159)
+exports = module.exports = {}
- this.#handler.onError(err)
- return
- }
- case 'ENOTFOUND':
- this.#state.deleteRecord(this.#origin)
- // eslint-disable-next-line no-fallthrough
- default:
- this.#handler.onError(err)
- break
- }
- }
-}
+// The actual regexps go on exports.re
+const re = exports.re = []
+const safeRe = exports.safeRe = []
+const src = exports.src = []
+const safeSrc = exports.safeSrc = []
+const t = exports.t = {}
+let R = 0
-module.exports = interceptorOpts => {
- if (
- interceptorOpts?.maxTTL != null &&
- (typeof interceptorOpts?.maxTTL !== 'number' || interceptorOpts?.maxTTL < 0)
- ) {
- throw new InvalidArgumentError('Invalid maxTTL. Must be a positive number')
- }
+const LETTERDASHNUMBER = '[a-zA-Z0-9-]'
- if (
- interceptorOpts?.maxItems != null &&
- (typeof interceptorOpts?.maxItems !== 'number' ||
- interceptorOpts?.maxItems < 1)
- ) {
- throw new InvalidArgumentError(
- 'Invalid maxItems. Must be a positive number and greater than zero'
- )
- }
+// Replace some greedy regex tokens to prevent regex dos issues. These regex are
+// used internally via the safeRe object since all inputs in this library get
+// normalized first to trim and collapse all extra whitespace. The original
+// regexes are exported for userland consumption and lower level usage. A
+// future breaking change could export the safer regex only with a note that
+// all input should have extra whitespace removed.
+const safeRegexReplacements = [
+ ['\\s', 1],
+ ['\\d', MAX_LENGTH],
+ [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH],
+]
- if (
- interceptorOpts?.affinity != null &&
- interceptorOpts?.affinity !== 4 &&
- interceptorOpts?.affinity !== 6
- ) {
- throw new InvalidArgumentError('Invalid affinity. Must be either 4 or 6')
+const makeSafeRegex = (value) => {
+ for (const [token, max] of safeRegexReplacements) {
+ value = value
+ .split(`${token}*`).join(`${token}{0,${max}}`)
+ .split(`${token}+`).join(`${token}{1,${max}}`)
}
+ return value
+}
- if (
- interceptorOpts?.dualStack != null &&
- typeof interceptorOpts?.dualStack !== 'boolean'
- ) {
- throw new InvalidArgumentError('Invalid dualStack. Must be a boolean')
- }
+const createToken = (name, value, isGlobal) => {
+ const safe = makeSafeRegex(value)
+ const index = R++
+ debug(name, index, value)
+ t[name] = index
+ src[index] = value
+ safeSrc[index] = safe
+ re[index] = new RegExp(value, isGlobal ? 'g' : undefined)
+ safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined)
+}
- if (
- interceptorOpts?.lookup != null &&
- typeof interceptorOpts?.lookup !== 'function'
- ) {
- throw new InvalidArgumentError('Invalid lookup. Must be a function')
- }
+// The following Regular Expressions can be used for tokenizing,
+// validating, and parsing SemVer version strings.
- if (
- interceptorOpts?.pick != null &&
- typeof interceptorOpts?.pick !== 'function'
- ) {
- throw new InvalidArgumentError('Invalid pick. Must be a function')
- }
+// ## Numeric Identifier
+// A single `0`, or a non-zero digit followed by zero or more digits.
- const dualStack = interceptorOpts?.dualStack ?? true
- let affinity
- if (dualStack) {
- affinity = interceptorOpts?.affinity ?? null
- } else {
- affinity = interceptorOpts?.affinity ?? 4
- }
+createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*')
+createToken('NUMERICIDENTIFIERLOOSE', '\\d+')
- const opts = {
- maxTTL: interceptorOpts?.maxTTL ?? 10e3, // Expressed in ms
- lookup: interceptorOpts?.lookup ?? null,
- pick: interceptorOpts?.pick ?? null,
- dualStack,
- affinity,
- maxItems: interceptorOpts?.maxItems ?? Infinity
- }
+// ## Non-numeric Identifier
+// Zero or more digits, followed by a letter or hyphen, and then zero or
+// more letters, digits, or hyphens.
- const instance = new DNSInstance(opts)
+createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`)
- return dispatch => {
- return function dnsInterceptor (origDispatchOpts, handler) {
- const origin =
- origDispatchOpts.origin.constructor === URL
- ? origDispatchOpts.origin
- : new URL(origDispatchOpts.origin)
+// ## Main Version
+// Three dot-separated numeric identifiers.
- if (isIP(origin.hostname) !== 0) {
- return dispatch(origDispatchOpts, handler)
- }
+createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` +
+ `(${src[t.NUMERICIDENTIFIER]})\\.` +
+ `(${src[t.NUMERICIDENTIFIER]})`)
- instance.runLookup(origin, origDispatchOpts, (err, newOrigin) => {
- if (err) {
- return handler.onError(err)
- }
+createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
+ `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
+ `(${src[t.NUMERICIDENTIFIERLOOSE]})`)
- let dispatchOpts = null
- dispatchOpts = {
- ...origDispatchOpts,
- servername: origin.hostname, // For SNI on TLS
- origin: newOrigin,
- headers: {
- host: origin.hostname,
- ...origDispatchOpts.headers
- }
- }
+// ## Pre-release Version Identifier
+// A numeric identifier, or a non-numeric identifier.
+// Non-numeric identifiers include numeric identifiers but can be longer.
+// Therefore non-numeric identifiers must go first.
- dispatch(
- dispatchOpts,
- instance.getHandler({ origin, dispatch, handler }, origDispatchOpts)
- )
- })
+createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NONNUMERICIDENTIFIER]
+}|${src[t.NUMERICIDENTIFIER]})`)
- return true
- }
- }
-}
+createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NONNUMERICIDENTIFIER]
+}|${src[t.NUMERICIDENTIFIERLOOSE]})`)
+// ## Pre-release Version
+// Hyphen, followed by one or more dot-separated pre-release version
+// identifiers.
-/***/ }),
+createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]
+}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`)
-/***/ 5057:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]
+}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`)
+// ## Build Metadata Identifier
+// Any combination of digits, letters, or hyphens.
+createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`)
-const util = __nccwpck_require__(7375)
-const { InvalidArgumentError, RequestAbortedError } = __nccwpck_require__(2344)
-const DecoratorHandler = __nccwpck_require__(9420)
+// ## Build Metadata
+// Plus sign, followed by one or more period-separated build metadata
+// identifiers.
-class DumpHandler extends DecoratorHandler {
- #maxSize = 1024 * 1024
- #abort = null
- #dumped = false
- #aborted = false
- #size = 0
- #reason = null
- #handler = null
+createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER]
+}(?:\\.${src[t.BUILDIDENTIFIER]})*))`)
- constructor ({ maxSize }, handler) {
- super(handler)
+// ## Full Version String
+// A main version, followed optionally by a pre-release version and
+// build metadata.
- if (maxSize != null && (!Number.isFinite(maxSize) || maxSize < 1)) {
- throw new InvalidArgumentError('maxSize must be a number greater than 0')
- }
+// Note that the only major, minor, patch, and pre-release sections of
+// the version string are capturing groups. The build metadata is not a
+// capturing group, because it should not ever be used in version
+// comparison.
- this.#maxSize = maxSize ?? this.#maxSize
- this.#handler = handler
- }
+createToken('FULLPLAIN', `v?${src[t.MAINVERSION]
+}${src[t.PRERELEASE]}?${
+ src[t.BUILD]}?`)
- onConnect (abort) {
- this.#abort = abort
+createToken('FULL', `^${src[t.FULLPLAIN]}$`)
- this.#handler.onConnect(this.#customAbort.bind(this))
- }
+// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
+// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
+// common in the npm registry.
+createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE]
+}${src[t.PRERELEASELOOSE]}?${
+ src[t.BUILD]}?`)
- #customAbort (reason) {
- this.#aborted = true
- this.#reason = reason
- }
+createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`)
- // TODO: will require adjustment after new hooks are out
- onHeaders (statusCode, rawHeaders, resume, statusMessage) {
- const headers = util.parseHeaders(rawHeaders)
- const contentLength = headers['content-length']
+createToken('GTLT', '((?:<|>)?=?)')
- if (contentLength != null && contentLength > this.#maxSize) {
- throw new RequestAbortedError(
- `Response size (${contentLength}) larger than maxSize (${
- this.#maxSize
- })`
- )
- }
+// Something like "2.*" or "1.2.x".
+// Note that "x.x" is a valid xRange identifer, meaning "any version"
+// Only the first item is strictly required.
+createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`)
+createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`)
- if (this.#aborted) {
- return true
- }
+createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` +
+ `(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
+ `(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
+ `(?:${src[t.PRERELEASE]})?${
+ src[t.BUILD]}?` +
+ `)?)?`)
- return this.#handler.onHeaders(
- statusCode,
- rawHeaders,
- resume,
- statusMessage
- )
- }
+createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +
+ `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
+ `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
+ `(?:${src[t.PRERELEASELOOSE]})?${
+ src[t.BUILD]}?` +
+ `)?)?`)
- onError (err) {
- if (this.#dumped) {
- return
- }
+createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`)
+createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`)
- err = this.#reason ?? err
+// Coercion.
+// Extract anything that could conceivably be a part of a valid semver
+createToken('COERCEPLAIN', `${'(^|[^\\d])' +
+ '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +
+ `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +
+ `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`)
+createToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\d])`)
+createToken('COERCEFULL', src[t.COERCEPLAIN] +
+ `(?:${src[t.PRERELEASE]})?` +
+ `(?:${src[t.BUILD]})?` +
+ `(?:$|[^\\d])`)
+createToken('COERCERTL', src[t.COERCE], true)
+createToken('COERCERTLFULL', src[t.COERCEFULL], true)
- this.#handler.onError(err)
- }
+// Tilde ranges.
+// Meaning is "reasonably at or greater than"
+createToken('LONETILDE', '(?:~>?)')
- onData (chunk) {
- this.#size = this.#size + chunk.length
+createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true)
+exports.tildeTrimReplace = '$1~'
- if (this.#size >= this.#maxSize) {
- this.#dumped = true
+createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`)
+createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`)
- if (this.#aborted) {
- this.#handler.onError(this.#reason)
- } else {
- this.#handler.onComplete([])
+// Caret ranges.
+// Meaning is "at least and backwards compatible with"
+createToken('LONECARET', '(?:\\^)')
+
+createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true)
+exports.caretTrimReplace = '$1^'
+
+createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`)
+createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`)
+
+// A simple gt/lt/eq thing, or just "" to indicate "any version"
+createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`)
+createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`)
+
+// An expression to strip any whitespace between the gtlt and the thing
+// it modifies, so that `> 1.2.3` ==> `>1.2.3`
+createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT]
+}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true)
+exports.comparatorTrimReplace = '$1$2$3'
+
+// Something like `1.2.3 - 1.2.4`
+// Note that these all use the loose form, because they'll be
+// checked against either the strict or loose comparator form
+// later.
+createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` +
+ `\\s+-\\s+` +
+ `(${src[t.XRANGEPLAIN]})` +
+ `\\s*$`)
+
+createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` +
+ `\\s+-\\s+` +
+ `(${src[t.XRANGEPLAINLOOSE]})` +
+ `\\s*$`)
+
+// Star ranges basically just allow anything at all.
+createToken('STAR', '(<|>)?=?\\s*\\*')
+// >=0.0.0 is like a star
+createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$')
+createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$')
+
+
+/***/ }),
+
+/***/ 2276:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+// Determine if version is greater than all the versions possible in the range.
+const outside = __nccwpck_require__(280)
+const gtr = (version, range, options) => outside(version, range, '>', options)
+module.exports = gtr
+
+
+/***/ }),
+
+/***/ 3465:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const Range = __nccwpck_require__(6782)
+const intersects = (r1, r2, options) => {
+ r1 = new Range(r1, options)
+ r2 = new Range(r2, options)
+ return r1.intersects(r2, options)
+}
+module.exports = intersects
+
+
+/***/ }),
+
+/***/ 5213:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const outside = __nccwpck_require__(280)
+// Determine if version is less than all the versions possible in the range
+const ltr = (version, range, options) => outside(version, range, '<', options)
+module.exports = ltr
+
+
+/***/ }),
+
+/***/ 5574:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const SemVer = __nccwpck_require__(7163)
+const Range = __nccwpck_require__(6782)
+
+const maxSatisfying = (versions, range, options) => {
+ let max = null
+ let maxSV = null
+ let rangeObj = null
+ try {
+ rangeObj = new Range(range, options)
+ } catch (er) {
+ return null
+ }
+ versions.forEach((v) => {
+ if (rangeObj.test(v)) {
+ // satisfies(v, range, options)
+ if (!max || maxSV.compare(v) === -1) {
+ // compare(max, v, true)
+ max = v
+ maxSV = new SemVer(max, options)
}
}
+ })
+ return max
+}
+module.exports = maxSatisfying
- return true
- }
- onComplete (trailers) {
- if (this.#dumped) {
- return
- }
+/***/ }),
- if (this.#aborted) {
- this.#handler.onError(this.reason)
- return
- }
+/***/ 8595:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- this.#handler.onComplete(trailers)
+
+
+const SemVer = __nccwpck_require__(7163)
+const Range = __nccwpck_require__(6782)
+const minSatisfying = (versions, range, options) => {
+ let min = null
+ let minSV = null
+ let rangeObj = null
+ try {
+ rangeObj = new Range(range, options)
+ } catch (er) {
+ return null
}
+ versions.forEach((v) => {
+ if (rangeObj.test(v)) {
+ // satisfies(v, range, options)
+ if (!min || minSV.compare(v) === 1) {
+ // compare(min, v, true)
+ min = v
+ minSV = new SemVer(min, options)
+ }
+ }
+ })
+ return min
}
+module.exports = minSatisfying
-function createDumpInterceptor (
- { maxSize: defaultMaxSize } = {
- maxSize: 1024 * 1024
+
+/***/ }),
+
+/***/ 1866:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const SemVer = __nccwpck_require__(7163)
+const Range = __nccwpck_require__(6782)
+const gt = __nccwpck_require__(6599)
+
+const minVersion = (range, loose) => {
+ range = new Range(range, loose)
+
+ let minver = new SemVer('0.0.0')
+ if (range.test(minver)) {
+ return minver
}
-) {
- return dispatch => {
- return function Intercept (opts, handler) {
- const { dumpMaxSize = defaultMaxSize } =
- opts
- const dumpHandler = new DumpHandler(
- { maxSize: dumpMaxSize },
- handler
- )
+ minver = new SemVer('0.0.0-0')
+ if (range.test(minver)) {
+ return minver
+ }
- return dispatch(opts, dumpHandler)
+ minver = null
+ for (let i = 0; i < range.set.length; ++i) {
+ const comparators = range.set[i]
+
+ let setMin = null
+ comparators.forEach((comparator) => {
+ // Clone to avoid manipulating the comparator's semver object.
+ const compver = new SemVer(comparator.semver.version)
+ switch (comparator.operator) {
+ case '>':
+ if (compver.prerelease.length === 0) {
+ compver.patch++
+ } else {
+ compver.prerelease.push(0)
+ }
+ compver.raw = compver.format()
+ /* fallthrough */
+ case '':
+ case '>=':
+ if (!setMin || gt(compver, setMin)) {
+ setMin = compver
+ }
+ break
+ case '<':
+ case '<=':
+ /* Ignore maximum versions */
+ break
+ /* istanbul ignore next */
+ default:
+ throw new Error(`Unexpected operation: ${comparator.operator}`)
+ }
+ })
+ if (setMin && (!minver || gt(minver, setMin))) {
+ minver = setMin
}
}
-}
-module.exports = createDumpInterceptor
+ if (minver && range.test(minver)) {
+ return minver
+ }
+
+ return null
+}
+module.exports = minVersion
/***/ }),
-/***/ 6097:
+/***/ 280:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const RedirectHandler = __nccwpck_require__(7031)
+const SemVer = __nccwpck_require__(7163)
+const Comparator = __nccwpck_require__(9379)
+const { ANY } = Comparator
+const Range = __nccwpck_require__(6782)
+const satisfies = __nccwpck_require__(8011)
+const gt = __nccwpck_require__(6599)
+const lt = __nccwpck_require__(3872)
+const lte = __nccwpck_require__(6717)
+const gte = __nccwpck_require__(1236)
-function createRedirectInterceptor ({ maxRedirections: defaultMaxRedirections }) {
- return (dispatch) => {
- return function Intercept (opts, handler) {
- const { maxRedirections = defaultMaxRedirections } = opts
+const outside = (version, range, hilo, options) => {
+ version = new SemVer(version, options)
+ range = new Range(range, options)
- if (!maxRedirections) {
- return dispatch(opts, handler)
+ let gtfn, ltefn, ltfn, comp, ecomp
+ switch (hilo) {
+ case '>':
+ gtfn = gt
+ ltefn = lte
+ ltfn = lt
+ comp = '>'
+ ecomp = '>='
+ break
+ case '<':
+ gtfn = lt
+ ltefn = gte
+ ltfn = gt
+ comp = '<'
+ ecomp = '<='
+ break
+ default:
+ throw new TypeError('Must provide a hilo val of "<" or ">"')
+ }
+
+ // If it satisfies the range it is not outside
+ if (satisfies(version, range, options)) {
+ return false
+ }
+
+ // From now on, variable terms are as if we're in "gtr" mode.
+ // but note that everything is flipped for the "ltr" function.
+
+ for (let i = 0; i < range.set.length; ++i) {
+ const comparators = range.set[i]
+
+ let high = null
+ let low = null
+
+ comparators.forEach((comparator) => {
+ if (comparator.semver === ANY) {
+ comparator = new Comparator('>=0.0.0')
+ }
+ high = high || comparator
+ low = low || comparator
+ if (gtfn(comparator.semver, high.semver, options)) {
+ high = comparator
+ } else if (ltfn(comparator.semver, low.semver, options)) {
+ low = comparator
}
+ })
- const redirectHandler = new RedirectHandler(dispatch, maxRedirections, opts, handler)
- opts = { ...opts, maxRedirections: 0 } // Stop sub dispatcher from also redirecting.
- return dispatch(opts, redirectHandler)
+ // If the edge version comparator has a operator then our version
+ // isn't outside it
+ if (high.operator === comp || high.operator === ecomp) {
+ return false
+ }
+
+ // If the lowest version comparator has an operator and our version
+ // is less than it then it isn't higher than the range
+ if ((!low.operator || low.operator === comp) &&
+ ltefn(version, low.semver)) {
+ return false
+ } else if (low.operator === ecomp && ltfn(version, low.semver)) {
+ return false
}
}
+ return true
}
-module.exports = createRedirectInterceptor
+module.exports = outside
/***/ }),
-/***/ 5711:
+/***/ 2028:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const RedirectHandler = __nccwpck_require__(7031)
-
-module.exports = opts => {
- const globalMaxRedirections = opts?.maxRedirections
- return dispatch => {
- return function redirectInterceptor (opts, handler) {
- const { maxRedirections = globalMaxRedirections, ...baseOpts } = opts
- if (!maxRedirections) {
- return dispatch(opts, handler)
+// given a set of versions and a range, create a "simplified" range
+// that includes the same versions that the original range does
+// If the original range is shorter than the simplified one, return that.
+const satisfies = __nccwpck_require__(8011)
+const compare = __nccwpck_require__(8469)
+module.exports = (versions, range, options) => {
+ const set = []
+ let first = null
+ let prev = null
+ const v = versions.sort((a, b) => compare(a, b, options))
+ for (const version of v) {
+ const included = satisfies(version, range, options)
+ if (included) {
+ prev = version
+ if (!first) {
+ first = version
}
+ } else {
+ if (prev) {
+ set.push([first, prev])
+ }
+ prev = null
+ first = null
+ }
+ }
+ if (first) {
+ set.push([first, null])
+ }
- const redirectHandler = new RedirectHandler(
- dispatch,
- maxRedirections,
- opts,
- handler
- )
-
- return dispatch(baseOpts, redirectHandler)
+ const ranges = []
+ for (const [min, max] of set) {
+ if (min === max) {
+ ranges.push(min)
+ } else if (!max && min === v[0]) {
+ ranges.push('*')
+ } else if (!max) {
+ ranges.push(`>=${min}`)
+ } else if (min === v[0]) {
+ ranges.push(`<=${max}`)
+ } else {
+ ranges.push(`${min} - ${max}`)
}
}
+ const simplified = ranges.join(' || ')
+ const original = typeof range.raw === 'string' ? range.raw : String(range)
+ return simplified.length < original.length ? simplified : range
}
/***/ }),
-/***/ 2117:
+/***/ 1489:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const RetryHandler = __nccwpck_require__(3783)
-module.exports = globalOpts => {
- return dispatch => {
- return function retryInterceptor (opts, handler) {
- return dispatch(
- opts,
- new RetryHandler(
- { ...opts, retryOptions: { ...globalOpts, ...opts.retryOptions } },
- {
- handler,
- dispatch
- }
- )
- )
- }
+const Range = __nccwpck_require__(6782)
+const Comparator = __nccwpck_require__(9379)
+const { ANY } = Comparator
+const satisfies = __nccwpck_require__(8011)
+const compare = __nccwpck_require__(8469)
+
+// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff:
+// - Every simple range `r1, r2, ...` is a null set, OR
+// - Every simple range `r1, r2, ...` which is not a null set is a subset of
+// some `R1, R2, ...`
+//
+// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff:
+// - If c is only the ANY comparator
+// - If C is only the ANY comparator, return true
+// - Else if in prerelease mode, return false
+// - else replace c with `[>=0.0.0]`
+// - If C is only the ANY comparator
+// - if in prerelease mode, return true
+// - else replace C with `[>=0.0.0]`
+// - Let EQ be the set of = comparators in c
+// - If EQ is more than one, return true (null set)
+// - Let GT be the highest > or >= comparator in c
+// - Let LT be the lowest < or <= comparator in c
+// - If GT and LT, and GT.semver > LT.semver, return true (null set)
+// - If any C is a = range, and GT or LT are set, return false
+// - If EQ
+// - If GT, and EQ does not satisfy GT, return true (null set)
+// - If LT, and EQ does not satisfy LT, return true (null set)
+// - If EQ satisfies every C, return true
+// - Else return false
+// - If GT
+// - If GT.semver is lower than any > or >= comp in C, return false
+// - If GT is >=, and GT.semver does not satisfy every C, return false
+// - If GT.semver has a prerelease, and not in prerelease mode
+// - If no C has a prerelease and the GT.semver tuple, return false
+// - If LT
+// - If LT.semver is greater than any < or <= comp in C, return false
+// - If LT is <=, and LT.semver does not satisfy every C, return false
+// - If LT.semver has a prerelease, and not in prerelease mode
+// - If no C has a prerelease and the LT.semver tuple, return false
+// - Else return true
+
+const subset = (sub, dom, options = {}) => {
+ if (sub === dom) {
+ return true
}
-}
+ sub = new Range(sub, options)
+ dom = new Range(dom, options)
+ let sawNonNull = false
-/***/ }),
+ OUTER: for (const simpleSub of sub.set) {
+ for (const simpleDom of dom.set) {
+ const isSub = simpleSubset(simpleSub, simpleDom, options)
+ sawNonNull = sawNonNull || isSub !== null
+ if (isSub) {
+ continue OUTER
+ }
+ }
+ // the null set is a subset of everything, but null simple ranges in
+ // a complex range should be ignored. so if we saw a non-null range,
+ // then we know this isn't a subset, but if EVERY simple range was null,
+ // then it is a subset.
+ if (sawNonNull) {
+ return false
+ }
+ }
+ return true
+}
-/***/ 2529:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')]
+const minimumVersion = [new Comparator('>=0.0.0')]
+const simpleSubset = (sub, dom, options) => {
+ if (sub === dom) {
+ return true
+ }
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.SPECIAL_HEADERS = exports.HEADER_STATE = exports.MINOR = exports.MAJOR = exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS = exports.TOKEN = exports.STRICT_TOKEN = exports.HEX = exports.URL_CHAR = exports.STRICT_URL_CHAR = exports.USERINFO_CHARS = exports.MARK = exports.ALPHANUM = exports.NUM = exports.HEX_MAP = exports.NUM_MAP = exports.ALPHA = exports.FINISH = exports.H_METHOD_MAP = exports.METHOD_MAP = exports.METHODS_RTSP = exports.METHODS_ICE = exports.METHODS_HTTP = exports.METHODS = exports.LENIENT_FLAGS = exports.FLAGS = exports.TYPE = exports.ERROR = void 0;
-const utils_1 = __nccwpck_require__(7557);
-// C headers
-var ERROR;
-(function (ERROR) {
- ERROR[ERROR["OK"] = 0] = "OK";
- ERROR[ERROR["INTERNAL"] = 1] = "INTERNAL";
- ERROR[ERROR["STRICT"] = 2] = "STRICT";
- ERROR[ERROR["LF_EXPECTED"] = 3] = "LF_EXPECTED";
- ERROR[ERROR["UNEXPECTED_CONTENT_LENGTH"] = 4] = "UNEXPECTED_CONTENT_LENGTH";
- ERROR[ERROR["CLOSED_CONNECTION"] = 5] = "CLOSED_CONNECTION";
- ERROR[ERROR["INVALID_METHOD"] = 6] = "INVALID_METHOD";
- ERROR[ERROR["INVALID_URL"] = 7] = "INVALID_URL";
- ERROR[ERROR["INVALID_CONSTANT"] = 8] = "INVALID_CONSTANT";
- ERROR[ERROR["INVALID_VERSION"] = 9] = "INVALID_VERSION";
- ERROR[ERROR["INVALID_HEADER_TOKEN"] = 10] = "INVALID_HEADER_TOKEN";
- ERROR[ERROR["INVALID_CONTENT_LENGTH"] = 11] = "INVALID_CONTENT_LENGTH";
- ERROR[ERROR["INVALID_CHUNK_SIZE"] = 12] = "INVALID_CHUNK_SIZE";
- ERROR[ERROR["INVALID_STATUS"] = 13] = "INVALID_STATUS";
- ERROR[ERROR["INVALID_EOF_STATE"] = 14] = "INVALID_EOF_STATE";
- ERROR[ERROR["INVALID_TRANSFER_ENCODING"] = 15] = "INVALID_TRANSFER_ENCODING";
- ERROR[ERROR["CB_MESSAGE_BEGIN"] = 16] = "CB_MESSAGE_BEGIN";
- ERROR[ERROR["CB_HEADERS_COMPLETE"] = 17] = "CB_HEADERS_COMPLETE";
- ERROR[ERROR["CB_MESSAGE_COMPLETE"] = 18] = "CB_MESSAGE_COMPLETE";
- ERROR[ERROR["CB_CHUNK_HEADER"] = 19] = "CB_CHUNK_HEADER";
- ERROR[ERROR["CB_CHUNK_COMPLETE"] = 20] = "CB_CHUNK_COMPLETE";
- ERROR[ERROR["PAUSED"] = 21] = "PAUSED";
- ERROR[ERROR["PAUSED_UPGRADE"] = 22] = "PAUSED_UPGRADE";
- ERROR[ERROR["PAUSED_H2_UPGRADE"] = 23] = "PAUSED_H2_UPGRADE";
- ERROR[ERROR["USER"] = 24] = "USER";
-})(ERROR = exports.ERROR || (exports.ERROR = {}));
-var TYPE;
-(function (TYPE) {
- TYPE[TYPE["BOTH"] = 0] = "BOTH";
- TYPE[TYPE["REQUEST"] = 1] = "REQUEST";
- TYPE[TYPE["RESPONSE"] = 2] = "RESPONSE";
-})(TYPE = exports.TYPE || (exports.TYPE = {}));
-var FLAGS;
-(function (FLAGS) {
- FLAGS[FLAGS["CONNECTION_KEEP_ALIVE"] = 1] = "CONNECTION_KEEP_ALIVE";
- FLAGS[FLAGS["CONNECTION_CLOSE"] = 2] = "CONNECTION_CLOSE";
- FLAGS[FLAGS["CONNECTION_UPGRADE"] = 4] = "CONNECTION_UPGRADE";
- FLAGS[FLAGS["CHUNKED"] = 8] = "CHUNKED";
- FLAGS[FLAGS["UPGRADE"] = 16] = "UPGRADE";
- FLAGS[FLAGS["CONTENT_LENGTH"] = 32] = "CONTENT_LENGTH";
- FLAGS[FLAGS["SKIPBODY"] = 64] = "SKIPBODY";
- FLAGS[FLAGS["TRAILING"] = 128] = "TRAILING";
- // 1 << 8 is unused
- FLAGS[FLAGS["TRANSFER_ENCODING"] = 512] = "TRANSFER_ENCODING";
-})(FLAGS = exports.FLAGS || (exports.FLAGS = {}));
-var LENIENT_FLAGS;
-(function (LENIENT_FLAGS) {
- LENIENT_FLAGS[LENIENT_FLAGS["HEADERS"] = 1] = "HEADERS";
- LENIENT_FLAGS[LENIENT_FLAGS["CHUNKED_LENGTH"] = 2] = "CHUNKED_LENGTH";
- LENIENT_FLAGS[LENIENT_FLAGS["KEEP_ALIVE"] = 4] = "KEEP_ALIVE";
-})(LENIENT_FLAGS = exports.LENIENT_FLAGS || (exports.LENIENT_FLAGS = {}));
-var METHODS;
-(function (METHODS) {
- METHODS[METHODS["DELETE"] = 0] = "DELETE";
- METHODS[METHODS["GET"] = 1] = "GET";
- METHODS[METHODS["HEAD"] = 2] = "HEAD";
- METHODS[METHODS["POST"] = 3] = "POST";
- METHODS[METHODS["PUT"] = 4] = "PUT";
- /* pathological */
- METHODS[METHODS["CONNECT"] = 5] = "CONNECT";
- METHODS[METHODS["OPTIONS"] = 6] = "OPTIONS";
- METHODS[METHODS["TRACE"] = 7] = "TRACE";
- /* WebDAV */
- METHODS[METHODS["COPY"] = 8] = "COPY";
- METHODS[METHODS["LOCK"] = 9] = "LOCK";
- METHODS[METHODS["MKCOL"] = 10] = "MKCOL";
- METHODS[METHODS["MOVE"] = 11] = "MOVE";
- METHODS[METHODS["PROPFIND"] = 12] = "PROPFIND";
- METHODS[METHODS["PROPPATCH"] = 13] = "PROPPATCH";
- METHODS[METHODS["SEARCH"] = 14] = "SEARCH";
- METHODS[METHODS["UNLOCK"] = 15] = "UNLOCK";
- METHODS[METHODS["BIND"] = 16] = "BIND";
- METHODS[METHODS["REBIND"] = 17] = "REBIND";
- METHODS[METHODS["UNBIND"] = 18] = "UNBIND";
- METHODS[METHODS["ACL"] = 19] = "ACL";
- /* subversion */
- METHODS[METHODS["REPORT"] = 20] = "REPORT";
- METHODS[METHODS["MKACTIVITY"] = 21] = "MKACTIVITY";
- METHODS[METHODS["CHECKOUT"] = 22] = "CHECKOUT";
- METHODS[METHODS["MERGE"] = 23] = "MERGE";
- /* upnp */
- METHODS[METHODS["M-SEARCH"] = 24] = "M-SEARCH";
- METHODS[METHODS["NOTIFY"] = 25] = "NOTIFY";
- METHODS[METHODS["SUBSCRIBE"] = 26] = "SUBSCRIBE";
- METHODS[METHODS["UNSUBSCRIBE"] = 27] = "UNSUBSCRIBE";
- /* RFC-5789 */
- METHODS[METHODS["PATCH"] = 28] = "PATCH";
- METHODS[METHODS["PURGE"] = 29] = "PURGE";
- /* CalDAV */
- METHODS[METHODS["MKCALENDAR"] = 30] = "MKCALENDAR";
- /* RFC-2068, section 19.6.1.2 */
- METHODS[METHODS["LINK"] = 31] = "LINK";
- METHODS[METHODS["UNLINK"] = 32] = "UNLINK";
- /* icecast */
- METHODS[METHODS["SOURCE"] = 33] = "SOURCE";
- /* RFC-7540, section 11.6 */
- METHODS[METHODS["PRI"] = 34] = "PRI";
- /* RFC-2326 RTSP */
- METHODS[METHODS["DESCRIBE"] = 35] = "DESCRIBE";
- METHODS[METHODS["ANNOUNCE"] = 36] = "ANNOUNCE";
- METHODS[METHODS["SETUP"] = 37] = "SETUP";
- METHODS[METHODS["PLAY"] = 38] = "PLAY";
- METHODS[METHODS["PAUSE"] = 39] = "PAUSE";
- METHODS[METHODS["TEARDOWN"] = 40] = "TEARDOWN";
- METHODS[METHODS["GET_PARAMETER"] = 41] = "GET_PARAMETER";
- METHODS[METHODS["SET_PARAMETER"] = 42] = "SET_PARAMETER";
- METHODS[METHODS["REDIRECT"] = 43] = "REDIRECT";
- METHODS[METHODS["RECORD"] = 44] = "RECORD";
- /* RAOP */
- METHODS[METHODS["FLUSH"] = 45] = "FLUSH";
-})(METHODS = exports.METHODS || (exports.METHODS = {}));
-exports.METHODS_HTTP = [
- METHODS.DELETE,
- METHODS.GET,
- METHODS.HEAD,
- METHODS.POST,
- METHODS.PUT,
- METHODS.CONNECT,
- METHODS.OPTIONS,
- METHODS.TRACE,
- METHODS.COPY,
- METHODS.LOCK,
- METHODS.MKCOL,
- METHODS.MOVE,
- METHODS.PROPFIND,
- METHODS.PROPPATCH,
- METHODS.SEARCH,
- METHODS.UNLOCK,
- METHODS.BIND,
- METHODS.REBIND,
- METHODS.UNBIND,
- METHODS.ACL,
- METHODS.REPORT,
- METHODS.MKACTIVITY,
- METHODS.CHECKOUT,
- METHODS.MERGE,
- METHODS['M-SEARCH'],
- METHODS.NOTIFY,
- METHODS.SUBSCRIBE,
- METHODS.UNSUBSCRIBE,
- METHODS.PATCH,
- METHODS.PURGE,
- METHODS.MKCALENDAR,
- METHODS.LINK,
- METHODS.UNLINK,
- METHODS.PRI,
- // TODO(indutny): should we allow it with HTTP?
- METHODS.SOURCE,
-];
-exports.METHODS_ICE = [
- METHODS.SOURCE,
-];
-exports.METHODS_RTSP = [
- METHODS.OPTIONS,
- METHODS.DESCRIBE,
- METHODS.ANNOUNCE,
- METHODS.SETUP,
- METHODS.PLAY,
- METHODS.PAUSE,
- METHODS.TEARDOWN,
- METHODS.GET_PARAMETER,
- METHODS.SET_PARAMETER,
- METHODS.REDIRECT,
- METHODS.RECORD,
- METHODS.FLUSH,
- // For AirPlay
- METHODS.GET,
- METHODS.POST,
-];
-exports.METHOD_MAP = utils_1.enumToMap(METHODS);
-exports.H_METHOD_MAP = {};
-Object.keys(exports.METHOD_MAP).forEach((key) => {
- if (/^H/.test(key)) {
- exports.H_METHOD_MAP[key] = exports.METHOD_MAP[key];
- }
-});
-var FINISH;
-(function (FINISH) {
- FINISH[FINISH["SAFE"] = 0] = "SAFE";
- FINISH[FINISH["SAFE_WITH_CB"] = 1] = "SAFE_WITH_CB";
- FINISH[FINISH["UNSAFE"] = 2] = "UNSAFE";
-})(FINISH = exports.FINISH || (exports.FINISH = {}));
-exports.ALPHA = [];
-for (let i = 'A'.charCodeAt(0); i <= 'Z'.charCodeAt(0); i++) {
- // Upper case
- exports.ALPHA.push(String.fromCharCode(i));
- // Lower case
- exports.ALPHA.push(String.fromCharCode(i + 0x20));
-}
-exports.NUM_MAP = {
- 0: 0, 1: 1, 2: 2, 3: 3, 4: 4,
- 5: 5, 6: 6, 7: 7, 8: 8, 9: 9,
-};
-exports.HEX_MAP = {
- 0: 0, 1: 1, 2: 2, 3: 3, 4: 4,
- 5: 5, 6: 6, 7: 7, 8: 8, 9: 9,
- A: 0XA, B: 0XB, C: 0XC, D: 0XD, E: 0XE, F: 0XF,
- a: 0xa, b: 0xb, c: 0xc, d: 0xd, e: 0xe, f: 0xf,
-};
-exports.NUM = [
- '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
-];
-exports.ALPHANUM = exports.ALPHA.concat(exports.NUM);
-exports.MARK = ['-', '_', '.', '!', '~', '*', '\'', '(', ')'];
-exports.USERINFO_CHARS = exports.ALPHANUM
- .concat(exports.MARK)
- .concat(['%', ';', ':', '&', '=', '+', '$', ',']);
-// TODO(indutny): use RFC
-exports.STRICT_URL_CHAR = [
- '!', '"', '$', '%', '&', '\'',
- '(', ')', '*', '+', ',', '-', '.', '/',
- ':', ';', '<', '=', '>',
- '@', '[', '\\', ']', '^', '_',
- '`',
- '{', '|', '}', '~',
-].concat(exports.ALPHANUM);
-exports.URL_CHAR = exports.STRICT_URL_CHAR
- .concat(['\t', '\f']);
-// All characters with 0x80 bit set to 1
-for (let i = 0x80; i <= 0xff; i++) {
- exports.URL_CHAR.push(i);
-}
-exports.HEX = exports.NUM.concat(['a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F']);
-/* Tokens as defined by rfc 2616. Also lowercases them.
- * token = 1*
- * separators = "(" | ")" | "<" | ">" | "@"
- * | "," | ";" | ":" | "\" | <">
- * | "/" | "[" | "]" | "?" | "="
- * | "{" | "}" | SP | HT
- */
-exports.STRICT_TOKEN = [
- '!', '#', '$', '%', '&', '\'',
- '*', '+', '-', '.',
- '^', '_', '`',
- '|', '~',
-].concat(exports.ALPHANUM);
-exports.TOKEN = exports.STRICT_TOKEN.concat([' ']);
-/*
- * Verify that a char is a valid visible (printable) US-ASCII
- * character or %x80-FF
- */
-exports.HEADER_CHARS = ['\t'];
-for (let i = 32; i <= 255; i++) {
- if (i !== 127) {
- exports.HEADER_CHARS.push(i);
+ if (sub.length === 1 && sub[0].semver === ANY) {
+ if (dom.length === 1 && dom[0].semver === ANY) {
+ return true
+ } else if (options.includePrerelease) {
+ sub = minimumVersionWithPreRelease
+ } else {
+ sub = minimumVersion
}
-}
-// ',' = \x44
-exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS.filter((c) => c !== 44);
-exports.MAJOR = exports.NUM_MAP;
-exports.MINOR = exports.MAJOR;
-var HEADER_STATE;
-(function (HEADER_STATE) {
- HEADER_STATE[HEADER_STATE["GENERAL"] = 0] = "GENERAL";
- HEADER_STATE[HEADER_STATE["CONNECTION"] = 1] = "CONNECTION";
- HEADER_STATE[HEADER_STATE["CONTENT_LENGTH"] = 2] = "CONTENT_LENGTH";
- HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING"] = 3] = "TRANSFER_ENCODING";
- HEADER_STATE[HEADER_STATE["UPGRADE"] = 4] = "UPGRADE";
- HEADER_STATE[HEADER_STATE["CONNECTION_KEEP_ALIVE"] = 5] = "CONNECTION_KEEP_ALIVE";
- HEADER_STATE[HEADER_STATE["CONNECTION_CLOSE"] = 6] = "CONNECTION_CLOSE";
- HEADER_STATE[HEADER_STATE["CONNECTION_UPGRADE"] = 7] = "CONNECTION_UPGRADE";
- HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING_CHUNKED"] = 8] = "TRANSFER_ENCODING_CHUNKED";
-})(HEADER_STATE = exports.HEADER_STATE || (exports.HEADER_STATE = {}));
-exports.SPECIAL_HEADERS = {
- 'connection': HEADER_STATE.CONNECTION,
- 'content-length': HEADER_STATE.CONTENT_LENGTH,
- 'proxy-connection': HEADER_STATE.CONNECTION,
- 'transfer-encoding': HEADER_STATE.TRANSFER_ENCODING,
- 'upgrade': HEADER_STATE.UPGRADE,
-};
-//# sourceMappingURL=constants.js.map
+ }
-/***/ }),
+ if (dom.length === 1 && dom[0].semver === ANY) {
+ if (options.includePrerelease) {
+ return true
+ } else {
+ dom = minimumVersion
+ }
+ }
-/***/ 7635:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ const eqSet = new Set()
+ let gt, lt
+ for (const c of sub) {
+ if (c.operator === '>' || c.operator === '>=') {
+ gt = higherGT(gt, c, options)
+ } else if (c.operator === '<' || c.operator === '<=') {
+ lt = lowerLT(lt, c, options)
+ } else {
+ eqSet.add(c.semver)
+ }
+ }
+ if (eqSet.size > 1) {
+ return null
+ }
+ let gtltComp
+ if (gt && lt) {
+ gtltComp = compare(gt.semver, lt.semver, options)
+ if (gtltComp > 0) {
+ return null
+ } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) {
+ return null
+ }
+ }
-const { Buffer } = __nccwpck_require__(4573)
+ // will iterate one or zero times
+ for (const eq of eqSet) {
+ if (gt && !satisfies(eq, String(gt), options)) {
+ return null
+ }
-module.exports = Buffer.from('AGFzbQEAAAABJwdgAX8Bf2ADf39/AX9gAX8AYAJ/fwBgBH9/f38Bf2AAAGADf39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQAEA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAAy0sBQYAAAIAAAAAAAACAQIAAgICAAADAAAAAAMDAwMBAQEBAQEBAQEAAAIAAAAEBQFwARISBQMBAAIGCAF/AUGA1AQLB9EFIgZtZW1vcnkCAAtfaW5pdGlhbGl6ZQAIGV9faW5kaXJlY3RfZnVuY3Rpb25fdGFibGUBAAtsbGh0dHBfaW5pdAAJGGxsaHR0cF9zaG91bGRfa2VlcF9hbGl2ZQAvDGxsaHR0cF9hbGxvYwALBm1hbGxvYwAxC2xsaHR0cF9mcmVlAAwEZnJlZQAMD2xsaHR0cF9nZXRfdHlwZQANFWxsaHR0cF9nZXRfaHR0cF9tYWpvcgAOFWxsaHR0cF9nZXRfaHR0cF9taW5vcgAPEWxsaHR0cF9nZXRfbWV0aG9kABAWbGxodHRwX2dldF9zdGF0dXNfY29kZQAREmxsaHR0cF9nZXRfdXBncmFkZQASDGxsaHR0cF9yZXNldAATDmxsaHR0cF9leGVjdXRlABQUbGxodHRwX3NldHRpbmdzX2luaXQAFQ1sbGh0dHBfZmluaXNoABYMbGxodHRwX3BhdXNlABcNbGxodHRwX3Jlc3Vt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An9BjNAAKAIAIgJBASAEQQN2dCIDcUUEQEGM0AAgAiADcjYCACAADAELIAAoAggLIgIgATYCDCAAIAE2AgggASAANgIMIAEgAjYCCAwBC0EfIQIgBEH///8HTQRAIARBJiAEQQh2ZyIAa3ZBAXEgAEEBdGtBPmohAgsgASACNgIcIAFCADcCECACQQJ0QbzSAGohAAJAQZDQACgCACIDQQEgAnQiB3FFBEAgACABNgIAQZDQACADIAdyNgIAIAEgADYCGCABIAE2AgggASABNgIMDAELIARBGSACQQF2a0EAIAJBH0cbdCECIAAoAgAhAAJAA0AgACIDKAIEQXhxIARGDQEgAkEddiEAIAJBAXQhAiADIABBBHFqQRBqIgcoAgAiAA0ACyAHIAE2AgAgASADNgIYIAEgATYCDCABIAE2AggMAQsgAygCCCIAIAE2AgwgAyABNgIIIAFBADYCGCABIAM2AgwgASAANgIIC0Gs0ABBrNAAKAIAQQFrIgBBfyAAGzYCAAsLBwAgAC0AKAsHACAALQAqCwcAIAAtACsLBwAgAC0AKQsHACAALwEyCwcAIAAtAC4LQAEEfyAAKAIYIQEgAC0ALSECIAAtACghAyAAKAI4IQQgABAwIAAgBDYCOCAAIAM6ACggACACOgAtIAAgATYCGAu74gECB38DfiABIAJqIQQCQCAAIgIoAgwiAA0AIAIoAgQEQCACIAE2AgQLIwBBEGsiCCQAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAk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0G5AQwKC0G6AQwJC0G7AQwIC0HGAQwHC0G8AQwGC0G9AQwFC0G+AQwEC0G/AQwDC0HAAQwCC0HCAQwBC0HBAQshAwNAAkACQAJAAkACQAJAAkACQAJAIAICfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJ/AkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAgJ/AkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAn8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJ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UNSSUJFTFVTSEVURUFEU0VBUkNIUkdFQ1RJVklUWUxFTkRBUlZFT1RJRllQVElPTlNDSFNFQVlTVEFUQ0hHRU9SRElSRUNUT1JUUkNIUEFSQU1FVEVSVVJDRUJTQ1JJQkVBUkRPV05BQ0VJTkROS0NLVUJTQ1JJQkVIVFRQL0FEVFAv', 'base64')
+ if (lt && !satisfies(eq, String(lt), options)) {
+ return null
+ }
+ for (const c of dom) {
+ if (!satisfies(eq, String(c), options)) {
+ return false
+ }
+ }
-/***/ }),
+ return true
+ }
-/***/ 5593:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ let higher, lower
+ let hasDomLT, hasDomGT
+ // if the subset has a prerelease, we need a comparator in the superset
+ // with the same tuple and a prerelease, or it's not a subset
+ let needDomLTPre = lt &&
+ !options.includePrerelease &&
+ lt.semver.prerelease.length ? lt.semver : false
+ let needDomGTPre = gt &&
+ !options.includePrerelease &&
+ gt.semver.prerelease.length ? gt.semver : false
+ // exception: <1.2.3-0 is the same as <1.2.3
+ if (needDomLTPre && needDomLTPre.prerelease.length === 1 &&
+ lt.operator === '<' && needDomLTPre.prerelease[0] === 0) {
+ needDomLTPre = false
+ }
+ for (const c of dom) {
+ hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='
+ hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='
+ if (gt) {
+ if (needDomGTPre) {
+ if (c.semver.prerelease && c.semver.prerelease.length &&
+ c.semver.major === needDomGTPre.major &&
+ c.semver.minor === needDomGTPre.minor &&
+ c.semver.patch === needDomGTPre.patch) {
+ needDomGTPre = false
+ }
+ }
+ if (c.operator === '>' || c.operator === '>=') {
+ higher = higherGT(gt, c, options)
+ if (higher === c && higher !== gt) {
+ return false
+ }
+ } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) {
+ return false
+ }
+ }
+ if (lt) {
+ if (needDomLTPre) {
+ if (c.semver.prerelease && c.semver.prerelease.length &&
+ c.semver.major === needDomLTPre.major &&
+ c.semver.minor === needDomLTPre.minor &&
+ c.semver.patch === needDomLTPre.patch) {
+ needDomLTPre = false
+ }
+ }
+ if (c.operator === '<' || c.operator === '<=') {
+ lower = lowerLT(lt, c, options)
+ if (lower === c && lower !== lt) {
+ return false
+ }
+ } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) {
+ return false
+ }
+ }
+ if (!c.operator && (lt || gt) && gtltComp !== 0) {
+ return false
+ }
+ }
+ // if there was a < or >, and nothing in the dom, then must be false
+ // UNLESS it was limited by another range in the other direction.
+ // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0
+ if (gt && hasDomLT && !lt && gtltComp !== 0) {
+ return false
+ }
-const { Buffer } = __nccwpck_require__(4573)
+ if (lt && hasDomGT && !gt && gtltComp !== 0) {
+ return false
+ }
-module.exports = Buffer.from('AGFzbQEAAAABJwdgAX8Bf2ADf39/AX9gAX8AYAJ/fwBgBH9/f38Bf2AAAGADf39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQAEA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAAy0sBQYAAAIAAAAAAAACAQIAAgICAAADAAAAAAMDAwMBAQEBAQEBAQEAAAIAAAAEBQFwARISBQMBAAIGCAF/AUGA1AQLB9EFIgZtZW1vcnkCAAtfaW5pdGlhbGl6ZQAIGV9faW5kaXJlY3RfZnVuY3Rpb25fdGFibGUBAAtsbGh0dHBfaW5pdAAJGGxsaHR0cF9zaG91bGRfa2VlcF9hbGl2ZQAvDGxsaHR0cF9hbGxvYwALBm1hbGxvYwAxC2xsaHR0cF9mcmVlAAwEZnJlZQAMD2x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BkEBaiEBQQUMcQsgASAERgRAQYABIQMMrQILIAEtAABB2QBHDW4gAUEBaiEBQQgMcAsgASAERgRAQYEBIQMMrAILAkACQCABLQAAQc4Aaw4DAG8BbwsgAUEBaiEBQesAIQMMkwILIAFBAWohAUHsACEDDJICCyABIARGBEBBggEhAwyrAgsCQAJAIAEtAABByABrDggAbm5ubm5uAW4LIAFBAWohAUHqACEDDJICCyABQQFqIQFB7QAhAwyRAgtBgwEhAyABIARGDakCIAIoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQYDPAGotAABHDWwgAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADKoCCyACQQA2AgAgBkEBaiEBQQAMbQtBhAEhAyABIARGDagCIAIoAgAiACAEIAFraiEFIAEgAGtBBGohBgJAA0AgAS0AACAAQYPPAGotAABHDWsgAEEERg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADKkCCyACQQA2AgAgBkEBaiEBQSMMbAsgASAERgRAQYUBIQMMqAILAkACQCABLQAAQcwAaw4IAGtra2trawFrCyABQQFqIQFB7wAhAwyPAgsgAUEBaiEBQfAAIQMMjgILIAEgBEYEQEGGASEDDKcCCyABLQAAQcUARw1oIAFBAWohAQxgC0GHASEDIAEgBEYNpQIgAigCACIAIAQgAWtqIQUgASAAa0EDaiEGAkADQCABLQAAIABBiM8Aai0AAEcNaCAAQQNGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMpgILIAJBADYCACAGQQFqIQFBLQxpC0GIASEDIAEgBEYNpAIgAigCACIAIAQgAWtqIQUgASAAa0EIaiEGAkADQCABLQAAIABB0M8Aai0AAEcNZyAAQQhGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMpQILIAJBADYCACAGQQFqIQFBKQxoCyABIARGBEBBiQEhAwykAgtBASABLQAAQd8ARw1nGiABQQFqIQEMXgtBigEhAyABIARGDaICIAIoAgAiACAEIAFraiEFIAEgAGtBAWoh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QgAkH9EjYCECACQQc2AgwMrAELIAJBADYCHCACIAE2AhQgAkHcCDYCECACQQc2AgxBACEDDKsBCyACKAIEIQAgAkEANgIEIAIgACABECUiAEUNByACQeUANgIcIAIgATYCFCACIAA2AgxBACEDDKoBCyACKAIEIQAgAkEANgIEIAIgACABECUiAEUNFiACQdMANgIcIAIgATYCFCACIAA2AgxBACEDDKkBCyACKAIEIQAgAkEANgIEIAIgACABECUiAEUNGCACQdIANgIcIAIgATYCFCACIAA2AgxBACEDDKgBCyACQQA2AhwgAiABNgIUIAJBxgo2AhAgAkEHNgIMQQAhAwynAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDQMgAkHlADYCHCACIAE2AhQgAiAANgIMQQAhAwymAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDRIgAkHTADYCHCACIAE2AhQgAiAANgIMQQAhAwylAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDRQgAkHSADYCHCACIAE2AhQgAiAANgIMQQAhAwykAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDQAgAkHlADYCHCACIAE2AhQgAiAANgIMQQAhAwyjAQtB1QAhAwyJAQsgAEEVRwRAIAJBADYCHCACIAE2AhQgAkG5DTYCECACQRo2AgxBACEDDKIBCyACQeQANgIcIAIgATYCFCACQeMXNgIQIAJBFTYCDEEAIQMMoQELIAJBADYCACAGQQFqIQEgAi0AKSIAQSNrQQtJDQQCQCAAQQZLDQBBASAAdEHKAHFFDQAMBQtBACEDIAJBADYCHCACIAE2AhQgAkH3CTYCECACQQg2AgwMoAELIAJBADYCACAGQQFqIQEgAi0AKUEhRg0DIAJBADYCHCACIAE2AhQgAkGbCjYCECACQQg2AgxBACEDDJ8BCyACQQA2AgALQQAhAyACQQA2AhwgAiABNgIUIAJBkDM2AhAgAkEINgIMDJ0BCyACQQA2AgAgBkEBaiEBIAItAClBI0kNACACQQA2AhwgAiABNgIUIAJB0wk2AhAgAkEINgIMQQAhAwycAQtB0QAhAwyCAQsg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BAQEBAQEBAQEBAQABAAGBwQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEAAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAEAEH6ygALBAEAAAEAQZDLAAsBAQBBqssAC0ECAAAAAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwBB+swACwQBAAABAEGQzQALAQEAQZrNAAsGAgAAAAACAEGxzQALOgMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAQfDOAAuWAU5PVU5DRUVDS09VVE5FQ1RFVEVDUklCRUxVU0hFVEVBRFNFQVJDSFJHRUNUSVZJVFlMRU5EQVJWRU9USUZZUFRJT05TQ0hTRUFZU1RBVENIR0VPUkRJUkVDVE9SVFJDSFBBUkFNRVRFUlVSQ0VCU0NSSUJFQVJET1dOQUNFSU5ETktDS1VCU0NSSUJFSFRUUC9BRFRQLw==', 'base64')
+ // we needed a prerelease range in a specific tuple, but didn't get one
+ // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0,
+ // because it includes prereleases in the 1.2.3 tuple
+ if (needDomGTPre || needDomLTPre) {
+ return false
+ }
+ return true
+}
-/***/ }),
+// >=1.2.3 is lower than >1.2.3
+const higherGT = (a, b, options) => {
+ if (!a) {
+ return b
+ }
+ const comp = compare(a.semver, b.semver, options)
+ return comp > 0 ? a
+ : comp < 0 ? b
+ : b.operator === '>' && a.operator === '>=' ? b
+ : a
+}
-/***/ 7557:
-/***/ ((__unused_webpack_module, exports) => {
+// <=1.2.3 is higher than <1.2.3
+const lowerLT = (a, b, options) => {
+ if (!a) {
+ return b
+ }
+ const comp = compare(a.semver, b.semver, options)
+ return comp < 0 ? a
+ : comp > 0 ? b
+ : b.operator === '<' && a.operator === '<=' ? b
+ : a
+}
+module.exports = subset
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.enumToMap = void 0;
-function enumToMap(obj) {
- const res = {};
- Object.keys(obj).forEach((key) => {
- const value = obj[key];
- if (typeof value === 'number') {
- res[key] = value;
- }
- });
- return res;
-}
-exports.enumToMap = enumToMap;
-//# sourceMappingURL=utils.js.map
/***/ }),
-/***/ 2710:
+/***/ 4750:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const { kClients } = __nccwpck_require__(6130)
-const Agent = __nccwpck_require__(4332)
-const {
- kAgent,
- kMockAgentSet,
- kMockAgentGet,
- kDispatches,
- kIsMockActive,
- kNetConnect,
- kGetNetConnect,
- kOptions,
- kFactory
-} = __nccwpck_require__(5154)
-const MockClient = __nccwpck_require__(9736)
-const MockPool = __nccwpck_require__(5157)
-const { matchValue, buildMockOptions } = __nccwpck_require__(2042)
-const { InvalidArgumentError, UndiciError } = __nccwpck_require__(2344)
-const Dispatcher = __nccwpck_require__(9784)
-const Pluralizer = __nccwpck_require__(4638)
-const PendingInterceptorsFormatter = __nccwpck_require__(6573)
+const Range = __nccwpck_require__(6782)
-class MockAgent extends Dispatcher {
- constructor (opts) {
- super(opts)
+// Mostly just for testing and legacy API reasons
+const toComparators = (range, options) =>
+ new Range(range, options).set
+ .map(comp => comp.map(c => c.value).join(' ').trim().split(' '))
- this[kNetConnect] = true
- this[kIsMockActive] = true
+module.exports = toComparators
- // Instantiate Agent and encapsulate
- if ((opts?.agent && typeof opts.agent.dispatch !== 'function')) {
- throw new InvalidArgumentError('Argument opts.agent must implement Agent')
- }
- const agent = opts?.agent ? opts.agent : new Agent(opts)
- this[kAgent] = agent
- this[kClients] = agent[kClients]
- this[kOptions] = buildMockOptions(opts)
- }
+/***/ }),
- get (origin) {
- let dispatcher = this[kMockAgentGet](origin)
+/***/ 4737:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- if (!dispatcher) {
- dispatcher = this[kFactory](origin)
- this[kMockAgentSet](origin, dispatcher)
- }
- return dispatcher
- }
- dispatch (opts, handler) {
- // Call MockAgent.get to perform additional setup before dispatching as normal
- this.get(opts.origin)
- return this[kAgent].dispatch(opts, handler)
- }
- async close () {
- await this[kAgent].close()
- this[kClients].clear()
+const Range = __nccwpck_require__(6782)
+const validRange = (range, options) => {
+ try {
+ // Return '*' instead of '' so that truthiness works.
+ // This will throw if it's invalid anyway
+ return new Range(range, options).range || '*'
+ } catch (er) {
+ return null
}
+}
+module.exports = validRange
- deactivate () {
- this[kIsMockActive] = false
- }
- activate () {
- this[kIsMockActive] = true
- }
+/***/ }),
- enableNetConnect (matcher) {
- if (typeof matcher === 'string' || typeof matcher === 'function' || matcher instanceof RegExp) {
- if (Array.isArray(this[kNetConnect])) {
- this[kNetConnect].push(matcher)
- } else {
- this[kNetConnect] = [matcher]
- }
- } else if (typeof matcher === 'undefined') {
- this[kNetConnect] = true
- } else {
- throw new InvalidArgumentError('Unsupported matcher. Must be one of String|Function|RegExp.')
- }
- }
+/***/ 1860:
+/***/ ((module) => {
- disableNetConnect () {
- this[kNetConnect] = false
- }
+/******************************************************************************
+Copyright (c) Microsoft Corporation.
+
+Permission to use, copy, modify, and/or distribute this software for any
+purpose with or without fee is hereby granted.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
+REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
+AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
+INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
+LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
+OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+PERFORMANCE OF THIS SOFTWARE.
+***************************************************************************** */
+/* global global, define, Symbol, Reflect, Promise, SuppressedError, Iterator */
+var __extends;
+var __assign;
+var __rest;
+var __decorate;
+var __param;
+var __esDecorate;
+var __runInitializers;
+var __propKey;
+var __setFunctionName;
+var __metadata;
+var __awaiter;
+var __generator;
+var __exportStar;
+var __values;
+var __read;
+var __spread;
+var __spreadArrays;
+var __spreadArray;
+var __await;
+var __asyncGenerator;
+var __asyncDelegator;
+var __asyncValues;
+var __makeTemplateObject;
+var __importStar;
+var __importDefault;
+var __classPrivateFieldGet;
+var __classPrivateFieldSet;
+var __classPrivateFieldIn;
+var __createBinding;
+var __addDisposableResource;
+var __disposeResources;
+var __rewriteRelativeImportExtension;
+(function (factory) {
+ var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {};
+ if (typeof define === "function" && define.amd) {
+ define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); });
+ }
+ else if ( true && typeof module.exports === "object") {
+ factory(createExporter(root, createExporter(module.exports)));
+ }
+ else {
+ factory(createExporter(root));
+ }
+ function createExporter(exports, previous) {
+ if (exports !== root) {
+ if (typeof Object.create === "function") {
+ Object.defineProperty(exports, "__esModule", { value: true });
+ }
+ else {
+ exports.__esModule = true;
+ }
+ }
+ return function (id, v) { return exports[id] = previous ? previous(id, v) : v; };
+ }
+})
+(function (exporter) {
+ var extendStatics = Object.setPrototypeOf ||
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
+
+ __extends = function (d, b) {
+ if (typeof b !== "function" && b !== null)
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
+ extendStatics(d, b);
+ function __() { this.constructor = d; }
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+ };
+
+ __assign = Object.assign || function (t) {
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
+ s = arguments[i];
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
+ }
+ return t;
+ };
+
+ __rest = function (s, e) {
+ var t = {};
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
+ t[p] = s[p];
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
+ t[p[i]] = s[p[i]];
+ }
+ return t;
+ };
+
+ __decorate = function (decorators, target, key, desc) {
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
+ };
+
+ __param = function (paramIndex, decorator) {
+ return function (target, key) { decorator(target, key, paramIndex); }
+ };
+
+ __esDecorate = function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
+ function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
+ var _, done = false;
+ for (var i = decorators.length - 1; i >= 0; i--) {
+ var context = {};
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
+ context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
+ var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
+ if (kind === "accessor") {
+ if (result === void 0) continue;
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
+ if (_ = accept(result.get)) descriptor.get = _;
+ if (_ = accept(result.set)) descriptor.set = _;
+ if (_ = accept(result.init)) initializers.unshift(_);
+ }
+ else if (_ = accept(result)) {
+ if (kind === "field") initializers.unshift(_);
+ else descriptor[key] = _;
+ }
+ }
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
+ done = true;
+ };
+
+ __runInitializers = function (thisArg, initializers, value) {
+ var useValue = arguments.length > 2;
+ for (var i = 0; i < initializers.length; i++) {
+ value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
+ }
+ return useValue ? value : void 0;
+ };
+
+ __propKey = function (x) {
+ return typeof x === "symbol" ? x : "".concat(x);
+ };
+
+ __setFunctionName = function (f, name, prefix) {
+ if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
+ return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
+ };
+
+ __metadata = function (metadataKey, metadataValue) {
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
+ };
+
+ __awaiter = function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+ };
+
+ __generator = function (thisArg, body) {
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
+ function verb(n) { return function (v) { return step([n, v]); }; }
+ function step(op) {
+ if (f) throw new TypeError("Generator is already executing.");
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
+ if (y = 0, t) op = [op[0] & 2, t.value];
+ switch (op[0]) {
+ case 0: case 1: t = op; break;
+ case 4: _.label++; return { value: op[1], done: false };
+ case 5: _.label++; y = op[1]; op = [0]; continue;
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
+ default:
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
+ if (t[2]) _.ops.pop();
+ _.trys.pop(); continue;
+ }
+ op = body.call(thisArg, _);
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
+ }
+ };
+
+ __exportStar = function(m, o) {
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);
+ };
+
+ __createBinding = Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
+ }
+ Object.defineProperty(o, k2, desc);
+ }) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+ });
+
+ __values = function (o) {
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
+ if (m) return m.call(o);
+ if (o && typeof o.length === "number") return {
+ next: function () {
+ if (o && i >= o.length) o = void 0;
+ return { value: o && o[i++], done: !o };
+ }
+ };
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
+ };
+
+ __read = function (o, n) {
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
+ if (!m) return o;
+ var i = m.call(o), r, ar = [], e;
+ try {
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
+ }
+ catch (error) { e = { error: error }; }
+ finally {
+ try {
+ if (r && !r.done && (m = i["return"])) m.call(i);
+ }
+ finally { if (e) throw e.error; }
+ }
+ return ar;
+ };
+
+ /** @deprecated */
+ __spread = function () {
+ for (var ar = [], i = 0; i < arguments.length; i++)
+ ar = ar.concat(__read(arguments[i]));
+ return ar;
+ };
+
+ /** @deprecated */
+ __spreadArrays = function () {
+ for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
+ for (var r = Array(s), k = 0, i = 0; i < il; i++)
+ for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
+ r[k] = a[j];
+ return r;
+ };
+
+ __spreadArray = function (to, from, pack) {
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
+ if (ar || !(i in from)) {
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
+ ar[i] = from[i];
+ }
+ }
+ return to.concat(ar || Array.prototype.slice.call(from));
+ };
+
+ __await = function (v) {
+ return this instanceof __await ? (this.v = v, this) : new __await(v);
+ };
+
+ __asyncGenerator = function (thisArg, _arguments, generator) {
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
+ return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
+ function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
+ function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
+ function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
+ function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
+ function fulfill(value) { resume("next", value); }
+ function reject(value) { resume("throw", value); }
+ function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
+ };
+
+ __asyncDelegator = function (o) {
+ var i, p;
+ return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
+ function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }
+ };
+
+ __asyncValues = function (o) {
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
+ var m = o[Symbol.asyncIterator], i;
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
+ };
+
+ __makeTemplateObject = function (cooked, raw) {
+ if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
+ return cooked;
+ };
+
+ var __setModuleDefault = Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+ }) : function(o, v) {
+ o["default"] = v;
+ };
+
+ var ownKeys = function(o) {
+ ownKeys = Object.getOwnPropertyNames || function (o) {
+ var ar = [];
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
+ return ar;
+ };
+ return ownKeys(o);
+ };
+
+ __importStar = function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
+ __setModuleDefault(result, mod);
+ return result;
+ };
+
+ __importDefault = function (mod) {
+ return (mod && mod.__esModule) ? mod : { "default": mod };
+ };
+
+ __classPrivateFieldGet = function (receiver, state, kind, f) {
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
+ };
+
+ __classPrivateFieldSet = function (receiver, state, value, kind, f) {
+ if (kind === "m") throw new TypeError("Private method is not writable");
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
+ };
+
+ __classPrivateFieldIn = function (state, receiver) {
+ if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object");
+ return typeof state === "function" ? receiver === state : state.has(receiver);
+ };
+
+ __addDisposableResource = function (env, value, async) {
+ if (value !== null && value !== void 0) {
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
+ var dispose, inner;
+ if (async) {
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
+ dispose = value[Symbol.asyncDispose];
+ }
+ if (dispose === void 0) {
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
+ dispose = value[Symbol.dispose];
+ if (async) inner = dispose;
+ }
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
+ if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
+ env.stack.push({ value: value, dispose: dispose, async: async });
+ }
+ else if (async) {
+ env.stack.push({ async: true });
+ }
+ return value;
+ };
+
+ var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
+ var e = new Error(message);
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
+ };
+
+ __disposeResources = function (env) {
+ function fail(e) {
+ env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
+ env.hasError = true;
+ }
+ var r, s = 0;
+ function next() {
+ while (r = env.stack.pop()) {
+ try {
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
+ if (r.dispose) {
+ var result = r.dispose.call(r.value);
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
+ }
+ else s |= 1;
+ }
+ catch (e) {
+ fail(e);
+ }
+ }
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
+ if (env.hasError) throw env.error;
+ }
+ return next();
+ };
+
+ __rewriteRelativeImportExtension = function (path, preserveJsx) {
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
+ });
+ }
+ return path;
+ };
+
+ exporter("__extends", __extends);
+ exporter("__assign", __assign);
+ exporter("__rest", __rest);
+ exporter("__decorate", __decorate);
+ exporter("__param", __param);
+ exporter("__esDecorate", __esDecorate);
+ exporter("__runInitializers", __runInitializers);
+ exporter("__propKey", __propKey);
+ exporter("__setFunctionName", __setFunctionName);
+ exporter("__metadata", __metadata);
+ exporter("__awaiter", __awaiter);
+ exporter("__generator", __generator);
+ exporter("__exportStar", __exportStar);
+ exporter("__createBinding", __createBinding);
+ exporter("__values", __values);
+ exporter("__read", __read);
+ exporter("__spread", __spread);
+ exporter("__spreadArrays", __spreadArrays);
+ exporter("__spreadArray", __spreadArray);
+ exporter("__await", __await);
+ exporter("__asyncGenerator", __asyncGenerator);
+ exporter("__asyncDelegator", __asyncDelegator);
+ exporter("__asyncValues", __asyncValues);
+ exporter("__makeTemplateObject", __makeTemplateObject);
+ exporter("__importStar", __importStar);
+ exporter("__importDefault", __importDefault);
+ exporter("__classPrivateFieldGet", __classPrivateFieldGet);
+ exporter("__classPrivateFieldSet", __classPrivateFieldSet);
+ exporter("__classPrivateFieldIn", __classPrivateFieldIn);
+ exporter("__addDisposableResource", __addDisposableResource);
+ exporter("__disposeResources", __disposeResources);
+ exporter("__rewriteRelativeImportExtension", __rewriteRelativeImportExtension);
+});
+
+0 && (0);
- // This is required to bypass issues caused by using global symbols - see:
- // https://github.com/nodejs/undici/issues/1447
- get isMockActive () {
- return this[kIsMockActive]
- }
- [kMockAgentSet] (origin, dispatcher) {
- this[kClients].set(origin, dispatcher)
- }
+/***/ }),
- [kFactory] (origin) {
- const mockOptions = Object.assign({ agent: this }, this[kOptions])
- return this[kOptions] && this[kOptions].connections === 1
- ? new MockClient(origin, mockOptions)
- : new MockPool(origin, mockOptions)
- }
+/***/ 770:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- [kMockAgentGet] (origin) {
- // First check if we can immediately find it
- const client = this[kClients].get(origin)
- if (client) {
- return client
- }
+module.exports = __nccwpck_require__(218);
- // If the origin is not a string create a dummy parent pool and return to user
- if (typeof origin !== 'string') {
- const dispatcher = this[kFactory]('http://localhost:9999')
- this[kMockAgentSet](origin, dispatcher)
- return dispatcher
- }
- // If we match, create a pool and assign the same dispatches
- for (const [keyMatcher, nonExplicitDispatcher] of Array.from(this[kClients])) {
- if (nonExplicitDispatcher && typeof keyMatcher !== 'string' && matchValue(keyMatcher, origin)) {
- const dispatcher = this[kFactory](origin)
- this[kMockAgentSet](origin, dispatcher)
- dispatcher[kDispatches] = nonExplicitDispatcher[kDispatches]
- return dispatcher
- }
- }
- }
+/***/ }),
- [kGetNetConnect] () {
- return this[kNetConnect]
- }
+/***/ 218:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- pendingInterceptors () {
- const mockAgentClients = this[kClients]
- return Array.from(mockAgentClients.entries())
- .flatMap(([origin, scope]) => scope[kDispatches].map(dispatch => ({ ...dispatch, origin })))
- .filter(({ pending }) => pending)
- }
- assertNoPendingInterceptors ({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) {
- const pending = this.pendingInterceptors()
+var net = __nccwpck_require__(9278);
+var tls = __nccwpck_require__(4756);
+var http = __nccwpck_require__(8611);
+var https = __nccwpck_require__(5692);
+var events = __nccwpck_require__(4434);
+var assert = __nccwpck_require__(2613);
+var util = __nccwpck_require__(9023);
- if (pending.length === 0) {
- return
- }
- const pluralizer = new Pluralizer('interceptor', 'interceptors').pluralize(pending.length)
+exports.httpOverHttp = httpOverHttp;
+exports.httpsOverHttp = httpsOverHttp;
+exports.httpOverHttps = httpOverHttps;
+exports.httpsOverHttps = httpsOverHttps;
- throw new UndiciError(`
-${pluralizer.count} ${pluralizer.noun} ${pluralizer.is} pending:
-${pendingInterceptorsFormatter.format(pending)}
-`.trim())
- }
+function httpOverHttp(options) {
+ var agent = new TunnelingAgent(options);
+ agent.request = http.request;
+ return agent;
}
-module.exports = MockAgent
+function httpsOverHttp(options) {
+ var agent = new TunnelingAgent(options);
+ agent.request = http.request;
+ agent.createSocket = createSecureSocket;
+ agent.defaultPort = 443;
+ return agent;
+}
+
+function httpOverHttps(options) {
+ var agent = new TunnelingAgent(options);
+ agent.request = https.request;
+ return agent;
+}
+function httpsOverHttps(options) {
+ var agent = new TunnelingAgent(options);
+ agent.request = https.request;
+ agent.createSocket = createSecureSocket;
+ agent.defaultPort = 443;
+ return agent;
+}
-/***/ }),
-/***/ 9736:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+function TunnelingAgent(options) {
+ var self = this;
+ self.options = options || {};
+ self.proxyOptions = self.options.proxy || {};
+ self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets;
+ self.requests = [];
+ self.sockets = [];
+ self.on('free', function onFree(socket, host, port, localAddress) {
+ var options = toOptions(host, port, localAddress);
+ for (var i = 0, len = self.requests.length; i < len; ++i) {
+ var pending = self.requests[i];
+ if (pending.host === options.host && pending.port === options.port) {
+ // Detect the request to connect same origin server,
+ // reuse the connection.
+ self.requests.splice(i, 1);
+ pending.request.onSocket(socket);
+ return;
+ }
+ }
+ socket.destroy();
+ self.removeSocket(socket);
+ });
+}
+util.inherits(TunnelingAgent, events.EventEmitter);
+TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) {
+ var self = this;
+ var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress));
-const { promisify } = __nccwpck_require__(7975)
-const Client = __nccwpck_require__(2138)
-const { buildMockDispatch } = __nccwpck_require__(2042)
-const {
- kDispatches,
- kMockAgent,
- kClose,
- kOriginalClose,
- kOrigin,
- kOriginalDispatch,
- kConnected
-} = __nccwpck_require__(5154)
-const { MockInterceptor } = __nccwpck_require__(4452)
-const Symbols = __nccwpck_require__(6130)
-const { InvalidArgumentError } = __nccwpck_require__(2344)
+ if (self.sockets.length >= this.maxSockets) {
+ // We are over limit so we'll add it to the queue.
+ self.requests.push(options);
+ return;
+ }
-/**
- * MockClient provides an API that extends the Client to influence the mockDispatches.
- */
-class MockClient extends Client {
- constructor (origin, opts) {
- super(origin, opts)
+ // If we are under maxSockets create a new one.
+ self.createSocket(options, function(socket) {
+ socket.on('free', onFree);
+ socket.on('close', onCloseOrRemove);
+ socket.on('agentRemove', onCloseOrRemove);
+ req.onSocket(socket);
- if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') {
- throw new InvalidArgumentError('Argument opts.agent must implement Agent')
+ function onFree() {
+ self.emit('free', socket, options);
}
- this[kMockAgent] = opts.agent
- this[kOrigin] = origin
- this[kDispatches] = []
- this[kConnected] = 1
- this[kOriginalDispatch] = this.dispatch
- this[kOriginalClose] = this.close.bind(this)
+ function onCloseOrRemove(err) {
+ self.removeSocket(socket);
+ socket.removeListener('free', onFree);
+ socket.removeListener('close', onCloseOrRemove);
+ socket.removeListener('agentRemove', onCloseOrRemove);
+ }
+ });
+};
- this.dispatch = buildMockDispatch.call(this)
- this.close = this[kClose]
- }
+TunnelingAgent.prototype.createSocket = function createSocket(options, cb) {
+ var self = this;
+ var placeholder = {};
+ self.sockets.push(placeholder);
- get [Symbols.kConnected] () {
- return this[kConnected]
+ var connectOptions = mergeOptions({}, self.proxyOptions, {
+ method: 'CONNECT',
+ path: options.host + ':' + options.port,
+ agent: false,
+ headers: {
+ host: options.host + ':' + options.port
+ }
+ });
+ if (options.localAddress) {
+ connectOptions.localAddress = options.localAddress;
+ }
+ if (connectOptions.proxyAuth) {
+ connectOptions.headers = connectOptions.headers || {};
+ connectOptions.headers['Proxy-Authorization'] = 'Basic ' +
+ new Buffer(connectOptions.proxyAuth).toString('base64');
}
- /**
- * Sets up the base interceptor for mocking replies from undici.
- */
- intercept (opts) {
- return new MockInterceptor(opts, this[kDispatches])
+ debug('making CONNECT request');
+ var connectReq = self.request(connectOptions);
+ connectReq.useChunkedEncodingByDefault = false; // for v0.6
+ connectReq.once('response', onResponse); // for v0.6
+ connectReq.once('upgrade', onUpgrade); // for v0.6
+ connectReq.once('connect', onConnect); // for v0.7 or later
+ connectReq.once('error', onError);
+ connectReq.end();
+
+ function onResponse(res) {
+ // Very hacky. This is necessary to avoid http-parser leaks.
+ res.upgrade = true;
}
- async [kClose] () {
- await promisify(this[kOriginalClose])()
- this[kConnected] = 0
- this[kMockAgent][Symbols.kClients].delete(this[kOrigin])
+ function onUpgrade(res, socket, head) {
+ // Hacky.
+ process.nextTick(function() {
+ onConnect(res, socket, head);
+ });
}
-}
-module.exports = MockClient
+ function onConnect(res, socket, head) {
+ connectReq.removeAllListeners();
+ socket.removeAllListeners();
+ if (res.statusCode !== 200) {
+ debug('tunneling socket could not be established, statusCode=%d',
+ res.statusCode);
+ socket.destroy();
+ var error = new Error('tunneling socket could not be established, ' +
+ 'statusCode=' + res.statusCode);
+ error.code = 'ECONNRESET';
+ options.request.emit('error', error);
+ self.removeSocket(placeholder);
+ return;
+ }
+ if (head.length > 0) {
+ debug('got illegal response body from proxy');
+ socket.destroy();
+ var error = new Error('got illegal response body from proxy');
+ error.code = 'ECONNRESET';
+ options.request.emit('error', error);
+ self.removeSocket(placeholder);
+ return;
+ }
+ debug('tunneling connection has established');
+ self.sockets[self.sockets.indexOf(placeholder)] = socket;
+ return cb(socket);
+ }
-/***/ }),
+ function onError(cause) {
+ connectReq.removeAllListeners();
-/***/ 8024:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ debug('tunneling socket could not be established, cause=%s\n',
+ cause.message, cause.stack);
+ var error = new Error('tunneling socket could not be established, ' +
+ 'cause=' + cause.message);
+ error.code = 'ECONNRESET';
+ options.request.emit('error', error);
+ self.removeSocket(placeholder);
+ }
+};
+TunnelingAgent.prototype.removeSocket = function removeSocket(socket) {
+ var pos = this.sockets.indexOf(socket)
+ if (pos === -1) {
+ return;
+ }
+ this.sockets.splice(pos, 1);
+ var pending = this.requests.shift();
+ if (pending) {
+ // If we have pending requests and a socket gets closed a new one
+ // needs to be created to take over in the pool for the one that closed.
+ this.createSocket(pending, function(socket) {
+ pending.request.onSocket(socket);
+ });
+ }
+};
-const { UndiciError } = __nccwpck_require__(2344)
+function createSecureSocket(options, cb) {
+ var self = this;
+ TunnelingAgent.prototype.createSocket.call(self, options, function(socket) {
+ var hostHeader = options.request.getHeader('host');
+ var tlsOptions = mergeOptions({}, self.options, {
+ socket: socket,
+ servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host
+ });
-const kMockNotMatchedError = Symbol.for('undici.error.UND_MOCK_ERR_MOCK_NOT_MATCHED')
+ // 0 is dummy port for v0.6
+ var secureSocket = tls.connect(0, tlsOptions);
+ self.sockets[self.sockets.indexOf(socket)] = secureSocket;
+ cb(secureSocket);
+ });
+}
-/**
- * The request does not match any registered mock dispatches.
- */
-class MockNotMatchedError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, MockNotMatchedError)
- this.name = 'MockNotMatchedError'
- this.message = message || 'The request does not match any registered mock dispatches'
- this.code = 'UND_MOCK_ERR_MOCK_NOT_MATCHED'
- }
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kMockNotMatchedError] === true
+function toOptions(host, port, localAddress) {
+ if (typeof host === 'string') { // since v0.10
+ return {
+ host: host,
+ port: port,
+ localAddress: localAddress
+ };
}
+ return host; // for v0.11 or later
+}
- [kMockNotMatchedError] = true
+function mergeOptions(target) {
+ for (var i = 1, len = arguments.length; i < len; ++i) {
+ var overrides = arguments[i];
+ if (typeof overrides === 'object') {
+ var keys = Object.keys(overrides);
+ for (var j = 0, keyLen = keys.length; j < keyLen; ++j) {
+ var k = keys[j];
+ if (overrides[k] !== undefined) {
+ target[k] = overrides[k];
+ }
+ }
+ }
+ }
+ return target;
}
-module.exports = {
- MockNotMatchedError
+
+var debug;
+if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) {
+ debug = function() {
+ var args = Array.prototype.slice.call(arguments);
+ if (typeof args[0] === 'string') {
+ args[0] = 'TUNNEL: ' + args[0];
+ } else {
+ args.unshift('TUNNEL:');
+ }
+ console.error.apply(console, args);
+ }
+} else {
+ debug = function() {};
}
+exports.debug = debug; // for test
/***/ }),
-/***/ 4452:
+/***/ 6752:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const { getResponseData, buildKey, addMockDispatch } = __nccwpck_require__(2042)
-const {
- kDispatches,
- kDispatchKey,
- kDefaultHeaders,
- kDefaultTrailers,
- kContentLength,
- kMockDispatch
-} = __nccwpck_require__(5154)
-const { InvalidArgumentError } = __nccwpck_require__(2344)
-const { buildURL } = __nccwpck_require__(7375)
-
-/**
- * Defines the scope API for an interceptor reply
- */
-class MockScope {
- constructor (mockDispatch) {
- this[kMockDispatch] = mockDispatch
- }
-
- /**
- * Delay a reply by a set amount in ms.
- */
- delay (waitInMs) {
- if (typeof waitInMs !== 'number' || !Number.isInteger(waitInMs) || waitInMs <= 0) {
- throw new InvalidArgumentError('waitInMs must be a valid integer > 0')
- }
+const Client = __nccwpck_require__(3701)
+const Dispatcher = __nccwpck_require__(883)
+const Pool = __nccwpck_require__(628)
+const BalancedPool = __nccwpck_require__(837)
+const Agent = __nccwpck_require__(7405)
+const ProxyAgent = __nccwpck_require__(6672)
+const EnvHttpProxyAgent = __nccwpck_require__(3137)
+const RetryAgent = __nccwpck_require__(50)
+const errors = __nccwpck_require__(8707)
+const util = __nccwpck_require__(3440)
+const { InvalidArgumentError } = errors
+const api = __nccwpck_require__(6615)
+const buildConnector = __nccwpck_require__(9136)
+const MockClient = __nccwpck_require__(7365)
+const MockAgent = __nccwpck_require__(7501)
+const MockPool = __nccwpck_require__(4004)
+const mockErrors = __nccwpck_require__(2429)
+const RetryHandler = __nccwpck_require__(7816)
+const { getGlobalDispatcher, setGlobalDispatcher } = __nccwpck_require__(2581)
+const DecoratorHandler = __nccwpck_require__(8155)
+const RedirectHandler = __nccwpck_require__(8754)
+const createRedirectInterceptor = __nccwpck_require__(5092)
- this[kMockDispatch].delay = waitInMs
- return this
- }
+Object.assign(Dispatcher.prototype, api)
- /**
- * For a defined reply, never mark as consumed.
- */
- persist () {
- this[kMockDispatch].persist = true
- return this
- }
+module.exports.Dispatcher = Dispatcher
+module.exports.Client = Client
+module.exports.Pool = Pool
+module.exports.BalancedPool = BalancedPool
+module.exports.Agent = Agent
+module.exports.ProxyAgent = ProxyAgent
+module.exports.EnvHttpProxyAgent = EnvHttpProxyAgent
+module.exports.RetryAgent = RetryAgent
+module.exports.RetryHandler = RetryHandler
- /**
- * Allow one to define a reply for a set amount of matching requests.
- */
- times (repeatTimes) {
- if (typeof repeatTimes !== 'number' || !Number.isInteger(repeatTimes) || repeatTimes <= 0) {
- throw new InvalidArgumentError('repeatTimes must be a valid integer > 0')
- }
+module.exports.DecoratorHandler = DecoratorHandler
+module.exports.RedirectHandler = RedirectHandler
+module.exports.createRedirectInterceptor = createRedirectInterceptor
+module.exports.interceptors = {
+ redirect: __nccwpck_require__(1514),
+ retry: __nccwpck_require__(2026),
+ dump: __nccwpck_require__(8060),
+ dns: __nccwpck_require__(379)
+}
- this[kMockDispatch].times = repeatTimes
- return this
- }
+module.exports.buildConnector = buildConnector
+module.exports.errors = errors
+module.exports.util = {
+ parseHeaders: util.parseHeaders,
+ headerNameToString: util.headerNameToString
}
-/**
- * Defines an interceptor for a Mock
- */
-class MockInterceptor {
- constructor (opts, mockDispatches) {
- if (typeof opts !== 'object') {
- throw new InvalidArgumentError('opts must be an object')
- }
- if (typeof opts.path === 'undefined') {
- throw new InvalidArgumentError('opts.path must be defined')
- }
- if (typeof opts.method === 'undefined') {
- opts.method = 'GET'
- }
- // See https://github.com/nodejs/undici/issues/1245
- // As per RFC 3986, clients are not supposed to send URI
- // fragments to servers when they retrieve a document,
- if (typeof opts.path === 'string') {
- if (opts.query) {
- opts.path = buildURL(opts.path, opts.query)
- } else {
- // Matches https://github.com/nodejs/undici/blob/main/lib/web/fetch/index.js#L1811
- const parsedURL = new URL(opts.path, 'data://')
- opts.path = parsedURL.pathname + parsedURL.search
- }
- }
- if (typeof opts.method === 'string') {
- opts.method = opts.method.toUpperCase()
+function makeDispatcher (fn) {
+ return (url, opts, handler) => {
+ if (typeof opts === 'function') {
+ handler = opts
+ opts = null
}
- this[kDispatchKey] = buildKey(opts)
- this[kDispatches] = mockDispatches
- this[kDefaultHeaders] = {}
- this[kDefaultTrailers] = {}
- this[kContentLength] = false
- }
-
- createMockScopeDispatchData ({ statusCode, data, responseOptions }) {
- const responseData = getResponseData(data)
- const contentLength = this[kContentLength] ? { 'content-length': responseData.length } : {}
- const headers = { ...this[kDefaultHeaders], ...contentLength, ...responseOptions.headers }
- const trailers = { ...this[kDefaultTrailers], ...responseOptions.trailers }
-
- return { statusCode, data, headers, trailers }
- }
-
- validateReplyParameters (replyParameters) {
- if (typeof replyParameters.statusCode === 'undefined') {
- throw new InvalidArgumentError('statusCode must be defined')
+ if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) {
+ throw new InvalidArgumentError('invalid url')
}
- if (typeof replyParameters.responseOptions !== 'object' || replyParameters.responseOptions === null) {
- throw new InvalidArgumentError('responseOptions must be an object')
+
+ if (opts != null && typeof opts !== 'object') {
+ throw new InvalidArgumentError('invalid opts')
}
- }
- /**
- * Mock an undici request with a defined reply.
- */
- reply (replyOptionsCallbackOrStatusCode) {
- // Values of reply aren't available right now as they
- // can only be available when the reply callback is invoked.
- if (typeof replyOptionsCallbackOrStatusCode === 'function') {
- // We'll first wrap the provided callback in another function,
- // this function will properly resolve the data from the callback
- // when invoked.
- const wrappedDefaultsCallback = (opts) => {
- // Our reply options callback contains the parameter for statusCode, data and options.
- const resolvedData = replyOptionsCallbackOrStatusCode(opts)
+ if (opts && opts.path != null) {
+ if (typeof opts.path !== 'string') {
+ throw new InvalidArgumentError('invalid opts.path')
+ }
- // Check if it is in the right format
- if (typeof resolvedData !== 'object' || resolvedData === null) {
- throw new InvalidArgumentError('reply options callback must return an object')
- }
+ let path = opts.path
+ if (!opts.path.startsWith('/')) {
+ path = `/${path}`
+ }
- const replyParameters = { data: '', responseOptions: {}, ...resolvedData }
- this.validateReplyParameters(replyParameters)
- // Since the values can be obtained immediately we return them
- // from this higher order function that will be resolved later.
- return {
- ...this.createMockScopeDispatchData(replyParameters)
- }
+ url = new URL(util.parseOrigin(url).origin + path)
+ } else {
+ if (!opts) {
+ opts = typeof url === 'object' ? url : {}
}
- // Add usual dispatch data, but this time set the data parameter to function that will eventually provide data.
- const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], wrappedDefaultsCallback)
- return new MockScope(newMockDispatch)
+ url = util.parseURL(url)
}
- // We can have either one or three parameters, if we get here,
- // we should have 1-3 parameters. So we spread the arguments of
- // this function to obtain the parameters, since replyData will always
- // just be the statusCode.
- const replyParameters = {
- statusCode: replyOptionsCallbackOrStatusCode,
- data: arguments[1] === undefined ? '' : arguments[1],
- responseOptions: arguments[2] === undefined ? {} : arguments[2]
+ const { agent, dispatcher = getGlobalDispatcher() } = opts
+
+ if (agent) {
+ throw new InvalidArgumentError('unsupported opts.agent. Did you mean opts.client?')
}
- this.validateReplyParameters(replyParameters)
- // Send in-already provided data like usual
- const dispatchData = this.createMockScopeDispatchData(replyParameters)
- const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], dispatchData)
- return new MockScope(newMockDispatch)
+ return fn.call(dispatcher, {
+ ...opts,
+ origin: url.origin,
+ path: url.search ? `${url.pathname}${url.search}` : url.pathname,
+ method: opts.method || (opts.body ? 'PUT' : 'GET')
+ }, handler)
}
+}
- /**
- * Mock an undici request with a defined error.
- */
- replyWithError (error) {
- if (typeof error === 'undefined') {
- throw new InvalidArgumentError('error must be defined')
+module.exports.setGlobalDispatcher = setGlobalDispatcher
+module.exports.getGlobalDispatcher = getGlobalDispatcher
+
+const fetchImpl = (__nccwpck_require__(4398).fetch)
+module.exports.fetch = async function fetch (init, options = undefined) {
+ try {
+ return await fetchImpl(init, options)
+ } catch (err) {
+ if (err && typeof err === 'object') {
+ Error.captureStackTrace(err)
}
- const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error })
- return new MockScope(newMockDispatch)
+ throw err
}
+}
+module.exports.Headers = __nccwpck_require__(660).Headers
+module.exports.Response = __nccwpck_require__(9051).Response
+module.exports.Request = __nccwpck_require__(9967).Request
+module.exports.FormData = __nccwpck_require__(5910).FormData
+module.exports.File = globalThis.File ?? (__nccwpck_require__(4573).File)
+module.exports.FileReader = __nccwpck_require__(8355).FileReader
- /**
- * Set default reply headers on the interceptor for subsequent replies
- */
- defaultReplyHeaders (headers) {
- if (typeof headers === 'undefined') {
- throw new InvalidArgumentError('headers must be defined')
- }
+const { setGlobalOrigin, getGlobalOrigin } = __nccwpck_require__(1059)
- this[kDefaultHeaders] = headers
- return this
- }
+module.exports.setGlobalOrigin = setGlobalOrigin
+module.exports.getGlobalOrigin = getGlobalOrigin
- /**
- * Set default reply trailers on the interceptor for subsequent replies
- */
- defaultReplyTrailers (trailers) {
- if (typeof trailers === 'undefined') {
- throw new InvalidArgumentError('trailers must be defined')
- }
+const { CacheStorage } = __nccwpck_require__(3245)
+const { kConstruct } = __nccwpck_require__(109)
- this[kDefaultTrailers] = trailers
- return this
- }
+// Cache & CacheStorage are tightly coupled with fetch. Even if it may run
+// in an older version of Node, it doesn't have any use without fetch.
+module.exports.caches = new CacheStorage(kConstruct)
- /**
- * Set reply content length header for replies on the interceptor
- */
- replyContentLength () {
- this[kContentLength] = true
- return this
- }
-}
+const { deleteCookie, getCookies, getSetCookies, setCookie } = __nccwpck_require__(9061)
-module.exports.MockInterceptor = MockInterceptor
-module.exports.MockScope = MockScope
+module.exports.deleteCookie = deleteCookie
+module.exports.getCookies = getCookies
+module.exports.getSetCookies = getSetCookies
+module.exports.setCookie = setCookie
+
+const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(1900)
+
+module.exports.parseMIMEType = parseMIMEType
+module.exports.serializeAMimeType = serializeAMimeType
+
+const { CloseEvent, ErrorEvent, MessageEvent } = __nccwpck_require__(5188)
+module.exports.WebSocket = __nccwpck_require__(3726).WebSocket
+module.exports.CloseEvent = CloseEvent
+module.exports.ErrorEvent = ErrorEvent
+module.exports.MessageEvent = MessageEvent
+
+module.exports.request = makeDispatcher(api.request)
+module.exports.stream = makeDispatcher(api.stream)
+module.exports.pipeline = makeDispatcher(api.pipeline)
+module.exports.connect = makeDispatcher(api.connect)
+module.exports.upgrade = makeDispatcher(api.upgrade)
+
+module.exports.MockClient = MockClient
+module.exports.MockPool = MockPool
+module.exports.MockAgent = MockAgent
+module.exports.mockErrors = mockErrors
+
+const { EventSource } = __nccwpck_require__(1238)
+
+module.exports.EventSource = EventSource
/***/ }),
-/***/ 5157:
+/***/ 158:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+const { addAbortListener } = __nccwpck_require__(3440)
+const { RequestAbortedError } = __nccwpck_require__(8707)
+const kListener = Symbol('kListener')
+const kSignal = Symbol('kSignal')
-const { promisify } = __nccwpck_require__(7975)
-const Pool = __nccwpck_require__(3959)
-const { buildMockDispatch } = __nccwpck_require__(2042)
-const {
- kDispatches,
- kMockAgent,
- kClose,
- kOriginalClose,
- kOrigin,
- kOriginalDispatch,
- kConnected
-} = __nccwpck_require__(5154)
-const { MockInterceptor } = __nccwpck_require__(4452)
-const Symbols = __nccwpck_require__(6130)
-const { InvalidArgumentError } = __nccwpck_require__(2344)
+function abort (self) {
+ if (self.abort) {
+ self.abort(self[kSignal]?.reason)
+ } else {
+ self.reason = self[kSignal]?.reason ?? new RequestAbortedError()
+ }
+ removeSignal(self)
+}
-/**
- * MockPool provides an API that extends the Pool to influence the mockDispatches.
- */
-class MockPool extends Pool {
- constructor (origin, opts) {
- super(origin, opts)
+function addSignal (self, signal) {
+ self.reason = null
- if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') {
- throw new InvalidArgumentError('Argument opts.agent must implement Agent')
- }
+ self[kSignal] = null
+ self[kListener] = null
- this[kMockAgent] = opts.agent
- this[kOrigin] = origin
- this[kDispatches] = []
- this[kConnected] = 1
- this[kOriginalDispatch] = this.dispatch
- this[kOriginalClose] = this.close.bind(this)
+ if (!signal) {
+ return
+ }
- this.dispatch = buildMockDispatch.call(this)
- this.close = this[kClose]
+ if (signal.aborted) {
+ abort(self)
+ return
}
- get [Symbols.kConnected] () {
- return this[kConnected]
+ self[kSignal] = signal
+ self[kListener] = () => {
+ abort(self)
}
- /**
- * Sets up the base interceptor for mocking replies from undici.
- */
- intercept (opts) {
- return new MockInterceptor(opts, this[kDispatches])
+ addAbortListener(self[kSignal], self[kListener])
+}
+
+function removeSignal (self) {
+ if (!self[kSignal]) {
+ return
}
- async [kClose] () {
- await promisify(this[kOriginalClose])()
- this[kConnected] = 0
- this[kMockAgent][Symbols.kClients].delete(this[kOrigin])
+ if ('removeEventListener' in self[kSignal]) {
+ self[kSignal].removeEventListener('abort', self[kListener])
+ } else {
+ self[kSignal].removeListener('abort', self[kListener])
}
+
+ self[kSignal] = null
+ self[kListener] = null
}
-module.exports = MockPool
+module.exports = {
+ addSignal,
+ removeSignal
+}
/***/ }),
-/***/ 5154:
-/***/ ((module) => {
+/***/ 2279:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-module.exports = {
- kAgent: Symbol('agent'),
- kOptions: Symbol('options'),
- kFactory: Symbol('factory'),
- kDispatches: Symbol('dispatches'),
- kDispatchKey: Symbol('dispatch key'),
- kDefaultHeaders: Symbol('default headers'),
- kDefaultTrailers: Symbol('default trailers'),
- kContentLength: Symbol('content length'),
- kMockAgent: Symbol('mock agent'),
- kMockAgentSet: Symbol('mock agent set'),
- kMockAgentGet: Symbol('mock agent get'),
- kMockDispatch: Symbol('mock dispatch'),
- kClose: Symbol('close'),
- kOriginalClose: Symbol('original agent close'),
- kOrigin: Symbol('origin'),
- kIsMockActive: Symbol('is mock active'),
- kNetConnect: Symbol('net connect'),
- kGetNetConnect: Symbol('get net connect'),
- kConnected: Symbol('connected')
-}
+const assert = __nccwpck_require__(4589)
+const { AsyncResource } = __nccwpck_require__(6698)
+const { InvalidArgumentError, SocketError } = __nccwpck_require__(8707)
+const util = __nccwpck_require__(3440)
+const { addSignal, removeSignal } = __nccwpck_require__(158)
+class ConnectHandler extends AsyncResource {
+ constructor (opts, callback) {
+ if (!opts || typeof opts !== 'object') {
+ throw new InvalidArgumentError('invalid opts')
+ }
-/***/ }),
+ if (typeof callback !== 'function') {
+ throw new InvalidArgumentError('invalid callback')
+ }
-/***/ 2042:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ const { signal, opaque, responseHeaders } = opts
+ if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
+ throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
+ }
+ super('UNDICI_CONNECT')
-const { MockNotMatchedError } = __nccwpck_require__(8024)
-const {
- kDispatches,
- kMockAgent,
- kOriginalDispatch,
- kOrigin,
- kGetNetConnect
-} = __nccwpck_require__(5154)
-const { buildURL } = __nccwpck_require__(7375)
-const { STATUS_CODES } = __nccwpck_require__(7067)
-const {
- types: {
- isPromise
- }
-} = __nccwpck_require__(7975)
+ this.opaque = opaque || null
+ this.responseHeaders = responseHeaders || null
+ this.callback = callback
+ this.abort = null
-function matchValue (match, value) {
- if (typeof match === 'string') {
- return match === value
+ addSignal(this, signal)
}
- if (match instanceof RegExp) {
- return match.test(value)
+
+ onConnect (abort, context) {
+ if (this.reason) {
+ abort(this.reason)
+ return
+ }
+
+ assert(this.callback)
+
+ this.abort = abort
+ this.context = context
}
- if (typeof match === 'function') {
- return match(value) === true
+
+ onHeaders () {
+ throw new SocketError('bad connect', null)
}
- return false
-}
-function lowerCaseEntries (headers) {
- return Object.fromEntries(
- Object.entries(headers).map(([headerName, headerValue]) => {
- return [headerName.toLocaleLowerCase(), headerValue]
- })
- )
-}
+ onUpgrade (statusCode, rawHeaders, socket) {
+ const { callback, opaque, context } = this
-/**
- * @param {import('../../index').Headers|string[]|Record} headers
- * @param {string} key
- */
-function getHeaderByName (headers, key) {
- if (Array.isArray(headers)) {
- for (let i = 0; i < headers.length; i += 2) {
- if (headers[i].toLocaleLowerCase() === key.toLocaleLowerCase()) {
- return headers[i + 1]
- }
+ removeSignal(this)
+
+ this.callback = null
+
+ let headers = rawHeaders
+ // Indicates is an HTTP2Session
+ if (headers != null) {
+ headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
}
- return undefined
- } else if (typeof headers.get === 'function') {
- return headers.get(key)
- } else {
- return lowerCaseEntries(headers)[key.toLocaleLowerCase()]
+ this.runInAsyncScope(callback, null, null, {
+ statusCode,
+ headers,
+ socket,
+ opaque,
+ context
+ })
}
-}
-/** @param {string[]} headers */
-function buildHeadersFromArray (headers) { // fetch HeadersList
- const clone = headers.slice()
- const entries = []
- for (let index = 0; index < clone.length; index += 2) {
- entries.push([clone[index], clone[index + 1]])
- }
- return Object.fromEntries(entries)
-}
+ onError (err) {
+ const { callback, opaque } = this
-function matchHeaders (mockDispatch, headers) {
- if (typeof mockDispatch.headers === 'function') {
- if (Array.isArray(headers)) { // fetch HeadersList
- headers = buildHeadersFromArray(headers)
+ removeSignal(this)
+
+ if (callback) {
+ this.callback = null
+ queueMicrotask(() => {
+ this.runInAsyncScope(callback, null, err, { opaque })
+ })
}
- return mockDispatch.headers(headers ? lowerCaseEntries(headers) : {})
- }
- if (typeof mockDispatch.headers === 'undefined') {
- return true
- }
- if (typeof headers !== 'object' || typeof mockDispatch.headers !== 'object') {
- return false
}
+}
- for (const [matchHeaderName, matchHeaderValue] of Object.entries(mockDispatch.headers)) {
- const headerValue = getHeaderByName(headers, matchHeaderName)
+function connect (opts, callback) {
+ if (callback === undefined) {
+ return new Promise((resolve, reject) => {
+ connect.call(this, opts, (err, data) => {
+ return err ? reject(err) : resolve(data)
+ })
+ })
+ }
- if (!matchValue(matchHeaderValue, headerValue)) {
- return false
+ try {
+ const connectHandler = new ConnectHandler(opts, callback)
+ this.dispatch({ ...opts, method: 'CONNECT' }, connectHandler)
+ } catch (err) {
+ if (typeof callback !== 'function') {
+ throw err
}
+ const opaque = opts?.opaque
+ queueMicrotask(() => callback(err, { opaque }))
}
- return true
}
-function safeUrl (path) {
- if (typeof path !== 'string') {
- return path
- }
+module.exports = connect
- const pathSegments = path.split('?')
- if (pathSegments.length !== 2) {
- return path
- }
+/***/ }),
- const qp = new URLSearchParams(pathSegments.pop())
- qp.sort()
- return [...pathSegments, qp.toString()].join('?')
-}
+/***/ 6862:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-function matchKey (mockDispatch, { path, method, body, headers }) {
- const pathMatch = matchValue(mockDispatch.path, path)
- const methodMatch = matchValue(mockDispatch.method, method)
- const bodyMatch = typeof mockDispatch.body !== 'undefined' ? matchValue(mockDispatch.body, body) : true
- const headersMatch = matchHeaders(mockDispatch, headers)
- return pathMatch && methodMatch && bodyMatch && headersMatch
-}
-function getResponseData (data) {
- if (Buffer.isBuffer(data)) {
- return data
- } else if (data instanceof Uint8Array) {
- return data
- } else if (data instanceof ArrayBuffer) {
- return data
- } else if (typeof data === 'object') {
- return JSON.stringify(data)
- } else {
- return data.toString()
- }
-}
-function getMockDispatch (mockDispatches, key) {
- const basePath = key.query ? buildURL(key.path, key.query) : key.path
- const resolvedPath = typeof basePath === 'string' ? safeUrl(basePath) : basePath
+const {
+ Readable,
+ Duplex,
+ PassThrough
+} = __nccwpck_require__(7075)
+const {
+ InvalidArgumentError,
+ InvalidReturnValueError,
+ RequestAbortedError
+} = __nccwpck_require__(8707)
+const util = __nccwpck_require__(3440)
+const { AsyncResource } = __nccwpck_require__(6698)
+const { addSignal, removeSignal } = __nccwpck_require__(158)
+const assert = __nccwpck_require__(4589)
- // Match path
- let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path }) => matchValue(safeUrl(path), resolvedPath))
- if (matchedMockDispatches.length === 0) {
- throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`)
- }
+const kResume = Symbol('resume')
- // Match method
- matchedMockDispatches = matchedMockDispatches.filter(({ method }) => matchValue(method, key.method))
- if (matchedMockDispatches.length === 0) {
- throw new MockNotMatchedError(`Mock dispatch not matched for method '${key.method}' on path '${resolvedPath}'`)
- }
+class PipelineRequest extends Readable {
+ constructor () {
+ super({ autoDestroy: true })
- // Match body
- matchedMockDispatches = matchedMockDispatches.filter(({ body }) => typeof body !== 'undefined' ? matchValue(body, key.body) : true)
- if (matchedMockDispatches.length === 0) {
- throw new MockNotMatchedError(`Mock dispatch not matched for body '${key.body}' on path '${resolvedPath}'`)
+ this[kResume] = null
}
- // Match headers
- matchedMockDispatches = matchedMockDispatches.filter((mockDispatch) => matchHeaders(mockDispatch, key.headers))
- if (matchedMockDispatches.length === 0) {
- const headers = typeof key.headers === 'object' ? JSON.stringify(key.headers) : key.headers
- throw new MockNotMatchedError(`Mock dispatch not matched for headers '${headers}' on path '${resolvedPath}'`)
+ _read () {
+ const { [kResume]: resume } = this
+
+ if (resume) {
+ this[kResume] = null
+ resume()
+ }
}
- return matchedMockDispatches[0]
-}
+ _destroy (err, callback) {
+ this._read()
-function addMockDispatch (mockDispatches, key, data) {
- const baseData = { timesInvoked: 0, times: 1, persist: false, consumed: false }
- const replyData = typeof data === 'function' ? { callback: data } : { ...data }
- const newMockDispatch = { ...baseData, ...key, pending: true, data: { error: null, ...replyData } }
- mockDispatches.push(newMockDispatch)
- return newMockDispatch
+ callback(err)
+ }
}
-function deleteMockDispatch (mockDispatches, key) {
- const index = mockDispatches.findIndex(dispatch => {
- if (!dispatch.consumed) {
- return false
- }
- return matchKey(dispatch, key)
- })
- if (index !== -1) {
- mockDispatches.splice(index, 1)
+class PipelineResponse extends Readable {
+ constructor (resume) {
+ super({ autoDestroy: true })
+ this[kResume] = resume
}
-}
-function buildKey (opts) {
- const { path, method, body, headers, query } = opts
- return {
- path,
- method,
- body,
- headers,
- query
+ _read () {
+ this[kResume]()
}
-}
-function generateKeyValues (data) {
- const keys = Object.keys(data)
- const result = []
- for (let i = 0; i < keys.length; ++i) {
- const key = keys[i]
- const value = data[key]
- const name = Buffer.from(`${key}`)
- if (Array.isArray(value)) {
- for (let j = 0; j < value.length; ++j) {
- result.push(name, Buffer.from(`${value[j]}`))
- }
- } else {
- result.push(name, Buffer.from(`${value}`))
+ _destroy (err, callback) {
+ if (!err && !this._readableState.endEmitted) {
+ err = new RequestAbortedError()
}
+
+ callback(err)
}
- return result
}
-/**
- * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
- * @param {number} statusCode
- */
-function getStatusText (statusCode) {
- return STATUS_CODES[statusCode] || 'unknown'
-}
+class PipelineHandler extends AsyncResource {
+ constructor (opts, handler) {
+ if (!opts || typeof opts !== 'object') {
+ throw new InvalidArgumentError('invalid opts')
+ }
-async function getResponse (body) {
- const buffers = []
- for await (const data of body) {
- buffers.push(data)
- }
- return Buffer.concat(buffers).toString('utf8')
-}
+ if (typeof handler !== 'function') {
+ throw new InvalidArgumentError('invalid handler')
+ }
-/**
- * Mock dispatch function used to simulate undici dispatches
- */
-function mockDispatch (opts, handler) {
- // Get mock dispatch from built key
- const key = buildKey(opts)
- const mockDispatch = getMockDispatch(this[kDispatches], key)
+ const { signal, method, opaque, onInfo, responseHeaders } = opts
- mockDispatch.timesInvoked++
+ if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
+ throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
+ }
- // Here's where we resolve a callback if a callback is present for the dispatch data.
- if (mockDispatch.data.callback) {
- mockDispatch.data = { ...mockDispatch.data, ...mockDispatch.data.callback(opts) }
- }
+ if (method === 'CONNECT') {
+ throw new InvalidArgumentError('invalid method')
+ }
- // Parse mockDispatch data
- const { data: { statusCode, data, headers, trailers, error }, delay, persist } = mockDispatch
- const { timesInvoked, times } = mockDispatch
+ if (onInfo && typeof onInfo !== 'function') {
+ throw new InvalidArgumentError('invalid onInfo callback')
+ }
- // If it's used up and not persistent, mark as consumed
- mockDispatch.consumed = !persist && timesInvoked >= times
- mockDispatch.pending = timesInvoked < times
+ super('UNDICI_PIPELINE')
- // If specified, trigger dispatch error
- if (error !== null) {
- deleteMockDispatch(this[kDispatches], key)
- handler.onError(error)
- return true
- }
+ this.opaque = opaque || null
+ this.responseHeaders = responseHeaders || null
+ this.handler = handler
+ this.abort = null
+ this.context = null
+ this.onInfo = onInfo || null
- // Handle the request with a delay if necessary
- if (typeof delay === 'number' && delay > 0) {
- setTimeout(() => {
- handleReply(this[kDispatches])
- }, delay)
- } else {
- handleReply(this[kDispatches])
+ this.req = new PipelineRequest().on('error', util.nop)
+
+ this.ret = new Duplex({
+ readableObjectMode: opts.objectMode,
+ autoDestroy: true,
+ read: () => {
+ const { body } = this
+
+ if (body?.resume) {
+ body.resume()
+ }
+ },
+ write: (chunk, encoding, callback) => {
+ const { req } = this
+
+ if (req.push(chunk, encoding) || req._readableState.destroyed) {
+ callback()
+ } else {
+ req[kResume] = callback
+ }
+ },
+ destroy: (err, callback) => {
+ const { body, req, res, ret, abort } = this
+
+ if (!err && !ret._readableState.endEmitted) {
+ err = new RequestAbortedError()
+ }
+
+ if (abort && err) {
+ abort()
+ }
+
+ util.destroy(body, err)
+ util.destroy(req, err)
+ util.destroy(res, err)
+
+ removeSignal(this)
+
+ callback(err)
+ }
+ }).on('prefinish', () => {
+ const { req } = this
+
+ // Node < 15 does not call _final in same tick.
+ req.push(null)
+ })
+
+ this.res = null
+
+ addSignal(this, signal)
}
- function handleReply (mockDispatches, _data = data) {
- // fetch's HeadersList is a 1D string array
- const optsHeaders = Array.isArray(opts.headers)
- ? buildHeadersFromArray(opts.headers)
- : opts.headers
- const body = typeof _data === 'function'
- ? _data({ ...opts, headers: optsHeaders })
- : _data
+ onConnect (abort, context) {
+ const { ret, res } = this
- // util.types.isPromise is likely needed for jest.
- if (isPromise(body)) {
- // If handleReply is asynchronous, throwing an error
- // in the callback will reject the promise, rather than
- // synchronously throw the error, which breaks some tests.
- // Rather, we wait for the callback to resolve if it is a
- // promise, and then re-run handleReply with the new body.
- body.then((newData) => handleReply(mockDispatches, newData))
+ if (this.reason) {
+ abort(this.reason)
return
}
- const responseData = getResponseData(body)
- const responseHeaders = generateKeyValues(headers)
- const responseTrailers = generateKeyValues(trailers)
+ assert(!res, 'pipeline cannot be retried')
+ assert(!ret.destroyed)
- handler.onConnect?.(err => handler.onError(err), null)
- handler.onHeaders?.(statusCode, responseHeaders, resume, getStatusText(statusCode))
- handler.onData?.(Buffer.from(responseData))
- handler.onComplete?.(responseTrailers)
- deleteMockDispatch(mockDispatches, key)
+ this.abort = abort
+ this.context = context
}
- function resume () {}
+ onHeaders (statusCode, rawHeaders, resume) {
+ const { opaque, handler, context } = this
- return true
-}
+ if (statusCode < 200) {
+ if (this.onInfo) {
+ const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
+ this.onInfo({ statusCode, headers })
+ }
+ return
+ }
-function buildMockDispatch () {
- const agent = this[kMockAgent]
- const origin = this[kOrigin]
- const originalDispatch = this[kOriginalDispatch]
+ this.res = new PipelineResponse(resume)
- return function dispatch (opts, handler) {
- if (agent.isMockActive) {
- try {
- mockDispatch.call(this, opts, handler)
- } catch (error) {
- if (error instanceof MockNotMatchedError) {
- const netConnect = agent[kGetNetConnect]()
- if (netConnect === false) {
- throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)`)
- }
- if (checkNetConnect(netConnect, origin)) {
- originalDispatch.call(this, opts, handler)
- } else {
- throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)`)
- }
- } else {
- throw error
- }
- }
- } else {
- originalDispatch.call(this, opts, handler)
+ let body
+ try {
+ this.handler = null
+ const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
+ body = this.runInAsyncScope(handler, null, {
+ statusCode,
+ headers,
+ opaque,
+ body: this.res,
+ context
+ })
+ } catch (err) {
+ this.res.on('error', util.nop)
+ throw err
+ }
+
+ if (!body || typeof body.on !== 'function') {
+ throw new InvalidReturnValueError('expected Readable')
}
+
+ body
+ .on('data', (chunk) => {
+ const { ret, body } = this
+
+ if (!ret.push(chunk) && body.pause) {
+ body.pause()
+ }
+ })
+ .on('error', (err) => {
+ const { ret } = this
+
+ util.destroy(ret, err)
+ })
+ .on('end', () => {
+ const { ret } = this
+
+ ret.push(null)
+ })
+ .on('close', () => {
+ const { ret } = this
+
+ if (!ret._readableState.ended) {
+ util.destroy(ret, new RequestAbortedError())
+ }
+ })
+
+ this.body = body
}
-}
-function checkNetConnect (netConnect, origin) {
- const url = new URL(origin)
- if (netConnect === true) {
- return true
- } else if (Array.isArray(netConnect) && netConnect.some((matcher) => matchValue(matcher, url.host))) {
- return true
+ onData (chunk) {
+ const { res } = this
+ return res.push(chunk)
}
- return false
-}
-function buildMockOptions (opts) {
- if (opts) {
- const { agent, ...mockOptions } = opts
- return mockOptions
+ onComplete (trailers) {
+ const { res } = this
+ res.push(null)
+ }
+
+ onError (err) {
+ const { ret } = this
+ this.handler = null
+ util.destroy(ret, err)
}
}
-module.exports = {
- getResponseData,
- getMockDispatch,
- addMockDispatch,
- deleteMockDispatch,
- buildKey,
- generateKeyValues,
- matchValue,
- getResponse,
- getStatusText,
- mockDispatch,
- buildMockDispatch,
- checkNetConnect,
- buildMockOptions,
- getHeaderByName,
- buildHeadersFromArray
+function pipeline (opts, handler) {
+ try {
+ const pipelineHandler = new PipelineHandler(opts, handler)
+ this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler)
+ return pipelineHandler.ret
+ } catch (err) {
+ return new PassThrough().destroy(err)
+ }
}
+module.exports = pipeline
+
/***/ }),
-/***/ 6573:
+/***/ 4043:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const { Transform } = __nccwpck_require__(7075)
-const { Console } = __nccwpck_require__(7540)
+const assert = __nccwpck_require__(4589)
+const { Readable } = __nccwpck_require__(9927)
+const { InvalidArgumentError, RequestAbortedError } = __nccwpck_require__(8707)
+const util = __nccwpck_require__(3440)
+const { getResolveErrorBodyCallback } = __nccwpck_require__(7655)
+const { AsyncResource } = __nccwpck_require__(6698)
-const PERSISTENT = process.versions.icu ? '✅' : 'Y '
-const NOT_PERSISTENT = process.versions.icu ? '❌' : 'N '
+class RequestHandler extends AsyncResource {
+ constructor (opts, callback) {
+ if (!opts || typeof opts !== 'object') {
+ throw new InvalidArgumentError('invalid opts')
+ }
-/**
- * Gets the output of `console.table(…)` as a string.
- */
-module.exports = class PendingInterceptorsFormatter {
- constructor ({ disableColors } = {}) {
- this.transform = new Transform({
- transform (chunk, _enc, cb) {
- cb(null, chunk)
+ const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError, highWaterMark } = opts
+
+ try {
+ if (typeof callback !== 'function') {
+ throw new InvalidArgumentError('invalid callback')
}
- })
- this.logger = new Console({
- stdout: this.transform,
- inspectOptions: {
- colors: !disableColors && !process.env.CI
+ if (highWaterMark && (typeof highWaterMark !== 'number' || highWaterMark < 0)) {
+ throw new InvalidArgumentError('invalid highWaterMark')
}
- })
+
+ if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
+ throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
+ }
+
+ if (method === 'CONNECT') {
+ throw new InvalidArgumentError('invalid method')
+ }
+
+ if (onInfo && typeof onInfo !== 'function') {
+ throw new InvalidArgumentError('invalid onInfo callback')
+ }
+
+ super('UNDICI_REQUEST')
+ } catch (err) {
+ if (util.isStream(body)) {
+ util.destroy(body.on('error', util.nop), err)
+ }
+ throw err
+ }
+
+ this.method = method
+ this.responseHeaders = responseHeaders || null
+ this.opaque = opaque || null
+ this.callback = callback
+ this.res = null
+ this.abort = null
+ this.body = body
+ this.trailers = {}
+ this.context = null
+ this.onInfo = onInfo || null
+ this.throwOnError = throwOnError
+ this.highWaterMark = highWaterMark
+ this.signal = signal
+ this.reason = null
+ this.removeAbortListener = null
+
+ if (util.isStream(body)) {
+ body.on('error', (err) => {
+ this.onError(err)
+ })
+ }
+
+ if (this.signal) {
+ if (this.signal.aborted) {
+ this.reason = this.signal.reason ?? new RequestAbortedError()
+ } else {
+ this.removeAbortListener = util.addAbortListener(this.signal, () => {
+ this.reason = this.signal.reason ?? new RequestAbortedError()
+ if (this.res) {
+ util.destroy(this.res.on('error', util.nop), this.reason)
+ } else if (this.abort) {
+ this.abort(this.reason)
+ }
+
+ if (this.removeAbortListener) {
+ this.res?.off('close', this.removeAbortListener)
+ this.removeAbortListener()
+ this.removeAbortListener = null
+ }
+ })
+ }
+ }
}
- format (pendingInterceptors) {
- const withPrettyHeaders = pendingInterceptors.map(
- ({ method, path, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
- Method: method,
- Origin: origin,
- Path: path,
- 'Status code': statusCode,
- Persistent: persist ? PERSISTENT : NOT_PERSISTENT,
- Invocations: timesInvoked,
- Remaining: persist ? Infinity : times - timesInvoked
- }))
+ onConnect (abort, context) {
+ if (this.reason) {
+ abort(this.reason)
+ return
+ }
- this.logger.table(withPrettyHeaders)
- return this.transform.read().toString()
+ assert(this.callback)
+
+ this.abort = abort
+ this.context = context
}
-}
+ onHeaders (statusCode, rawHeaders, resume, statusMessage) {
+ const { callback, opaque, abort, context, responseHeaders, highWaterMark } = this
-/***/ }),
+ const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
-/***/ 4638:
-/***/ ((module) => {
+ if (statusCode < 200) {
+ if (this.onInfo) {
+ this.onInfo({ statusCode, headers })
+ }
+ return
+ }
+ const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers
+ const contentType = parsedHeaders['content-type']
+ const contentLength = parsedHeaders['content-length']
+ const res = new Readable({
+ resume,
+ abort,
+ contentType,
+ contentLength: this.method !== 'HEAD' && contentLength
+ ? Number(contentLength)
+ : null,
+ highWaterMark
+ })
+ if (this.removeAbortListener) {
+ res.on('close', this.removeAbortListener)
+ }
-const singulars = {
- pronoun: 'it',
- is: 'is',
- was: 'was',
- this: 'this'
-}
+ this.callback = null
+ this.res = res
+ if (callback !== null) {
+ if (this.throwOnError && statusCode >= 400) {
+ this.runInAsyncScope(getResolveErrorBodyCallback, null,
+ { callback, body: res, contentType, statusCode, statusMessage, headers }
+ )
+ } else {
+ this.runInAsyncScope(callback, null, null, {
+ statusCode,
+ headers,
+ trailers: this.trailers,
+ opaque,
+ body: res,
+ context
+ })
+ }
+ }
+ }
-const plurals = {
- pronoun: 'they',
- is: 'are',
- was: 'were',
- this: 'these'
+ onData (chunk) {
+ return this.res.push(chunk)
+ }
+
+ onComplete (trailers) {
+ util.parseHeaders(trailers, this.trailers)
+ this.res.push(null)
+ }
+
+ onError (err) {
+ const { res, callback, body, opaque } = this
+
+ if (callback) {
+ // TODO: Does this need queueMicrotask?
+ this.callback = null
+ queueMicrotask(() => {
+ this.runInAsyncScope(callback, null, err, { opaque })
+ })
+ }
+
+ if (res) {
+ this.res = null
+ // Ensure all queued handlers are invoked before destroying res.
+ queueMicrotask(() => {
+ util.destroy(res, err)
+ })
+ }
+
+ if (body) {
+ this.body = null
+ util.destroy(body, err)
+ }
+
+ if (this.removeAbortListener) {
+ res?.off('close', this.removeAbortListener)
+ this.removeAbortListener()
+ this.removeAbortListener = null
+ }
+ }
}
-module.exports = class Pluralizer {
- constructor (singular, plural) {
- this.singular = singular
- this.plural = plural
+function request (opts, callback) {
+ if (callback === undefined) {
+ return new Promise((resolve, reject) => {
+ request.call(this, opts, (err, data) => {
+ return err ? reject(err) : resolve(data)
+ })
+ })
}
- pluralize (count) {
- const one = count === 1
- const keys = one ? singulars : plurals
- const noun = one ? this.singular : this.plural
- return { ...keys, count, noun }
+ try {
+ this.dispatch(opts, new RequestHandler(opts, callback))
+ } catch (err) {
+ if (typeof callback !== 'function') {
+ throw err
+ }
+ const opaque = opts?.opaque
+ queueMicrotask(() => callback(err, { opaque }))
}
}
+module.exports = request
+module.exports.RequestHandler = RequestHandler
-/***/ }),
-/***/ 7256:
-/***/ ((module) => {
+/***/ }),
+/***/ 3560:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-/**
- * This module offers an optimized timer implementation designed for scenarios
- * where high precision is not critical.
- *
- * The timer achieves faster performance by using a low-resolution approach,
- * with an accuracy target of within 500ms. This makes it particularly useful
- * for timers with delays of 1 second or more, where exact timing is less
- * crucial.
- *
- * It's important to note that Node.js timers are inherently imprecise, as
- * delays can occur due to the event loop being blocked by other operations.
- * Consequently, timers may trigger later than their scheduled time.
- */
-/**
- * The fastNow variable contains the internal fast timer clock value.
- *
- * @type {number}
- */
-let fastNow = 0
+const assert = __nccwpck_require__(4589)
+const { finished, PassThrough } = __nccwpck_require__(7075)
+const { InvalidArgumentError, InvalidReturnValueError } = __nccwpck_require__(8707)
+const util = __nccwpck_require__(3440)
+const { getResolveErrorBodyCallback } = __nccwpck_require__(7655)
+const { AsyncResource } = __nccwpck_require__(6698)
+const { addSignal, removeSignal } = __nccwpck_require__(158)
-/**
- * RESOLUTION_MS represents the target resolution time in milliseconds.
- *
- * @type {number}
- * @default 1000
- */
-const RESOLUTION_MS = 1e3
+class StreamHandler extends AsyncResource {
+ constructor (opts, factory, callback) {
+ if (!opts || typeof opts !== 'object') {
+ throw new InvalidArgumentError('invalid opts')
+ }
-/**
- * TICK_MS defines the desired interval in milliseconds between each tick.
- * The target value is set to half the resolution time, minus 1 ms, to account
- * for potential event loop overhead.
- *
- * @type {number}
- * @default 499
- */
-const TICK_MS = (RESOLUTION_MS >> 1) - 1
+ const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError } = opts
-/**
- * fastNowTimeout is a Node.js timer used to manage and process
- * the FastTimers stored in the `fastTimers` array.
- *
- * @type {NodeJS.Timeout}
- */
-let fastNowTimeout
+ try {
+ if (typeof callback !== 'function') {
+ throw new InvalidArgumentError('invalid callback')
+ }
-/**
- * The kFastTimer symbol is used to identify FastTimer instances.
- *
- * @type {Symbol}
- */
-const kFastTimer = Symbol('kFastTimer')
+ if (typeof factory !== 'function') {
+ throw new InvalidArgumentError('invalid factory')
+ }
-/**
- * The fastTimers array contains all active FastTimers.
- *
- * @type {FastTimer[]}
- */
-const fastTimers = []
+ if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
+ throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
+ }
-/**
- * These constants represent the various states of a FastTimer.
- */
+ if (method === 'CONNECT') {
+ throw new InvalidArgumentError('invalid method')
+ }
-/**
- * The `NOT_IN_LIST` constant indicates that the FastTimer is not included
- * in the `fastTimers` array. Timers with this status will not be processed
- * during the next tick by the `onTick` function.
- *
- * A FastTimer can be re-added to the `fastTimers` array by invoking the
- * `refresh` method on the FastTimer instance.
- *
- * @type {-2}
- */
-const NOT_IN_LIST = -2
+ if (onInfo && typeof onInfo !== 'function') {
+ throw new InvalidArgumentError('invalid onInfo callback')
+ }
-/**
- * The `TO_BE_CLEARED` constant indicates that the FastTimer is scheduled
- * for removal from the `fastTimers` array. A FastTimer in this state will
- * be removed in the next tick by the `onTick` function and will no longer
- * be processed.
- *
- * This status is also set when the `clear` method is called on the FastTimer instance.
- *
- * @type {-1}
- */
-const TO_BE_CLEARED = -1
+ super('UNDICI_STREAM')
+ } catch (err) {
+ if (util.isStream(body)) {
+ util.destroy(body.on('error', util.nop), err)
+ }
+ throw err
+ }
-/**
- * The `PENDING` constant signifies that the FastTimer is awaiting processing
- * in the next tick by the `onTick` function. Timers with this status will have
- * their `_idleStart` value set and their status updated to `ACTIVE` in the next tick.
- *
- * @type {0}
- */
-const PENDING = 0
+ this.responseHeaders = responseHeaders || null
+ this.opaque = opaque || null
+ this.factory = factory
+ this.callback = callback
+ this.res = null
+ this.abort = null
+ this.context = null
+ this.trailers = null
+ this.body = body
+ this.onInfo = onInfo || null
+ this.throwOnError = throwOnError || false
-/**
- * The `ACTIVE` constant indicates that the FastTimer is active and waiting
- * for its timer to expire. During the next tick, the `onTick` function will
- * check if the timer has expired, and if so, it will execute the associated callback.
- *
- * @type {1}
- */
-const ACTIVE = 1
+ if (util.isStream(body)) {
+ body.on('error', (err) => {
+ this.onError(err)
+ })
+ }
-/**
- * The onTick function processes the fastTimers array.
- *
- * @returns {void}
- */
-function onTick () {
- /**
- * Increment the fastNow value by the TICK_MS value, despite the actual time
- * that has passed since the last tick. This approach ensures independence
- * from the system clock and delays caused by a blocked event loop.
- *
- * @type {number}
- */
- fastNow += TICK_MS
+ addSignal(this, signal)
+ }
- /**
- * The `idx` variable is used to iterate over the `fastTimers` array.
- * Expired timers are removed by replacing them with the last element in the array.
- * Consequently, `idx` is only incremented when the current element is not removed.
- *
- * @type {number}
- */
- let idx = 0
+ onConnect (abort, context) {
+ if (this.reason) {
+ abort(this.reason)
+ return
+ }
- /**
- * The len variable will contain the length of the fastTimers array
- * and will be decremented when a FastTimer should be removed from the
- * fastTimers array.
- *
- * @type {number}
- */
- let len = fastTimers.length
+ assert(this.callback)
- while (idx < len) {
- /**
- * @type {FastTimer}
- */
- const timer = fastTimers[idx]
+ this.abort = abort
+ this.context = context
+ }
- // If the timer is in the ACTIVE state and the timer has expired, it will
- // be processed in the next tick.
- if (timer._state === PENDING) {
- // Set the _idleStart value to the fastNow value minus the TICK_MS value
- // to account for the time the timer was in the PENDING state.
- timer._idleStart = fastNow - TICK_MS
- timer._state = ACTIVE
- } else if (
- timer._state === ACTIVE &&
- fastNow >= timer._idleStart + timer._idleTimeout
- ) {
- timer._state = TO_BE_CLEARED
- timer._idleStart = -1
- timer._onTimeout(timer._timerArg)
- }
+ onHeaders (statusCode, rawHeaders, resume, statusMessage) {
+ const { factory, opaque, context, callback, responseHeaders } = this
- if (timer._state === TO_BE_CLEARED) {
- timer._state = NOT_IN_LIST
+ const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
- // Move the last element to the current index and decrement len if it is
- // not the only element in the array.
- if (--len !== 0) {
- fastTimers[idx] = fastTimers[len]
+ if (statusCode < 200) {
+ if (this.onInfo) {
+ this.onInfo({ statusCode, headers })
}
- } else {
- ++idx
+ return
}
- }
- // Set the length of the fastTimers array to the new length and thus
- // removing the excess FastTimers elements from the array.
- fastTimers.length = len
+ this.factory = null
- // If there are still active FastTimers in the array, refresh the Timer.
- // If there are no active FastTimers, the timer will be refreshed again
- // when a new FastTimer is instantiated.
- if (fastTimers.length !== 0) {
- refreshTimeout()
- }
-}
+ let res
-function refreshTimeout () {
- // If the fastNowTimeout is already set, refresh it.
- if (fastNowTimeout) {
- fastNowTimeout.refresh()
- // fastNowTimeout is not instantiated yet, create a new Timer.
- } else {
- clearTimeout(fastNowTimeout)
- fastNowTimeout = setTimeout(onTick, TICK_MS)
+ if (this.throwOnError && statusCode >= 400) {
+ const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers
+ const contentType = parsedHeaders['content-type']
+ res = new PassThrough()
- // If the Timer has an unref method, call it to allow the process to exit if
- // there are no other active handles.
- if (fastNowTimeout.unref) {
- fastNowTimeout.unref()
- }
- }
-}
+ this.callback = null
+ this.runInAsyncScope(getResolveErrorBodyCallback, null,
+ { callback, body: res, contentType, statusCode, statusMessage, headers }
+ )
+ } else {
+ if (factory === null) {
+ return
+ }
-/**
- * The `FastTimer` class is a data structure designed to store and manage
- * timer information.
- */
-class FastTimer {
- [kFastTimer] = true
+ res = this.runInAsyncScope(factory, null, {
+ statusCode,
+ headers,
+ opaque,
+ context
+ })
- /**
- * The state of the timer, which can be one of the following:
- * - NOT_IN_LIST (-2)
- * - TO_BE_CLEARED (-1)
- * - PENDING (0)
- * - ACTIVE (1)
- *
- * @type {-2|-1|0|1}
- * @private
- */
- _state = NOT_IN_LIST
+ if (
+ !res ||
+ typeof res.write !== 'function' ||
+ typeof res.end !== 'function' ||
+ typeof res.on !== 'function'
+ ) {
+ throw new InvalidReturnValueError('expected Writable')
+ }
- /**
- * The number of milliseconds to wait before calling the callback.
- *
- * @type {number}
- * @private
- */
- _idleTimeout = -1
+ // TODO: Avoid finished. It registers an unnecessary amount of listeners.
+ finished(res, { readable: false }, (err) => {
+ const { callback, res, opaque, trailers, abort } = this
- /**
- * The time in milliseconds when the timer was started. This value is used to
- * calculate when the timer should expire.
- *
- * @type {number}
- * @default -1
- * @private
- */
- _idleStart = -1
+ this.res = null
+ if (err || !res.readable) {
+ util.destroy(res, err)
+ }
- /**
- * The function to be executed when the timer expires.
- * @type {Function}
- * @private
- */
- _onTimeout
+ this.callback = null
+ this.runInAsyncScope(callback, null, err || null, { opaque, trailers })
- /**
- * The argument to be passed to the callback when the timer expires.
- *
- * @type {*}
- * @private
- */
- _timerArg
+ if (err) {
+ abort()
+ }
+ })
+ }
- /**
- * @constructor
- * @param {Function} callback A function to be executed after the timer
- * expires.
- * @param {number} delay The time, in milliseconds that the timer should wait
- * before the specified function or code is executed.
- * @param {*} arg
- */
- constructor (callback, delay, arg) {
- this._onTimeout = callback
- this._idleTimeout = delay
- this._timerArg = arg
+ res.on('drain', resume)
- this.refresh()
+ this.res = res
+
+ const needDrain = res.writableNeedDrain !== undefined
+ ? res.writableNeedDrain
+ : res._writableState?.needDrain
+
+ return needDrain !== true
}
- /**
- * Sets the timer's start time to the current time, and reschedules the timer
- * to call its callback at the previously specified duration adjusted to the
- * current time.
- * Using this on a timer that has already called its callback will reactivate
- * the timer.
- *
- * @returns {void}
- */
- refresh () {
- // In the special case that the timer is not in the list of active timers,
- // add it back to the array to be processed in the next tick by the onTick
- // function.
- if (this._state === NOT_IN_LIST) {
- fastTimers.push(this)
- }
+ onData (chunk) {
+ const { res } = this
- // If the timer is the only active timer, refresh the fastNowTimeout for
- // better resolution.
- if (!fastNowTimeout || fastTimers.length === 1) {
- refreshTimeout()
+ return res ? res.write(chunk) : true
+ }
+
+ onComplete (trailers) {
+ const { res } = this
+
+ removeSignal(this)
+
+ if (!res) {
+ return
}
- // Setting the state to PENDING will cause the timer to be reset in the
- // next tick by the onTick function.
- this._state = PENDING
+ this.trailers = util.parseHeaders(trailers)
+
+ res.end()
}
- /**
- * The `clear` method cancels the timer, preventing it from executing.
- *
- * @returns {void}
- * @private
- */
- clear () {
- // Set the state to TO_BE_CLEARED to mark the timer for removal in the next
- // tick by the onTick function.
- this._state = TO_BE_CLEARED
+ onError (err) {
+ const { res, callback, opaque, body } = this
- // Reset the _idleStart value to -1 to indicate that the timer is no longer
- // active.
- this._idleStart = -1
+ removeSignal(this)
+
+ this.factory = null
+
+ if (res) {
+ this.res = null
+ util.destroy(res, err)
+ } else if (callback) {
+ this.callback = null
+ queueMicrotask(() => {
+ this.runInAsyncScope(callback, null, err, { opaque })
+ })
+ }
+
+ if (body) {
+ this.body = null
+ util.destroy(body, err)
+ }
}
}
-/**
- * This module exports a setTimeout and clearTimeout function that can be
- * used as a drop-in replacement for the native functions.
- */
-module.exports = {
- /**
- * The setTimeout() method sets a timer which executes a function once the
- * timer expires.
- * @param {Function} callback A function to be executed after the timer
- * expires.
- * @param {number} delay The time, in milliseconds that the timer should
- * wait before the specified function or code is executed.
- * @param {*} [arg] An optional argument to be passed to the callback function
- * when the timer expires.
- * @returns {NodeJS.Timeout|FastTimer}
- */
- setTimeout (callback, delay, arg) {
- // If the delay is less than or equal to the RESOLUTION_MS value return a
- // native Node.js Timer instance.
- return delay <= RESOLUTION_MS
- ? setTimeout(callback, delay, arg)
- : new FastTimer(callback, delay, arg)
- },
- /**
- * The clearTimeout method cancels an instantiated Timer previously created
- * by calling setTimeout.
- *
- * @param {NodeJS.Timeout|FastTimer} timeout
- */
- clearTimeout (timeout) {
- // If the timeout is a FastTimer, call its own clear method.
- if (timeout[kFastTimer]) {
- /**
- * @type {FastTimer}
- */
- timeout.clear()
- // Otherwise it is an instance of a native NodeJS.Timeout, so call the
- // Node.js native clearTimeout function.
- } else {
- clearTimeout(timeout)
+function stream (opts, factory, callback) {
+ if (callback === undefined) {
+ return new Promise((resolve, reject) => {
+ stream.call(this, opts, factory, (err, data) => {
+ return err ? reject(err) : resolve(data)
+ })
+ })
+ }
+
+ try {
+ this.dispatch(opts, new StreamHandler(opts, factory, callback))
+ } catch (err) {
+ if (typeof callback !== 'function') {
+ throw err
}
- },
- /**
- * The setFastTimeout() method sets a fastTimer which executes a function once
- * the timer expires.
- * @param {Function} callback A function to be executed after the timer
- * expires.
- * @param {number} delay The time, in milliseconds that the timer should
- * wait before the specified function or code is executed.
- * @param {*} [arg] An optional argument to be passed to the callback function
- * when the timer expires.
- * @returns {FastTimer}
- */
- setFastTimeout (callback, delay, arg) {
- return new FastTimer(callback, delay, arg)
- },
- /**
- * The clearTimeout method cancels an instantiated FastTimer previously
- * created by calling setFastTimeout.
- *
- * @param {FastTimer} timeout
- */
- clearFastTimeout (timeout) {
- timeout.clear()
- },
- /**
- * The now method returns the value of the internal fast timer clock.
- *
- * @returns {number}
- */
- now () {
- return fastNow
- },
- /**
- * Trigger the onTick function to process the fastTimers array.
- * Exported for testing purposes only.
- * Marking as deprecated to discourage any use outside of testing.
- * @deprecated
- * @param {number} [delay=0] The delay in milliseconds to add to the now value.
- */
- tick (delay = 0) {
- fastNow += delay - RESOLUTION_MS + 1
- onTick()
- onTick()
- },
- /**
- * Reset FastTimers.
- * Exported for testing purposes only.
- * Marking as deprecated to discourage any use outside of testing.
- * @deprecated
- */
- reset () {
- fastNow = 0
- fastTimers.length = 0
- clearTimeout(fastNowTimeout)
- fastNowTimeout = null
- },
- /**
- * Exporting for testing purposes only.
- * Marking as deprecated to discourage any use outside of testing.
- * @deprecated
- */
- kFastTimer
+ const opaque = opts?.opaque
+ queueMicrotask(() => callback(err, { opaque }))
+ }
}
+module.exports = stream
+
/***/ }),
-/***/ 2185:
+/***/ 1882:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const { kConstruct } = __nccwpck_require__(3202)
-const { urlEquals, getFieldValues } = __nccwpck_require__(4159)
-const { kEnumerableProperty, isDisturbed } = __nccwpck_require__(7375)
-const { webidl } = __nccwpck_require__(220)
-const { Response, cloneResponse, fromInnerResponse } = __nccwpck_require__(6678)
-const { Request, fromInnerRequest } = __nccwpck_require__(7412)
-const { kState } = __nccwpck_require__(1944)
-const { fetching } = __nccwpck_require__(8033)
-const { urlIsHttpHttpsScheme, createDeferredPromise, readAllBytes } = __nccwpck_require__(7241)
+const { InvalidArgumentError, SocketError } = __nccwpck_require__(8707)
+const { AsyncResource } = __nccwpck_require__(6698)
+const util = __nccwpck_require__(3440)
+const { addSignal, removeSignal } = __nccwpck_require__(158)
const assert = __nccwpck_require__(4589)
-/**
- * @see https://w3c.github.io/ServiceWorker/#dfn-cache-batch-operation
- * @typedef {Object} CacheBatchOperation
- * @property {'delete' | 'put'} type
- * @property {any} request
- * @property {any} response
- * @property {import('../../types/cache').CacheQueryOptions} options
- */
-
-/**
- * @see https://w3c.github.io/ServiceWorker/#dfn-request-response-list
- * @typedef {[any, any][]} requestResponseList
- */
-
-class Cache {
- /**
- * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list
- * @type {requestResponseList}
- */
- #relevantRequestResponseList
+class UpgradeHandler extends AsyncResource {
+ constructor (opts, callback) {
+ if (!opts || typeof opts !== 'object') {
+ throw new InvalidArgumentError('invalid opts')
+ }
- constructor () {
- if (arguments[0] !== kConstruct) {
- webidl.illegalConstructor()
+ if (typeof callback !== 'function') {
+ throw new InvalidArgumentError('invalid callback')
}
- webidl.util.markAsUncloneable(this)
- this.#relevantRequestResponseList = arguments[1]
- }
+ const { signal, opaque, responseHeaders } = opts
- async match (request, options = {}) {
- webidl.brandCheck(this, Cache)
+ if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
+ throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
+ }
- const prefix = 'Cache.match'
- webidl.argumentLengthCheck(arguments, 1, prefix)
+ super('UNDICI_UPGRADE')
- request = webidl.converters.RequestInfo(request, prefix, 'request')
- options = webidl.converters.CacheQueryOptions(options, prefix, 'options')
+ this.responseHeaders = responseHeaders || null
+ this.opaque = opaque || null
+ this.callback = callback
+ this.abort = null
+ this.context = null
- const p = this.#internalMatchAll(request, options, 1)
+ addSignal(this, signal)
+ }
- if (p.length === 0) {
+ onConnect (abort, context) {
+ if (this.reason) {
+ abort(this.reason)
return
}
- return p[0]
- }
-
- async matchAll (request = undefined, options = {}) {
- webidl.brandCheck(this, Cache)
-
- const prefix = 'Cache.matchAll'
- if (request !== undefined) request = webidl.converters.RequestInfo(request, prefix, 'request')
- options = webidl.converters.CacheQueryOptions(options, prefix, 'options')
+ assert(this.callback)
- return this.#internalMatchAll(request, options)
+ this.abort = abort
+ this.context = null
}
- async add (request) {
- webidl.brandCheck(this, Cache)
-
- const prefix = 'Cache.add'
- webidl.argumentLengthCheck(arguments, 1, prefix)
-
- request = webidl.converters.RequestInfo(request, prefix, 'request')
-
- // 1.
- const requests = [request]
-
- // 2.
- const responseArrayPromise = this.addAll(requests)
-
- // 3.
- return await responseArrayPromise
+ onHeaders () {
+ throw new SocketError('bad upgrade', null)
}
- async addAll (requests) {
- webidl.brandCheck(this, Cache)
+ onUpgrade (statusCode, rawHeaders, socket) {
+ assert(statusCode === 101)
- const prefix = 'Cache.addAll'
- webidl.argumentLengthCheck(arguments, 1, prefix)
+ const { callback, opaque, context } = this
- // 1.
- const responsePromises = []
+ removeSignal(this)
- // 2.
- const requestList = []
+ this.callback = null
+ const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
+ this.runInAsyncScope(callback, null, null, {
+ headers,
+ socket,
+ opaque,
+ context
+ })
+ }
- // 3.
- for (let request of requests) {
- if (request === undefined) {
- throw webidl.errors.conversionFailed({
- prefix,
- argument: 'Argument 1',
- types: ['undefined is not allowed']
- })
- }
+ onError (err) {
+ const { callback, opaque } = this
- request = webidl.converters.RequestInfo(request)
+ removeSignal(this)
- if (typeof request === 'string') {
- continue
- }
+ if (callback) {
+ this.callback = null
+ queueMicrotask(() => {
+ this.runInAsyncScope(callback, null, err, { opaque })
+ })
+ }
+ }
+}
- // 3.1
- const r = request[kState]
+function upgrade (opts, callback) {
+ if (callback === undefined) {
+ return new Promise((resolve, reject) => {
+ upgrade.call(this, opts, (err, data) => {
+ return err ? reject(err) : resolve(data)
+ })
+ })
+ }
- // 3.2
- if (!urlIsHttpHttpsScheme(r.url) || r.method !== 'GET') {
- throw webidl.errors.exception({
- header: prefix,
- message: 'Expected http/s scheme when method is not GET.'
- })
- }
+ try {
+ const upgradeHandler = new UpgradeHandler(opts, callback)
+ this.dispatch({
+ ...opts,
+ method: opts.method || 'GET',
+ upgrade: opts.protocol || 'Websocket'
+ }, upgradeHandler)
+ } catch (err) {
+ if (typeof callback !== 'function') {
+ throw err
}
+ const opaque = opts?.opaque
+ queueMicrotask(() => callback(err, { opaque }))
+ }
+}
- // 4.
- /** @type {ReturnType[]} */
- const fetchControllers = []
-
- // 5.
- for (const request of requests) {
- // 5.1
- const r = new Request(request)[kState]
+module.exports = upgrade
- // 5.2
- if (!urlIsHttpHttpsScheme(r.url)) {
- throw webidl.errors.exception({
- header: prefix,
- message: 'Expected http/s scheme.'
- })
- }
- // 5.4
- r.initiator = 'fetch'
- r.destination = 'subresource'
+/***/ }),
- // 5.5
- requestList.push(r)
+/***/ 6615:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 5.6
- const responsePromise = createDeferredPromise()
- // 5.7
- fetchControllers.push(fetching({
- request: r,
- processResponse (response) {
- // 1.
- if (response.type === 'error' || response.status === 206 || response.status < 200 || response.status > 299) {
- responsePromise.reject(webidl.errors.exception({
- header: 'Cache.addAll',
- message: 'Received an invalid status code or the request failed.'
- }))
- } else if (response.headersList.contains('vary')) { // 2.
- // 2.1
- const fieldValues = getFieldValues(response.headersList.get('vary'))
- // 2.2
- for (const fieldValue of fieldValues) {
- // 2.2.1
- if (fieldValue === '*') {
- responsePromise.reject(webidl.errors.exception({
- header: 'Cache.addAll',
- message: 'invalid vary field value'
- }))
+module.exports.request = __nccwpck_require__(4043)
+module.exports.stream = __nccwpck_require__(3560)
+module.exports.pipeline = __nccwpck_require__(6862)
+module.exports.upgrade = __nccwpck_require__(1882)
+module.exports.connect = __nccwpck_require__(2279)
- for (const controller of fetchControllers) {
- controller.abort()
- }
- return
- }
- }
- }
- },
- processResponseEndOfBody (response) {
- // 1.
- if (response.aborted) {
- responsePromise.reject(new DOMException('aborted', 'AbortError'))
- return
- }
+/***/ }),
- // 2.
- responsePromise.resolve(response)
- }
- }))
+/***/ 9927:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 5.8
- responsePromises.push(responsePromise.promise)
- }
+// Ported from https://github.com/nodejs/undici/pull/907
- // 6.
- const p = Promise.all(responsePromises)
- // 7.
- const responses = await p
- // 7.1
- const operations = []
+const assert = __nccwpck_require__(4589)
+const { Readable } = __nccwpck_require__(7075)
+const { RequestAbortedError, NotSupportedError, InvalidArgumentError, AbortError } = __nccwpck_require__(8707)
+const util = __nccwpck_require__(3440)
+const { ReadableStreamFrom } = __nccwpck_require__(3440)
- // 7.2
- let index = 0
+const kConsume = Symbol('kConsume')
+const kReading = Symbol('kReading')
+const kBody = Symbol('kBody')
+const kAbort = Symbol('kAbort')
+const kContentType = Symbol('kContentType')
+const kContentLength = Symbol('kContentLength')
- // 7.3
- for (const response of responses) {
- // 7.3.1
- /** @type {CacheBatchOperation} */
- const operation = {
- type: 'put', // 7.3.2
- request: requestList[index], // 7.3.3
- response // 7.3.4
- }
+const noop = () => {}
- operations.push(operation) // 7.3.5
+class BodyReadable extends Readable {
+ constructor ({
+ resume,
+ abort,
+ contentType = '',
+ contentLength,
+ highWaterMark = 64 * 1024 // Same as nodejs fs streams.
+ }) {
+ super({
+ autoDestroy: true,
+ read: resume,
+ highWaterMark
+ })
- index++ // 7.3.6
- }
+ this._readableState.dataEmitted = false
- // 7.5
- const cacheJobPromise = createDeferredPromise()
+ this[kAbort] = abort
+ this[kConsume] = null
+ this[kBody] = null
+ this[kContentType] = contentType
+ this[kContentLength] = contentLength
- // 7.6.1
- let errorData = null
+ // Is stream being consumed through Readable API?
+ // This is an optimization so that we avoid checking
+ // for 'data' and 'readable' listeners in the hot path
+ // inside push().
+ this[kReading] = false
+ }
- // 7.6.2
- try {
- this.#batchCacheOperations(operations)
- } catch (e) {
- errorData = e
+ destroy (err) {
+ if (!err && !this._readableState.endEmitted) {
+ err = new RequestAbortedError()
}
- // 7.6.3
- queueMicrotask(() => {
- // 7.6.3.1
- if (errorData === null) {
- cacheJobPromise.resolve(undefined)
- } else {
- // 7.6.3.2
- cacheJobPromise.reject(errorData)
- }
- })
+ if (err) {
+ this[kAbort]()
+ }
- // 7.7
- return cacheJobPromise.promise
+ return super.destroy(err)
}
- async put (request, response) {
- webidl.brandCheck(this, Cache)
-
- const prefix = 'Cache.put'
- webidl.argumentLengthCheck(arguments, 2, prefix)
-
- request = webidl.converters.RequestInfo(request, prefix, 'request')
- response = webidl.converters.Response(response, prefix, 'response')
-
- // 1.
- let innerRequest = null
-
- // 2.
- if (request instanceof Request) {
- innerRequest = request[kState]
- } else { // 3.
- innerRequest = new Request(request)[kState]
+ _destroy (err, callback) {
+ // Workaround for Node "bug". If the stream is destroyed in same
+ // tick as it is created, then a user who is waiting for a
+ // promise (i.e micro tick) for installing a 'error' listener will
+ // never get a chance and will always encounter an unhandled exception.
+ if (!this[kReading]) {
+ setImmediate(() => {
+ callback(err)
+ })
+ } else {
+ callback(err)
}
+ }
- // 4.
- if (!urlIsHttpHttpsScheme(innerRequest.url) || innerRequest.method !== 'GET') {
- throw webidl.errors.exception({
- header: prefix,
- message: 'Expected an http/s scheme when method is not GET'
- })
+ on (ev, ...args) {
+ if (ev === 'data' || ev === 'readable') {
+ this[kReading] = true
}
+ return super.on(ev, ...args)
+ }
- // 5.
- const innerResponse = response[kState]
+ addListener (ev, ...args) {
+ return this.on(ev, ...args)
+ }
- // 6.
- if (innerResponse.status === 206) {
- throw webidl.errors.exception({
- header: prefix,
- message: 'Got 206 status'
- })
+ off (ev, ...args) {
+ const ret = super.off(ev, ...args)
+ if (ev === 'data' || ev === 'readable') {
+ this[kReading] = (
+ this.listenerCount('data') > 0 ||
+ this.listenerCount('readable') > 0
+ )
}
+ return ret
+ }
- // 7.
- if (innerResponse.headersList.contains('vary')) {
- // 7.1.
- const fieldValues = getFieldValues(innerResponse.headersList.get('vary'))
+ removeListener (ev, ...args) {
+ return this.off(ev, ...args)
+ }
- // 7.2.
- for (const fieldValue of fieldValues) {
- // 7.2.1
- if (fieldValue === '*') {
- throw webidl.errors.exception({
- header: prefix,
- message: 'Got * vary field value'
- })
- }
- }
+ push (chunk) {
+ if (this[kConsume] && chunk !== null) {
+ consumePush(this[kConsume], chunk)
+ return this[kReading] ? super.push(chunk) : true
}
+ return super.push(chunk)
+ }
- // 8.
- if (innerResponse.body && (isDisturbed(innerResponse.body.stream) || innerResponse.body.stream.locked)) {
- throw webidl.errors.exception({
- header: prefix,
- message: 'Response body is locked or disturbed'
- })
- }
+ // https://fetch.spec.whatwg.org/#dom-body-text
+ async text () {
+ return consume(this, 'text')
+ }
- // 9.
- const clonedResponse = cloneResponse(innerResponse)
+ // https://fetch.spec.whatwg.org/#dom-body-json
+ async json () {
+ return consume(this, 'json')
+ }
- // 10.
- const bodyReadPromise = createDeferredPromise()
+ // https://fetch.spec.whatwg.org/#dom-body-blob
+ async blob () {
+ return consume(this, 'blob')
+ }
- // 11.
- if (innerResponse.body != null) {
- // 11.1
- const stream = innerResponse.body.stream
+ // https://fetch.spec.whatwg.org/#dom-body-bytes
+ async bytes () {
+ return consume(this, 'bytes')
+ }
- // 11.2
- const reader = stream.getReader()
+ // https://fetch.spec.whatwg.org/#dom-body-arraybuffer
+ async arrayBuffer () {
+ return consume(this, 'arrayBuffer')
+ }
- // 11.3
- readAllBytes(reader).then(bodyReadPromise.resolve, bodyReadPromise.reject)
- } else {
- bodyReadPromise.resolve(undefined)
- }
+ // https://fetch.spec.whatwg.org/#dom-body-formdata
+ async formData () {
+ // TODO: Implement.
+ throw new NotSupportedError()
+ }
- // 12.
- /** @type {CacheBatchOperation[]} */
- const operations = []
+ // https://fetch.spec.whatwg.org/#dom-body-bodyused
+ get bodyUsed () {
+ return util.isDisturbed(this)
+ }
- // 13.
- /** @type {CacheBatchOperation} */
- const operation = {
- type: 'put', // 14.
- request: innerRequest, // 15.
- response: clonedResponse // 16.
+ // https://fetch.spec.whatwg.org/#dom-body-body
+ get body () {
+ if (!this[kBody]) {
+ this[kBody] = ReadableStreamFrom(this)
+ if (this[kConsume]) {
+ // TODO: Is this the best way to force a lock?
+ this[kBody].getReader() // Ensure stream is locked.
+ assert(this[kBody].locked)
+ }
}
+ return this[kBody]
+ }
- // 17.
- operations.push(operation)
-
- // 19.
- const bytes = await bodyReadPromise.promise
+ async dump (opts) {
+ let limit = Number.isFinite(opts?.limit) ? opts.limit : 128 * 1024
+ const signal = opts?.signal
- if (clonedResponse.body != null) {
- clonedResponse.body.source = bytes
+ if (signal != null && (typeof signal !== 'object' || !('aborted' in signal))) {
+ throw new InvalidArgumentError('signal must be an AbortSignal')
}
- // 19.1
- const cacheJobPromise = createDeferredPromise()
-
- // 19.2.1
- let errorData = null
+ signal?.throwIfAborted()
- // 19.2.2
- try {
- this.#batchCacheOperations(operations)
- } catch (e) {
- errorData = e
+ if (this._readableState.closeEmitted) {
+ return null
}
- // 19.2.3
- queueMicrotask(() => {
- // 19.2.3.1
- if (errorData === null) {
- cacheJobPromise.resolve()
- } else { // 19.2.3.2
- cacheJobPromise.reject(errorData)
+ return await new Promise((resolve, reject) => {
+ if (this[kContentLength] > limit) {
+ this.destroy(new AbortError())
}
- })
- return cacheJobPromise.promise
- }
-
- async delete (request, options = {}) {
- webidl.brandCheck(this, Cache)
-
- const prefix = 'Cache.delete'
- webidl.argumentLengthCheck(arguments, 1, prefix)
-
- request = webidl.converters.RequestInfo(request, prefix, 'request')
- options = webidl.converters.CacheQueryOptions(options, prefix, 'options')
+ const onAbort = () => {
+ this.destroy(signal.reason ?? new AbortError())
+ }
+ signal?.addEventListener('abort', onAbort)
- /**
- * @type {Request}
- */
- let r = null
+ this
+ .on('close', function () {
+ signal?.removeEventListener('abort', onAbort)
+ if (signal?.aborted) {
+ reject(signal.reason ?? new AbortError())
+ } else {
+ resolve(null)
+ }
+ })
+ .on('error', noop)
+ .on('data', function (chunk) {
+ limit -= chunk.length
+ if (limit <= 0) {
+ this.destroy()
+ }
+ })
+ .resume()
+ })
+ }
+}
- if (request instanceof Request) {
- r = request[kState]
+// https://streams.spec.whatwg.org/#readablestream-locked
+function isLocked (self) {
+ // Consume is an implicit lock.
+ return (self[kBody] && self[kBody].locked === true) || self[kConsume]
+}
- if (r.method !== 'GET' && !options.ignoreMethod) {
- return false
+// https://fetch.spec.whatwg.org/#body-unusable
+function isUnusable (self) {
+ return util.isDisturbed(self) || isLocked(self)
+}
+
+async function consume (stream, type) {
+ assert(!stream[kConsume])
+
+ return new Promise((resolve, reject) => {
+ if (isUnusable(stream)) {
+ const rState = stream._readableState
+ if (rState.destroyed && rState.closeEmitted === false) {
+ stream
+ .on('error', err => {
+ reject(err)
+ })
+ .on('close', () => {
+ reject(new TypeError('unusable'))
+ })
+ } else {
+ reject(rState.errored ?? new TypeError('unusable'))
}
} else {
- assert(typeof request === 'string')
-
- r = new Request(request)[kState]
- }
+ queueMicrotask(() => {
+ stream[kConsume] = {
+ type,
+ stream,
+ resolve,
+ reject,
+ length: 0,
+ body: []
+ }
- /** @type {CacheBatchOperation[]} */
- const operations = []
+ stream
+ .on('error', function (err) {
+ consumeFinish(this[kConsume], err)
+ })
+ .on('close', function () {
+ if (this[kConsume].body !== null) {
+ consumeFinish(this[kConsume], new RequestAbortedError())
+ }
+ })
- /** @type {CacheBatchOperation} */
- const operation = {
- type: 'delete',
- request: r,
- options
+ consumeStart(stream[kConsume])
+ })
}
+ })
+}
- operations.push(operation)
-
- const cacheJobPromise = createDeferredPromise()
+function consumeStart (consume) {
+ if (consume.body === null) {
+ return
+ }
- let errorData = null
- let requestResponses
+ const { _readableState: state } = consume.stream
- try {
- requestResponses = this.#batchCacheOperations(operations)
- } catch (e) {
- errorData = e
+ if (state.bufferIndex) {
+ const start = state.bufferIndex
+ const end = state.buffer.length
+ for (let n = start; n < end; n++) {
+ consumePush(consume, state.buffer[n])
+ }
+ } else {
+ for (const chunk of state.buffer) {
+ consumePush(consume, chunk)
}
+ }
- queueMicrotask(() => {
- if (errorData === null) {
- cacheJobPromise.resolve(!!requestResponses?.length)
- } else {
- cacheJobPromise.reject(errorData)
- }
+ if (state.endEmitted) {
+ consumeEnd(this[kConsume])
+ } else {
+ consume.stream.on('end', function () {
+ consumeEnd(this[kConsume])
})
-
- return cacheJobPromise.promise
}
- /**
- * @see https://w3c.github.io/ServiceWorker/#dom-cache-keys
- * @param {any} request
- * @param {import('../../types/cache').CacheQueryOptions} options
- * @returns {Promise}
- */
- async keys (request = undefined, options = {}) {
- webidl.brandCheck(this, Cache)
-
- const prefix = 'Cache.keys'
+ consume.stream.resume()
- if (request !== undefined) request = webidl.converters.RequestInfo(request, prefix, 'request')
- options = webidl.converters.CacheQueryOptions(options, prefix, 'options')
+ while (consume.stream.read() != null) {
+ // Loop
+ }
+}
- // 1.
- let r = null
+/**
+ * @param {Buffer[]} chunks
+ * @param {number} length
+ */
+function chunksDecode (chunks, length) {
+ if (chunks.length === 0 || length === 0) {
+ return ''
+ }
+ const buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks, length)
+ const bufferLength = buffer.length
- // 2.
- if (request !== undefined) {
- // 2.1
- if (request instanceof Request) {
- // 2.1.1
- r = request[kState]
+ // Skip BOM.
+ const start =
+ bufferLength > 2 &&
+ buffer[0] === 0xef &&
+ buffer[1] === 0xbb &&
+ buffer[2] === 0xbf
+ ? 3
+ : 0
+ return buffer.utf8Slice(start, bufferLength)
+}
- // 2.1.2
- if (r.method !== 'GET' && !options.ignoreMethod) {
- return []
- }
- } else if (typeof request === 'string') { // 2.2
- r = new Request(request)[kState]
- }
- }
+/**
+ * @param {Buffer[]} chunks
+ * @param {number} length
+ * @returns {Uint8Array}
+ */
+function chunksConcat (chunks, length) {
+ if (chunks.length === 0 || length === 0) {
+ return new Uint8Array(0)
+ }
+ if (chunks.length === 1) {
+ // fast-path
+ return new Uint8Array(chunks[0])
+ }
+ const buffer = new Uint8Array(Buffer.allocUnsafeSlow(length).buffer)
- // 4.
- const promise = createDeferredPromise()
+ let offset = 0
+ for (let i = 0; i < chunks.length; ++i) {
+ const chunk = chunks[i]
+ buffer.set(chunk, offset)
+ offset += chunk.length
+ }
- // 5.
- // 5.1
- const requests = []
+ return buffer
+}
- // 5.2
- if (request === undefined) {
- // 5.2.1
- for (const requestResponse of this.#relevantRequestResponseList) {
- // 5.2.1.1
- requests.push(requestResponse[0])
- }
- } else { // 5.3
- // 5.3.1
- const requestResponses = this.#queryCache(r, options)
+function consumeEnd (consume) {
+ const { type, body, resolve, stream, length } = consume
- // 5.3.2
- for (const requestResponse of requestResponses) {
- // 5.3.2.1
- requests.push(requestResponse[0])
- }
+ try {
+ if (type === 'text') {
+ resolve(chunksDecode(body, length))
+ } else if (type === 'json') {
+ resolve(JSON.parse(chunksDecode(body, length)))
+ } else if (type === 'arrayBuffer') {
+ resolve(chunksConcat(body, length).buffer)
+ } else if (type === 'blob') {
+ resolve(new Blob(body, { type: stream[kContentType] }))
+ } else if (type === 'bytes') {
+ resolve(chunksConcat(body, length))
}
- // 5.4
- queueMicrotask(() => {
- // 5.4.1
- const requestList = []
+ consumeFinish(consume)
+ } catch (err) {
+ stream.destroy(err)
+ }
+}
- // 5.4.2
- for (const request of requests) {
- const requestObject = fromInnerRequest(
- request,
- new AbortController().signal,
- 'immutable'
- )
- // 5.4.2.1
- requestList.push(requestObject)
- }
+function consumePush (consume, chunk) {
+ consume.length += chunk.length
+ consume.body.push(chunk)
+}
- // 5.4.3
- promise.resolve(Object.freeze(requestList))
- })
+function consumeFinish (consume, err) {
+ if (consume.body === null) {
+ return
+ }
- return promise.promise
+ if (err) {
+ consume.reject(err)
+ } else {
+ consume.resolve()
}
- /**
- * @see https://w3c.github.io/ServiceWorker/#batch-cache-operations-algorithm
- * @param {CacheBatchOperation[]} operations
- * @returns {requestResponseList}
- */
- #batchCacheOperations (operations) {
- // 1.
- const cache = this.#relevantRequestResponseList
+ consume.type = null
+ consume.stream = null
+ consume.resolve = null
+ consume.reject = null
+ consume.length = 0
+ consume.body = null
+}
- // 2.
- const backupCache = [...cache]
+module.exports = { Readable: BodyReadable, chunksDecode }
- // 3.
- const addedItems = []
- // 4.1
- const resultList = []
+/***/ }),
- try {
- // 4.2
- for (const operation of operations) {
- // 4.2.1
- if (operation.type !== 'delete' && operation.type !== 'put') {
- throw webidl.errors.exception({
- header: 'Cache.#batchCacheOperations',
- message: 'operation type does not match "delete" or "put"'
- })
- }
+/***/ 7655:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 4.2.2
- if (operation.type === 'delete' && operation.response != null) {
- throw webidl.errors.exception({
- header: 'Cache.#batchCacheOperations',
- message: 'delete operation should not have an associated response'
- })
- }
+const assert = __nccwpck_require__(4589)
+const {
+ ResponseStatusCodeError
+} = __nccwpck_require__(8707)
- // 4.2.3
- if (this.#queryCache(operation.request, operation.options, addedItems).length) {
- throw new DOMException('???', 'InvalidStateError')
- }
+const { chunksDecode } = __nccwpck_require__(9927)
+const CHUNK_LIMIT = 128 * 1024
- // 4.2.4
- let requestResponses
+async function getResolveErrorBodyCallback ({ callback, body, contentType, statusCode, statusMessage, headers }) {
+ assert(body)
- // 4.2.5
- if (operation.type === 'delete') {
- // 4.2.5.1
- requestResponses = this.#queryCache(operation.request, operation.options)
+ let chunks = []
+ let length = 0
- // TODO: the spec is wrong, this is needed to pass WPTs
- if (requestResponses.length === 0) {
- return []
- }
+ try {
+ for await (const chunk of body) {
+ chunks.push(chunk)
+ length += chunk.length
+ if (length > CHUNK_LIMIT) {
+ chunks = []
+ length = 0
+ break
+ }
+ }
+ } catch {
+ chunks = []
+ length = 0
+ // Do nothing....
+ }
- // 4.2.5.2
- for (const requestResponse of requestResponses) {
- const idx = cache.indexOf(requestResponse)
- assert(idx !== -1)
+ const message = `Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`
- // 4.2.5.2.1
- cache.splice(idx, 1)
- }
- } else if (operation.type === 'put') { // 4.2.6
- // 4.2.6.1
- if (operation.response == null) {
- throw webidl.errors.exception({
- header: 'Cache.#batchCacheOperations',
- message: 'put operation should have an associated response'
- })
- }
+ if (statusCode === 204 || !contentType || !length) {
+ queueMicrotask(() => callback(new ResponseStatusCodeError(message, statusCode, headers)))
+ return
+ }
- // 4.2.6.2
- const r = operation.request
+ const stackTraceLimit = Error.stackTraceLimit
+ Error.stackTraceLimit = 0
+ let payload
- // 4.2.6.3
- if (!urlIsHttpHttpsScheme(r.url)) {
- throw webidl.errors.exception({
- header: 'Cache.#batchCacheOperations',
- message: 'expected http or https scheme'
- })
- }
+ try {
+ if (isContentTypeApplicationJson(contentType)) {
+ payload = JSON.parse(chunksDecode(chunks, length))
+ } else if (isContentTypeText(contentType)) {
+ payload = chunksDecode(chunks, length)
+ }
+ } catch {
+ // process in a callback to avoid throwing in the microtask queue
+ } finally {
+ Error.stackTraceLimit = stackTraceLimit
+ }
+ queueMicrotask(() => callback(new ResponseStatusCodeError(message, statusCode, headers, payload)))
+}
- // 4.2.6.4
- if (r.method !== 'GET') {
- throw webidl.errors.exception({
- header: 'Cache.#batchCacheOperations',
- message: 'not get method'
- })
- }
+const isContentTypeApplicationJson = (contentType) => {
+ return (
+ contentType.length > 15 &&
+ contentType[11] === '/' &&
+ contentType[0] === 'a' &&
+ contentType[1] === 'p' &&
+ contentType[2] === 'p' &&
+ contentType[3] === 'l' &&
+ contentType[4] === 'i' &&
+ contentType[5] === 'c' &&
+ contentType[6] === 'a' &&
+ contentType[7] === 't' &&
+ contentType[8] === 'i' &&
+ contentType[9] === 'o' &&
+ contentType[10] === 'n' &&
+ contentType[12] === 'j' &&
+ contentType[13] === 's' &&
+ contentType[14] === 'o' &&
+ contentType[15] === 'n'
+ )
+}
- // 4.2.6.5
- if (operation.options != null) {
- throw webidl.errors.exception({
- header: 'Cache.#batchCacheOperations',
- message: 'options must not be defined'
- })
- }
+const isContentTypeText = (contentType) => {
+ return (
+ contentType.length > 4 &&
+ contentType[4] === '/' &&
+ contentType[0] === 't' &&
+ contentType[1] === 'e' &&
+ contentType[2] === 'x' &&
+ contentType[3] === 't'
+ )
+}
- // 4.2.6.6
- requestResponses = this.#queryCache(operation.request)
+module.exports = {
+ getResolveErrorBodyCallback,
+ isContentTypeApplicationJson,
+ isContentTypeText
+}
- // 4.2.6.7
- for (const requestResponse of requestResponses) {
- const idx = cache.indexOf(requestResponse)
- assert(idx !== -1)
- // 4.2.6.7.1
- cache.splice(idx, 1)
- }
+/***/ }),
- // 4.2.6.8
- cache.push([operation.request, operation.response])
+/***/ 9136:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 4.2.6.10
- addedItems.push([operation.request, operation.response])
- }
- // 4.2.7
- resultList.push([operation.request, operation.response])
- }
- // 4.3
- return resultList
- } catch (e) { // 5.
- // 5.1
- this.#relevantRequestResponseList.length = 0
+const net = __nccwpck_require__(7030)
+const assert = __nccwpck_require__(4589)
+const util = __nccwpck_require__(3440)
+const { InvalidArgumentError, ConnectTimeoutError } = __nccwpck_require__(8707)
+const timers = __nccwpck_require__(6603)
- // 5.2
- this.#relevantRequestResponseList = backupCache
+function noop () {}
- // 5.3
- throw e
- }
- }
+let tls // include tls conditionally since it is not always available
- /**
- * @see https://w3c.github.io/ServiceWorker/#query-cache
- * @param {any} requestQuery
- * @param {import('../../types/cache').CacheQueryOptions} options
- * @param {requestResponseList} targetStorage
- * @returns {requestResponseList}
- */
- #queryCache (requestQuery, options, targetStorage) {
- /** @type {requestResponseList} */
- const resultList = []
+// TODO: session re-use does not wait for the first
+// connection to resolve the session and might therefore
+// resolve the same servername multiple times even when
+// re-use is enabled.
- const storage = targetStorage ?? this.#relevantRequestResponseList
+let SessionCache
+// FIXME: remove workaround when the Node bug is fixed
+// https://github.com/nodejs/node/issues/49344#issuecomment-1741776308
+if (global.FinalizationRegistry && !(process.env.NODE_V8_COVERAGE || process.env.UNDICI_NO_FG)) {
+ SessionCache = class WeakSessionCache {
+ constructor (maxCachedSessions) {
+ this._maxCachedSessions = maxCachedSessions
+ this._sessionCache = new Map()
+ this._sessionRegistry = new global.FinalizationRegistry((key) => {
+ if (this._sessionCache.size < this._maxCachedSessions) {
+ return
+ }
- for (const requestResponse of storage) {
- const [cachedRequest, cachedResponse] = requestResponse
- if (this.#requestMatchesCachedItem(requestQuery, cachedRequest, cachedResponse, options)) {
- resultList.push(requestResponse)
- }
+ const ref = this._sessionCache.get(key)
+ if (ref !== undefined && ref.deref() === undefined) {
+ this._sessionCache.delete(key)
+ }
+ })
}
- return resultList
- }
-
- /**
- * @see https://w3c.github.io/ServiceWorker/#request-matches-cached-item-algorithm
- * @param {any} requestQuery
- * @param {any} request
- * @param {any | null} response
- * @param {import('../../types/cache').CacheQueryOptions | undefined} options
- * @returns {boolean}
- */
- #requestMatchesCachedItem (requestQuery, request, response = null, options) {
- // if (options?.ignoreMethod === false && request.method === 'GET') {
- // return false
- // }
-
- const queryURL = new URL(requestQuery.url)
-
- const cachedURL = new URL(request.url)
-
- if (options?.ignoreSearch) {
- cachedURL.search = ''
-
- queryURL.search = ''
- }
-
- if (!urlEquals(queryURL, cachedURL, true)) {
- return false
- }
-
- if (
- response == null ||
- options?.ignoreVary ||
- !response.headersList.contains('vary')
- ) {
- return true
+ get (sessionKey) {
+ const ref = this._sessionCache.get(sessionKey)
+ return ref ? ref.deref() : null
}
- const fieldValues = getFieldValues(response.headersList.get('vary'))
-
- for (const fieldValue of fieldValues) {
- if (fieldValue === '*') {
- return false
+ set (sessionKey, session) {
+ if (this._maxCachedSessions === 0) {
+ return
}
- const requestValue = request.headersList.get(fieldValue)
- const queryValue = requestQuery.headersList.get(fieldValue)
-
- // If one has the header and the other doesn't, or one has
- // a different value than the other, return false
- if (requestValue !== queryValue) {
- return false
- }
+ this._sessionCache.set(sessionKey, new WeakRef(session))
+ this._sessionRegistry.register(session, sessionKey)
}
-
- return true
}
-
- #internalMatchAll (request, options, maxResponses = Infinity) {
- // 1.
- let r = null
-
- // 2.
- if (request !== undefined) {
- if (request instanceof Request) {
- // 2.1.1
- r = request[kState]
-
- // 2.1.2
- if (r.method !== 'GET' && !options.ignoreMethod) {
- return []
- }
- } else if (typeof request === 'string') {
- // 2.2.1
- r = new Request(request)[kState]
- }
+} else {
+ SessionCache = class SimpleSessionCache {
+ constructor (maxCachedSessions) {
+ this._maxCachedSessions = maxCachedSessions
+ this._sessionCache = new Map()
}
- // 5.
- // 5.1
- const responses = []
+ get (sessionKey) {
+ return this._sessionCache.get(sessionKey)
+ }
- // 5.2
- if (request === undefined) {
- // 5.2.1
- for (const requestResponse of this.#relevantRequestResponseList) {
- responses.push(requestResponse[1])
+ set (sessionKey, session) {
+ if (this._maxCachedSessions === 0) {
+ return
}
- } else { // 5.3
- // 5.3.1
- const requestResponses = this.#queryCache(r, options)
- // 5.3.2
- for (const requestResponse of requestResponses) {
- responses.push(requestResponse[1])
+ if (this._sessionCache.size >= this._maxCachedSessions) {
+ // remove the oldest session
+ const { value: oldestKey } = this._sessionCache.keys().next()
+ this._sessionCache.delete(oldestKey)
}
- }
-
- // 5.4
- // We don't implement CORs so we don't need to loop over the responses, yay!
-
- // 5.5.1
- const responseList = []
- // 5.5.2
- for (const response of responses) {
- // 5.5.2.1
- const responseObject = fromInnerResponse(response, 'immutable')
-
- responseList.push(responseObject.clone())
-
- if (responseList.length >= maxResponses) {
- break
- }
+ this._sessionCache.set(sessionKey, session)
}
-
- // 6.
- return Object.freeze(responseList)
- }
-}
-
-Object.defineProperties(Cache.prototype, {
- [Symbol.toStringTag]: {
- value: 'Cache',
- configurable: true
- },
- match: kEnumerableProperty,
- matchAll: kEnumerableProperty,
- add: kEnumerableProperty,
- addAll: kEnumerableProperty,
- put: kEnumerableProperty,
- delete: kEnumerableProperty,
- keys: kEnumerableProperty
-})
-
-const cacheQueryOptionConverters = [
- {
- key: 'ignoreSearch',
- converter: webidl.converters.boolean,
- defaultValue: () => false
- },
- {
- key: 'ignoreMethod',
- converter: webidl.converters.boolean,
- defaultValue: () => false
- },
- {
- key: 'ignoreVary',
- converter: webidl.converters.boolean,
- defaultValue: () => false
- }
-]
-
-webidl.converters.CacheQueryOptions = webidl.dictionaryConverter(cacheQueryOptionConverters)
-
-webidl.converters.MultiCacheQueryOptions = webidl.dictionaryConverter([
- ...cacheQueryOptionConverters,
- {
- key: 'cacheName',
- converter: webidl.converters.DOMString
}
-])
-
-webidl.converters.Response = webidl.interfaceConverter(Response)
-
-webidl.converters['sequence'] = webidl.sequenceConverter(
- webidl.converters.RequestInfo
-)
-
-module.exports = {
- Cache
}
-
-/***/ }),
-
-/***/ 3832:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const { kConstruct } = __nccwpck_require__(3202)
-const { Cache } = __nccwpck_require__(2185)
-const { webidl } = __nccwpck_require__(220)
-const { kEnumerableProperty } = __nccwpck_require__(7375)
-
-class CacheStorage {
- /**
- * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-name-to-cache-map
- * @type {Map}
- */
- async has (cacheName) {
- webidl.brandCheck(this, CacheStorage)
-
- const prefix = 'CacheStorage.has'
- webidl.argumentLengthCheck(arguments, 1, prefix)
-
- cacheName = webidl.converters.DOMString(cacheName, prefix, 'cacheName')
+ servername = servername || options.servername || util.getServerName(host) || null
- // 2.1.1
- // 2.2
- return this.#caches.has(cacheName)
- }
+ const sessionKey = servername || hostname
+ assert(sessionKey)
- /**
- * @see https://w3c.github.io/ServiceWorker/#dom-cachestorage-open
- * @param {string} cacheName
- * @returns {Promise}
- */
- async open (cacheName) {
- webidl.brandCheck(this, CacheStorage)
+ const session = customSession || sessionCache.get(sessionKey) || null
- const prefix = 'CacheStorage.open'
- webidl.argumentLengthCheck(arguments, 1, prefix)
+ port = port || 443
- cacheName = webidl.converters.DOMString(cacheName, prefix, 'cacheName')
+ socket = tls.connect({
+ highWaterMark: 16384, // TLS in node can't have bigger HWM anyway...
+ ...options,
+ servername,
+ session,
+ localAddress,
+ // TODO(HTTP/2): Add support for h2c
+ ALPNProtocols: allowH2 ? ['http/1.1', 'h2'] : ['http/1.1'],
+ socket: httpSocket, // upgrade socket connection
+ port,
+ host: hostname
+ })
- // 2.1
- if (this.#caches.has(cacheName)) {
- // await caches.open('v1') !== await caches.open('v1')
+ socket
+ .on('session', function (session) {
+ // TODO (fix): Can a session become invalid once established? Don't think so?
+ sessionCache.set(sessionKey, session)
+ })
+ } else {
+ assert(!httpSocket, 'httpSocket can only be sent on TLS update')
- // 2.1.1
- const cache = this.#caches.get(cacheName)
+ port = port || 80
- // 2.1.1.1
- return new Cache(kConstruct, cache)
+ socket = net.connect({
+ highWaterMark: 64 * 1024, // Same as nodejs fs streams.
+ ...options,
+ localAddress,
+ port,
+ host: hostname
+ })
}
- // 2.2
- const cache = []
-
- // 2.3
- this.#caches.set(cacheName, cache)
-
- // 2.4
- return new Cache(kConstruct, cache)
- }
-
- /**
- * @see https://w3c.github.io/ServiceWorker/#cache-storage-delete
- * @param {string} cacheName
- * @returns {Promise}
- */
- async delete (cacheName) {
- webidl.brandCheck(this, CacheStorage)
-
- const prefix = 'CacheStorage.delete'
- webidl.argumentLengthCheck(arguments, 1, prefix)
+ // Set TCP keep alive options on the socket here instead of in connect() for the case of assigning the socket
+ if (options.keepAlive == null || options.keepAlive) {
+ const keepAliveInitialDelay = options.keepAliveInitialDelay === undefined ? 60e3 : options.keepAliveInitialDelay
+ socket.setKeepAlive(true, keepAliveInitialDelay)
+ }
- cacheName = webidl.converters.DOMString(cacheName, prefix, 'cacheName')
+ const clearConnectTimeout = setupConnectTimeout(new WeakRef(socket), { timeout, hostname, port })
- return this.#caches.delete(cacheName)
- }
+ socket
+ .setNoDelay(true)
+ .once(protocol === 'https:' ? 'secureConnect' : 'connect', function () {
+ queueMicrotask(clearConnectTimeout)
- /**
- * @see https://w3c.github.io/ServiceWorker/#cache-storage-keys
- * @returns {Promise}
- */
- async keys () {
- webidl.brandCheck(this, CacheStorage)
+ if (callback) {
+ const cb = callback
+ callback = null
+ cb(null, this)
+ }
+ })
+ .on('error', function (err) {
+ queueMicrotask(clearConnectTimeout)
- // 2.1
- const keys = this.#caches.keys()
+ if (callback) {
+ const cb = callback
+ callback = null
+ cb(err)
+ }
+ })
- // 2.2
- return [...keys]
+ return socket
}
}
-Object.defineProperties(CacheStorage.prototype, {
- [Symbol.toStringTag]: {
- value: 'CacheStorage',
- configurable: true
- },
- match: kEnumerableProperty,
- has: kEnumerableProperty,
- open: kEnumerableProperty,
- delete: kEnumerableProperty,
- keys: kEnumerableProperty
-})
-
-module.exports = {
- CacheStorage
-}
-
-
-/***/ }),
-
-/***/ 3202:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-module.exports = {
- kConstruct: (__nccwpck_require__(6130).kConstruct)
-}
-
-
-/***/ }),
-
-/***/ 4159:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const assert = __nccwpck_require__(4589)
-const { URLSerializer } = __nccwpck_require__(2121)
-const { isValidHeaderName } = __nccwpck_require__(7241)
-
/**
- * @see https://url.spec.whatwg.org/#concept-url-equals
- * @param {URL} A
- * @param {URL} B
- * @param {boolean | undefined} excludeFragment
- * @returns {boolean}
+ * @param {WeakRef} socketWeakRef
+ * @param {object} opts
+ * @param {number} opts.timeout
+ * @param {string} opts.hostname
+ * @param {number} opts.port
+ * @returns {() => void}
*/
-function urlEquals (A, B, excludeFragment = false) {
- const serializedA = URLSerializer(A, excludeFragment)
+const setupConnectTimeout = process.platform === 'win32'
+ ? (socketWeakRef, opts) => {
+ if (!opts.timeout) {
+ return noop
+ }
- const serializedB = URLSerializer(B, excludeFragment)
+ let s1 = null
+ let s2 = null
+ const fastTimer = timers.setFastTimeout(() => {
+ // setImmediate is added to make sure that we prioritize socket error events over timeouts
+ s1 = setImmediate(() => {
+ // Windows needs an extra setImmediate probably due to implementation differences in the socket logic
+ s2 = setImmediate(() => onConnectTimeout(socketWeakRef.deref(), opts))
+ })
+ }, opts.timeout)
+ return () => {
+ timers.clearFastTimeout(fastTimer)
+ clearImmediate(s1)
+ clearImmediate(s2)
+ }
+ }
+ : (socketWeakRef, opts) => {
+ if (!opts.timeout) {
+ return noop
+ }
- return serializedA === serializedB
-}
+ let s1 = null
+ const fastTimer = timers.setFastTimeout(() => {
+ // setImmediate is added to make sure that we prioritize socket error events over timeouts
+ s1 = setImmediate(() => {
+ onConnectTimeout(socketWeakRef.deref(), opts)
+ })
+ }, opts.timeout)
+ return () => {
+ timers.clearFastTimeout(fastTimer)
+ clearImmediate(s1)
+ }
+ }
/**
- * @see https://github.com/chromium/chromium/blob/694d20d134cb553d8d89e5500b9148012b1ba299/content/browser/cache_storage/cache_storage_cache.cc#L260-L262
- * @param {string} header
+ * @param {net.Socket} socket
+ * @param {object} opts
+ * @param {number} opts.timeout
+ * @param {string} opts.hostname
+ * @param {number} opts.port
*/
-function getFieldValues (header) {
- assert(header !== null)
-
- const values = []
-
- for (let value of header.split(',')) {
- value = value.trim()
+function onConnectTimeout (socket, opts) {
+ // The socket could be already garbage collected
+ if (socket == null) {
+ return
+ }
- if (isValidHeaderName(value)) {
- values.push(value)
- }
+ let message = 'Connect Timeout Error'
+ if (Array.isArray(socket.autoSelectFamilyAttemptedAddresses)) {
+ message += ` (attempted addresses: ${socket.autoSelectFamilyAttemptedAddresses.join(', ')},`
+ } else {
+ message += ` (attempted address: ${opts.hostname}:${opts.port},`
}
- return values
-}
+ message += ` timeout: ${opts.timeout}ms)`
-module.exports = {
- urlEquals,
- getFieldValues
+ util.destroy(socket, new ConnectTimeoutError(message))
}
-
-/***/ }),
-
-/***/ 3819:
-/***/ ((module) => {
-
-
-
-// https://wicg.github.io/cookie-store/#cookie-maximum-attribute-value-size
-const maxAttributeValueSize = 1024
-
-// https://wicg.github.io/cookie-store/#cookie-maximum-name-value-pair-size
-const maxNameValuePairSize = 4096
-
-module.exports = {
- maxAttributeValueSize,
- maxNameValuePairSize
-}
+module.exports = buildConnector
/***/ }),
-/***/ 2778:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 735:
+/***/ ((module) => {
-const { parseSetCookie } = __nccwpck_require__(8745)
-const { stringify } = __nccwpck_require__(9556)
-const { webidl } = __nccwpck_require__(220)
-const { Headers } = __nccwpck_require__(1271)
+/** @type {Record} */
+const headerNameLowerCasedRecord = {}
-/**
- * @typedef {Object} Cookie
- * @property {string} name
- * @property {string} value
- * @property {Date|number|undefined} expires
- * @property {number|undefined} maxAge
- * @property {string|undefined} domain
- * @property {string|undefined} path
- * @property {boolean|undefined} secure
- * @property {boolean|undefined} httpOnly
- * @property {'Strict'|'Lax'|'None'} sameSite
- * @property {string[]} unparsed
- */
+// https://developer.mozilla.org/docs/Web/HTTP/Headers
+const wellknownHeaderNames = [
+ 'Accept',
+ 'Accept-Encoding',
+ 'Accept-Language',
+ 'Accept-Ranges',
+ 'Access-Control-Allow-Credentials',
+ 'Access-Control-Allow-Headers',
+ 'Access-Control-Allow-Methods',
+ 'Access-Control-Allow-Origin',
+ 'Access-Control-Expose-Headers',
+ 'Access-Control-Max-Age',
+ 'Access-Control-Request-Headers',
+ 'Access-Control-Request-Method',
+ 'Age',
+ 'Allow',
+ 'Alt-Svc',
+ 'Alt-Used',
+ 'Authorization',
+ 'Cache-Control',
+ 'Clear-Site-Data',
+ 'Connection',
+ 'Content-Disposition',
+ 'Content-Encoding',
+ 'Content-Language',
+ 'Content-Length',
+ 'Content-Location',
+ 'Content-Range',
+ 'Content-Security-Policy',
+ 'Content-Security-Policy-Report-Only',
+ 'Content-Type',
+ 'Cookie',
+ 'Cross-Origin-Embedder-Policy',
+ 'Cross-Origin-Opener-Policy',
+ 'Cross-Origin-Resource-Policy',
+ 'Date',
+ 'Device-Memory',
+ 'Downlink',
+ 'ECT',
+ 'ETag',
+ 'Expect',
+ 'Expect-CT',
+ 'Expires',
+ 'Forwarded',
+ 'From',
+ 'Host',
+ 'If-Match',
+ 'If-Modified-Since',
+ 'If-None-Match',
+ 'If-Range',
+ 'If-Unmodified-Since',
+ 'Keep-Alive',
+ 'Last-Modified',
+ 'Link',
+ 'Location',
+ 'Max-Forwards',
+ 'Origin',
+ 'Permissions-Policy',
+ 'Pragma',
+ 'Proxy-Authenticate',
+ 'Proxy-Authorization',
+ 'RTT',
+ 'Range',
+ 'Referer',
+ 'Referrer-Policy',
+ 'Refresh',
+ 'Retry-After',
+ 'Sec-WebSocket-Accept',
+ 'Sec-WebSocket-Extensions',
+ 'Sec-WebSocket-Key',
+ 'Sec-WebSocket-Protocol',
+ 'Sec-WebSocket-Version',
+ 'Server',
+ 'Server-Timing',
+ 'Service-Worker-Allowed',
+ 'Service-Worker-Navigation-Preload',
+ 'Set-Cookie',
+ 'SourceMap',
+ 'Strict-Transport-Security',
+ 'Supports-Loading-Mode',
+ 'TE',
+ 'Timing-Allow-Origin',
+ 'Trailer',
+ 'Transfer-Encoding',
+ 'Upgrade',
+ 'Upgrade-Insecure-Requests',
+ 'User-Agent',
+ 'Vary',
+ 'Via',
+ 'WWW-Authenticate',
+ 'X-Content-Type-Options',
+ 'X-DNS-Prefetch-Control',
+ 'X-Frame-Options',
+ 'X-Permitted-Cross-Domain-Policies',
+ 'X-Powered-By',
+ 'X-Requested-With',
+ 'X-XSS-Protection'
+]
-/**
- * @param {Headers} headers
- * @returns {Record}
- */
-function getCookies (headers) {
- webidl.argumentLengthCheck(arguments, 1, 'getCookies')
+for (let i = 0; i < wellknownHeaderNames.length; ++i) {
+ const key = wellknownHeaderNames[i]
+ const lowerCasedKey = key.toLowerCase()
+ headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] =
+ lowerCasedKey
+}
- webidl.brandCheck(headers, Headers, { strict: false })
+// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`.
+Object.setPrototypeOf(headerNameLowerCasedRecord, null)
- const cookie = headers.get('cookie')
- const out = {}
+module.exports = {
+ wellknownHeaderNames,
+ headerNameLowerCasedRecord
+}
- if (!cookie) {
- return out
- }
- for (const piece of cookie.split(';')) {
- const [name, ...value] = piece.split('=')
+/***/ }),
- out[name.trim()] = value.join('=')
- }
+/***/ 2414:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- return out
+
+const diagnosticsChannel = __nccwpck_require__(3053)
+const util = __nccwpck_require__(7975)
+
+const undiciDebugLog = util.debuglog('undici')
+const fetchDebuglog = util.debuglog('fetch')
+const websocketDebuglog = util.debuglog('websocket')
+let isClientSet = false
+const channels = {
+ // Client
+ beforeConnect: diagnosticsChannel.channel('undici:client:beforeConnect'),
+ connected: diagnosticsChannel.channel('undici:client:connected'),
+ connectError: diagnosticsChannel.channel('undici:client:connectError'),
+ sendHeaders: diagnosticsChannel.channel('undici:client:sendHeaders'),
+ // Request
+ create: diagnosticsChannel.channel('undici:request:create'),
+ bodySent: diagnosticsChannel.channel('undici:request:bodySent'),
+ headers: diagnosticsChannel.channel('undici:request:headers'),
+ trailers: diagnosticsChannel.channel('undici:request:trailers'),
+ error: diagnosticsChannel.channel('undici:request:error'),
+ // WebSocket
+ open: diagnosticsChannel.channel('undici:websocket:open'),
+ close: diagnosticsChannel.channel('undici:websocket:close'),
+ socketError: diagnosticsChannel.channel('undici:websocket:socket_error'),
+ ping: diagnosticsChannel.channel('undici:websocket:ping'),
+ pong: diagnosticsChannel.channel('undici:websocket:pong')
}
-/**
- * @param {Headers} headers
- * @param {string} name
- * @param {{ path?: string, domain?: string }|undefined} attributes
- * @returns {void}
- */
-function deleteCookie (headers, name, attributes) {
- webidl.brandCheck(headers, Headers, { strict: false })
+if (undiciDebugLog.enabled || fetchDebuglog.enabled) {
+ const debuglog = fetchDebuglog.enabled ? fetchDebuglog : undiciDebugLog
- const prefix = 'deleteCookie'
- webidl.argumentLengthCheck(arguments, 2, prefix)
+ // Track all Client events
+ diagnosticsChannel.channel('undici:client:beforeConnect').subscribe(evt => {
+ const {
+ connectParams: { version, protocol, port, host }
+ } = evt
+ debuglog(
+ 'connecting to %s using %s%s',
+ `${host}${port ? `:${port}` : ''}`,
+ protocol,
+ version
+ )
+ })
- name = webidl.converters.DOMString(name, prefix, 'name')
- attributes = webidl.converters.DeleteCookieAttributes(attributes)
+ diagnosticsChannel.channel('undici:client:connected').subscribe(evt => {
+ const {
+ connectParams: { version, protocol, port, host }
+ } = evt
+ debuglog(
+ 'connected to %s using %s%s',
+ `${host}${port ? `:${port}` : ''}`,
+ protocol,
+ version
+ )
+ })
- // Matches behavior of
- // https://github.com/denoland/deno_std/blob/63827b16330b82489a04614027c33b7904e08be5/http/cookie.ts#L278
- setCookie(headers, {
- name,
- value: '',
- expires: new Date(0),
- ...attributes
+ diagnosticsChannel.channel('undici:client:connectError').subscribe(evt => {
+ const {
+ connectParams: { version, protocol, port, host },
+ error
+ } = evt
+ debuglog(
+ 'connection to %s using %s%s errored - %s',
+ `${host}${port ? `:${port}` : ''}`,
+ protocol,
+ version,
+ error.message
+ )
})
-}
-/**
- * @param {Headers} headers
- * @returns {Cookie[]}
- */
-function getSetCookies (headers) {
- webidl.argumentLengthCheck(arguments, 1, 'getSetCookies')
+ diagnosticsChannel.channel('undici:client:sendHeaders').subscribe(evt => {
+ const {
+ request: { method, path, origin }
+ } = evt
+ debuglog('sending request to %s %s/%s', method, origin, path)
+ })
- webidl.brandCheck(headers, Headers, { strict: false })
+ // Track Request events
+ diagnosticsChannel.channel('undici:request:headers').subscribe(evt => {
+ const {
+ request: { method, path, origin },
+ response: { statusCode }
+ } = evt
+ debuglog(
+ 'received response to %s %s/%s - HTTP %d',
+ method,
+ origin,
+ path,
+ statusCode
+ )
+ })
- const cookies = headers.getSetCookie()
+ diagnosticsChannel.channel('undici:request:trailers').subscribe(evt => {
+ const {
+ request: { method, path, origin }
+ } = evt
+ debuglog('trailers received from %s %s/%s', method, origin, path)
+ })
- if (!cookies) {
- return []
- }
+ diagnosticsChannel.channel('undici:request:error').subscribe(evt => {
+ const {
+ request: { method, path, origin },
+ error
+ } = evt
+ debuglog(
+ 'request to %s %s/%s errored - %s',
+ method,
+ origin,
+ path,
+ error.message
+ )
+ })
- return cookies.map((pair) => parseSetCookie(pair))
+ isClientSet = true
}
-/**
- * @param {Headers} headers
- * @param {Cookie} cookie
- * @returns {void}
- */
-function setCookie (headers, cookie) {
- webidl.argumentLengthCheck(arguments, 2, 'setCookie')
-
- webidl.brandCheck(headers, Headers, { strict: false })
+if (websocketDebuglog.enabled) {
+ if (!isClientSet) {
+ const debuglog = undiciDebugLog.enabled ? undiciDebugLog : websocketDebuglog
+ diagnosticsChannel.channel('undici:client:beforeConnect').subscribe(evt => {
+ const {
+ connectParams: { version, protocol, port, host }
+ } = evt
+ debuglog(
+ 'connecting to %s%s using %s%s',
+ host,
+ port ? `:${port}` : '',
+ protocol,
+ version
+ )
+ })
- cookie = webidl.converters.Cookie(cookie)
+ diagnosticsChannel.channel('undici:client:connected').subscribe(evt => {
+ const {
+ connectParams: { version, protocol, port, host }
+ } = evt
+ debuglog(
+ 'connected to %s%s using %s%s',
+ host,
+ port ? `:${port}` : '',
+ protocol,
+ version
+ )
+ })
- const str = stringify(cookie)
+ diagnosticsChannel.channel('undici:client:connectError').subscribe(evt => {
+ const {
+ connectParams: { version, protocol, port, host },
+ error
+ } = evt
+ debuglog(
+ 'connection to %s%s using %s%s errored - %s',
+ host,
+ port ? `:${port}` : '',
+ protocol,
+ version,
+ error.message
+ )
+ })
- if (str) {
- headers.append('Set-Cookie', str)
+ diagnosticsChannel.channel('undici:client:sendHeaders').subscribe(evt => {
+ const {
+ request: { method, path, origin }
+ } = evt
+ debuglog('sending request to %s %s/%s', method, origin, path)
+ })
}
-}
-webidl.converters.DeleteCookieAttributes = webidl.dictionaryConverter([
- {
- converter: webidl.nullableConverter(webidl.converters.DOMString),
- key: 'path',
- defaultValue: () => null
- },
- {
- converter: webidl.nullableConverter(webidl.converters.DOMString),
- key: 'domain',
- defaultValue: () => null
- }
-])
+ // Track all WebSocket events
+ diagnosticsChannel.channel('undici:websocket:open').subscribe(evt => {
+ const {
+ address: { address, port }
+ } = evt
+ websocketDebuglog('connection opened %s%s', address, port ? `:${port}` : '')
+ })
-webidl.converters.Cookie = webidl.dictionaryConverter([
- {
- converter: webidl.converters.DOMString,
- key: 'name'
- },
- {
- converter: webidl.converters.DOMString,
- key: 'value'
- },
- {
- converter: webidl.nullableConverter((value) => {
- if (typeof value === 'number') {
- return webidl.converters['unsigned long long'](value)
- }
+ diagnosticsChannel.channel('undici:websocket:close').subscribe(evt => {
+ const { websocket, code, reason } = evt
+ websocketDebuglog(
+ 'closed connection to %s - %s %s',
+ websocket.url,
+ code,
+ reason
+ )
+ })
- return new Date(value)
- }),
- key: 'expires',
- defaultValue: () => null
- },
- {
- converter: webidl.nullableConverter(webidl.converters['long long']),
- key: 'maxAge',
- defaultValue: () => null
- },
- {
- converter: webidl.nullableConverter(webidl.converters.DOMString),
- key: 'domain',
- defaultValue: () => null
- },
- {
- converter: webidl.nullableConverter(webidl.converters.DOMString),
- key: 'path',
- defaultValue: () => null
- },
- {
- converter: webidl.nullableConverter(webidl.converters.boolean),
- key: 'secure',
- defaultValue: () => null
- },
- {
- converter: webidl.nullableConverter(webidl.converters.boolean),
- key: 'httpOnly',
- defaultValue: () => null
- },
- {
- converter: webidl.converters.USVString,
- key: 'sameSite',
- allowedValues: ['Strict', 'Lax', 'None']
- },
- {
- converter: webidl.sequenceConverter(webidl.converters.DOMString),
- key: 'unparsed',
- defaultValue: () => new Array(0)
- }
-])
+ diagnosticsChannel.channel('undici:websocket:socket_error').subscribe(err => {
+ websocketDebuglog('connection errored - %s', err.message)
+ })
+
+ diagnosticsChannel.channel('undici:websocket:ping').subscribe(evt => {
+ websocketDebuglog('ping received')
+ })
+
+ diagnosticsChannel.channel('undici:websocket:pong').subscribe(evt => {
+ websocketDebuglog('pong received')
+ })
+}
module.exports = {
- getCookies,
- deleteCookie,
- getSetCookies,
- setCookie
+ channels
}
/***/ }),
-/***/ 8745:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
+/***/ 8707:
+/***/ ((module) => {
-const { maxNameValuePairSize, maxAttributeValueSize } = __nccwpck_require__(3819)
-const { isCTLExcludingHtab } = __nccwpck_require__(9556)
-const { collectASequenceOfCodePointsFast } = __nccwpck_require__(2121)
-const assert = __nccwpck_require__(4589)
-/**
- * @description Parses the field-value attributes of a set-cookie header string.
- * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4
- * @param {string} header
- * @returns if the header is invalid, null will be returned
- */
-function parseSetCookie (header) {
- // 1. If the set-cookie-string contains a %x00-08 / %x0A-1F / %x7F
- // character (CTL characters excluding HTAB): Abort these steps and
- // ignore the set-cookie-string entirely.
- if (isCTLExcludingHtab(header)) {
- return null
+const kUndiciError = Symbol.for('undici.error.UND_ERR')
+class UndiciError extends Error {
+ constructor (message) {
+ super(message)
+ this.name = 'UndiciError'
+ this.code = 'UND_ERR'
}
- let nameValuePair = ''
- let unparsedAttributes = ''
- let name = ''
- let value = ''
-
- // 2. If the set-cookie-string contains a %x3B (";") character:
- if (header.includes(';')) {
- // 1. The name-value-pair string consists of the characters up to,
- // but not including, the first %x3B (";"), and the unparsed-
- // attributes consist of the remainder of the set-cookie-string
- // (including the %x3B (";") in question).
- const position = { position: 0 }
+ static [Symbol.hasInstance] (instance) {
+ return instance && instance[kUndiciError] === true
+ }
- nameValuePair = collectASequenceOfCodePointsFast(';', header, position)
- unparsedAttributes = header.slice(position.position)
- } else {
- // Otherwise:
+ [kUndiciError] = true
+}
- // 1. The name-value-pair string consists of all the characters
- // contained in the set-cookie-string, and the unparsed-
- // attributes is the empty string.
- nameValuePair = header
+const kConnectTimeoutError = Symbol.for('undici.error.UND_ERR_CONNECT_TIMEOUT')
+class ConnectTimeoutError extends UndiciError {
+ constructor (message) {
+ super(message)
+ this.name = 'ConnectTimeoutError'
+ this.message = message || 'Connect Timeout Error'
+ this.code = 'UND_ERR_CONNECT_TIMEOUT'
}
- // 3. If the name-value-pair string lacks a %x3D ("=") character, then
- // the name string is empty, and the value string is the value of
- // name-value-pair.
- if (!nameValuePair.includes('=')) {
- value = nameValuePair
- } else {
- // Otherwise, the name string consists of the characters up to, but
- // not including, the first %x3D ("=") character, and the (possibly
- // empty) value string consists of the characters after the first
- // %x3D ("=") character.
- const position = { position: 0 }
- name = collectASequenceOfCodePointsFast(
- '=',
- nameValuePair,
- position
- )
- value = nameValuePair.slice(position.position + 1)
+ static [Symbol.hasInstance] (instance) {
+ return instance && instance[kConnectTimeoutError] === true
}
- // 4. Remove any leading or trailing WSP characters from the name
- // string and the value string.
- name = name.trim()
- value = value.trim()
-
- // 5. If the sum of the lengths of the name string and the value string
- // is more than 4096 octets, abort these steps and ignore the set-
- // cookie-string entirely.
- if (name.length + value.length > maxNameValuePairSize) {
- return null
+ [kConnectTimeoutError] = true
+}
+
+const kHeadersTimeoutError = Symbol.for('undici.error.UND_ERR_HEADERS_TIMEOUT')
+class HeadersTimeoutError extends UndiciError {
+ constructor (message) {
+ super(message)
+ this.name = 'HeadersTimeoutError'
+ this.message = message || 'Headers Timeout Error'
+ this.code = 'UND_ERR_HEADERS_TIMEOUT'
}
- // 6. The cookie-name is the name string, and the cookie-value is the
- // value string.
- return {
- name, value, ...parseUnparsedAttributes(unparsedAttributes)
+ static [Symbol.hasInstance] (instance) {
+ return instance && instance[kHeadersTimeoutError] === true
}
+
+ [kHeadersTimeoutError] = true
}
-/**
- * Parses the remaining attributes of a set-cookie header
- * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4
- * @param {string} unparsedAttributes
- * @param {[Object.]={}} cookieAttributeList
- */
-function parseUnparsedAttributes (unparsedAttributes, cookieAttributeList = {}) {
- // 1. If the unparsed-attributes string is empty, skip the rest of
- // these steps.
- if (unparsedAttributes.length === 0) {
- return cookieAttributeList
+const kHeadersOverflowError = Symbol.for('undici.error.UND_ERR_HEADERS_OVERFLOW')
+class HeadersOverflowError extends UndiciError {
+ constructor (message) {
+ super(message)
+ this.name = 'HeadersOverflowError'
+ this.message = message || 'Headers Overflow Error'
+ this.code = 'UND_ERR_HEADERS_OVERFLOW'
}
- // 2. Discard the first character of the unparsed-attributes (which
- // will be a %x3B (";") character).
- assert(unparsedAttributes[0] === ';')
- unparsedAttributes = unparsedAttributes.slice(1)
+ static [Symbol.hasInstance] (instance) {
+ return instance && instance[kHeadersOverflowError] === true
+ }
- let cookieAv = ''
+ [kHeadersOverflowError] = true
+}
- // 3. If the remaining unparsed-attributes contains a %x3B (";")
- // character:
- if (unparsedAttributes.includes(';')) {
- // 1. Consume the characters of the unparsed-attributes up to, but
- // not including, the first %x3B (";") character.
- cookieAv = collectASequenceOfCodePointsFast(
- ';',
- unparsedAttributes,
- { position: 0 }
- )
- unparsedAttributes = unparsedAttributes.slice(cookieAv.length)
- } else {
- // Otherwise:
+const kBodyTimeoutError = Symbol.for('undici.error.UND_ERR_BODY_TIMEOUT')
+class BodyTimeoutError extends UndiciError {
+ constructor (message) {
+ super(message)
+ this.name = 'BodyTimeoutError'
+ this.message = message || 'Body Timeout Error'
+ this.code = 'UND_ERR_BODY_TIMEOUT'
+ }
- // 1. Consume the remainder of the unparsed-attributes.
- cookieAv = unparsedAttributes
- unparsedAttributes = ''
+ static [Symbol.hasInstance] (instance) {
+ return instance && instance[kBodyTimeoutError] === true
}
- // Let the cookie-av string be the characters consumed in this step.
+ [kBodyTimeoutError] = true
+}
- let attributeName = ''
- let attributeValue = ''
+const kResponseStatusCodeError = Symbol.for('undici.error.UND_ERR_RESPONSE_STATUS_CODE')
+class ResponseStatusCodeError extends UndiciError {
+ constructor (message, statusCode, headers, body) {
+ super(message)
+ this.name = 'ResponseStatusCodeError'
+ this.message = message || 'Response Status Code Error'
+ this.code = 'UND_ERR_RESPONSE_STATUS_CODE'
+ this.body = body
+ this.status = statusCode
+ this.statusCode = statusCode
+ this.headers = headers
+ }
- // 4. If the cookie-av string contains a %x3D ("=") character:
- if (cookieAv.includes('=')) {
- // 1. The (possibly empty) attribute-name string consists of the
- // characters up to, but not including, the first %x3D ("=")
- // character, and the (possibly empty) attribute-value string
- // consists of the characters after the first %x3D ("=")
- // character.
- const position = { position: 0 }
+ static [Symbol.hasInstance] (instance) {
+ return instance && instance[kResponseStatusCodeError] === true
+ }
- attributeName = collectASequenceOfCodePointsFast(
- '=',
- cookieAv,
- position
- )
- attributeValue = cookieAv.slice(position.position + 1)
- } else {
- // Otherwise:
+ [kResponseStatusCodeError] = true
+}
- // 1. The attribute-name string consists of the entire cookie-av
- // string, and the attribute-value string is empty.
- attributeName = cookieAv
+const kInvalidArgumentError = Symbol.for('undici.error.UND_ERR_INVALID_ARG')
+class InvalidArgumentError extends UndiciError {
+ constructor (message) {
+ super(message)
+ this.name = 'InvalidArgumentError'
+ this.message = message || 'Invalid Argument Error'
+ this.code = 'UND_ERR_INVALID_ARG'
}
- // 5. Remove any leading or trailing WSP characters from the attribute-
- // name string and the attribute-value string.
- attributeName = attributeName.trim()
- attributeValue = attributeValue.trim()
-
- // 6. If the attribute-value is longer than 1024 octets, ignore the
- // cookie-av string and return to Step 1 of this algorithm.
- if (attributeValue.length > maxAttributeValueSize) {
- return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
+ static [Symbol.hasInstance] (instance) {
+ return instance && instance[kInvalidArgumentError] === true
}
- // 7. Process the attribute-name and attribute-value according to the
- // requirements in the following subsections. (Notice that
- // attributes with unrecognized attribute-names are ignored.)
- const attributeNameLowercase = attributeName.toLowerCase()
+ [kInvalidArgumentError] = true
+}
- // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.1
- // If the attribute-name case-insensitively matches the string
- // "Expires", the user agent MUST process the cookie-av as follows.
- if (attributeNameLowercase === 'expires') {
- // 1. Let the expiry-time be the result of parsing the attribute-value
- // as cookie-date (see Section 5.1.1).
- const expiryTime = new Date(attributeValue)
+const kInvalidReturnValueError = Symbol.for('undici.error.UND_ERR_INVALID_RETURN_VALUE')
+class InvalidReturnValueError extends UndiciError {
+ constructor (message) {
+ super(message)
+ this.name = 'InvalidReturnValueError'
+ this.message = message || 'Invalid Return Value Error'
+ this.code = 'UND_ERR_INVALID_RETURN_VALUE'
+ }
- // 2. If the attribute-value failed to parse as a cookie date, ignore
- // the cookie-av.
+ static [Symbol.hasInstance] (instance) {
+ return instance && instance[kInvalidReturnValueError] === true
+ }
- cookieAttributeList.expires = expiryTime
- } else if (attributeNameLowercase === 'max-age') {
- // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.2
- // If the attribute-name case-insensitively matches the string "Max-
- // Age", the user agent MUST process the cookie-av as follows.
+ [kInvalidReturnValueError] = true
+}
- // 1. If the first character of the attribute-value is not a DIGIT or a
- // "-" character, ignore the cookie-av.
- const charCode = attributeValue.charCodeAt(0)
+const kAbortError = Symbol.for('undici.error.UND_ERR_ABORT')
+class AbortError extends UndiciError {
+ constructor (message) {
+ super(message)
+ this.name = 'AbortError'
+ this.message = message || 'The operation was aborted'
+ this.code = 'UND_ERR_ABORT'
+ }
- if ((charCode < 48 || charCode > 57) && attributeValue[0] !== '-') {
- return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
- }
+ static [Symbol.hasInstance] (instance) {
+ return instance && instance[kAbortError] === true
+ }
- // 2. If the remainder of attribute-value contains a non-DIGIT
- // character, ignore the cookie-av.
- if (!/^\d+$/.test(attributeValue)) {
- return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
- }
+ [kAbortError] = true
+}
- // 3. Let delta-seconds be the attribute-value converted to an integer.
- const deltaSeconds = Number(attributeValue)
+const kRequestAbortedError = Symbol.for('undici.error.UND_ERR_ABORTED')
+class RequestAbortedError extends AbortError {
+ constructor (message) {
+ super(message)
+ this.name = 'AbortError'
+ this.message = message || 'Request aborted'
+ this.code = 'UND_ERR_ABORTED'
+ }
- // 4. Let cookie-age-limit be the maximum age of the cookie (which
- // SHOULD be 400 days or less, see Section 4.1.2.2).
+ static [Symbol.hasInstance] (instance) {
+ return instance && instance[kRequestAbortedError] === true
+ }
- // 5. Set delta-seconds to the smaller of its present value and cookie-
- // age-limit.
- // deltaSeconds = Math.min(deltaSeconds * 1000, maxExpiresMs)
+ [kRequestAbortedError] = true
+}
- // 6. If delta-seconds is less than or equal to zero (0), let expiry-
- // time be the earliest representable date and time. Otherwise, let
- // the expiry-time be the current date and time plus delta-seconds
- // seconds.
- // const expiryTime = deltaSeconds <= 0 ? Date.now() : Date.now() + deltaSeconds
+const kInformationalError = Symbol.for('undici.error.UND_ERR_INFO')
+class InformationalError extends UndiciError {
+ constructor (message) {
+ super(message)
+ this.name = 'InformationalError'
+ this.message = message || 'Request information'
+ this.code = 'UND_ERR_INFO'
+ }
- // 7. Append an attribute to the cookie-attribute-list with an
- // attribute-name of Max-Age and an attribute-value of expiry-time.
- cookieAttributeList.maxAge = deltaSeconds
- } else if (attributeNameLowercase === 'domain') {
- // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.3
- // If the attribute-name case-insensitively matches the string "Domain",
- // the user agent MUST process the cookie-av as follows.
+ static [Symbol.hasInstance] (instance) {
+ return instance && instance[kInformationalError] === true
+ }
- // 1. Let cookie-domain be the attribute-value.
- let cookieDomain = attributeValue
+ [kInformationalError] = true
+}
- // 2. If cookie-domain starts with %x2E ("."), let cookie-domain be
- // cookie-domain without its leading %x2E (".").
- if (cookieDomain[0] === '.') {
- cookieDomain = cookieDomain.slice(1)
- }
+const kRequestContentLengthMismatchError = Symbol.for('undici.error.UND_ERR_REQ_CONTENT_LENGTH_MISMATCH')
+class RequestContentLengthMismatchError extends UndiciError {
+ constructor (message) {
+ super(message)
+ this.name = 'RequestContentLengthMismatchError'
+ this.message = message || 'Request body length does not match content-length header'
+ this.code = 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH'
+ }
- // 3. Convert the cookie-domain to lower case.
- cookieDomain = cookieDomain.toLowerCase()
+ static [Symbol.hasInstance] (instance) {
+ return instance && instance[kRequestContentLengthMismatchError] === true
+ }
- // 4. Append an attribute to the cookie-attribute-list with an
- // attribute-name of Domain and an attribute-value of cookie-domain.
- cookieAttributeList.domain = cookieDomain
- } else if (attributeNameLowercase === 'path') {
- // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.4
- // If the attribute-name case-insensitively matches the string "Path",
- // the user agent MUST process the cookie-av as follows.
+ [kRequestContentLengthMismatchError] = true
+}
- // 1. If the attribute-value is empty or if the first character of the
- // attribute-value is not %x2F ("/"):
- let cookiePath = ''
- if (attributeValue.length === 0 || attributeValue[0] !== '/') {
- // 1. Let cookie-path be the default-path.
- cookiePath = '/'
- } else {
- // Otherwise:
+const kResponseContentLengthMismatchError = Symbol.for('undici.error.UND_ERR_RES_CONTENT_LENGTH_MISMATCH')
+class ResponseContentLengthMismatchError extends UndiciError {
+ constructor (message) {
+ super(message)
+ this.name = 'ResponseContentLengthMismatchError'
+ this.message = message || 'Response body length does not match content-length header'
+ this.code = 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH'
+ }
- // 1. Let cookie-path be the attribute-value.
- cookiePath = attributeValue
- }
+ static [Symbol.hasInstance] (instance) {
+ return instance && instance[kResponseContentLengthMismatchError] === true
+ }
- // 2. Append an attribute to the cookie-attribute-list with an
- // attribute-name of Path and an attribute-value of cookie-path.
- cookieAttributeList.path = cookiePath
- } else if (attributeNameLowercase === 'secure') {
- // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.5
- // If the attribute-name case-insensitively matches the string "Secure",
- // the user agent MUST append an attribute to the cookie-attribute-list
- // with an attribute-name of Secure and an empty attribute-value.
+ [kResponseContentLengthMismatchError] = true
+}
- cookieAttributeList.secure = true
- } else if (attributeNameLowercase === 'httponly') {
- // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.6
- // If the attribute-name case-insensitively matches the string
- // "HttpOnly", the user agent MUST append an attribute to the cookie-
- // attribute-list with an attribute-name of HttpOnly and an empty
- // attribute-value.
+const kClientDestroyedError = Symbol.for('undici.error.UND_ERR_DESTROYED')
+class ClientDestroyedError extends UndiciError {
+ constructor (message) {
+ super(message)
+ this.name = 'ClientDestroyedError'
+ this.message = message || 'The client is destroyed'
+ this.code = 'UND_ERR_DESTROYED'
+ }
- cookieAttributeList.httpOnly = true
- } else if (attributeNameLowercase === 'samesite') {
- // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.7
- // If the attribute-name case-insensitively matches the string
- // "SameSite", the user agent MUST process the cookie-av as follows:
+ static [Symbol.hasInstance] (instance) {
+ return instance && instance[kClientDestroyedError] === true
+ }
- // 1. Let enforcement be "Default".
- let enforcement = 'Default'
+ [kClientDestroyedError] = true
+}
- const attributeValueLowercase = attributeValue.toLowerCase()
- // 2. If cookie-av's attribute-value is a case-insensitive match for
- // "None", set enforcement to "None".
- if (attributeValueLowercase.includes('none')) {
- enforcement = 'None'
- }
+const kClientClosedError = Symbol.for('undici.error.UND_ERR_CLOSED')
+class ClientClosedError extends UndiciError {
+ constructor (message) {
+ super(message)
+ this.name = 'ClientClosedError'
+ this.message = message || 'The client is closed'
+ this.code = 'UND_ERR_CLOSED'
+ }
- // 3. If cookie-av's attribute-value is a case-insensitive match for
- // "Strict", set enforcement to "Strict".
- if (attributeValueLowercase.includes('strict')) {
- enforcement = 'Strict'
- }
+ static [Symbol.hasInstance] (instance) {
+ return instance && instance[kClientClosedError] === true
+ }
- // 4. If cookie-av's attribute-value is a case-insensitive match for
- // "Lax", set enforcement to "Lax".
- if (attributeValueLowercase.includes('lax')) {
- enforcement = 'Lax'
- }
+ [kClientClosedError] = true
+}
- // 5. Append an attribute to the cookie-attribute-list with an
- // attribute-name of "SameSite" and an attribute-value of
- // enforcement.
- cookieAttributeList.sameSite = enforcement
- } else {
- cookieAttributeList.unparsed ??= []
+const kSocketError = Symbol.for('undici.error.UND_ERR_SOCKET')
+class SocketError extends UndiciError {
+ constructor (message, socket) {
+ super(message)
+ this.name = 'SocketError'
+ this.message = message || 'Socket error'
+ this.code = 'UND_ERR_SOCKET'
+ this.socket = socket
+ }
- cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`)
+ static [Symbol.hasInstance] (instance) {
+ return instance && instance[kSocketError] === true
}
- // 8. Return to Step 1 of this algorithm.
- return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
+ [kSocketError] = true
}
-module.exports = {
- parseSetCookie,
- parseUnparsedAttributes
-}
+const kNotSupportedError = Symbol.for('undici.error.UND_ERR_NOT_SUPPORTED')
+class NotSupportedError extends UndiciError {
+ constructor (message) {
+ super(message)
+ this.name = 'NotSupportedError'
+ this.message = message || 'Not supported error'
+ this.code = 'UND_ERR_NOT_SUPPORTED'
+ }
+ static [Symbol.hasInstance] (instance) {
+ return instance && instance[kNotSupportedError] === true
+ }
-/***/ }),
+ [kNotSupportedError] = true
+}
-/***/ 9556:
-/***/ ((module) => {
+const kBalancedPoolMissingUpstreamError = Symbol.for('undici.error.UND_ERR_BPL_MISSING_UPSTREAM')
+class BalancedPoolMissingUpstreamError extends UndiciError {
+ constructor (message) {
+ super(message)
+ this.name = 'MissingUpstreamError'
+ this.message = message || 'No upstream has been added to the BalancedPool'
+ this.code = 'UND_ERR_BPL_MISSING_UPSTREAM'
+ }
+ static [Symbol.hasInstance] (instance) {
+ return instance && instance[kBalancedPoolMissingUpstreamError] === true
+ }
+ [kBalancedPoolMissingUpstreamError] = true
+}
-/**
- * @param {string} value
- * @returns {boolean}
- */
-function isCTLExcludingHtab (value) {
- for (let i = 0; i < value.length; ++i) {
- const code = value.charCodeAt(i)
+const kHTTPParserError = Symbol.for('undici.error.UND_ERR_HTTP_PARSER')
+class HTTPParserError extends Error {
+ constructor (message, code, data) {
+ super(message)
+ this.name = 'HTTPParserError'
+ this.code = code ? `HPE_${code}` : undefined
+ this.data = data ? data.toString() : undefined
+ }
- if (
- (code >= 0x00 && code <= 0x08) ||
- (code >= 0x0A && code <= 0x1F) ||
- code === 0x7F
- ) {
- return true
- }
+ static [Symbol.hasInstance] (instance) {
+ return instance && instance[kHTTPParserError] === true
}
- return false
+
+ [kHTTPParserError] = true
}
-/**
- CHAR =
- token = 1*
- separators = "(" | ")" | "<" | ">" | "@"
- | "," | ";" | ":" | "\" | <">
- | "/" | "[" | "]" | "?" | "="
- | "{" | "}" | SP | HT
- * @param {string} name
- */
-function validateCookieName (name) {
- for (let i = 0; i < name.length; ++i) {
- const code = name.charCodeAt(i)
+const kResponseExceededMaxSizeError = Symbol.for('undici.error.UND_ERR_RES_EXCEEDED_MAX_SIZE')
+class ResponseExceededMaxSizeError extends UndiciError {
+ constructor (message) {
+ super(message)
+ this.name = 'ResponseExceededMaxSizeError'
+ this.message = message || 'Response content exceeded max size'
+ this.code = 'UND_ERR_RES_EXCEEDED_MAX_SIZE'
+ }
- if (
- code < 0x21 || // exclude CTLs (0-31), SP and HT
- code > 0x7E || // exclude non-ascii and DEL
- code === 0x22 || // "
- code === 0x28 || // (
- code === 0x29 || // )
- code === 0x3C || // <
- code === 0x3E || // >
- code === 0x40 || // @
- code === 0x2C || // ,
- code === 0x3B || // ;
- code === 0x3A || // :
- code === 0x5C || // \
- code === 0x2F || // /
- code === 0x5B || // [
- code === 0x5D || // ]
- code === 0x3F || // ?
- code === 0x3D || // =
- code === 0x7B || // {
- code === 0x7D // }
- ) {
- throw new Error('Invalid cookie name')
- }
+ static [Symbol.hasInstance] (instance) {
+ return instance && instance[kResponseExceededMaxSizeError] === true
}
-}
-/**
- cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )
- cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E
- ; US-ASCII characters excluding CTLs,
- ; whitespace DQUOTE, comma, semicolon,
- ; and backslash
- * @param {string} value
- */
-function validateCookieValue (value) {
- let len = value.length
- let i = 0
+ [kResponseExceededMaxSizeError] = true
+}
- // if the value is wrapped in DQUOTE
- if (value[0] === '"') {
- if (len === 1 || value[len - 1] !== '"') {
- throw new Error('Invalid cookie value')
- }
- --len
- ++i
+const kRequestRetryError = Symbol.for('undici.error.UND_ERR_REQ_RETRY')
+class RequestRetryError extends UndiciError {
+ constructor (message, code, { headers, data }) {
+ super(message)
+ this.name = 'RequestRetryError'
+ this.message = message || 'Request retry error'
+ this.code = 'UND_ERR_REQ_RETRY'
+ this.statusCode = code
+ this.data = data
+ this.headers = headers
}
- while (i < len) {
- const code = value.charCodeAt(i++)
+ static [Symbol.hasInstance] (instance) {
+ return instance && instance[kRequestRetryError] === true
+ }
- if (
- code < 0x21 || // exclude CTLs (0-31)
- code > 0x7E || // non-ascii and DEL (127)
- code === 0x22 || // "
- code === 0x2C || // ,
- code === 0x3B || // ;
- code === 0x5C // \
- ) {
- throw new Error('Invalid cookie value')
- }
+ [kRequestRetryError] = true
+}
+
+const kResponseError = Symbol.for('undici.error.UND_ERR_RESPONSE')
+class ResponseError extends UndiciError {
+ constructor (message, code, { headers, data }) {
+ super(message)
+ this.name = 'ResponseError'
+ this.message = message || 'Response error'
+ this.code = 'UND_ERR_RESPONSE'
+ this.statusCode = code
+ this.data = data
+ this.headers = headers
+ }
+
+ static [Symbol.hasInstance] (instance) {
+ return instance && instance[kResponseError] === true
}
+
+ [kResponseError] = true
}
-/**
- * path-value =
- * @param {string} path
- */
-function validateCookiePath (path) {
- for (let i = 0; i < path.length; ++i) {
- const code = path.charCodeAt(i)
+const kSecureProxyConnectionError = Symbol.for('undici.error.UND_ERR_PRX_TLS')
+class SecureProxyConnectionError extends UndiciError {
+ constructor (cause, message, options) {
+ super(message, { cause, ...(options ?? {}) })
+ this.name = 'SecureProxyConnectionError'
+ this.message = message || 'Secure Proxy Connection failed'
+ this.code = 'UND_ERR_PRX_TLS'
+ this.cause = cause
+ }
- if (
- code < 0x20 || // exclude CTLs (0-31)
- code === 0x7F || // DEL
- code === 0x3B // ;
- ) {
- throw new Error('Invalid cookie path')
- }
+ static [Symbol.hasInstance] (instance) {
+ return instance && instance[kSecureProxyConnectionError] === true
}
+
+ [kSecureProxyConnectionError] = true
}
-/**
- * I have no idea why these values aren't allowed to be honest,
- * but Deno tests these. - Khafra
- * @param {string} domain
- */
-function validateCookieDomain (domain) {
- if (
- domain.startsWith('-') ||
- domain.endsWith('.') ||
- domain.endsWith('-')
- ) {
- throw new Error('Invalid cookie domain')
+const kMessageSizeExceededError = Symbol.for('undici.error.UND_ERR_WS_MESSAGE_SIZE_EXCEEDED')
+class MessageSizeExceededError extends UndiciError {
+ constructor (message) {
+ super(message)
+ this.name = 'MessageSizeExceededError'
+ this.message = message || 'Max decompressed message size exceeded'
+ this.code = 'UND_ERR_WS_MESSAGE_SIZE_EXCEEDED'
+ }
+
+ static [Symbol.hasInstance] (instance) {
+ return instance && instance[kMessageSizeExceededError] === true
+ }
+
+ get [kMessageSizeExceededError] () {
+ return true
}
}
-const IMFDays = [
- 'Sun', 'Mon', 'Tue', 'Wed',
- 'Thu', 'Fri', 'Sat'
-]
+module.exports = {
+ AbortError,
+ HTTPParserError,
+ UndiciError,
+ HeadersTimeoutError,
+ HeadersOverflowError,
+ BodyTimeoutError,
+ RequestContentLengthMismatchError,
+ ConnectTimeoutError,
+ ResponseStatusCodeError,
+ InvalidArgumentError,
+ InvalidReturnValueError,
+ RequestAbortedError,
+ ClientDestroyedError,
+ ClientClosedError,
+ InformationalError,
+ SocketError,
+ NotSupportedError,
+ ResponseContentLengthMismatchError,
+ BalancedPoolMissingUpstreamError,
+ ResponseExceededMaxSizeError,
+ RequestRetryError,
+ ResponseError,
+ SecureProxyConnectionError,
+ MessageSizeExceededError
+}
-const IMFMonths = [
- 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
- 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
-]
-const IMFPaddedNumbers = Array(61).fill(0).map((_, i) => i.toString().padStart(2, '0'))
+/***/ }),
-/**
- * @see https://www.rfc-editor.org/rfc/rfc7231#section-7.1.1.1
- * @param {number|Date} date
- IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
- ; fixed length/zone/capitalization subset of the format
- ; see Section 3.3 of [RFC5322]
+/***/ 4655:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- day-name = %x4D.6F.6E ; "Mon", case-sensitive
- / %x54.75.65 ; "Tue", case-sensitive
- / %x57.65.64 ; "Wed", case-sensitive
- / %x54.68.75 ; "Thu", case-sensitive
- / %x46.72.69 ; "Fri", case-sensitive
- / %x53.61.74 ; "Sat", case-sensitive
- / %x53.75.6E ; "Sun", case-sensitive
- date1 = day SP month SP year
- ; e.g., 02 Jun 1982
- day = 2DIGIT
- month = %x4A.61.6E ; "Jan", case-sensitive
- / %x46.65.62 ; "Feb", case-sensitive
- / %x4D.61.72 ; "Mar", case-sensitive
- / %x41.70.72 ; "Apr", case-sensitive
- / %x4D.61.79 ; "May", case-sensitive
- / %x4A.75.6E ; "Jun", case-sensitive
- / %x4A.75.6C ; "Jul", case-sensitive
- / %x41.75.67 ; "Aug", case-sensitive
- / %x53.65.70 ; "Sep", case-sensitive
- / %x4F.63.74 ; "Oct", case-sensitive
- / %x4E.6F.76 ; "Nov", case-sensitive
- / %x44.65.63 ; "Dec", case-sensitive
- year = 4DIGIT
- GMT = %x47.4D.54 ; "GMT", case-sensitive
+const {
+ InvalidArgumentError,
+ NotSupportedError
+} = __nccwpck_require__(8707)
+const assert = __nccwpck_require__(4589)
+const {
+ isValidHTTPToken,
+ isValidHeaderValue,
+ isStream,
+ destroy,
+ isBuffer,
+ isFormDataLike,
+ isIterable,
+ isBlobLike,
+ buildURL,
+ validateHandler,
+ getServerName,
+ normalizedMethodRecords
+} = __nccwpck_require__(3440)
+const { channels } = __nccwpck_require__(2414)
+const { headerNameLowerCasedRecord } = __nccwpck_require__(735)
- time-of-day = hour ":" minute ":" second
- ; 00:00:00 - 23:59:60 (leap second)
+// Verifies that a given path is valid does not contain control chars \x00 to \x20
+const invalidPathRegex = /[^\u0021-\u00ff]/
- hour = 2DIGIT
- minute = 2DIGIT
- second = 2DIGIT
- */
-function toIMFDate (date) {
- if (typeof date === 'number') {
- date = new Date(date)
- }
+const kHandler = Symbol('handler')
- return `${IMFDays[date.getUTCDay()]}, ${IMFPaddedNumbers[date.getUTCDate()]} ${IMFMonths[date.getUTCMonth()]} ${date.getUTCFullYear()} ${IMFPaddedNumbers[date.getUTCHours()]}:${IMFPaddedNumbers[date.getUTCMinutes()]}:${IMFPaddedNumbers[date.getUTCSeconds()]} GMT`
-}
+class Request {
+ constructor (origin, {
+ path,
+ method,
+ body,
+ headers,
+ query,
+ idempotent,
+ blocking,
+ upgrade,
+ headersTimeout,
+ bodyTimeout,
+ reset,
+ throwOnError,
+ expectContinue,
+ servername
+ }, handler) {
+ if (typeof path !== 'string') {
+ throw new InvalidArgumentError('path must be a string')
+ } else if (
+ path[0] !== '/' &&
+ !(path.startsWith('http://') || path.startsWith('https://')) &&
+ method !== 'CONNECT'
+ ) {
+ throw new InvalidArgumentError('path must be an absolute URL or start with a slash')
+ } else if (invalidPathRegex.test(path)) {
+ throw new InvalidArgumentError('invalid request path')
+ }
-/**
- max-age-av = "Max-Age=" non-zero-digit *DIGIT
- ; In practice, both expires-av and max-age-av
- ; are limited to dates representable by the
- ; user agent.
- * @param {number} maxAge
- */
-function validateCookieMaxAge (maxAge) {
- if (maxAge < 0) {
- throw new Error('Invalid cookie max-age')
- }
-}
+ if (typeof method !== 'string') {
+ throw new InvalidArgumentError('method must be a string')
+ } else if (normalizedMethodRecords[method] === undefined && !isValidHTTPToken(method)) {
+ throw new InvalidArgumentError('invalid request method')
+ }
-/**
- * @see https://www.rfc-editor.org/rfc/rfc6265#section-4.1.1
- * @param {import('./index').Cookie} cookie
- */
-function stringify (cookie) {
- if (cookie.name.length === 0) {
- return null
- }
+ if (upgrade && typeof upgrade !== 'string') {
+ throw new InvalidArgumentError('upgrade must be a string')
+ }
- validateCookieName(cookie.name)
- validateCookieValue(cookie.value)
+ if (upgrade && !isValidHeaderValue(upgrade)) {
+ throw new InvalidArgumentError('invalid upgrade header')
+ }
- const out = [`${cookie.name}=${cookie.value}`]
+ if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) {
+ throw new InvalidArgumentError('invalid headersTimeout')
+ }
- // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.1
- // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.2
- if (cookie.name.startsWith('__Secure-')) {
- cookie.secure = true
- }
+ if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) {
+ throw new InvalidArgumentError('invalid bodyTimeout')
+ }
- if (cookie.name.startsWith('__Host-')) {
- cookie.secure = true
- cookie.domain = null
- cookie.path = '/'
- }
+ if (reset != null && typeof reset !== 'boolean') {
+ throw new InvalidArgumentError('invalid reset')
+ }
- if (cookie.secure) {
- out.push('Secure')
- }
+ if (expectContinue != null && typeof expectContinue !== 'boolean') {
+ throw new InvalidArgumentError('invalid expectContinue')
+ }
- if (cookie.httpOnly) {
- out.push('HttpOnly')
- }
+ this.headersTimeout = headersTimeout
- if (typeof cookie.maxAge === 'number') {
- validateCookieMaxAge(cookie.maxAge)
- out.push(`Max-Age=${cookie.maxAge}`)
- }
+ this.bodyTimeout = bodyTimeout
- if (cookie.domain) {
- validateCookieDomain(cookie.domain)
- out.push(`Domain=${cookie.domain}`)
- }
+ this.throwOnError = throwOnError === true
- if (cookie.path) {
- validateCookiePath(cookie.path)
- out.push(`Path=${cookie.path}`)
- }
+ this.method = method
- if (cookie.expires && cookie.expires.toString() !== 'Invalid Date') {
- out.push(`Expires=${toIMFDate(cookie.expires)}`)
- }
+ this.abort = null
- if (cookie.sameSite) {
- out.push(`SameSite=${cookie.sameSite}`)
- }
+ if (body == null) {
+ this.body = null
+ } else if (isStream(body)) {
+ this.body = body
- for (const part of cookie.unparsed) {
- if (!part.includes('=')) {
- throw new Error('Invalid unparsed')
- }
+ const rState = this.body._readableState
+ if (!rState || !rState.autoDestroy) {
+ this.endHandler = function autoDestroy () {
+ destroy(this)
+ }
+ this.body.on('end', this.endHandler)
+ }
- const [key, ...value] = part.split('=')
+ this.errorHandler = err => {
+ if (this.abort) {
+ this.abort(err)
+ } else {
+ this.error = err
+ }
+ }
+ this.body.on('error', this.errorHandler)
+ } else if (isBuffer(body)) {
+ this.body = body.byteLength ? body : null
+ } else if (ArrayBuffer.isView(body)) {
+ this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null
+ } else if (body instanceof ArrayBuffer) {
+ this.body = body.byteLength ? Buffer.from(body) : null
+ } else if (typeof body === 'string') {
+ this.body = body.length ? Buffer.from(body) : null
+ } else if (isFormDataLike(body) || isIterable(body) || isBlobLike(body)) {
+ this.body = body
+ } else {
+ throw new InvalidArgumentError('body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable')
+ }
- out.push(`${key.trim()}=${value.join('=')}`)
- }
+ this.completed = false
- return out.join('; ')
-}
+ this.aborted = false
-module.exports = {
- isCTLExcludingHtab,
- validateCookieName,
- validateCookiePath,
- validateCookieValue,
- toIMFDate,
- stringify
-}
+ this.upgrade = upgrade || null
+ this.path = query ? buildURL(path, query) : path
-/***/ }),
+ this.origin = origin
-/***/ 7974:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ this.idempotent = idempotent == null
+ ? method === 'HEAD' || method === 'GET'
+ : idempotent
+ this.blocking = blocking == null ? false : blocking
-const { Transform } = __nccwpck_require__(7075)
-const { isASCIINumber, isValidLastEventId } = __nccwpck_require__(8794)
+ this.reset = reset == null ? null : reset
-/**
- * @type {number[]} BOM
- */
-const BOM = [0xEF, 0xBB, 0xBF]
-/**
- * @type {10} LF
- */
-const LF = 0x0A
-/**
- * @type {13} CR
- */
-const CR = 0x0D
-/**
- * @type {58} COLON
- */
-const COLON = 0x3A
-/**
- * @type {32} SPACE
- */
-const SPACE = 0x20
+ this.host = null
-/**
- * @typedef {object} EventSourceStreamEvent
- * @type {object}
- * @property {string} [event] The event type.
- * @property {string} [data] The data of the message.
- * @property {string} [id] A unique ID for the event.
- * @property {string} [retry] The reconnection time, in milliseconds.
- */
+ this.contentLength = null
-/**
- * @typedef eventSourceSettings
- * @type {object}
- * @property {string} lastEventId The last event ID received from the server.
- * @property {string} origin The origin of the event source.
- * @property {number} reconnectionTime The reconnection time, in milliseconds.
- */
+ this.contentType = null
-class EventSourceStream extends Transform {
- /**
- * @type {eventSourceSettings}
- */
- state = null
+ this.headers = []
- /**
- * Leading byte-order-mark check.
- * @type {boolean}
- */
- checkBOM = true
+ // Only for H2
+ this.expectContinue = expectContinue != null ? expectContinue : false
- /**
- * @type {boolean}
- */
- crlfCheck = false
+ if (Array.isArray(headers)) {
+ if (headers.length % 2 !== 0) {
+ throw new InvalidArgumentError('headers array must be even')
+ }
+ for (let i = 0; i < headers.length; i += 2) {
+ processHeader(this, headers[i], headers[i + 1])
+ }
+ } else if (headers && typeof headers === 'object') {
+ if (headers[Symbol.iterator]) {
+ for (const header of headers) {
+ if (!Array.isArray(header) || header.length !== 2) {
+ throw new InvalidArgumentError('headers must be in key-value pair format')
+ }
+ processHeader(this, header[0], header[1])
+ }
+ } else {
+ const keys = Object.keys(headers)
+ for (let i = 0; i < keys.length; ++i) {
+ processHeader(this, keys[i], headers[keys[i]])
+ }
+ }
+ } else if (headers != null) {
+ throw new InvalidArgumentError('headers must be an object or an array')
+ }
- /**
- * @type {boolean}
- */
- eventEndCheck = false
+ validateHandler(handler, method, upgrade)
- /**
- * @type {Buffer}
- */
- buffer = null
+ this.servername = servername || getServerName(this.host)
- pos = 0
+ this[kHandler] = handler
- event = {
- data: undefined,
- event: undefined,
- id: undefined,
- retry: undefined
+ if (channels.create.hasSubscribers) {
+ channels.create.publish({ request: this })
+ }
}
- /**
- * @param {object} options
- * @param {eventSourceSettings} options.eventSourceSettings
- * @param {Function} [options.push]
- */
- constructor (options = {}) {
- // Enable object mode as EventSourceStream emits objects of shape
- // EventSourceStreamEvent
- options.readableObjectMode = true
+ onBodySent (chunk) {
+ if (this[kHandler].onBodySent) {
+ try {
+ return this[kHandler].onBodySent(chunk)
+ } catch (err) {
+ this.abort(err)
+ }
+ }
+ }
- super(options)
+ onRequestSent () {
+ if (channels.bodySent.hasSubscribers) {
+ channels.bodySent.publish({ request: this })
+ }
- this.state = options.eventSourceSettings || {}
- if (options.push) {
- this.push = options.push
+ if (this[kHandler].onRequestSent) {
+ try {
+ return this[kHandler].onRequestSent()
+ } catch (err) {
+ this.abort(err)
+ }
}
}
- /**
- * @param {Buffer} chunk
- * @param {string} _encoding
- * @param {Function} callback
- * @returns {void}
- */
- _transform (chunk, _encoding, callback) {
- if (chunk.length === 0) {
- callback()
- return
- }
+ onConnect (abort) {
+ assert(!this.aborted)
+ assert(!this.completed)
- // Cache the chunk in the buffer, as the data might not be complete while
- // processing it
- // TODO: Investigate if there is a more performant way to handle
- // incoming chunks
- // see: https://github.com/nodejs/undici/issues/2630
- if (this.buffer) {
- this.buffer = Buffer.concat([this.buffer, chunk])
+ if (this.error) {
+ abort(this.error)
} else {
- this.buffer = chunk
+ this.abort = abort
+ return this[kHandler].onConnect(abort)
}
+ }
- // Strip leading byte-order-mark if we opened the stream and started
- // the processing of the incoming data
- if (this.checkBOM) {
- switch (this.buffer.length) {
- case 1:
- // Check if the first byte is the same as the first byte of the BOM
- if (this.buffer[0] === BOM[0]) {
- // If it is, we need to wait for more data
- callback()
- return
- }
- // Set the checkBOM flag to false as we don't need to check for the
- // BOM anymore
- this.checkBOM = false
-
- // The buffer only contains one byte so we need to wait for more data
- callback()
- return
- case 2:
- // Check if the first two bytes are the same as the first two bytes
- // of the BOM
- if (
- this.buffer[0] === BOM[0] &&
- this.buffer[1] === BOM[1]
- ) {
- // If it is, we need to wait for more data, because the third byte
- // is needed to determine if it is the BOM or not
- callback()
- return
- }
+ onResponseStarted () {
+ return this[kHandler].onResponseStarted?.()
+ }
- // Set the checkBOM flag to false as we don't need to check for the
- // BOM anymore
- this.checkBOM = false
- break
- case 3:
- // Check if the first three bytes are the same as the first three
- // bytes of the BOM
- if (
- this.buffer[0] === BOM[0] &&
- this.buffer[1] === BOM[1] &&
- this.buffer[2] === BOM[2]
- ) {
- // If it is, we can drop the buffered data, as it is only the BOM
- this.buffer = Buffer.alloc(0)
- // Set the checkBOM flag to false as we don't need to check for the
- // BOM anymore
- this.checkBOM = false
+ onHeaders (statusCode, headers, resume, statusText) {
+ assert(!this.aborted)
+ assert(!this.completed)
- // Await more data
- callback()
- return
- }
- // If it is not the BOM, we can start processing the data
- this.checkBOM = false
- break
- default:
- // The buffer is longer than 3 bytes, so we can drop the BOM if it is
- // present
- if (
- this.buffer[0] === BOM[0] &&
- this.buffer[1] === BOM[1] &&
- this.buffer[2] === BOM[2]
- ) {
- // Remove the BOM from the buffer
- this.buffer = this.buffer.subarray(3)
- }
+ if (channels.headers.hasSubscribers) {
+ channels.headers.publish({ request: this, response: { statusCode, headers, statusText } })
+ }
- // Set the checkBOM flag to false as we don't need to check for the
- this.checkBOM = false
- break
- }
+ try {
+ return this[kHandler].onHeaders(statusCode, headers, resume, statusText)
+ } catch (err) {
+ this.abort(err)
}
+ }
- while (this.pos < this.buffer.length) {
- // If the previous line ended with an end-of-line, we need to check
- // if the next character is also an end-of-line.
- if (this.eventEndCheck) {
- // If the the current character is an end-of-line, then the event
- // is finished and we can process it
+ onData (chunk) {
+ assert(!this.aborted)
+ assert(!this.completed)
- // If the previous line ended with a carriage return, we need to
- // check if the current character is a line feed and remove it
- // from the buffer.
- if (this.crlfCheck) {
- // If the current character is a line feed, we can remove it
- // from the buffer and reset the crlfCheck flag
- if (this.buffer[this.pos] === LF) {
- this.buffer = this.buffer.subarray(this.pos + 1)
- this.pos = 0
- this.crlfCheck = false
+ try {
+ return this[kHandler].onData(chunk)
+ } catch (err) {
+ this.abort(err)
+ return false
+ }
+ }
- // It is possible that the line feed is not the end of the
- // event. We need to check if the next character is an
- // end-of-line character to determine if the event is
- // finished. We simply continue the loop to check the next
- // character.
+ onUpgrade (statusCode, headers, socket) {
+ assert(!this.aborted)
+ assert(!this.completed)
- // As we removed the line feed from the buffer and set the
- // crlfCheck flag to false, we basically don't make any
- // distinction between a line feed and a carriage return.
- continue
- }
- this.crlfCheck = false
- }
+ return this[kHandler].onUpgrade(statusCode, headers, socket)
+ }
- if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) {
- // If the current character is a carriage return, we need to
- // set the crlfCheck flag to true, as we need to check if the
- // next character is a line feed so we can remove it from the
- // buffer
- if (this.buffer[this.pos] === CR) {
- this.crlfCheck = true
- }
+ onComplete (trailers) {
+ this.onFinally()
- this.buffer = this.buffer.subarray(this.pos + 1)
- this.pos = 0
- if (
- this.event.data !== undefined || this.event.event || this.event.id || this.event.retry) {
- this.processEvent(this.event)
- }
- this.clearEvent()
- continue
- }
- // If the current character is not an end-of-line, then the event
- // is not finished and we have to reset the eventEndCheck flag
- this.eventEndCheck = false
- continue
- }
+ assert(!this.aborted)
- // If the current character is an end-of-line, we can process the
- // line
- if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) {
- // If the current character is a carriage return, we need to
- // set the crlfCheck flag to true, as we need to check if the
- // next character is a line feed
- if (this.buffer[this.pos] === CR) {
- this.crlfCheck = true
- }
+ this.completed = true
+ if (channels.trailers.hasSubscribers) {
+ channels.trailers.publish({ request: this, trailers })
+ }
- // In any case, we can process the line as we reached an
- // end-of-line character
- this.parseLine(this.buffer.subarray(0, this.pos), this.event)
+ try {
+ return this[kHandler].onComplete(trailers)
+ } catch (err) {
+ // TODO (fix): This might be a bad idea?
+ this.onError(err)
+ }
+ }
- // Remove the processed line from the buffer
- this.buffer = this.buffer.subarray(this.pos + 1)
- // Reset the position as we removed the processed line from the buffer
- this.pos = 0
- // A line was processed and this could be the end of the event. We need
- // to check if the next line is empty to determine if the event is
- // finished.
- this.eventEndCheck = true
- continue
- }
+ onError (error) {
+ this.onFinally()
- this.pos++
+ if (channels.error.hasSubscribers) {
+ channels.error.publish({ request: this, error })
}
- callback()
+ if (this.aborted) {
+ return
+ }
+ this.aborted = true
+
+ return this[kHandler].onError(error)
}
- /**
- * @param {Buffer} line
- * @param {EventStreamEvent} event
- */
- parseLine (line, event) {
- // If the line is empty (a blank line)
- // Dispatch the event, as defined below.
- // This will be handled in the _transform method
- if (line.length === 0) {
- return
+ onFinally () {
+ if (this.errorHandler) {
+ this.body.off('error', this.errorHandler)
+ this.errorHandler = null
}
- // If the line starts with a U+003A COLON character (:)
- // Ignore the line.
- const colonPosition = line.indexOf(COLON)
- if (colonPosition === 0) {
- return
+ if (this.endHandler) {
+ this.body.off('end', this.endHandler)
+ this.endHandler = null
}
+ }
- let field = ''
- let value = ''
+ addHeader (key, value) {
+ processHeader(this, key, value)
+ return this
+ }
+}
- // If the line contains a U+003A COLON character (:)
- if (colonPosition !== -1) {
- // Collect the characters on the line before the first U+003A COLON
- // character (:), and let field be that string.
- // TODO: Investigate if there is a more performant way to extract the
- // field
- // see: https://github.com/nodejs/undici/issues/2630
- field = line.subarray(0, colonPosition).toString('utf8')
+function processHeader (request, key, val) {
+ if (val && (typeof val === 'object' && !Array.isArray(val))) {
+ throw new InvalidArgumentError(`invalid ${key} header`)
+ } else if (val === undefined) {
+ return
+ }
- // Collect the characters on the line after the first U+003A COLON
- // character (:), and let value be that string.
- // If value starts with a U+0020 SPACE character, remove it from value.
- let valueStart = colonPosition + 1
- if (line[valueStart] === SPACE) {
- ++valueStart
- }
- // TODO: Investigate if there is a more performant way to extract the
- // value
- // see: https://github.com/nodejs/undici/issues/2630
- value = line.subarray(valueStart).toString('utf8')
+ let headerName = headerNameLowerCasedRecord[key]
- // Otherwise, the string is not empty but does not contain a U+003A COLON
- // character (:)
- } else {
- // Process the field using the steps described below, using the whole
- // line as the field name, and the empty string as the field value.
- field = line.toString('utf8')
- value = ''
+ if (headerName === undefined) {
+ headerName = key.toLowerCase()
+ if (headerNameLowerCasedRecord[headerName] === undefined && !isValidHTTPToken(headerName)) {
+ throw new InvalidArgumentError('invalid header key')
}
+ }
- // Modify the event with the field name and value. The value is also
- // decoded as UTF-8
- switch (field) {
- case 'data':
- if (event[field] === undefined) {
- event[field] = value
- } else {
- event[field] += `\n${value}`
- }
- break
- case 'retry':
- if (isASCIINumber(value)) {
- event[field] = value
- }
- break
- case 'id':
- if (isValidLastEventId(value)) {
- event[field] = value
- }
- break
- case 'event':
- if (value.length > 0) {
- event[field] = value
+ if (Array.isArray(val)) {
+ const arr = []
+ for (let i = 0; i < val.length; i++) {
+ if (typeof val[i] === 'string') {
+ if (!isValidHeaderValue(val[i])) {
+ throw new InvalidArgumentError(`invalid ${key} header`)
}
- break
+ arr.push(val[i])
+ } else if (val[i] === null) {
+ arr.push('')
+ } else if (typeof val[i] === 'object') {
+ throw new InvalidArgumentError(`invalid ${key} header`)
+ } else {
+ arr.push(`${val[i]}`)
+ }
+ }
+ val = arr
+ } else if (typeof val === 'string') {
+ if (!isValidHeaderValue(val)) {
+ throw new InvalidArgumentError(`invalid ${key} header`)
}
+ } else if (val === null) {
+ val = ''
+ } else {
+ val = `${val}`
}
- /**
- * @param {EventSourceStreamEvent} event
- */
- processEvent (event) {
- if (event.retry && isASCIINumber(event.retry)) {
- this.state.reconnectionTime = parseInt(event.retry, 10)
+ if (headerName === 'host') {
+ if (request.host !== null) {
+ throw new InvalidArgumentError('duplicate host header')
}
-
- if (event.id && isValidLastEventId(event.id)) {
- this.state.lastEventId = event.id
+ if (typeof val !== 'string') {
+ throw new InvalidArgumentError('invalid host header')
}
-
- // only dispatch event, when data is provided
- if (event.data !== undefined) {
- this.push({
- type: event.event || 'message',
- options: {
- data: event.data,
- lastEventId: this.state.lastEventId,
- origin: this.state.origin
- }
- })
+ // Consumed by Client
+ request.host = val
+ } else if (headerName === 'content-length') {
+ if (request.contentLength !== null) {
+ throw new InvalidArgumentError('duplicate content-length header')
+ }
+ request.contentLength = parseInt(val, 10)
+ if (!Number.isFinite(request.contentLength)) {
+ throw new InvalidArgumentError('invalid content-length header')
+ }
+ } else if (request.contentType === null && headerName === 'content-type') {
+ request.contentType = val
+ request.headers.push(key, val)
+ } else if (headerName === 'transfer-encoding' || headerName === 'keep-alive' || headerName === 'upgrade') {
+ throw new InvalidArgumentError(`invalid ${headerName} header`)
+ } else if (headerName === 'connection') {
+ const value = typeof val === 'string' ? val.toLowerCase() : null
+ if (value !== 'close' && value !== 'keep-alive') {
+ throw new InvalidArgumentError('invalid connection header')
}
- }
- clearEvent () {
- this.event = {
- data: undefined,
- event: undefined,
- id: undefined,
- retry: undefined
+ if (value === 'close') {
+ request.reset = true
}
+ } else if (headerName === 'expect') {
+ throw new NotSupportedError('expect header not supported')
+ } else {
+ request.headers.push(key, val)
}
}
-module.exports = {
- EventSourceStream
-}
+module.exports = Request
/***/ }),
-/***/ 5413:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
+/***/ 6443:
+/***/ ((module) => {
-const { pipeline } = __nccwpck_require__(7075)
-const { fetching } = __nccwpck_require__(8033)
-const { makeRequest } = __nccwpck_require__(7412)
-const { webidl } = __nccwpck_require__(220)
-const { EventSourceStream } = __nccwpck_require__(7974)
-const { parseMIMEType } = __nccwpck_require__(2121)
-const { createFastMessageEvent } = __nccwpck_require__(9617)
-const { isNetworkError } = __nccwpck_require__(6678)
-const { delay } = __nccwpck_require__(8794)
-const { kEnumerableProperty } = __nccwpck_require__(7375)
-const { environmentSettingsObject } = __nccwpck_require__(7241)
+module.exports = {
+ kClose: Symbol('close'),
+ kDestroy: Symbol('destroy'),
+ kDispatch: Symbol('dispatch'),
+ kUrl: Symbol('url'),
+ kWriting: Symbol('writing'),
+ kResuming: Symbol('resuming'),
+ kQueue: Symbol('queue'),
+ kConnect: Symbol('connect'),
+ kConnecting: Symbol('connecting'),
+ kKeepAliveDefaultTimeout: Symbol('default keep alive timeout'),
+ kKeepAliveMaxTimeout: Symbol('max keep alive timeout'),
+ kKeepAliveTimeoutThreshold: Symbol('keep alive timeout threshold'),
+ kKeepAliveTimeoutValue: Symbol('keep alive timeout'),
+ kKeepAlive: Symbol('keep alive'),
+ kHeadersTimeout: Symbol('headers timeout'),
+ kBodyTimeout: Symbol('body timeout'),
+ kServerName: Symbol('server name'),
+ kLocalAddress: Symbol('local address'),
+ kHost: Symbol('host'),
+ kNoRef: Symbol('no ref'),
+ kBodyUsed: Symbol('used'),
+ kBody: Symbol('abstracted request body'),
+ kRunning: Symbol('running'),
+ kBlocking: Symbol('blocking'),
+ kPending: Symbol('pending'),
+ kSize: Symbol('size'),
+ kBusy: Symbol('busy'),
+ kQueued: Symbol('queued'),
+ kFree: Symbol('free'),
+ kConnected: Symbol('connected'),
+ kClosed: Symbol('closed'),
+ kNeedDrain: Symbol('need drain'),
+ kReset: Symbol('reset'),
+ kDestroyed: Symbol.for('nodejs.stream.destroyed'),
+ kResume: Symbol('resume'),
+ kOnError: Symbol('on error'),
+ kMaxHeadersSize: Symbol('max headers size'),
+ kRunningIdx: Symbol('running index'),
+ kPendingIdx: Symbol('pending index'),
+ kError: Symbol('error'),
+ kClients: Symbol('clients'),
+ kClient: Symbol('client'),
+ kParser: Symbol('parser'),
+ kOnDestroyed: Symbol('destroy callbacks'),
+ kPipelining: Symbol('pipelining'),
+ kSocket: Symbol('socket'),
+ kHostHeader: Symbol('host header'),
+ kConnector: Symbol('connector'),
+ kStrictContentLength: Symbol('strict content length'),
+ kMaxRedirections: Symbol('maxRedirections'),
+ kMaxRequests: Symbol('maxRequestsPerClient'),
+ kProxy: Symbol('proxy agent options'),
+ kCounter: Symbol('socket request counter'),
+ kInterceptors: Symbol('dispatch interceptors'),
+ kMaxResponseSize: Symbol('max response size'),
+ kHTTP2Session: Symbol('http2Session'),
+ kHTTP2SessionState: Symbol('http2Session state'),
+ kRetryHandlerDefaultRetry: Symbol('retry agent default retry'),
+ kConstruct: Symbol('constructable'),
+ kListeners: Symbol('listeners'),
+ kHTTPContext: Symbol('http context'),
+ kMaxConcurrentStreams: Symbol('max concurrent streams'),
+ kNoProxyAgent: Symbol('no proxy agent'),
+ kHttpProxyAgent: Symbol('http proxy agent'),
+ kHttpsProxyAgent: Symbol('https proxy agent')
+}
-let experimentalWarned = false
-/**
- * A reconnection time, in milliseconds. This must initially be an implementation-defined value,
- * probably in the region of a few seconds.
- *
- * In Comparison:
- * - Chrome uses 3000ms.
- * - Deno uses 5000ms.
- *
- * @type {3000}
- */
-const defaultReconnectionTime = 3000
+/***/ }),
-/**
- * The readyState attribute represents the state of the connection.
- * @enum
- * @readonly
- * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#dom-eventsource-readystate-dev
- */
+/***/ 7752:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-/**
- * The connection has not yet been established, or it was closed and the user
- * agent is reconnecting.
- * @type {0}
- */
-const CONNECTING = 0
-/**
- * The user agent has an open connection and is dispatching events as it
- * receives them.
- * @type {1}
- */
-const OPEN = 1
-/**
- * The connection is not open, and the user agent is not trying to reconnect.
- * @type {2}
- */
-const CLOSED = 2
+const {
+ wellknownHeaderNames,
+ headerNameLowerCasedRecord
+} = __nccwpck_require__(735)
-/**
- * Requests for the element will have their mode set to "cors" and their credentials mode set to "same-origin".
- * @type {'anonymous'}
- */
-const ANONYMOUS = 'anonymous'
+class TstNode {
+ /** @type {any} */
+ value = null
+ /** @type {null | TstNode} */
+ left = null
+ /** @type {null | TstNode} */
+ middle = null
+ /** @type {null | TstNode} */
+ right = null
+ /** @type {number} */
+ code
+ /**
+ * @param {string} key
+ * @param {any} value
+ * @param {number} index
+ */
+ constructor (key, value, index) {
+ if (index === undefined || index >= key.length) {
+ throw new TypeError('Unreachable')
+ }
+ const code = this.code = key.charCodeAt(index)
+ // check code is ascii string
+ if (code > 0x7F) {
+ throw new TypeError('key must be ascii string')
+ }
+ if (key.length !== ++index) {
+ this.middle = new TstNode(key, value, index)
+ } else {
+ this.value = value
+ }
+ }
-/**
- * Requests for the element will have their mode set to "cors" and their credentials mode set to "include".
- * @type {'use-credentials'}
- */
-const USE_CREDENTIALS = 'use-credentials'
-
-/**
- * The EventSource interface is used to receive server-sent events. It
- * connects to a server over HTTP and receives events in text/event-stream
- * format without closing the connection.
- * @extends {EventTarget}
- * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#server-sent-events
- * @api public
- */
-class EventSource extends EventTarget {
- #events = {
- open: null,
- error: null,
- message: null
+ /**
+ * @param {string} key
+ * @param {any} value
+ */
+ add (key, value) {
+ const length = key.length
+ if (length === 0) {
+ throw new TypeError('Unreachable')
+ }
+ let index = 0
+ let node = this
+ while (true) {
+ const code = key.charCodeAt(index)
+ // check code is ascii string
+ if (code > 0x7F) {
+ throw new TypeError('key must be ascii string')
+ }
+ if (node.code === code) {
+ if (length === ++index) {
+ node.value = value
+ break
+ } else if (node.middle !== null) {
+ node = node.middle
+ } else {
+ node.middle = new TstNode(key, value, index)
+ break
+ }
+ } else if (node.code < code) {
+ if (node.left !== null) {
+ node = node.left
+ } else {
+ node.left = new TstNode(key, value, index)
+ break
+ }
+ } else if (node.right !== null) {
+ node = node.right
+ } else {
+ node.right = new TstNode(key, value, index)
+ break
+ }
+ }
}
- #url = null
- #withCredentials = false
-
- #readyState = CONNECTING
-
- #request = null
- #controller = null
+ /**
+ * @param {Uint8Array} key
+ * @return {TstNode | null}
+ */
+ search (key) {
+ const keylength = key.length
+ let index = 0
+ let node = this
+ while (node !== null && index < keylength) {
+ let code = key[index]
+ // A-Z
+ // First check if it is bigger than 0x5a.
+ // Lowercase letters have higher char codes than uppercase ones.
+ // Also we assume that headers will mostly contain lowercase characters.
+ if (code <= 0x5a && code >= 0x41) {
+ // Lowercase for uppercase.
+ code |= 32
+ }
+ while (node !== null) {
+ if (code === node.code) {
+ if (keylength === ++index) {
+ // Returns Node since it is the last key.
+ return node
+ }
+ node = node.middle
+ break
+ }
+ node = node.code < code ? node.left : node.right
+ }
+ }
+ return null
+ }
+}
- #dispatcher
+class TernarySearchTree {
+ /** @type {TstNode | null} */
+ node = null
/**
- * @type {import('./eventsource-stream').eventSourceSettings}
- */
- #state
+ * @param {string} key
+ * @param {any} value
+ * */
+ insert (key, value) {
+ if (this.node === null) {
+ this.node = new TstNode(key, value, 0)
+ } else {
+ this.node.add(key, value)
+ }
+ }
/**
- * Creates a new EventSource object.
- * @param {string} url
- * @param {EventSourceInit} [eventSourceInitDict]
- * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#the-eventsource-interface
+ * @param {Uint8Array} key
+ * @return {any}
*/
- constructor (url, eventSourceInitDict = {}) {
- // 1. Let ev be a new EventSource object.
- super()
+ lookup (key) {
+ return this.node?.search(key)?.value ?? null
+ }
+}
- webidl.util.markAsUncloneable(this)
+const tree = new TernarySearchTree()
- const prefix = 'EventSource constructor'
- webidl.argumentLengthCheck(arguments, 1, prefix)
+for (let i = 0; i < wellknownHeaderNames.length; ++i) {
+ const key = headerNameLowerCasedRecord[wellknownHeaderNames[i]]
+ tree.insert(key, key)
+}
- if (!experimentalWarned) {
- experimentalWarned = true
- process.emitWarning('EventSource is experimental, expect them to change at any time.', {
- code: 'UNDICI-ES'
- })
- }
+module.exports = {
+ TernarySearchTree,
+ tree
+}
- url = webidl.converters.USVString(url, prefix, 'url')
- eventSourceInitDict = webidl.converters.EventSourceInitDict(eventSourceInitDict, prefix, 'eventSourceInitDict')
- this.#dispatcher = eventSourceInitDict.dispatcher
- this.#state = {
- lastEventId: '',
- reconnectionTime: defaultReconnectionTime
- }
+/***/ }),
- // 2. Let settings be ev's relevant settings object.
- // https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object
- const settings = environmentSettingsObject
+/***/ 3440:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- let urlRecord
- try {
- // 3. Let urlRecord be the result of encoding-parsing a URL given url, relative to settings.
- urlRecord = new URL(url, settings.settingsObject.baseUrl)
- this.#state.origin = urlRecord.origin
- } catch (e) {
- // 4. If urlRecord is failure, then throw a "SyntaxError" DOMException.
- throw new DOMException(e, 'SyntaxError')
- }
- // 5. Set ev's url to urlRecord.
- this.#url = urlRecord.href
+const assert = __nccwpck_require__(4589)
+const { kDestroyed, kBodyUsed, kListeners, kBody } = __nccwpck_require__(6443)
+const { IncomingMessage } = __nccwpck_require__(7067)
+const stream = __nccwpck_require__(7075)
+const net = __nccwpck_require__(7030)
+const { Blob } = __nccwpck_require__(4573)
+const nodeUtil = __nccwpck_require__(7975)
+const { stringify } = __nccwpck_require__(1792)
+const { EventEmitter: EE } = __nccwpck_require__(8474)
+const { InvalidArgumentError } = __nccwpck_require__(8707)
+const { headerNameLowerCasedRecord } = __nccwpck_require__(735)
+const { tree } = __nccwpck_require__(7752)
- // 6. Let corsAttributeState be Anonymous.
- let corsAttributeState = ANONYMOUS
+const [nodeMajor, nodeMinor] = process.versions.node.split('.').map(v => Number(v))
- // 7. If the value of eventSourceInitDict's withCredentials member is true,
- // then set corsAttributeState to Use Credentials and set ev's
- // withCredentials attribute to true.
- if (eventSourceInitDict.withCredentials) {
- corsAttributeState = USE_CREDENTIALS
- this.#withCredentials = true
- }
+class BodyAsyncIterable {
+ constructor (body) {
+ this[kBody] = body
+ this[kBodyUsed] = false
+ }
- // 8. Let request be the result of creating a potential-CORS request given
- // urlRecord, the empty string, and corsAttributeState.
- const initRequest = {
- redirect: 'follow',
- keepalive: true,
- // @see https://html.spec.whatwg.org/multipage/urls-and-fetching.html#cors-settings-attributes
- mode: 'cors',
- credentials: corsAttributeState === 'anonymous'
- ? 'same-origin'
- : 'omit',
- referrer: 'no-referrer'
- }
+ async * [Symbol.asyncIterator] () {
+ assert(!this[kBodyUsed], 'disturbed')
+ this[kBodyUsed] = true
+ yield * this[kBody]
+ }
+}
- // 9. Set request's client to settings.
- initRequest.client = environmentSettingsObject.settingsObject
+function wrapRequestBody (body) {
+ if (isStream(body)) {
+ // TODO (fix): Provide some way for the user to cache the file to e.g. /tmp
+ // so that it can be dispatched again?
+ // TODO (fix): Do we need 100-expect support to provide a way to do this properly?
+ if (bodyLength(body) === 0) {
+ body
+ .on('data', function () {
+ assert(false)
+ })
+ }
- // 10. User agents may set (`Accept`, `text/event-stream`) in request's header list.
- initRequest.headersList = [['accept', { name: 'accept', value: 'text/event-stream' }]]
+ if (typeof body.readableDidRead !== 'boolean') {
+ body[kBodyUsed] = false
+ EE.prototype.on.call(body, 'data', function () {
+ this[kBodyUsed] = true
+ })
+ }
- // 11. Set request's cache mode to "no-store".
- initRequest.cache = 'no-store'
+ return body
+ } else if (body && typeof body.pipeTo === 'function') {
+ // TODO (fix): We can't access ReadableStream internal state
+ // to determine whether or not it has been disturbed. This is just
+ // a workaround.
+ return new BodyAsyncIterable(body)
+ } else if (
+ body &&
+ typeof body !== 'string' &&
+ !ArrayBuffer.isView(body) &&
+ isIterable(body)
+ ) {
+ // TODO: Should we allow re-using iterable if !this.opts.idempotent
+ // or through some other flag?
+ return new BodyAsyncIterable(body)
+ } else {
+ return body
+ }
+}
- // 12. Set request's initiator type to "other".
- initRequest.initiator = 'other'
+function nop () {}
- initRequest.urlList = [new URL(this.#url)]
+function isStream (obj) {
+ return obj && typeof obj === 'object' && typeof obj.pipe === 'function' && typeof obj.on === 'function'
+}
- // 13. Set ev's request to request.
- this.#request = makeRequest(initRequest)
+// based on https://github.com/node-fetch/fetch-blob/blob/8ab587d34080de94140b54f07168451e7d0b655e/index.js#L229-L241 (MIT License)
+function isBlobLike (object) {
+ if (object === null) {
+ return false
+ } else if (object instanceof Blob) {
+ return true
+ } else if (typeof object !== 'object') {
+ return false
+ } else {
+ const sTag = object[Symbol.toStringTag]
- this.#connect()
+ return (sTag === 'Blob' || sTag === 'File') && (
+ ('stream' in object && typeof object.stream === 'function') ||
+ ('arrayBuffer' in object && typeof object.arrayBuffer === 'function')
+ )
}
+}
- /**
- * Returns the state of this EventSource object's connection. It can have the
- * values described below.
- * @returns {0|1|2}
- * @readonly
- */
- get readyState () {
- return this.#readyState
+function buildURL (url, queryParams) {
+ if (url.includes('?') || url.includes('#')) {
+ throw new Error('Query params cannot be passed when url already contains "?" or "#".')
}
- /**
- * Returns the URL providing the event stream.
- * @readonly
- * @returns {string}
- */
- get url () {
- return this.#url
- }
+ const stringified = stringify(queryParams)
- /**
- * Returns a boolean indicating whether the EventSource object was
- * instantiated with CORS credentials set (true), or not (false, the default).
- */
- get withCredentials () {
- return this.#withCredentials
+ if (stringified) {
+ url += '?' + stringified
}
- #connect () {
- if (this.#readyState === CLOSED) return
+ return url
+}
- this.#readyState = CONNECTING
+function isValidPort (port) {
+ const value = parseInt(port, 10)
+ return (
+ value === Number(port) &&
+ value >= 0 &&
+ value <= 65535
+ )
+}
- const fetchParams = {
- request: this.#request,
- dispatcher: this.#dispatcher
- }
+function isHttpOrHttpsPrefixed (value) {
+ return (
+ value != null &&
+ value[0] === 'h' &&
+ value[1] === 't' &&
+ value[2] === 't' &&
+ value[3] === 'p' &&
+ (
+ value[4] === ':' ||
+ (
+ value[4] === 's' &&
+ value[5] === ':'
+ )
+ )
+ )
+}
- // 14. Let processEventSourceEndOfBody given response res be the following step: if res is not a network error, then reestablish the connection.
- const processEventSourceEndOfBody = (response) => {
- if (isNetworkError(response)) {
- this.dispatchEvent(new Event('error'))
- this.close()
- }
+function parseURL (url) {
+ if (typeof url === 'string') {
+ url = new URL(url)
- this.#reconnect()
+ if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) {
+ throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')
}
- // 15. Fetch request, with processResponseEndOfBody set to processEventSourceEndOfBody...
- fetchParams.processResponseEndOfBody = processEventSourceEndOfBody
+ return url
+ }
- // and processResponse set to the following steps given response res:
- fetchParams.processResponse = (response) => {
- // 1. If res is an aborted network error, then fail the connection.
+ if (!url || typeof url !== 'object') {
+ throw new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.')
+ }
- if (isNetworkError(response)) {
- // 1. When a user agent is to fail the connection, the user agent
- // must queue a task which, if the readyState attribute is set to a
- // value other than CLOSED, sets the readyState attribute to CLOSED
- // and fires an event named error at the EventSource object. Once the
- // user agent has failed the connection, it does not attempt to
- // reconnect.
- if (response.aborted) {
- this.close()
- this.dispatchEvent(new Event('error'))
- return
- // 2. Otherwise, if res is a network error, then reestablish the
- // connection, unless the user agent knows that to be futile, in
- // which case the user agent may fail the connection.
- } else {
- this.#reconnect()
- return
- }
- }
+ if (!(url instanceof URL)) {
+ if (url.port != null && url.port !== '' && isValidPort(url.port) === false) {
+ throw new InvalidArgumentError('Invalid URL: port must be a valid integer or a string representation of an integer.')
+ }
- // 3. Otherwise, if res's status is not 200, or if res's `Content-Type`
- // is not `text/event-stream`, then fail the connection.
- const contentType = response.headersList.get('content-type', true)
- const mimeType = contentType !== null ? parseMIMEType(contentType) : 'failure'
- const contentTypeValid = mimeType !== 'failure' && mimeType.essence === 'text/event-stream'
- if (
- response.status !== 200 ||
- contentTypeValid === false
- ) {
- this.close()
- this.dispatchEvent(new Event('error'))
- return
- }
+ if (url.path != null && typeof url.path !== 'string') {
+ throw new InvalidArgumentError('Invalid URL path: the path must be a string or null/undefined.')
+ }
- // 4. Otherwise, announce the connection and interpret res's body
- // line by line.
+ if (url.pathname != null && typeof url.pathname !== 'string') {
+ throw new InvalidArgumentError('Invalid URL pathname: the pathname must be a string or null/undefined.')
+ }
- // When a user agent is to announce the connection, the user agent
- // must queue a task which, if the readyState attribute is set to a
- // value other than CLOSED, sets the readyState attribute to OPEN
- // and fires an event named open at the EventSource object.
- // @see https://html.spec.whatwg.org/multipage/server-sent-events.html#sse-processing-model
- this.#readyState = OPEN
- this.dispatchEvent(new Event('open'))
+ if (url.hostname != null && typeof url.hostname !== 'string') {
+ throw new InvalidArgumentError('Invalid URL hostname: the hostname must be a string or null/undefined.')
+ }
- // If redirected to a different origin, set the origin to the new origin.
- this.#state.origin = response.urlList[response.urlList.length - 1].origin
+ if (url.origin != null && typeof url.origin !== 'string') {
+ throw new InvalidArgumentError('Invalid URL origin: the origin must be a string or null/undefined.')
+ }
- const eventSourceStream = new EventSourceStream({
- eventSourceSettings: this.#state,
- push: (event) => {
- this.dispatchEvent(createFastMessageEvent(
- event.type,
- event.options
- ))
- }
- })
+ if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) {
+ throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')
+ }
- pipeline(response.body.stream,
- eventSourceStream,
- (error) => {
- if (
- error?.aborted === false
- ) {
- this.close()
- this.dispatchEvent(new Event('error'))
- }
- })
+ const port = url.port != null
+ ? url.port
+ : (url.protocol === 'https:' ? 443 : 80)
+ let origin = url.origin != null
+ ? url.origin
+ : `${url.protocol || ''}//${url.hostname || ''}:${port}`
+ let path = url.path != null
+ ? url.path
+ : `${url.pathname || ''}${url.search || ''}`
+
+ if (origin[origin.length - 1] === '/') {
+ origin = origin.slice(0, origin.length - 1)
}
- this.#controller = fetching(fetchParams)
+ if (path && path[0] !== '/') {
+ path = `/${path}`
+ }
+ // new URL(path, origin) is unsafe when `path` contains an absolute URL
+ // From https://developer.mozilla.org/en-US/docs/Web/API/URL/URL:
+ // If first parameter is a relative URL, second param is required, and will be used as the base URL.
+ // If first parameter is an absolute URL, a given second param will be ignored.
+ return new URL(`${origin}${path}`)
}
- /**
- * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#sse-processing-model
- * @returns {Promise}
- */
- async #reconnect () {
- // When a user agent is to reestablish the connection, the user agent must
- // run the following steps. These steps are run in parallel, not as part of
- // a task. (The tasks that it queues, of course, are run like normal tasks
- // and not themselves in parallel.)
+ if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) {
+ throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')
+ }
- // 1. Queue a task to run the following steps:
+ return url
+}
- // 1. If the readyState attribute is set to CLOSED, abort the task.
- if (this.#readyState === CLOSED) return
+function parseOrigin (url) {
+ url = parseURL(url)
- // 2. Set the readyState attribute to CONNECTING.
- this.#readyState = CONNECTING
+ if (url.pathname !== '/' || url.search || url.hash) {
+ throw new InvalidArgumentError('invalid url')
+ }
- // 3. Fire an event named error at the EventSource object.
- this.dispatchEvent(new Event('error'))
+ return url
+}
- // 2. Wait a delay equal to the reconnection time of the event source.
- await delay(this.#state.reconnectionTime)
+function getHostname (host) {
+ if (host[0] === '[') {
+ const idx = host.indexOf(']')
- // 5. Queue a task to run the following steps:
+ assert(idx !== -1)
+ return host.substring(1, idx)
+ }
- // 1. If the EventSource object's readyState attribute is not set to
- // CONNECTING, then return.
- if (this.#readyState !== CONNECTING) return
+ const idx = host.indexOf(':')
+ if (idx === -1) return host
- // 2. Let request be the EventSource object's request.
- // 3. If the EventSource object's last event ID string is not the empty
- // string, then:
- // 1. Let lastEventIDValue be the EventSource object's last event ID
- // string, encoded as UTF-8.
- // 2. Set (`Last-Event-ID`, lastEventIDValue) in request's header
- // list.
- if (this.#state.lastEventId.length) {
- this.#request.headersList.set('last-event-id', this.#state.lastEventId, true)
- }
+ return host.substring(0, idx)
+}
- // 4. Fetch request and process the response obtained in this fashion, if any, as described earlier in this section.
- this.#connect()
+// IP addresses are not valid server names per RFC6066
+// > Currently, the only server names supported are DNS hostnames
+function getServerName (host) {
+ if (!host) {
+ return null
}
- /**
- * Closes the connection, if any, and sets the readyState attribute to
- * CLOSED.
- */
- close () {
- webidl.brandCheck(this, EventSource)
+ assert(typeof host === 'string')
- if (this.#readyState === CLOSED) return
- this.#readyState = CLOSED
- this.#controller.abort()
- this.#request = null
+ const servername = getHostname(host)
+ if (net.isIP(servername)) {
+ return ''
}
- get onopen () {
- return this.#events.open
- }
+ return servername
+}
- set onopen (fn) {
- if (this.#events.open) {
- this.removeEventListener('open', this.#events.open)
- }
+function deepClone (obj) {
+ return JSON.parse(JSON.stringify(obj))
+}
- if (typeof fn === 'function') {
- this.#events.open = fn
- this.addEventListener('open', fn)
- } else {
- this.#events.open = null
- }
+function isAsyncIterable (obj) {
+ return !!(obj != null && typeof obj[Symbol.asyncIterator] === 'function')
+}
+
+function isIterable (obj) {
+ return !!(obj != null && (typeof obj[Symbol.iterator] === 'function' || typeof obj[Symbol.asyncIterator] === 'function'))
+}
+
+function bodyLength (body) {
+ if (body == null) {
+ return 0
+ } else if (isStream(body)) {
+ const state = body._readableState
+ return state && state.objectMode === false && state.ended === true && Number.isFinite(state.length)
+ ? state.length
+ : null
+ } else if (isBlobLike(body)) {
+ return body.size != null ? body.size : null
+ } else if (isBuffer(body)) {
+ return body.byteLength
}
- get onmessage () {
- return this.#events.message
+ return null
+}
+
+function isDestroyed (body) {
+ return body && !!(body.destroyed || body[kDestroyed] || (stream.isDestroyed?.(body)))
+}
+
+function destroy (stream, err) {
+ if (stream == null || !isStream(stream) || isDestroyed(stream)) {
+ return
}
- set onmessage (fn) {
- if (this.#events.message) {
- this.removeEventListener('message', this.#events.message)
+ if (typeof stream.destroy === 'function') {
+ if (Object.getPrototypeOf(stream).constructor === IncomingMessage) {
+ // See: https://github.com/nodejs/node/pull/38505/files
+ stream.socket = null
}
- if (typeof fn === 'function') {
- this.#events.message = fn
- this.addEventListener('message', fn)
- } else {
- this.#events.message = null
- }
+ stream.destroy(err)
+ } else if (err) {
+ queueMicrotask(() => {
+ stream.emit('error', err)
+ })
}
- get onerror () {
- return this.#events.error
+ if (stream.destroyed !== true) {
+ stream[kDestroyed] = true
}
+}
- set onerror (fn) {
- if (this.#events.error) {
- this.removeEventListener('error', this.#events.error)
- }
+const KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/
+function parseKeepAliveTimeout (val) {
+ const m = val.toString().match(KEEPALIVE_TIMEOUT_EXPR)
+ return m ? parseInt(m[1], 10) * 1000 : null
+}
- if (typeof fn === 'function') {
- this.#events.error = fn
- this.addEventListener('error', fn)
- } else {
- this.#events.error = null
- }
- }
+/**
+ * Retrieves a header name and returns its lowercase value.
+ * @param {string | Buffer} value Header name
+ * @returns {string}
+ */
+function headerNameToString (value) {
+ return typeof value === 'string'
+ ? headerNameLowerCasedRecord[value] ?? value.toLowerCase()
+ : tree.lookup(value) ?? value.toString('latin1').toLowerCase()
}
-const constantsPropertyDescriptors = {
- CONNECTING: {
- __proto__: null,
- configurable: false,
- enumerable: true,
- value: CONNECTING,
- writable: false
- },
- OPEN: {
- __proto__: null,
- configurable: false,
- enumerable: true,
- value: OPEN,
- writable: false
- },
- CLOSED: {
- __proto__: null,
- configurable: false,
- enumerable: true,
- value: CLOSED,
- writable: false
- }
+/**
+ * Receive the buffer as a string and return its lowercase value.
+ * @param {Buffer} value Header name
+ * @returns {string}
+ */
+function bufferToLowerCasedHeaderName (value) {
+ return tree.lookup(value) ?? value.toString('latin1').toLowerCase()
}
-Object.defineProperties(EventSource, constantsPropertyDescriptors)
-Object.defineProperties(EventSource.prototype, constantsPropertyDescriptors)
+/**
+ * @param {Record | (Buffer | string | (Buffer | string)[])[]} headers
+ * @param {Record} [obj]
+ * @returns {Record}
+ */
+function parseHeaders (headers, obj) {
+ if (obj === undefined) obj = {}
+ for (let i = 0; i < headers.length; i += 2) {
+ const key = headerNameToString(headers[i])
+ let val = obj[key]
-Object.defineProperties(EventSource.prototype, {
- close: kEnumerableProperty,
- onerror: kEnumerableProperty,
- onmessage: kEnumerableProperty,
- onopen: kEnumerableProperty,
- readyState: kEnumerableProperty,
- url: kEnumerableProperty,
- withCredentials: kEnumerableProperty
-})
+ if (val) {
+ if (typeof val === 'string') {
+ val = [val]
+ obj[key] = val
+ }
+ val.push(headers[i + 1].toString('utf8'))
+ } else {
+ const headersValue = headers[i + 1]
+ if (typeof headersValue === 'string') {
+ obj[key] = headersValue
+ } else {
+ obj[key] = Array.isArray(headersValue) ? headersValue.map(x => x.toString('utf8')) : headersValue.toString('utf8')
+ }
+ }
+ }
-webidl.converters.EventSourceInitDict = webidl.dictionaryConverter([
- {
- key: 'withCredentials',
- converter: webidl.converters.boolean,
- defaultValue: () => false
- },
- {
- key: 'dispatcher', // undici only
- converter: webidl.converters.any
+ // See https://github.com/nodejs/node/pull/46528
+ if ('content-length' in obj && 'content-disposition' in obj) {
+ obj['content-disposition'] = Buffer.from(obj['content-disposition']).toString('latin1')
}
-])
-module.exports = {
- EventSource,
- defaultReconnectionTime
+ return obj
}
+function parseRawHeaders (headers) {
+ const len = headers.length
+ const ret = new Array(len)
-/***/ }),
-
-/***/ 8794:
-/***/ ((module) => {
+ let hasContentLength = false
+ let contentDispositionIdx = -1
+ let key
+ let val
+ let kLen = 0
+ for (let n = 0; n < headers.length; n += 2) {
+ key = headers[n]
+ val = headers[n + 1]
+ typeof key !== 'string' && (key = key.toString())
+ typeof val !== 'string' && (val = val.toString('utf8'))
-/**
- * Checks if the given value is a valid LastEventId.
- * @param {string} value
- * @returns {boolean}
- */
-function isValidLastEventId (value) {
- // LastEventId should not contain U+0000 NULL
- return value.indexOf('\u0000') === -1
-}
+ kLen = key.length
+ if (kLen === 14 && key[7] === '-' && (key === 'content-length' || key.toLowerCase() === 'content-length')) {
+ hasContentLength = true
+ } else if (kLen === 19 && key[7] === '-' && (key === 'content-disposition' || key.toLowerCase() === 'content-disposition')) {
+ contentDispositionIdx = n + 1
+ }
+ ret[n] = key
+ ret[n + 1] = val
+ }
-/**
- * Checks if the given value is a base 10 digit.
- * @param {string} value
- * @returns {boolean}
- */
-function isASCIINumber (value) {
- if (value.length === 0) return false
- for (let i = 0; i < value.length; i++) {
- if (value.charCodeAt(i) < 0x30 || value.charCodeAt(i) > 0x39) return false
+ // See https://github.com/nodejs/node/pull/46528
+ if (hasContentLength && contentDispositionIdx !== -1) {
+ ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString('latin1')
}
- return true
-}
-// https://github.com/nodejs/undici/issues/2664
-function delay (ms) {
- return new Promise((resolve) => {
- setTimeout(resolve, ms).unref()
- })
+ return ret
}
-module.exports = {
- isValidLastEventId,
- isASCIINumber,
- delay
+function isBuffer (buffer) {
+ // See, https://github.com/mcollina/undici/pull/319
+ return buffer instanceof Uint8Array || Buffer.isBuffer(buffer)
}
+function validateHandler (handler, method, upgrade) {
+ if (!handler || typeof handler !== 'object') {
+ throw new InvalidArgumentError('handler must be an object')
+ }
-/***/ }),
+ if (typeof handler.onConnect !== 'function') {
+ throw new InvalidArgumentError('invalid onConnect method')
+ }
-/***/ 3278:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ if (typeof handler.onError !== 'function') {
+ throw new InvalidArgumentError('invalid onError method')
+ }
+ if (typeof handler.onBodySent !== 'function' && handler.onBodySent !== undefined) {
+ throw new InvalidArgumentError('invalid onBodySent method')
+ }
+ if (upgrade || method === 'CONNECT') {
+ if (typeof handler.onUpgrade !== 'function') {
+ throw new InvalidArgumentError('invalid onUpgrade method')
+ }
+ } else {
+ if (typeof handler.onHeaders !== 'function') {
+ throw new InvalidArgumentError('invalid onHeaders method')
+ }
-const util = __nccwpck_require__(7375)
-const {
- ReadableStreamFrom,
- isBlobLike,
- isReadableStreamLike,
- readableStreamClose,
- createDeferredPromise,
- fullyReadBody,
- extractMimeType,
- utf8DecodeBytes
-} = __nccwpck_require__(7241)
-const { FormData } = __nccwpck_require__(6443)
-const { kState } = __nccwpck_require__(1944)
-const { webidl } = __nccwpck_require__(220)
-const { Blob } = __nccwpck_require__(4573)
-const assert = __nccwpck_require__(4589)
-const { isErrored, isDisturbed } = __nccwpck_require__(7075)
-const { isArrayBuffer } = __nccwpck_require__(3429)
-const { serializeAMimeType } = __nccwpck_require__(2121)
-const { multipartFormDataParser } = __nccwpck_require__(5779)
-let random
+ if (typeof handler.onData !== 'function') {
+ throw new InvalidArgumentError('invalid onData method')
+ }
-try {
- const crypto = __nccwpck_require__(7598)
- random = (max) => crypto.randomInt(0, max)
-} catch {
- random = (max) => Math.floor(Math.random(max))
+ if (typeof handler.onComplete !== 'function') {
+ throw new InvalidArgumentError('invalid onComplete method')
+ }
+ }
}
-const textEncoder = new TextEncoder()
-function noop () {}
+// A body is disturbed if it has been read from and it cannot
+// be re-used without losing state or data.
+function isDisturbed (body) {
+ // TODO (fix): Why is body[kBodyUsed] needed?
+ return !!(body && (stream.isDisturbed(body) || body[kBodyUsed]))
+}
-const hasFinalizationRegistry = globalThis.FinalizationRegistry && process.version.indexOf('v18') !== 0
-let streamRegistry
+function isErrored (body) {
+ return !!(body && stream.isErrored(body))
+}
-if (hasFinalizationRegistry) {
- streamRegistry = new FinalizationRegistry((weakRef) => {
- const stream = weakRef.deref()
- if (stream && !stream.locked && !isDisturbed(stream) && !isErrored(stream)) {
- stream.cancel('Response object has been garbage collected').catch(noop)
- }
- })
+function isReadable (body) {
+ return !!(body && stream.isReadable(body))
}
-// https://fetch.spec.whatwg.org/#concept-bodyinit-extract
-function extractBody (object, keepalive = false) {
- // 1. Let stream be null.
- let stream = null
+function getSocketInfo (socket) {
+ return {
+ localAddress: socket.localAddress,
+ localPort: socket.localPort,
+ remoteAddress: socket.remoteAddress,
+ remotePort: socket.remotePort,
+ remoteFamily: socket.remoteFamily,
+ timeout: socket.timeout,
+ bytesWritten: socket.bytesWritten,
+ bytesRead: socket.bytesRead
+ }
+}
- // 2. If object is a ReadableStream object, then set stream to object.
- if (object instanceof ReadableStream) {
- stream = object
- } else if (isBlobLike(object)) {
- // 3. Otherwise, if object is a Blob object, set stream to the
- // result of running object’s get stream.
- stream = object.stream()
- } else {
- // 4. Otherwise, set stream to a new ReadableStream object, and set
- // up stream with byte reading support.
- stream = new ReadableStream({
- async pull (controller) {
- const buffer = typeof source === 'string' ? textEncoder.encode(source) : source
+/** @type {globalThis['ReadableStream']} */
+function ReadableStreamFrom (iterable) {
+ // We cannot use ReadableStream.from here because it does not return a byte stream.
- if (buffer.byteLength) {
- controller.enqueue(buffer)
+ let iterator
+ return new ReadableStream(
+ {
+ async start () {
+ iterator = iterable[Symbol.asyncIterator]()
+ },
+ async pull (controller) {
+ const { done, value } = await iterator.next()
+ if (done) {
+ queueMicrotask(() => {
+ controller.close()
+ controller.byobRequest?.respond(0)
+ })
+ } else {
+ const buf = Buffer.isBuffer(value) ? value : Buffer.from(value)
+ if (buf.byteLength) {
+ controller.enqueue(new Uint8Array(buf))
+ }
}
-
- queueMicrotask(() => readableStreamClose(controller))
+ return controller.desiredSize > 0
+ },
+ async cancel (reason) {
+ await iterator.return()
},
- start () {},
type: 'bytes'
- })
- }
+ }
+ )
+}
- // 5. Assert: stream is a ReadableStream object.
- assert(isReadableStreamLike(stream))
+// The chunk should be a FormData instance and contains
+// all the required methods.
+function isFormDataLike (object) {
+ return (
+ object &&
+ typeof object === 'object' &&
+ typeof object.append === 'function' &&
+ typeof object.delete === 'function' &&
+ typeof object.get === 'function' &&
+ typeof object.getAll === 'function' &&
+ typeof object.has === 'function' &&
+ typeof object.set === 'function' &&
+ object[Symbol.toStringTag] === 'FormData'
+ )
+}
- // 6. Let action be null.
- let action = null
+function addAbortListener (signal, listener) {
+ if ('addEventListener' in signal) {
+ signal.addEventListener('abort', listener, { once: true })
+ return () => signal.removeEventListener('abort', listener)
+ }
+ signal.addListener('abort', listener)
+ return () => signal.removeListener('abort', listener)
+}
- // 7. Let source be null.
- let source = null
+const hasToWellFormed = typeof String.prototype.toWellFormed === 'function'
+const hasIsWellFormed = typeof String.prototype.isWellFormed === 'function'
- // 8. Let length be null.
- let length = null
+/**
+ * @param {string} val
+ */
+function toUSVString (val) {
+ return hasToWellFormed ? `${val}`.toWellFormed() : nodeUtil.toUSVString(val)
+}
- // 9. Let type be null.
- let type = null
+/**
+ * @param {string} val
+ */
+// TODO: move this to webidl
+function isUSVString (val) {
+ return hasIsWellFormed ? `${val}`.isWellFormed() : toUSVString(val) === `${val}`
+}
- // 10. Switch on object:
- if (typeof object === 'string') {
- // Set source to the UTF-8 encoding of object.
- // Note: setting source to a Uint8Array here breaks some mocking assumptions.
- source = object
+/**
+ * @see https://tools.ietf.org/html/rfc7230#section-3.2.6
+ * @param {number} c
+ */
+function isTokenCharCode (c) {
+ switch (c) {
+ case 0x22:
+ case 0x28:
+ case 0x29:
+ case 0x2c:
+ case 0x2f:
+ case 0x3a:
+ case 0x3b:
+ case 0x3c:
+ case 0x3d:
+ case 0x3e:
+ case 0x3f:
+ case 0x40:
+ case 0x5b:
+ case 0x5c:
+ case 0x5d:
+ case 0x7b:
+ case 0x7d:
+ // DQUOTE and "(),/:;<=>?@[\]{}"
+ return false
+ default:
+ // VCHAR %x21-7E
+ return c >= 0x21 && c <= 0x7e
+ }
+}
- // Set type to `text/plain;charset=UTF-8`.
- type = 'text/plain;charset=UTF-8'
- } else if (object instanceof URLSearchParams) {
- // URLSearchParams
+/**
+ * @param {string} characters
+ */
+function isValidHTTPToken (characters) {
+ if (characters.length === 0) {
+ return false
+ }
+ for (let i = 0; i < characters.length; ++i) {
+ if (!isTokenCharCode(characters.charCodeAt(i))) {
+ return false
+ }
+ }
+ return true
+}
- // spec says to run application/x-www-form-urlencoded on body.list
- // this is implemented in Node.js as apart of an URLSearchParams instance toString method
- // See: https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L490
- // and https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L1100
+// headerCharRegex have been lifted from
+// https://github.com/nodejs/node/blob/main/lib/_http_common.js
- // Set source to the result of running the application/x-www-form-urlencoded serializer with object’s list.
- source = object.toString()
+/**
+ * Matches if val contains an invalid field-vchar
+ * field-value = *( field-content / obs-fold )
+ * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
+ * field-vchar = VCHAR / obs-text
+ */
+const headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/
- // Set type to `application/x-www-form-urlencoded;charset=UTF-8`.
- type = 'application/x-www-form-urlencoded;charset=UTF-8'
- } else if (isArrayBuffer(object)) {
- // BufferSource/ArrayBuffer
+/**
+ * @param {string} characters
+ */
+function isValidHeaderValue (characters) {
+ return !headerCharRegex.test(characters)
+}
- // Set source to a copy of the bytes held by object.
- source = new Uint8Array(object.slice())
- } else if (ArrayBuffer.isView(object)) {
- // BufferSource/ArrayBufferView
+// Parsed accordingly to RFC 9110
+// https://www.rfc-editor.org/rfc/rfc9110#field.content-range
+function parseRangeHeader (range) {
+ if (range == null || range === '') return { start: 0, end: null, size: null }
- // Set source to a copy of the bytes held by object.
- source = new Uint8Array(object.buffer.slice(object.byteOffset, object.byteOffset + object.byteLength))
- } else if (util.isFormDataLike(object)) {
- const boundary = `----formdata-undici-0${`${random(1e11)}`.padStart(11, '0')}`
- const prefix = `--${boundary}\r\nContent-Disposition: form-data`
+ const m = range ? range.match(/^bytes (\d+)-(\d+)\/(\d+)?$/) : null
+ return m
+ ? {
+ start: parseInt(m[1]),
+ end: m[2] ? parseInt(m[2]) : null,
+ size: m[3] ? parseInt(m[3]) : null
+ }
+ : null
+}
- /*! formdata-polyfill. MIT License. Jimmy Wärting */
- const escape = (str) =>
- str.replace(/\n/g, '%0A').replace(/\r/g, '%0D').replace(/"/g, '%22')
- const normalizeLinefeeds = (value) => value.replace(/\r?\n|\r/g, '\r\n')
+function addListener (obj, name, listener) {
+ const listeners = (obj[kListeners] ??= [])
+ listeners.push([name, listener])
+ obj.on(name, listener)
+ return obj
+}
- // Set action to this step: run the multipart/form-data
- // encoding algorithm, with object’s entry list and UTF-8.
- // - This ensures that the body is immutable and can't be changed afterwords
- // - That the content-length is calculated in advance.
- // - And that all parts are pre-encoded and ready to be sent.
+function removeAllListeners (obj) {
+ for (const [name, listener] of obj[kListeners] ?? []) {
+ obj.removeListener(name, listener)
+ }
+ obj[kListeners] = null
+}
- const blobParts = []
- const rn = new Uint8Array([13, 10]) // '\r\n'
- length = 0
- let hasUnknownSizeValue = false
+function errorRequest (client, request, err) {
+ try {
+ request.onError(err)
+ assert(request.aborted)
+ } catch (err) {
+ client.emit('error', err)
+ }
+}
- for (const [name, value] of object) {
- if (typeof value === 'string') {
- const chunk = textEncoder.encode(prefix +
- `; name="${escape(normalizeLinefeeds(name))}"` +
- `\r\n\r\n${normalizeLinefeeds(value)}\r\n`)
- blobParts.push(chunk)
- length += chunk.byteLength
- } else {
- const chunk = textEncoder.encode(`${prefix}; name="${escape(normalizeLinefeeds(name))}"` +
- (value.name ? `; filename="${escape(value.name)}"` : '') + '\r\n' +
- `Content-Type: ${
- value.type || 'application/octet-stream'
- }\r\n\r\n`)
- blobParts.push(chunk, value, rn)
- if (typeof value.size === 'number') {
- length += chunk.byteLength + value.size + rn.byteLength
- } else {
- hasUnknownSizeValue = true
- }
- }
- }
+const kEnumerableProperty = Object.create(null)
+kEnumerableProperty.enumerable = true
- // CRLF is appended to the body to function with legacy servers and match other implementations.
- // https://github.com/curl/curl/blob/3434c6b46e682452973972e8313613dfa58cd690/lib/mime.c#L1029-L1030
- // https://github.com/form-data/form-data/issues/63
- const chunk = textEncoder.encode(`--${boundary}--\r\n`)
- blobParts.push(chunk)
- length += chunk.byteLength
- if (hasUnknownSizeValue) {
- length = null
+const normalizedMethodRecordsBase = {
+ delete: 'DELETE',
+ DELETE: 'DELETE',
+ get: 'GET',
+ GET: 'GET',
+ head: 'HEAD',
+ HEAD: 'HEAD',
+ options: 'OPTIONS',
+ OPTIONS: 'OPTIONS',
+ post: 'POST',
+ POST: 'POST',
+ put: 'PUT',
+ PUT: 'PUT'
+}
+
+const normalizedMethodRecords = {
+ ...normalizedMethodRecordsBase,
+ patch: 'patch',
+ PATCH: 'PATCH'
+}
+
+// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`.
+Object.setPrototypeOf(normalizedMethodRecordsBase, null)
+Object.setPrototypeOf(normalizedMethodRecords, null)
+
+module.exports = {
+ kEnumerableProperty,
+ nop,
+ isDisturbed,
+ isErrored,
+ isReadable,
+ toUSVString,
+ isUSVString,
+ isBlobLike,
+ parseOrigin,
+ parseURL,
+ getServerName,
+ isStream,
+ isIterable,
+ isAsyncIterable,
+ isDestroyed,
+ headerNameToString,
+ bufferToLowerCasedHeaderName,
+ addListener,
+ removeAllListeners,
+ errorRequest,
+ parseRawHeaders,
+ parseHeaders,
+ parseKeepAliveTimeout,
+ destroy,
+ bodyLength,
+ deepClone,
+ ReadableStreamFrom,
+ isBuffer,
+ validateHandler,
+ getSocketInfo,
+ isFormDataLike,
+ buildURL,
+ addAbortListener,
+ isValidHTTPToken,
+ isValidHeaderValue,
+ isTokenCharCode,
+ parseRangeHeader,
+ normalizedMethodRecordsBase,
+ normalizedMethodRecords,
+ isValidPort,
+ isHttpOrHttpsPrefixed,
+ nodeMajor,
+ nodeMinor,
+ safeHTTPMethods: ['GET', 'HEAD', 'OPTIONS', 'TRACE'],
+ wrapRequestBody
+}
+
+
+/***/ }),
+
+/***/ 7405:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const { InvalidArgumentError } = __nccwpck_require__(8707)
+const { kClients, kRunning, kClose, kDestroy, kDispatch, kInterceptors } = __nccwpck_require__(6443)
+const DispatcherBase = __nccwpck_require__(1841)
+const Pool = __nccwpck_require__(628)
+const Client = __nccwpck_require__(3701)
+const util = __nccwpck_require__(3440)
+const createRedirectInterceptor = __nccwpck_require__(5092)
+
+const kOnConnect = Symbol('onConnect')
+const kOnDisconnect = Symbol('onDisconnect')
+const kOnConnectionError = Symbol('onConnectionError')
+const kMaxRedirections = Symbol('maxRedirections')
+const kOnDrain = Symbol('onDrain')
+const kFactory = Symbol('factory')
+const kOptions = Symbol('options')
+
+function defaultFactory (origin, opts) {
+ return opts && opts.connections === 1
+ ? new Client(origin, opts)
+ : new Pool(origin, opts)
+}
+
+class Agent extends DispatcherBase {
+ constructor ({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) {
+ super()
+
+ if (typeof factory !== 'function') {
+ throw new InvalidArgumentError('factory must be a function.')
}
- // Set source to object.
- source = object
+ if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {
+ throw new InvalidArgumentError('connect must be a function or an object')
+ }
- action = async function * () {
- for (const part of blobParts) {
- if (part.stream) {
- yield * part.stream()
- } else {
- yield part
- }
- }
+ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) {
+ throw new InvalidArgumentError('maxRedirections must be a positive number')
}
- // Set type to `multipart/form-data; boundary=`,
- // followed by the multipart/form-data boundary string generated
- // by the multipart/form-data encoding algorithm.
- type = `multipart/form-data; boundary=${boundary}`
- } else if (isBlobLike(object)) {
- // Blob
+ if (connect && typeof connect !== 'function') {
+ connect = { ...connect }
+ }
- // Set source to object.
- source = object
+ this[kInterceptors] = options.interceptors?.Agent && Array.isArray(options.interceptors.Agent)
+ ? options.interceptors.Agent
+ : [createRedirectInterceptor({ maxRedirections })]
- // Set length to object’s size.
- length = object.size
+ this[kOptions] = { ...util.deepClone(options), connect }
+ this[kOptions].interceptors = options.interceptors
+ ? { ...options.interceptors }
+ : undefined
+ this[kMaxRedirections] = maxRedirections
+ this[kFactory] = factory
+ this[kClients] = new Map()
- // If object’s type attribute is not the empty byte sequence, set
- // type to its value.
- if (object.type) {
- type = object.type
+ this[kOnDrain] = (origin, targets) => {
+ this.emit('drain', origin, [this, ...targets])
}
- } else if (typeof object[Symbol.asyncIterator] === 'function') {
- // If keepalive is true, then throw a TypeError.
- if (keepalive) {
- throw new TypeError('keepalive')
+
+ this[kOnConnect] = (origin, targets) => {
+ this.emit('connect', origin, [this, ...targets])
}
- // If object is disturbed or locked, then throw a TypeError.
- if (util.isDisturbed(object) || object.locked) {
- throw new TypeError(
- 'Response body object should not be disturbed or locked'
- )
+ this[kOnDisconnect] = (origin, targets, err) => {
+ this.emit('disconnect', origin, [this, ...targets], err)
}
- stream =
- object instanceof ReadableStream ? object : ReadableStreamFrom(object)
+ this[kOnConnectionError] = (origin, targets, err) => {
+ this.emit('connectionError', origin, [this, ...targets], err)
+ }
}
- // 11. If source is a byte sequence, then set action to a
- // step that returns source and length to source’s length.
- if (typeof source === 'string' || util.isBuffer(source)) {
- length = Buffer.byteLength(source)
+ get [kRunning] () {
+ let ret = 0
+ for (const client of this[kClients].values()) {
+ ret += client[kRunning]
+ }
+ return ret
}
- // 12. If action is non-null, then run these steps in in parallel:
- if (action != null) {
- // Run action.
- let iterator
- stream = new ReadableStream({
- async start () {
- iterator = action(object)[Symbol.asyncIterator]()
- },
- async pull (controller) {
- const { value, done } = await iterator.next()
- if (done) {
- // When running action is done, close stream.
- queueMicrotask(() => {
- controller.close()
- controller.byobRequest?.respond(0)
- })
- } else {
- // Whenever one or more bytes are available and stream is not errored,
- // enqueue a Uint8Array wrapping an ArrayBuffer containing the available
- // bytes into stream.
- if (!isErrored(stream)) {
- const buffer = new Uint8Array(value)
- if (buffer.byteLength) {
- controller.enqueue(buffer)
- }
- }
- }
- return controller.desiredSize > 0
- },
- async cancel (reason) {
- await iterator.return()
- },
- type: 'bytes'
- })
- }
+ [kDispatch] (opts, handler) {
+ let key
+ if (opts.origin && (typeof opts.origin === 'string' || opts.origin instanceof URL)) {
+ key = String(opts.origin)
+ } else {
+ throw new InvalidArgumentError('opts.origin must be a non-empty string or URL.')
+ }
- // 13. Let body be a body whose stream is stream, source is source,
- // and length is length.
- const body = { stream, source, length }
+ let dispatcher = this[kClients].get(key)
- // 14. Return (body, type).
- return [body, type]
-}
+ if (!dispatcher) {
+ dispatcher = this[kFactory](opts.origin, this[kOptions])
+ .on('drain', this[kOnDrain])
+ .on('connect', this[kOnConnect])
+ .on('disconnect', this[kOnDisconnect])
+ .on('connectionError', this[kOnConnectionError])
-// https://fetch.spec.whatwg.org/#bodyinit-safely-extract
-function safelyExtractBody (object, keepalive = false) {
- // To safely extract a body and a `Content-Type` value from
- // a byte sequence or BodyInit object object, run these steps:
+ // This introduces a tiny memory leak, as dispatchers are never removed from the map.
+ // TODO(mcollina): remove te timer when the client/pool do not have any more
+ // active connections.
+ this[kClients].set(key, dispatcher)
+ }
- // 1. If object is a ReadableStream object, then:
- if (object instanceof ReadableStream) {
- // Assert: object is neither disturbed nor locked.
- // istanbul ignore next
- assert(!util.isDisturbed(object), 'The body has already been consumed.')
- // istanbul ignore next
- assert(!object.locked, 'The stream is locked.')
+ return dispatcher.dispatch(opts, handler)
}
- // 2. Return the results of extracting object.
- return extractBody(object, keepalive)
-}
-
-function cloneBody (instance, body) {
- // To clone a body body, run these steps:
-
- // https://fetch.spec.whatwg.org/#concept-body-clone
+ async [kClose] () {
+ const closePromises = []
+ for (const client of this[kClients].values()) {
+ closePromises.push(client.close())
+ }
+ this[kClients].clear()
- // 1. Let « out1, out2 » be the result of teeing body’s stream.
- const [out1, out2] = body.stream.tee()
+ await Promise.all(closePromises)
+ }
- // 2. Set body’s stream to out1.
- body.stream = out1
+ async [kDestroy] (err) {
+ const destroyPromises = []
+ for (const client of this[kClients].values()) {
+ destroyPromises.push(client.destroy(err))
+ }
+ this[kClients].clear()
- // 3. Return a body whose stream is out2 and other members are copied from body.
- return {
- stream: out2,
- length: body.length,
- source: body.source
+ await Promise.all(destroyPromises)
}
}
-function throwIfAborted (state) {
- if (state.aborted) {
- throw new DOMException('The operation was aborted.', 'AbortError')
- }
-}
+module.exports = Agent
-function bodyMixinMethods (instance) {
- const methods = {
- blob () {
- // The blob() method steps are to return the result of
- // running consume body with this and the following step
- // given a byte sequence bytes: return a Blob whose
- // contents are bytes and whose type attribute is this’s
- // MIME type.
- return consumeBody(this, (bytes) => {
- let mimeType = bodyMimeType(this)
- if (mimeType === null) {
- mimeType = ''
- } else if (mimeType) {
- mimeType = serializeAMimeType(mimeType)
- }
+/***/ }),
- // Return a Blob whose contents are bytes and type attribute
- // is mimeType.
- return new Blob([bytes], { type: mimeType })
- }, instance)
- },
+/***/ 837:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- arrayBuffer () {
- // The arrayBuffer() method steps are to return the result
- // of running consume body with this and the following step
- // given a byte sequence bytes: return a new ArrayBuffer
- // whose contents are bytes.
- return consumeBody(this, (bytes) => {
- return new Uint8Array(bytes).buffer
- }, instance)
- },
- text () {
- // The text() method steps are to return the result of running
- // consume body with this and UTF-8 decode.
- return consumeBody(this, utf8DecodeBytes, instance)
- },
- json () {
- // The json() method steps are to return the result of running
- // consume body with this and parse JSON from bytes.
- return consumeBody(this, parseJSONFromBytes, instance)
- },
+const {
+ BalancedPoolMissingUpstreamError,
+ InvalidArgumentError
+} = __nccwpck_require__(8707)
+const {
+ PoolBase,
+ kClients,
+ kNeedDrain,
+ kAddClient,
+ kRemoveClient,
+ kGetDispatcher
+} = __nccwpck_require__(2128)
+const Pool = __nccwpck_require__(628)
+const { kUrl, kInterceptors } = __nccwpck_require__(6443)
+const { parseOrigin } = __nccwpck_require__(3440)
+const kFactory = Symbol('factory')
- formData () {
- // The formData() method steps are to return the result of running
- // consume body with this and the following step given a byte sequence bytes:
- return consumeBody(this, (value) => {
- // 1. Let mimeType be the result of get the MIME type with this.
- const mimeType = bodyMimeType(this)
+const kOptions = Symbol('options')
+const kGreatestCommonDivisor = Symbol('kGreatestCommonDivisor')
+const kCurrentWeight = Symbol('kCurrentWeight')
+const kIndex = Symbol('kIndex')
+const kWeight = Symbol('kWeight')
+const kMaxWeightPerServer = Symbol('kMaxWeightPerServer')
+const kErrorPenalty = Symbol('kErrorPenalty')
- // 2. If mimeType is non-null, then switch on mimeType’s essence and run
- // the corresponding steps:
- if (mimeType !== null) {
- switch (mimeType.essence) {
- case 'multipart/form-data': {
- // 1. ... [long step]
- const parsed = multipartFormDataParser(value, mimeType)
+/**
+ * Calculate the greatest common divisor of two numbers by
+ * using the Euclidean algorithm.
+ *
+ * @param {number} a
+ * @param {number} b
+ * @returns {number}
+ */
+function getGreatestCommonDivisor (a, b) {
+ if (a === 0) return b
- // 2. If that fails for some reason, then throw a TypeError.
- if (parsed === 'failure') {
- throw new TypeError('Failed to parse body as FormData.')
- }
+ while (b !== 0) {
+ const t = b
+ b = a % b
+ a = t
+ }
+ return a
+}
- // 3. Return a new FormData object, appending each entry,
- // resulting from the parsing operation, to its entry list.
- const fd = new FormData()
- fd[kState] = parsed
+function defaultFactory (origin, opts) {
+ return new Pool(origin, opts)
+}
- return fd
- }
- case 'application/x-www-form-urlencoded': {
- // 1. Let entries be the result of parsing bytes.
- const entries = new URLSearchParams(value.toString())
+class BalancedPool extends PoolBase {
+ constructor (upstreams = [], { factory = defaultFactory, ...opts } = {}) {
+ super()
- // 2. If entries is failure, then throw a TypeError.
+ this[kOptions] = opts
+ this[kIndex] = -1
+ this[kCurrentWeight] = 0
- // 3. Return a new FormData object whose entry list is entries.
- const fd = new FormData()
+ this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100
+ this[kErrorPenalty] = this[kOptions].errorPenalty || 15
- for (const [name, value] of entries) {
- fd.append(name, value)
- }
+ if (!Array.isArray(upstreams)) {
+ upstreams = [upstreams]
+ }
- return fd
- }
- }
- }
+ if (typeof factory !== 'function') {
+ throw new InvalidArgumentError('factory must be a function.')
+ }
- // 3. Throw a TypeError.
- throw new TypeError(
- 'Content-Type was not one of "multipart/form-data" or "application/x-www-form-urlencoded".'
- )
- }, instance)
- },
+ this[kInterceptors] = opts.interceptors?.BalancedPool && Array.isArray(opts.interceptors.BalancedPool)
+ ? opts.interceptors.BalancedPool
+ : []
+ this[kFactory] = factory
- bytes () {
- // The bytes() method steps are to return the result of running consume body
- // with this and the following step given a byte sequence bytes: return the
- // result of creating a Uint8Array from bytes in this’s relevant realm.
- return consumeBody(this, (bytes) => {
- return new Uint8Array(bytes)
- }, instance)
+ for (const upstream of upstreams) {
+ this.addUpstream(upstream)
}
+ this._updateBalancedPoolStats()
}
- return methods
-}
-
-function mixinBody (prototype) {
- Object.assign(prototype.prototype, bodyMixinMethods(prototype))
-}
-
-/**
- * @see https://fetch.spec.whatwg.org/#concept-body-consume-body
- * @param {Response|Request} object
- * @param {(value: unknown) => unknown} convertBytesToJSValue
- * @param {Response|Request} instance
- */
-async function consumeBody (object, convertBytesToJSValue, instance) {
- webidl.brandCheck(object, instance)
+ addUpstream (upstream) {
+ const upstreamOrigin = parseOrigin(upstream).origin
- // 1. If object is unusable, then return a promise rejected
- // with a TypeError.
- if (bodyUnusable(object)) {
- throw new TypeError('Body is unusable: Body has already been read')
- }
+ if (this[kClients].find((pool) => (
+ pool[kUrl].origin === upstreamOrigin &&
+ pool.closed !== true &&
+ pool.destroyed !== true
+ ))) {
+ return this
+ }
+ const pool = this[kFactory](upstreamOrigin, Object.assign({}, this[kOptions]))
- throwIfAborted(object[kState])
+ this[kAddClient](pool)
+ pool.on('connect', () => {
+ pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty])
+ })
- // 2. Let promise be a new promise.
- const promise = createDeferredPromise()
+ pool.on('connectionError', () => {
+ pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty])
+ this._updateBalancedPoolStats()
+ })
- // 3. Let errorSteps given error be to reject promise with error.
- const errorSteps = (error) => promise.reject(error)
+ pool.on('disconnect', (...args) => {
+ const err = args[2]
+ if (err && err.code === 'UND_ERR_SOCKET') {
+ // decrease the weight of the pool.
+ pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty])
+ this._updateBalancedPoolStats()
+ }
+ })
- // 4. Let successSteps given a byte sequence data be to resolve
- // promise with the result of running convertBytesToJSValue
- // with data. If that threw an exception, then run errorSteps
- // with that exception.
- const successSteps = (data) => {
- try {
- promise.resolve(convertBytesToJSValue(data))
- } catch (e) {
- errorSteps(e)
+ for (const client of this[kClients]) {
+ client[kWeight] = this[kMaxWeightPerServer]
}
- }
- // 5. If object’s body is null, then run successSteps with an
- // empty byte sequence.
- if (object[kState].body == null) {
- successSteps(Buffer.allocUnsafe(0))
- return promise.promise
- }
+ this._updateBalancedPoolStats()
- // 6. Otherwise, fully read object’s body given successSteps,
- // errorSteps, and object’s relevant global object.
- await fullyReadBody(object[kState].body, successSteps, errorSteps)
+ return this
+ }
- // 7. Return promise.
- return promise.promise
-}
+ _updateBalancedPoolStats () {
+ let result = 0
+ for (let i = 0; i < this[kClients].length; i++) {
+ result = getGreatestCommonDivisor(this[kClients][i][kWeight], result)
+ }
-// https://fetch.spec.whatwg.org/#body-unusable
-function bodyUnusable (object) {
- const body = object[kState].body
+ this[kGreatestCommonDivisor] = result
+ }
- // An object including the Body interface mixin is
- // said to be unusable if its body is non-null and
- // its body’s stream is disturbed or locked.
- return body != null && (body.stream.locked || util.isDisturbed(body.stream))
-}
+ removeUpstream (upstream) {
+ const upstreamOrigin = parseOrigin(upstream).origin
-/**
- * @see https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value
- * @param {Uint8Array} bytes
- */
-function parseJSONFromBytes (bytes) {
- return JSON.parse(utf8DecodeBytes(bytes))
-}
+ const pool = this[kClients].find((pool) => (
+ pool[kUrl].origin === upstreamOrigin &&
+ pool.closed !== true &&
+ pool.destroyed !== true
+ ))
-/**
- * @see https://fetch.spec.whatwg.org/#concept-body-mime-type
- * @param {import('./response').Response|import('./request').Request} requestOrResponse
- */
-function bodyMimeType (requestOrResponse) {
- // 1. Let headers be null.
- // 2. If requestOrResponse is a Request object, then set headers to requestOrResponse’s request’s header list.
- // 3. Otherwise, set headers to requestOrResponse’s response’s header list.
- /** @type {import('./headers').HeadersList} */
- const headers = requestOrResponse[kState].headersList
+ if (pool) {
+ this[kRemoveClient](pool)
+ }
- // 4. Let mimeType be the result of extracting a MIME type from headers.
- const mimeType = extractMimeType(headers)
+ return this
+ }
- // 5. If mimeType is failure, then return null.
- if (mimeType === 'failure') {
- return null
+ get upstreams () {
+ return this[kClients]
+ .filter(dispatcher => dispatcher.closed !== true && dispatcher.destroyed !== true)
+ .map((p) => p[kUrl].origin)
}
- // 6. Return mimeType.
- return mimeType
-}
+ [kGetDispatcher] () {
+ // We validate that pools is greater than 0,
+ // otherwise we would have to wait until an upstream
+ // is added, which might never happen.
+ if (this[kClients].length === 0) {
+ throw new BalancedPoolMissingUpstreamError()
+ }
-module.exports = {
- extractBody,
- safelyExtractBody,
- cloneBody,
- mixinBody,
- streamRegistry,
- hasFinalizationRegistry,
- bodyUnusable
-}
+ const dispatcher = this[kClients].find(dispatcher => (
+ !dispatcher[kNeedDrain] &&
+ dispatcher.closed !== true &&
+ dispatcher.destroyed !== true
+ ))
+ if (!dispatcher) {
+ return
+ }
-/***/ }),
+ const allClientsBusy = this[kClients].map(pool => pool[kNeedDrain]).reduce((a, b) => a && b, true)
-/***/ 5336:
-/***/ ((module) => {
+ if (allClientsBusy) {
+ return
+ }
+ let counter = 0
+ let maxWeightIndex = this[kClients].findIndex(pool => !pool[kNeedDrain])
-const corsSafeListedMethods = /** @type {const} */ (['GET', 'HEAD', 'POST'])
-const corsSafeListedMethodsSet = new Set(corsSafeListedMethods)
+ while (counter++ < this[kClients].length) {
+ this[kIndex] = (this[kIndex] + 1) % this[kClients].length
+ const pool = this[kClients][this[kIndex]]
-const nullBodyStatus = /** @type {const} */ ([101, 204, 205, 304])
+ // find pool index with the largest weight
+ if (pool[kWeight] > this[kClients][maxWeightIndex][kWeight] && !pool[kNeedDrain]) {
+ maxWeightIndex = this[kIndex]
+ }
-const redirectStatus = /** @type {const} */ ([301, 302, 303, 307, 308])
-const redirectStatusSet = new Set(redirectStatus)
+ // decrease the current weight every `this[kClients].length`.
+ if (this[kIndex] === 0) {
+ // Set the current weight to the next lower weight.
+ this[kCurrentWeight] = this[kCurrentWeight] - this[kGreatestCommonDivisor]
-/**
- * @see https://fetch.spec.whatwg.org/#block-bad-port
- */
-const badPorts = /** @type {const} */ ([
- '1', '7', '9', '11', '13', '15', '17', '19', '20', '21', '22', '23', '25', '37', '42', '43', '53', '69', '77', '79',
- '87', '95', '101', '102', '103', '104', '109', '110', '111', '113', '115', '117', '119', '123', '135', '137',
- '139', '143', '161', '179', '389', '427', '465', '512', '513', '514', '515', '526', '530', '531', '532',
- '540', '548', '554', '556', '563', '587', '601', '636', '989', '990', '993', '995', '1719', '1720', '1723',
- '2049', '3659', '4045', '4190', '5060', '5061', '6000', '6566', '6665', '6666', '6667', '6668', '6669', '6679',
- '6697', '10080'
-])
-const badPortsSet = new Set(badPorts)
+ if (this[kCurrentWeight] <= 0) {
+ this[kCurrentWeight] = this[kMaxWeightPerServer]
+ }
+ }
+ if (pool[kWeight] >= this[kCurrentWeight] && (!pool[kNeedDrain])) {
+ return pool
+ }
+ }
-/**
- * @see https://w3c.github.io/webappsec-referrer-policy/#referrer-policies
- */
-const referrerPolicy = /** @type {const} */ ([
- '',
- 'no-referrer',
- 'no-referrer-when-downgrade',
- 'same-origin',
- 'origin',
- 'strict-origin',
- 'origin-when-cross-origin',
- 'strict-origin-when-cross-origin',
- 'unsafe-url'
-])
-const referrerPolicySet = new Set(referrerPolicy)
+ this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight]
+ this[kIndex] = maxWeightIndex
+ return this[kClients][maxWeightIndex]
+ }
+}
-const requestRedirect = /** @type {const} */ (['follow', 'manual', 'error'])
+module.exports = BalancedPool
-const safeMethods = /** @type {const} */ (['GET', 'HEAD', 'OPTIONS', 'TRACE'])
-const safeMethodsSet = new Set(safeMethods)
-const requestMode = /** @type {const} */ (['navigate', 'same-origin', 'no-cors', 'cors'])
+/***/ }),
-const requestCredentials = /** @type {const} */ (['omit', 'same-origin', 'include'])
+/***/ 637:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const requestCache = /** @type {const} */ ([
- 'default',
- 'no-store',
- 'reload',
- 'no-cache',
- 'force-cache',
- 'only-if-cached'
-])
-/**
- * @see https://fetch.spec.whatwg.org/#request-body-header-name
- */
-const requestBodyHeader = /** @type {const} */ ([
- 'content-encoding',
- 'content-language',
- 'content-location',
- 'content-type',
- // See https://github.com/nodejs/undici/issues/2021
- // 'Content-Length' is a forbidden header name, which is typically
- // removed in the Headers implementation. However, undici doesn't
- // filter out headers, so we add it here.
- 'content-length'
-])
-/**
- * @see https://fetch.spec.whatwg.org/#enumdef-requestduplex
- */
-const requestDuplex = /** @type {const} */ ([
- 'half'
-])
+/* global WebAssembly */
-/**
- * @see http://fetch.spec.whatwg.org/#forbidden-method
- */
-const forbiddenMethods = /** @type {const} */ (['CONNECT', 'TRACE', 'TRACK'])
-const forbiddenMethodsSet = new Set(forbiddenMethods)
+const assert = __nccwpck_require__(4589)
+const util = __nccwpck_require__(3440)
+const { channels } = __nccwpck_require__(2414)
+const timers = __nccwpck_require__(6603)
+const {
+ RequestContentLengthMismatchError,
+ ResponseContentLengthMismatchError,
+ RequestAbortedError,
+ HeadersTimeoutError,
+ HeadersOverflowError,
+ SocketError,
+ InformationalError,
+ BodyTimeoutError,
+ HTTPParserError,
+ ResponseExceededMaxSizeError
+} = __nccwpck_require__(8707)
+const {
+ kUrl,
+ kReset,
+ kClient,
+ kParser,
+ kBlocking,
+ kRunning,
+ kPending,
+ kSize,
+ kWriting,
+ kQueue,
+ kNoRef,
+ kKeepAliveDefaultTimeout,
+ kHostHeader,
+ kPendingIdx,
+ kRunningIdx,
+ kError,
+ kPipelining,
+ kSocket,
+ kKeepAliveTimeoutValue,
+ kMaxHeadersSize,
+ kKeepAliveMaxTimeout,
+ kKeepAliveTimeoutThreshold,
+ kHeadersTimeout,
+ kBodyTimeout,
+ kStrictContentLength,
+ kMaxRequests,
+ kCounter,
+ kMaxResponseSize,
+ kOnError,
+ kResume,
+ kHTTPContext
+} = __nccwpck_require__(6443)
-const subresource = /** @type {const} */ ([
- 'audio',
- 'audioworklet',
- 'font',
- 'image',
- 'manifest',
- 'paintworklet',
- 'script',
- 'style',
- 'track',
- 'video',
- 'xslt',
- ''
-])
-const subresourceSet = new Set(subresource)
+const constants = __nccwpck_require__(2824)
+const EMPTY_BUF = Buffer.alloc(0)
+const FastBuffer = Buffer[Symbol.species]
+const addListener = util.addListener
+const removeAllListeners = util.removeAllListeners
-module.exports = {
- subresource,
- forbiddenMethods,
- requestBodyHeader,
- referrerPolicy,
- requestRedirect,
- requestMode,
- requestCredentials,
- requestCache,
- redirectStatus,
- corsSafeListedMethods,
- nullBodyStatus,
- safeMethods,
- badPorts,
- requestDuplex,
- subresourceSet,
- badPortsSet,
- redirectStatusSet,
- corsSafeListedMethodsSet,
- safeMethodsSet,
- forbiddenMethodsSet,
- referrerPolicySet
-}
+let extractBody
+async function lazyllhttp () {
+ const llhttpWasmData = process.env.JEST_WORKER_ID ? __nccwpck_require__(3870) : undefined
-/***/ }),
+ let mod
+ try {
+ mod = await WebAssembly.compile(__nccwpck_require__(3434))
+ } catch (e) {
+ /* istanbul ignore next */
-/***/ 2121:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // We could check if the error was caused by the simd option not
+ // being enabled, but the occurring of this other error
+ // * https://github.com/emscripten-core/emscripten/issues/11495
+ // got me to remove that check to avoid breaking Node 12.
+ mod = await WebAssembly.compile(llhttpWasmData || __nccwpck_require__(3870))
+ }
+ return await WebAssembly.instantiate(mod, {
+ env: {
+ /* eslint-disable camelcase */
+ wasm_on_url: (p, at, len) => {
+ /* istanbul ignore next */
+ return 0
+ },
+ wasm_on_status: (p, at, len) => {
+ assert(currentParser.ptr === p)
+ const start = at - currentBufferPtr + currentBufferRef.byteOffset
+ return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
+ },
+ wasm_on_message_begin: (p) => {
+ assert(currentParser.ptr === p)
+ return currentParser.onMessageBegin() || 0
+ },
+ wasm_on_header_field: (p, at, len) => {
+ assert(currentParser.ptr === p)
+ const start = at - currentBufferPtr + currentBufferRef.byteOffset
+ return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
+ },
+ wasm_on_header_value: (p, at, len) => {
+ assert(currentParser.ptr === p)
+ const start = at - currentBufferPtr + currentBufferRef.byteOffset
+ return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
+ },
+ wasm_on_headers_complete: (p, statusCode, upgrade, shouldKeepAlive) => {
+ assert(currentParser.ptr === p)
+ return currentParser.onHeadersComplete(statusCode, Boolean(upgrade), Boolean(shouldKeepAlive)) || 0
+ },
+ wasm_on_body: (p, at, len) => {
+ assert(currentParser.ptr === p)
+ const start = at - currentBufferPtr + currentBufferRef.byteOffset
+ return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
+ },
+ wasm_on_message_complete: (p) => {
+ assert(currentParser.ptr === p)
+ return currentParser.onMessageComplete() || 0
+ }
-const assert = __nccwpck_require__(4589)
+ /* eslint-enable camelcase */
+ }
+ })
+}
-const encoder = new TextEncoder()
+let llhttpInstance = null
+let llhttpPromise = lazyllhttp()
+llhttpPromise.catch()
-/**
- * @see https://mimesniff.spec.whatwg.org/#http-token-code-point
- */
-const HTTP_TOKEN_CODEPOINTS = /^[!#$%&'*+\-.^_|~A-Za-z0-9]+$/
-const HTTP_WHITESPACE_REGEX = /[\u000A\u000D\u0009\u0020]/ // eslint-disable-line
-const ASCII_WHITESPACE_REPLACE_REGEX = /[\u0009\u000A\u000C\u000D\u0020]/g // eslint-disable-line
-/**
- * @see https://mimesniff.spec.whatwg.org/#http-quoted-string-token-code-point
- */
-const HTTP_QUOTED_STRING_TOKENS = /^[\u0009\u0020-\u007E\u0080-\u00FF]+$/ // eslint-disable-line
+let currentParser = null
+let currentBufferRef = null
+let currentBufferSize = 0
+let currentBufferPtr = null
-// https://fetch.spec.whatwg.org/#data-url-processor
-/** @param {URL} dataURL */
-function dataURLProcessor (dataURL) {
- // 1. Assert: dataURL’s scheme is "data".
- assert(dataURL.protocol === 'data:')
+const USE_NATIVE_TIMER = 0
+const USE_FAST_TIMER = 1
- // 2. Let input be the result of running the URL
- // serializer on dataURL with exclude fragment
- // set to true.
- let input = URLSerializer(dataURL, true)
+// Use fast timers for headers and body to take eventual event loop
+// latency into account.
+const TIMEOUT_HEADERS = 2 | USE_FAST_TIMER
+const TIMEOUT_BODY = 4 | USE_FAST_TIMER
- // 3. Remove the leading "data:" string from input.
- input = input.slice(5)
+// Use native timers to ignore event loop latency for keep-alive
+// handling.
+const TIMEOUT_KEEP_ALIVE = 8 | USE_NATIVE_TIMER
- // 4. Let position point at the start of input.
- const position = { position: 0 }
+class Parser {
+ constructor (client, socket, { exports }) {
+ assert(Number.isFinite(client[kMaxHeadersSize]) && client[kMaxHeadersSize] > 0)
- // 5. Let mimeType be the result of collecting a
- // sequence of code points that are not equal
- // to U+002C (,), given position.
- let mimeType = collectASequenceOfCodePointsFast(
- ',',
- input,
- position
- )
+ this.llhttp = exports
+ this.ptr = this.llhttp.llhttp_alloc(constants.TYPE.RESPONSE)
+ this.client = client
+ this.socket = socket
+ this.timeout = null
+ this.timeoutValue = null
+ this.timeoutType = null
+ this.statusCode = null
+ this.statusText = ''
+ this.upgrade = false
+ this.headers = []
+ this.headersSize = 0
+ this.headersMaxSize = client[kMaxHeadersSize]
+ this.shouldKeepAlive = false
+ this.paused = false
+ this.resume = this.resume.bind(this)
- // 6. Strip leading and trailing ASCII whitespace
- // from mimeType.
- // Undici implementation note: we need to store the
- // length because if the mimetype has spaces removed,
- // the wrong amount will be sliced from the input in
- // step #9
- const mimeTypeLength = mimeType.length
- mimeType = removeASCIIWhitespace(mimeType, true, true)
+ this.bytesRead = 0
- // 7. If position is past the end of input, then
- // return failure
- if (position.position >= input.length) {
- return 'failure'
- }
-
- // 8. Advance position by 1.
- position.position++
+ this.keepAlive = ''
+ this.contentLength = ''
+ this.connection = ''
+ this.maxResponseSize = client[kMaxResponseSize]
+ }
- // 9. Let encodedBody be the remainder of input.
- const encodedBody = input.slice(mimeTypeLength + 1)
+ setTimeout (delay, type) {
+ // If the existing timer and the new timer are of different timer type
+ // (fast or native) or have different delay, we need to clear the existing
+ // timer and set a new one.
+ if (
+ delay !== this.timeoutValue ||
+ (type & USE_FAST_TIMER) ^ (this.timeoutType & USE_FAST_TIMER)
+ ) {
+ // If a timeout is already set, clear it with clearTimeout of the fast
+ // timer implementation, as it can clear fast and native timers.
+ if (this.timeout) {
+ timers.clearTimeout(this.timeout)
+ this.timeout = null
+ }
- // 10. Let body be the percent-decoding of encodedBody.
- let body = stringPercentDecode(encodedBody)
+ if (delay) {
+ if (type & USE_FAST_TIMER) {
+ this.timeout = timers.setFastTimeout(onParserTimeout, delay, new WeakRef(this))
+ } else {
+ this.timeout = setTimeout(onParserTimeout, delay, new WeakRef(this))
+ this.timeout.unref()
+ }
+ }
- // 11. If mimeType ends with U+003B (;), followed by
- // zero or more U+0020 SPACE, followed by an ASCII
- // case-insensitive match for "base64", then:
- if (/;(\u0020){0,}base64$/i.test(mimeType)) {
- // 1. Let stringBody be the isomorphic decode of body.
- const stringBody = isomorphicDecode(body)
+ this.timeoutValue = delay
+ } else if (this.timeout) {
+ // istanbul ignore else: only for jest
+ if (this.timeout.refresh) {
+ this.timeout.refresh()
+ }
+ }
- // 2. Set body to the forgiving-base64 decode of
- // stringBody.
- body = forgivingBase64(stringBody)
+ this.timeoutType = type
+ }
- // 3. If body is failure, then return failure.
- if (body === 'failure') {
- return 'failure'
+ resume () {
+ if (this.socket.destroyed || !this.paused) {
+ return
}
- // 4. Remove the last 6 code points from mimeType.
- mimeType = mimeType.slice(0, -6)
+ assert(this.ptr != null)
+ assert(currentParser == null)
- // 5. Remove trailing U+0020 SPACE code points from mimeType,
- // if any.
- mimeType = mimeType.replace(/(\u0020)+$/, '')
+ this.llhttp.llhttp_resume(this.ptr)
- // 6. Remove the last U+003B (;) code point from mimeType.
- mimeType = mimeType.slice(0, -1)
- }
+ assert(this.timeoutType === TIMEOUT_BODY)
+ if (this.timeout) {
+ // istanbul ignore else: only for jest
+ if (this.timeout.refresh) {
+ this.timeout.refresh()
+ }
+ }
- // 12. If mimeType starts with U+003B (;), then prepend
- // "text/plain" to mimeType.
- if (mimeType.startsWith(';')) {
- mimeType = 'text/plain' + mimeType
+ this.paused = false
+ this.execute(this.socket.read() || EMPTY_BUF) // Flush parser.
+ this.readMore()
}
- // 13. Let mimeTypeRecord be the result of parsing
- // mimeType.
- let mimeTypeRecord = parseMIMEType(mimeType)
-
- // 14. If mimeTypeRecord is failure, then set
- // mimeTypeRecord to text/plain;charset=US-ASCII.
- if (mimeTypeRecord === 'failure') {
- mimeTypeRecord = parseMIMEType('text/plain;charset=US-ASCII')
+ readMore () {
+ while (!this.paused && this.ptr) {
+ const chunk = this.socket.read()
+ if (chunk === null) {
+ break
+ }
+ this.execute(chunk)
+ }
}
- // 15. Return a new data: URL struct whose MIME
- // type is mimeTypeRecord and body is body.
- // https://fetch.spec.whatwg.org/#data-url-struct
- return { mimeType: mimeTypeRecord, body }
-}
-
-// https://url.spec.whatwg.org/#concept-url-serializer
-/**
- * @param {URL} url
- * @param {boolean} excludeFragment
- */
-function URLSerializer (url, excludeFragment = false) {
- if (!excludeFragment) {
- return url.href
- }
+ execute (data) {
+ assert(this.ptr != null)
+ assert(currentParser == null)
+ assert(!this.paused)
- const href = url.href
- const hashLength = url.hash.length
+ const { socket, llhttp } = this
- const serialized = hashLength === 0 ? href : href.substring(0, href.length - hashLength)
+ if (data.length > currentBufferSize) {
+ if (currentBufferPtr) {
+ llhttp.free(currentBufferPtr)
+ }
+ currentBufferSize = Math.ceil(data.length / 4096) * 4096
+ currentBufferPtr = llhttp.malloc(currentBufferSize)
+ }
- if (!hashLength && href.endsWith('#')) {
- return serialized.slice(0, -1)
- }
+ new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(data)
- return serialized
-}
+ // Call `execute` on the wasm parser.
+ // We pass the `llhttp_parser` pointer address, the pointer address of buffer view data,
+ // and finally the length of bytes to parse.
+ // The return value is an error code or `constants.ERROR.OK`.
+ try {
+ let ret
-// https://infra.spec.whatwg.org/#collect-a-sequence-of-code-points
-/**
- * @param {(char: string) => boolean} condition
- * @param {string} input
- * @param {{ position: number }} position
- */
-function collectASequenceOfCodePoints (condition, input, position) {
- // 1. Let result be the empty string.
- let result = ''
+ try {
+ currentBufferRef = data
+ currentParser = this
+ ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, data.length)
+ /* eslint-disable-next-line no-useless-catch */
+ } catch (err) {
+ /* istanbul ignore next: difficult to make a test case for */
+ throw err
+ } finally {
+ currentParser = null
+ currentBufferRef = null
+ }
- // 2. While position doesn’t point past the end of input and the
- // code point at position within input meets the condition condition:
- while (position.position < input.length && condition(input[position.position])) {
- // 1. Append that code point to the end of result.
- result += input[position.position]
+ const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr
- // 2. Advance position by 1.
- position.position++
+ if (ret === constants.ERROR.PAUSED_UPGRADE) {
+ this.onUpgrade(data.slice(offset))
+ } else if (ret === constants.ERROR.PAUSED) {
+ this.paused = true
+ socket.unshift(data.slice(offset))
+ } else if (ret !== constants.ERROR.OK) {
+ const ptr = llhttp.llhttp_get_error_reason(this.ptr)
+ let message = ''
+ /* istanbul ignore else: difficult to make a test case for */
+ if (ptr) {
+ const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0)
+ message =
+ 'Response does not match the HTTP/1.1 protocol (' +
+ Buffer.from(llhttp.memory.buffer, ptr, len).toString() +
+ ')'
+ }
+ throw new HTTPParserError(message, constants.ERROR[ret], data.slice(offset))
+ }
+ } catch (err) {
+ util.destroy(socket, err)
+ }
}
- // 3. Return result.
- return result
-}
+ destroy () {
+ assert(this.ptr != null)
+ assert(currentParser == null)
-/**
- * A faster collectASequenceOfCodePoints that only works when comparing a single character.
- * @param {string} char
- * @param {string} input
- * @param {{ position: number }} position
- */
-function collectASequenceOfCodePointsFast (char, input, position) {
- const idx = input.indexOf(char, position.position)
- const start = position.position
+ this.llhttp.llhttp_free(this.ptr)
+ this.ptr = null
- if (idx === -1) {
- position.position = input.length
- return input.slice(start)
+ this.timeout && timers.clearTimeout(this.timeout)
+ this.timeout = null
+ this.timeoutValue = null
+ this.timeoutType = null
+
+ this.paused = false
}
- position.position = idx
- return input.slice(start, position.position)
-}
+ onStatus (buf) {
+ this.statusText = buf.toString()
+ }
-// https://url.spec.whatwg.org/#string-percent-decode
-/** @param {string} input */
-function stringPercentDecode (input) {
- // 1. Let bytes be the UTF-8 encoding of input.
- const bytes = encoder.encode(input)
+ onMessageBegin () {
+ const { socket, client } = this
- // 2. Return the percent-decoding of bytes.
- return percentDecode(bytes)
-}
+ /* istanbul ignore next: difficult to make a test case for */
+ if (socket.destroyed) {
+ return -1
+ }
-/**
- * @param {number} byte
- */
-function isHexCharByte (byte) {
- // 0-9 A-F a-f
- return (byte >= 0x30 && byte <= 0x39) || (byte >= 0x41 && byte <= 0x46) || (byte >= 0x61 && byte <= 0x66)
-}
+ const request = client[kQueue][client[kRunningIdx]]
+ if (!request) {
+ return -1
+ }
+ request.onResponseStarted()
+ }
-/**
- * @param {number} byte
- */
-function hexByteToNumber (byte) {
- return (
- // 0-9
- byte >= 0x30 && byte <= 0x39
- ? (byte - 48)
- // Convert to uppercase
- // ((byte & 0xDF) - 65) + 10
- : ((byte & 0xDF) - 55)
- )
-}
+ onHeaderField (buf) {
+ const len = this.headers.length
-// https://url.spec.whatwg.org/#percent-decode
-/** @param {Uint8Array} input */
-function percentDecode (input) {
- const length = input.length
- // 1. Let output be an empty byte sequence.
- /** @type {Uint8Array} */
- const output = new Uint8Array(length)
- let j = 0
- // 2. For each byte byte in input:
- for (let i = 0; i < length; ++i) {
- const byte = input[i]
+ if ((len & 1) === 0) {
+ this.headers.push(buf)
+ } else {
+ this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf])
+ }
- // 1. If byte is not 0x25 (%), then append byte to output.
- if (byte !== 0x25) {
- output[j++] = byte
+ this.trackHeader(buf.length)
+ }
- // 2. Otherwise, if byte is 0x25 (%) and the next two bytes
- // after byte in input are not in the ranges
- // 0x30 (0) to 0x39 (9), 0x41 (A) to 0x46 (F),
- // and 0x61 (a) to 0x66 (f), all inclusive, append byte
- // to output.
- } else if (
- byte === 0x25 &&
- !(isHexCharByte(input[i + 1]) && isHexCharByte(input[i + 2]))
- ) {
- output[j++] = 0x25
+ onHeaderValue (buf) {
+ let len = this.headers.length
- // 3. Otherwise:
+ if ((len & 1) === 1) {
+ this.headers.push(buf)
+ len += 1
} else {
- // 1. Let bytePoint be the two bytes after byte in input,
- // decoded, and then interpreted as hexadecimal number.
- // 2. Append a byte whose value is bytePoint to output.
- output[j++] = (hexByteToNumber(input[i + 1]) << 4) | hexByteToNumber(input[i + 2])
+ this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf])
+ }
- // 3. Skip the next two bytes in input.
- i += 2
+ const key = this.headers[len - 2]
+ if (key.length === 10) {
+ const headerName = util.bufferToLowerCasedHeaderName(key)
+ if (headerName === 'keep-alive') {
+ this.keepAlive += buf.toString()
+ } else if (headerName === 'connection') {
+ this.connection += buf.toString()
+ }
+ } else if (key.length === 14 && util.bufferToLowerCasedHeaderName(key) === 'content-length') {
+ this.contentLength += buf.toString()
}
+
+ this.trackHeader(buf.length)
}
- // 3. Return output.
- return length === j ? output : output.subarray(0, j)
-}
+ trackHeader (len) {
+ this.headersSize += len
+ if (this.headersSize >= this.headersMaxSize) {
+ util.destroy(this.socket, new HeadersOverflowError())
+ }
+ }
-// https://mimesniff.spec.whatwg.org/#parse-a-mime-type
-/** @param {string} input */
-function parseMIMEType (input) {
- // 1. Remove any leading and trailing HTTP whitespace
- // from input.
- input = removeHTTPWhitespace(input, true, true)
+ onUpgrade (head) {
+ const { upgrade, client, socket, headers, statusCode } = this
- // 2. Let position be a position variable for input,
- // initially pointing at the start of input.
- const position = { position: 0 }
+ assert(upgrade)
+ assert(client[kSocket] === socket)
+ assert(!socket.destroyed)
+ assert(!this.paused)
+ assert((headers.length & 1) === 0)
- // 3. Let type be the result of collecting a sequence
- // of code points that are not U+002F (/) from
- // input, given position.
- const type = collectASequenceOfCodePointsFast(
- '/',
- input,
- position
- )
+ const request = client[kQueue][client[kRunningIdx]]
+ assert(request)
+ assert(request.upgrade || request.method === 'CONNECT')
- // 4. If type is the empty string or does not solely
- // contain HTTP token code points, then return failure.
- // https://mimesniff.spec.whatwg.org/#http-token-code-point
- if (type.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(type)) {
- return 'failure'
- }
+ this.statusCode = null
+ this.statusText = ''
+ this.shouldKeepAlive = null
- // 5. If position is past the end of input, then return
- // failure
- if (position.position > input.length) {
- return 'failure'
- }
+ this.headers = []
+ this.headersSize = 0
- // 6. Advance position by 1. (This skips past U+002F (/).)
- position.position++
+ socket.unshift(head)
- // 7. Let subtype be the result of collecting a sequence of
- // code points that are not U+003B (;) from input, given
- // position.
- let subtype = collectASequenceOfCodePointsFast(
- ';',
- input,
- position
- )
+ socket[kParser].destroy()
+ socket[kParser] = null
- // 8. Remove any trailing HTTP whitespace from subtype.
- subtype = removeHTTPWhitespace(subtype, false, true)
+ socket[kClient] = null
+ socket[kError] = null
- // 9. If subtype is the empty string or does not solely
- // contain HTTP token code points, then return failure.
- if (subtype.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(subtype)) {
- return 'failure'
- }
+ removeAllListeners(socket)
- const typeLowercase = type.toLowerCase()
- const subtypeLowercase = subtype.toLowerCase()
+ client[kSocket] = null
+ client[kHTTPContext] = null // TODO (fix): This is hacky...
+ client[kQueue][client[kRunningIdx]++] = null
+ client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade'))
- // 10. Let mimeType be a new MIME type record whose type
- // is type, in ASCII lowercase, and subtype is subtype,
- // in ASCII lowercase.
- // https://mimesniff.spec.whatwg.org/#mime-type
- const mimeType = {
- type: typeLowercase,
- subtype: subtypeLowercase,
- /** @type {Map} */
- parameters: new Map(),
- // https://mimesniff.spec.whatwg.org/#mime-type-essence
- essence: `${typeLowercase}/${subtypeLowercase}`
+ try {
+ request.onUpgrade(statusCode, headers, socket)
+ } catch (err) {
+ util.destroy(socket, err)
+ }
+
+ client[kResume]()
}
- // 11. While position is not past the end of input:
- while (position.position < input.length) {
- // 1. Advance position by 1. (This skips past U+003B (;).)
- position.position++
+ onHeadersComplete (statusCode, upgrade, shouldKeepAlive) {
+ const { client, socket, headers, statusText } = this
- // 2. Collect a sequence of code points that are HTTP
- // whitespace from input given position.
- collectASequenceOfCodePoints(
- // https://fetch.spec.whatwg.org/#http-whitespace
- char => HTTP_WHITESPACE_REGEX.test(char),
- input,
- position
- )
+ /* istanbul ignore next: difficult to make a test case for */
+ if (socket.destroyed) {
+ return -1
+ }
- // 3. Let parameterName be the result of collecting a
- // sequence of code points that are not U+003B (;)
- // or U+003D (=) from input, given position.
- let parameterName = collectASequenceOfCodePoints(
- (char) => char !== ';' && char !== '=',
- input,
- position
- )
+ const request = client[kQueue][client[kRunningIdx]]
- // 4. Set parameterName to parameterName, in ASCII
- // lowercase.
- parameterName = parameterName.toLowerCase()
+ /* istanbul ignore next: difficult to make a test case for */
+ if (!request) {
+ return -1
+ }
- // 5. If position is not past the end of input, then:
- if (position.position < input.length) {
- // 1. If the code point at position within input is
- // U+003B (;), then continue.
- if (input[position.position] === ';') {
- continue
- }
+ assert(!this.upgrade)
+ assert(this.statusCode < 200)
- // 2. Advance position by 1. (This skips past U+003D (=).)
- position.position++
+ if (statusCode === 100) {
+ util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket)))
+ return -1
}
- // 6. If position is past the end of input, then break.
- if (position.position > input.length) {
- break
+ /* this can only happen if server is misbehaving */
+ if (upgrade && !request.upgrade) {
+ util.destroy(socket, new SocketError('bad upgrade', util.getSocketInfo(socket)))
+ return -1
}
- // 7. Let parameterValue be null.
- let parameterValue = null
+ assert(this.timeoutType === TIMEOUT_HEADERS)
- // 8. If the code point at position within input is
- // U+0022 ("), then:
- if (input[position.position] === '"') {
- // 1. Set parameterValue to the result of collecting
- // an HTTP quoted string from input, given position
- // and the extract-value flag.
- parameterValue = collectAnHTTPQuotedString(input, position, true)
+ this.statusCode = statusCode
+ this.shouldKeepAlive = (
+ shouldKeepAlive ||
+ // Override llhttp value which does not allow keepAlive for HEAD.
+ (request.method === 'HEAD' && !socket[kReset] && this.connection.toLowerCase() === 'keep-alive')
+ )
- // 2. Collect a sequence of code points that are not
- // U+003B (;) from input, given position.
- collectASequenceOfCodePointsFast(
- ';',
- input,
- position
- )
+ if (this.statusCode >= 200) {
+ const bodyTimeout = request.bodyTimeout != null
+ ? request.bodyTimeout
+ : client[kBodyTimeout]
+ this.setTimeout(bodyTimeout, TIMEOUT_BODY)
+ } else if (this.timeout) {
+ // istanbul ignore else: only for jest
+ if (this.timeout.refresh) {
+ this.timeout.refresh()
+ }
+ }
- // 9. Otherwise:
- } else {
- // 1. Set parameterValue to the result of collecting
- // a sequence of code points that are not U+003B (;)
- // from input, given position.
- parameterValue = collectASequenceOfCodePointsFast(
- ';',
- input,
- position
- )
-
- // 2. Remove any trailing HTTP whitespace from parameterValue.
- parameterValue = removeHTTPWhitespace(parameterValue, false, true)
-
- // 3. If parameterValue is the empty string, then continue.
- if (parameterValue.length === 0) {
- continue
- }
+ if (request.method === 'CONNECT') {
+ assert(client[kRunning] === 1)
+ this.upgrade = true
+ return 2
}
- // 10. If all of the following are true
- // - parameterName is not the empty string
- // - parameterName solely contains HTTP token code points
- // - parameterValue solely contains HTTP quoted-string token code points
- // - mimeType’s parameters[parameterName] does not exist
- // then set mimeType’s parameters[parameterName] to parameterValue.
- if (
- parameterName.length !== 0 &&
- HTTP_TOKEN_CODEPOINTS.test(parameterName) &&
- (parameterValue.length === 0 || HTTP_QUOTED_STRING_TOKENS.test(parameterValue)) &&
- !mimeType.parameters.has(parameterName)
- ) {
- mimeType.parameters.set(parameterName, parameterValue)
+ if (upgrade) {
+ assert(client[kRunning] === 1)
+ this.upgrade = true
+ return 2
}
- }
- // 12. Return mimeType.
- return mimeType
-}
+ assert((this.headers.length & 1) === 0)
+ this.headers = []
+ this.headersSize = 0
-// https://infra.spec.whatwg.org/#forgiving-base64-decode
-/** @param {string} data */
-function forgivingBase64 (data) {
- // 1. Remove all ASCII whitespace from data.
- data = data.replace(ASCII_WHITESPACE_REPLACE_REGEX, '') // eslint-disable-line
+ if (this.shouldKeepAlive && client[kPipelining]) {
+ const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null
- let dataLength = data.length
- // 2. If data’s code point length divides by 4 leaving
- // no remainder, then:
- if (dataLength % 4 === 0) {
- // 1. If data ends with one or two U+003D (=) code points,
- // then remove them from data.
- if (data.charCodeAt(dataLength - 1) === 0x003D) {
- --dataLength
- if (data.charCodeAt(dataLength - 1) === 0x003D) {
- --dataLength
+ if (keepAliveTimeout != null) {
+ const timeout = Math.min(
+ keepAliveTimeout - client[kKeepAliveTimeoutThreshold],
+ client[kKeepAliveMaxTimeout]
+ )
+ if (timeout <= 0) {
+ socket[kReset] = true
+ } else {
+ client[kKeepAliveTimeoutValue] = timeout
+ }
+ } else {
+ client[kKeepAliveTimeoutValue] = client[kKeepAliveDefaultTimeout]
}
+ } else {
+ // Stop more requests from being dispatched.
+ socket[kReset] = true
}
- }
-
- // 3. If data’s code point length divides by 4 leaving
- // a remainder of 1, then return failure.
- if (dataLength % 4 === 1) {
- return 'failure'
- }
- // 4. If data contains a code point that is not one of
- // U+002B (+)
- // U+002F (/)
- // ASCII alphanumeric
- // then return failure.
- if (/[^+/0-9A-Za-z]/.test(data.length === dataLength ? data : data.substring(0, dataLength))) {
- return 'failure'
- }
+ const pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false
- const buffer = Buffer.from(data, 'base64')
- return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength)
-}
+ if (request.aborted) {
+ return -1
+ }
-// https://fetch.spec.whatwg.org/#collect-an-http-quoted-string
-// tests: https://fetch.spec.whatwg.org/#example-http-quoted-string
-/**
- * @param {string} input
- * @param {{ position: number }} position
- * @param {boolean?} extractValue
- */
-function collectAnHTTPQuotedString (input, position, extractValue) {
- // 1. Let positionStart be position.
- const positionStart = position.position
+ if (request.method === 'HEAD') {
+ return 1
+ }
- // 2. Let value be the empty string.
- let value = ''
+ if (statusCode < 200) {
+ return 1
+ }
- // 3. Assert: the code point at position within input
- // is U+0022 (").
- assert(input[position.position] === '"')
+ if (socket[kBlocking]) {
+ socket[kBlocking] = false
+ client[kResume]()
+ }
- // 4. Advance position by 1.
- position.position++
+ return pause ? constants.ERROR.PAUSED : 0
+ }
- // 5. While true:
- while (true) {
- // 1. Append the result of collecting a sequence of code points
- // that are not U+0022 (") or U+005C (\) from input, given
- // position, to value.
- value += collectASequenceOfCodePoints(
- (char) => char !== '"' && char !== '\\',
- input,
- position
- )
+ onBody (buf) {
+ const { client, socket, statusCode, maxResponseSize } = this
- // 2. If position is past the end of input, then break.
- if (position.position >= input.length) {
- break
+ if (socket.destroyed) {
+ return -1
}
- // 3. Let quoteOrBackslash be the code point at position within
- // input.
- const quoteOrBackslash = input[position.position]
-
- // 4. Advance position by 1.
- position.position++
+ const request = client[kQueue][client[kRunningIdx]]
+ assert(request)
- // 5. If quoteOrBackslash is U+005C (\), then:
- if (quoteOrBackslash === '\\') {
- // 1. If position is past the end of input, then append
- // U+005C (\) to value and break.
- if (position.position >= input.length) {
- value += '\\'
- break
+ assert(this.timeoutType === TIMEOUT_BODY)
+ if (this.timeout) {
+ // istanbul ignore else: only for jest
+ if (this.timeout.refresh) {
+ this.timeout.refresh()
}
+ }
- // 2. Append the code point at position within input to value.
- value += input[position.position]
+ assert(statusCode >= 200)
- // 3. Advance position by 1.
- position.position++
+ if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) {
+ util.destroy(socket, new ResponseExceededMaxSizeError())
+ return -1
+ }
- // 6. Otherwise:
- } else {
- // 1. Assert: quoteOrBackslash is U+0022 (").
- assert(quoteOrBackslash === '"')
+ this.bytesRead += buf.length
- // 2. Break.
- break
+ if (request.onData(buf) === false) {
+ return constants.ERROR.PAUSED
}
}
- // 6. If the extract-value flag is set, then return value.
- if (extractValue) {
- return value
- }
-
- // 7. Return the code points from positionStart to position,
- // inclusive, within input.
- return input.slice(positionStart, position.position)
-}
-
-/**
- * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type
- */
-function serializeAMimeType (mimeType) {
- assert(mimeType !== 'failure')
- const { parameters, essence } = mimeType
+ onMessageComplete () {
+ const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this
- // 1. Let serialization be the concatenation of mimeType’s
- // type, U+002F (/), and mimeType’s subtype.
- let serialization = essence
+ if (socket.destroyed && (!statusCode || shouldKeepAlive)) {
+ return -1
+ }
- // 2. For each name → value of mimeType’s parameters:
- for (let [name, value] of parameters.entries()) {
- // 1. Append U+003B (;) to serialization.
- serialization += ';'
+ if (upgrade) {
+ return
+ }
- // 2. Append name to serialization.
- serialization += name
+ assert(statusCode >= 100)
+ assert((this.headers.length & 1) === 0)
- // 3. Append U+003D (=) to serialization.
- serialization += '='
+ const request = client[kQueue][client[kRunningIdx]]
+ assert(request)
- // 4. If value does not solely contain HTTP token code
- // points or value is the empty string, then:
- if (!HTTP_TOKEN_CODEPOINTS.test(value)) {
- // 1. Precede each occurrence of U+0022 (") or
- // U+005C (\) in value with U+005C (\).
- value = value.replace(/(\\|")/g, '\\$1')
+ this.statusCode = null
+ this.statusText = ''
+ this.bytesRead = 0
+ this.contentLength = ''
+ this.keepAlive = ''
+ this.connection = ''
- // 2. Prepend U+0022 (") to value.
- value = '"' + value
+ this.headers = []
+ this.headersSize = 0
- // 3. Append U+0022 (") to value.
- value += '"'
+ if (statusCode < 200) {
+ return
}
- // 5. Append value to serialization.
- serialization += value
- }
+ /* istanbul ignore next: should be handled by llhttp? */
+ if (request.method !== 'HEAD' && contentLength && bytesRead !== parseInt(contentLength, 10)) {
+ util.destroy(socket, new ResponseContentLengthMismatchError())
+ return -1
+ }
- // 3. Return serialization.
- return serialization
-}
+ request.onComplete(headers)
-/**
- * @see https://fetch.spec.whatwg.org/#http-whitespace
- * @param {number} char
- */
-function isHTTPWhiteSpace (char) {
- // "\r\n\t "
- return char === 0x00d || char === 0x00a || char === 0x009 || char === 0x020
-}
+ client[kQueue][client[kRunningIdx]++] = null
-/**
- * @see https://fetch.spec.whatwg.org/#http-whitespace
- * @param {string} str
- * @param {boolean} [leading=true]
- * @param {boolean} [trailing=true]
- */
-function removeHTTPWhitespace (str, leading = true, trailing = true) {
- return removeChars(str, leading, trailing, isHTTPWhiteSpace)
+ if (socket[kWriting]) {
+ assert(client[kRunning] === 0)
+ // Response completed before request.
+ util.destroy(socket, new InformationalError('reset'))
+ return constants.ERROR.PAUSED
+ } else if (!shouldKeepAlive) {
+ util.destroy(socket, new InformationalError('reset'))
+ return constants.ERROR.PAUSED
+ } else if (socket[kReset] && client[kRunning] === 0) {
+ // Destroy socket once all requests have completed.
+ // The request at the tail of the pipeline is the one
+ // that requested reset and no further requests should
+ // have been queued since then.
+ util.destroy(socket, new InformationalError('reset'))
+ return constants.ERROR.PAUSED
+ } else if (client[kPipelining] == null || client[kPipelining] === 1) {
+ // We must wait a full event loop cycle to reuse this socket to make sure
+ // that non-spec compliant servers are not closing the connection even if they
+ // said they won't.
+ setImmediate(() => client[kResume]())
+ } else {
+ client[kResume]()
+ }
+ }
}
-/**
- * @see https://infra.spec.whatwg.org/#ascii-whitespace
- * @param {number} char
- */
-function isASCIIWhitespace (char) {
- // "\r\n\t\f "
- return char === 0x00d || char === 0x00a || char === 0x009 || char === 0x00c || char === 0x020
-}
+function onParserTimeout (parser) {
+ const { socket, timeoutType, client, paused } = parser.deref()
-/**
- * @see https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace
- * @param {string} str
- * @param {boolean} [leading=true]
- * @param {boolean} [trailing=true]
- */
-function removeASCIIWhitespace (str, leading = true, trailing = true) {
- return removeChars(str, leading, trailing, isASCIIWhitespace)
+ /* istanbul ignore else */
+ if (timeoutType === TIMEOUT_HEADERS) {
+ if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) {
+ assert(!paused, 'cannot be paused while waiting for headers')
+ util.destroy(socket, new HeadersTimeoutError())
+ }
+ } else if (timeoutType === TIMEOUT_BODY) {
+ if (!paused) {
+ util.destroy(socket, new BodyTimeoutError())
+ }
+ } else if (timeoutType === TIMEOUT_KEEP_ALIVE) {
+ assert(client[kRunning] === 0 && client[kKeepAliveTimeoutValue])
+ util.destroy(socket, new InformationalError('socket idle timeout'))
+ }
}
-/**
- * @param {string} str
- * @param {boolean} leading
- * @param {boolean} trailing
- * @param {(charCode: number) => boolean} predicate
- * @returns
- */
-function removeChars (str, leading, trailing, predicate) {
- let lead = 0
- let trail = str.length - 1
+async function connectH1 (client, socket) {
+ client[kSocket] = socket
- if (leading) {
- while (lead < str.length && predicate(str.charCodeAt(lead))) lead++
+ if (!llhttpInstance) {
+ llhttpInstance = await llhttpPromise
+ llhttpPromise = null
}
- if (trailing) {
- while (trail > 0 && predicate(str.charCodeAt(trail))) trail--
- }
+ socket[kNoRef] = false
+ socket[kWriting] = false
+ socket[kReset] = false
+ socket[kBlocking] = false
+ socket[kParser] = new Parser(client, socket, llhttpInstance)
- return lead === 0 && trail === str.length - 1 ? str : str.slice(lead, trail + 1)
-}
+ addListener(socket, 'error', function (err) {
+ assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')
-/**
- * @see https://infra.spec.whatwg.org/#isomorphic-decode
- * @param {Uint8Array} input
- * @returns {string}
- */
-function isomorphicDecode (input) {
- // 1. To isomorphic decode a byte sequence input, return a string whose code point
- // length is equal to input’s length and whose code points have the same values
- // as the values of input’s bytes, in the same order.
- const length = input.length
- if ((2 << 15) - 1 > length) {
- return String.fromCharCode.apply(null, input)
- }
- let result = ''; let i = 0
- let addition = (2 << 15) - 1
- while (i < length) {
- if (i + addition > length) {
- addition = length - i
+ const parser = this[kParser]
+
+ // On Mac OS, we get an ECONNRESET even if there is a full body to be forwarded
+ // to the user.
+ if (err.code === 'ECONNRESET' && parser.statusCode && !parser.shouldKeepAlive) {
+ // We treat all incoming data so for as a valid response.
+ parser.onMessageComplete()
+ return
}
- result += String.fromCharCode.apply(null, input.subarray(i, i += addition))
- }
- return result
-}
-/**
- * @see https://mimesniff.spec.whatwg.org/#minimize-a-supported-mime-type
- * @param {Exclude, 'failure'>} mimeType
- */
-function minimizeSupportedMimeType (mimeType) {
- switch (mimeType.essence) {
- case 'application/ecmascript':
- case 'application/javascript':
- case 'application/x-ecmascript':
- case 'application/x-javascript':
- case 'text/ecmascript':
- case 'text/javascript':
- case 'text/javascript1.0':
- case 'text/javascript1.1':
- case 'text/javascript1.2':
- case 'text/javascript1.3':
- case 'text/javascript1.4':
- case 'text/javascript1.5':
- case 'text/jscript':
- case 'text/livescript':
- case 'text/x-ecmascript':
- case 'text/x-javascript':
- // 1. If mimeType is a JavaScript MIME type, then return "text/javascript".
- return 'text/javascript'
- case 'application/json':
- case 'text/json':
- // 2. If mimeType is a JSON MIME type, then return "application/json".
- return 'application/json'
- case 'image/svg+xml':
- // 3. If mimeType’s essence is "image/svg+xml", then return "image/svg+xml".
- return 'image/svg+xml'
- case 'text/xml':
- case 'application/xml':
- // 4. If mimeType is an XML MIME type, then return "application/xml".
- return 'application/xml'
- }
+ this[kError] = err
- // 2. If mimeType is a JSON MIME type, then return "application/json".
- if (mimeType.subtype.endsWith('+json')) {
- return 'application/json'
- }
+ this[kClient][kOnError](err)
+ })
+ addListener(socket, 'readable', function () {
+ const parser = this[kParser]
- // 4. If mimeType is an XML MIME type, then return "application/xml".
- if (mimeType.subtype.endsWith('+xml')) {
- return 'application/xml'
- }
+ if (parser) {
+ parser.readMore()
+ }
+ })
+ addListener(socket, 'end', function () {
+ const parser = this[kParser]
- // 5. If mimeType is supported by the user agent, then return mimeType’s essence.
- // Technically, node doesn't support any mimetypes.
+ if (parser.statusCode && !parser.shouldKeepAlive) {
+ // We treat all incoming data so far as a valid response.
+ parser.onMessageComplete()
+ return
+ }
- // 6. Return the empty string.
- return ''
-}
+ util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this)))
+ })
+ addListener(socket, 'close', function () {
+ const client = this[kClient]
+ const parser = this[kParser]
-module.exports = {
- dataURLProcessor,
- URLSerializer,
- collectASequenceOfCodePoints,
- collectASequenceOfCodePointsFast,
- stringPercentDecode,
- parseMIMEType,
- collectAnHTTPQuotedString,
- serializeAMimeType,
- removeChars,
- removeHTTPWhitespace,
- minimizeSupportedMimeType,
- HTTP_TOKEN_CODEPOINTS,
- isomorphicDecode
-}
+ if (parser) {
+ if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) {
+ // We treat all incoming data so far as a valid response.
+ parser.onMessageComplete()
+ }
+ this[kParser].destroy()
+ this[kParser] = null
+ }
-/***/ }),
+ const err = this[kError] || new SocketError('closed', util.getSocketInfo(this))
-/***/ 656:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ client[kSocket] = null
+ client[kHTTPContext] = null // TODO (fix): This is hacky...
+ if (client.destroyed) {
+ assert(client[kPending] === 0)
+ // Fail entire queue.
+ const requests = client[kQueue].splice(client[kRunningIdx])
+ for (let i = 0; i < requests.length; i++) {
+ const request = requests[i]
+ util.errorRequest(client, request, err)
+ }
+ } else if (client[kRunning] > 0 && err.code !== 'UND_ERR_INFO') {
+ // Fail head of pipeline.
+ const request = client[kQueue][client[kRunningIdx]]
+ client[kQueue][client[kRunningIdx]++] = null
-const { kConnected, kSize } = __nccwpck_require__(6130)
+ util.errorRequest(client, request, err)
+ }
-class CompatWeakRef {
- constructor (value) {
- this.value = value
- }
+ client[kPendingIdx] = client[kRunningIdx]
- deref () {
- return this.value[kConnected] === 0 && this.value[kSize] === 0
- ? undefined
- : this.value
- }
-}
+ assert(client[kRunning] === 0)
-class CompatFinalizer {
- constructor (finalizer) {
- this.finalizer = finalizer
- }
+ client.emit('disconnect', client[kUrl], [client], err)
- register (dispatcher, key) {
- if (dispatcher.on) {
- dispatcher.on('disconnect', () => {
- if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) {
- this.finalizer(key)
- }
- })
- }
- }
+ client[kResume]()
+ })
- unregister (key) {}
-}
+ let closed = false
+ socket.on('close', () => {
+ closed = true
+ })
-module.exports = function () {
- // FIXME: remove workaround when the Node bug is backported to v18
- // https://github.com/nodejs/node/issues/49344#issuecomment-1741776308
- if (process.env.NODE_V8_COVERAGE && process.version.startsWith('v18')) {
- process._rawDebug('Using compatibility WeakRef and FinalizationRegistry')
- return {
- WeakRef: CompatWeakRef,
- FinalizationRegistry: CompatFinalizer
- }
- }
- return { WeakRef, FinalizationRegistry }
-}
+ return {
+ version: 'h1',
+ defaultPipelining: 1,
+ write (...args) {
+ return writeH1(client, ...args)
+ },
+ resume () {
+ resumeH1(client)
+ },
+ destroy (err, callback) {
+ if (closed) {
+ queueMicrotask(callback)
+ } else {
+ socket.destroy(err).on('close', callback)
+ }
+ },
+ get destroyed () {
+ return socket.destroyed
+ },
+ busy (request) {
+ if (socket[kWriting] || socket[kReset] || socket[kBlocking]) {
+ return true
+ }
+ if (request) {
+ if (client[kRunning] > 0 && !request.idempotent) {
+ // Non-idempotent request cannot be retried.
+ // Ensure that no other requests are inflight and
+ // could cause failure.
+ return true
+ }
-/***/ }),
+ if (client[kRunning] > 0 && (request.upgrade || request.method === 'CONNECT')) {
+ // Don't dispatch an upgrade until all preceding requests have completed.
+ // A misbehaving server might upgrade the connection before all pipelined
+ // request has completed.
+ return true
+ }
-/***/ 2835:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ if (client[kRunning] > 0 && util.bodyLength(request.body) !== 0 &&
+ (util.isStream(request.body) || util.isAsyncIterable(request.body) || util.isFormDataLike(request.body))) {
+ // Request with stream or iterator body can error while other requests
+ // are inflight and indirectly error those as well.
+ // Ensure this doesn't happen by waiting for inflight
+ // to complete before dispatching.
+ // Request with stream or iterator body cannot be retried.
+ // Ensure that no other requests are inflight and
+ // could cause failure.
+ return true
+ }
+ }
+ return false
+ }
+ }
+}
-const { Blob, File } = __nccwpck_require__(4573)
-const { kState } = __nccwpck_require__(1944)
-const { webidl } = __nccwpck_require__(220)
+function resumeH1 (client) {
+ const socket = client[kSocket]
-// TODO(@KhafraDev): remove
-class FileLike {
- constructor (blobLike, fileName, options = {}) {
- // TODO: argument idl type check
+ if (socket && !socket.destroyed) {
+ if (client[kSize] === 0) {
+ if (!socket[kNoRef] && socket.unref) {
+ socket.unref()
+ socket[kNoRef] = true
+ }
+ } else if (socket[kNoRef] && socket.ref) {
+ socket.ref()
+ socket[kNoRef] = false
+ }
- // The File constructor is invoked with two or three parameters, depending
- // on whether the optional dictionary parameter is used. When the File()
- // constructor is invoked, user agents must run the following steps:
+ if (client[kSize] === 0) {
+ if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) {
+ socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE)
+ }
+ } else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) {
+ if (socket[kParser].timeoutType !== TIMEOUT_HEADERS) {
+ const request = client[kQueue][client[kRunningIdx]]
+ const headersTimeout = request.headersTimeout != null
+ ? request.headersTimeout
+ : client[kHeadersTimeout]
+ socket[kParser].setTimeout(headersTimeout, TIMEOUT_HEADERS)
+ }
+ }
+ }
+}
- // 1. Let bytes be the result of processing blob parts given fileBits and
- // options.
+// https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2
+function shouldSendContentLength (method) {
+ return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT'
+}
- // 2. Let n be the fileName argument to the constructor.
- const n = fileName
+function writeH1 (client, request) {
+ const { method, path, host, upgrade, blocking, reset } = request
- // 3. Process FilePropertyBag dictionary argument by running the following
- // substeps:
+ let { body, headers, contentLength } = request
- // 1. If the type member is provided and is not the empty string, let t
- // be set to the type dictionary member. If t contains any characters
- // outside the range U+0020 to U+007E, then set t to the empty string
- // and return from these substeps.
- // TODO
- const t = options.type
+ // https://tools.ietf.org/html/rfc7231#section-4.3.1
+ // https://tools.ietf.org/html/rfc7231#section-4.3.2
+ // https://tools.ietf.org/html/rfc7231#section-4.3.5
- // 2. Convert every character in t to ASCII lowercase.
- // TODO
+ // Sending a payload body on a request that does not
+ // expect it can cause undefined behavior on some
+ // servers and corrupt connection state. Do not
+ // re-use the connection for further requests.
- // 3. If the lastModified member is provided, let d be set to the
- // lastModified dictionary member. If it is not provided, set d to the
- // current date and time represented as the number of milliseconds since
- // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]).
- const d = options.lastModified ?? Date.now()
+ const expectsPayload = (
+ method === 'PUT' ||
+ method === 'POST' ||
+ method === 'PATCH' ||
+ method === 'QUERY' ||
+ method === 'PROPFIND' ||
+ method === 'PROPPATCH'
+ )
- // 4. Return a new File object F such that:
- // F refers to the bytes byte sequence.
- // F.size is set to the number of total bytes in bytes.
- // F.name is set to n.
- // F.type is set to t.
- // F.lastModified is set to d.
+ if (util.isFormDataLike(body)) {
+ if (!extractBody) {
+ extractBody = (__nccwpck_require__(4492).extractBody)
+ }
- this[kState] = {
- blobLike,
- name: n,
- type: t,
- lastModified: d
+ const [bodyStream, contentType] = extractBody(body)
+ if (request.contentType == null) {
+ headers.push('content-type', contentType)
}
+ body = bodyStream.stream
+ contentLength = bodyStream.length
+ } else if (util.isBlobLike(body) && request.contentType == null && body.type) {
+ headers.push('content-type', body.type)
}
- stream (...args) {
- webidl.brandCheck(this, FileLike)
-
- return this[kState].blobLike.stream(...args)
+ if (body && typeof body.read === 'function') {
+ // Try to read EOF in order to get length.
+ body.read(0)
}
- arrayBuffer (...args) {
- webidl.brandCheck(this, FileLike)
-
- return this[kState].blobLike.arrayBuffer(...args)
- }
+ const bodyLength = util.bodyLength(body)
- slice (...args) {
- webidl.brandCheck(this, FileLike)
+ contentLength = bodyLength ?? contentLength
- return this[kState].blobLike.slice(...args)
+ if (contentLength === null) {
+ contentLength = request.contentLength
}
- text (...args) {
- webidl.brandCheck(this, FileLike)
+ if (contentLength === 0 && !expectsPayload) {
+ // https://tools.ietf.org/html/rfc7230#section-3.3.2
+ // A user agent SHOULD NOT send a Content-Length header field when
+ // the request message does not contain a payload body and the method
+ // semantics do not anticipate such a body.
- return this[kState].blobLike.text(...args)
+ contentLength = null
}
- get size () {
- webidl.brandCheck(this, FileLike)
+ // https://github.com/nodejs/undici/issues/2046
+ // A user agent may send a Content-Length header with 0 value, this should be allowed.
+ if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength !== null && request.contentLength !== contentLength) {
+ if (client[kStrictContentLength]) {
+ util.errorRequest(client, request, new RequestContentLengthMismatchError())
+ return false
+ }
- return this[kState].blobLike.size
+ process.emitWarning(new RequestContentLengthMismatchError())
}
- get type () {
- webidl.brandCheck(this, FileLike)
+ const socket = client[kSocket]
- return this[kState].blobLike.type
- }
+ const abort = (err) => {
+ if (request.aborted || request.completed) {
+ return
+ }
- get name () {
- webidl.brandCheck(this, FileLike)
+ util.errorRequest(client, request, err || new RequestAbortedError())
- return this[kState].name
+ util.destroy(body)
+ util.destroy(socket, new InformationalError('aborted'))
}
- get lastModified () {
- webidl.brandCheck(this, FileLike)
-
- return this[kState].lastModified
+ try {
+ request.onConnect(abort)
+ } catch (err) {
+ util.errorRequest(client, request, err)
}
- get [Symbol.toStringTag] () {
- return 'File'
+ if (request.aborted) {
+ return false
}
-}
-webidl.converters.Blob = webidl.interfaceConverter(Blob)
+ if (method === 'HEAD') {
+ // https://github.com/mcollina/undici/issues/258
+ // Close after a HEAD request to interop with misbehaving servers
+ // that may send a body in the response.
-// If this function is moved to ./util.js, some tools (such as
-// rollup) will warn about circular dependencies. See:
-// https://github.com/nodejs/undici/issues/1629
-function isFileLike (object) {
- return (
- (object instanceof File) ||
- (
- object &&
- (typeof object.stream === 'function' ||
- typeof object.arrayBuffer === 'function') &&
- object[Symbol.toStringTag] === 'File'
- )
- )
-}
+ socket[kReset] = true
+ }
-module.exports = { FileLike, isFileLike }
+ if (upgrade || method === 'CONNECT') {
+ // On CONNECT or upgrade, block pipeline from dispatching further
+ // requests on this connection.
+ socket[kReset] = true
+ }
-/***/ }),
+ if (reset != null) {
+ socket[kReset] = reset
+ }
-/***/ 5779:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) {
+ socket[kReset] = true
+ }
+ if (blocking) {
+ socket[kBlocking] = true
+ }
+ let header = `${method} ${path} HTTP/1.1\r\n`
-const { isUSVString, bufferToLowerCasedHeaderName } = __nccwpck_require__(7375)
-const { utf8DecodeBytes } = __nccwpck_require__(7241)
-const { HTTP_TOKEN_CODEPOINTS, isomorphicDecode } = __nccwpck_require__(2121)
-const { isFileLike } = __nccwpck_require__(2835)
-const { makeEntry } = __nccwpck_require__(6443)
-const assert = __nccwpck_require__(4589)
-const { File: NodeFile } = __nccwpck_require__(4573)
+ if (typeof host === 'string') {
+ header += `host: ${host}\r\n`
+ } else {
+ header += client[kHostHeader]
+ }
-const File = globalThis.File ?? NodeFile
+ if (upgrade) {
+ header += `connection: upgrade\r\nupgrade: ${upgrade}\r\n`
+ } else if (client[kPipelining] && !socket[kReset]) {
+ header += 'connection: keep-alive\r\n'
+ } else {
+ header += 'connection: close\r\n'
+ }
-const formDataNameBuffer = Buffer.from('form-data; name="')
-const filenameBuffer = Buffer.from('; filename')
-const dd = Buffer.from('--')
-const ddcrlf = Buffer.from('--\r\n')
+ if (Array.isArray(headers)) {
+ for (let n = 0; n < headers.length; n += 2) {
+ const key = headers[n + 0]
+ const val = headers[n + 1]
-/**
- * @param {string} chars
- */
-function isAsciiString (chars) {
- for (let i = 0; i < chars.length; ++i) {
- if ((chars.charCodeAt(i) & ~0x7F) !== 0) {
- return false
+ if (Array.isArray(val)) {
+ for (let i = 0; i < val.length; i++) {
+ header += `${key}: ${val[i]}\r\n`
+ }
+ } else {
+ header += `${key}: ${val}\r\n`
+ }
}
}
- return true
-}
-/**
- * @see https://andreubotella.github.io/multipart-form-data/#multipart-form-data-boundary
- * @param {string} boundary
- */
-function validateBoundary (boundary) {
- const length = boundary.length
-
- // - its length is greater or equal to 27 and lesser or equal to 70, and
- if (length < 27 || length > 70) {
- return false
+ if (channels.sendHeaders.hasSubscribers) {
+ channels.sendHeaders.publish({ request, headers: header, socket })
}
- // - it is composed by bytes in the ranges 0x30 to 0x39, 0x41 to 0x5A, or
- // 0x61 to 0x7A, inclusive (ASCII alphanumeric), or which are 0x27 ('),
- // 0x2D (-) or 0x5F (_).
- for (let i = 0; i < length; ++i) {
- const cp = boundary.charCodeAt(i)
-
- if (!(
- (cp >= 0x30 && cp <= 0x39) ||
- (cp >= 0x41 && cp <= 0x5a) ||
- (cp >= 0x61 && cp <= 0x7a) ||
- cp === 0x27 ||
- cp === 0x2d ||
- cp === 0x5f
- )) {
- return false
+ /* istanbul ignore else: assertion */
+ if (!body || bodyLength === 0) {
+ writeBuffer(abort, null, client, request, socket, contentLength, header, expectsPayload)
+ } else if (util.isBuffer(body)) {
+ writeBuffer(abort, body, client, request, socket, contentLength, header, expectsPayload)
+ } else if (util.isBlobLike(body)) {
+ if (typeof body.stream === 'function') {
+ writeIterable(abort, body.stream(), client, request, socket, contentLength, header, expectsPayload)
+ } else {
+ writeBlob(abort, body, client, request, socket, contentLength, header, expectsPayload)
}
+ } else if (util.isStream(body)) {
+ writeStream(abort, body, client, request, socket, contentLength, header, expectsPayload)
+ } else if (util.isIterable(body)) {
+ writeIterable(abort, body, client, request, socket, contentLength, header, expectsPayload)
+ } else {
+ assert(false)
}
return true
}
-/**
- * @see https://andreubotella.github.io/multipart-form-data/#multipart-form-data-parser
- * @param {Buffer} input
- * @param {ReturnType} mimeType
- */
-function multipartFormDataParser (input, mimeType) {
- // 1. Assert: mimeType’s essence is "multipart/form-data".
- assert(mimeType !== 'failure' && mimeType.essence === 'multipart/form-data')
-
- const boundaryString = mimeType.parameters.get('boundary')
-
- // 2. If mimeType’s parameters["boundary"] does not exist, return failure.
- // Otherwise, let boundary be the result of UTF-8 decoding mimeType’s
- // parameters["boundary"].
- if (boundaryString === undefined) {
- return 'failure'
- }
+function writeStream (abort, body, client, request, socket, contentLength, header, expectsPayload) {
+ assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined')
- const boundary = Buffer.from(`--${boundaryString}`, 'utf8')
+ let finished = false
- // 3. Let entry list be an empty entry list.
- const entryList = []
+ const writer = new AsyncWriter({ abort, socket, request, contentLength, client, expectsPayload, header })
- // 4. Let position be a pointer to a byte in input, initially pointing at
- // the first byte.
- const position = { position: 0 }
+ const onData = function (chunk) {
+ if (finished) {
+ return
+ }
- // Note: undici addition, allows leading and trailing CRLFs.
- while (input[position.position] === 0x0d && input[position.position + 1] === 0x0a) {
- position.position += 2
+ try {
+ if (!writer.write(chunk) && this.pause) {
+ this.pause()
+ }
+ } catch (err) {
+ util.destroy(this, err)
+ }
}
+ const onDrain = function () {
+ if (finished) {
+ return
+ }
- let trailing = input.length
-
- while (input[trailing - 1] === 0x0a && input[trailing - 2] === 0x0d) {
- trailing -= 2
+ if (body.resume) {
+ body.resume()
+ }
}
+ const onClose = function () {
+ // 'close' might be emitted *before* 'error' for
+ // broken streams. Wait a tick to avoid this case.
+ queueMicrotask(() => {
+ // It's only safe to remove 'error' listener after
+ // 'close'.
+ body.removeListener('error', onFinished)
+ })
- if (trailing !== input.length) {
- input = input.subarray(0, trailing)
+ if (!finished) {
+ const err = new RequestAbortedError()
+ queueMicrotask(() => onFinished(err))
+ }
}
-
- // 5. While true:
- while (true) {
- // 5.1. If position points to a sequence of bytes starting with 0x2D 0x2D
- // (`--`) followed by boundary, advance position by 2 + the length of
- // boundary. Otherwise, return failure.
- // Note: boundary is padded with 2 dashes already, no need to add 2.
- if (input.subarray(position.position, position.position + boundary.length).equals(boundary)) {
- position.position += boundary.length
- } else {
- return 'failure'
+ const onFinished = function (err) {
+ if (finished) {
+ return
}
- // 5.2. If position points to the sequence of bytes 0x2D 0x2D 0x0D 0x0A
- // (`--` followed by CR LF) followed by the end of input, return entry list.
- // Note: a body does NOT need to end with CRLF. It can end with --.
- if (
- (position.position === input.length - 2 && bufferStartsWith(input, dd, position)) ||
- (position.position === input.length - 4 && bufferStartsWith(input, ddcrlf, position))
- ) {
- return entryList
- }
+ finished = true
- // 5.3. If position does not point to a sequence of bytes starting with 0x0D
- // 0x0A (CR LF), return failure.
- if (input[position.position] !== 0x0d || input[position.position + 1] !== 0x0a) {
- return 'failure'
- }
+ assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1))
- // 5.4. Advance position by 2. (This skips past the newline.)
- position.position += 2
+ socket
+ .off('drain', onDrain)
+ .off('error', onFinished)
- // 5.5. Let name, filename and contentType be the result of parsing
- // multipart/form-data headers on input and position, if the result
- // is not failure. Otherwise, return failure.
- const result = parseMultipartFormDataHeaders(input, position)
+ body
+ .removeListener('data', onData)
+ .removeListener('end', onFinished)
+ .removeListener('close', onClose)
- if (result === 'failure') {
- return 'failure'
+ if (!err) {
+ try {
+ writer.end()
+ } catch (er) {
+ err = er
+ }
}
- let { name, filename, contentType, encoding } = result
-
- // 5.6. Advance position by 2. (This skips past the empty line that marks
- // the end of the headers.)
- position.position += 2
+ writer.destroy(err)
- // 5.7. Let body be the empty byte sequence.
- let body
+ if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) {
+ util.destroy(body, err)
+ } else {
+ util.destroy(body)
+ }
+ }
- // 5.8. Body loop: While position is not past the end of input:
- // TODO: the steps here are completely wrong
- {
- const boundaryIndex = input.indexOf(boundary.subarray(2), position.position)
+ body
+ .on('data', onData)
+ .on('end', onFinished)
+ .on('error', onFinished)
+ .on('close', onClose)
- if (boundaryIndex === -1) {
- return 'failure'
- }
+ if (body.resume) {
+ body.resume()
+ }
- body = input.subarray(position.position, boundaryIndex - 4)
+ socket
+ .on('drain', onDrain)
+ .on('error', onFinished)
- position.position += body.length
+ if (body.errorEmitted ?? body.errored) {
+ setImmediate(() => onFinished(body.errored))
+ } else if (body.endEmitted ?? body.readableEnded) {
+ setImmediate(() => onFinished(null))
+ }
- // Note: position must be advanced by the body's length before being
- // decoded, otherwise the parsing will fail.
- if (encoding === 'base64') {
- body = Buffer.from(body.toString(), 'base64')
+ if (body.closeEmitted ?? body.closed) {
+ setImmediate(onClose)
+ }
+}
+
+function writeBuffer (abort, body, client, request, socket, contentLength, header, expectsPayload) {
+ try {
+ if (!body) {
+ if (contentLength === 0) {
+ socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1')
+ } else {
+ assert(contentLength === null, 'no body must not have content length')
+ socket.write(`${header}\r\n`, 'latin1')
}
- }
+ } else if (util.isBuffer(body)) {
+ assert(contentLength === body.byteLength, 'buffer body must have content length')
- // 5.9. If position does not point to a sequence of bytes starting with
- // 0x0D 0x0A (CR LF), return failure. Otherwise, advance position by 2.
- if (input[position.position] !== 0x0d || input[position.position + 1] !== 0x0a) {
- return 'failure'
- } else {
- position.position += 2
+ socket.cork()
+ socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
+ socket.write(body)
+ socket.uncork()
+ request.onBodySent(body)
+
+ if (!expectsPayload && request.reset !== false) {
+ socket[kReset] = true
+ }
}
+ request.onRequestSent()
- // 5.10. If filename is not null:
- let value
+ client[kResume]()
+ } catch (err) {
+ abort(err)
+ }
+}
- if (filename !== null) {
- // 5.10.1. If contentType is null, set contentType to "text/plain".
- contentType ??= 'text/plain'
+async function writeBlob (abort, body, client, request, socket, contentLength, header, expectsPayload) {
+ assert(contentLength === body.size, 'blob body must have content length')
- // 5.10.2. If contentType is not an ASCII string, set contentType to the empty string.
+ try {
+ if (contentLength != null && contentLength !== body.size) {
+ throw new RequestContentLengthMismatchError()
+ }
- // Note: `buffer.isAscii` can be used at zero-cost, but converting a string to a buffer is a high overhead.
- // Content-Type is a relatively small string, so it is faster to use `String#charCodeAt`.
- if (!isAsciiString(contentType)) {
- contentType = ''
- }
+ const buffer = Buffer.from(await body.arrayBuffer())
- // 5.10.3. Let value be a new File object with name filename, type contentType, and body body.
- value = new File([body], filename, { type: contentType })
- } else {
- // 5.11. Otherwise:
+ socket.cork()
+ socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
+ socket.write(buffer)
+ socket.uncork()
- // 5.11.1. Let value be the UTF-8 decoding without BOM of body.
- value = utf8DecodeBytes(Buffer.from(body))
- }
+ request.onBodySent(buffer)
+ request.onRequestSent()
- // 5.12. Assert: name is a scalar value string and value is either a scalar value string or a File object.
- assert(isUSVString(name))
- assert((typeof value === 'string' && isUSVString(value)) || isFileLike(value))
+ if (!expectsPayload && request.reset !== false) {
+ socket[kReset] = true
+ }
- // 5.13. Create an entry with name and value, and append it to entry list.
- entryList.push(makeEntry(name, value, filename))
+ client[kResume]()
+ } catch (err) {
+ abort(err)
}
}
-/**
- * @see https://andreubotella.github.io/multipart-form-data/#parse-multipart-form-data-headers
- * @param {Buffer} input
- * @param {{ position: number }} position
- */
-function parseMultipartFormDataHeaders (input, position) {
- // 1. Let name, filename and contentType be null.
- let name = null
- let filename = null
- let contentType = null
- let encoding = null
-
- // 2. While true:
- while (true) {
- // 2.1. If position points to a sequence of bytes starting with 0x0D 0x0A (CR LF):
- if (input[position.position] === 0x0d && input[position.position + 1] === 0x0a) {
- // 2.1.1. If name is null, return failure.
- if (name === null) {
- return 'failure'
- }
+async function writeIterable (abort, body, client, request, socket, contentLength, header, expectsPayload) {
+ assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined')
- // 2.1.2. Return name, filename and contentType.
- return { name, filename, contentType, encoding }
+ let callback = null
+ function onDrain () {
+ if (callback) {
+ const cb = callback
+ callback = null
+ cb()
}
+ }
- // 2.2. Let header name be the result of collecting a sequence of bytes that are
- // not 0x0A (LF), 0x0D (CR) or 0x3A (:), given position.
- let headerName = collectASequenceOfBytes(
- (char) => char !== 0x0a && char !== 0x0d && char !== 0x3a,
- input,
- position
- )
-
- // 2.3. Remove any HTTP tab or space bytes from the start or end of header name.
- headerName = removeChars(headerName, true, true, (char) => char === 0x9 || char === 0x20)
+ const waitForDrain = () => new Promise((resolve, reject) => {
+ assert(callback === null)
- // 2.4. If header name does not match the field-name token production, return failure.
- if (!HTTP_TOKEN_CODEPOINTS.test(headerName.toString())) {
- return 'failure'
+ if (socket[kError]) {
+ reject(socket[kError])
+ } else {
+ callback = resolve
}
+ })
- // 2.5. If the byte at position is not 0x3A (:), return failure.
- if (input[position.position] !== 0x3a) {
- return 'failure'
- }
+ socket
+ .on('close', onDrain)
+ .on('drain', onDrain)
- // 2.6. Advance position by 1.
- position.position++
+ const writer = new AsyncWriter({ abort, socket, request, contentLength, client, expectsPayload, header })
+ try {
+ // It's up to the user to somehow abort the async iterable.
+ for await (const chunk of body) {
+ if (socket[kError]) {
+ throw socket[kError]
+ }
- // 2.7. Collect a sequence of bytes that are HTTP tab or space bytes given position.
- // (Do nothing with those bytes.)
- collectASequenceOfBytes(
- (char) => char === 0x20 || char === 0x09,
- input,
- position
- )
+ if (!writer.write(chunk)) {
+ await waitForDrain()
+ }
+ }
- // 2.8. Byte-lowercase header name and switch on the result:
- switch (bufferToLowerCasedHeaderName(headerName)) {
- case 'content-disposition': {
- // 1. Set name and filename to null.
- name = filename = null
+ writer.end()
+ } catch (err) {
+ writer.destroy(err)
+ } finally {
+ socket
+ .off('close', onDrain)
+ .off('drain', onDrain)
+ }
+}
- // 2. If position does not point to a sequence of bytes starting with
- // `form-data; name="`, return failure.
- if (!bufferStartsWith(input, formDataNameBuffer, position)) {
- return 'failure'
- }
+class AsyncWriter {
+ constructor ({ abort, socket, request, contentLength, client, expectsPayload, header }) {
+ this.socket = socket
+ this.request = request
+ this.contentLength = contentLength
+ this.client = client
+ this.bytesWritten = 0
+ this.expectsPayload = expectsPayload
+ this.header = header
+ this.abort = abort
- // 3. Advance position so it points at the byte after the next 0x22 (")
- // byte (the one in the sequence of bytes matched above).
- position.position += 17
+ socket[kWriting] = true
+ }
- // 4. Set name to the result of parsing a multipart/form-data name given
- // input and position, if the result is not failure. Otherwise, return
- // failure.
- name = parseMultipartFormDataName(input, position)
+ write (chunk) {
+ const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this
- if (name === null) {
- return 'failure'
- }
+ if (socket[kError]) {
+ throw socket[kError]
+ }
- // 5. If position points to a sequence of bytes starting with `; filename="`:
- if (bufferStartsWith(input, filenameBuffer, position)) {
- // Note: undici also handles filename*
- let check = position.position + filenameBuffer.length
+ if (socket.destroyed) {
+ return false
+ }
- if (input[check] === 0x2a) {
- position.position += 1
- check += 1
- }
+ const len = Buffer.byteLength(chunk)
+ if (!len) {
+ return true
+ }
- if (input[check] !== 0x3d || input[check + 1] !== 0x22) { // ="
- return 'failure'
- }
+ // We should defer writing chunks.
+ if (contentLength !== null && bytesWritten + len > contentLength) {
+ if (client[kStrictContentLength]) {
+ throw new RequestContentLengthMismatchError()
+ }
- // 1. Advance position so it points at the byte after the next 0x22 (") byte
- // (the one in the sequence of bytes matched above).
- position.position += 12
+ process.emitWarning(new RequestContentLengthMismatchError())
+ }
- // 2. Set filename to the result of parsing a multipart/form-data name given
- // input and position, if the result is not failure. Otherwise, return failure.
- filename = parseMultipartFormDataName(input, position)
+ socket.cork()
- if (filename === null) {
- return 'failure'
- }
- }
+ if (bytesWritten === 0) {
+ if (!expectsPayload && request.reset !== false) {
+ socket[kReset] = true
+ }
- break
+ if (contentLength === null) {
+ socket.write(`${header}transfer-encoding: chunked\r\n`, 'latin1')
+ } else {
+ socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
}
- case 'content-type': {
- // 1. Let header value be the result of collecting a sequence of bytes that are
- // not 0x0A (LF) or 0x0D (CR), given position.
- let headerValue = collectASequenceOfBytes(
- (char) => char !== 0x0a && char !== 0x0d,
- input,
- position
- )
+ }
- // 2. Remove any HTTP tab or space bytes from the end of header value.
- headerValue = removeChars(headerValue, false, true, (char) => char === 0x9 || char === 0x20)
+ if (contentLength === null) {
+ socket.write(`\r\n${len.toString(16)}\r\n`, 'latin1')
+ }
- // 3. Set contentType to the isomorphic decoding of header value.
- contentType = isomorphicDecode(headerValue)
+ this.bytesWritten += len
- break
- }
- case 'content-transfer-encoding': {
- let headerValue = collectASequenceOfBytes(
- (char) => char !== 0x0a && char !== 0x0d,
- input,
- position
- )
+ const ret = socket.write(chunk)
- headerValue = removeChars(headerValue, false, true, (char) => char === 0x9 || char === 0x20)
+ socket.uncork()
- encoding = isomorphicDecode(headerValue)
+ request.onBodySent(chunk)
- break
- }
- default: {
- // Collect a sequence of bytes that are not 0x0A (LF) or 0x0D (CR), given position.
- // (Do nothing with those bytes.)
- collectASequenceOfBytes(
- (char) => char !== 0x0a && char !== 0x0d,
- input,
- position
- )
+ if (!ret) {
+ if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
+ // istanbul ignore else: only for jest
+ if (socket[kParser].timeout.refresh) {
+ socket[kParser].timeout.refresh()
+ }
}
}
- // 2.9. If position does not point to a sequence of bytes starting with 0x0D 0x0A
- // (CR LF), return failure. Otherwise, advance position by 2 (past the newline).
- if (input[position.position] !== 0x0d && input[position.position + 1] !== 0x0a) {
- return 'failure'
- } else {
- position.position += 2
- }
+ return ret
}
-}
-
-/**
- * @see https://andreubotella.github.io/multipart-form-data/#parse-a-multipart-form-data-name
- * @param {Buffer} input
- * @param {{ position: number }} position
- */
-function parseMultipartFormDataName (input, position) {
- // 1. Assert: The byte at (position - 1) is 0x22 (").
- assert(input[position.position - 1] === 0x22)
-
- // 2. Let name be the result of collecting a sequence of bytes that are not 0x0A (LF), 0x0D (CR) or 0x22 ("), given position.
- /** @type {string | Buffer} */
- let name = collectASequenceOfBytes(
- (char) => char !== 0x0a && char !== 0x0d && char !== 0x22,
- input,
- position
- )
- // 3. If the byte at position is not 0x22 ("), return failure. Otherwise, advance position by 1.
- if (input[position.position] !== 0x22) {
- return null // name could be 'failure'
- } else {
- position.position++
- }
+ end () {
+ const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this
+ request.onRequestSent()
- // 4. Replace any occurrence of the following subsequences in name with the given byte:
- // - `%0A`: 0x0A (LF)
- // - `%0D`: 0x0D (CR)
- // - `%22`: 0x22 (")
- name = new TextDecoder().decode(name)
- .replace(/%0A/ig, '\n')
- .replace(/%0D/ig, '\r')
- .replace(/%22/g, '"')
+ socket[kWriting] = false
- // 5. Return the UTF-8 decoding without BOM of name.
- return name
-}
+ if (socket[kError]) {
+ throw socket[kError]
+ }
-/**
- * @param {(char: number) => boolean} condition
- * @param {Buffer} input
- * @param {{ position: number }} position
- */
-function collectASequenceOfBytes (condition, input, position) {
- let start = position.position
+ if (socket.destroyed) {
+ return
+ }
- while (start < input.length && condition(input[start])) {
- ++start
- }
+ if (bytesWritten === 0) {
+ if (expectsPayload) {
+ // https://tools.ietf.org/html/rfc7230#section-3.3.2
+ // A user agent SHOULD send a Content-Length in a request message when
+ // no Transfer-Encoding is sent and the request method defines a meaning
+ // for an enclosed payload body.
- return input.subarray(position.position, (position.position = start))
-}
+ socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1')
+ } else {
+ socket.write(`${header}\r\n`, 'latin1')
+ }
+ } else if (contentLength === null) {
+ socket.write('\r\n0\r\n\r\n', 'latin1')
+ }
-/**
- * @param {Buffer} buf
- * @param {boolean} leading
- * @param {boolean} trailing
- * @param {(charCode: number) => boolean} predicate
- * @returns {Buffer}
- */
-function removeChars (buf, leading, trailing, predicate) {
- let lead = 0
- let trail = buf.length - 1
+ if (contentLength !== null && bytesWritten !== contentLength) {
+ if (client[kStrictContentLength]) {
+ throw new RequestContentLengthMismatchError()
+ } else {
+ process.emitWarning(new RequestContentLengthMismatchError())
+ }
+ }
- if (leading) {
- while (lead < buf.length && predicate(buf[lead])) lead++
- }
+ if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
+ // istanbul ignore else: only for jest
+ if (socket[kParser].timeout.refresh) {
+ socket[kParser].timeout.refresh()
+ }
+ }
- if (trailing) {
- while (trail > 0 && predicate(buf[trail])) trail--
+ client[kResume]()
}
- return lead === 0 && trail === buf.length - 1 ? buf : buf.subarray(lead, trail + 1)
-}
+ destroy (err) {
+ const { socket, client, abort } = this
-/**
- * Checks if {@param buffer} starts with {@param start}
- * @param {Buffer} buffer
- * @param {Buffer} start
- * @param {{ position: number }} position
- */
-function bufferStartsWith (buffer, start, position) {
- if (buffer.length < start.length) {
- return false
- }
+ socket[kWriting] = false
- for (let i = 0; i < start.length; i++) {
- if (start[i] !== buffer[position.position + i]) {
- return false
+ if (err) {
+ assert(client[kRunning] <= 1, 'pipeline should only contain this request')
+ abort(err)
}
}
-
- return true
}
-module.exports = {
- multipartFormDataParser,
- validateBoundary
-}
+module.exports = connectH1
/***/ }),
-/***/ 6443:
+/***/ 8788:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const { isBlobLike, iteratorMixin } = __nccwpck_require__(7241)
-const { kState } = __nccwpck_require__(1944)
-const { kEnumerableProperty } = __nccwpck_require__(7375)
-const { FileLike, isFileLike } = __nccwpck_require__(2835)
-const { webidl } = __nccwpck_require__(220)
-const { File: NativeFile } = __nccwpck_require__(4573)
-const nodeUtil = __nccwpck_require__(7975)
-
-/** @type {globalThis['File']} */
-const File = globalThis.File ?? NativeFile
-
-// https://xhr.spec.whatwg.org/#formdata
-class FormData {
- constructor (form) {
- webidl.util.markAsUncloneable(this)
+const assert = __nccwpck_require__(4589)
+const { pipeline } = __nccwpck_require__(7075)
+const util = __nccwpck_require__(3440)
+const {
+ RequestContentLengthMismatchError,
+ RequestAbortedError,
+ SocketError,
+ InformationalError
+} = __nccwpck_require__(8707)
+const {
+ kUrl,
+ kReset,
+ kClient,
+ kRunning,
+ kPending,
+ kQueue,
+ kPendingIdx,
+ kRunningIdx,
+ kError,
+ kSocket,
+ kStrictContentLength,
+ kOnError,
+ kMaxConcurrentStreams,
+ kHTTP2Session,
+ kResume,
+ kSize,
+ kHTTPContext
+} = __nccwpck_require__(6443)
- if (form !== undefined) {
- throw webidl.errors.conversionFailed({
- prefix: 'FormData constructor',
- argument: 'Argument 1',
- types: ['undefined']
- })
- }
+const kOpenStreams = Symbol('open streams')
- this[kState] = []
- }
+let extractBody
- append (name, value, filename = undefined) {
- webidl.brandCheck(this, FormData)
+// Experimental
+let h2ExperimentalWarned = false
- const prefix = 'FormData.append'
- webidl.argumentLengthCheck(arguments, 2, prefix)
+/** @type {import('http2')} */
+let http2
+try {
+ http2 = __nccwpck_require__(2467)
+} catch {
+ // @ts-ignore
+ http2 = { constants: {} }
+}
- if (arguments.length === 3 && !isBlobLike(value)) {
- throw new TypeError(
- "Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'"
- )
- }
-
- // 1. Let value be value if given; otherwise blobValue.
-
- name = webidl.converters.USVString(name, prefix, 'name')
- value = isBlobLike(value)
- ? webidl.converters.Blob(value, prefix, 'value', { strict: false })
- : webidl.converters.USVString(value, prefix, 'value')
- filename = arguments.length === 3
- ? webidl.converters.USVString(filename, prefix, 'filename')
- : undefined
+const {
+ constants: {
+ HTTP2_HEADER_AUTHORITY,
+ HTTP2_HEADER_METHOD,
+ HTTP2_HEADER_PATH,
+ HTTP2_HEADER_SCHEME,
+ HTTP2_HEADER_CONTENT_LENGTH,
+ HTTP2_HEADER_EXPECT,
+ HTTP2_HEADER_STATUS
+ }
+} = http2
- // 2. Let entry be the result of creating an entry with
- // name, value, and filename if given.
- const entry = makeEntry(name, value, filename)
+function parseH2Headers (headers) {
+ const result = []
- // 3. Append entry to this’s entry list.
- this[kState].push(entry)
+ for (const [name, value] of Object.entries(headers)) {
+ // h2 may concat the header value by array
+ // e.g. Set-Cookie
+ if (Array.isArray(value)) {
+ for (const subvalue of value) {
+ // we need to provide each header value of header name
+ // because the headers handler expect name-value pair
+ result.push(Buffer.from(name), Buffer.from(subvalue))
+ }
+ } else {
+ result.push(Buffer.from(name), Buffer.from(value))
+ }
}
- delete (name) {
- webidl.brandCheck(this, FormData)
-
- const prefix = 'FormData.delete'
- webidl.argumentLengthCheck(arguments, 1, prefix)
+ return result
+}
- name = webidl.converters.USVString(name, prefix, 'name')
+async function connectH2 (client, socket) {
+ client[kSocket] = socket
- // The delete(name) method steps are to remove all entries whose name
- // is name from this’s entry list.
- this[kState] = this[kState].filter(entry => entry.name !== name)
+ if (!h2ExperimentalWarned) {
+ h2ExperimentalWarned = true
+ process.emitWarning('H2 support is experimental, expect them to change at any time.', {
+ code: 'UNDICI-H2'
+ })
}
- get (name) {
- webidl.brandCheck(this, FormData)
+ const session = http2.connect(client[kUrl], {
+ createConnection: () => socket,
+ peerMaxConcurrentStreams: client[kMaxConcurrentStreams]
+ })
- const prefix = 'FormData.get'
- webidl.argumentLengthCheck(arguments, 1, prefix)
+ session[kOpenStreams] = 0
+ session[kClient] = client
+ session[kSocket] = socket
- name = webidl.converters.USVString(name, prefix, 'name')
+ util.addListener(session, 'error', onHttp2SessionError)
+ util.addListener(session, 'frameError', onHttp2FrameError)
+ util.addListener(session, 'end', onHttp2SessionEnd)
+ util.addListener(session, 'goaway', onHTTP2GoAway)
+ util.addListener(session, 'close', function () {
+ const { [kClient]: client } = this
+ const { [kSocket]: socket } = client
- // 1. If there is no entry whose name is name in this’s entry list,
- // then return null.
- const idx = this[kState].findIndex((entry) => entry.name === name)
- if (idx === -1) {
- return null
- }
+ const err = this[kSocket][kError] || this[kError] || new SocketError('closed', util.getSocketInfo(socket))
- // 2. Return the value of the first entry whose name is name from
- // this’s entry list.
- return this[kState][idx].value
- }
+ client[kHTTP2Session] = null
- getAll (name) {
- webidl.brandCheck(this, FormData)
+ if (client.destroyed) {
+ assert(client[kPending] === 0)
- const prefix = 'FormData.getAll'
- webidl.argumentLengthCheck(arguments, 1, prefix)
+ // Fail entire queue.
+ const requests = client[kQueue].splice(client[kRunningIdx])
+ for (let i = 0; i < requests.length; i++) {
+ const request = requests[i]
+ util.errorRequest(client, request, err)
+ }
+ }
+ })
- name = webidl.converters.USVString(name, prefix, 'name')
+ session.unref()
- // 1. If there is no entry whose name is name in this’s entry list,
- // then return the empty list.
- // 2. Return the values of all entries whose name is name, in order,
- // from this’s entry list.
- return this[kState]
- .filter((entry) => entry.name === name)
- .map((entry) => entry.value)
- }
+ client[kHTTP2Session] = session
+ socket[kHTTP2Session] = session
- has (name) {
- webidl.brandCheck(this, FormData)
+ util.addListener(socket, 'error', function (err) {
+ assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')
- const prefix = 'FormData.has'
- webidl.argumentLengthCheck(arguments, 1, prefix)
+ this[kError] = err
- name = webidl.converters.USVString(name, prefix, 'name')
+ this[kClient][kOnError](err)
+ })
- // The has(name) method steps are to return true if there is an entry
- // whose name is name in this’s entry list; otherwise false.
- return this[kState].findIndex((entry) => entry.name === name) !== -1
- }
+ util.addListener(socket, 'end', function () {
+ util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this)))
+ })
- set (name, value, filename = undefined) {
- webidl.brandCheck(this, FormData)
+ util.addListener(socket, 'close', function () {
+ const err = this[kError] || new SocketError('closed', util.getSocketInfo(this))
- const prefix = 'FormData.set'
- webidl.argumentLengthCheck(arguments, 2, prefix)
+ client[kSocket] = null
- if (arguments.length === 3 && !isBlobLike(value)) {
- throw new TypeError(
- "Failed to execute 'set' on 'FormData': parameter 2 is not of type 'Blob'"
- )
+ if (this[kHTTP2Session] != null) {
+ this[kHTTP2Session].destroy(err)
}
- // The set(name, value) and set(name, blobValue, filename) method steps
- // are:
+ client[kPendingIdx] = client[kRunningIdx]
- // 1. Let value be value if given; otherwise blobValue.
+ assert(client[kRunning] === 0)
- name = webidl.converters.USVString(name, prefix, 'name')
- value = isBlobLike(value)
- ? webidl.converters.Blob(value, prefix, 'name', { strict: false })
- : webidl.converters.USVString(value, prefix, 'name')
- filename = arguments.length === 3
- ? webidl.converters.USVString(filename, prefix, 'name')
- : undefined
+ client.emit('disconnect', client[kUrl], [client], err)
- // 2. Let entry be the result of creating an entry with name, value, and
- // filename if given.
- const entry = makeEntry(name, value, filename)
+ client[kResume]()
+ })
- // 3. If there are entries in this’s entry list whose name is name, then
- // replace the first such entry with entry and remove the others.
- const idx = this[kState].findIndex((entry) => entry.name === name)
- if (idx !== -1) {
- this[kState] = [
- ...this[kState].slice(0, idx),
- entry,
- ...this[kState].slice(idx + 1).filter((entry) => entry.name !== name)
- ]
- } else {
- // 4. Otherwise, append entry to this’s entry list.
- this[kState].push(entry)
- }
- }
+ let closed = false
+ socket.on('close', () => {
+ closed = true
+ })
- [nodeUtil.inspect.custom] (depth, options) {
- const state = this[kState].reduce((a, b) => {
- if (a[b.name]) {
- if (Array.isArray(a[b.name])) {
- a[b.name].push(b.value)
- } else {
- a[b.name] = [a[b.name], b.value]
- }
+ return {
+ version: 'h2',
+ defaultPipelining: Infinity,
+ write (...args) {
+ return writeH2(client, ...args)
+ },
+ resume () {
+ resumeH2(client)
+ },
+ destroy (err, callback) {
+ if (closed) {
+ queueMicrotask(callback)
} else {
- a[b.name] = b.value
+ // Destroying the socket will trigger the session close
+ socket.destroy(err).on('close', callback)
}
+ },
+ get destroyed () {
+ return socket.destroyed
+ },
+ busy () {
+ return false
+ }
+ }
+}
- return a
- }, { __proto__: null })
-
- options.depth ??= depth
- options.colors ??= true
-
- const output = nodeUtil.formatWithOptions(options, state)
+function resumeH2 (client) {
+ const socket = client[kSocket]
- // remove [Object null prototype]
- return `FormData ${output.slice(output.indexOf(']') + 2)}`
+ if (socket?.destroyed === false) {
+ if (client[kSize] === 0 && client[kMaxConcurrentStreams] === 0) {
+ socket.unref()
+ client[kHTTP2Session].unref()
+ } else {
+ socket.ref()
+ client[kHTTP2Session].ref()
+ }
}
}
-iteratorMixin('FormData', FormData, kState, 'name', 'value')
+function onHttp2SessionError (err) {
+ assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')
-Object.defineProperties(FormData.prototype, {
- append: kEnumerableProperty,
- delete: kEnumerableProperty,
- get: kEnumerableProperty,
- getAll: kEnumerableProperty,
- has: kEnumerableProperty,
- set: kEnumerableProperty,
- [Symbol.toStringTag]: {
- value: 'FormData',
- configurable: true
+ this[kSocket][kError] = err
+ this[kClient][kOnError](err)
+}
+
+function onHttp2FrameError (type, code, id) {
+ if (id === 0) {
+ const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`)
+ this[kSocket][kError] = err
+ this[kClient][kOnError](err)
}
-})
+}
+
+function onHttp2SessionEnd () {
+ const err = new SocketError('other side closed', util.getSocketInfo(this[kSocket]))
+ this.destroy(err)
+ util.destroy(this[kSocket], err)
+}
/**
- * @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#create-an-entry
- * @param {string} name
- * @param {string|Blob} value
- * @param {?string} filename
- * @returns
+ * This is the root cause of #3011
+ * We need to handle GOAWAY frames properly, and trigger the session close
+ * along with the socket right away
*/
-function makeEntry (name, value, filename) {
- // 1. Set name to the result of converting name into a scalar value string.
- // Note: This operation was done by the webidl converter USVString.
+function onHTTP2GoAway (code) {
+ // We cannot recover, so best to close the session and the socket
+ const err = this[kError] || new SocketError(`HTTP/2: "GOAWAY" frame received with code ${code}`, util.getSocketInfo(this))
+ const client = this[kClient]
- // 2. If value is a string, then set value to the result of converting
- // value into a scalar value string.
- if (typeof value === 'string') {
- // Note: This operation was done by the webidl converter USVString.
- } else {
- // 3. Otherwise:
+ client[kSocket] = null
+ client[kHTTPContext] = null
- // 1. If value is not a File object, then set value to a new File object,
- // representing the same bytes, whose name attribute value is "blob"
- if (!isFileLike(value)) {
- value = value instanceof Blob
- ? new File([value], 'blob', { type: value.type })
- : new FileLike(value, 'blob', { type: value.type })
- }
+ if (this[kHTTP2Session] != null) {
+ this[kHTTP2Session].destroy(err)
+ this[kHTTP2Session] = null
+ }
- // 2. If filename is given, then set value to a new File object,
- // representing the same bytes, whose name attribute is filename.
- if (filename !== undefined) {
- /** @type {FilePropertyBag} */
- const options = {
- type: value.type,
- lastModified: value.lastModified
- }
+ util.destroy(this[kSocket], err)
- value = value instanceof NativeFile
- ? new File([value], filename, options)
- : new FileLike(value, filename, options)
- }
+ // Fail head of pipeline.
+ if (client[kRunningIdx] < client[kQueue].length) {
+ const request = client[kQueue][client[kRunningIdx]]
+ client[kQueue][client[kRunningIdx]++] = null
+ util.errorRequest(client, request, err)
+ client[kPendingIdx] = client[kRunningIdx]
}
- // 4. Return an entry whose name is name and whose value is value.
- return { name, value }
+ assert(client[kRunning] === 0)
+
+ client.emit('disconnect', client[kUrl], [client], err)
+
+ client[kResume]()
}
-module.exports = { FormData, makeEntry }
+// https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2
+function shouldSendContentLength (method) {
+ return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT'
+}
+function writeH2 (client, request) {
+ const session = client[kHTTP2Session]
+ const { method, path, host, upgrade, expectContinue, signal, headers: reqHeaders } = request
+ let { body } = request
-/***/ }),
+ if (upgrade) {
+ util.errorRequest(client, request, new Error('Upgrade not supported for H2'))
+ return false
+ }
-/***/ 7038:
-/***/ ((module) => {
+ const headers = {}
+ for (let n = 0; n < reqHeaders.length; n += 2) {
+ const key = reqHeaders[n + 0]
+ const val = reqHeaders[n + 1]
+ if (Array.isArray(val)) {
+ for (let i = 0; i < val.length; i++) {
+ if (headers[key]) {
+ headers[key] += `,${val[i]}`
+ } else {
+ headers[key] = val[i]
+ }
+ }
+ } else {
+ headers[key] = val
+ }
+ }
+ /** @type {import('node:http2').ClientHttp2Stream} */
+ let stream
-// In case of breaking changes, increase the version
-// number to avoid conflicts.
-const globalOrigin = Symbol.for('undici.globalOrigin.1')
+ const { hostname, port } = client[kUrl]
-function getGlobalOrigin () {
- return globalThis[globalOrigin]
-}
+ headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ''}`
+ headers[HTTP2_HEADER_METHOD] = method
-function setGlobalOrigin (newOrigin) {
- if (newOrigin === undefined) {
- Object.defineProperty(globalThis, globalOrigin, {
- value: undefined,
- writable: true,
- enumerable: false,
- configurable: false
- })
+ const abort = (err) => {
+ if (request.aborted || request.completed) {
+ return
+ }
- return
- }
+ err = err || new RequestAbortedError()
- const parsedURL = new URL(newOrigin)
+ util.errorRequest(client, request, err)
- if (parsedURL.protocol !== 'http:' && parsedURL.protocol !== 'https:') {
- throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`)
+ if (stream != null) {
+ util.destroy(stream, err)
+ }
+
+ // We do not destroy the socket as we can continue using the session
+ // the stream get's destroyed and the session remains to create new streams
+ util.destroy(body, err)
+ client[kQueue][client[kRunningIdx]++] = null
+ client[kResume]()
}
- Object.defineProperty(globalThis, globalOrigin, {
- value: parsedURL,
- writable: true,
- enumerable: false,
- configurable: false
- })
-}
+ try {
+ // We are already connected, streams are pending.
+ // We can call on connect, and wait for abort
+ request.onConnect(abort)
+ } catch (err) {
+ util.errorRequest(client, request, err)
+ }
-module.exports = {
- getGlobalOrigin,
- setGlobalOrigin
-}
+ if (request.aborted) {
+ return false
+ }
+ if (method === 'CONNECT') {
+ session.ref()
+ // We are already connected, streams are pending, first request
+ // will create a new stream. We trigger a request to create the stream and wait until
+ // `ready` event is triggered
+ // We disabled endStream to allow the user to write to the stream
+ stream = session.request(headers, { endStream: false, signal })
-/***/ }),
+ if (stream.id && !stream.pending) {
+ request.onUpgrade(null, null, stream)
+ ++session[kOpenStreams]
+ client[kQueue][client[kRunningIdx]++] = null
+ } else {
+ stream.once('ready', () => {
+ request.onUpgrade(null, null, stream)
+ ++session[kOpenStreams]
+ client[kQueue][client[kRunningIdx]++] = null
+ })
+ }
-/***/ 1271:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ stream.once('close', () => {
+ session[kOpenStreams] -= 1
+ if (session[kOpenStreams] === 0) session.unref()
+ })
-// https://github.com/Ethan-Arrowood/undici-fetch
+ return true
+ }
+ // https://tools.ietf.org/html/rfc7540#section-8.3
+ // :path and :scheme headers must be omitted when sending CONNECT
+ headers[HTTP2_HEADER_PATH] = path
+ headers[HTTP2_HEADER_SCHEME] = 'https'
-const { kConstruct } = __nccwpck_require__(6130)
-const { kEnumerableProperty } = __nccwpck_require__(7375)
-const {
- iteratorMixin,
- isValidHeaderName,
- isValidHeaderValue
-} = __nccwpck_require__(7241)
-const { webidl } = __nccwpck_require__(220)
-const assert = __nccwpck_require__(4589)
-const util = __nccwpck_require__(7975)
+ // https://tools.ietf.org/html/rfc7231#section-4.3.1
+ // https://tools.ietf.org/html/rfc7231#section-4.3.2
+ // https://tools.ietf.org/html/rfc7231#section-4.3.5
-const kHeadersMap = Symbol('headers map')
-const kHeadersSortedMap = Symbol('headers map sorted')
+ // Sending a payload body on a request that does not
+ // expect it can cause undefined behavior on some
+ // servers and corrupt connection state. Do not
+ // re-use the connection for further requests.
-/**
- * @param {number} code
- */
-function isHTTPWhiteSpaceCharCode (code) {
- return code === 0x00a || code === 0x00d || code === 0x009 || code === 0x020
-}
+ const expectsPayload = (
+ method === 'PUT' ||
+ method === 'POST' ||
+ method === 'PATCH'
+ )
-/**
- * @see https://fetch.spec.whatwg.org/#concept-header-value-normalize
- * @param {string} potentialValue
- */
-function headerValueNormalize (potentialValue) {
- // To normalize a byte sequence potentialValue, remove
- // any leading and trailing HTTP whitespace bytes from
- // potentialValue.
- let i = 0; let j = potentialValue.length
+ if (body && typeof body.read === 'function') {
+ // Try to read EOF in order to get length.
+ body.read(0)
+ }
- while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j - 1))) --j
- while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i))) ++i
+ let contentLength = util.bodyLength(body)
- return i === 0 && j === potentialValue.length ? potentialValue : potentialValue.substring(i, j)
-}
+ if (util.isFormDataLike(body)) {
+ extractBody ??= (__nccwpck_require__(4492).extractBody)
-function fill (headers, object) {
- // To fill a Headers object headers with a given object object, run these steps:
+ const [bodyStream, contentType] = extractBody(body)
+ headers['content-type'] = contentType
- // 1. If object is a sequence, then for each header in object:
- // Note: webidl conversion to array has already been done.
- if (Array.isArray(object)) {
- for (let i = 0; i < object.length; ++i) {
- const header = object[i]
- // 1. If header does not contain exactly two items, then throw a TypeError.
- if (header.length !== 2) {
- throw webidl.errors.exception({
- header: 'Headers constructor',
- message: `expected name/value pair to be length 2, found ${header.length}.`
- })
- }
+ body = bodyStream.stream
+ contentLength = bodyStream.length
+ }
- // 2. Append (header’s first item, header’s second item) to headers.
- appendHeader(headers, header[0], header[1])
- }
- } else if (typeof object === 'object' && object !== null) {
- // Note: null should throw
+ if (contentLength == null) {
+ contentLength = request.contentLength
+ }
- // 2. Otherwise, object is a record, then for each key → value in object,
- // append (key, value) to headers
- const keys = Object.keys(object)
- for (let i = 0; i < keys.length; ++i) {
- appendHeader(headers, keys[i], object[keys[i]])
- }
- } else {
- throw webidl.errors.conversionFailed({
- prefix: 'Headers constructor',
- argument: 'Argument 1',
- types: ['sequence>', 'record']
- })
+ if (contentLength === 0 || !expectsPayload) {
+ // https://tools.ietf.org/html/rfc7230#section-3.3.2
+ // A user agent SHOULD NOT send a Content-Length header field when
+ // the request message does not contain a payload body and the method
+ // semantics do not anticipate such a body.
+
+ contentLength = null
}
-}
-/**
- * @see https://fetch.spec.whatwg.org/#concept-headers-append
- */
-function appendHeader (headers, name, value) {
- // 1. Normalize value.
- value = headerValueNormalize(value)
+ // https://github.com/nodejs/undici/issues/2046
+ // A user agent may send a Content-Length header with 0 value, this should be allowed.
+ if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength != null && request.contentLength !== contentLength) {
+ if (client[kStrictContentLength]) {
+ util.errorRequest(client, request, new RequestContentLengthMismatchError())
+ return false
+ }
- // 2. If name is not a header name or value is not a
- // header value, then throw a TypeError.
- if (!isValidHeaderName(name)) {
- throw webidl.errors.invalidArgument({
- prefix: 'Headers.append',
- value: name,
- type: 'header name'
- })
- } else if (!isValidHeaderValue(value)) {
- throw webidl.errors.invalidArgument({
- prefix: 'Headers.append',
- value,
- type: 'header value'
- })
+ process.emitWarning(new RequestContentLengthMismatchError())
}
- // 3. If headers’s guard is "immutable", then throw a TypeError.
- // 4. Otherwise, if headers’s guard is "request" and name is a
- // forbidden header name, return.
- // 5. Otherwise, if headers’s guard is "request-no-cors":
- // TODO
- // Note: undici does not implement forbidden header names
- if (getHeadersGuard(headers) === 'immutable') {
- throw new TypeError('immutable')
+ if (contentLength != null) {
+ assert(body, 'no body must not have content length')
+ headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}`
}
- // 6. Otherwise, if headers’s guard is "response" and name is a
- // forbidden response-header name, return.
+ session.ref()
- // 7. Append (name, value) to headers’s header list.
- return getHeadersList(headers).append(name, value, false)
+ const shouldEndStream = method === 'GET' || method === 'HEAD' || body === null
+ if (expectContinue) {
+ headers[HTTP2_HEADER_EXPECT] = '100-continue'
+ stream = session.request(headers, { endStream: shouldEndStream, signal })
- // 8. If headers’s guard is "request-no-cors", then remove
- // privileged no-CORS request headers from headers
-}
+ stream.once('continue', writeBodyH2)
+ } else {
+ stream = session.request(headers, {
+ endStream: shouldEndStream,
+ signal
+ })
+ writeBodyH2()
+ }
-function compareHeaderName (a, b) {
- return a[0] < b[0] ? -1 : 1
-}
+ // Increment counter as we have new streams open
+ ++session[kOpenStreams]
-class HeadersList {
- /** @type {[string, string][]|null} */
- cookies = null
+ stream.once('response', headers => {
+ const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers
+ request.onResponseStarted()
- constructor (init) {
- if (init instanceof HeadersList) {
- this[kHeadersMap] = new Map(init[kHeadersMap])
- this[kHeadersSortedMap] = init[kHeadersSortedMap]
- this.cookies = init.cookies === null ? null : [...init.cookies]
- } else {
- this[kHeadersMap] = new Map(init)
- this[kHeadersSortedMap] = null
+ // Due to the stream nature, it is possible we face a race condition
+ // where the stream has been assigned, but the request has been aborted
+ // the request remains in-flight and headers hasn't been received yet
+ // for those scenarios, best effort is to destroy the stream immediately
+ // as there's no value to keep it open.
+ if (request.aborted) {
+ const err = new RequestAbortedError()
+ util.errorRequest(client, request, err)
+ util.destroy(stream, err)
+ return
}
- }
-
- /**
- * @see https://fetch.spec.whatwg.org/#header-list-contains
- * @param {string} name
- * @param {boolean} isLowerCase
- */
- contains (name, isLowerCase) {
- // A header list list contains a header name name if list
- // contains a header whose name is a byte-case-insensitive
- // match for name.
- return this[kHeadersMap].has(isLowerCase ? name : name.toLowerCase())
- }
+ if (request.onHeaders(Number(statusCode), parseH2Headers(realHeaders), stream.resume.bind(stream), '') === false) {
+ stream.pause()
+ }
- clear () {
- this[kHeadersMap].clear()
- this[kHeadersSortedMap] = null
- this.cookies = null
- }
+ stream.on('data', (chunk) => {
+ if (request.onData(chunk) === false) {
+ stream.pause()
+ }
+ })
+ })
- /**
- * @see https://fetch.spec.whatwg.org/#concept-header-list-append
- * @param {string} name
- * @param {string} value
- * @param {boolean} isLowerCase
- */
- append (name, value, isLowerCase) {
- this[kHeadersSortedMap] = null
+ stream.once('end', () => {
+ // When state is null, it means we haven't consumed body and the stream still do not have
+ // a state.
+ // Present specially when using pipeline or stream
+ if (stream.state?.state == null || stream.state.state < 6) {
+ request.onComplete([])
+ }
- // 1. If list contains name, then set name to the first such
- // header’s name.
- const lowercaseName = isLowerCase ? name : name.toLowerCase()
- const exists = this[kHeadersMap].get(lowercaseName)
+ if (session[kOpenStreams] === 0) {
+ // Stream is closed or half-closed-remote (6), decrement counter and cleanup
+ // It does not have sense to continue working with the stream as we do not
+ // have yet RST_STREAM support on client-side
- // 2. Append (name, value) to list.
- if (exists) {
- const delimiter = lowercaseName === 'cookie' ? '; ' : ', '
- this[kHeadersMap].set(lowercaseName, {
- name: exists.name,
- value: `${exists.value}${delimiter}${value}`
- })
- } else {
- this[kHeadersMap].set(lowercaseName, { name, value })
+ session.unref()
}
- if (lowercaseName === 'set-cookie') {
- (this.cookies ??= []).push(value)
+ abort(new InformationalError('HTTP/2: stream half-closed (remote)'))
+ client[kQueue][client[kRunningIdx]++] = null
+ client[kPendingIdx] = client[kRunningIdx]
+ client[kResume]()
+ })
+
+ stream.once('close', () => {
+ session[kOpenStreams] -= 1
+ if (session[kOpenStreams] === 0) {
+ session.unref()
}
- }
+ })
- /**
- * @see https://fetch.spec.whatwg.org/#concept-header-list-set
- * @param {string} name
- * @param {string} value
- * @param {boolean} isLowerCase
- */
- set (name, value, isLowerCase) {
- this[kHeadersSortedMap] = null
- const lowercaseName = isLowerCase ? name : name.toLowerCase()
+ stream.once('error', function (err) {
+ abort(err)
+ })
- if (lowercaseName === 'set-cookie') {
- this.cookies = [value]
- }
+ stream.once('frameError', (type, code) => {
+ abort(new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`))
+ })
- // 1. If list contains name, then set the value of
- // the first such header to value and remove the
- // others.
- // 2. Otherwise, append header (name, value) to list.
- this[kHeadersMap].set(lowercaseName, { name, value })
- }
+ // stream.on('aborted', () => {
+ // // TODO(HTTP/2): Support aborted
+ // })
- /**
- * @see https://fetch.spec.whatwg.org/#concept-header-list-delete
- * @param {string} name
- * @param {boolean} isLowerCase
- */
- delete (name, isLowerCase) {
- this[kHeadersSortedMap] = null
- if (!isLowerCase) name = name.toLowerCase()
+ // stream.on('timeout', () => {
+ // // TODO(HTTP/2): Support timeout
+ // })
- if (name === 'set-cookie') {
- this.cookies = null
- }
+ // stream.on('push', headers => {
+ // // TODO(HTTP/2): Support push
+ // })
- this[kHeadersMap].delete(name)
- }
+ // stream.on('trailers', headers => {
+ // // TODO(HTTP/2): Support trailers
+ // })
- /**
- * @see https://fetch.spec.whatwg.org/#concept-header-list-get
- * @param {string} name
- * @param {boolean} isLowerCase
- * @returns {string | null}
- */
- get (name, isLowerCase) {
- // 1. If list does not contain name, then return null.
- // 2. Return the values of all headers in list whose name
- // is a byte-case-insensitive match for name,
- // separated from each other by 0x2C 0x20, in order.
- return this[kHeadersMap].get(isLowerCase ? name : name.toLowerCase())?.value ?? null
- }
+ return true
- * [Symbol.iterator] () {
- // use the lowercased name
- for (const { 0: name, 1: { value } } of this[kHeadersMap]) {
- yield [name, value]
+ function writeBodyH2 () {
+ /* istanbul ignore else: assertion */
+ if (!body || contentLength === 0) {
+ writeBuffer(
+ abort,
+ stream,
+ null,
+ client,
+ request,
+ client[kSocket],
+ contentLength,
+ expectsPayload
+ )
+ } else if (util.isBuffer(body)) {
+ writeBuffer(
+ abort,
+ stream,
+ body,
+ client,
+ request,
+ client[kSocket],
+ contentLength,
+ expectsPayload
+ )
+ } else if (util.isBlobLike(body)) {
+ if (typeof body.stream === 'function') {
+ writeIterable(
+ abort,
+ stream,
+ body.stream(),
+ client,
+ request,
+ client[kSocket],
+ contentLength,
+ expectsPayload
+ )
+ } else {
+ writeBlob(
+ abort,
+ stream,
+ body,
+ client,
+ request,
+ client[kSocket],
+ contentLength,
+ expectsPayload
+ )
+ }
+ } else if (util.isStream(body)) {
+ writeStream(
+ abort,
+ client[kSocket],
+ expectsPayload,
+ stream,
+ body,
+ client,
+ request,
+ contentLength
+ )
+ } else if (util.isIterable(body)) {
+ writeIterable(
+ abort,
+ stream,
+ body,
+ client,
+ request,
+ client[kSocket],
+ contentLength,
+ expectsPayload
+ )
+ } else {
+ assert(false)
}
}
+}
- get entries () {
- const headers = {}
+function writeBuffer (abort, h2stream, body, client, request, socket, contentLength, expectsPayload) {
+ try {
+ if (body != null && util.isBuffer(body)) {
+ assert(contentLength === body.byteLength, 'buffer body must have content length')
+ h2stream.cork()
+ h2stream.write(body)
+ h2stream.uncork()
+ h2stream.end()
- if (this[kHeadersMap].size !== 0) {
- for (const { name, value } of this[kHeadersMap].values()) {
- headers[name] = value
- }
+ request.onBodySent(body)
}
- return headers
- }
+ if (!expectsPayload) {
+ socket[kReset] = true
+ }
- rawValues () {
- return this[kHeadersMap].values()
+ request.onRequestSent()
+ client[kResume]()
+ } catch (error) {
+ abort(error)
}
+}
- get entriesList () {
- const headers = []
+function writeStream (abort, socket, expectsPayload, h2stream, body, client, request, contentLength) {
+ assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined')
- if (this[kHeadersMap].size !== 0) {
- for (const { 0: lowerName, 1: { name, value } } of this[kHeadersMap]) {
- if (lowerName === 'set-cookie') {
- for (const cookie of this.cookies) {
- headers.push([name, cookie])
- }
- } else {
- headers.push([name, value])
+ // For HTTP/2, is enough to pipe the stream
+ const pipe = pipeline(
+ body,
+ h2stream,
+ (err) => {
+ if (err) {
+ util.destroy(pipe, err)
+ abort(err)
+ } else {
+ util.removeAllListeners(pipe)
+ request.onRequestSent()
+
+ if (!expectsPayload) {
+ socket[kReset] = true
}
+
+ client[kResume]()
}
}
+ )
- return headers
- }
+ util.addListener(pipe, 'data', onPipeData)
- // https://fetch.spec.whatwg.org/#convert-header-names-to-a-sorted-lowercase-set
- toSortedArray () {
- const size = this[kHeadersMap].size
- const array = new Array(size)
- // In most cases, you will use the fast-path.
- // fast-path: Use binary insertion sort for small arrays.
- if (size <= 32) {
- if (size === 0) {
- // If empty, it is an empty array. To avoid the first index assignment.
- return array
- }
- // Improve performance by unrolling loop and avoiding double-loop.
- // Double-loop-less version of the binary insertion sort.
- const iterator = this[kHeadersMap][Symbol.iterator]()
- const firstValue = iterator.next().value
- // set [name, value] to first index.
- array[0] = [firstValue[0], firstValue[1].value]
- // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine
- // 3.2.2. Assert: value is non-null.
- assert(firstValue[1].value !== null)
- for (
- let i = 1, j = 0, right = 0, left = 0, pivot = 0, x, value;
- i < size;
- ++i
- ) {
- // get next value
- value = iterator.next().value
- // set [name, value] to current index.
- x = array[i] = [value[0], value[1].value]
- // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine
- // 3.2.2. Assert: value is non-null.
- assert(x[1] !== null)
- left = 0
- right = i
- // binary search
- while (left < right) {
- // middle index
- pivot = left + ((right - left) >> 1)
- // compare header name
- if (array[pivot][0] <= x[0]) {
- left = pivot + 1
- } else {
- right = pivot
- }
- }
- if (i !== pivot) {
- j = i
- while (j > left) {
- array[j] = array[--j]
- }
- array[left] = x
- }
- }
- /* c8 ignore next 4 */
- if (!iterator.next().done) {
- // This is for debugging and will never be called.
- throw new TypeError('Unreachable')
- }
- return array
- } else {
- // This case would be a rare occurrence.
- // slow-path: fallback
- let i = 0
- for (const { 0: name, 1: { value } } of this[kHeadersMap]) {
- array[i++] = [name, value]
- // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine
- // 3.2.2. Assert: value is non-null.
- assert(value !== null)
- }
- return array.sort(compareHeaderName)
- }
+ function onPipeData (chunk) {
+ request.onBodySent(chunk)
}
}
-// https://fetch.spec.whatwg.org/#headers-class
-class Headers {
- #guard
- #headersList
-
- constructor (init = undefined) {
- webidl.util.markAsUncloneable(this)
+async function writeBlob (abort, h2stream, body, client, request, socket, contentLength, expectsPayload) {
+ assert(contentLength === body.size, 'blob body must have content length')
- if (init === kConstruct) {
- return
+ try {
+ if (contentLength != null && contentLength !== body.size) {
+ throw new RequestContentLengthMismatchError()
}
- this.#headersList = new HeadersList()
+ const buffer = Buffer.from(await body.arrayBuffer())
- // The new Headers(init) constructor steps are:
+ h2stream.cork()
+ h2stream.write(buffer)
+ h2stream.uncork()
+ h2stream.end()
- // 1. Set this’s guard to "none".
- this.#guard = 'none'
+ request.onBodySent(buffer)
+ request.onRequestSent()
- // 2. If init is given, then fill this with init.
- if (init !== undefined) {
- init = webidl.converters.HeadersInit(init, 'Headers contructor', 'init')
- fill(this, init)
+ if (!expectsPayload) {
+ socket[kReset] = true
}
- }
-
- // https://fetch.spec.whatwg.org/#dom-headers-append
- append (name, value) {
- webidl.brandCheck(this, Headers)
- webidl.argumentLengthCheck(arguments, 2, 'Headers.append')
-
- const prefix = 'Headers.append'
- name = webidl.converters.ByteString(name, prefix, 'name')
- value = webidl.converters.ByteString(value, prefix, 'value')
-
- return appendHeader(this, name, value)
+ client[kResume]()
+ } catch (err) {
+ abort(err)
}
+}
- // https://fetch.spec.whatwg.org/#dom-headers-delete
- delete (name) {
- webidl.brandCheck(this, Headers)
+async function writeIterable (abort, h2stream, body, client, request, socket, contentLength, expectsPayload) {
+ assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined')
- webidl.argumentLengthCheck(arguments, 1, 'Headers.delete')
+ let callback = null
+ function onDrain () {
+ if (callback) {
+ const cb = callback
+ callback = null
+ cb()
+ }
+ }
- const prefix = 'Headers.delete'
- name = webidl.converters.ByteString(name, prefix, 'name')
+ const waitForDrain = () => new Promise((resolve, reject) => {
+ assert(callback === null)
- // 1. If name is not a header name, then throw a TypeError.
- if (!isValidHeaderName(name)) {
- throw webidl.errors.invalidArgument({
- prefix: 'Headers.delete',
- value: name,
- type: 'header name'
- })
+ if (socket[kError]) {
+ reject(socket[kError])
+ } else {
+ callback = resolve
}
+ })
- // 2. If this’s guard is "immutable", then throw a TypeError.
- // 3. Otherwise, if this’s guard is "request" and name is a
- // forbidden header name, return.
- // 4. Otherwise, if this’s guard is "request-no-cors", name
- // is not a no-CORS-safelisted request-header name, and
- // name is not a privileged no-CORS request-header name,
- // return.
- // 5. Otherwise, if this’s guard is "response" and name is
- // a forbidden response-header name, return.
- // Note: undici does not implement forbidden header names
- if (this.#guard === 'immutable') {
- throw new TypeError('immutable')
+ h2stream
+ .on('close', onDrain)
+ .on('drain', onDrain)
+
+ try {
+ // It's up to the user to somehow abort the async iterable.
+ for await (const chunk of body) {
+ if (socket[kError]) {
+ throw socket[kError]
+ }
+
+ const res = h2stream.write(chunk)
+ request.onBodySent(chunk)
+ if (!res) {
+ await waitForDrain()
+ }
}
- // 6. If this’s header list does not contain name, then
- // return.
- if (!this.#headersList.contains(name, false)) {
- return
+ h2stream.end()
+
+ request.onRequestSent()
+
+ if (!expectsPayload) {
+ socket[kReset] = true
}
- // 7. Delete name from this’s header list.
- // 8. If this’s guard is "request-no-cors", then remove
- // privileged no-CORS request headers from this.
- this.#headersList.delete(name, false)
+ client[kResume]()
+ } catch (err) {
+ abort(err)
+ } finally {
+ h2stream
+ .off('close', onDrain)
+ .off('drain', onDrain)
}
+}
- // https://fetch.spec.whatwg.org/#dom-headers-get
- get (name) {
- webidl.brandCheck(this, Headers)
+module.exports = connectH2
- webidl.argumentLengthCheck(arguments, 1, 'Headers.get')
- const prefix = 'Headers.get'
- name = webidl.converters.ByteString(name, prefix, 'name')
+/***/ }),
- // 1. If name is not a header name, then throw a TypeError.
- if (!isValidHeaderName(name)) {
- throw webidl.errors.invalidArgument({
- prefix,
- value: name,
- type: 'header name'
- })
- }
+/***/ 3701:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 2. Return the result of getting name from this’s header
- // list.
- return this.#headersList.get(name, false)
- }
+// @ts-check
- // https://fetch.spec.whatwg.org/#dom-headers-has
- has (name) {
- webidl.brandCheck(this, Headers)
- webidl.argumentLengthCheck(arguments, 1, 'Headers.has')
- const prefix = 'Headers.has'
- name = webidl.converters.ByteString(name, prefix, 'name')
+const assert = __nccwpck_require__(4589)
+const net = __nccwpck_require__(7030)
+const http = __nccwpck_require__(7067)
+const util = __nccwpck_require__(3440)
+const { channels } = __nccwpck_require__(2414)
+const Request = __nccwpck_require__(4655)
+const DispatcherBase = __nccwpck_require__(1841)
+const {
+ InvalidArgumentError,
+ InformationalError,
+ ClientDestroyedError
+} = __nccwpck_require__(8707)
+const buildConnector = __nccwpck_require__(9136)
+const {
+ kUrl,
+ kServerName,
+ kClient,
+ kBusy,
+ kConnect,
+ kResuming,
+ kRunning,
+ kPending,
+ kSize,
+ kQueue,
+ kConnected,
+ kConnecting,
+ kNeedDrain,
+ kKeepAliveDefaultTimeout,
+ kHostHeader,
+ kPendingIdx,
+ kRunningIdx,
+ kError,
+ kPipelining,
+ kKeepAliveTimeoutValue,
+ kMaxHeadersSize,
+ kKeepAliveMaxTimeout,
+ kKeepAliveTimeoutThreshold,
+ kHeadersTimeout,
+ kBodyTimeout,
+ kStrictContentLength,
+ kConnector,
+ kMaxRedirections,
+ kMaxRequests,
+ kCounter,
+ kClose,
+ kDestroy,
+ kDispatch,
+ kInterceptors,
+ kLocalAddress,
+ kMaxResponseSize,
+ kOnError,
+ kHTTPContext,
+ kMaxConcurrentStreams,
+ kResume
+} = __nccwpck_require__(6443)
+const connectH1 = __nccwpck_require__(637)
+const connectH2 = __nccwpck_require__(8788)
+let deprecatedInterceptorWarned = false
- // 1. If name is not a header name, then throw a TypeError.
- if (!isValidHeaderName(name)) {
- throw webidl.errors.invalidArgument({
- prefix,
- value: name,
- type: 'header name'
- })
- }
+const kClosedResolve = Symbol('kClosedResolve')
- // 2. Return true if this’s header list contains name;
- // otherwise false.
- return this.#headersList.contains(name, false)
- }
+const noop = () => {}
- // https://fetch.spec.whatwg.org/#dom-headers-set
- set (name, value) {
- webidl.brandCheck(this, Headers)
+function getPipelining (client) {
+ return client[kPipelining] ?? client[kHTTPContext]?.defaultPipelining ?? 1
+}
- webidl.argumentLengthCheck(arguments, 2, 'Headers.set')
+/**
+ * @type {import('../../types/client.js').default}
+ */
+class Client extends DispatcherBase {
+ /**
+ *
+ * @param {string|URL} url
+ * @param {import('../../types/client.js').Client.Options} options
+ */
+ constructor (url, {
+ interceptors,
+ maxHeaderSize,
+ headersTimeout,
+ socketTimeout,
+ requestTimeout,
+ connectTimeout,
+ bodyTimeout,
+ idleTimeout,
+ keepAlive,
+ keepAliveTimeout,
+ maxKeepAliveTimeout,
+ keepAliveMaxTimeout,
+ keepAliveTimeoutThreshold,
+ socketPath,
+ pipelining,
+ tls,
+ strictContentLength,
+ maxCachedSessions,
+ maxRedirections,
+ connect,
+ maxRequestsPerClient,
+ localAddress,
+ maxResponseSize,
+ autoSelectFamily,
+ autoSelectFamilyAttemptTimeout,
+ // h2
+ maxConcurrentStreams,
+ allowH2
+ } = {}) {
+ super()
- const prefix = 'Headers.set'
- name = webidl.converters.ByteString(name, prefix, 'name')
- value = webidl.converters.ByteString(value, prefix, 'value')
+ if (keepAlive !== undefined) {
+ throw new InvalidArgumentError('unsupported keepAlive, use pipelining=0 instead')
+ }
- // 1. Normalize value.
- value = headerValueNormalize(value)
+ if (socketTimeout !== undefined) {
+ throw new InvalidArgumentError('unsupported socketTimeout, use headersTimeout & bodyTimeout instead')
+ }
- // 2. If name is not a header name or value is not a
- // header value, then throw a TypeError.
- if (!isValidHeaderName(name)) {
- throw webidl.errors.invalidArgument({
- prefix,
- value: name,
- type: 'header name'
- })
- } else if (!isValidHeaderValue(value)) {
- throw webidl.errors.invalidArgument({
- prefix,
- value,
- type: 'header value'
- })
+ if (requestTimeout !== undefined) {
+ throw new InvalidArgumentError('unsupported requestTimeout, use headersTimeout & bodyTimeout instead')
}
- // 3. If this’s guard is "immutable", then throw a TypeError.
- // 4. Otherwise, if this’s guard is "request" and name is a
- // forbidden header name, return.
- // 5. Otherwise, if this’s guard is "request-no-cors" and
- // name/value is not a no-CORS-safelisted request-header,
- // return.
- // 6. Otherwise, if this’s guard is "response" and name is a
- // forbidden response-header name, return.
- // Note: undici does not implement forbidden header names
- if (this.#guard === 'immutable') {
- throw new TypeError('immutable')
+ if (idleTimeout !== undefined) {
+ throw new InvalidArgumentError('unsupported idleTimeout, use keepAliveTimeout instead')
}
- // 7. Set (name, value) in this’s header list.
- // 8. If this’s guard is "request-no-cors", then remove
- // privileged no-CORS request headers from this
- this.#headersList.set(name, value, false)
- }
+ if (maxKeepAliveTimeout !== undefined) {
+ throw new InvalidArgumentError('unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead')
+ }
- // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie
- getSetCookie () {
- webidl.brandCheck(this, Headers)
+ if (maxHeaderSize != null && !Number.isFinite(maxHeaderSize)) {
+ throw new InvalidArgumentError('invalid maxHeaderSize')
+ }
- // 1. If this’s header list does not contain `Set-Cookie`, then return « ».
- // 2. Return the values of all headers in this’s header list whose name is
- // a byte-case-insensitive match for `Set-Cookie`, in order.
+ if (socketPath != null && typeof socketPath !== 'string') {
+ throw new InvalidArgumentError('invalid socketPath')
+ }
- const list = this.#headersList.cookies
+ if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) {
+ throw new InvalidArgumentError('invalid connectTimeout')
+ }
- if (list) {
- return [...list]
+ if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) {
+ throw new InvalidArgumentError('invalid keepAliveTimeout')
}
- return []
- }
+ if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) {
+ throw new InvalidArgumentError('invalid keepAliveMaxTimeout')
+ }
- // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine
- get [kHeadersSortedMap] () {
- if (this.#headersList[kHeadersSortedMap]) {
- return this.#headersList[kHeadersSortedMap]
+ if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) {
+ throw new InvalidArgumentError('invalid keepAliveTimeoutThreshold')
}
- // 1. Let headers be an empty list of headers with the key being the name
- // and value the value.
- const headers = []
+ if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) {
+ throw new InvalidArgumentError('headersTimeout must be a positive integer or zero')
+ }
- // 2. Let names be the result of convert header names to a sorted-lowercase
- // set with all the names of the headers in list.
- const names = this.#headersList.toSortedArray()
+ if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) {
+ throw new InvalidArgumentError('bodyTimeout must be a positive integer or zero')
+ }
- const cookies = this.#headersList.cookies
+ if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {
+ throw new InvalidArgumentError('connect must be a function or an object')
+ }
- // fast-path
- if (cookies === null || cookies.length === 1) {
- // Note: The non-null assertion of value has already been done by `HeadersList#toSortedArray`
- return (this.#headersList[kHeadersSortedMap] = names)
+ if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {
+ throw new InvalidArgumentError('maxRedirections must be a positive number')
}
- // 3. For each name of names:
- for (let i = 0; i < names.length; ++i) {
- const { 0: name, 1: value } = names[i]
- // 1. If name is `set-cookie`, then:
- if (name === 'set-cookie') {
- // 1. Let values be a list of all values of headers in list whose name
- // is a byte-case-insensitive match for name, in order.
+ if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) {
+ throw new InvalidArgumentError('maxRequestsPerClient must be a positive number')
+ }
- // 2. For each value of values:
- // 1. Append (name, value) to headers.
- for (let j = 0; j < cookies.length; ++j) {
- headers.push([name, cookies[j]])
- }
- } else {
- // 2. Otherwise:
+ if (localAddress != null && (typeof localAddress !== 'string' || net.isIP(localAddress) === 0)) {
+ throw new InvalidArgumentError('localAddress must be valid string IP address')
+ }
- // 1. Let value be the result of getting name from list.
+ if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) {
+ throw new InvalidArgumentError('maxResponseSize must be a positive number')
+ }
- // 2. Assert: value is non-null.
- // Note: This operation was done by `HeadersList#toSortedArray`.
+ if (
+ autoSelectFamilyAttemptTimeout != null &&
+ (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1)
+ ) {
+ throw new InvalidArgumentError('autoSelectFamilyAttemptTimeout must be a positive number')
+ }
- // 3. Append (name, value) to headers.
- headers.push([name, value])
+ // h2
+ if (allowH2 != null && typeof allowH2 !== 'boolean') {
+ throw new InvalidArgumentError('allowH2 must be a valid boolean value')
+ }
+
+ if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== 'number' || maxConcurrentStreams < 1)) {
+ throw new InvalidArgumentError('maxConcurrentStreams must be a positive integer, greater than 0')
+ }
+
+ if (typeof connect !== 'function') {
+ connect = buildConnector({
+ ...tls,
+ maxCachedSessions,
+ allowH2,
+ socketPath,
+ timeout: connectTimeout,
+ ...(autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined),
+ ...connect
+ })
+ }
+
+ if (interceptors?.Client && Array.isArray(interceptors.Client)) {
+ this[kInterceptors] = interceptors.Client
+ if (!deprecatedInterceptorWarned) {
+ deprecatedInterceptorWarned = true
+ process.emitWarning('Client.Options#interceptor is deprecated. Use Dispatcher#compose instead.', {
+ code: 'UNDICI-CLIENT-INTERCEPTOR-DEPRECATED'
+ })
}
+ } else {
+ this[kInterceptors] = [createRedirectInterceptor({ maxRedirections })]
}
- // 4. Return headers.
- return (this.#headersList[kHeadersSortedMap] = headers)
- }
+ this[kUrl] = util.parseOrigin(url)
+ this[kConnector] = connect
+ this[kPipelining] = pipelining != null ? pipelining : 1
+ this[kMaxHeadersSize] = maxHeaderSize || http.maxHeaderSize
+ this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout
+ this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 600e3 : keepAliveMaxTimeout
+ this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 2e3 : keepAliveTimeoutThreshold
+ this[kKeepAliveTimeoutValue] = this[kKeepAliveDefaultTimeout]
+ this[kServerName] = null
+ this[kLocalAddress] = localAddress != null ? localAddress : null
+ this[kResuming] = 0 // 0, idle, 1, scheduled, 2 resuming
+ this[kNeedDrain] = 0 // 0, idle, 1, scheduled, 2 resuming
+ this[kHostHeader] = `host: ${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}\r\n`
+ this[kBodyTimeout] = bodyTimeout != null ? bodyTimeout : 300e3
+ this[kHeadersTimeout] = headersTimeout != null ? headersTimeout : 300e3
+ this[kStrictContentLength] = strictContentLength == null ? true : strictContentLength
+ this[kMaxRedirections] = maxRedirections
+ this[kMaxRequests] = maxRequestsPerClient
+ this[kClosedResolve] = null
+ this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1
+ this[kMaxConcurrentStreams] = maxConcurrentStreams != null ? maxConcurrentStreams : 100 // Max peerConcurrentStreams for a Node h2 server
+ this[kHTTPContext] = null
- [util.inspect.custom] (depth, options) {
- options.depth ??= depth
+ // kQueue is built up of 3 sections separated by
+ // the kRunningIdx and kPendingIdx indices.
+ // | complete | running | pending |
+ // ^ kRunningIdx ^ kPendingIdx ^ kQueue.length
+ // kRunningIdx points to the first running element.
+ // kPendingIdx points to the first pending element.
+ // This implements a fast queue with an amortized
+ // time of O(1).
- return `Headers ${util.formatWithOptions(options, this.#headersList.entries)}`
+ this[kQueue] = []
+ this[kRunningIdx] = 0
+ this[kPendingIdx] = 0
+
+ this[kResume] = (sync) => resume(this, sync)
+ this[kOnError] = (err) => onError(this, err)
}
- static getHeadersGuard (o) {
- return o.#guard
+ get pipelining () {
+ return this[kPipelining]
}
- static setHeadersGuard (o, guard) {
- o.#guard = guard
+ set pipelining (value) {
+ this[kPipelining] = value
+ this[kResume](true)
}
- static getHeadersList (o) {
- return o.#headersList
+ get [kPending] () {
+ return this[kQueue].length - this[kPendingIdx]
}
- static setHeadersList (o, list) {
- o.#headersList = list
+ get [kRunning] () {
+ return this[kPendingIdx] - this[kRunningIdx]
}
-}
-const { getHeadersGuard, setHeadersGuard, getHeadersList, setHeadersList } = Headers
-Reflect.deleteProperty(Headers, 'getHeadersGuard')
-Reflect.deleteProperty(Headers, 'setHeadersGuard')
-Reflect.deleteProperty(Headers, 'getHeadersList')
-Reflect.deleteProperty(Headers, 'setHeadersList')
+ get [kSize] () {
+ return this[kQueue].length - this[kRunningIdx]
+ }
-iteratorMixin('Headers', Headers, kHeadersSortedMap, 0, 1)
+ get [kConnected] () {
+ return !!this[kHTTPContext] && !this[kConnecting] && !this[kHTTPContext].destroyed
+ }
-Object.defineProperties(Headers.prototype, {
- append: kEnumerableProperty,
- delete: kEnumerableProperty,
- get: kEnumerableProperty,
- has: kEnumerableProperty,
- set: kEnumerableProperty,
- getSetCookie: kEnumerableProperty,
- [Symbol.toStringTag]: {
- value: 'Headers',
- configurable: true
- },
- [util.inspect.custom]: {
- enumerable: false
+ get [kBusy] () {
+ return Boolean(
+ this[kHTTPContext]?.busy(null) ||
+ (this[kSize] >= (getPipelining(this) || 1)) ||
+ this[kPending] > 0
+ )
}
-})
-webidl.converters.HeadersInit = function (V, prefix, argument) {
- if (webidl.util.Type(V) === 'Object') {
- const iterator = Reflect.get(V, Symbol.iterator)
+ /* istanbul ignore: only used for test */
+ [kConnect] (cb) {
+ connect(this)
+ this.once('connect', cb)
+ }
- // A work-around to ensure we send the properly-cased Headers when V is a Headers object.
- // Read https://github.com/nodejs/undici/pull/3159#issuecomment-2075537226 before touching, please.
- if (!util.types.isProxy(V) && iterator === Headers.prototype.entries) { // Headers object
- try {
- return getHeadersList(V).entriesList
- } catch {
- // fall-through
- }
+ [kDispatch] (opts, handler) {
+ const origin = opts.origin || this[kUrl].origin
+ const request = new Request(origin, opts, handler)
+
+ this[kQueue].push(request)
+ if (this[kResuming]) {
+ // Do nothing.
+ } else if (util.bodyLength(request.body) == null && util.isIterable(request.body)) {
+ // Wait a tick in case stream/iterator is ended in the same tick.
+ this[kResuming] = 1
+ queueMicrotask(() => resume(this))
+ } else {
+ this[kResume](true)
}
- if (typeof iterator === 'function') {
- return webidl.converters['sequence>'](V, prefix, argument, iterator.bind(V))
+ if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) {
+ this[kNeedDrain] = 2
}
- return webidl.converters['record'](V, prefix, argument)
+ return this[kNeedDrain] < 2
}
- throw webidl.errors.conversionFailed({
- prefix: 'Headers constructor',
- argument: 'Argument 1',
- types: ['sequence>', 'record']
- })
-}
-
-module.exports = {
- fill,
- // for test.
- compareHeaderName,
- Headers,
- HeadersList,
- getHeadersGuard,
- setHeadersGuard,
- setHeadersList,
- getHeadersList
-}
+ async [kClose] () {
+ // TODO: for H2 we need to gracefully flush the remaining enqueued
+ // request and close each stream.
+ return new Promise((resolve) => {
+ if (this[kSize]) {
+ this[kClosedResolve] = resolve
+ } else {
+ resolve(null)
+ }
+ })
+ }
+ async [kDestroy] (err) {
+ return new Promise((resolve) => {
+ const requests = this[kQueue].splice(this[kPendingIdx])
+ for (let i = 0; i < requests.length; i++) {
+ const request = requests[i]
+ util.errorRequest(this, request, err)
+ }
-/***/ }),
+ const callback = () => {
+ if (this[kClosedResolve]) {
+ // TODO (fix): Should we error here with ClientDestroyedError?
+ this[kClosedResolve]()
+ this[kClosedResolve] = null
+ }
+ resolve(null)
+ }
-/***/ 8033:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ if (this[kHTTPContext]) {
+ this[kHTTPContext].destroy(err, callback)
+ this[kHTTPContext] = null
+ } else {
+ queueMicrotask(callback)
+ }
-// https://github.com/Ethan-Arrowood/undici-fetch
+ this[kResume]()
+ })
+ }
+}
+const createRedirectInterceptor = __nccwpck_require__(5092)
+function onError (client, err) {
+ if (
+ client[kRunning] === 0 &&
+ err.code !== 'UND_ERR_INFO' &&
+ err.code !== 'UND_ERR_SOCKET'
+ ) {
+ // Error is not caused by running request and not a recoverable
+ // socket error.
-const {
- makeNetworkError,
- makeAppropriateNetworkError,
- filterResponse,
- makeResponse,
- fromInnerResponse
-} = __nccwpck_require__(6678)
-const { HeadersList } = __nccwpck_require__(1271)
-const { Request, cloneRequest } = __nccwpck_require__(7412)
-const zlib = __nccwpck_require__(8522)
-const {
- bytesMatch,
- makePolicyContainer,
- clonePolicyContainer,
- requestBadPort,
- TAOCheck,
- appendRequestOriginHeader,
- responseLocationURL,
- requestCurrentURL,
- setRequestReferrerPolicyOnRedirect,
- tryUpgradeRequestToAPotentiallyTrustworthyURL,
- createOpaqueTimingInfo,
- appendFetchMetadata,
- corsCheck,
- crossOriginResourcePolicyCheck,
- determineRequestsReferrer,
- coarsenedSharedCurrentTime,
- createDeferredPromise,
- isBlobLike,
- sameOrigin,
- isCancelled,
- isAborted,
- isErrorLike,
- fullyReadBody,
- readableStreamClose,
- isomorphicEncode,
- urlIsLocal,
- urlIsHttpHttpsScheme,
- urlHasHttpsScheme,
- clampAndCoarsenConnectionTimingInfo,
- simpleRangeHeaderValue,
- buildContentRange,
- createInflate,
- extractMimeType
-} = __nccwpck_require__(7241)
-const { kState, kDispatcher } = __nccwpck_require__(1944)
-const assert = __nccwpck_require__(4589)
-const { safelyExtractBody, extractBody } = __nccwpck_require__(3278)
-const {
- redirectStatusSet,
- nullBodyStatus,
- safeMethodsSet,
- requestBodyHeader,
- subresourceSet
-} = __nccwpck_require__(5336)
-const EE = __nccwpck_require__(8474)
-const { Readable, pipeline, finished } = __nccwpck_require__(7075)
-const { addAbortListener, isErrored, isReadable, bufferToLowerCasedHeaderName } = __nccwpck_require__(7375)
-const { dataURLProcessor, serializeAMimeType, minimizeSupportedMimeType } = __nccwpck_require__(2121)
-const { getGlobalDispatcher } = __nccwpck_require__(1088)
-const { webidl } = __nccwpck_require__(220)
-const { STATUS_CODES } = __nccwpck_require__(7067)
-const GET_OR_HEAD = ['GET', 'HEAD']
+ assert(client[kPendingIdx] === client[kRunningIdx])
-const defaultUserAgent = typeof __UNDICI_IS_NODE__ !== 'undefined' || typeof esbuildDetection !== 'undefined'
- ? 'node'
- : 'undici'
+ const requests = client[kQueue].splice(client[kRunningIdx])
-/** @type {import('buffer').resolveObjectURL} */
-let resolveObjectURL
+ for (let i = 0; i < requests.length; i++) {
+ const request = requests[i]
+ util.errorRequest(client, request, err)
+ }
+ assert(client[kSize] === 0)
+ }
+}
-class Fetch extends EE {
- constructor (dispatcher) {
- super()
+/**
+ * @param {Client} client
+ * @returns
+ */
+async function connect (client) {
+ assert(!client[kConnecting])
+ assert(!client[kHTTPContext])
- this.dispatcher = dispatcher
- this.connection = null
- this.dump = false
- this.state = 'ongoing'
+ let { host, hostname, protocol, port } = client[kUrl]
+
+ // Resolve ipv6
+ if (hostname[0] === '[') {
+ const idx = hostname.indexOf(']')
+
+ assert(idx !== -1)
+ const ip = hostname.substring(1, idx)
+
+ assert(net.isIP(ip))
+ hostname = ip
}
- terminate (reason) {
- if (this.state !== 'ongoing') {
- return
- }
+ client[kConnecting] = true
- this.state = 'terminated'
- this.connection?.destroy(reason)
- this.emit('terminated', reason)
+ if (channels.beforeConnect.hasSubscribers) {
+ channels.beforeConnect.publish({
+ connectParams: {
+ host,
+ hostname,
+ protocol,
+ port,
+ version: client[kHTTPContext]?.version,
+ servername: client[kServerName],
+ localAddress: client[kLocalAddress]
+ },
+ connector: client[kConnector]
+ })
}
- // https://fetch.spec.whatwg.org/#fetch-controller-abort
- abort (error) {
- if (this.state !== 'ongoing') {
+ try {
+ const socket = await new Promise((resolve, reject) => {
+ client[kConnector]({
+ host,
+ hostname,
+ protocol,
+ port,
+ servername: client[kServerName],
+ localAddress: client[kLocalAddress]
+ }, (err, socket) => {
+ if (err) {
+ reject(err)
+ } else {
+ resolve(socket)
+ }
+ })
+ })
+
+ if (client.destroyed) {
+ util.destroy(socket.on('error', noop), new ClientDestroyedError())
return
}
- // 1. Set controller’s state to "aborted".
- this.state = 'aborted'
+ assert(socket)
- // 2. Let fallbackError be an "AbortError" DOMException.
- // 3. Set error to fallbackError if it is not given.
- if (!error) {
- error = new DOMException('The operation was aborted.', 'AbortError')
+ try {
+ client[kHTTPContext] = socket.alpnProtocol === 'h2'
+ ? await connectH2(client, socket)
+ : await connectH1(client, socket)
+ } catch (err) {
+ socket.destroy().on('error', noop)
+ throw err
}
- // 4. Let serializedError be StructuredSerialize(error).
- // If that threw an exception, catch it, and let
- // serializedError be StructuredSerialize(fallbackError).
-
- // 5. Set controller’s serialized abort reason to serializedError.
- this.serializedAbortReason = error
+ client[kConnecting] = false
- this.connection?.destroy(error)
- this.emit('terminated', error)
- }
-}
+ socket[kCounter] = 0
+ socket[kMaxRequests] = client[kMaxRequests]
+ socket[kClient] = client
+ socket[kError] = null
-function handleFetchDone (response) {
- finalizeAndReportTiming(response, 'fetch')
-}
+ if (channels.connected.hasSubscribers) {
+ channels.connected.publish({
+ connectParams: {
+ host,
+ hostname,
+ protocol,
+ port,
+ version: client[kHTTPContext]?.version,
+ servername: client[kServerName],
+ localAddress: client[kLocalAddress]
+ },
+ connector: client[kConnector],
+ socket
+ })
+ }
+ client.emit('connect', client[kUrl], [client])
+ } catch (err) {
+ if (client.destroyed) {
+ return
+ }
-// https://fetch.spec.whatwg.org/#fetch-method
-function fetch (input, init = undefined) {
- webidl.argumentLengthCheck(arguments, 1, 'globalThis.fetch')
+ client[kConnecting] = false
- // 1. Let p be a new promise.
- let p = createDeferredPromise()
+ if (channels.connectError.hasSubscribers) {
+ channels.connectError.publish({
+ connectParams: {
+ host,
+ hostname,
+ protocol,
+ port,
+ version: client[kHTTPContext]?.version,
+ servername: client[kServerName],
+ localAddress: client[kLocalAddress]
+ },
+ connector: client[kConnector],
+ error: err
+ })
+ }
- // 2. Let requestObject be the result of invoking the initial value of
- // Request as constructor with input and init as arguments. If this throws
- // an exception, reject p with it and return p.
- let requestObject
+ if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') {
+ assert(client[kRunning] === 0)
+ while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) {
+ const request = client[kQueue][client[kPendingIdx]++]
+ util.errorRequest(client, request, err)
+ }
+ } else {
+ onError(client, err)
+ }
- try {
- requestObject = new Request(input, init)
- } catch (e) {
- p.reject(e)
- return p.promise
+ client.emit('connectionError', client[kUrl], [client], err)
}
- // 3. Let request be requestObject’s request.
- const request = requestObject[kState]
+ client[kResume]()
+}
- // 4. If requestObject’s signal’s aborted flag is set, then:
- if (requestObject.signal.aborted) {
- // 1. Abort the fetch() call with p, request, null, and
- // requestObject’s signal’s abort reason.
- abortFetch(p, request, null, requestObject.signal.reason)
+function emitDrain (client) {
+ client[kNeedDrain] = 0
+ client.emit('drain', client[kUrl], [client])
+}
- // 2. Return p.
- return p.promise
+function resume (client, sync) {
+ if (client[kResuming] === 2) {
+ return
}
- // 5. Let globalObject be request’s client’s global object.
- const globalObject = request.client.globalObject
+ client[kResuming] = 2
- // 6. If globalObject is a ServiceWorkerGlobalScope object, then set
- // request’s service-workers mode to "none".
- if (globalObject?.constructor?.name === 'ServiceWorkerGlobalScope') {
- request.serviceWorkers = 'none'
+ _resume(client, sync)
+ client[kResuming] = 0
+
+ if (client[kRunningIdx] > 256) {
+ client[kQueue].splice(0, client[kRunningIdx])
+ client[kPendingIdx] -= client[kRunningIdx]
+ client[kRunningIdx] = 0
}
+}
- // 7. Let responseObject be null.
- let responseObject = null
+function _resume (client, sync) {
+ while (true) {
+ if (client.destroyed) {
+ assert(client[kPending] === 0)
+ return
+ }
- // 8. Let relevantRealm be this’s relevant Realm.
+ if (client[kClosedResolve] && !client[kSize]) {
+ client[kClosedResolve]()
+ client[kClosedResolve] = null
+ return
+ }
- // 9. Let locallyAborted be false.
- let locallyAborted = false
+ if (client[kHTTPContext]) {
+ client[kHTTPContext].resume()
+ }
- // 10. Let controller be null.
- let controller = null
+ if (client[kBusy]) {
+ client[kNeedDrain] = 2
+ } else if (client[kNeedDrain] === 2) {
+ if (sync) {
+ client[kNeedDrain] = 1
+ queueMicrotask(() => emitDrain(client))
+ } else {
+ emitDrain(client)
+ }
+ continue
+ }
- // 11. Add the following abort steps to requestObject’s signal:
- addAbortListener(
- requestObject.signal,
- () => {
- // 1. Set locallyAborted to true.
- locallyAborted = true
+ if (client[kPending] === 0) {
+ return
+ }
- // 2. Assert: controller is non-null.
- assert(controller != null)
+ if (client[kRunning] >= (getPipelining(client) || 1)) {
+ return
+ }
- // 3. Abort controller with requestObject’s signal’s abort reason.
- controller.abort(requestObject.signal.reason)
+ const request = client[kQueue][client[kPendingIdx]]
- const realResponse = responseObject?.deref()
+ if (client[kUrl].protocol === 'https:' && client[kServerName] !== request.servername) {
+ if (client[kRunning] > 0) {
+ return
+ }
- // 4. Abort the fetch() call with p, request, responseObject,
- // and requestObject’s signal’s abort reason.
- abortFetch(p, request, realResponse, requestObject.signal.reason)
+ client[kServerName] = request.servername
+ client[kHTTPContext]?.destroy(new InformationalError('servername changed'), () => {
+ client[kHTTPContext] = null
+ resume(client)
+ })
}
- )
-
- // 12. Let handleFetchDone given response response be to finalize and
- // report timing with response, globalObject, and "fetch".
- // see function handleFetchDone
-
- // 13. Set controller to the result of calling fetch given request,
- // with processResponseEndOfBody set to handleFetchDone, and processResponse
- // given response being these substeps:
- const processResponse = (response) => {
- // 1. If locallyAborted is true, terminate these substeps.
- if (locallyAborted) {
+ if (client[kConnecting]) {
return
}
- // 2. If response’s aborted flag is set, then:
- if (response.aborted) {
- // 1. Let deserializedError be the result of deserialize a serialized
- // abort reason given controller’s serialized abort reason and
- // relevantRealm.
-
- // 2. Abort the fetch() call with p, request, responseObject, and
- // deserializedError.
-
- abortFetch(p, request, responseObject, controller.serializedAbortReason)
+ if (!client[kHTTPContext]) {
+ connect(client)
return
}
- // 3. If response is a network error, then reject p with a TypeError
- // and terminate these substeps.
- if (response.type === 'error') {
- p.reject(new TypeError('fetch failed', { cause: response.error }))
+ if (client[kHTTPContext].destroyed) {
return
}
- // 4. Set responseObject to the result of creating a Response object,
- // given response, "immutable", and relevantRealm.
- responseObject = new WeakRef(fromInnerResponse(response, 'immutable'))
+ if (client[kHTTPContext].busy(request)) {
+ return
+ }
- // 5. Resolve p with responseObject.
- p.resolve(responseObject.deref())
- p = null
+ if (!request.aborted && client[kHTTPContext].write(request)) {
+ client[kPendingIdx]++
+ } else {
+ client[kQueue].splice(client[kPendingIdx], 1)
+ }
}
+}
- controller = fetching({
- request,
- processResponseEndOfBody: handleFetchDone,
- processResponse,
- dispatcher: requestObject[kDispatcher] // undici
- })
+module.exports = Client
- // 14. Return p.
- return p.promise
-}
-// https://fetch.spec.whatwg.org/#finalize-and-report-timing
-function finalizeAndReportTiming (response, initiatorType = 'other') {
- // 1. If response is an aborted network error, then return.
- if (response.type === 'error' && response.aborted) {
- return
- }
+/***/ }),
- // 2. If response’s URL list is null or empty, then return.
- if (!response.urlList?.length) {
- return
- }
+/***/ 1841:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 3. Let originalURL be response’s URL list[0].
- const originalURL = response.urlList[0]
- // 4. Let timingInfo be response’s timing info.
- let timingInfo = response.timingInfo
- // 5. Let cacheState be response’s cache state.
- let cacheState = response.cacheState
+const Dispatcher = __nccwpck_require__(883)
+const {
+ ClientDestroyedError,
+ ClientClosedError,
+ InvalidArgumentError
+} = __nccwpck_require__(8707)
+const { kDestroy, kClose, kClosed, kDestroyed, kDispatch, kInterceptors } = __nccwpck_require__(6443)
- // 6. If originalURL’s scheme is not an HTTP(S) scheme, then return.
- if (!urlIsHttpHttpsScheme(originalURL)) {
- return
+const kOnDestroyed = Symbol('onDestroyed')
+const kOnClosed = Symbol('onClosed')
+const kInterceptedDispatch = Symbol('Intercepted Dispatch')
+
+class DispatcherBase extends Dispatcher {
+ constructor () {
+ super()
+
+ this[kDestroyed] = false
+ this[kOnDestroyed] = null
+ this[kClosed] = false
+ this[kOnClosed] = []
}
- // 7. If timingInfo is null, then return.
- if (timingInfo === null) {
- return
+ get destroyed () {
+ return this[kDestroyed]
}
- // 8. If response’s timing allow passed flag is not set, then:
- if (!response.timingAllowPassed) {
- // 1. Set timingInfo to a the result of creating an opaque timing info for timingInfo.
- timingInfo = createOpaqueTimingInfo({
- startTime: timingInfo.startTime
- })
+ get closed () {
+ return this[kClosed]
+ }
- // 2. Set cacheState to the empty string.
- cacheState = ''
+ get interceptors () {
+ return this[kInterceptors]
}
- // 9. Set timingInfo’s end time to the coarsened shared current time
- // given global’s relevant settings object’s cross-origin isolated
- // capability.
- // TODO: given global’s relevant settings object’s cross-origin isolated
- // capability?
- timingInfo.endTime = coarsenedSharedCurrentTime()
+ set interceptors (newInterceptors) {
+ if (newInterceptors) {
+ for (let i = newInterceptors.length - 1; i >= 0; i--) {
+ const interceptor = this[kInterceptors][i]
+ if (typeof interceptor !== 'function') {
+ throw new InvalidArgumentError('interceptor must be an function')
+ }
+ }
+ }
- // 10. Set response’s timing info to timingInfo.
- response.timingInfo = timingInfo
+ this[kInterceptors] = newInterceptors
+ }
- // 11. Mark resource timing for timingInfo, originalURL, initiatorType,
- // global, and cacheState.
- markResourceTiming(
- timingInfo,
- originalURL.href,
- initiatorType,
- globalThis,
- cacheState
- )
-}
+ close (callback) {
+ if (callback === undefined) {
+ return new Promise((resolve, reject) => {
+ this.close((err, data) => {
+ return err ? reject(err) : resolve(data)
+ })
+ })
+ }
-// https://w3c.github.io/resource-timing/#dfn-mark-resource-timing
-const markResourceTiming = performance.markResourceTiming
+ if (typeof callback !== 'function') {
+ throw new InvalidArgumentError('invalid callback')
+ }
-// https://fetch.spec.whatwg.org/#abort-fetch
-function abortFetch (p, request, responseObject, error) {
- // 1. Reject promise with error.
- if (p) {
- // We might have already resolved the promise at this stage
- p.reject(error)
- }
+ if (this[kDestroyed]) {
+ queueMicrotask(() => callback(new ClientDestroyedError(), null))
+ return
+ }
- // 2. If request’s body is not null and is readable, then cancel request’s
- // body with error.
- if (request.body != null && isReadable(request.body?.stream)) {
- request.body.stream.cancel(error).catch((err) => {
- if (err.code === 'ERR_INVALID_STATE') {
- // Node bug?
- return
+ if (this[kClosed]) {
+ if (this[kOnClosed]) {
+ this[kOnClosed].push(callback)
+ } else {
+ queueMicrotask(() => callback(null, null))
}
- throw err
- })
- }
-
- // 3. If responseObject is null, then return.
- if (responseObject == null) {
- return
- }
+ return
+ }
- // 4. Let response be responseObject’s response.
- const response = responseObject[kState]
+ this[kClosed] = true
+ this[kOnClosed].push(callback)
- // 5. If response’s body is not null and is readable, then error response’s
- // body with error.
- if (response.body != null && isReadable(response.body?.stream)) {
- response.body.stream.cancel(error).catch((err) => {
- if (err.code === 'ERR_INVALID_STATE') {
- // Node bug?
- return
+ const onClosed = () => {
+ const callbacks = this[kOnClosed]
+ this[kOnClosed] = null
+ for (let i = 0; i < callbacks.length; i++) {
+ callbacks[i](null, null)
}
- throw err
- })
+ }
+
+ // Should not error.
+ this[kClose]()
+ .then(() => this.destroy())
+ .then(() => {
+ queueMicrotask(onClosed)
+ })
}
-}
-// https://fetch.spec.whatwg.org/#fetching
-function fetching ({
- request,
- processRequestBodyChunkLength,
- processRequestEndOfBody,
- processResponse,
- processResponseEndOfBody,
- processResponseConsumeBody,
- useParallelQueue = false,
- dispatcher = getGlobalDispatcher() // undici
-}) {
- // Ensure that the dispatcher is set accordingly
- assert(dispatcher)
+ destroy (err, callback) {
+ if (typeof err === 'function') {
+ callback = err
+ err = null
+ }
- // 1. Let taskDestination be null.
- let taskDestination = null
+ if (callback === undefined) {
+ return new Promise((resolve, reject) => {
+ this.destroy(err, (err, data) => {
+ return err ? /* istanbul ignore next: should never error */ reject(err) : resolve(data)
+ })
+ })
+ }
- // 2. Let crossOriginIsolatedCapability be false.
- let crossOriginIsolatedCapability = false
+ if (typeof callback !== 'function') {
+ throw new InvalidArgumentError('invalid callback')
+ }
- // 3. If request’s client is non-null, then:
- if (request.client != null) {
- // 1. Set taskDestination to request’s client’s global object.
- taskDestination = request.client.globalObject
+ if (this[kDestroyed]) {
+ if (this[kOnDestroyed]) {
+ this[kOnDestroyed].push(callback)
+ } else {
+ queueMicrotask(() => callback(null, null))
+ }
+ return
+ }
- // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin
- // isolated capability.
- crossOriginIsolatedCapability =
- request.client.crossOriginIsolatedCapability
- }
+ if (!err) {
+ err = new ClientDestroyedError()
+ }
- // 4. If useParallelQueue is true, then set taskDestination to the result of
- // starting a new parallel queue.
- // TODO
+ this[kDestroyed] = true
+ this[kOnDestroyed] = this[kOnDestroyed] || []
+ this[kOnDestroyed].push(callback)
- // 5. Let timingInfo be a new fetch timing info whose start time and
- // post-redirect start time are the coarsened shared current time given
- // crossOriginIsolatedCapability.
- const currentTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability)
- const timingInfo = createOpaqueTimingInfo({
- startTime: currentTime
- })
+ const onDestroyed = () => {
+ const callbacks = this[kOnDestroyed]
+ this[kOnDestroyed] = null
+ for (let i = 0; i < callbacks.length; i++) {
+ callbacks[i](null, null)
+ }
+ }
- // 6. Let fetchParams be a new fetch params whose
- // request is request,
- // timing info is timingInfo,
- // process request body chunk length is processRequestBodyChunkLength,
- // process request end-of-body is processRequestEndOfBody,
- // process response is processResponse,
- // process response consume body is processResponseConsumeBody,
- // process response end-of-body is processResponseEndOfBody,
- // task destination is taskDestination,
- // and cross-origin isolated capability is crossOriginIsolatedCapability.
- const fetchParams = {
- controller: new Fetch(dispatcher),
- request,
- timingInfo,
- processRequestBodyChunkLength,
- processRequestEndOfBody,
- processResponse,
- processResponseConsumeBody,
- processResponseEndOfBody,
- taskDestination,
- crossOriginIsolatedCapability
+ // Should not error.
+ this[kDestroy](err).then(() => {
+ queueMicrotask(onDestroyed)
+ })
}
- // 7. If request’s body is a byte sequence, then set request’s body to
- // request’s body as a body.
- // NOTE: Since fetching is only called from fetch, body should already be
- // extracted.
- assert(!request.body || request.body.stream)
+ [kInterceptedDispatch] (opts, handler) {
+ if (!this[kInterceptors] || this[kInterceptors].length === 0) {
+ this[kInterceptedDispatch] = this[kDispatch]
+ return this[kDispatch](opts, handler)
+ }
- // 8. If request’s window is "client", then set request’s window to request’s
- // client, if request’s client’s global object is a Window object; otherwise
- // "no-window".
- if (request.window === 'client') {
- // TODO: What if request.client is null?
- request.window =
- request.client?.globalObject?.constructor?.name === 'Window'
- ? request.client
- : 'no-window'
+ let dispatch = this[kDispatch].bind(this)
+ for (let i = this[kInterceptors].length - 1; i >= 0; i--) {
+ dispatch = this[kInterceptors][i](dispatch)
+ }
+ this[kInterceptedDispatch] = dispatch
+ return dispatch(opts, handler)
}
- // 9. If request’s origin is "client", then set request’s origin to request’s
- // client’s origin.
- if (request.origin === 'client') {
- request.origin = request.client.origin
- }
+ dispatch (opts, handler) {
+ if (!handler || typeof handler !== 'object') {
+ throw new InvalidArgumentError('handler must be an object')
+ }
- // 10. If all of the following conditions are true:
- // TODO
+ try {
+ if (!opts || typeof opts !== 'object') {
+ throw new InvalidArgumentError('opts must be an object.')
+ }
- // 11. If request’s policy container is "client", then:
- if (request.policyContainer === 'client') {
- // 1. If request’s client is non-null, then set request’s policy
- // container to a clone of request’s client’s policy container. [HTML]
- if (request.client != null) {
- request.policyContainer = clonePolicyContainer(
- request.client.policyContainer
- )
- } else {
- // 2. Otherwise, set request’s policy container to a new policy
- // container.
- request.policyContainer = makePolicyContainer()
+ if (this[kDestroyed] || this[kOnDestroyed]) {
+ throw new ClientDestroyedError()
+ }
+
+ if (this[kClosed]) {
+ throw new ClientClosedError()
+ }
+
+ return this[kInterceptedDispatch](opts, handler)
+ } catch (err) {
+ if (typeof handler.onError !== 'function') {
+ throw new InvalidArgumentError('invalid onError method')
+ }
+
+ handler.onError(err)
+
+ return false
}
}
+}
- // 12. If request’s header list does not contain `Accept`, then:
- if (!request.headersList.contains('accept', true)) {
- // 1. Let value be `*/*`.
- const value = '*/*'
+module.exports = DispatcherBase
- // 2. A user agent should set value to the first matching statement, if
- // any, switching on request’s destination:
- // "document"
- // "frame"
- // "iframe"
- // `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8`
- // "image"
- // `image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5`
- // "style"
- // `text/css,*/*;q=0.1`
- // TODO
- // 3. Append `Accept`/value to request’s header list.
- request.headersList.append('accept', value, true)
- }
+/***/ }),
- // 13. If request’s header list does not contain `Accept-Language`, then
- // user agents should append `Accept-Language`/an appropriate value to
- // request’s header list.
- if (!request.headersList.contains('accept-language', true)) {
- request.headersList.append('accept-language', '*', true)
+/***/ 883:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+const EventEmitter = __nccwpck_require__(8474)
+
+class Dispatcher extends EventEmitter {
+ dispatch () {
+ throw new Error('not implemented')
}
- // 14. If request’s priority is null, then use request’s initiator and
- // destination appropriately in setting request’s priority to a
- // user-agent-defined object.
- if (request.priority === null) {
- // TODO
+ close () {
+ throw new Error('not implemented')
}
- // 15. If request is a subresource request, then:
- if (subresourceSet.has(request.destination)) {
- // TODO
+ destroy () {
+ throw new Error('not implemented')
}
- // 16. Run main fetch given fetchParams.
- mainFetch(fetchParams)
- .catch(err => {
- fetchParams.controller.terminate(err)
- })
+ compose (...args) {
+ // So we handle [interceptor1, interceptor2] or interceptor1, interceptor2, ...
+ const interceptors = Array.isArray(args[0]) ? args[0] : args
+ let dispatch = this.dispatch.bind(this)
- // 17. Return fetchParam's controller
- return fetchParams.controller
-}
+ for (const interceptor of interceptors) {
+ if (interceptor == null) {
+ continue
+ }
-// https://fetch.spec.whatwg.org/#concept-main-fetch
-async function mainFetch (fetchParams, recursive = false) {
- // 1. Let request be fetchParams’s request.
- const request = fetchParams.request
+ if (typeof interceptor !== 'function') {
+ throw new TypeError(`invalid interceptor, expected function received ${typeof interceptor}`)
+ }
- // 2. Let response be null.
- let response = null
+ dispatch = interceptor(dispatch)
- // 3. If request’s local-URLs-only flag is set and request’s current URL is
- // not local, then set response to a network error.
- if (request.localURLsOnly && !urlIsLocal(requestCurrentURL(request))) {
- response = makeNetworkError('local URLs only')
+ if (dispatch == null || typeof dispatch !== 'function' || dispatch.length !== 2) {
+ throw new TypeError('invalid interceptor')
+ }
+ }
+
+ return new ComposedDispatcher(this, dispatch)
}
+}
- // 4. Run report Content Security Policy violations for request.
- // TODO
+class ComposedDispatcher extends Dispatcher {
+ #dispatcher = null
+ #dispatch = null
- // 5. Upgrade request to a potentially trustworthy URL, if appropriate.
- tryUpgradeRequestToAPotentiallyTrustworthyURL(request)
+ constructor (dispatcher, dispatch) {
+ super()
+ this.#dispatcher = dispatcher
+ this.#dispatch = dispatch
+ }
- // 6. If should request be blocked due to a bad port, should fetching request
- // be blocked as mixed content, or should request be blocked by Content
- // Security Policy returns blocked, then set response to a network error.
- if (requestBadPort(request) === 'blocked') {
- response = makeNetworkError('bad port')
+ dispatch (...args) {
+ this.#dispatch(...args)
}
- // TODO: should fetching request be blocked as mixed content?
- // TODO: should request be blocked by Content Security Policy?
- // 7. If request’s referrer policy is the empty string, then set request’s
- // referrer policy to request’s policy container’s referrer policy.
- if (request.referrerPolicy === '') {
- request.referrerPolicy = request.policyContainer.referrerPolicy
+ close (...args) {
+ return this.#dispatcher.close(...args)
}
- // 8. If request’s referrer is not "no-referrer", then set request’s
- // referrer to the result of invoking determine request’s referrer.
- if (request.referrer !== 'no-referrer') {
- request.referrer = determineRequestsReferrer(request)
+ destroy (...args) {
+ return this.#dispatcher.destroy(...args)
}
+}
- // 9. Set request’s current URL’s scheme to "https" if all of the following
- // conditions are true:
- // - request’s current URL’s scheme is "http"
- // - request’s current URL’s host is a domain
- // - Matching request’s current URL’s host per Known HSTS Host Domain Name
- // Matching results in either a superdomain match with an asserted
- // includeSubDomains directive or a congruent match (with or without an
- // asserted includeSubDomains directive). [HSTS]
- // TODO
+module.exports = Dispatcher
- // 10. If recursive is false, then run the remaining steps in parallel.
- // TODO
- // 11. If response is null, then set response to the result of running
- // the steps corresponding to the first matching statement:
- if (response === null) {
- response = await (async () => {
- const currentURL = requestCurrentURL(request)
+/***/ }),
- if (
- // - request’s current URL’s origin is same origin with request’s origin,
- // and request’s response tainting is "basic"
- (sameOrigin(currentURL, request.url) && request.responseTainting === 'basic') ||
- // request’s current URL’s scheme is "data"
- (currentURL.protocol === 'data:') ||
- // - request’s mode is "navigate" or "websocket"
- (request.mode === 'navigate' || request.mode === 'websocket')
- ) {
- // 1. Set request’s response tainting to "basic".
- request.responseTainting = 'basic'
+/***/ 3137:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 2. Return the result of running scheme fetch given fetchParams.
- return await schemeFetch(fetchParams)
- }
- // request’s mode is "same-origin"
- if (request.mode === 'same-origin') {
- // 1. Return a network error.
- return makeNetworkError('request mode cannot be "same-origin"')
- }
- // request’s mode is "no-cors"
- if (request.mode === 'no-cors') {
- // 1. If request’s redirect mode is not "follow", then return a network
- // error.
- if (request.redirect !== 'follow') {
- return makeNetworkError(
- 'redirect mode cannot be "follow" for "no-cors" request'
- )
- }
+const DispatcherBase = __nccwpck_require__(1841)
+const { kClose, kDestroy, kClosed, kDestroyed, kDispatch, kNoProxyAgent, kHttpProxyAgent, kHttpsProxyAgent } = __nccwpck_require__(6443)
+const ProxyAgent = __nccwpck_require__(6672)
+const Agent = __nccwpck_require__(7405)
- // 2. Set request’s response tainting to "opaque".
- request.responseTainting = 'opaque'
+const DEFAULT_PORTS = {
+ 'http:': 80,
+ 'https:': 443
+}
- // 3. Return the result of running scheme fetch given fetchParams.
- return await schemeFetch(fetchParams)
- }
+let experimentalWarned = false
- // request’s current URL’s scheme is not an HTTP(S) scheme
- if (!urlIsHttpHttpsScheme(requestCurrentURL(request))) {
- // Return a network error.
- return makeNetworkError('URL scheme must be a HTTP(S) scheme')
- }
+class EnvHttpProxyAgent extends DispatcherBase {
+ #noProxyValue = null
+ #noProxyEntries = null
+ #opts = null
- // - request’s use-CORS-preflight flag is set
- // - request’s unsafe-request flag is set and either request’s method is
- // not a CORS-safelisted method or CORS-unsafe request-header names with
- // request’s header list is not empty
- // 1. Set request’s response tainting to "cors".
- // 2. Let corsWithPreflightResponse be the result of running HTTP fetch
- // given fetchParams and true.
- // 3. If corsWithPreflightResponse is a network error, then clear cache
- // entries using request.
- // 4. Return corsWithPreflightResponse.
- // TODO
+ constructor (opts = {}) {
+ super()
+ this.#opts = opts
- // Otherwise
- // 1. Set request’s response tainting to "cors".
- request.responseTainting = 'cors'
+ if (!experimentalWarned) {
+ experimentalWarned = true
+ process.emitWarning('EnvHttpProxyAgent is experimental, expect them to change at any time.', {
+ code: 'UNDICI-EHPA'
+ })
+ }
- // 2. Return the result of running HTTP fetch given fetchParams.
- return await httpFetch(fetchParams)
- })()
- }
+ const { httpProxy, httpsProxy, noProxy, ...agentOpts } = opts
- // 12. If recursive is true, then return response.
- if (recursive) {
- return response
- }
+ this[kNoProxyAgent] = new Agent(agentOpts)
- // 13. If response is not a network error and response is not a filtered
- // response, then:
- if (response.status !== 0 && !response.internalResponse) {
- // If request’s response tainting is "cors", then:
- if (request.responseTainting === 'cors') {
- // 1. Let headerNames be the result of extracting header list values
- // given `Access-Control-Expose-Headers` and response’s header list.
- // TODO
- // 2. If request’s credentials mode is not "include" and headerNames
- // contains `*`, then set response’s CORS-exposed header-name list to
- // all unique header names in response’s header list.
- // TODO
- // 3. Otherwise, if headerNames is not null or failure, then set
- // response’s CORS-exposed header-name list to headerNames.
- // TODO
+ const HTTP_PROXY = httpProxy ?? process.env.http_proxy ?? process.env.HTTP_PROXY
+ if (HTTP_PROXY) {
+ this[kHttpProxyAgent] = new ProxyAgent({ ...agentOpts, uri: HTTP_PROXY })
+ } else {
+ this[kHttpProxyAgent] = this[kNoProxyAgent]
}
- // Set response to the following filtered response with response as its
- // internal response, depending on request’s response tainting:
- if (request.responseTainting === 'basic') {
- response = filterResponse(response, 'basic')
- } else if (request.responseTainting === 'cors') {
- response = filterResponse(response, 'cors')
- } else if (request.responseTainting === 'opaque') {
- response = filterResponse(response, 'opaque')
+ const HTTPS_PROXY = httpsProxy ?? process.env.https_proxy ?? process.env.HTTPS_PROXY
+ if (HTTPS_PROXY) {
+ this[kHttpsProxyAgent] = new ProxyAgent({ ...agentOpts, uri: HTTPS_PROXY })
} else {
- assert(false)
+ this[kHttpsProxyAgent] = this[kHttpProxyAgent]
}
- }
- // 14. Let internalResponse be response, if response is a network error,
- // and response’s internal response otherwise.
- let internalResponse =
- response.status === 0 ? response : response.internalResponse
+ this.#parseNoProxy()
+ }
- // 15. If internalResponse’s URL list is empty, then set it to a clone of
- // request’s URL list.
- if (internalResponse.urlList.length === 0) {
- internalResponse.urlList.push(...request.urlList)
+ [kDispatch] (opts, handler) {
+ const url = new URL(opts.origin)
+ const agent = this.#getProxyAgentForUrl(url)
+ return agent.dispatch(opts, handler)
}
- // 16. If request’s timing allow failed flag is unset, then set
- // internalResponse’s timing allow passed flag.
- if (!request.timingAllowFailed) {
- response.timingAllowPassed = true
+ async [kClose] () {
+ await this[kNoProxyAgent].close()
+ if (!this[kHttpProxyAgent][kClosed]) {
+ await this[kHttpProxyAgent].close()
+ }
+ if (!this[kHttpsProxyAgent][kClosed]) {
+ await this[kHttpsProxyAgent].close()
+ }
}
- // 17. If response is not a network error and any of the following returns
- // blocked
- // - should internalResponse to request be blocked as mixed content
- // - should internalResponse to request be blocked by Content Security Policy
- // - should internalResponse to request be blocked due to its MIME type
- // - should internalResponse to request be blocked due to nosniff
- // TODO
-
- // 18. If response’s type is "opaque", internalResponse’s status is 206,
- // internalResponse’s range-requested flag is set, and request’s header
- // list does not contain `Range`, then set response and internalResponse
- // to a network error.
- if (
- response.type === 'opaque' &&
- internalResponse.status === 206 &&
- internalResponse.rangeRequested &&
- !request.headers.contains('range', true)
- ) {
- response = internalResponse = makeNetworkError()
+ async [kDestroy] (err) {
+ await this[kNoProxyAgent].destroy(err)
+ if (!this[kHttpProxyAgent][kDestroyed]) {
+ await this[kHttpProxyAgent].destroy(err)
+ }
+ if (!this[kHttpsProxyAgent][kDestroyed]) {
+ await this[kHttpsProxyAgent].destroy(err)
+ }
}
- // 19. If response is not a network error and either request’s method is
- // `HEAD` or `CONNECT`, or internalResponse’s status is a null body status,
- // set internalResponse’s body to null and disregard any enqueuing toward
- // it (if any).
- if (
- response.status !== 0 &&
- (request.method === 'HEAD' ||
- request.method === 'CONNECT' ||
- nullBodyStatus.includes(internalResponse.status))
- ) {
- internalResponse.body = null
- fetchParams.controller.dump = true
+ #getProxyAgentForUrl (url) {
+ let { protocol, host: hostname, port } = url
+
+ // Stripping ports in this way instead of using parsedUrl.hostname to make
+ // sure that the brackets around IPv6 addresses are kept.
+ hostname = hostname.replace(/:\d*$/, '').toLowerCase()
+ port = Number.parseInt(port, 10) || DEFAULT_PORTS[protocol] || 0
+ if (!this.#shouldProxy(hostname, port)) {
+ return this[kNoProxyAgent]
+ }
+ if (protocol === 'https:') {
+ return this[kHttpsProxyAgent]
+ }
+ return this[kHttpProxyAgent]
}
- // 20. If request’s integrity metadata is not the empty string, then:
- if (request.integrity) {
- // 1. Let processBodyError be this step: run fetch finale given fetchParams
- // and a network error.
- const processBodyError = (reason) =>
- fetchFinale(fetchParams, makeNetworkError(reason))
+ #shouldProxy (hostname, port) {
+ if (this.#noProxyChanged) {
+ this.#parseNoProxy()
+ }
- // 2. If request’s response tainting is "opaque", or response’s body is null,
- // then run processBodyError and abort these steps.
- if (request.responseTainting === 'opaque' || response.body == null) {
- processBodyError(response.error)
- return
+ if (this.#noProxyEntries.length === 0) {
+ return true // Always proxy if NO_PROXY is not set or empty.
+ }
+ if (this.#noProxyValue === '*') {
+ return false // Never proxy if wildcard is set.
}
- // 3. Let processBody given bytes be these steps:
- const processBody = (bytes) => {
- // 1. If bytes do not match request’s integrity metadata,
- // then run processBodyError and abort these steps. [SRI]
- if (!bytesMatch(bytes, request.integrity)) {
- processBodyError('integrity mismatch')
- return
+ for (let i = 0; i < this.#noProxyEntries.length; i++) {
+ const entry = this.#noProxyEntries[i]
+ if (entry.port && entry.port !== port) {
+ continue // Skip if ports don't match.
+ }
+ if (!/^[.*]/.test(entry.hostname)) {
+ // No wildcards, so don't proxy only if there is not an exact match.
+ if (hostname === entry.hostname) {
+ return false
+ }
+ } else {
+ // Don't proxy if the hostname ends with the no_proxy host.
+ if (hostname.endsWith(entry.hostname.replace(/^\*/, ''))) {
+ return false
+ }
}
+ }
- // 2. Set response’s body to bytes as a body.
- response.body = safelyExtractBody(bytes)[0]
+ return true
+ }
- // 3. Run fetch finale given fetchParams and response.
- fetchFinale(fetchParams, response)
+ #parseNoProxy () {
+ const noProxyValue = this.#opts.noProxy ?? this.#noProxyEnv
+ const noProxySplit = noProxyValue.split(/[,\s]/)
+ const noProxyEntries = []
+
+ for (let i = 0; i < noProxySplit.length; i++) {
+ const entry = noProxySplit[i]
+ if (!entry) {
+ continue
+ }
+ const parsed = entry.match(/^(.+):(\d+)$/)
+ noProxyEntries.push({
+ hostname: (parsed ? parsed[1] : entry).toLowerCase(),
+ port: parsed ? Number.parseInt(parsed[2], 10) : 0
+ })
}
- // 4. Fully read response’s body given processBody and processBodyError.
- await fullyReadBody(response.body, processBody, processBodyError)
- } else {
- // 21. Otherwise, run fetch finale given fetchParams and response.
- fetchFinale(fetchParams, response)
+ this.#noProxyValue = noProxyValue
+ this.#noProxyEntries = noProxyEntries
}
-}
-// https://fetch.spec.whatwg.org/#concept-scheme-fetch
-// given a fetch params fetchParams
-function schemeFetch (fetchParams) {
- // Note: since the connection is destroyed on redirect, which sets fetchParams to a
- // cancelled state, we do not want this condition to trigger *unless* there have been
- // no redirects. See https://github.com/nodejs/undici/issues/1776
- // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
- if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) {
- return Promise.resolve(makeAppropriateNetworkError(fetchParams))
+ get #noProxyChanged () {
+ if (this.#opts.noProxy !== undefined) {
+ return false
+ }
+ return this.#noProxyValue !== this.#noProxyEnv
}
- // 2. Let request be fetchParams’s request.
- const { request } = fetchParams
+ get #noProxyEnv () {
+ return process.env.no_proxy ?? process.env.NO_PROXY ?? ''
+ }
+}
- const { protocol: scheme } = requestCurrentURL(request)
+module.exports = EnvHttpProxyAgent
- // 3. Switch on request’s current URL’s scheme and run the associated steps:
- switch (scheme) {
- case 'about:': {
- // If request’s current URL’s path is the string "blank", then return a new response
- // whose status message is `OK`, header list is « (`Content-Type`, `text/html;charset=utf-8`) »,
- // and body is the empty byte sequence as a body.
- // Otherwise, return a network error.
- return Promise.resolve(makeNetworkError('about scheme is not supported'))
- }
- case 'blob:': {
- if (!resolveObjectURL) {
- resolveObjectURL = (__nccwpck_require__(4573).resolveObjectURL)
- }
+/***/ }),
- // 1. Let blobURLEntry be request’s current URL’s blob URL entry.
- const blobURLEntry = requestCurrentURL(request)
+/***/ 4660:
+/***/ ((module) => {
- // https://github.com/web-platform-tests/wpt/blob/7b0ebaccc62b566a1965396e5be7bb2bc06f841f/FileAPI/url/resources/fetch-tests.js#L52-L56
- // Buffer.resolveObjectURL does not ignore URL queries.
- if (blobURLEntry.search.length !== 0) {
- return Promise.resolve(makeNetworkError('NetworkError when attempting to fetch resource.'))
- }
+/* eslint-disable */
- const blob = resolveObjectURL(blobURLEntry.toString())
- // 2. If request’s method is not `GET`, blobURLEntry is null, or blobURLEntry’s
- // object is not a Blob object, then return a network error.
- if (request.method !== 'GET' || !isBlobLike(blob)) {
- return Promise.resolve(makeNetworkError('invalid method'))
- }
- // 3. Let blob be blobURLEntry’s object.
- // Note: done above
+// Extracted from node/lib/internal/fixed_queue.js
- // 4. Let response be a new response.
- const response = makeResponse()
+// Currently optimal queue size, tested on V8 6.0 - 6.6. Must be power of two.
+const kSize = 2048;
+const kMask = kSize - 1;
- // 5. Let fullLength be blob’s size.
- const fullLength = blob.size
+// The FixedQueue is implemented as a singly-linked list of fixed-size
+// circular buffers. It looks something like this:
+//
+// head tail
+// | |
+// v v
+// +-----------+ <-----\ +-----------+ <------\ +-----------+
+// | [null] | \----- | next | \------- | next |
+// +-----------+ +-----------+ +-----------+
+// | item | <-- bottom | item | <-- bottom | [empty] |
+// | item | | item | | [empty] |
+// | item | | item | | [empty] |
+// | item | | item | | [empty] |
+// | item | | item | bottom --> | item |
+// | item | | item | | item |
+// | ... | | ... | | ... |
+// | item | | item | | item |
+// | item | | item | | item |
+// | [empty] | <-- top | item | | item |
+// | [empty] | | item | | item |
+// | [empty] | | [empty] | <-- top top --> | [empty] |
+// +-----------+ +-----------+ +-----------+
+//
+// Or, if there is only one circular buffer, it looks something
+// like either of these:
+//
+// head tail head tail
+// | | | |
+// v v v v
+// +-----------+ +-----------+
+// | [null] | | [null] |
+// +-----------+ +-----------+
+// | [empty] | | item |
+// | [empty] | | item |
+// | item | <-- bottom top --> | [empty] |
+// | item | | [empty] |
+// | [empty] | <-- top bottom --> | item |
+// | [empty] | | item |
+// +-----------+ +-----------+
+//
+// Adding a value means moving `top` forward by one, removing means
+// moving `bottom` forward by one. After reaching the end, the queue
+// wraps around.
+//
+// When `top === bottom` the current queue is empty and when
+// `top + 1 === bottom` it's full. This wastes a single space of storage
+// but allows much quicker checks.
- // 6. Let serializedFullLength be fullLength, serialized and isomorphic encoded.
- const serializedFullLength = isomorphicEncode(`${fullLength}`)
+class FixedCircularBuffer {
+ constructor() {
+ this.bottom = 0;
+ this.top = 0;
+ this.list = new Array(kSize);
+ this.next = null;
+ }
- // 7. Let type be blob’s type.
- const type = blob.type
+ isEmpty() {
+ return this.top === this.bottom;
+ }
- // 8. If request’s header list does not contain `Range`:
- // 9. Otherwise:
- if (!request.headersList.contains('range', true)) {
- // 1. Let bodyWithType be the result of safely extracting blob.
- // Note: in the FileAPI a blob "object" is a Blob *or* a MediaSource.
- // In node, this can only ever be a Blob. Therefore we can safely
- // use extractBody directly.
- const bodyWithType = extractBody(blob)
+ isFull() {
+ return ((this.top + 1) & kMask) === this.bottom;
+ }
- // 2. Set response’s status message to `OK`.
- response.statusText = 'OK'
+ push(data) {
+ this.list[this.top] = data;
+ this.top = (this.top + 1) & kMask;
+ }
- // 3. Set response’s body to bodyWithType’s body.
- response.body = bodyWithType[0]
+ shift() {
+ const nextItem = this.list[this.bottom];
+ if (nextItem === undefined)
+ return null;
+ this.list[this.bottom] = undefined;
+ this.bottom = (this.bottom + 1) & kMask;
+ return nextItem;
+ }
+}
- // 4. Set response’s header list to « (`Content-Length`, serializedFullLength), (`Content-Type`, type) ».
- response.headersList.set('content-length', serializedFullLength, true)
- response.headersList.set('content-type', type, true)
- } else {
- // 1. Set response’s range-requested flag.
- response.rangeRequested = true
+module.exports = class FixedQueue {
+ constructor() {
+ this.head = this.tail = new FixedCircularBuffer();
+ }
- // 2. Let rangeHeader be the result of getting `Range` from request’s header list.
- const rangeHeader = request.headersList.get('range', true)
+ isEmpty() {
+ return this.head.isEmpty();
+ }
- // 3. Let rangeValue be the result of parsing a single range header value given rangeHeader and true.
- const rangeValue = simpleRangeHeaderValue(rangeHeader, true)
+ push(data) {
+ if (this.head.isFull()) {
+ // Head is full: Creates a new queue, sets the old queue's `.next` to it,
+ // and sets it as the new main queue.
+ this.head = this.head.next = new FixedCircularBuffer();
+ }
+ this.head.push(data);
+ }
- // 4. If rangeValue is failure, then return a network error.
- if (rangeValue === 'failure') {
- return Promise.resolve(makeNetworkError('failed to fetch the data URL'))
- }
+ shift() {
+ const tail = this.tail;
+ const next = tail.shift();
+ if (tail.isEmpty() && tail.next !== null) {
+ // If there is another queue, it forms the new tail.
+ this.tail = tail.next;
+ }
+ return next;
+ }
+};
- // 5. Let (rangeStart, rangeEnd) be rangeValue.
- let { rangeStartValue: rangeStart, rangeEndValue: rangeEnd } = rangeValue
- // 6. If rangeStart is null:
- // 7. Otherwise:
- if (rangeStart === null) {
- // 1. Set rangeStart to fullLength − rangeEnd.
- rangeStart = fullLength - rangeEnd
+/***/ }),
- // 2. Set rangeEnd to rangeStart + rangeEnd − 1.
- rangeEnd = rangeStart + rangeEnd - 1
- } else {
- // 1. If rangeStart is greater than or equal to fullLength, then return a network error.
- if (rangeStart >= fullLength) {
- return Promise.resolve(makeNetworkError('Range start is greater than the blob\'s size.'))
- }
+/***/ 2128:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 2. If rangeEnd is null or rangeEnd is greater than or equal to fullLength, then set
- // rangeEnd to fullLength − 1.
- if (rangeEnd === null || rangeEnd >= fullLength) {
- rangeEnd = fullLength - 1
- }
- }
- // 8. Let slicedBlob be the result of invoking slice blob given blob, rangeStart,
- // rangeEnd + 1, and type.
- const slicedBlob = blob.slice(rangeStart, rangeEnd, type)
- // 9. Let slicedBodyWithType be the result of safely extracting slicedBlob.
- // Note: same reason as mentioned above as to why we use extractBody
- const slicedBodyWithType = extractBody(slicedBlob)
+const DispatcherBase = __nccwpck_require__(1841)
+const FixedQueue = __nccwpck_require__(4660)
+const { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = __nccwpck_require__(6443)
+const PoolStats = __nccwpck_require__(3246)
- // 10. Set response’s body to slicedBodyWithType’s body.
- response.body = slicedBodyWithType[0]
+const kClients = Symbol('clients')
+const kNeedDrain = Symbol('needDrain')
+const kQueue = Symbol('queue')
+const kClosedResolve = Symbol('closed resolve')
+const kOnDrain = Symbol('onDrain')
+const kOnConnect = Symbol('onConnect')
+const kOnDisconnect = Symbol('onDisconnect')
+const kOnConnectionError = Symbol('onConnectionError')
+const kGetDispatcher = Symbol('get dispatcher')
+const kAddClient = Symbol('add client')
+const kRemoveClient = Symbol('remove client')
+const kStats = Symbol('stats')
- // 11. Let serializedSlicedLength be slicedBlob’s size, serialized and isomorphic encoded.
- const serializedSlicedLength = isomorphicEncode(`${slicedBlob.size}`)
+class PoolBase extends DispatcherBase {
+ constructor () {
+ super()
- // 12. Let contentRange be the result of invoking build a content range given rangeStart,
- // rangeEnd, and fullLength.
- const contentRange = buildContentRange(rangeStart, rangeEnd, fullLength)
+ this[kQueue] = new FixedQueue()
+ this[kClients] = []
+ this[kQueued] = 0
- // 13. Set response’s status to 206.
- response.status = 206
+ const pool = this
- // 14. Set response’s status message to `Partial Content`.
- response.statusText = 'Partial Content'
+ this[kOnDrain] = function onDrain (origin, targets) {
+ const queue = pool[kQueue]
- // 15. Set response’s header list to « (`Content-Length`, serializedSlicedLength),
- // (`Content-Type`, type), (`Content-Range`, contentRange) ».
- response.headersList.set('content-length', serializedSlicedLength, true)
- response.headersList.set('content-type', type, true)
- response.headersList.set('content-range', contentRange, true)
+ let needDrain = false
+
+ while (!needDrain) {
+ const item = queue.shift()
+ if (!item) {
+ break
+ }
+ pool[kQueued]--
+ needDrain = !this.dispatch(item.opts, item.handler)
}
- // 10. Return response.
- return Promise.resolve(response)
- }
- case 'data:': {
- // 1. Let dataURLStruct be the result of running the
- // data: URL processor on request’s current URL.
- const currentURL = requestCurrentURL(request)
- const dataURLStruct = dataURLProcessor(currentURL)
+ this[kNeedDrain] = needDrain
- // 2. If dataURLStruct is failure, then return a
- // network error.
- if (dataURLStruct === 'failure') {
- return Promise.resolve(makeNetworkError('failed to fetch the data URL'))
+ if (!this[kNeedDrain] && pool[kNeedDrain]) {
+ pool[kNeedDrain] = false
+ pool.emit('drain', origin, [pool, ...targets])
}
- // 3. Let mimeType be dataURLStruct’s MIME type, serialized.
- const mimeType = serializeAMimeType(dataURLStruct.mimeType)
-
- // 4. Return a response whose status message is `OK`,
- // header list is « (`Content-Type`, mimeType) »,
- // and body is dataURLStruct’s body as a body.
- return Promise.resolve(makeResponse({
- statusText: 'OK',
- headersList: [
- ['content-type', { name: 'Content-Type', value: mimeType }]
- ],
- body: safelyExtractBody(dataURLStruct.body)[0]
- }))
+ if (pool[kClosedResolve] && queue.isEmpty()) {
+ Promise
+ .all(pool[kClients].map(c => c.close()))
+ .then(pool[kClosedResolve])
+ }
}
- case 'file:': {
- // For now, unfortunate as it is, file URLs are left as an exercise for the reader.
- // When in doubt, return a network error.
- return Promise.resolve(makeNetworkError('not implemented... yet...'))
+
+ this[kOnConnect] = (origin, targets) => {
+ pool.emit('connect', origin, [pool, ...targets])
}
- case 'http:':
- case 'https:': {
- // Return the result of running HTTP fetch given fetchParams.
- return httpFetch(fetchParams)
- .catch((err) => makeNetworkError(err))
+ this[kOnDisconnect] = (origin, targets, err) => {
+ pool.emit('disconnect', origin, [pool, ...targets], err)
}
- default: {
- return Promise.resolve(makeNetworkError('unknown scheme'))
+
+ this[kOnConnectionError] = (origin, targets, err) => {
+ pool.emit('connectionError', origin, [pool, ...targets], err)
}
+
+ this[kStats] = new PoolStats(this)
}
-}
-// https://fetch.spec.whatwg.org/#finalize-response
-function finalizeResponse (fetchParams, response) {
- // 1. Set fetchParams’s request’s done flag.
- fetchParams.request.done = true
+ get [kBusy] () {
+ return this[kNeedDrain]
+ }
- // 2, If fetchParams’s process response done is not null, then queue a fetch
- // task to run fetchParams’s process response done given response, with
- // fetchParams’s task destination.
- if (fetchParams.processResponseDone != null) {
- queueMicrotask(() => fetchParams.processResponseDone(response))
+ get [kConnected] () {
+ return this[kClients].filter(client => client[kConnected]).length
}
-}
-// https://fetch.spec.whatwg.org/#fetch-finale
-function fetchFinale (fetchParams, response) {
- // 1. Let timingInfo be fetchParams’s timing info.
- let timingInfo = fetchParams.timingInfo
+ get [kFree] () {
+ return this[kClients].filter(client => client[kConnected] && !client[kNeedDrain]).length
+ }
- // 2. If response is not a network error and fetchParams’s request’s client is a secure context,
- // then set timingInfo’s server-timing headers to the result of getting, decoding, and splitting
- // `Server-Timing` from response’s internal response’s header list.
- // TODO
+ get [kPending] () {
+ let ret = this[kQueued]
+ for (const { [kPending]: pending } of this[kClients]) {
+ ret += pending
+ }
+ return ret
+ }
- // 3. Let processResponseEndOfBody be the following steps:
- const processResponseEndOfBody = () => {
- // 1. Let unsafeEndTime be the unsafe shared current time.
- const unsafeEndTime = Date.now() // ?
+ get [kRunning] () {
+ let ret = 0
+ for (const { [kRunning]: running } of this[kClients]) {
+ ret += running
+ }
+ return ret
+ }
- // 2. If fetchParams’s request’s destination is "document", then set fetchParams’s controller’s
- // full timing info to fetchParams’s timing info.
- if (fetchParams.request.destination === 'document') {
- fetchParams.controller.fullTimingInfo = timingInfo
+ get [kSize] () {
+ let ret = this[kQueued]
+ for (const { [kSize]: size } of this[kClients]) {
+ ret += size
}
+ return ret
+ }
- // 3. Set fetchParams’s controller’s report timing steps to the following steps given a global object global:
- fetchParams.controller.reportTimingSteps = () => {
- // 1. If fetchParams’s request’s URL’s scheme is not an HTTP(S) scheme, then return.
- if (fetchParams.request.url.protocol !== 'https:') {
- return
- }
+ get stats () {
+ return this[kStats]
+ }
- // 2. Set timingInfo’s end time to the relative high resolution time given unsafeEndTime and global.
- timingInfo.endTime = unsafeEndTime
+ async [kClose] () {
+ if (this[kQueue].isEmpty()) {
+ await Promise.all(this[kClients].map(c => c.close()))
+ } else {
+ await new Promise((resolve) => {
+ this[kClosedResolve] = resolve
+ })
+ }
+ }
- // 3. Let cacheState be response’s cache state.
- let cacheState = response.cacheState
+ async [kDestroy] (err) {
+ while (true) {
+ const item = this[kQueue].shift()
+ if (!item) {
+ break
+ }
+ item.handler.onError(err)
+ }
- // 4. Let bodyInfo be response’s body info.
- const bodyInfo = response.bodyInfo
+ await Promise.all(this[kClients].map(c => c.destroy(err)))
+ }
- // 5. If response’s timing allow passed flag is not set, then set timingInfo to the result of creating an
- // opaque timing info for timingInfo and set cacheState to the empty string.
- if (!response.timingAllowPassed) {
- timingInfo = createOpaqueTimingInfo(timingInfo)
+ [kDispatch] (opts, handler) {
+ const dispatcher = this[kGetDispatcher]()
- cacheState = ''
- }
+ if (!dispatcher) {
+ this[kNeedDrain] = true
+ this[kQueue].push({ opts, handler })
+ this[kQueued]++
+ } else if (!dispatcher.dispatch(opts, handler)) {
+ dispatcher[kNeedDrain] = true
+ this[kNeedDrain] = !this[kGetDispatcher]()
+ }
- // 6. Let responseStatus be 0.
- let responseStatus = 0
+ return !this[kNeedDrain]
+ }
- // 7. If fetchParams’s request’s mode is not "navigate" or response’s has-cross-origin-redirects is false:
- if (fetchParams.request.mode !== 'navigator' || !response.hasCrossOriginRedirects) {
- // 1. Set responseStatus to response’s status.
- responseStatus = response.status
+ [kAddClient] (client) {
+ client
+ .on('drain', this[kOnDrain])
+ .on('connect', this[kOnConnect])
+ .on('disconnect', this[kOnDisconnect])
+ .on('connectionError', this[kOnConnectionError])
- // 2. Let mimeType be the result of extracting a MIME type from response’s header list.
- const mimeType = extractMimeType(response.headersList)
+ this[kClients].push(client)
- // 3. If mimeType is not failure, then set bodyInfo’s content type to the result of minimizing a supported MIME type given mimeType.
- if (mimeType !== 'failure') {
- bodyInfo.contentType = minimizeSupportedMimeType(mimeType)
+ if (this[kNeedDrain]) {
+ queueMicrotask(() => {
+ if (this[kNeedDrain]) {
+ this[kOnDrain](client[kUrl], [this, client])
}
- }
-
- // 8. If fetchParams’s request’s initiator type is non-null, then mark resource timing given timingInfo,
- // fetchParams’s request’s URL, fetchParams’s request’s initiator type, global, cacheState, bodyInfo,
- // and responseStatus.
- if (fetchParams.request.initiatorType != null) {
- // TODO: update markresourcetiming
- markResourceTiming(timingInfo, fetchParams.request.url.href, fetchParams.request.initiatorType, globalThis, cacheState, bodyInfo, responseStatus)
- }
+ })
}
- // 4. Let processResponseEndOfBodyTask be the following steps:
- const processResponseEndOfBodyTask = () => {
- // 1. Set fetchParams’s request’s done flag.
- fetchParams.request.done = true
+ return this
+ }
- // 2. If fetchParams’s process response end-of-body is non-null, then run fetchParams’s process
- // response end-of-body given response.
- if (fetchParams.processResponseEndOfBody != null) {
- queueMicrotask(() => fetchParams.processResponseEndOfBody(response))
+ [kRemoveClient] (client) {
+ client.close(() => {
+ const idx = this[kClients].indexOf(client)
+ if (idx !== -1) {
+ this[kClients].splice(idx, 1)
}
+ })
- // 3. If fetchParams’s request’s initiator type is non-null and fetchParams’s request’s client’s
- // global object is fetchParams’s task destination, then run fetchParams’s controller’s report
- // timing steps given fetchParams’s request’s client’s global object.
- if (fetchParams.request.initiatorType != null) {
- fetchParams.controller.reportTimingSteps()
- }
- }
+ this[kNeedDrain] = this[kClients].some(dispatcher => (
+ !dispatcher[kNeedDrain] &&
+ dispatcher.closed !== true &&
+ dispatcher.destroyed !== true
+ ))
+ }
+}
- // 5. Queue a fetch task to run processResponseEndOfBodyTask with fetchParams’s task destination
- queueMicrotask(() => processResponseEndOfBodyTask())
+module.exports = {
+ PoolBase,
+ kClients,
+ kNeedDrain,
+ kAddClient,
+ kRemoveClient,
+ kGetDispatcher
+}
+
+
+/***/ }),
+
+/***/ 3246:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+const { kFree, kConnected, kPending, kQueued, kRunning, kSize } = __nccwpck_require__(6443)
+const kPool = Symbol('pool')
+
+class PoolStats {
+ constructor (pool) {
+ this[kPool] = pool
}
- // 4. If fetchParams’s process response is non-null, then queue a fetch task to run fetchParams’s
- // process response given response, with fetchParams’s task destination.
- if (fetchParams.processResponse != null) {
- queueMicrotask(() => {
- fetchParams.processResponse(response)
- fetchParams.processResponse = null
- })
+ get connected () {
+ return this[kPool][kConnected]
}
- // 5. Let internalResponse be response, if response is a network error; otherwise response’s internal response.
- const internalResponse = response.type === 'error' ? response : (response.internalResponse ?? response)
+ get free () {
+ return this[kPool][kFree]
+ }
- // 6. If internalResponse’s body is null, then run processResponseEndOfBody.
- // 7. Otherwise:
- if (internalResponse.body == null) {
- processResponseEndOfBody()
- } else {
- // mcollina: all the following steps of the specs are skipped.
- // The internal transform stream is not needed.
- // See https://github.com/nodejs/undici/pull/3093#issuecomment-2050198541
+ get pending () {
+ return this[kPool][kPending]
+ }
- // 1. Let transformStream be a new TransformStream.
- // 2. Let identityTransformAlgorithm be an algorithm which, given chunk, enqueues chunk in transformStream.
- // 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm and flushAlgorithm
- // set to processResponseEndOfBody.
- // 4. Set internalResponse’s body’s stream to the result of internalResponse’s body’s stream piped through transformStream.
+ get queued () {
+ return this[kPool][kQueued]
+ }
- finished(internalResponse.body.stream, () => {
- processResponseEndOfBody()
- })
+ get running () {
+ return this[kPool][kRunning]
+ }
+
+ get size () {
+ return this[kPool][kSize]
}
}
-// https://fetch.spec.whatwg.org/#http-fetch
-async function httpFetch (fetchParams) {
- // 1. Let request be fetchParams’s request.
- const request = fetchParams.request
+module.exports = PoolStats
- // 2. Let response be null.
- let response = null
- // 3. Let actualResponse be null.
- let actualResponse = null
+/***/ }),
- // 4. Let timingInfo be fetchParams’s timing info.
- const timingInfo = fetchParams.timingInfo
+/***/ 628:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 5. If request’s service-workers mode is "all", then:
- if (request.serviceWorkers === 'all') {
- // TODO
- }
- // 6. If response is null, then:
- if (response === null) {
- // 1. If makeCORSPreflight is true and one of these conditions is true:
- // TODO
- // 2. If request’s redirect mode is "follow", then set request’s
- // service-workers mode to "none".
- if (request.redirect === 'follow') {
- request.serviceWorkers = 'none'
+const {
+ PoolBase,
+ kClients,
+ kNeedDrain,
+ kAddClient,
+ kGetDispatcher
+} = __nccwpck_require__(2128)
+const Client = __nccwpck_require__(3701)
+const {
+ InvalidArgumentError
+} = __nccwpck_require__(8707)
+const util = __nccwpck_require__(3440)
+const { kUrl, kInterceptors } = __nccwpck_require__(6443)
+const buildConnector = __nccwpck_require__(9136)
+
+const kOptions = Symbol('options')
+const kConnections = Symbol('connections')
+const kFactory = Symbol('factory')
+
+function defaultFactory (origin, opts) {
+ return new Client(origin, opts)
+}
+
+class Pool extends PoolBase {
+ constructor (origin, {
+ connections,
+ factory = defaultFactory,
+ connect,
+ connectTimeout,
+ tls,
+ maxCachedSessions,
+ socketPath,
+ autoSelectFamily,
+ autoSelectFamilyAttemptTimeout,
+ allowH2,
+ ...options
+ } = {}) {
+ super()
+
+ if (connections != null && (!Number.isFinite(connections) || connections < 0)) {
+ throw new InvalidArgumentError('invalid connections')
}
- // 3. Set response and actualResponse to the result of running
- // HTTP-network-or-cache fetch given fetchParams.
- actualResponse = response = await httpNetworkOrCacheFetch(fetchParams)
+ if (typeof factory !== 'function') {
+ throw new InvalidArgumentError('factory must be a function.')
+ }
- // 4. If request’s response tainting is "cors" and a CORS check
- // for request and response returns failure, then return a network error.
- if (
- request.responseTainting === 'cors' &&
- corsCheck(request, response) === 'failure'
- ) {
- return makeNetworkError('cors failure')
+ if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {
+ throw new InvalidArgumentError('connect must be a function or an object')
}
- // 5. If the TAO check for request and response returns failure, then set
- // request’s timing allow failed flag.
- if (TAOCheck(request, response) === 'failure') {
- request.timingAllowFailed = true
+ if (typeof connect !== 'function') {
+ connect = buildConnector({
+ ...tls,
+ maxCachedSessions,
+ allowH2,
+ socketPath,
+ timeout: connectTimeout,
+ ...(autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined),
+ ...connect
+ })
}
- }
- // 7. If either request’s response tainting or response’s type
- // is "opaque", and the cross-origin resource policy check with
- // request’s origin, request’s client, request’s destination,
- // and actualResponse returns blocked, then return a network error.
- if (
- (request.responseTainting === 'opaque' || response.type === 'opaque') &&
- crossOriginResourcePolicyCheck(
- request.origin,
- request.client,
- request.destination,
- actualResponse
- ) === 'blocked'
- ) {
- return makeNetworkError('blocked')
+ this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool)
+ ? options.interceptors.Pool
+ : []
+ this[kConnections] = connections || null
+ this[kUrl] = util.parseOrigin(origin)
+ this[kOptions] = { ...util.deepClone(options), connect, allowH2 }
+ this[kOptions].interceptors = options.interceptors
+ ? { ...options.interceptors }
+ : undefined
+ this[kFactory] = factory
+
+ this.on('connectionError', (origin, targets, error) => {
+ // If a connection error occurs, we remove the client from the pool,
+ // and emit a connectionError event. They will not be re-used.
+ // Fixes https://github.com/nodejs/undici/issues/3895
+ for (const target of targets) {
+ // Do not use kRemoveClient here, as it will close the client,
+ // but the client cannot be closed in this state.
+ const idx = this[kClients].indexOf(target)
+ if (idx !== -1) {
+ this[kClients].splice(idx, 1)
+ }
+ }
+ })
}
- // 8. If actualResponse’s status is a redirect status, then:
- if (redirectStatusSet.has(actualResponse.status)) {
- // 1. If actualResponse’s status is not 303, request’s body is not null,
- // and the connection uses HTTP/2, then user agents may, and are even
- // encouraged to, transmit an RST_STREAM frame.
- // See, https://github.com/whatwg/fetch/issues/1288
- if (request.redirect !== 'manual') {
- fetchParams.controller.connection.destroy(undefined, false)
+ [kGetDispatcher] () {
+ for (const client of this[kClients]) {
+ if (!client[kNeedDrain]) {
+ return client
+ }
}
- // 2. Switch on request’s redirect mode:
- if (request.redirect === 'error') {
- // Set response to a network error.
- response = makeNetworkError('unexpected redirect')
- } else if (request.redirect === 'manual') {
- // Set response to an opaque-redirect filtered response whose internal
- // response is actualResponse.
- // NOTE(spec): On the web this would return an `opaqueredirect` response,
- // but that doesn't make sense server side.
- // See https://github.com/nodejs/undici/issues/1193.
- response = actualResponse
- } else if (request.redirect === 'follow') {
- // Set response to the result of running HTTP-redirect fetch given
- // fetchParams and response.
- response = await httpRedirectFetch(fetchParams, response)
- } else {
- assert(false)
+ if (!this[kConnections] || this[kClients].length < this[kConnections]) {
+ const dispatcher = this[kFactory](this[kUrl], this[kOptions])
+ this[kAddClient](dispatcher)
+ return dispatcher
}
}
+}
- // 9. Set response’s timing info to timingInfo.
- response.timingInfo = timingInfo
+module.exports = Pool
- // 10. Return response.
- return response
-}
-// https://fetch.spec.whatwg.org/#http-redirect-fetch
-function httpRedirectFetch (fetchParams, response) {
- // 1. Let request be fetchParams’s request.
- const request = fetchParams.request
+/***/ }),
- // 2. Let actualResponse be response, if response is not a filtered response,
- // and response’s internal response otherwise.
- const actualResponse = response.internalResponse
- ? response.internalResponse
- : response
+/***/ 6672:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 3. Let locationURL be actualResponse’s location URL given request’s current
- // URL’s fragment.
- let locationURL
- try {
- locationURL = responseLocationURL(
- actualResponse,
- requestCurrentURL(request).hash
- )
- // 4. If locationURL is null, then return response.
- if (locationURL == null) {
- return response
- }
- } catch (err) {
- // 5. If locationURL is failure, then return a network error.
- return Promise.resolve(makeNetworkError(err))
- }
+const { kProxy, kClose, kDestroy, kDispatch, kInterceptors } = __nccwpck_require__(6443)
+const { URL } = __nccwpck_require__(3136)
+const Agent = __nccwpck_require__(7405)
+const Pool = __nccwpck_require__(628)
+const DispatcherBase = __nccwpck_require__(1841)
+const { InvalidArgumentError, RequestAbortedError, SecureProxyConnectionError } = __nccwpck_require__(8707)
+const buildConnector = __nccwpck_require__(9136)
+const Client = __nccwpck_require__(3701)
- // 6. If locationURL’s scheme is not an HTTP(S) scheme, then return a network
- // error.
- if (!urlIsHttpHttpsScheme(locationURL)) {
- return Promise.resolve(makeNetworkError('URL scheme must be a HTTP(S) scheme'))
- }
+const kAgent = Symbol('proxy agent')
+const kClient = Symbol('proxy client')
+const kProxyHeaders = Symbol('proxy headers')
+const kRequestTls = Symbol('request tls settings')
+const kProxyTls = Symbol('proxy tls settings')
+const kConnectEndpoint = Symbol('connect endpoint function')
+const kTunnelProxy = Symbol('tunnel proxy')
- // 7. If request’s redirect count is 20, then return a network error.
- if (request.redirectCount === 20) {
- return Promise.resolve(makeNetworkError('redirect count exceeded'))
- }
+function defaultProtocolPort (protocol) {
+ return protocol === 'https:' ? 443 : 80
+}
- // 8. Increase request’s redirect count by 1.
- request.redirectCount += 1
+function defaultFactory (origin, opts) {
+ return new Pool(origin, opts)
+}
- // 9. If request’s mode is "cors", locationURL includes credentials, and
- // request’s origin is not same origin with locationURL’s origin, then return
- // a network error.
- if (
- request.mode === 'cors' &&
- (locationURL.username || locationURL.password) &&
- !sameOrigin(request, locationURL)
- ) {
- return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"'))
- }
+const noop = () => {}
- // 10. If request’s response tainting is "cors" and locationURL includes
- // credentials, then return a network error.
- if (
- request.responseTainting === 'cors' &&
- (locationURL.username || locationURL.password)
- ) {
- return Promise.resolve(makeNetworkError(
- 'URL cannot contain credentials for request mode "cors"'
- ))
+function defaultAgentFactory (origin, opts) {
+ if (opts.connections === 1) {
+ return new Client(origin, opts)
}
+ return new Pool(origin, opts)
+}
- // 11. If actualResponse’s status is not 303, request’s body is non-null,
- // and request’s body’s source is null, then return a network error.
- if (
- actualResponse.status !== 303 &&
- request.body != null &&
- request.body.source == null
- ) {
- return Promise.resolve(makeNetworkError())
- }
+class Http1ProxyWrapper extends DispatcherBase {
+ #client
- // 12. If one of the following is true
- // - actualResponse’s status is 301 or 302 and request’s method is `POST`
- // - actualResponse’s status is 303 and request’s method is not `GET` or `HEAD`
- if (
- ([301, 302].includes(actualResponse.status) && request.method === 'POST') ||
- (actualResponse.status === 303 &&
- !GET_OR_HEAD.includes(request.method))
- ) {
- // then:
- // 1. Set request’s method to `GET` and request’s body to null.
- request.method = 'GET'
- request.body = null
+ constructor (proxyUrl, { headers = {}, connect, factory }) {
+ super()
+ if (!proxyUrl) {
+ throw new InvalidArgumentError('Proxy URL is mandatory')
+ }
- // 2. For each headerName of request-body-header name, delete headerName from
- // request’s header list.
- for (const headerName of requestBodyHeader) {
- request.headersList.delete(headerName)
+ this[kProxyHeaders] = headers
+ if (factory) {
+ this.#client = factory(proxyUrl, { connect })
+ } else {
+ this.#client = new Client(proxyUrl, { connect })
}
}
- // 13. If request’s current URL’s origin is not same origin with locationURL’s
- // origin, then for each headerName of CORS non-wildcard request-header name,
- // delete headerName from request’s header list.
- if (!sameOrigin(requestCurrentURL(request), locationURL)) {
- // https://fetch.spec.whatwg.org/#cors-non-wildcard-request-header-name
- request.headersList.delete('authorization', true)
+ [kDispatch] (opts, handler) {
+ const onHeaders = handler.onHeaders
+ handler.onHeaders = function (statusCode, data, resume) {
+ if (statusCode === 407) {
+ if (typeof handler.onError === 'function') {
+ handler.onError(new InvalidArgumentError('Proxy Authentication Required (407)'))
+ }
+ return
+ }
+ if (onHeaders) onHeaders.call(this, statusCode, data, resume)
+ }
- // https://fetch.spec.whatwg.org/#authentication-entries
- request.headersList.delete('proxy-authorization', true)
+ // Rewrite request as an HTTP1 Proxy request, without tunneling.
+ const {
+ origin,
+ path = '/',
+ headers = {}
+ } = opts
- // "Cookie" and "Host" are forbidden request-headers, which undici doesn't implement.
- request.headersList.delete('cookie', true)
- request.headersList.delete('host', true)
- }
+ opts.path = origin + path
- // 14. If request’s body is non-null, then set request’s body to the first return
- // value of safely extracting request’s body’s source.
- if (request.body != null) {
- assert(request.body.source != null)
- request.body = safelyExtractBody(request.body.source)[0]
+ if (!('host' in headers) && !('Host' in headers)) {
+ const { host } = new URL(origin)
+ headers.host = host
+ }
+ opts.headers = { ...this[kProxyHeaders], ...headers }
+
+ return this.#client[kDispatch](opts, handler)
}
- // 15. Let timingInfo be fetchParams’s timing info.
- const timingInfo = fetchParams.timingInfo
+ async [kClose] () {
+ return this.#client.close()
+ }
- // 16. Set timingInfo’s redirect end time and post-redirect start time to the
- // coarsened shared current time given fetchParams’s cross-origin isolated
- // capability.
- timingInfo.redirectEndTime = timingInfo.postRedirectStartTime =
- coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability)
+ async [kDestroy] (err) {
+ return this.#client.destroy(err)
+ }
+}
- // 17. If timingInfo’s redirect start time is 0, then set timingInfo’s
- // redirect start time to timingInfo’s start time.
- if (timingInfo.redirectStartTime === 0) {
- timingInfo.redirectStartTime = timingInfo.startTime
- }
-
- // 18. Append locationURL to request’s URL list.
- request.urlList.push(locationURL)
-
- // 19. Invoke set request’s referrer policy on redirect on request and
- // actualResponse.
- setRequestReferrerPolicyOnRedirect(request, actualResponse)
+class ProxyAgent extends DispatcherBase {
+ constructor (opts) {
+ super()
- // 20. Return the result of running main fetch given fetchParams and true.
- return mainFetch(fetchParams, true)
-}
+ if (!opts || (typeof opts === 'object' && !(opts instanceof URL) && !opts.uri)) {
+ throw new InvalidArgumentError('Proxy uri is mandatory')
+ }
-// https://fetch.spec.whatwg.org/#http-network-or-cache-fetch
-async function httpNetworkOrCacheFetch (
- fetchParams,
- isAuthenticationFetch = false,
- isNewConnectionFetch = false
-) {
- // 1. Let request be fetchParams’s request.
- const request = fetchParams.request
+ const { clientFactory = defaultFactory } = opts
+ if (typeof clientFactory !== 'function') {
+ throw new InvalidArgumentError('Proxy opts.clientFactory must be a function.')
+ }
- // 2. Let httpFetchParams be null.
- let httpFetchParams = null
+ const { proxyTunnel = true } = opts
- // 3. Let httpRequest be null.
- let httpRequest = null
+ const url = this.#getUrl(opts)
+ const { href, origin, port, protocol, username, password, hostname: proxyHostname } = url
- // 4. Let response be null.
- let response = null
+ this[kProxy] = { uri: href, protocol }
+ this[kInterceptors] = opts.interceptors?.ProxyAgent && Array.isArray(opts.interceptors.ProxyAgent)
+ ? opts.interceptors.ProxyAgent
+ : []
+ this[kRequestTls] = opts.requestTls
+ this[kProxyTls] = opts.proxyTls
+ this[kProxyHeaders] = opts.headers || {}
+ this[kTunnelProxy] = proxyTunnel
- // 5. Let storedResponse be null.
- // TODO: cache
+ if (opts.auth && opts.token) {
+ throw new InvalidArgumentError('opts.auth cannot be used in combination with opts.token')
+ } else if (opts.auth) {
+ /* @deprecated in favour of opts.token */
+ this[kProxyHeaders]['proxy-authorization'] = `Basic ${opts.auth}`
+ } else if (opts.token) {
+ this[kProxyHeaders]['proxy-authorization'] = opts.token
+ } else if (username && password) {
+ this[kProxyHeaders]['proxy-authorization'] = `Basic ${Buffer.from(`${decodeURIComponent(username)}:${decodeURIComponent(password)}`).toString('base64')}`
+ }
- // 6. Let httpCache be null.
- const httpCache = null
+ const connect = buildConnector({ ...opts.proxyTls })
+ this[kConnectEndpoint] = buildConnector({ ...opts.requestTls })
- // 7. Let the revalidatingFlag be unset.
- const revalidatingFlag = false
+ const agentFactory = opts.factory || defaultAgentFactory
+ const factory = (origin, options) => {
+ const { protocol } = new URL(origin)
+ if (!this[kTunnelProxy] && protocol === 'http:' && this[kProxy].protocol === 'http:') {
+ return new Http1ProxyWrapper(this[kProxy].uri, {
+ headers: this[kProxyHeaders],
+ connect,
+ factory: agentFactory
+ })
+ }
+ return agentFactory(origin, options)
+ }
+ this[kClient] = clientFactory(url, { connect })
+ this[kAgent] = new Agent({
+ ...opts,
+ factory,
+ connect: async (opts, callback) => {
+ let requestedPath = opts.host
+ if (!opts.port) {
+ requestedPath += `:${defaultProtocolPort(opts.protocol)}`
+ }
+ try {
+ const { socket, statusCode } = await this[kClient].connect({
+ origin,
+ port,
+ path: requestedPath,
+ signal: opts.signal,
+ headers: {
+ ...this[kProxyHeaders],
+ host: opts.host
+ },
+ servername: this[kProxyTls]?.servername || proxyHostname
+ })
+ if (statusCode !== 200) {
+ socket.on('error', noop).destroy()
+ callback(new RequestAbortedError(`Proxy response (${statusCode}) !== 200 when HTTP Tunneling`))
+ }
+ if (opts.protocol !== 'https:') {
+ callback(null, socket)
+ return
+ }
+ let servername
+ if (this[kRequestTls]) {
+ servername = this[kRequestTls].servername
+ } else {
+ servername = opts.servername
+ }
+ this[kConnectEndpoint]({ ...opts, servername, httpSocket: socket }, callback)
+ } catch (err) {
+ if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') {
+ // Throw a custom error to avoid loop in client.js#connect
+ callback(new SecureProxyConnectionError(err))
+ } else {
+ callback(err)
+ }
+ }
+ }
+ })
+ }
- // 8. Run these steps, but abort when the ongoing fetch is terminated:
+ dispatch (opts, handler) {
+ const headers = buildHeaders(opts.headers)
+ throwIfProxyAuthIsSent(headers)
- // 1. If request’s window is "no-window" and request’s redirect mode is
- // "error", then set httpFetchParams to fetchParams and httpRequest to
- // request.
- if (request.window === 'no-window' && request.redirect === 'error') {
- httpFetchParams = fetchParams
- httpRequest = request
- } else {
- // Otherwise:
+ if (headers && !('host' in headers) && !('Host' in headers)) {
+ const { host } = new URL(opts.origin)
+ headers.host = host
+ }
- // 1. Set httpRequest to a clone of request.
- httpRequest = cloneRequest(request)
+ return this[kAgent].dispatch(
+ {
+ ...opts,
+ headers
+ },
+ handler
+ )
+ }
- // 2. Set httpFetchParams to a copy of fetchParams.
- httpFetchParams = { ...fetchParams }
+ /**
+ * @param {import('../types/proxy-agent').ProxyAgent.Options | string | URL} opts
+ * @returns {URL}
+ */
+ #getUrl (opts) {
+ if (typeof opts === 'string') {
+ return new URL(opts)
+ } else if (opts instanceof URL) {
+ return opts
+ } else {
+ return new URL(opts.uri)
+ }
+ }
- // 3. Set httpFetchParams’s request to httpRequest.
- httpFetchParams.request = httpRequest
+ async [kClose] () {
+ await this[kAgent].close()
+ await this[kClient].close()
}
- // 3. Let includeCredentials be true if one of
- const includeCredentials =
- request.credentials === 'include' ||
- (request.credentials === 'same-origin' &&
- request.responseTainting === 'basic')
+ async [kDestroy] () {
+ await this[kAgent].destroy()
+ await this[kClient].destroy()
+ }
+}
- // 4. Let contentLength be httpRequest’s body’s length, if httpRequest’s
- // body is non-null; otherwise null.
- const contentLength = httpRequest.body ? httpRequest.body.length : null
+/**
+ * @param {string[] | Record} headers
+ * @returns {Record}
+ */
+function buildHeaders (headers) {
+ // When using undici.fetch, the headers list is stored
+ // as an array.
+ if (Array.isArray(headers)) {
+ /** @type {Record} */
+ const headersPair = {}
- // 5. Let contentLengthHeaderValue be null.
- let contentLengthHeaderValue = null
+ for (let i = 0; i < headers.length; i += 2) {
+ headersPair[headers[i]] = headers[i + 1]
+ }
- // 6. If httpRequest’s body is null and httpRequest’s method is `POST` or
- // `PUT`, then set contentLengthHeaderValue to `0`.
- if (
- httpRequest.body == null &&
- ['POST', 'PUT'].includes(httpRequest.method)
- ) {
- contentLengthHeaderValue = '0'
+ return headersPair
}
- // 7. If contentLength is non-null, then set contentLengthHeaderValue to
- // contentLength, serialized and isomorphic encoded.
- if (contentLength != null) {
- contentLengthHeaderValue = isomorphicEncode(`${contentLength}`)
- }
+ return headers
+}
- // 8. If contentLengthHeaderValue is non-null, then append
- // `Content-Length`/contentLengthHeaderValue to httpRequest’s header
- // list.
- if (contentLengthHeaderValue != null) {
- httpRequest.headersList.append('content-length', contentLengthHeaderValue, true)
+/**
+ * @param {Record} headers
+ *
+ * Previous versions of ProxyAgent suggests the Proxy-Authorization in request headers
+ * Nevertheless, it was changed and to avoid a security vulnerability by end users
+ * this check was created.
+ * It should be removed in the next major version for performance reasons
+ */
+function throwIfProxyAuthIsSent (headers) {
+ const existProxyAuth = headers && Object.keys(headers)
+ .find((key) => key.toLowerCase() === 'proxy-authorization')
+ if (existProxyAuth) {
+ throw new InvalidArgumentError('Proxy-Authorization should be sent in ProxyAgent constructor')
}
+}
- // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`,
- // contentLengthHeaderValue) to httpRequest’s header list.
+module.exports = ProxyAgent
- // 10. If contentLength is non-null and httpRequest’s keepalive is true,
- // then:
- if (contentLength != null && httpRequest.keepalive) {
- // NOTE: keepalive is a noop outside of browser context.
- }
- // 11. If httpRequest’s referrer is a URL, then append
- // `Referer`/httpRequest’s referrer, serialized and isomorphic encoded,
- // to httpRequest’s header list.
- if (httpRequest.referrer instanceof URL) {
- httpRequest.headersList.append('referer', isomorphicEncode(httpRequest.referrer.href), true)
- }
+/***/ }),
- // 12. Append a request `Origin` header for httpRequest.
- appendRequestOriginHeader(httpRequest)
+/***/ 50:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 13. Append the Fetch metadata headers for httpRequest. [FETCH-METADATA]
- appendFetchMetadata(httpRequest)
- // 14. If httpRequest’s header list does not contain `User-Agent`, then
- // user agents should append `User-Agent`/default `User-Agent` value to
- // httpRequest’s header list.
- if (!httpRequest.headersList.contains('user-agent', true)) {
- httpRequest.headersList.append('user-agent', defaultUserAgent)
- }
- // 15. If httpRequest’s cache mode is "default" and httpRequest’s header
- // list contains `If-Modified-Since`, `If-None-Match`,
- // `If-Unmodified-Since`, `If-Match`, or `If-Range`, then set
- // httpRequest’s cache mode to "no-store".
- if (
- httpRequest.cache === 'default' &&
- (httpRequest.headersList.contains('if-modified-since', true) ||
- httpRequest.headersList.contains('if-none-match', true) ||
- httpRequest.headersList.contains('if-unmodified-since', true) ||
- httpRequest.headersList.contains('if-match', true) ||
- httpRequest.headersList.contains('if-range', true))
- ) {
- httpRequest.cache = 'no-store'
- }
+const Dispatcher = __nccwpck_require__(883)
+const RetryHandler = __nccwpck_require__(7816)
- // 16. If httpRequest’s cache mode is "no-cache", httpRequest’s prevent
- // no-cache cache-control header modification flag is unset, and
- // httpRequest’s header list does not contain `Cache-Control`, then append
- // `Cache-Control`/`max-age=0` to httpRequest’s header list.
- if (
- httpRequest.cache === 'no-cache' &&
- !httpRequest.preventNoCacheCacheControlHeaderModification &&
- !httpRequest.headersList.contains('cache-control', true)
- ) {
- httpRequest.headersList.append('cache-control', 'max-age=0', true)
+class RetryAgent extends Dispatcher {
+ #agent = null
+ #options = null
+ constructor (agent, options = {}) {
+ super(options)
+ this.#agent = agent
+ this.#options = options
}
- // 17. If httpRequest’s cache mode is "no-store" or "reload", then:
- if (httpRequest.cache === 'no-store' || httpRequest.cache === 'reload') {
- // 1. If httpRequest’s header list does not contain `Pragma`, then append
- // `Pragma`/`no-cache` to httpRequest’s header list.
- if (!httpRequest.headersList.contains('pragma', true)) {
- httpRequest.headersList.append('pragma', 'no-cache', true)
- }
-
- // 2. If httpRequest’s header list does not contain `Cache-Control`,
- // then append `Cache-Control`/`no-cache` to httpRequest’s header list.
- if (!httpRequest.headersList.contains('cache-control', true)) {
- httpRequest.headersList.append('cache-control', 'no-cache', true)
- }
+ dispatch (opts, handler) {
+ const retry = new RetryHandler({
+ ...opts,
+ retryOptions: this.#options
+ }, {
+ dispatch: this.#agent.dispatch.bind(this.#agent),
+ handler
+ })
+ return this.#agent.dispatch(opts, retry)
}
- // 18. If httpRequest’s header list contains `Range`, then append
- // `Accept-Encoding`/`identity` to httpRequest’s header list.
- if (httpRequest.headersList.contains('range', true)) {
- httpRequest.headersList.append('accept-encoding', 'identity', true)
+ close () {
+ return this.#agent.close()
}
- // 19. Modify httpRequest’s header list per HTTP. Do not append a given
- // header if httpRequest’s header list contains that header’s name.
- // TODO: https://github.com/whatwg/fetch/issues/1285#issuecomment-896560129
- if (!httpRequest.headersList.contains('accept-encoding', true)) {
- if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) {
- httpRequest.headersList.append('accept-encoding', 'br, gzip, deflate', true)
- } else {
- httpRequest.headersList.append('accept-encoding', 'gzip, deflate', true)
- }
+ destroy () {
+ return this.#agent.destroy()
}
+}
- httpRequest.headersList.delete('host', true)
+module.exports = RetryAgent
- // 20. If includeCredentials is true, then:
- if (includeCredentials) {
- // 1. If the user agent is not configured to block cookies for httpRequest
- // (see section 7 of [COOKIES]), then:
- // TODO: credentials
- // 2. If httpRequest’s header list does not contain `Authorization`, then:
- // TODO: credentials
- }
- // 21. If there’s a proxy-authentication entry, use it as appropriate.
- // TODO: proxy-authentication
+/***/ }),
- // 22. Set httpCache to the result of determining the HTTP cache
- // partition, given httpRequest.
- // TODO: cache
+/***/ 2581:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 23. If httpCache is null, then set httpRequest’s cache mode to
- // "no-store".
- if (httpCache == null) {
- httpRequest.cache = 'no-store'
- }
- // 24. If httpRequest’s cache mode is neither "no-store" nor "reload",
- // then:
- if (httpRequest.cache !== 'no-store' && httpRequest.cache !== 'reload') {
- // TODO: cache
+
+// We include a version number for the Dispatcher API. In case of breaking changes,
+// this version number must be increased to avoid conflicts.
+const globalDispatcher = Symbol.for('undici.globalDispatcher.1')
+const { InvalidArgumentError } = __nccwpck_require__(8707)
+const Agent = __nccwpck_require__(7405)
+
+if (getGlobalDispatcher() === undefined) {
+ setGlobalDispatcher(new Agent())
+}
+
+function setGlobalDispatcher (agent) {
+ if (!agent || typeof agent.dispatch !== 'function') {
+ throw new InvalidArgumentError('Argument agent must implement Agent')
}
+ Object.defineProperty(globalThis, globalDispatcher, {
+ value: agent,
+ writable: true,
+ enumerable: false,
+ configurable: false
+ })
+}
- // 9. If aborted, then return the appropriate network error for fetchParams.
- // TODO
+function getGlobalDispatcher () {
+ return globalThis[globalDispatcher]
+}
- // 10. If response is null, then:
- if (response == null) {
- // 1. If httpRequest’s cache mode is "only-if-cached", then return a
- // network error.
- if (httpRequest.cache === 'only-if-cached') {
- return makeNetworkError('only if cached')
- }
+module.exports = {
+ setGlobalDispatcher,
+ getGlobalDispatcher
+}
- // 2. Let forwardResponse be the result of running HTTP-network fetch
- // given httpFetchParams, includeCredentials, and isNewConnectionFetch.
- const forwardResponse = await httpNetworkFetch(
- httpFetchParams,
- includeCredentials,
- isNewConnectionFetch
- )
- // 3. If httpRequest’s method is unsafe and forwardResponse’s status is
- // in the range 200 to 399, inclusive, invalidate appropriate stored
- // responses in httpCache, as per the "Invalidation" chapter of HTTP
- // Caching, and set storedResponse to null. [HTTP-CACHING]
- if (
- !safeMethodsSet.has(httpRequest.method) &&
- forwardResponse.status >= 200 &&
- forwardResponse.status <= 399
- ) {
- // TODO: cache
- }
+/***/ }),
- // 4. If the revalidatingFlag is set and forwardResponse’s status is 304,
- // then:
- if (revalidatingFlag && forwardResponse.status === 304) {
- // TODO: cache
- }
+/***/ 8155:
+/***/ ((module) => {
- // 5. If response is null, then:
- if (response == null) {
- // 1. Set response to forwardResponse.
- response = forwardResponse
- // 2. Store httpRequest and forwardResponse in httpCache, as per the
- // "Storing Responses in Caches" chapter of HTTP Caching. [HTTP-CACHING]
- // TODO: cache
+
+module.exports = class DecoratorHandler {
+ #handler
+
+ constructor (handler) {
+ if (typeof handler !== 'object' || handler === null) {
+ throw new TypeError('handler must be an object')
}
+ this.#handler = handler
}
- // 11. Set response’s URL list to a clone of httpRequest’s URL list.
- response.urlList = [...httpRequest.urlList]
-
- // 12. If httpRequest’s header list contains `Range`, then set response’s
- // range-requested flag.
- if (httpRequest.headersList.contains('range', true)) {
- response.rangeRequested = true
+ onConnect (...args) {
+ return this.#handler.onConnect?.(...args)
}
- // 13. Set response’s request-includes-credentials to includeCredentials.
- response.requestIncludesCredentials = includeCredentials
+ onError (...args) {
+ return this.#handler.onError?.(...args)
+ }
- // 14. If response’s status is 401, httpRequest’s response tainting is not
- // "cors", includeCredentials is true, and request’s window is an environment
- // settings object, then:
- // TODO
+ onUpgrade (...args) {
+ return this.#handler.onUpgrade?.(...args)
+ }
- // 15. If response’s status is 407, then:
- if (response.status === 407) {
- // 1. If request’s window is "no-window", then return a network error.
- if (request.window === 'no-window') {
- return makeNetworkError()
- }
+ onResponseStarted (...args) {
+ return this.#handler.onResponseStarted?.(...args)
+ }
- // 2. ???
+ onHeaders (...args) {
+ return this.#handler.onHeaders?.(...args)
+ }
- // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams.
- if (isCancelled(fetchParams)) {
- return makeAppropriateNetworkError(fetchParams)
- }
+ onData (...args) {
+ return this.#handler.onData?.(...args)
+ }
- // 4. Prompt the end user as appropriate in request’s window and store
- // the result as a proxy-authentication entry. [HTTP-AUTH]
- // TODO: Invoke some kind of callback?
+ onComplete (...args) {
+ return this.#handler.onComplete?.(...args)
+ }
- // 5. Set response to the result of running HTTP-network-or-cache fetch given
- // fetchParams.
- // TODO
- return makeNetworkError('proxy authentication required')
+ onBodySent (...args) {
+ return this.#handler.onBodySent?.(...args)
}
+}
- // 16. If all of the following are true
- if (
- // response’s status is 421
- response.status === 421 &&
- // isNewConnectionFetch is false
- !isNewConnectionFetch &&
- // request’s body is null, or request’s body is non-null and request’s body’s source is non-null
- (request.body == null || request.body.source != null)
- ) {
- // then:
- // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
- if (isCancelled(fetchParams)) {
- return makeAppropriateNetworkError(fetchParams)
- }
+/***/ }),
- // 2. Set response to the result of running HTTP-network-or-cache
- // fetch given fetchParams, isAuthenticationFetch, and true.
+/***/ 8754:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // TODO (spec): The spec doesn't specify this but we need to cancel
- // the active response before we can start a new one.
- // https://github.com/whatwg/fetch/issues/1293
- fetchParams.controller.connection.destroy()
- response = await httpNetworkOrCacheFetch(
- fetchParams,
- isAuthenticationFetch,
- true
- )
- }
- // 17. If isAuthenticationFetch is true, then create an authentication entry
- if (isAuthenticationFetch) {
- // TODO
- }
+const util = __nccwpck_require__(3440)
+const { kBodyUsed } = __nccwpck_require__(6443)
+const assert = __nccwpck_require__(4589)
+const { InvalidArgumentError } = __nccwpck_require__(8707)
+const EE = __nccwpck_require__(8474)
- // 18. Return response.
- return response
-}
+const redirectableStatusCodes = [300, 301, 302, 303, 307, 308]
-// https://fetch.spec.whatwg.org/#http-network-fetch
-async function httpNetworkFetch (
- fetchParams,
- includeCredentials = false,
- forceNewConnection = false
-) {
- assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed)
+const kBody = Symbol('body')
- fetchParams.controller.connection = {
- abort: null,
- destroyed: false,
- destroy (err, abort = true) {
- if (!this.destroyed) {
- this.destroyed = true
- if (abort) {
- this.abort?.(err ?? new DOMException('The operation was aborted.', 'AbortError'))
- }
- }
- }
+class BodyAsyncIterable {
+ constructor (body) {
+ this[kBody] = body
+ this[kBodyUsed] = false
}
- // 1. Let request be fetchParams’s request.
- const request = fetchParams.request
+ async * [Symbol.asyncIterator] () {
+ assert(!this[kBodyUsed], 'disturbed')
+ this[kBodyUsed] = true
+ yield * this[kBody]
+ }
+}
- // 2. Let response be null.
- let response = null
+class RedirectHandler {
+ constructor (dispatch, maxRedirections, opts, handler) {
+ if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {
+ throw new InvalidArgumentError('maxRedirections must be a positive number')
+ }
- // 3. Let timingInfo be fetchParams’s timing info.
- const timingInfo = fetchParams.timingInfo
+ util.validateHandler(handler, opts.method, opts.upgrade)
- // 4. Let httpCache be the result of determining the HTTP cache partition,
- // given request.
- // TODO: cache
- const httpCache = null
+ this.dispatch = dispatch
+ this.location = null
+ this.abort = null
+ this.opts = { ...opts, maxRedirections: 0 } // opts must be a copy
+ this.maxRedirections = maxRedirections
+ this.handler = handler
+ this.history = []
+ this.redirectionLimitReached = false
- // 5. If httpCache is null, then set request’s cache mode to "no-store".
- if (httpCache == null) {
- request.cache = 'no-store'
+ if (util.isStream(this.opts.body)) {
+ // TODO (fix): Provide some way for the user to cache the file to e.g. /tmp
+ // so that it can be dispatched again?
+ // TODO (fix): Do we need 100-expect support to provide a way to do this properly?
+ if (util.bodyLength(this.opts.body) === 0) {
+ this.opts.body
+ .on('data', function () {
+ assert(false)
+ })
+ }
+
+ if (typeof this.opts.body.readableDidRead !== 'boolean') {
+ this.opts.body[kBodyUsed] = false
+ EE.prototype.on.call(this.opts.body, 'data', function () {
+ this[kBodyUsed] = true
+ })
+ }
+ } else if (this.opts.body && typeof this.opts.body.pipeTo === 'function') {
+ // TODO (fix): We can't access ReadableStream internal state
+ // to determine whether or not it has been disturbed. This is just
+ // a workaround.
+ this.opts.body = new BodyAsyncIterable(this.opts.body)
+ } else if (
+ this.opts.body &&
+ typeof this.opts.body !== 'string' &&
+ !ArrayBuffer.isView(this.opts.body) &&
+ util.isIterable(this.opts.body)
+ ) {
+ // TODO: Should we allow re-using iterable if !this.opts.idempotent
+ // or through some other flag?
+ this.opts.body = new BodyAsyncIterable(this.opts.body)
+ }
}
- // 6. Let networkPartitionKey be the result of determining the network
- // partition key given request.
- // TODO
+ onConnect (abort) {
+ this.abort = abort
+ this.handler.onConnect(abort, { history: this.history })
+ }
- // 7. Let newConnection be "yes" if forceNewConnection is true; otherwise
- // "no".
- const newConnection = forceNewConnection ? 'yes' : 'no' // eslint-disable-line no-unused-vars
+ onUpgrade (statusCode, headers, socket) {
+ this.handler.onUpgrade(statusCode, headers, socket)
+ }
- // 8. Switch on request’s mode:
- if (request.mode === 'websocket') {
- // Let connection be the result of obtaining a WebSocket connection,
- // given request’s current URL.
- // TODO
- } else {
- // Let connection be the result of obtaining a connection, given
- // networkPartitionKey, request’s current URL’s origin,
- // includeCredentials, and forceNewConnection.
- // TODO
+ onError (error) {
+ this.handler.onError(error)
}
- // 9. Run these steps, but abort when the ongoing fetch is terminated:
+ onHeaders (statusCode, headers, resume, statusText) {
+ this.location = this.history.length >= this.maxRedirections || util.isDisturbed(this.opts.body)
+ ? null
+ : parseLocation(statusCode, headers)
- // 1. If connection is failure, then return a network error.
+ if (this.opts.throwOnMaxRedirect && this.history.length >= this.maxRedirections) {
+ if (this.request) {
+ this.request.abort(new Error('max redirects'))
+ }
- // 2. Set timingInfo’s final connection timing info to the result of
- // calling clamp and coarsen connection timing info with connection’s
- // timing info, timingInfo’s post-redirect start time, and fetchParams’s
- // cross-origin isolated capability.
+ this.redirectionLimitReached = true
+ this.abort(new Error('max redirects'))
+ return
+ }
- // 3. If connection is not an HTTP/2 connection, request’s body is non-null,
- // and request’s body’s source is null, then append (`Transfer-Encoding`,
- // `chunked`) to request’s header list.
+ if (this.opts.origin) {
+ this.history.push(new URL(this.opts.path, this.opts.origin))
+ }
- // 4. Set timingInfo’s final network-request start time to the coarsened
- // shared current time given fetchParams’s cross-origin isolated
- // capability.
+ if (!this.location) {
+ return this.handler.onHeaders(statusCode, headers, resume, statusText)
+ }
- // 5. Set response to the result of making an HTTP request over connection
- // using request with the following caveats:
+ const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin)))
+ const path = search ? `${pathname}${search}` : pathname
- // - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS]
- // [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH]
+ // Remove headers referring to the original URL.
+ // By default it is Host only, unless it's a 303 (see below), which removes also all Content-* headers.
+ // https://tools.ietf.org/html/rfc7231#section-6.4
+ this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin)
+ this.opts.path = path
+ this.opts.origin = origin
+ this.opts.maxRedirections = 0
+ this.opts.query = null
- // - If request’s body is non-null, and request’s body’s source is null,
- // then the user agent may have a buffer of up to 64 kibibytes and store
- // a part of request’s body in that buffer. If the user agent reads from
- // request’s body beyond that buffer’s size and the user agent needs to
- // resend request, then instead return a network error.
+ // https://tools.ietf.org/html/rfc7231#section-6.4.4
+ // In case of HTTP 303, always replace method to be either HEAD or GET
+ if (statusCode === 303 && this.opts.method !== 'HEAD') {
+ this.opts.method = 'GET'
+ this.opts.body = null
+ }
+ }
- // - Set timingInfo’s final network-response start time to the coarsened
- // shared current time given fetchParams’s cross-origin isolated capability,
- // immediately after the user agent’s HTTP parser receives the first byte
- // of the response (e.g., frame header bytes for HTTP/2 or response status
- // line for HTTP/1.x).
+ onData (chunk) {
+ if (this.location) {
+ /*
+ https://tools.ietf.org/html/rfc7231#section-6.4
- // - Wait until all the headers are transmitted.
+ TLDR: undici always ignores 3xx response bodies.
- // - Any responses whose status is in the range 100 to 199, inclusive,
- // and is not 101, are to be ignored, except for the purposes of setting
- // timingInfo’s final network-response start time above.
+ Redirection is used to serve the requested resource from another URL, so it is assumes that
+ no body is generated (and thus can be ignored). Even though generating a body is not prohibited.
- // - If request’s header list contains `Transfer-Encoding`/`chunked` and
- // response is transferred via HTTP/1.0 or older, then return a network
- // error.
+ For status 301, 302, 303, 307 and 308 (the latter from RFC 7238), the specs mention that the body usually
+ (which means it's optional and not mandated) contain just an hyperlink to the value of
+ the Location response header, so the body can be ignored safely.
- // - If the HTTP request results in a TLS client certificate dialog, then:
+ For status 300, which is "Multiple Choices", the spec mentions both generating a Location
+ response header AND a response body with the other possible location to follow.
+ Since the spec explicitly chooses not to specify a format for such body and leave it to
+ servers and browsers implementors, we ignore the body as there is no specified way to eventually parse it.
+ */
+ } else {
+ return this.handler.onData(chunk)
+ }
+ }
- // 1. If request’s window is an environment settings object, make the
- // dialog available in request’s window.
+ onComplete (trailers) {
+ if (this.location) {
+ /*
+ https://tools.ietf.org/html/rfc7231#section-6.4
- // 2. Otherwise, return a network error.
+ TLDR: undici always ignores 3xx response trailers as they are not expected in case of redirections
+ and neither are useful if present.
- // To transmit request’s body body, run these steps:
- let requestBody = null
- // 1. If body is null and fetchParams’s process request end-of-body is
- // non-null, then queue a fetch task given fetchParams’s process request
- // end-of-body and fetchParams’s task destination.
- if (request.body == null && fetchParams.processRequestEndOfBody) {
- queueMicrotask(() => fetchParams.processRequestEndOfBody())
- } else if (request.body != null) {
- // 2. Otherwise, if body is non-null:
+ See comment on onData method above for more detailed information.
+ */
- // 1. Let processBodyChunk given bytes be these steps:
- const processBodyChunk = async function * (bytes) {
- // 1. If the ongoing fetch is terminated, then abort these steps.
- if (isCancelled(fetchParams)) {
- return
- }
+ this.location = null
+ this.abort = null
- // 2. Run this step in parallel: transmit bytes.
- yield bytes
+ this.dispatch(this.opts, this)
+ } else {
+ this.handler.onComplete(trailers)
+ }
+ }
- // 3. If fetchParams’s process request body is non-null, then run
- // fetchParams’s process request body given bytes’s length.
- fetchParams.processRequestBodyChunkLength?.(bytes.byteLength)
+ onBodySent (chunk) {
+ if (this.handler.onBodySent) {
+ this.handler.onBodySent(chunk)
}
+ }
+}
- // 2. Let processEndOfBody be these steps:
- const processEndOfBody = () => {
- // 1. If fetchParams is canceled, then abort these steps.
- if (isCancelled(fetchParams)) {
- return
- }
+function parseLocation (statusCode, headers) {
+ if (redirectableStatusCodes.indexOf(statusCode) === -1) {
+ return null
+ }
- // 2. If fetchParams’s process request end-of-body is non-null,
- // then run fetchParams’s process request end-of-body.
- if (fetchParams.processRequestEndOfBody) {
- fetchParams.processRequestEndOfBody()
- }
+ for (let i = 0; i < headers.length; i += 2) {
+ if (headers[i].length === 8 && util.headerNameToString(headers[i]) === 'location') {
+ return headers[i + 1]
}
+ }
+}
- // 3. Let processBodyError given e be these steps:
- const processBodyError = (e) => {
- // 1. If fetchParams is canceled, then abort these steps.
- if (isCancelled(fetchParams)) {
- return
- }
+// https://tools.ietf.org/html/rfc7231#section-6.4.4
+function shouldRemoveHeader (header, removeContent, unknownOrigin) {
+ if (header.length === 4) {
+ return util.headerNameToString(header) === 'host'
+ }
+ if (removeContent && util.headerNameToString(header).startsWith('content-')) {
+ return true
+ }
+ if (unknownOrigin && (header.length === 13 || header.length === 6 || header.length === 19)) {
+ const name = util.headerNameToString(header)
+ return name === 'authorization' || name === 'cookie' || name === 'proxy-authorization'
+ }
+ return false
+}
- // 2. If e is an "AbortError" DOMException, then abort fetchParams’s controller.
- if (e.name === 'AbortError') {
- fetchParams.controller.abort()
- } else {
- fetchParams.controller.terminate(e)
+// https://tools.ietf.org/html/rfc7231#section-6.4
+function cleanRequestHeaders (headers, removeContent, unknownOrigin) {
+ const ret = []
+ if (Array.isArray(headers)) {
+ for (let i = 0; i < headers.length; i += 2) {
+ if (!shouldRemoveHeader(headers[i], removeContent, unknownOrigin)) {
+ ret.push(headers[i], headers[i + 1])
}
}
-
- // 4. Incrementally read request’s body given processBodyChunk, processEndOfBody,
- // processBodyError, and fetchParams’s task destination.
- requestBody = (async function * () {
- try {
- for await (const bytes of request.body.stream) {
- yield * processBodyChunk(bytes)
- }
- processEndOfBody()
- } catch (err) {
- processBodyError(err)
+ } else if (headers && typeof headers === 'object') {
+ for (const key of Object.keys(headers)) {
+ if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) {
+ ret.push(key, headers[key])
}
- })()
+ }
+ } else {
+ assert(headers == null, 'headers must be an object or an array')
}
+ return ret
+}
- try {
- // socket is only provided for websockets
- const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody })
+module.exports = RedirectHandler
- if (socket) {
- response = makeResponse({ status, statusText, headersList, socket })
- } else {
- const iterator = body[Symbol.asyncIterator]()
- fetchParams.controller.next = () => iterator.next()
- response = makeResponse({ status, statusText, headersList })
- }
- } catch (err) {
- // 10. If aborted, then:
- if (err.name === 'AbortError') {
- // 1. If connection uses HTTP/2, then transmit an RST_STREAM frame.
- fetchParams.controller.connection.destroy()
+/***/ }),
- // 2. Return the appropriate network error for fetchParams.
- return makeAppropriateNetworkError(fetchParams, err)
+/***/ 7816:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+const assert = __nccwpck_require__(4589)
+
+const { kRetryHandlerDefaultRetry } = __nccwpck_require__(6443)
+const { RequestRetryError } = __nccwpck_require__(8707)
+const {
+ isDisturbed,
+ parseHeaders,
+ parseRangeHeader,
+ wrapRequestBody
+} = __nccwpck_require__(3440)
+
+function calculateRetryAfterHeader (retryAfter) {
+ const current = Date.now()
+ return new Date(retryAfter).getTime() - current
+}
+
+class RetryHandler {
+ constructor (opts, handlers) {
+ const { retryOptions, ...dispatchOpts } = opts
+ const {
+ // Retry scoped
+ retry: retryFn,
+ maxRetries,
+ maxTimeout,
+ minTimeout,
+ timeoutFactor,
+ // Response scoped
+ methods,
+ errorCodes,
+ retryAfter,
+ statusCodes
+ } = retryOptions ?? {}
+
+ this.dispatch = handlers.dispatch
+ this.handler = handlers.handler
+ this.opts = { ...dispatchOpts, body: wrapRequestBody(opts.body) }
+ this.abort = null
+ this.aborted = false
+ this.retryOpts = {
+ retry: retryFn ?? RetryHandler[kRetryHandlerDefaultRetry],
+ retryAfter: retryAfter ?? true,
+ maxTimeout: maxTimeout ?? 30 * 1000, // 30s,
+ minTimeout: minTimeout ?? 500, // .5s
+ timeoutFactor: timeoutFactor ?? 2,
+ maxRetries: maxRetries ?? 5,
+ // What errors we should retry
+ methods: methods ?? ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE'],
+ // Indicates which errors to retry
+ statusCodes: statusCodes ?? [500, 502, 503, 504, 429],
+ // List of errors to retry
+ errorCodes: errorCodes ?? [
+ 'ECONNRESET',
+ 'ECONNREFUSED',
+ 'ENOTFOUND',
+ 'ENETDOWN',
+ 'ENETUNREACH',
+ 'EHOSTDOWN',
+ 'EHOSTUNREACH',
+ 'EPIPE',
+ 'UND_ERR_SOCKET'
+ ]
}
- return makeNetworkError(err)
+ this.retryCount = 0
+ this.retryCountCheckpoint = 0
+ this.start = 0
+ this.end = null
+ this.etag = null
+ this.resume = null
+
+ // Handle possible onConnect duplication
+ this.handler.onConnect(reason => {
+ this.aborted = true
+ if (this.abort) {
+ this.abort(reason)
+ } else {
+ this.reason = reason
+ }
+ })
}
- // 11. Let pullAlgorithm be an action that resumes the ongoing fetch
- // if it is suspended.
- const pullAlgorithm = async () => {
- await fetchParams.controller.resume()
+ onRequestSent () {
+ if (this.handler.onRequestSent) {
+ this.handler.onRequestSent()
+ }
}
- // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s
- // controller with reason, given reason.
- const cancelAlgorithm = (reason) => {
- // If the aborted fetch was already terminated, then we do not
- // need to do anything.
- if (!isCancelled(fetchParams)) {
- fetchParams.controller.abort(reason)
+ onUpgrade (statusCode, headers, socket) {
+ if (this.handler.onUpgrade) {
+ this.handler.onUpgrade(statusCode, headers, socket)
}
}
- // 13. Let highWaterMark be a non-negative, non-NaN number, chosen by
- // the user agent.
- // TODO
+ onConnect (abort) {
+ if (this.aborted) {
+ abort(this.reason)
+ } else {
+ this.abort = abort
+ }
+ }
- // 14. Let sizeAlgorithm be an algorithm that accepts a chunk object
- // and returns a non-negative, non-NaN, non-infinite number, chosen by the user agent.
- // TODO
+ onBodySent (chunk) {
+ if (this.handler.onBodySent) return this.handler.onBodySent(chunk)
+ }
- // 15. Let stream be a new ReadableStream.
- // 16. Set up stream with byte reading support with pullAlgorithm set to pullAlgorithm,
- // cancelAlgorithm set to cancelAlgorithm.
- const stream = new ReadableStream(
- {
- async start (controller) {
- fetchParams.controller.controller = controller
- },
- async pull (controller) {
- await pullAlgorithm(controller)
- },
- async cancel (reason) {
- await cancelAlgorithm(reason)
- },
- type: 'bytes'
+ static [kRetryHandlerDefaultRetry] (err, { state, opts }, cb) {
+ const { statusCode, code, headers } = err
+ const { method, retryOptions } = opts
+ const {
+ maxRetries,
+ minTimeout,
+ maxTimeout,
+ timeoutFactor,
+ statusCodes,
+ errorCodes,
+ methods
+ } = retryOptions
+ const { counter } = state
+
+ // Any code that is not a Undici's originated and allowed to retry
+ if (code && code !== 'UND_ERR_REQ_RETRY' && !errorCodes.includes(code)) {
+ cb(err)
+ return
}
- )
- // 17. Run these steps, but abort when the ongoing fetch is terminated:
+ // If a set of method are provided and the current method is not in the list
+ if (Array.isArray(methods) && !methods.includes(method)) {
+ cb(err)
+ return
+ }
- // 1. Set response’s body to a new body whose stream is stream.
- response.body = { stream, source: null, length: null }
+ // If a set of status code are provided and the current status code is not in the list
+ if (
+ statusCode != null &&
+ Array.isArray(statusCodes) &&
+ !statusCodes.includes(statusCode)
+ ) {
+ cb(err)
+ return
+ }
- // 2. If response is not a network error and request’s cache mode is
- // not "no-store", then update response in httpCache for request.
- // TODO
-
- // 3. If includeCredentials is true and the user agent is not configured
- // to block cookies for request (see section 7 of [COOKIES]), then run the
- // "set-cookie-string" parsing algorithm (see section 5.2 of [COOKIES]) on
- // the value of each header whose name is a byte-case-insensitive match for
- // `Set-Cookie` in response’s header list, if any, and request’s current URL.
- // TODO
-
- // 18. If aborted, then:
- // TODO
-
- // 19. Run these steps in parallel:
-
- // 1. Run these steps, but abort when fetchParams is canceled:
- fetchParams.controller.onAborted = onAborted
- fetchParams.controller.on('terminated', onAborted)
- fetchParams.controller.resume = async () => {
- // 1. While true
- while (true) {
- // 1-3. See onData...
-
- // 4. Set bytes to the result of handling content codings given
- // codings and bytes.
- let bytes
- let isFailure
- try {
- const { done, value } = await fetchParams.controller.next()
+ // If we reached the max number of retries
+ if (counter > maxRetries) {
+ cb(err)
+ return
+ }
- if (isAborted(fetchParams)) {
- break
- }
+ let retryAfterHeader = headers?.['retry-after']
+ if (retryAfterHeader) {
+ retryAfterHeader = Number(retryAfterHeader)
+ retryAfterHeader = Number.isNaN(retryAfterHeader)
+ ? calculateRetryAfterHeader(retryAfterHeader)
+ : retryAfterHeader * 1e3 // Retry-After is in seconds
+ }
- bytes = done ? undefined : value
- } catch (err) {
- if (fetchParams.controller.ended && !timingInfo.encodedBodySize) {
- // zlib doesn't like empty streams.
- bytes = undefined
- } else {
- bytes = err
+ const retryTimeout =
+ retryAfterHeader > 0
+ ? Math.min(retryAfterHeader, maxTimeout)
+ : Math.min(minTimeout * timeoutFactor ** (counter - 1), maxTimeout)
- // err may be propagated from the result of calling readablestream.cancel,
- // which might not be an error. https://github.com/nodejs/undici/issues/2009
- isFailure = true
- }
- }
+ setTimeout(() => cb(null), retryTimeout)
+ }
- if (bytes === undefined) {
- // 2. Otherwise, if the bytes transmission for response’s message
- // body is done normally and stream is readable, then close
- // stream, finalize response for fetchParams and response, and
- // abort these in-parallel steps.
- readableStreamClose(fetchParams.controller.controller)
+ onHeaders (statusCode, rawHeaders, resume, statusMessage) {
+ const headers = parseHeaders(rawHeaders)
- finalizeResponse(fetchParams, response)
+ this.retryCount += 1
- return
+ if (statusCode >= 300) {
+ if (this.retryOpts.statusCodes.includes(statusCode) === false) {
+ return this.handler.onHeaders(
+ statusCode,
+ rawHeaders,
+ resume,
+ statusMessage
+ )
+ } else {
+ this.abort(
+ new RequestRetryError('Request failed', statusCode, {
+ headers,
+ data: {
+ count: this.retryCount
+ }
+ })
+ )
+ return false
}
+ }
- // 5. Increase timingInfo’s decoded body size by bytes’s length.
- timingInfo.decodedBodySize += bytes?.byteLength ?? 0
+ // Checkpoint for resume from where we left it
+ if (this.resume != null) {
+ this.resume = null
- // 6. If bytes is failure, then terminate fetchParams’s controller.
- if (isFailure) {
- fetchParams.controller.terminate(bytes)
- return
+ // Only Partial Content 206 supposed to provide Content-Range,
+ // any other status code that partially consumed the payload
+ // should not be retry because it would result in downstream
+ // wrongly concatanete multiple responses.
+ if (statusCode !== 206 && (this.start > 0 || statusCode !== 200)) {
+ this.abort(
+ new RequestRetryError('server does not support the range header and the payload was partially consumed', statusCode, {
+ headers,
+ data: { count: this.retryCount }
+ })
+ )
+ return false
}
- // 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes
- // into stream.
- const buffer = new Uint8Array(bytes)
- if (buffer.byteLength) {
- fetchParams.controller.controller.enqueue(buffer)
+ const contentRange = parseRangeHeader(headers['content-range'])
+ // If no content range
+ if (!contentRange) {
+ this.abort(
+ new RequestRetryError('Content-Range mismatch', statusCode, {
+ headers,
+ data: { count: this.retryCount }
+ })
+ )
+ return false
}
- // 8. If stream is errored, then terminate the ongoing fetch.
- if (isErrored(stream)) {
- fetchParams.controller.terminate()
- return
+ // Let's start with a weak etag check
+ if (this.etag != null && this.etag !== headers.etag) {
+ this.abort(
+ new RequestRetryError('ETag mismatch', statusCode, {
+ headers,
+ data: { count: this.retryCount }
+ })
+ )
+ return false
}
- // 9. If stream doesn’t need more data ask the user agent to suspend
- // the ongoing fetch.
- if (fetchParams.controller.controller.desiredSize <= 0) {
- return
- }
- }
- }
+ const { start, size, end = size - 1 } = contentRange
- // 2. If aborted, then:
- function onAborted (reason) {
- // 2. If fetchParams is aborted, then:
- if (isAborted(fetchParams)) {
- // 1. Set response’s aborted flag.
- response.aborted = true
+ assert(this.start === start, 'content-range mismatch')
+ assert(this.end == null || this.end === end, 'content-range mismatch')
- // 2. If stream is readable, then error stream with the result of
- // deserialize a serialized abort reason given fetchParams’s
- // controller’s serialized abort reason and an
- // implementation-defined realm.
- if (isReadable(stream)) {
- fetchParams.controller.controller.error(
- fetchParams.controller.serializedAbortReason
- )
- }
- } else {
- // 3. Otherwise, if stream is readable, error stream with a TypeError.
- if (isReadable(stream)) {
- fetchParams.controller.controller.error(new TypeError('terminated', {
- cause: isErrorLike(reason) ? reason : undefined
- }))
- }
+ this.resume = resume
+ return true
}
- // 4. If connection uses HTTP/2, then transmit an RST_STREAM frame.
- // 5. Otherwise, the user agent should close connection unless it would be bad for performance to do so.
- fetchParams.controller.connection.destroy()
- }
-
- // 20. Return response.
- return response
+ if (this.end == null) {
+ if (statusCode === 206) {
+ // First time we receive 206
+ const range = parseRangeHeader(headers['content-range'])
- function dispatch ({ body }) {
- const url = requestCurrentURL(request)
- /** @type {import('../..').Agent} */
- const agent = fetchParams.controller.dispatcher
+ if (range == null) {
+ return this.handler.onHeaders(
+ statusCode,
+ rawHeaders,
+ resume,
+ statusMessage
+ )
+ }
- return new Promise((resolve, reject) => agent.dispatch(
- {
- path: url.pathname + url.search,
- origin: url.origin,
- method: request.method,
- body: agent.isMockActive ? request.body && (request.body.source || request.body.stream) : body,
- headers: request.headersList.entries,
- maxRedirections: 0,
- upgrade: request.mode === 'websocket' ? 'websocket' : undefined
- },
- {
- body: null,
- abort: null,
+ const { start, size, end = size - 1 } = range
+ assert(
+ start != null && Number.isFinite(start),
+ 'content-range mismatch'
+ )
+ assert(end != null && Number.isFinite(end), 'invalid content-length')
- onConnect (abort) {
- // TODO (fix): Do we need connection here?
- const { connection } = fetchParams.controller
+ this.start = start
+ this.end = end
+ }
- // Set timingInfo’s final connection timing info to the result of calling clamp and coarsen
- // connection timing info with connection’s timing info, timingInfo’s post-redirect start
- // time, and fetchParams’s cross-origin isolated capability.
- // TODO: implement connection timing
- timingInfo.finalConnectionTimingInfo = clampAndCoarsenConnectionTimingInfo(undefined, timingInfo.postRedirectStartTime, fetchParams.crossOriginIsolatedCapability)
+ // We make our best to checkpoint the body for further range headers
+ if (this.end == null) {
+ const contentLength = headers['content-length']
+ this.end = contentLength != null ? Number(contentLength) - 1 : null
+ }
- if (connection.destroyed) {
- abort(new DOMException('The operation was aborted.', 'AbortError'))
- } else {
- fetchParams.controller.on('terminated', abort)
- this.abort = connection.abort = abort
- }
+ assert(Number.isFinite(this.start))
+ assert(
+ this.end == null || Number.isFinite(this.end),
+ 'invalid content-length'
+ )
- // Set timingInfo’s final network-request start time to the coarsened shared current time given
- // fetchParams’s cross-origin isolated capability.
- timingInfo.finalNetworkRequestStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability)
- },
+ this.resume = resume
+ this.etag = headers.etag != null ? headers.etag : null
- onResponseStarted () {
- // Set timingInfo’s final network-response start time to the coarsened shared current
- // time given fetchParams’s cross-origin isolated capability, immediately after the
- // user agent’s HTTP parser receives the first byte of the response (e.g., frame header
- // bytes for HTTP/2 or response status line for HTTP/1.x).
- timingInfo.finalNetworkResponseStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability)
- },
+ // Weak etags are not useful for comparison nor cache
+ // for instance not safe to assume if the response is byte-per-byte
+ // equal
+ if (this.etag != null && this.etag.startsWith('W/')) {
+ this.etag = null
+ }
- onHeaders (status, rawHeaders, resume, statusText) {
- if (status < 200) {
- return
- }
+ return this.handler.onHeaders(
+ statusCode,
+ rawHeaders,
+ resume,
+ statusMessage
+ )
+ }
- let location = ''
+ const err = new RequestRetryError('Request failed', statusCode, {
+ headers,
+ data: { count: this.retryCount }
+ })
- const headersList = new HeadersList()
+ this.abort(err)
- for (let i = 0; i < rawHeaders.length; i += 2) {
- headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i]), rawHeaders[i + 1].toString('latin1'), true)
- }
- location = headersList.get('location', true)
+ return false
+ }
- this.body = new Readable({ read: resume })
+ onData (chunk) {
+ this.start += chunk.length
- const decoders = []
+ return this.handler.onData(chunk)
+ }
- const willFollow = location && request.redirect === 'follow' &&
- redirectStatusSet.has(status)
+ onComplete (rawTrailers) {
+ this.retryCount = 0
+ return this.handler.onComplete(rawTrailers)
+ }
- // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding
- if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) {
- // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1
- const contentEncoding = headersList.get('content-encoding', true)
- // "All content-coding values are case-insensitive..."
- /** @type {string[]} */
- const codings = contentEncoding ? contentEncoding.toLowerCase().split(',') : []
+ onError (err) {
+ if (this.aborted || isDisturbed(this.opts.body)) {
+ return this.handler.onError(err)
+ }
- // Limit the number of content-encodings to prevent resource exhaustion.
- // CVE fix similar to urllib3 (GHSA-gm62-xv2j-4w53) and curl (CVE-2022-32206).
- const maxContentEncodings = 5
- if (codings.length > maxContentEncodings) {
- reject(new Error(`too many content-encodings in response: ${codings.length}, maximum allowed is ${maxContentEncodings}`))
- return true
- }
+ // We reconcile in case of a mix between network errors
+ // and server error response
+ if (this.retryCount - this.retryCountCheckpoint > 0) {
+ // We count the difference between the last checkpoint and the current retry count
+ this.retryCount =
+ this.retryCountCheckpoint +
+ (this.retryCount - this.retryCountCheckpoint)
+ } else {
+ this.retryCount += 1
+ }
- for (let i = codings.length - 1; i >= 0; --i) {
- const coding = codings[i].trim()
- // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.2
- if (coding === 'x-gzip' || coding === 'gzip') {
- decoders.push(zlib.createGunzip({
- // Be less strict when decoding compressed responses, since sometimes
- // servers send slightly invalid responses that are still accepted
- // by common browsers.
- // Always using Z_SYNC_FLUSH is what cURL does.
- flush: zlib.constants.Z_SYNC_FLUSH,
- finishFlush: zlib.constants.Z_SYNC_FLUSH
- }))
- } else if (coding === 'deflate') {
- decoders.push(createInflate({
- flush: zlib.constants.Z_SYNC_FLUSH,
- finishFlush: zlib.constants.Z_SYNC_FLUSH
- }))
- } else if (coding === 'br') {
- decoders.push(zlib.createBrotliDecompress({
- flush: zlib.constants.BROTLI_OPERATION_FLUSH,
- finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH
- }))
- } else {
- decoders.length = 0
- break
- }
- }
- }
+ this.retryOpts.retry(
+ err,
+ {
+ state: { counter: this.retryCount },
+ opts: { retryOptions: this.retryOpts, ...this.opts }
+ },
+ onRetry.bind(this)
+ )
- const onError = this.onError.bind(this)
+ function onRetry (err) {
+ if (err != null || this.aborted || isDisturbed(this.opts.body)) {
+ return this.handler.onError(err)
+ }
- resolve({
- status,
- statusText,
- headersList,
- body: decoders.length
- ? pipeline(this.body, ...decoders, (err) => {
- if (err) {
- this.onError(err)
- }
- }).on('error', onError)
- : this.body.on('error', onError)
- })
+ if (this.start !== 0) {
+ const headers = { range: `bytes=${this.start}-${this.end ?? ''}` }
- return true
- },
+ // Weak etag check - weak etags will make comparison algorithms never match
+ if (this.etag != null) {
+ headers['if-match'] = this.etag
+ }
- onData (chunk) {
- if (fetchParams.controller.dump) {
- return
+ this.opts = {
+ ...this.opts,
+ headers: {
+ ...this.opts.headers,
+ ...headers
}
+ }
+ }
- // 1. If one or more bytes have been transmitted from response’s
- // message body, then:
+ try {
+ this.retryCountCheckpoint = this.retryCount
+ this.dispatch(this.opts, this)
+ } catch (err) {
+ this.handler.onError(err)
+ }
+ }
+ }
+}
- // 1. Let bytes be the transmitted bytes.
- const bytes = chunk
+module.exports = RetryHandler
- // 2. Let codings be the result of extracting header list values
- // given `Content-Encoding` and response’s header list.
- // See pullAlgorithm.
- // 3. Increase timingInfo’s encoded body size by bytes’s length.
- timingInfo.encodedBodySize += bytes.byteLength
+/***/ }),
- // 4. See pullAlgorithm...
+/***/ 379:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- return this.body.push(bytes)
- },
- onComplete () {
- if (this.abort) {
- fetchParams.controller.off('terminated', this.abort)
- }
+const { isIP } = __nccwpck_require__(7030)
+const { lookup } = __nccwpck_require__(610)
+const DecoratorHandler = __nccwpck_require__(8155)
+const { InvalidArgumentError, InformationalError } = __nccwpck_require__(8707)
+const maxInt = Math.pow(2, 31) - 1
- if (fetchParams.controller.onAborted) {
- fetchParams.controller.off('terminated', fetchParams.controller.onAborted)
- }
+class DNSInstance {
+ #maxTTL = 0
+ #maxItems = 0
+ #records = new Map()
+ dualStack = true
+ affinity = null
+ lookup = null
+ pick = null
- fetchParams.controller.ended = true
+ constructor (opts) {
+ this.#maxTTL = opts.maxTTL
+ this.#maxItems = opts.maxItems
+ this.dualStack = opts.dualStack
+ this.affinity = opts.affinity
+ this.lookup = opts.lookup ?? this.#defaultLookup
+ this.pick = opts.pick ?? this.#defaultPick
+ }
- this.body.push(null)
- },
+ get full () {
+ return this.#records.size === this.#maxItems
+ }
- onError (error) {
- if (this.abort) {
- fetchParams.controller.off('terminated', this.abort)
- }
+ runLookup (origin, opts, cb) {
+ const ips = this.#records.get(origin.hostname)
- this.body?.destroy(error)
+ // If full, we just return the origin
+ if (ips == null && this.full) {
+ cb(null, origin.origin)
+ return
+ }
- fetchParams.controller.terminate(error)
+ const newOpts = {
+ affinity: this.affinity,
+ dualStack: this.dualStack,
+ lookup: this.lookup,
+ pick: this.pick,
+ ...opts.dns,
+ maxTTL: this.#maxTTL,
+ maxItems: this.#maxItems
+ }
- reject(error)
- },
+ // If no IPs we lookup
+ if (ips == null) {
+ this.lookup(origin, newOpts, (err, addresses) => {
+ if (err || addresses == null || addresses.length === 0) {
+ cb(err ?? new InformationalError('No DNS entries found'))
+ return
+ }
- onUpgrade (status, rawHeaders, socket) {
- if (status !== 101) {
- return
- }
+ this.setRecords(origin, addresses)
+ const records = this.#records.get(origin.hostname)
- const headersList = new HeadersList()
+ const ip = this.pick(
+ origin,
+ records,
+ newOpts.affinity
+ )
- for (let i = 0; i < rawHeaders.length; i += 2) {
- headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i]), rawHeaders[i + 1].toString('latin1'), true)
- }
+ let port
+ if (typeof ip.port === 'number') {
+ port = `:${ip.port}`
+ } else if (origin.port !== '') {
+ port = `:${origin.port}`
+ } else {
+ port = ''
+ }
- resolve({
- status,
- statusText: STATUS_CODES[status],
- headersList,
- socket
- })
+ cb(
+ null,
+ `${origin.protocol}//${
+ ip.family === 6 ? `[${ip.address}]` : ip.address
+ }${port}`
+ )
+ })
+ } else {
+ // If there's IPs we pick
+ const ip = this.pick(
+ origin,
+ ips,
+ newOpts.affinity
+ )
- return true
+ // If no IPs we lookup - deleting old records
+ if (ip == null) {
+ this.#records.delete(origin.hostname)
+ this.runLookup(origin, opts, cb)
+ return
+ }
+
+ let port
+ if (typeof ip.port === 'number') {
+ port = `:${ip.port}`
+ } else if (origin.port !== '') {
+ port = `:${origin.port}`
+ } else {
+ port = ''
+ }
+
+ cb(
+ null,
+ `${origin.protocol}//${
+ ip.family === 6 ? `[${ip.address}]` : ip.address
+ }${port}`
+ )
+ }
+ }
+
+ #defaultLookup (origin, opts, cb) {
+ lookup(
+ origin.hostname,
+ {
+ all: true,
+ family: this.dualStack === false ? this.affinity : 0,
+ order: 'ipv4first'
+ },
+ (err, addresses) => {
+ if (err) {
+ return cb(err)
+ }
+
+ const results = new Map()
+
+ for (const addr of addresses) {
+ // On linux we found duplicates, we attempt to remove them with
+ // the latest record
+ results.set(`${addr.address}:${addr.family}`, addr)
}
+
+ cb(null, results.values())
}
- ))
+ )
}
-}
-module.exports = {
- fetch,
- Fetch,
- fetching,
- finalizeAndReportTiming
-}
+ #defaultPick (origin, hostnameRecords, affinity) {
+ let ip = null
+ const { records, offset } = hostnameRecords
+ let family
+ if (this.dualStack) {
+ if (affinity == null) {
+ // Balance between ip families
+ if (offset == null || offset === maxInt) {
+ hostnameRecords.offset = 0
+ affinity = 4
+ } else {
+ hostnameRecords.offset++
+ affinity = (hostnameRecords.offset & 1) === 1 ? 6 : 4
+ }
+ }
-/***/ }),
+ if (records[affinity] != null && records[affinity].ips.length > 0) {
+ family = records[affinity]
+ } else {
+ family = records[affinity === 4 ? 6 : 4]
+ }
+ } else {
+ family = records[affinity]
+ }
-/***/ 7412:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // If no IPs we return null
+ if (family == null || family.ips.length === 0) {
+ return ip
+ }
-/* globals AbortController */
+ if (family.offset == null || family.offset === maxInt) {
+ family.offset = 0
+ } else {
+ family.offset++
+ }
+ const position = family.offset % family.ips.length
+ ip = family.ips[position] ?? null
+ if (ip == null) {
+ return ip
+ }
-const { extractBody, mixinBody, cloneBody, bodyUnusable } = __nccwpck_require__(3278)
-const { Headers, fill: fillHeaders, HeadersList, setHeadersGuard, getHeadersGuard, setHeadersList, getHeadersList } = __nccwpck_require__(1271)
-const { FinalizationRegistry } = __nccwpck_require__(656)()
-const util = __nccwpck_require__(7375)
-const nodeUtil = __nccwpck_require__(7975)
-const {
- isValidHTTPToken,
- sameOrigin,
- environmentSettingsObject
-} = __nccwpck_require__(7241)
-const {
- forbiddenMethodsSet,
- corsSafeListedMethodsSet,
- referrerPolicy,
- requestRedirect,
- requestMode,
- requestCredentials,
- requestCache,
- requestDuplex
-} = __nccwpck_require__(5336)
-const { kEnumerableProperty, normalizedMethodRecordsBase, normalizedMethodRecords } = util
-const { kHeaders, kSignal, kState, kDispatcher } = __nccwpck_require__(1944)
-const { webidl } = __nccwpck_require__(220)
-const { URLSerializer } = __nccwpck_require__(2121)
-const { kConstruct } = __nccwpck_require__(6130)
-const assert = __nccwpck_require__(4589)
-const { getMaxListeners, setMaxListeners, getEventListeners, defaultMaxListeners } = __nccwpck_require__(8474)
+ if (Date.now() - ip.timestamp > ip.ttl) { // record TTL is already in ms
+ // We delete expired records
+ // It is possible that they have different TTL, so we manage them individually
+ family.ips.splice(position, 1)
+ return this.pick(origin, hostnameRecords, affinity)
+ }
-const kAbortController = Symbol('abortController')
+ return ip
+ }
-const requestFinalizer = new FinalizationRegistry(({ signal, abort }) => {
- signal.removeEventListener('abort', abort)
-})
+ setRecords (origin, addresses) {
+ const timestamp = Date.now()
+ const records = { records: { 4: null, 6: null } }
+ for (const record of addresses) {
+ record.timestamp = timestamp
+ if (typeof record.ttl === 'number') {
+ // The record TTL is expected to be in ms
+ record.ttl = Math.min(record.ttl, this.#maxTTL)
+ } else {
+ record.ttl = this.#maxTTL
+ }
-const dependentControllerMap = new WeakMap()
+ const familyRecords = records.records[record.family] ?? { ips: [] }
-function buildAbort (acRef) {
- return abort
+ familyRecords.ips.push(record)
+ records.records[record.family] = familyRecords
+ }
- function abort () {
- const ac = acRef.deref()
- if (ac !== undefined) {
- // Currently, there is a problem with FinalizationRegistry.
- // https://github.com/nodejs/node/issues/49344
- // https://github.com/nodejs/node/issues/47748
- // In the case of abort, the first step is to unregister from it.
- // If the controller can refer to it, it is still registered.
- // It will be removed in the future.
- requestFinalizer.unregister(abort)
+ this.#records.set(origin.hostname, records)
+ }
- // Unsubscribe a listener.
- // FinalizationRegistry will no longer be called, so this must be done.
- this.removeEventListener('abort', abort)
+ getHandler (meta, opts) {
+ return new DNSDispatchHandler(this, meta, opts)
+ }
+}
- ac.abort(this.reason)
+class DNSDispatchHandler extends DecoratorHandler {
+ #state = null
+ #opts = null
+ #dispatch = null
+ #handler = null
+ #origin = null
- const controllerList = dependentControllerMap.get(ac.signal)
+ constructor (state, { origin, handler, dispatch }, opts) {
+ super(handler)
+ this.#origin = origin
+ this.#handler = handler
+ this.#opts = { ...opts }
+ this.#state = state
+ this.#dispatch = dispatch
+ }
- if (controllerList !== undefined) {
- if (controllerList.size !== 0) {
- for (const ref of controllerList) {
- const ctrl = ref.deref()
- if (ctrl !== undefined) {
- ctrl.abort(this.reason)
+ onError (err) {
+ switch (err.code) {
+ case 'ETIMEDOUT':
+ case 'ECONNREFUSED': {
+ if (this.#state.dualStack) {
+ // We delete the record and retry
+ this.#state.runLookup(this.#origin, this.#opts, (err, newOrigin) => {
+ if (err) {
+ return this.#handler.onError(err)
}
- }
- controllerList.clear()
+
+ const dispatchOpts = {
+ ...this.#opts,
+ origin: newOrigin
+ }
+
+ this.#dispatch(dispatchOpts, this)
+ })
+
+ // if dual-stack disabled, we error out
+ return
}
- dependentControllerMap.delete(ac.signal)
+
+ this.#handler.onError(err)
+ return
}
+ case 'ENOTFOUND':
+ this.#state.deleteRecord(this.#origin)
+ // eslint-disable-next-line no-fallthrough
+ default:
+ this.#handler.onError(err)
+ break
}
}
}
-let patchMethodWarning = false
+module.exports = interceptorOpts => {
+ if (
+ interceptorOpts?.maxTTL != null &&
+ (typeof interceptorOpts?.maxTTL !== 'number' || interceptorOpts?.maxTTL < 0)
+ ) {
+ throw new InvalidArgumentError('Invalid maxTTL. Must be a positive number')
+ }
-// https://fetch.spec.whatwg.org/#request-class
-class Request {
- // https://fetch.spec.whatwg.org/#dom-request
- constructor (input, init = {}) {
- webidl.util.markAsUncloneable(this)
- if (input === kConstruct) {
- return
- }
+ if (
+ interceptorOpts?.maxItems != null &&
+ (typeof interceptorOpts?.maxItems !== 'number' ||
+ interceptorOpts?.maxItems < 1)
+ ) {
+ throw new InvalidArgumentError(
+ 'Invalid maxItems. Must be a positive number and greater than zero'
+ )
+ }
- const prefix = 'Request constructor'
- webidl.argumentLengthCheck(arguments, 1, prefix)
+ if (
+ interceptorOpts?.affinity != null &&
+ interceptorOpts?.affinity !== 4 &&
+ interceptorOpts?.affinity !== 6
+ ) {
+ throw new InvalidArgumentError('Invalid affinity. Must be either 4 or 6')
+ }
- input = webidl.converters.RequestInfo(input, prefix, 'input')
- init = webidl.converters.RequestInit(init, prefix, 'init')
+ if (
+ interceptorOpts?.dualStack != null &&
+ typeof interceptorOpts?.dualStack !== 'boolean'
+ ) {
+ throw new InvalidArgumentError('Invalid dualStack. Must be a boolean')
+ }
- // 1. Let request be null.
- let request = null
+ if (
+ interceptorOpts?.lookup != null &&
+ typeof interceptorOpts?.lookup !== 'function'
+ ) {
+ throw new InvalidArgumentError('Invalid lookup. Must be a function')
+ }
- // 2. Let fallbackMode be null.
- let fallbackMode = null
+ if (
+ interceptorOpts?.pick != null &&
+ typeof interceptorOpts?.pick !== 'function'
+ ) {
+ throw new InvalidArgumentError('Invalid pick. Must be a function')
+ }
- // 3. Let baseURL be this’s relevant settings object’s API base URL.
- const baseUrl = environmentSettingsObject.settingsObject.baseUrl
+ const dualStack = interceptorOpts?.dualStack ?? true
+ let affinity
+ if (dualStack) {
+ affinity = interceptorOpts?.affinity ?? null
+ } else {
+ affinity = interceptorOpts?.affinity ?? 4
+ }
- // 4. Let signal be null.
- let signal = null
+ const opts = {
+ maxTTL: interceptorOpts?.maxTTL ?? 10e3, // Expressed in ms
+ lookup: interceptorOpts?.lookup ?? null,
+ pick: interceptorOpts?.pick ?? null,
+ dualStack,
+ affinity,
+ maxItems: interceptorOpts?.maxItems ?? Infinity
+ }
- // 5. If input is a string, then:
- if (typeof input === 'string') {
- this[kDispatcher] = init.dispatcher
+ const instance = new DNSInstance(opts)
- // 1. Let parsedURL be the result of parsing input with baseURL.
- // 2. If parsedURL is failure, then throw a TypeError.
- let parsedURL
- try {
- parsedURL = new URL(input, baseUrl)
- } catch (err) {
- throw new TypeError('Failed to parse URL from ' + input, { cause: err })
+ return dispatch => {
+ return function dnsInterceptor (origDispatchOpts, handler) {
+ const origin =
+ origDispatchOpts.origin.constructor === URL
+ ? origDispatchOpts.origin
+ : new URL(origDispatchOpts.origin)
+
+ if (isIP(origin.hostname) !== 0) {
+ return dispatch(origDispatchOpts, handler)
}
- // 3. If parsedURL includes credentials, then throw a TypeError.
- if (parsedURL.username || parsedURL.password) {
- throw new TypeError(
- 'Request cannot be constructed from a URL that includes credentials: ' +
- input
+ instance.runLookup(origin, origDispatchOpts, (err, newOrigin) => {
+ if (err) {
+ return handler.onError(err)
+ }
+
+ let dispatchOpts = null
+ dispatchOpts = {
+ ...origDispatchOpts,
+ servername: origin.hostname, // For SNI on TLS
+ origin: newOrigin,
+ headers: {
+ host: origin.hostname,
+ ...origDispatchOpts.headers
+ }
+ }
+
+ dispatch(
+ dispatchOpts,
+ instance.getHandler({ origin, dispatch, handler }, origDispatchOpts)
)
- }
+ })
- // 4. Set request to a new request whose URL is parsedURL.
- request = makeRequest({ urlList: [parsedURL] })
+ return true
+ }
+ }
+}
- // 5. Set fallbackMode to "cors".
- fallbackMode = 'cors'
- } else {
- this[kDispatcher] = init.dispatcher || input[kDispatcher]
- // 6. Otherwise:
+/***/ }),
- // 7. Assert: input is a Request object.
- assert(input instanceof Request)
+/***/ 8060:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 8. Set request to input’s request.
- request = input[kState]
- // 9. Set signal to input’s signal.
- signal = input[kSignal]
- }
- // 7. Let origin be this’s relevant settings object’s origin.
- const origin = environmentSettingsObject.settingsObject.origin
+const util = __nccwpck_require__(3440)
+const { InvalidArgumentError, RequestAbortedError } = __nccwpck_require__(8707)
+const DecoratorHandler = __nccwpck_require__(8155)
- // 8. Let window be "client".
- let window = 'client'
+class DumpHandler extends DecoratorHandler {
+ #maxSize = 1024 * 1024
+ #abort = null
+ #dumped = false
+ #aborted = false
+ #size = 0
+ #reason = null
+ #handler = null
- // 9. If request’s window is an environment settings object and its origin
- // is same origin with origin, then set window to request’s window.
- if (
- request.window?.constructor?.name === 'EnvironmentSettingsObject' &&
- sameOrigin(request.window, origin)
- ) {
- window = request.window
- }
+ constructor ({ maxSize }, handler) {
+ super(handler)
- // 10. If init["window"] exists and is non-null, then throw a TypeError.
- if (init.window != null) {
- throw new TypeError(`'window' option '${window}' must be null`)
+ if (maxSize != null && (!Number.isFinite(maxSize) || maxSize < 1)) {
+ throw new InvalidArgumentError('maxSize must be a number greater than 0')
}
- // 11. If init["window"] exists, then set window to "no-window".
- if ('window' in init) {
- window = 'no-window'
- }
+ this.#maxSize = maxSize ?? this.#maxSize
+ this.#handler = handler
+ }
- // 12. Set request to a new request with the following properties:
- request = makeRequest({
- // URL request’s URL.
- // undici implementation note: this is set as the first item in request's urlList in makeRequest
- // method request’s method.
- method: request.method,
- // header list A copy of request’s header list.
- // undici implementation note: headersList is cloned in makeRequest
- headersList: request.headersList,
- // unsafe-request flag Set.
- unsafeRequest: request.unsafeRequest,
- // client This’s relevant settings object.
- client: environmentSettingsObject.settingsObject,
- // window window.
- window,
- // priority request’s priority.
- priority: request.priority,
- // origin request’s origin. The propagation of the origin is only significant for navigation requests
- // being handled by a service worker. In this scenario a request can have an origin that is different
- // from the current client.
- origin: request.origin,
- // referrer request’s referrer.
- referrer: request.referrer,
- // referrer policy request’s referrer policy.
- referrerPolicy: request.referrerPolicy,
- // mode request’s mode.
- mode: request.mode,
- // credentials mode request’s credentials mode.
- credentials: request.credentials,
- // cache mode request’s cache mode.
- cache: request.cache,
- // redirect mode request’s redirect mode.
- redirect: request.redirect,
- // integrity metadata request’s integrity metadata.
- integrity: request.integrity,
- // keepalive request’s keepalive.
- keepalive: request.keepalive,
- // reload-navigation flag request’s reload-navigation flag.
- reloadNavigation: request.reloadNavigation,
- // history-navigation flag request’s history-navigation flag.
- historyNavigation: request.historyNavigation,
- // URL list A clone of request’s URL list.
- urlList: [...request.urlList]
- })
+ onConnect (abort) {
+ this.#abort = abort
- const initHasKey = Object.keys(init).length !== 0
+ this.#handler.onConnect(this.#customAbort.bind(this))
+ }
- // 13. If init is not empty, then:
- if (initHasKey) {
- // 1. If request’s mode is "navigate", then set it to "same-origin".
- if (request.mode === 'navigate') {
- request.mode = 'same-origin'
- }
+ #customAbort (reason) {
+ this.#aborted = true
+ this.#reason = reason
+ }
- // 2. Unset request’s reload-navigation flag.
- request.reloadNavigation = false
+ // TODO: will require adjustment after new hooks are out
+ onHeaders (statusCode, rawHeaders, resume, statusMessage) {
+ const headers = util.parseHeaders(rawHeaders)
+ const contentLength = headers['content-length']
- // 3. Unset request’s history-navigation flag.
- request.historyNavigation = false
+ if (contentLength != null && contentLength > this.#maxSize) {
+ throw new RequestAbortedError(
+ `Response size (${contentLength}) larger than maxSize (${
+ this.#maxSize
+ })`
+ )
+ }
- // 4. Set request’s origin to "client".
- request.origin = 'client'
+ if (this.#aborted) {
+ return true
+ }
- // 5. Set request’s referrer to "client"
- request.referrer = 'client'
+ return this.#handler.onHeaders(
+ statusCode,
+ rawHeaders,
+ resume,
+ statusMessage
+ )
+ }
- // 6. Set request’s referrer policy to the empty string.
- request.referrerPolicy = ''
+ onError (err) {
+ if (this.#dumped) {
+ return
+ }
- // 7. Set request’s URL to request’s current URL.
- request.url = request.urlList[request.urlList.length - 1]
+ err = this.#reason ?? err
- // 8. Set request’s URL list to « request’s URL ».
- request.urlList = [request.url]
- }
+ this.#handler.onError(err)
+ }
- // 14. If init["referrer"] exists, then:
- if (init.referrer !== undefined) {
- // 1. Let referrer be init["referrer"].
- const referrer = init.referrer
+ onData (chunk) {
+ this.#size = this.#size + chunk.length
- // 2. If referrer is the empty string, then set request’s referrer to "no-referrer".
- if (referrer === '') {
- request.referrer = 'no-referrer'
- } else {
- // 1. Let parsedReferrer be the result of parsing referrer with
- // baseURL.
- // 2. If parsedReferrer is failure, then throw a TypeError.
- let parsedReferrer
- try {
- parsedReferrer = new URL(referrer, baseUrl)
- } catch (err) {
- throw new TypeError(`Referrer "${referrer}" is not a valid URL.`, { cause: err })
- }
+ if (this.#size >= this.#maxSize) {
+ this.#dumped = true
- // 3. If one of the following is true
- // - parsedReferrer’s scheme is "about" and path is the string "client"
- // - parsedReferrer’s origin is not same origin with origin
- // then set request’s referrer to "client".
- if (
- (parsedReferrer.protocol === 'about:' && parsedReferrer.hostname === 'client') ||
- (origin && !sameOrigin(parsedReferrer, environmentSettingsObject.settingsObject.baseUrl))
- ) {
- request.referrer = 'client'
- } else {
- // 4. Otherwise, set request’s referrer to parsedReferrer.
- request.referrer = parsedReferrer
- }
+ if (this.#aborted) {
+ this.#handler.onError(this.#reason)
+ } else {
+ this.#handler.onComplete([])
}
}
- // 15. If init["referrerPolicy"] exists, then set request’s referrer policy
- // to it.
- if (init.referrerPolicy !== undefined) {
- request.referrerPolicy = init.referrerPolicy
- }
-
- // 16. Let mode be init["mode"] if it exists, and fallbackMode otherwise.
- let mode
- if (init.mode !== undefined) {
- mode = init.mode
- } else {
- mode = fallbackMode
- }
+ return true
+ }
- // 17. If mode is "navigate", then throw a TypeError.
- if (mode === 'navigate') {
- throw webidl.errors.exception({
- header: 'Request constructor',
- message: 'invalid request mode navigate.'
- })
+ onComplete (trailers) {
+ if (this.#dumped) {
+ return
}
- // 18. If mode is non-null, set request’s mode to mode.
- if (mode != null) {
- request.mode = mode
+ if (this.#aborted) {
+ this.#handler.onError(this.reason)
+ return
}
- // 19. If init["credentials"] exists, then set request’s credentials mode
- // to it.
- if (init.credentials !== undefined) {
- request.credentials = init.credentials
- }
+ this.#handler.onComplete(trailers)
+ }
+}
- // 18. If init["cache"] exists, then set request’s cache mode to it.
- if (init.cache !== undefined) {
- request.cache = init.cache
- }
+function createDumpInterceptor (
+ { maxSize: defaultMaxSize } = {
+ maxSize: 1024 * 1024
+ }
+) {
+ return dispatch => {
+ return function Intercept (opts, handler) {
+ const { dumpMaxSize = defaultMaxSize } =
+ opts
- // 21. If request’s cache mode is "only-if-cached" and request’s mode is
- // not "same-origin", then throw a TypeError.
- if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {
- throw new TypeError(
- "'only-if-cached' can be set only with 'same-origin' mode"
+ const dumpHandler = new DumpHandler(
+ { maxSize: dumpMaxSize },
+ handler
)
- }
-
- // 22. If init["redirect"] exists, then set request’s redirect mode to it.
- if (init.redirect !== undefined) {
- request.redirect = init.redirect
- }
-
- // 23. If init["integrity"] exists, then set request’s integrity metadata to it.
- if (init.integrity != null) {
- request.integrity = String(init.integrity)
- }
- // 24. If init["keepalive"] exists, then set request’s keepalive to it.
- if (init.keepalive !== undefined) {
- request.keepalive = Boolean(init.keepalive)
+ return dispatch(opts, dumpHandler)
}
+ }
+}
- // 25. If init["method"] exists, then:
- if (init.method !== undefined) {
- // 1. Let method be init["method"].
- let method = init.method
+module.exports = createDumpInterceptor
- const mayBeNormalized = normalizedMethodRecords[method]
- if (mayBeNormalized !== undefined) {
- // Note: Bypass validation DELETE, GET, HEAD, OPTIONS, POST, PUT, PATCH and these lowercase ones
- request.method = mayBeNormalized
- } else {
- // 2. If method is not a method or method is a forbidden method, then
- // throw a TypeError.
- if (!isValidHTTPToken(method)) {
- throw new TypeError(`'${method}' is not a valid HTTP method.`)
- }
+/***/ }),
- const upperCase = method.toUpperCase()
+/***/ 5092:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- if (forbiddenMethodsSet.has(upperCase)) {
- throw new TypeError(`'${method}' HTTP method is unsupported.`)
- }
- // 3. Normalize method.
- // https://fetch.spec.whatwg.org/#concept-method-normalize
- // Note: must be in uppercase
- method = normalizedMethodRecordsBase[upperCase] ?? method
- // 4. Set request’s method to method.
- request.method = method
- }
+const RedirectHandler = __nccwpck_require__(8754)
- if (!patchMethodWarning && request.method === 'patch') {
- process.emitWarning('Using `patch` is highly likely to result in a `405 Method Not Allowed`. `PATCH` is much more likely to succeed.', {
- code: 'UNDICI-FETCH-patch'
- })
+function createRedirectInterceptor ({ maxRedirections: defaultMaxRedirections }) {
+ return (dispatch) => {
+ return function Intercept (opts, handler) {
+ const { maxRedirections = defaultMaxRedirections } = opts
- patchMethodWarning = true
+ if (!maxRedirections) {
+ return dispatch(opts, handler)
}
- }
- // 26. If init["signal"] exists, then set signal to it.
- if (init.signal !== undefined) {
- signal = init.signal
+ const redirectHandler = new RedirectHandler(dispatch, maxRedirections, opts, handler)
+ opts = { ...opts, maxRedirections: 0 } // Stop sub dispatcher from also redirecting.
+ return dispatch(opts, redirectHandler)
}
+ }
+}
- // 27. Set this’s request to request.
- this[kState] = request
-
- // 28. Set this’s signal to a new AbortSignal object with this’s relevant
- // Realm.
- // TODO: could this be simplified with AbortSignal.any
- // (https://dom.spec.whatwg.org/#dom-abortsignal-any)
- const ac = new AbortController()
- this[kSignal] = ac.signal
-
- // 29. If signal is not null, then make this’s signal follow signal.
- if (signal != null) {
- if (
- !signal ||
- typeof signal.aborted !== 'boolean' ||
- typeof signal.addEventListener !== 'function'
- ) {
- throw new TypeError(
- "Failed to construct 'Request': member signal is not of type AbortSignal."
- )
- }
-
- if (signal.aborted) {
- ac.abort(signal.reason)
- } else {
- // Keep a strong ref to ac while request object
- // is alive. This is needed to prevent AbortController
- // from being prematurely garbage collected.
- // See, https://github.com/nodejs/undici/issues/1926.
- this[kAbortController] = ac
-
- const acRef = new WeakRef(ac)
- const abort = buildAbort(acRef)
-
- // Third-party AbortControllers may not work with these.
- // See, https://github.com/nodejs/undici/pull/1910#issuecomment-1464495619.
- try {
- // If the max amount of listeners is equal to the default, increase it
- // This is only available in node >= v19.9.0
- if (typeof getMaxListeners === 'function' && getMaxListeners(signal) === defaultMaxListeners) {
- setMaxListeners(1500, signal)
- } else if (getEventListeners(signal, 'abort').length >= defaultMaxListeners) {
- setMaxListeners(1500, signal)
- }
- } catch {}
+module.exports = createRedirectInterceptor
- util.addAbortListener(signal, abort)
- // The third argument must be a registry key to be unregistered.
- // Without it, you cannot unregister.
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry
- // abort is used as the unregister key. (because it is unique)
- requestFinalizer.register(ac, { signal, abort }, abort)
- }
- }
- // 30. Set this’s headers to a new Headers object with this’s relevant
- // Realm, whose header list is request’s header list and guard is
- // "request".
- this[kHeaders] = new Headers(kConstruct)
- setHeadersList(this[kHeaders], request.headersList)
- setHeadersGuard(this[kHeaders], 'request')
+/***/ }),
- // 31. If this’s request’s mode is "no-cors", then:
- if (mode === 'no-cors') {
- // 1. If this’s request’s method is not a CORS-safelisted method,
- // then throw a TypeError.
- if (!corsSafeListedMethodsSet.has(request.method)) {
- throw new TypeError(
- `'${request.method} is unsupported in no-cors mode.`
- )
- }
+/***/ 1514:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 2. Set this’s headers’s guard to "request-no-cors".
- setHeadersGuard(this[kHeaders], 'request-no-cors')
- }
- // 32. If init is not empty, then:
- if (initHasKey) {
- /** @type {HeadersList} */
- const headersList = getHeadersList(this[kHeaders])
- // 1. Let headers be a copy of this’s headers and its associated header
- // list.
- // 2. If init["headers"] exists, then set headers to init["headers"].
- const headers = init.headers !== undefined ? init.headers : new HeadersList(headersList)
+const RedirectHandler = __nccwpck_require__(8754)
- // 3. Empty this’s headers’s header list.
- headersList.clear()
+module.exports = opts => {
+ const globalMaxRedirections = opts?.maxRedirections
+ return dispatch => {
+ return function redirectInterceptor (opts, handler) {
+ const { maxRedirections = globalMaxRedirections, ...baseOpts } = opts
- // 4. If headers is a Headers object, then for each header in its header
- // list, append header’s name/header’s value to this’s headers.
- if (headers instanceof HeadersList) {
- for (const { name, value } of headers.rawValues()) {
- headersList.append(name, value, false)
- }
- // Note: Copy the `set-cookie` meta-data.
- headersList.cookies = headers.cookies
- } else {
- // 5. Otherwise, fill this’s headers with headers.
- fillHeaders(this[kHeaders], headers)
+ if (!maxRedirections) {
+ return dispatch(opts, handler)
}
- }
-
- // 33. Let inputBody be input’s request’s body if input is a Request
- // object; otherwise null.
- const inputBody = input instanceof Request ? input[kState].body : null
-
- // 34. If either init["body"] exists and is non-null or inputBody is
- // non-null, and request’s method is `GET` or `HEAD`, then throw a
- // TypeError.
- if (
- (init.body != null || inputBody != null) &&
- (request.method === 'GET' || request.method === 'HEAD')
- ) {
- throw new TypeError('Request with GET/HEAD method cannot have body.')
- }
-
- // 35. Let initBody be null.
- let initBody = null
- // 36. If init["body"] exists and is non-null, then:
- if (init.body != null) {
- // 1. Let Content-Type be null.
- // 2. Set initBody and Content-Type to the result of extracting
- // init["body"], with keepalive set to request’s keepalive.
- const [extractedBody, contentType] = extractBody(
- init.body,
- request.keepalive
+ const redirectHandler = new RedirectHandler(
+ dispatch,
+ maxRedirections,
+ opts,
+ handler
)
- initBody = extractedBody
-
- // 3, If Content-Type is non-null and this’s headers’s header list does
- // not contain `Content-Type`, then append `Content-Type`/Content-Type to
- // this’s headers.
- if (contentType && !getHeadersList(this[kHeaders]).contains('content-type', true)) {
- this[kHeaders].append('content-type', contentType)
- }
- }
-
- // 37. Let inputOrInitBody be initBody if it is non-null; otherwise
- // inputBody.
- const inputOrInitBody = initBody ?? inputBody
-
- // 38. If inputOrInitBody is non-null and inputOrInitBody’s source is
- // null, then:
- if (inputOrInitBody != null && inputOrInitBody.source == null) {
- // 1. If initBody is non-null and init["duplex"] does not exist,
- // then throw a TypeError.
- if (initBody != null && init.duplex == null) {
- throw new TypeError('RequestInit: duplex option is required when sending a body.')
- }
-
- // 2. If this’s request’s mode is neither "same-origin" nor "cors",
- // then throw a TypeError.
- if (request.mode !== 'same-origin' && request.mode !== 'cors') {
- throw new TypeError(
- 'If request is made from ReadableStream, mode should be "same-origin" or "cors"'
- )
- }
-
- // 3. Set this’s request’s use-CORS-preflight flag.
- request.useCORSPreflightFlag = true
- }
-
- // 39. Let finalBody be inputOrInitBody.
- let finalBody = inputOrInitBody
-
- // 40. If initBody is null and inputBody is non-null, then:
- if (initBody == null && inputBody != null) {
- // 1. If input is unusable, then throw a TypeError.
- if (bodyUnusable(input)) {
- throw new TypeError(
- 'Cannot construct a Request with a Request object that has already been used.'
- )
- }
- // 2. Set finalBody to the result of creating a proxy for inputBody.
- // https://streams.spec.whatwg.org/#readablestream-create-a-proxy
- const identityTransform = new TransformStream()
- inputBody.stream.pipeThrough(identityTransform)
- finalBody = {
- source: inputBody.source,
- length: inputBody.length,
- stream: identityTransform.readable
- }
+ return dispatch(baseOpts, redirectHandler)
}
-
- // 41. Set this’s request’s body to finalBody.
- this[kState].body = finalBody
- }
-
- // Returns request’s HTTP method, which is "GET" by default.
- get method () {
- webidl.brandCheck(this, Request)
-
- // The method getter steps are to return this’s request’s method.
- return this[kState].method
- }
-
- // Returns the URL of request as a string.
- get url () {
- webidl.brandCheck(this, Request)
-
- // The url getter steps are to return this’s request’s URL, serialized.
- return URLSerializer(this[kState].url)
}
+}
- // Returns a Headers object consisting of the headers associated with request.
- // Note that headers added in the network layer by the user agent will not
- // be accounted for in this object, e.g., the "Host" header.
- get headers () {
- webidl.brandCheck(this, Request)
-
- // The headers getter steps are to return this’s headers.
- return this[kHeaders]
- }
- // Returns the kind of resource requested by request, e.g., "document"
- // or "script".
- get destination () {
- webidl.brandCheck(this, Request)
+/***/ }),
- // The destination getter are to return this’s request’s destination.
- return this[kState].destination
- }
+/***/ 2026:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // Returns the referrer of request. Its value can be a same-origin URL if
- // explicitly set in init, the empty string to indicate no referrer, and
- // "about:client" when defaulting to the global’s default. This is used
- // during fetching to determine the value of the `Referer` header of the
- // request being made.
- get referrer () {
- webidl.brandCheck(this, Request)
- // 1. If this’s request’s referrer is "no-referrer", then return the
- // empty string.
- if (this[kState].referrer === 'no-referrer') {
- return ''
- }
+const RetryHandler = __nccwpck_require__(7816)
- // 2. If this’s request’s referrer is "client", then return
- // "about:client".
- if (this[kState].referrer === 'client') {
- return 'about:client'
+module.exports = globalOpts => {
+ return dispatch => {
+ return function retryInterceptor (opts, handler) {
+ return dispatch(
+ opts,
+ new RetryHandler(
+ { ...opts, retryOptions: { ...globalOpts, ...opts.retryOptions } },
+ {
+ handler,
+ dispatch
+ }
+ )
+ )
}
-
- // Return this’s request’s referrer, serialized.
- return this[kState].referrer.toString()
- }
-
- // Returns the referrer policy associated with request.
- // This is used during fetching to compute the value of the request’s
- // referrer.
- get referrerPolicy () {
- webidl.brandCheck(this, Request)
-
- // The referrerPolicy getter steps are to return this’s request’s referrer policy.
- return this[kState].referrerPolicy
- }
-
- // Returns the mode associated with request, which is a string indicating
- // whether the request will use CORS, or will be restricted to same-origin
- // URLs.
- get mode () {
- webidl.brandCheck(this, Request)
-
- // The mode getter steps are to return this’s request’s mode.
- return this[kState].mode
- }
-
- // Returns the credentials mode associated with request,
- // which is a string indicating whether credentials will be sent with the
- // request always, never, or only when sent to a same-origin URL.
- get credentials () {
- // The credentials getter steps are to return this’s request’s credentials mode.
- return this[kState].credentials
- }
-
- // Returns the cache mode associated with request,
- // which is a string indicating how the request will
- // interact with the browser’s cache when fetching.
- get cache () {
- webidl.brandCheck(this, Request)
-
- // The cache getter steps are to return this’s request’s cache mode.
- return this[kState].cache
- }
-
- // Returns the redirect mode associated with request,
- // which is a string indicating how redirects for the
- // request will be handled during fetching. A request
- // will follow redirects by default.
- get redirect () {
- webidl.brandCheck(this, Request)
-
- // The redirect getter steps are to return this’s request’s redirect mode.
- return this[kState].redirect
- }
-
- // Returns request’s subresource integrity metadata, which is a
- // cryptographic hash of the resource being fetched. Its value
- // consists of multiple hashes separated by whitespace. [SRI]
- get integrity () {
- webidl.brandCheck(this, Request)
-
- // The integrity getter steps are to return this’s request’s integrity
- // metadata.
- return this[kState].integrity
- }
-
- // Returns a boolean indicating whether or not request can outlive the
- // global in which it was created.
- get keepalive () {
- webidl.brandCheck(this, Request)
-
- // The keepalive getter steps are to return this’s request’s keepalive.
- return this[kState].keepalive
}
+}
- // Returns a boolean indicating whether or not request is for a reload
- // navigation.
- get isReloadNavigation () {
- webidl.brandCheck(this, Request)
- // The isReloadNavigation getter steps are to return true if this’s
- // request’s reload-navigation flag is set; otherwise false.
- return this[kState].reloadNavigation
- }
+/***/ }),
- // Returns a boolean indicating whether or not request is for a history
- // navigation (a.k.a. back-forward navigation).
- get isHistoryNavigation () {
- webidl.brandCheck(this, Request)
+/***/ 2824:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // The isHistoryNavigation getter steps are to return true if this’s request’s
- // history-navigation flag is set; otherwise false.
- return this[kState].historyNavigation
- }
- // Returns the signal associated with request, which is an AbortSignal
- // object indicating whether or not request has been aborted, and its
- // abort event handler.
- get signal () {
- webidl.brandCheck(this, Request)
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.SPECIAL_HEADERS = exports.HEADER_STATE = exports.MINOR = exports.MAJOR = exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS = exports.TOKEN = exports.STRICT_TOKEN = exports.HEX = exports.URL_CHAR = exports.STRICT_URL_CHAR = exports.USERINFO_CHARS = exports.MARK = exports.ALPHANUM = exports.NUM = exports.HEX_MAP = exports.NUM_MAP = exports.ALPHA = exports.FINISH = exports.H_METHOD_MAP = exports.METHOD_MAP = exports.METHODS_RTSP = exports.METHODS_ICE = exports.METHODS_HTTP = exports.METHODS = exports.LENIENT_FLAGS = exports.FLAGS = exports.TYPE = exports.ERROR = void 0;
+const utils_1 = __nccwpck_require__(172);
+// C headers
+var ERROR;
+(function (ERROR) {
+ ERROR[ERROR["OK"] = 0] = "OK";
+ ERROR[ERROR["INTERNAL"] = 1] = "INTERNAL";
+ ERROR[ERROR["STRICT"] = 2] = "STRICT";
+ ERROR[ERROR["LF_EXPECTED"] = 3] = "LF_EXPECTED";
+ ERROR[ERROR["UNEXPECTED_CONTENT_LENGTH"] = 4] = "UNEXPECTED_CONTENT_LENGTH";
+ ERROR[ERROR["CLOSED_CONNECTION"] = 5] = "CLOSED_CONNECTION";
+ ERROR[ERROR["INVALID_METHOD"] = 6] = "INVALID_METHOD";
+ ERROR[ERROR["INVALID_URL"] = 7] = "INVALID_URL";
+ ERROR[ERROR["INVALID_CONSTANT"] = 8] = "INVALID_CONSTANT";
+ ERROR[ERROR["INVALID_VERSION"] = 9] = "INVALID_VERSION";
+ ERROR[ERROR["INVALID_HEADER_TOKEN"] = 10] = "INVALID_HEADER_TOKEN";
+ ERROR[ERROR["INVALID_CONTENT_LENGTH"] = 11] = "INVALID_CONTENT_LENGTH";
+ ERROR[ERROR["INVALID_CHUNK_SIZE"] = 12] = "INVALID_CHUNK_SIZE";
+ ERROR[ERROR["INVALID_STATUS"] = 13] = "INVALID_STATUS";
+ ERROR[ERROR["INVALID_EOF_STATE"] = 14] = "INVALID_EOF_STATE";
+ ERROR[ERROR["INVALID_TRANSFER_ENCODING"] = 15] = "INVALID_TRANSFER_ENCODING";
+ ERROR[ERROR["CB_MESSAGE_BEGIN"] = 16] = "CB_MESSAGE_BEGIN";
+ ERROR[ERROR["CB_HEADERS_COMPLETE"] = 17] = "CB_HEADERS_COMPLETE";
+ ERROR[ERROR["CB_MESSAGE_COMPLETE"] = 18] = "CB_MESSAGE_COMPLETE";
+ ERROR[ERROR["CB_CHUNK_HEADER"] = 19] = "CB_CHUNK_HEADER";
+ ERROR[ERROR["CB_CHUNK_COMPLETE"] = 20] = "CB_CHUNK_COMPLETE";
+ ERROR[ERROR["PAUSED"] = 21] = "PAUSED";
+ ERROR[ERROR["PAUSED_UPGRADE"] = 22] = "PAUSED_UPGRADE";
+ ERROR[ERROR["PAUSED_H2_UPGRADE"] = 23] = "PAUSED_H2_UPGRADE";
+ ERROR[ERROR["USER"] = 24] = "USER";
+})(ERROR = exports.ERROR || (exports.ERROR = {}));
+var TYPE;
+(function (TYPE) {
+ TYPE[TYPE["BOTH"] = 0] = "BOTH";
+ TYPE[TYPE["REQUEST"] = 1] = "REQUEST";
+ TYPE[TYPE["RESPONSE"] = 2] = "RESPONSE";
+})(TYPE = exports.TYPE || (exports.TYPE = {}));
+var FLAGS;
+(function (FLAGS) {
+ FLAGS[FLAGS["CONNECTION_KEEP_ALIVE"] = 1] = "CONNECTION_KEEP_ALIVE";
+ FLAGS[FLAGS["CONNECTION_CLOSE"] = 2] = "CONNECTION_CLOSE";
+ FLAGS[FLAGS["CONNECTION_UPGRADE"] = 4] = "CONNECTION_UPGRADE";
+ FLAGS[FLAGS["CHUNKED"] = 8] = "CHUNKED";
+ FLAGS[FLAGS["UPGRADE"] = 16] = "UPGRADE";
+ FLAGS[FLAGS["CONTENT_LENGTH"] = 32] = "CONTENT_LENGTH";
+ FLAGS[FLAGS["SKIPBODY"] = 64] = "SKIPBODY";
+ FLAGS[FLAGS["TRAILING"] = 128] = "TRAILING";
+ // 1 << 8 is unused
+ FLAGS[FLAGS["TRANSFER_ENCODING"] = 512] = "TRANSFER_ENCODING";
+})(FLAGS = exports.FLAGS || (exports.FLAGS = {}));
+var LENIENT_FLAGS;
+(function (LENIENT_FLAGS) {
+ LENIENT_FLAGS[LENIENT_FLAGS["HEADERS"] = 1] = "HEADERS";
+ LENIENT_FLAGS[LENIENT_FLAGS["CHUNKED_LENGTH"] = 2] = "CHUNKED_LENGTH";
+ LENIENT_FLAGS[LENIENT_FLAGS["KEEP_ALIVE"] = 4] = "KEEP_ALIVE";
+})(LENIENT_FLAGS = exports.LENIENT_FLAGS || (exports.LENIENT_FLAGS = {}));
+var METHODS;
+(function (METHODS) {
+ METHODS[METHODS["DELETE"] = 0] = "DELETE";
+ METHODS[METHODS["GET"] = 1] = "GET";
+ METHODS[METHODS["HEAD"] = 2] = "HEAD";
+ METHODS[METHODS["POST"] = 3] = "POST";
+ METHODS[METHODS["PUT"] = 4] = "PUT";
+ /* pathological */
+ METHODS[METHODS["CONNECT"] = 5] = "CONNECT";
+ METHODS[METHODS["OPTIONS"] = 6] = "OPTIONS";
+ METHODS[METHODS["TRACE"] = 7] = "TRACE";
+ /* WebDAV */
+ METHODS[METHODS["COPY"] = 8] = "COPY";
+ METHODS[METHODS["LOCK"] = 9] = "LOCK";
+ METHODS[METHODS["MKCOL"] = 10] = "MKCOL";
+ METHODS[METHODS["MOVE"] = 11] = "MOVE";
+ METHODS[METHODS["PROPFIND"] = 12] = "PROPFIND";
+ METHODS[METHODS["PROPPATCH"] = 13] = "PROPPATCH";
+ METHODS[METHODS["SEARCH"] = 14] = "SEARCH";
+ METHODS[METHODS["UNLOCK"] = 15] = "UNLOCK";
+ METHODS[METHODS["BIND"] = 16] = "BIND";
+ METHODS[METHODS["REBIND"] = 17] = "REBIND";
+ METHODS[METHODS["UNBIND"] = 18] = "UNBIND";
+ METHODS[METHODS["ACL"] = 19] = "ACL";
+ /* subversion */
+ METHODS[METHODS["REPORT"] = 20] = "REPORT";
+ METHODS[METHODS["MKACTIVITY"] = 21] = "MKACTIVITY";
+ METHODS[METHODS["CHECKOUT"] = 22] = "CHECKOUT";
+ METHODS[METHODS["MERGE"] = 23] = "MERGE";
+ /* upnp */
+ METHODS[METHODS["M-SEARCH"] = 24] = "M-SEARCH";
+ METHODS[METHODS["NOTIFY"] = 25] = "NOTIFY";
+ METHODS[METHODS["SUBSCRIBE"] = 26] = "SUBSCRIBE";
+ METHODS[METHODS["UNSUBSCRIBE"] = 27] = "UNSUBSCRIBE";
+ /* RFC-5789 */
+ METHODS[METHODS["PATCH"] = 28] = "PATCH";
+ METHODS[METHODS["PURGE"] = 29] = "PURGE";
+ /* CalDAV */
+ METHODS[METHODS["MKCALENDAR"] = 30] = "MKCALENDAR";
+ /* RFC-2068, section 19.6.1.2 */
+ METHODS[METHODS["LINK"] = 31] = "LINK";
+ METHODS[METHODS["UNLINK"] = 32] = "UNLINK";
+ /* icecast */
+ METHODS[METHODS["SOURCE"] = 33] = "SOURCE";
+ /* RFC-7540, section 11.6 */
+ METHODS[METHODS["PRI"] = 34] = "PRI";
+ /* RFC-2326 RTSP */
+ METHODS[METHODS["DESCRIBE"] = 35] = "DESCRIBE";
+ METHODS[METHODS["ANNOUNCE"] = 36] = "ANNOUNCE";
+ METHODS[METHODS["SETUP"] = 37] = "SETUP";
+ METHODS[METHODS["PLAY"] = 38] = "PLAY";
+ METHODS[METHODS["PAUSE"] = 39] = "PAUSE";
+ METHODS[METHODS["TEARDOWN"] = 40] = "TEARDOWN";
+ METHODS[METHODS["GET_PARAMETER"] = 41] = "GET_PARAMETER";
+ METHODS[METHODS["SET_PARAMETER"] = 42] = "SET_PARAMETER";
+ METHODS[METHODS["REDIRECT"] = 43] = "REDIRECT";
+ METHODS[METHODS["RECORD"] = 44] = "RECORD";
+ /* RAOP */
+ METHODS[METHODS["FLUSH"] = 45] = "FLUSH";
+})(METHODS = exports.METHODS || (exports.METHODS = {}));
+exports.METHODS_HTTP = [
+ METHODS.DELETE,
+ METHODS.GET,
+ METHODS.HEAD,
+ METHODS.POST,
+ METHODS.PUT,
+ METHODS.CONNECT,
+ METHODS.OPTIONS,
+ METHODS.TRACE,
+ METHODS.COPY,
+ METHODS.LOCK,
+ METHODS.MKCOL,
+ METHODS.MOVE,
+ METHODS.PROPFIND,
+ METHODS.PROPPATCH,
+ METHODS.SEARCH,
+ METHODS.UNLOCK,
+ METHODS.BIND,
+ METHODS.REBIND,
+ METHODS.UNBIND,
+ METHODS.ACL,
+ METHODS.REPORT,
+ METHODS.MKACTIVITY,
+ METHODS.CHECKOUT,
+ METHODS.MERGE,
+ METHODS['M-SEARCH'],
+ METHODS.NOTIFY,
+ METHODS.SUBSCRIBE,
+ METHODS.UNSUBSCRIBE,
+ METHODS.PATCH,
+ METHODS.PURGE,
+ METHODS.MKCALENDAR,
+ METHODS.LINK,
+ METHODS.UNLINK,
+ METHODS.PRI,
+ // TODO(indutny): should we allow it with HTTP?
+ METHODS.SOURCE,
+];
+exports.METHODS_ICE = [
+ METHODS.SOURCE,
+];
+exports.METHODS_RTSP = [
+ METHODS.OPTIONS,
+ METHODS.DESCRIBE,
+ METHODS.ANNOUNCE,
+ METHODS.SETUP,
+ METHODS.PLAY,
+ METHODS.PAUSE,
+ METHODS.TEARDOWN,
+ METHODS.GET_PARAMETER,
+ METHODS.SET_PARAMETER,
+ METHODS.REDIRECT,
+ METHODS.RECORD,
+ METHODS.FLUSH,
+ // For AirPlay
+ METHODS.GET,
+ METHODS.POST,
+];
+exports.METHOD_MAP = utils_1.enumToMap(METHODS);
+exports.H_METHOD_MAP = {};
+Object.keys(exports.METHOD_MAP).forEach((key) => {
+ if (/^H/.test(key)) {
+ exports.H_METHOD_MAP[key] = exports.METHOD_MAP[key];
+ }
+});
+var FINISH;
+(function (FINISH) {
+ FINISH[FINISH["SAFE"] = 0] = "SAFE";
+ FINISH[FINISH["SAFE_WITH_CB"] = 1] = "SAFE_WITH_CB";
+ FINISH[FINISH["UNSAFE"] = 2] = "UNSAFE";
+})(FINISH = exports.FINISH || (exports.FINISH = {}));
+exports.ALPHA = [];
+for (let i = 'A'.charCodeAt(0); i <= 'Z'.charCodeAt(0); i++) {
+ // Upper case
+ exports.ALPHA.push(String.fromCharCode(i));
+ // Lower case
+ exports.ALPHA.push(String.fromCharCode(i + 0x20));
+}
+exports.NUM_MAP = {
+ 0: 0, 1: 1, 2: 2, 3: 3, 4: 4,
+ 5: 5, 6: 6, 7: 7, 8: 8, 9: 9,
+};
+exports.HEX_MAP = {
+ 0: 0, 1: 1, 2: 2, 3: 3, 4: 4,
+ 5: 5, 6: 6, 7: 7, 8: 8, 9: 9,
+ A: 0XA, B: 0XB, C: 0XC, D: 0XD, E: 0XE, F: 0XF,
+ a: 0xa, b: 0xb, c: 0xc, d: 0xd, e: 0xe, f: 0xf,
+};
+exports.NUM = [
+ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
+];
+exports.ALPHANUM = exports.ALPHA.concat(exports.NUM);
+exports.MARK = ['-', '_', '.', '!', '~', '*', '\'', '(', ')'];
+exports.USERINFO_CHARS = exports.ALPHANUM
+ .concat(exports.MARK)
+ .concat(['%', ';', ':', '&', '=', '+', '$', ',']);
+// TODO(indutny): use RFC
+exports.STRICT_URL_CHAR = [
+ '!', '"', '$', '%', '&', '\'',
+ '(', ')', '*', '+', ',', '-', '.', '/',
+ ':', ';', '<', '=', '>',
+ '@', '[', '\\', ']', '^', '_',
+ '`',
+ '{', '|', '}', '~',
+].concat(exports.ALPHANUM);
+exports.URL_CHAR = exports.STRICT_URL_CHAR
+ .concat(['\t', '\f']);
+// All characters with 0x80 bit set to 1
+for (let i = 0x80; i <= 0xff; i++) {
+ exports.URL_CHAR.push(i);
+}
+exports.HEX = exports.NUM.concat(['a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F']);
+/* Tokens as defined by rfc 2616. Also lowercases them.
+ * token = 1*
+ * separators = "(" | ")" | "<" | ">" | "@"
+ * | "," | ";" | ":" | "\" | <">
+ * | "/" | "[" | "]" | "?" | "="
+ * | "{" | "}" | SP | HT
+ */
+exports.STRICT_TOKEN = [
+ '!', '#', '$', '%', '&', '\'',
+ '*', '+', '-', '.',
+ '^', '_', '`',
+ '|', '~',
+].concat(exports.ALPHANUM);
+exports.TOKEN = exports.STRICT_TOKEN.concat([' ']);
+/*
+ * Verify that a char is a valid visible (printable) US-ASCII
+ * character or %x80-FF
+ */
+exports.HEADER_CHARS = ['\t'];
+for (let i = 32; i <= 255; i++) {
+ if (i !== 127) {
+ exports.HEADER_CHARS.push(i);
+ }
+}
+// ',' = \x44
+exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS.filter((c) => c !== 44);
+exports.MAJOR = exports.NUM_MAP;
+exports.MINOR = exports.MAJOR;
+var HEADER_STATE;
+(function (HEADER_STATE) {
+ HEADER_STATE[HEADER_STATE["GENERAL"] = 0] = "GENERAL";
+ HEADER_STATE[HEADER_STATE["CONNECTION"] = 1] = "CONNECTION";
+ HEADER_STATE[HEADER_STATE["CONTENT_LENGTH"] = 2] = "CONTENT_LENGTH";
+ HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING"] = 3] = "TRANSFER_ENCODING";
+ HEADER_STATE[HEADER_STATE["UPGRADE"] = 4] = "UPGRADE";
+ HEADER_STATE[HEADER_STATE["CONNECTION_KEEP_ALIVE"] = 5] = "CONNECTION_KEEP_ALIVE";
+ HEADER_STATE[HEADER_STATE["CONNECTION_CLOSE"] = 6] = "CONNECTION_CLOSE";
+ HEADER_STATE[HEADER_STATE["CONNECTION_UPGRADE"] = 7] = "CONNECTION_UPGRADE";
+ HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING_CHUNKED"] = 8] = "TRANSFER_ENCODING_CHUNKED";
+})(HEADER_STATE = exports.HEADER_STATE || (exports.HEADER_STATE = {}));
+exports.SPECIAL_HEADERS = {
+ 'connection': HEADER_STATE.CONNECTION,
+ 'content-length': HEADER_STATE.CONTENT_LENGTH,
+ 'proxy-connection': HEADER_STATE.CONNECTION,
+ 'transfer-encoding': HEADER_STATE.TRANSFER_ENCODING,
+ 'upgrade': HEADER_STATE.UPGRADE,
+};
+//# sourceMappingURL=constants.js.map
- // The signal getter steps are to return this’s signal.
- return this[kSignal]
- }
+/***/ }),
- get body () {
- webidl.brandCheck(this, Request)
+/***/ 3870:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- return this[kState].body ? this[kState].body.stream : null
- }
- get bodyUsed () {
- webidl.brandCheck(this, Request)
- return !!this[kState].body && util.isDisturbed(this[kState].body.stream)
- }
+const { Buffer } = __nccwpck_require__(4573)
- get duplex () {
- webidl.brandCheck(this, Request)
+module.exports = Buffer.from('AGFzbQEAAAABJwdgAX8Bf2ADf39/AX9gAX8AYAJ/fwBgBH9/f38Bf2AAAGADf39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQAEA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAAy0sBQYAAAIAAAAAAAACAQIAAgICAAADAAAAAAMDAwMBAQEBAQEBAQEAAAIAAAAEBQFwARISBQMBAAIGCAF/AUGA1AQLB9EFIgZtZW1vcnkCAAtfaW5pdGlhbGl6ZQAIGV9faW5kaXJlY3RfZnVuY3Rpb25fdGFibGUBAAtsbGh0dHBfaW5pdAAJGGxsaHR0cF9zaG91bGRfa2VlcF9hb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ASABLQAAQd8ARw1nGiABQQFqIQEMXgtBigEhAyABIARGDaICIAIoAgAiACAEIAFraiEFIAEgAGtBAWohBgNAIAEtAAAgAEGMzwBqLQAARw1kIABBAUYN+gEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMogILQYsBIQMgASAERg2hAiACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEGOzwBqLQAARw1kIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyiAgsgAkEANgIAIAZBAWohAUECDGULQYwBIQMgASAERg2gAiACKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHwzwBqLQAARw1jIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyhAgsgAkEANgIAIAZBAWohAUEfDGQLQY0BIQMgASAERg2fAiACKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHyzwBqLQAARw1iIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAygAgsgAkEANgIAIAZBAWohAUEJDGMLIAEgBEYEQEGOASEDDJ8CCwJAAkAgAS0AAEHJAGsOBwBiYmJiYgFiCyABQQFqIQFB+AAhAwyGAgsgAUEBaiEBQfkAIQMMhQILQY8BIQMgASAERg2dAiACKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEGRzwBqLQAARw1gIABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyeAgsgAkEANgIAIAZBAWohAUEYDGELQZABIQMgASAERg2cAiACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEGXzwBqLQAARw1fIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAydAgsgAkEANgIAIAZBAWohAUEXDGALQZEBIQMgASAERg2bAiACKAIAIgAgBCABa2ohBSABIABrQQZqIQYCQANAIAEtAAAgAEGazwBqLQAARw1eIABBBkYNASAAQ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NgIUIAIgADYCDEEAIQMMrwELIABBP0cNASABQQFqCyEBQQUhAwyUAQtBACEDIAJBADYCHCACIAE2AhQgAkH9EjYCECACQQc2AgwMrAELIAJBADYCHCACIAE2AhQgAkHcCDYCECACQQc2AgxBACEDDKsBCyACKAIEIQAgAkEANgIEIAIgACABECUiAEUNByACQeUANgIcIAIgATYCFCACIAA2AgxBACEDDKoBCyACKAIEIQAgAkEANgIEIAIgACABECUiAEUNFiACQdMANgIcIAIgATYCFCACIAA2AgxBACEDDKkBCyACKAIEIQAgAkEANgIEIAIgACABECUiAEUNGCACQdIANgIcIAIgATYCFCACIAA2AgxBACEDDKgBCyACQQA2AhwgAiABNgIUIAJBxgo2AhAgAkEHNgIMQQAhAwynAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDQMgAkHlADYCHCACIAE2AhQgAiAANgIMQQAhAwymAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDRIgAkHTADYCHCACIAE2AhQgAiAANgIMQQAhAwylAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDRQgAkHSADYCHCACIAE2AhQgAiAANgIMQQAhAwykAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDQAgAkHlADYCHCACIAE2AhQgAiAANgIMQQAhAwyjAQtB1QAhAwyJAQsgAEEVRwRAIAJBADYCHCACIAE2AhQgAkG5DTYCECACQRo2AgxBACEDDKIBCyACQeQANgIcIAIgATYCFCACQeMXNgIQIAJBFTYCDEEAIQMMoQELIAJBADYCACAGQQFqIQEgAi0AKSIAQSNrQQtJDQQCQCAAQQZLDQBBASAAdEHKAHFFDQAMBQtBACEDIAJBADYCHCACIAE2AhQgAkH3CTYCECACQQg2AgwMoAELIAJBADYCACAGQQFqIQEgAi0AKUEhRg0DIAJBADYCHCACIAE2AhQgAkGbCjYCECACQQg2AgxBACEDDJ8BCyACQQA2AgALQQAhAyACQQA2AhwgAiABNgIUIAJBkDM2AhAgAkEINgIMDJ0BCyACQQA2AgAgBkEBaiE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BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQABAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAQAQfrKAAsEAQAAAQBBkMsACwEBAEGqywALQQIAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAEH6zAALBAEAAAEAQZDNAAsBAQBBms0ACwYCAAAAAAIAQbHNAAs6AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwBB8M4AC5YBTk9VTkNFRUNLT1VUTkVDVEVURUNSSUJFTFVTSEVURUFEU0VBUkNIUkdFQ1RJVklUWUxFTkRBUlZFT1RJRllQVElPTlNDSFNFQVlTVEFUQ0hHRU9SRElSRUNUT1JUUkNIUEFSQU1FVEVSVVJDRUJTQ1JJQkVBUkRPV05BQ0VJTkROS0NLVUJTQ1JJQkVIVFRQL0FEVFAv', 'base64')
- return 'half'
- }
- // Returns a clone of request.
- clone () {
- webidl.brandCheck(this, Request)
+/***/ }),
- // 1. If this is unusable, then throw a TypeError.
- if (bodyUnusable(this)) {
- throw new TypeError('unusable')
- }
+/***/ 3434:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 2. Let clonedRequest be the result of cloning this’s request.
- const clonedRequest = cloneRequest(this[kState])
- // 3. Let clonedRequestObject be the result of creating a Request object,
- // given clonedRequest, this’s headers’s guard, and this’s relevant Realm.
- // 4. Make clonedRequestObject’s signal follow this’s signal.
- const ac = new AbortController()
- if (this.signal.aborted) {
- ac.abort(this.signal.reason)
- } else {
- let list = dependentControllerMap.get(this.signal)
- if (list === undefined) {
- list = new Set()
- dependentControllerMap.set(this.signal, list)
- }
- const acRef = new WeakRef(ac)
- list.add(acRef)
- util.addAbortListener(
- ac.signal,
- buildAbort(acRef)
- )
- }
- // 4. Return clonedRequestObject.
- return fromInnerRequest(clonedRequest, ac.signal, getHeadersGuard(this[kHeaders]))
- }
+const { Buffer } = __nccwpck_require__(4573)
- [nodeUtil.inspect.custom] (depth, options) {
- if (options.depth === null) {
- options.depth = 2
- }
+module.exports = Buffer.from('AGFzbQEAAAABJwdgAX8Bf2ADf39/AX9gAX8AYAJ/fwBgBH9/f38Bf2AAAGADf39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQAEA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAAy0sBQYAAAIAAAAAAAACAQIAAgICAAADAAAAAAMDAwMBAQEBAQEBAQEAAAIAAAAEBQFwARISBQMBAAIGCAF/AUGA1AQLB9EFIgZtZW1vcnkCAAtfaW5pdGlhbGl6ZQAIGV9faW5kaXJlY3RfZnVuY3Rpb25fdGFibGUBAAtsbGh0dHBfaW5pdAAJGGxsaHR0cF9zaG91bGRfa2VlcF9hbGl2ZQAvDGxsaHR0cF9hbGxvYwALBm1hbGxvYwAxC2xsaHR0cF9mcmVlAAwEZnJlZQAMD2xsaHR0cF9nZXRfdHlwZQANFWxsaHR0cF9nZXRfaHR0cF9tYWpvcgAOFWxsaHR0cF9nZXRfaHR0cF9taW5vcgAPEWxsaHR0cF9nZXRfbWV0aG9kABAWbGxodHRwX2dldF9zdGF0dXNfY29kZQAREmxsaHR0cF9nZXRfdXBncmFkZQASDGxsaHR0cF9yZXNldAATDmxsaHR0cF9leGVjdXRlABQUbGxodHRwX3NldHRpbmdzX2luaXQAFQ1sbGh0dHBfZmluaXNoABYMbGxodHRwX3BhdXNlABcNbGxodHRwX3Jlc3VtZQAYG2xsaHR0cF9yZXN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QQN2dCIDcUUEQEGM0AAgAiADcjYCACAADAELIAAoAggLIgIgATYCDCAAIAE2AgggASAANgIMIAEgAjYCCAwBC0EfIQIgBEH///8HTQRAIARBJiAEQQh2ZyIAa3ZBAXEgAEEBdGtBPmohAgsgASACNgIcIAFCADcCECACQQJ0QbzSAGohAAJAQZDQACgCACIDQQEgAnQiB3FFBEAgACABNgIAQZDQACADIAdyNgIAIAEgADYCGCABIAE2AgggASABNgIMDAELIARBGSACQQF2a0EAIAJBH0cbdCECIAAoAgAhAAJAA0AgACIDKAIEQXhxIARGDQEgAkEddiEAIAJBAXQhAiADIABBBHFqQRBqIgcoAgAiAA0ACyAHIAE2AgAgASADNgIYIAEgATYCDCABIAE2AggMAQsgAygCCCIAIAE2AgwgAyABNgIIIAFBADYCGCABIAM2AgwgASAANgIIC0Gs0ABBrNAAKAIAQQFrIgBBfyAAGzYCAAsLBwAgAC0AKAsHACAALQAqCwcAIAAtACsLBwAgAC0AKQsHACAALwEyCwcAIAAtAC4LQAEEfyAAKAIYIQEgAC0ALSECIAAtACghAyAAKAI4IQQgABAwIAAgBDYCOCAAIAM6ACggACACOgAtIAAgATYCGAu74gECB38DfiABIAJqIQQCQCAAIgIoAgwiAA0AIAIoAgQEQCACIAE2AgQLIwBBEGsiCCQAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJA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AQwIC0HGAQwHC0G8AQwGC0G9AQwFC0G+AQwEC0G/AQwDC0HAAQwCC0HCAQwBC0HBAQshAwNAAkACQAJAAkACQAJAAkACQAJAIAICfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJ/AkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAgJ/AkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAn8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQ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AAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAQfDOAAuWAU5PVU5DRUVDS09VVE5FQ1RFVEVDUklCRUxVU0hFVEVBRFNFQVJDSFJHRUNUSVZJVFlMRU5EQVJWRU9USUZZUFRJT05TQ0hTRUFZU1RBVENIR0VPUkRJUkVDVE9SVFJDSFBBUkFNRVRFUlVSQ0VCU0NSSUJFQVJET1dOQUNFSU5ETktDS1VCU0NSSUJFSFRUUC9BRFRQLw==', 'base64')
- options.colors ??= true
- const properties = {
- method: this.method,
- url: this.url,
- headers: this.headers,
- destination: this.destination,
- referrer: this.referrer,
- referrerPolicy: this.referrerPolicy,
- mode: this.mode,
- credentials: this.credentials,
- cache: this.cache,
- redirect: this.redirect,
- integrity: this.integrity,
- keepalive: this.keepalive,
- isReloadNavigation: this.isReloadNavigation,
- isHistoryNavigation: this.isHistoryNavigation,
- signal: this.signal
- }
+/***/ }),
- return `Request ${nodeUtil.formatWithOptions(options, properties)}`
- }
-}
+/***/ 172:
+/***/ ((__unused_webpack_module, exports) => {
-mixinBody(Request)
-// https://fetch.spec.whatwg.org/#requests
-function makeRequest (init) {
- return {
- method: init.method ?? 'GET',
- localURLsOnly: init.localURLsOnly ?? false,
- unsafeRequest: init.unsafeRequest ?? false,
- body: init.body ?? null,
- client: init.client ?? null,
- reservedClient: init.reservedClient ?? null,
- replacesClientId: init.replacesClientId ?? '',
- window: init.window ?? 'client',
- keepalive: init.keepalive ?? false,
- serviceWorkers: init.serviceWorkers ?? 'all',
- initiator: init.initiator ?? '',
- destination: init.destination ?? '',
- priority: init.priority ?? null,
- origin: init.origin ?? 'client',
- policyContainer: init.policyContainer ?? 'client',
- referrer: init.referrer ?? 'client',
- referrerPolicy: init.referrerPolicy ?? '',
- mode: init.mode ?? 'no-cors',
- useCORSPreflightFlag: init.useCORSPreflightFlag ?? false,
- credentials: init.credentials ?? 'same-origin',
- useCredentials: init.useCredentials ?? false,
- cache: init.cache ?? 'default',
- redirect: init.redirect ?? 'follow',
- integrity: init.integrity ?? '',
- cryptoGraphicsNonceMetadata: init.cryptoGraphicsNonceMetadata ?? '',
- parserMetadata: init.parserMetadata ?? '',
- reloadNavigation: init.reloadNavigation ?? false,
- historyNavigation: init.historyNavigation ?? false,
- userActivation: init.userActivation ?? false,
- taintedOrigin: init.taintedOrigin ?? false,
- redirectCount: init.redirectCount ?? 0,
- responseTainting: init.responseTainting ?? 'basic',
- preventNoCacheCacheControlHeaderModification: init.preventNoCacheCacheControlHeaderModification ?? false,
- done: init.done ?? false,
- timingAllowFailed: init.timingAllowFailed ?? false,
- urlList: init.urlList,
- url: init.urlList[0],
- headersList: init.headersList
- ? new HeadersList(init.headersList)
- : new HeadersList()
- }
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.enumToMap = void 0;
+function enumToMap(obj) {
+ const res = {};
+ Object.keys(obj).forEach((key) => {
+ const value = obj[key];
+ if (typeof value === 'number') {
+ res[key] = value;
+ }
+ });
+ return res;
}
+exports.enumToMap = enumToMap;
+//# sourceMappingURL=utils.js.map
-// https://fetch.spec.whatwg.org/#concept-request-clone
-function cloneRequest (request) {
- // To clone a request request, run these steps:
+/***/ }),
- // 1. Let newRequest be a copy of request, except for its body.
- const newRequest = makeRequest({ ...request, body: null })
+/***/ 7501:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 2. If request’s body is non-null, set newRequest’s body to the
- // result of cloning request’s body.
- if (request.body != null) {
- newRequest.body = cloneBody(newRequest, request.body)
- }
- // 3. Return newRequest.
- return newRequest
-}
-/**
- * @see https://fetch.spec.whatwg.org/#request-create
- * @param {any} innerRequest
- * @param {AbortSignal} signal
- * @param {'request' | 'immutable' | 'request-no-cors' | 'response' | 'none'} guard
- * @returns {Request}
- */
-function fromInnerRequest (innerRequest, signal, guard) {
- const request = new Request(kConstruct)
- request[kState] = innerRequest
- request[kSignal] = signal
- request[kHeaders] = new Headers(kConstruct)
- setHeadersList(request[kHeaders], innerRequest.headersList)
- setHeadersGuard(request[kHeaders], guard)
- return request
-}
+const { kClients } = __nccwpck_require__(6443)
+const Agent = __nccwpck_require__(7405)
+const {
+ kAgent,
+ kMockAgentSet,
+ kMockAgentGet,
+ kDispatches,
+ kIsMockActive,
+ kNetConnect,
+ kGetNetConnect,
+ kOptions,
+ kFactory
+} = __nccwpck_require__(1117)
+const MockClient = __nccwpck_require__(7365)
+const MockPool = __nccwpck_require__(4004)
+const { matchValue, buildMockOptions } = __nccwpck_require__(3397)
+const { InvalidArgumentError, UndiciError } = __nccwpck_require__(8707)
+const Dispatcher = __nccwpck_require__(883)
+const Pluralizer = __nccwpck_require__(1529)
+const PendingInterceptorsFormatter = __nccwpck_require__(6142)
-Object.defineProperties(Request.prototype, {
- method: kEnumerableProperty,
- url: kEnumerableProperty,
- headers: kEnumerableProperty,
- redirect: kEnumerableProperty,
- clone: kEnumerableProperty,
- signal: kEnumerableProperty,
- duplex: kEnumerableProperty,
- destination: kEnumerableProperty,
- body: kEnumerableProperty,
- bodyUsed: kEnumerableProperty,
- isHistoryNavigation: kEnumerableProperty,
- isReloadNavigation: kEnumerableProperty,
- keepalive: kEnumerableProperty,
- integrity: kEnumerableProperty,
- cache: kEnumerableProperty,
- credentials: kEnumerableProperty,
- attribute: kEnumerableProperty,
- referrerPolicy: kEnumerableProperty,
- referrer: kEnumerableProperty,
- mode: kEnumerableProperty,
- [Symbol.toStringTag]: {
- value: 'Request',
- configurable: true
- }
-})
+class MockAgent extends Dispatcher {
+ constructor (opts) {
+ super(opts)
-webidl.converters.Request = webidl.interfaceConverter(
- Request
-)
+ this[kNetConnect] = true
+ this[kIsMockActive] = true
-// https://fetch.spec.whatwg.org/#requestinfo
-webidl.converters.RequestInfo = function (V, prefix, argument) {
- if (typeof V === 'string') {
- return webidl.converters.USVString(V, prefix, argument)
- }
+ // Instantiate Agent and encapsulate
+ if ((opts?.agent && typeof opts.agent.dispatch !== 'function')) {
+ throw new InvalidArgumentError('Argument opts.agent must implement Agent')
+ }
+ const agent = opts?.agent ? opts.agent : new Agent(opts)
+ this[kAgent] = agent
- if (V instanceof Request) {
- return webidl.converters.Request(V, prefix, argument)
+ this[kClients] = agent[kClients]
+ this[kOptions] = buildMockOptions(opts)
}
- return webidl.converters.USVString(V, prefix, argument)
-}
+ get (origin) {
+ let dispatcher = this[kMockAgentGet](origin)
-webidl.converters.AbortSignal = webidl.interfaceConverter(
- AbortSignal
-)
-
-// https://fetch.spec.whatwg.org/#requestinit
-webidl.converters.RequestInit = webidl.dictionaryConverter([
- {
- key: 'method',
- converter: webidl.converters.ByteString
- },
- {
- key: 'headers',
- converter: webidl.converters.HeadersInit
- },
- {
- key: 'body',
- converter: webidl.nullableConverter(
- webidl.converters.BodyInit
- )
- },
- {
- key: 'referrer',
- converter: webidl.converters.USVString
- },
- {
- key: 'referrerPolicy',
- converter: webidl.converters.DOMString,
- // https://w3c.github.io/webappsec-referrer-policy/#referrer-policy
- allowedValues: referrerPolicy
- },
- {
- key: 'mode',
- converter: webidl.converters.DOMString,
- // https://fetch.spec.whatwg.org/#concept-request-mode
- allowedValues: requestMode
- },
- {
- key: 'credentials',
- converter: webidl.converters.DOMString,
- // https://fetch.spec.whatwg.org/#requestcredentials
- allowedValues: requestCredentials
- },
- {
- key: 'cache',
- converter: webidl.converters.DOMString,
- // https://fetch.spec.whatwg.org/#requestcache
- allowedValues: requestCache
- },
- {
- key: 'redirect',
- converter: webidl.converters.DOMString,
- // https://fetch.spec.whatwg.org/#requestredirect
- allowedValues: requestRedirect
- },
- {
- key: 'integrity',
- converter: webidl.converters.DOMString
- },
- {
- key: 'keepalive',
- converter: webidl.converters.boolean
- },
- {
- key: 'signal',
- converter: webidl.nullableConverter(
- (signal) => webidl.converters.AbortSignal(
- signal,
- 'RequestInit',
- 'signal',
- { strict: false }
- )
- )
- },
- {
- key: 'window',
- converter: webidl.converters.any
- },
- {
- key: 'duplex',
- converter: webidl.converters.DOMString,
- allowedValues: requestDuplex
- },
- {
- key: 'dispatcher', // undici specific option
- converter: webidl.converters.any
+ if (!dispatcher) {
+ dispatcher = this[kFactory](origin)
+ this[kMockAgentSet](origin, dispatcher)
+ }
+ return dispatcher
}
-])
-
-module.exports = { Request, makeRequest, fromInnerRequest, cloneRequest }
+ dispatch (opts, handler) {
+ // Call MockAgent.get to perform additional setup before dispatching as normal
+ this.get(opts.origin)
+ return this[kAgent].dispatch(opts, handler)
+ }
-/***/ }),
-
-/***/ 6678:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ async close () {
+ await this[kAgent].close()
+ this[kClients].clear()
+ }
+ deactivate () {
+ this[kIsMockActive] = false
+ }
+ activate () {
+ this[kIsMockActive] = true
+ }
-const { Headers, HeadersList, fill, getHeadersGuard, setHeadersGuard, setHeadersList } = __nccwpck_require__(1271)
-const { extractBody, cloneBody, mixinBody, hasFinalizationRegistry, streamRegistry, bodyUnusable } = __nccwpck_require__(3278)
-const util = __nccwpck_require__(7375)
-const nodeUtil = __nccwpck_require__(7975)
-const { kEnumerableProperty } = util
-const {
- isValidReasonPhrase,
- isCancelled,
- isAborted,
- isBlobLike,
- serializeJavascriptValueToJSONString,
- isErrorLike,
- isomorphicEncode,
- environmentSettingsObject: relevantRealm
-} = __nccwpck_require__(7241)
-const {
- redirectStatusSet,
- nullBodyStatus
-} = __nccwpck_require__(5336)
-const { kState, kHeaders } = __nccwpck_require__(1944)
-const { webidl } = __nccwpck_require__(220)
-const { FormData } = __nccwpck_require__(6443)
-const { URLSerializer } = __nccwpck_require__(2121)
-const { kConstruct } = __nccwpck_require__(6130)
-const assert = __nccwpck_require__(4589)
-const { types } = __nccwpck_require__(7975)
+ enableNetConnect (matcher) {
+ if (typeof matcher === 'string' || typeof matcher === 'function' || matcher instanceof RegExp) {
+ if (Array.isArray(this[kNetConnect])) {
+ this[kNetConnect].push(matcher)
+ } else {
+ this[kNetConnect] = [matcher]
+ }
+ } else if (typeof matcher === 'undefined') {
+ this[kNetConnect] = true
+ } else {
+ throw new InvalidArgumentError('Unsupported matcher. Must be one of String|Function|RegExp.')
+ }
+ }
-const textEncoder = new TextEncoder('utf-8')
+ disableNetConnect () {
+ this[kNetConnect] = false
+ }
-// https://fetch.spec.whatwg.org/#response-class
-class Response {
- // Creates network error Response.
- static error () {
- // The static error() method steps are to return the result of creating a
- // Response object, given a new network error, "immutable", and this’s
- // relevant Realm.
- const responseObject = fromInnerResponse(makeNetworkError(), 'immutable')
+ // This is required to bypass issues caused by using global symbols - see:
+ // https://github.com/nodejs/undici/issues/1447
+ get isMockActive () {
+ return this[kIsMockActive]
+ }
- return responseObject
+ [kMockAgentSet] (origin, dispatcher) {
+ this[kClients].set(origin, dispatcher)
}
- // https://fetch.spec.whatwg.org/#dom-response-json
- static json (data, init = {}) {
- webidl.argumentLengthCheck(arguments, 1, 'Response.json')
+ [kFactory] (origin) {
+ const mockOptions = Object.assign({ agent: this }, this[kOptions])
+ return this[kOptions] && this[kOptions].connections === 1
+ ? new MockClient(origin, mockOptions)
+ : new MockPool(origin, mockOptions)
+ }
- if (init !== null) {
- init = webidl.converters.ResponseInit(init)
+ [kMockAgentGet] (origin) {
+ // First check if we can immediately find it
+ const client = this[kClients].get(origin)
+ if (client) {
+ return client
}
- // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data.
- const bytes = textEncoder.encode(
- serializeJavascriptValueToJSONString(data)
- )
-
- // 2. Let body be the result of extracting bytes.
- const body = extractBody(bytes)
-
- // 3. Let responseObject be the result of creating a Response object, given a new response,
- // "response", and this’s relevant Realm.
- const responseObject = fromInnerResponse(makeResponse({}), 'response')
+ // If the origin is not a string create a dummy parent pool and return to user
+ if (typeof origin !== 'string') {
+ const dispatcher = this[kFactory]('http://localhost:9999')
+ this[kMockAgentSet](origin, dispatcher)
+ return dispatcher
+ }
- // 4. Perform initialize a response given responseObject, init, and (body, "application/json").
- initializeResponse(responseObject, init, { body: body[0], type: 'application/json' })
+ // If we match, create a pool and assign the same dispatches
+ for (const [keyMatcher, nonExplicitDispatcher] of Array.from(this[kClients])) {
+ if (nonExplicitDispatcher && typeof keyMatcher !== 'string' && matchValue(keyMatcher, origin)) {
+ const dispatcher = this[kFactory](origin)
+ this[kMockAgentSet](origin, dispatcher)
+ dispatcher[kDispatches] = nonExplicitDispatcher[kDispatches]
+ return dispatcher
+ }
+ }
+ }
- // 5. Return responseObject.
- return responseObject
+ [kGetNetConnect] () {
+ return this[kNetConnect]
}
- // Creates a redirect Response that redirects to url with status status.
- static redirect (url, status = 302) {
- webidl.argumentLengthCheck(arguments, 1, 'Response.redirect')
+ pendingInterceptors () {
+ const mockAgentClients = this[kClients]
- url = webidl.converters.USVString(url)
- status = webidl.converters['unsigned short'](status)
+ return Array.from(mockAgentClients.entries())
+ .flatMap(([origin, scope]) => scope[kDispatches].map(dispatch => ({ ...dispatch, origin })))
+ .filter(({ pending }) => pending)
+ }
- // 1. Let parsedURL be the result of parsing url with current settings
- // object’s API base URL.
- // 2. If parsedURL is failure, then throw a TypeError.
- // TODO: base-URL?
- let parsedURL
- try {
- parsedURL = new URL(url, relevantRealm.settingsObject.baseUrl)
- } catch (err) {
- throw new TypeError(`Failed to parse URL from ${url}`, { cause: err })
- }
+ assertNoPendingInterceptors ({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) {
+ const pending = this.pendingInterceptors()
- // 3. If status is not a redirect status, then throw a RangeError.
- if (!redirectStatusSet.has(status)) {
- throw new RangeError(`Invalid status code ${status}`)
+ if (pending.length === 0) {
+ return
}
- // 4. Let responseObject be the result of creating a Response object,
- // given a new response, "immutable", and this’s relevant Realm.
- const responseObject = fromInnerResponse(makeResponse({}), 'immutable')
+ const pluralizer = new Pluralizer('interceptor', 'interceptors').pluralize(pending.length)
- // 5. Set responseObject’s response’s status to status.
- responseObject[kState].status = status
+ throw new UndiciError(`
+${pluralizer.count} ${pluralizer.noun} ${pluralizer.is} pending:
- // 6. Let value be parsedURL, serialized and isomorphic encoded.
- const value = isomorphicEncode(URLSerializer(parsedURL))
+${pendingInterceptorsFormatter.format(pending)}
+`.trim())
+ }
+}
- // 7. Append `Location`/value to responseObject’s response’s header list.
- responseObject[kState].headersList.append('location', value, true)
+module.exports = MockAgent
- // 8. Return responseObject.
- return responseObject
- }
- // https://fetch.spec.whatwg.org/#dom-response
- constructor (body = null, init = {}) {
- webidl.util.markAsUncloneable(this)
- if (body === kConstruct) {
- return
- }
+/***/ }),
- if (body !== null) {
- body = webidl.converters.BodyInit(body)
- }
+/***/ 7365:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- init = webidl.converters.ResponseInit(init)
- // 1. Set this’s response to a new response.
- this[kState] = makeResponse({})
- // 2. Set this’s headers to a new Headers object with this’s relevant
- // Realm, whose header list is this’s response’s header list and guard
- // is "response".
- this[kHeaders] = new Headers(kConstruct)
- setHeadersGuard(this[kHeaders], 'response')
- setHeadersList(this[kHeaders], this[kState].headersList)
+const { promisify } = __nccwpck_require__(7975)
+const Client = __nccwpck_require__(3701)
+const { buildMockDispatch } = __nccwpck_require__(3397)
+const {
+ kDispatches,
+ kMockAgent,
+ kClose,
+ kOriginalClose,
+ kOrigin,
+ kOriginalDispatch,
+ kConnected
+} = __nccwpck_require__(1117)
+const { MockInterceptor } = __nccwpck_require__(1511)
+const Symbols = __nccwpck_require__(6443)
+const { InvalidArgumentError } = __nccwpck_require__(8707)
- // 3. Let bodyWithType be null.
- let bodyWithType = null
+/**
+ * MockClient provides an API that extends the Client to influence the mockDispatches.
+ */
+class MockClient extends Client {
+ constructor (origin, opts) {
+ super(origin, opts)
- // 4. If body is non-null, then set bodyWithType to the result of extracting body.
- if (body != null) {
- const [extractedBody, type] = extractBody(body)
- bodyWithType = { body: extractedBody, type }
+ if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') {
+ throw new InvalidArgumentError('Argument opts.agent must implement Agent')
}
- // 5. Perform initialize a response given this, init, and bodyWithType.
- initializeResponse(this, init, bodyWithType)
- }
+ this[kMockAgent] = opts.agent
+ this[kOrigin] = origin
+ this[kDispatches] = []
+ this[kConnected] = 1
+ this[kOriginalDispatch] = this.dispatch
+ this[kOriginalClose] = this.close.bind(this)
- // Returns response’s type, e.g., "cors".
- get type () {
- webidl.brandCheck(this, Response)
+ this.dispatch = buildMockDispatch.call(this)
+ this.close = this[kClose]
+ }
- // The type getter steps are to return this’s response’s type.
- return this[kState].type
+ get [Symbols.kConnected] () {
+ return this[kConnected]
}
- // Returns response’s URL, if it has one; otherwise the empty string.
- get url () {
- webidl.brandCheck(this, Response)
+ /**
+ * Sets up the base interceptor for mocking replies from undici.
+ */
+ intercept (opts) {
+ return new MockInterceptor(opts, this[kDispatches])
+ }
- const urlList = this[kState].urlList
+ async [kClose] () {
+ await promisify(this[kOriginalClose])()
+ this[kConnected] = 0
+ this[kMockAgent][Symbols.kClients].delete(this[kOrigin])
+ }
+}
- // The url getter steps are to return the empty string if this’s
- // response’s URL is null; otherwise this’s response’s URL,
- // serialized with exclude fragment set to true.
- const url = urlList[urlList.length - 1] ?? null
+module.exports = MockClient
- if (url === null) {
- return ''
- }
- return URLSerializer(url, true)
- }
+/***/ }),
- // Returns whether response was obtained through a redirect.
- get redirected () {
- webidl.brandCheck(this, Response)
+/***/ 2429:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // The redirected getter steps are to return true if this’s response’s URL
- // list has more than one item; otherwise false.
- return this[kState].urlList.length > 1
- }
- // Returns response’s status.
- get status () {
- webidl.brandCheck(this, Response)
- // The status getter steps are to return this’s response’s status.
- return this[kState].status
- }
+const { UndiciError } = __nccwpck_require__(8707)
- // Returns whether response’s status is an ok status.
- get ok () {
- webidl.brandCheck(this, Response)
+const kMockNotMatchedError = Symbol.for('undici.error.UND_MOCK_ERR_MOCK_NOT_MATCHED')
- // The ok getter steps are to return true if this’s response’s status is an
- // ok status; otherwise false.
- return this[kState].status >= 200 && this[kState].status <= 299
+/**
+ * The request does not match any registered mock dispatches.
+ */
+class MockNotMatchedError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, MockNotMatchedError)
+ this.name = 'MockNotMatchedError'
+ this.message = message || 'The request does not match any registered mock dispatches'
+ this.code = 'UND_MOCK_ERR_MOCK_NOT_MATCHED'
}
- // Returns response’s status message.
- get statusText () {
- webidl.brandCheck(this, Response)
-
- // The statusText getter steps are to return this’s response’s status
- // message.
- return this[kState].statusText
+ static [Symbol.hasInstance] (instance) {
+ return instance && instance[kMockNotMatchedError] === true
}
- // Returns response’s headers as Headers.
- get headers () {
- webidl.brandCheck(this, Response)
+ [kMockNotMatchedError] = true
+}
- // The headers getter steps are to return this’s headers.
- return this[kHeaders]
- }
+module.exports = {
+ MockNotMatchedError
+}
- get body () {
- webidl.brandCheck(this, Response)
- return this[kState].body ? this[kState].body.stream : null
- }
+/***/ }),
- get bodyUsed () {
- webidl.brandCheck(this, Response)
+/***/ 1511:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- return !!this[kState].body && util.isDisturbed(this[kState].body.stream)
- }
- // Returns a clone of response.
- clone () {
- webidl.brandCheck(this, Response)
- // 1. If this is unusable, then throw a TypeError.
- if (bodyUnusable(this)) {
- throw webidl.errors.exception({
- header: 'Response.clone',
- message: 'Body has already been consumed.'
- })
- }
+const { getResponseData, buildKey, addMockDispatch } = __nccwpck_require__(3397)
+const {
+ kDispatches,
+ kDispatchKey,
+ kDefaultHeaders,
+ kDefaultTrailers,
+ kContentLength,
+ kMockDispatch
+} = __nccwpck_require__(1117)
+const { InvalidArgumentError } = __nccwpck_require__(8707)
+const { buildURL } = __nccwpck_require__(3440)
- // 2. Let clonedResponse be the result of cloning this’s response.
- const clonedResponse = cloneResponse(this[kState])
+/**
+ * Defines the scope API for an interceptor reply
+ */
+class MockScope {
+ constructor (mockDispatch) {
+ this[kMockDispatch] = mockDispatch
+ }
- // Note: To re-register because of a new stream.
- if (hasFinalizationRegistry && this[kState].body?.stream) {
- streamRegistry.register(this, new WeakRef(this[kState].body.stream))
+ /**
+ * Delay a reply by a set amount in ms.
+ */
+ delay (waitInMs) {
+ if (typeof waitInMs !== 'number' || !Number.isInteger(waitInMs) || waitInMs <= 0) {
+ throw new InvalidArgumentError('waitInMs must be a valid integer > 0')
}
- // 3. Return the result of creating a Response object, given
- // clonedResponse, this’s headers’s guard, and this’s relevant Realm.
- return fromInnerResponse(clonedResponse, getHeadersGuard(this[kHeaders]))
+ this[kMockDispatch].delay = waitInMs
+ return this
}
- [nodeUtil.inspect.custom] (depth, options) {
- if (options.depth === null) {
- options.depth = 2
- }
-
- options.colors ??= true
+ /**
+ * For a defined reply, never mark as consumed.
+ */
+ persist () {
+ this[kMockDispatch].persist = true
+ return this
+ }
- const properties = {
- status: this.status,
- statusText: this.statusText,
- headers: this.headers,
- body: this.body,
- bodyUsed: this.bodyUsed,
- ok: this.ok,
- redirected: this.redirected,
- type: this.type,
- url: this.url
+ /**
+ * Allow one to define a reply for a set amount of matching requests.
+ */
+ times (repeatTimes) {
+ if (typeof repeatTimes !== 'number' || !Number.isInteger(repeatTimes) || repeatTimes <= 0) {
+ throw new InvalidArgumentError('repeatTimes must be a valid integer > 0')
}
- return `Response ${nodeUtil.formatWithOptions(options, properties)}`
+ this[kMockDispatch].times = repeatTimes
+ return this
}
}
-mixinBody(Response)
+/**
+ * Defines an interceptor for a Mock
+ */
+class MockInterceptor {
+ constructor (opts, mockDispatches) {
+ if (typeof opts !== 'object') {
+ throw new InvalidArgumentError('opts must be an object')
+ }
+ if (typeof opts.path === 'undefined') {
+ throw new InvalidArgumentError('opts.path must be defined')
+ }
+ if (typeof opts.method === 'undefined') {
+ opts.method = 'GET'
+ }
+ // See https://github.com/nodejs/undici/issues/1245
+ // As per RFC 3986, clients are not supposed to send URI
+ // fragments to servers when they retrieve a document,
+ if (typeof opts.path === 'string') {
+ if (opts.query) {
+ opts.path = buildURL(opts.path, opts.query)
+ } else {
+ // Matches https://github.com/nodejs/undici/blob/main/lib/web/fetch/index.js#L1811
+ const parsedURL = new URL(opts.path, 'data://')
+ opts.path = parsedURL.pathname + parsedURL.search
+ }
+ }
+ if (typeof opts.method === 'string') {
+ opts.method = opts.method.toUpperCase()
+ }
-Object.defineProperties(Response.prototype, {
- type: kEnumerableProperty,
- url: kEnumerableProperty,
- status: kEnumerableProperty,
- ok: kEnumerableProperty,
- redirected: kEnumerableProperty,
- statusText: kEnumerableProperty,
- headers: kEnumerableProperty,
- clone: kEnumerableProperty,
- body: kEnumerableProperty,
- bodyUsed: kEnumerableProperty,
- [Symbol.toStringTag]: {
- value: 'Response',
- configurable: true
- }
-})
-
-Object.defineProperties(Response, {
- json: kEnumerableProperty,
- redirect: kEnumerableProperty,
- error: kEnumerableProperty
-})
-
-// https://fetch.spec.whatwg.org/#concept-response-clone
-function cloneResponse (response) {
- // To clone a response response, run these steps:
-
- // 1. If response is a filtered response, then return a new identical
- // filtered response whose internal response is a clone of response’s
- // internal response.
- if (response.internalResponse) {
- return filterResponse(
- cloneResponse(response.internalResponse),
- response.type
- )
+ this[kDispatchKey] = buildKey(opts)
+ this[kDispatches] = mockDispatches
+ this[kDefaultHeaders] = {}
+ this[kDefaultTrailers] = {}
+ this[kContentLength] = false
}
- // 2. Let newResponse be a copy of response, except for its body.
- const newResponse = makeResponse({ ...response, body: null })
+ createMockScopeDispatchData ({ statusCode, data, responseOptions }) {
+ const responseData = getResponseData(data)
+ const contentLength = this[kContentLength] ? { 'content-length': responseData.length } : {}
+ const headers = { ...this[kDefaultHeaders], ...contentLength, ...responseOptions.headers }
+ const trailers = { ...this[kDefaultTrailers], ...responseOptions.trailers }
- // 3. If response’s body is non-null, then set newResponse’s body to the
- // result of cloning response’s body.
- if (response.body != null) {
- newResponse.body = cloneBody(newResponse, response.body)
+ return { statusCode, data, headers, trailers }
}
- // 4. Return newResponse.
- return newResponse
-}
-
-function makeResponse (init) {
- return {
- aborted: false,
- rangeRequested: false,
- timingAllowPassed: false,
- requestIncludesCredentials: false,
- type: 'default',
- status: 200,
- timingInfo: null,
- cacheState: '',
- statusText: '',
- ...init,
- headersList: init?.headersList
- ? new HeadersList(init?.headersList)
- : new HeadersList(),
- urlList: init?.urlList ? [...init.urlList] : []
+ validateReplyParameters (replyParameters) {
+ if (typeof replyParameters.statusCode === 'undefined') {
+ throw new InvalidArgumentError('statusCode must be defined')
+ }
+ if (typeof replyParameters.responseOptions !== 'object' || replyParameters.responseOptions === null) {
+ throw new InvalidArgumentError('responseOptions must be an object')
+ }
}
-}
-function makeNetworkError (reason) {
- const isError = isErrorLike(reason)
- return makeResponse({
- type: 'error',
- status: 0,
- error: isError
- ? reason
- : new Error(reason ? String(reason) : reason),
- aborted: reason && reason.name === 'AbortError'
- })
-}
+ /**
+ * Mock an undici request with a defined reply.
+ */
+ reply (replyOptionsCallbackOrStatusCode) {
+ // Values of reply aren't available right now as they
+ // can only be available when the reply callback is invoked.
+ if (typeof replyOptionsCallbackOrStatusCode === 'function') {
+ // We'll first wrap the provided callback in another function,
+ // this function will properly resolve the data from the callback
+ // when invoked.
+ const wrappedDefaultsCallback = (opts) => {
+ // Our reply options callback contains the parameter for statusCode, data and options.
+ const resolvedData = replyOptionsCallbackOrStatusCode(opts)
-// @see https://fetch.spec.whatwg.org/#concept-network-error
-function isNetworkError (response) {
- return (
- // A network error is a response whose type is "error",
- response.type === 'error' &&
- // status is 0
- response.status === 0
- )
-}
+ // Check if it is in the right format
+ if (typeof resolvedData !== 'object' || resolvedData === null) {
+ throw new InvalidArgumentError('reply options callback must return an object')
+ }
-function makeFilteredResponse (response, state) {
- state = {
- internalResponse: response,
- ...state
- }
+ const replyParameters = { data: '', responseOptions: {}, ...resolvedData }
+ this.validateReplyParameters(replyParameters)
+ // Since the values can be obtained immediately we return them
+ // from this higher order function that will be resolved later.
+ return {
+ ...this.createMockScopeDispatchData(replyParameters)
+ }
+ }
- return new Proxy(response, {
- get (target, p) {
- return p in state ? state[p] : target[p]
- },
- set (target, p, value) {
- assert(!(p in state))
- target[p] = value
- return true
+ // Add usual dispatch data, but this time set the data parameter to function that will eventually provide data.
+ const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], wrappedDefaultsCallback)
+ return new MockScope(newMockDispatch)
}
- })
-}
-
-// https://fetch.spec.whatwg.org/#concept-filtered-response
-function filterResponse (response, type) {
- // Set response to the following filtered response with response as its
- // internal response, depending on request’s response tainting:
- if (type === 'basic') {
- // A basic filtered response is a filtered response whose type is "basic"
- // and header list excludes any headers in internal response’s header list
- // whose name is a forbidden response-header name.
-
- // Note: undici does not implement forbidden response-header names
- return makeFilteredResponse(response, {
- type: 'basic',
- headersList: response.headersList
- })
- } else if (type === 'cors') {
- // A CORS filtered response is a filtered response whose type is "cors"
- // and header list excludes any headers in internal response’s header
- // list whose name is not a CORS-safelisted response-header name, given
- // internal response’s CORS-exposed header-name list.
-
- // Note: undici does not implement CORS-safelisted response-header names
- return makeFilteredResponse(response, {
- type: 'cors',
- headersList: response.headersList
- })
- } else if (type === 'opaque') {
- // An opaque filtered response is a filtered response whose type is
- // "opaque", URL list is the empty list, status is 0, status message
- // is the empty byte sequence, header list is empty, and body is null.
-
- return makeFilteredResponse(response, {
- type: 'opaque',
- urlList: Object.freeze([]),
- status: 0,
- statusText: '',
- body: null
- })
- } else if (type === 'opaqueredirect') {
- // An opaque-redirect filtered response is a filtered response whose type
- // is "opaqueredirect", status is 0, status message is the empty byte
- // sequence, header list is empty, and body is null.
-
- return makeFilteredResponse(response, {
- type: 'opaqueredirect',
- status: 0,
- statusText: '',
- headersList: [],
- body: null
- })
- } else {
- assert(false)
- }
-}
-
-// https://fetch.spec.whatwg.org/#appropriate-network-error
-function makeAppropriateNetworkError (fetchParams, err = null) {
- // 1. Assert: fetchParams is canceled.
- assert(isCancelled(fetchParams))
- // 2. Return an aborted network error if fetchParams is aborted;
- // otherwise return a network error.
- return isAborted(fetchParams)
- ? makeNetworkError(Object.assign(new DOMException('The operation was aborted.', 'AbortError'), { cause: err }))
- : makeNetworkError(Object.assign(new DOMException('Request was cancelled.'), { cause: err }))
-}
+ // We can have either one or three parameters, if we get here,
+ // we should have 1-3 parameters. So we spread the arguments of
+ // this function to obtain the parameters, since replyData will always
+ // just be the statusCode.
+ const replyParameters = {
+ statusCode: replyOptionsCallbackOrStatusCode,
+ data: arguments[1] === undefined ? '' : arguments[1],
+ responseOptions: arguments[2] === undefined ? {} : arguments[2]
+ }
+ this.validateReplyParameters(replyParameters)
-// https://whatpr.org/fetch/1392.html#initialize-a-response
-function initializeResponse (response, init, body) {
- // 1. If init["status"] is not in the range 200 to 599, inclusive, then
- // throw a RangeError.
- if (init.status !== null && (init.status < 200 || init.status > 599)) {
- throw new RangeError('init["status"] must be in the range of 200 to 599, inclusive.')
+ // Send in-already provided data like usual
+ const dispatchData = this.createMockScopeDispatchData(replyParameters)
+ const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], dispatchData)
+ return new MockScope(newMockDispatch)
}
- // 2. If init["statusText"] does not match the reason-phrase token production,
- // then throw a TypeError.
- if ('statusText' in init && init.statusText != null) {
- // See, https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2:
- // reason-phrase = *( HTAB / SP / VCHAR / obs-text )
- if (!isValidReasonPhrase(String(init.statusText))) {
- throw new TypeError('Invalid statusText')
+ /**
+ * Mock an undici request with a defined error.
+ */
+ replyWithError (error) {
+ if (typeof error === 'undefined') {
+ throw new InvalidArgumentError('error must be defined')
}
- }
- // 3. Set response’s response’s status to init["status"].
- if ('status' in init && init.status != null) {
- response[kState].status = init.status
+ const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error })
+ return new MockScope(newMockDispatch)
}
- // 4. Set response’s response’s status message to init["statusText"].
- if ('statusText' in init && init.statusText != null) {
- response[kState].statusText = init.statusText
- }
+ /**
+ * Set default reply headers on the interceptor for subsequent replies
+ */
+ defaultReplyHeaders (headers) {
+ if (typeof headers === 'undefined') {
+ throw new InvalidArgumentError('headers must be defined')
+ }
- // 5. If init["headers"] exists, then fill response’s headers with init["headers"].
- if ('headers' in init && init.headers != null) {
- fill(response[kHeaders], init.headers)
+ this[kDefaultHeaders] = headers
+ return this
}
- // 6. If body was given, then:
- if (body) {
- // 1. If response's status is a null body status, then throw a TypeError.
- if (nullBodyStatus.includes(response.status)) {
- throw webidl.errors.exception({
- header: 'Response constructor',
- message: `Invalid response status code ${response.status}`
- })
+ /**
+ * Set default reply trailers on the interceptor for subsequent replies
+ */
+ defaultReplyTrailers (trailers) {
+ if (typeof trailers === 'undefined') {
+ throw new InvalidArgumentError('trailers must be defined')
}
- // 2. Set response's body to body's body.
- response[kState].body = body.body
+ this[kDefaultTrailers] = trailers
+ return this
+ }
- // 3. If body's type is non-null and response's header list does not contain
- // `Content-Type`, then append (`Content-Type`, body's type) to response's header list.
- if (body.type != null && !response[kState].headersList.contains('content-type', true)) {
- response[kState].headersList.append('content-type', body.type, true)
- }
+ /**
+ * Set reply content length header for replies on the interceptor
+ */
+ replyContentLength () {
+ this[kContentLength] = true
+ return this
}
}
-/**
- * @see https://fetch.spec.whatwg.org/#response-create
- * @param {any} innerResponse
- * @param {'request' | 'immutable' | 'request-no-cors' | 'response' | 'none'} guard
- * @returns {Response}
- */
-function fromInnerResponse (innerResponse, guard) {
- const response = new Response(kConstruct)
- response[kState] = innerResponse
- response[kHeaders] = new Headers(kConstruct)
- setHeadersList(response[kHeaders], innerResponse.headersList)
- setHeadersGuard(response[kHeaders], guard)
+module.exports.MockInterceptor = MockInterceptor
+module.exports.MockScope = MockScope
- if (hasFinalizationRegistry && innerResponse.body?.stream) {
- // If the target (response) is reclaimed, the cleanup callback may be called at some point with
- // the held value provided for it (innerResponse.body.stream). The held value can be any value:
- // a primitive or an object, even undefined. If the held value is an object, the registry keeps
- // a strong reference to it (so it can pass it to the cleanup callback later). Reworded from
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry
- streamRegistry.register(response, new WeakRef(innerResponse.body.stream))
- }
- return response
-}
+/***/ }),
-webidl.converters.ReadableStream = webidl.interfaceConverter(
- ReadableStream
-)
+/***/ 4004:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-webidl.converters.FormData = webidl.interfaceConverter(
- FormData
-)
-webidl.converters.URLSearchParams = webidl.interfaceConverter(
- URLSearchParams
-)
-// https://fetch.spec.whatwg.org/#typedefdef-xmlhttprequestbodyinit
-webidl.converters.XMLHttpRequestBodyInit = function (V, prefix, name) {
- if (typeof V === 'string') {
- return webidl.converters.USVString(V, prefix, name)
- }
+const { promisify } = __nccwpck_require__(7975)
+const Pool = __nccwpck_require__(628)
+const { buildMockDispatch } = __nccwpck_require__(3397)
+const {
+ kDispatches,
+ kMockAgent,
+ kClose,
+ kOriginalClose,
+ kOrigin,
+ kOriginalDispatch,
+ kConnected
+} = __nccwpck_require__(1117)
+const { MockInterceptor } = __nccwpck_require__(1511)
+const Symbols = __nccwpck_require__(6443)
+const { InvalidArgumentError } = __nccwpck_require__(8707)
- if (isBlobLike(V)) {
- return webidl.converters.Blob(V, prefix, name, { strict: false })
- }
+/**
+ * MockPool provides an API that extends the Pool to influence the mockDispatches.
+ */
+class MockPool extends Pool {
+ constructor (origin, opts) {
+ super(origin, opts)
- if (ArrayBuffer.isView(V) || types.isArrayBuffer(V)) {
- return webidl.converters.BufferSource(V, prefix, name)
- }
+ if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') {
+ throw new InvalidArgumentError('Argument opts.agent must implement Agent')
+ }
- if (util.isFormDataLike(V)) {
- return webidl.converters.FormData(V, prefix, name, { strict: false })
- }
+ this[kMockAgent] = opts.agent
+ this[kOrigin] = origin
+ this[kDispatches] = []
+ this[kConnected] = 1
+ this[kOriginalDispatch] = this.dispatch
+ this[kOriginalClose] = this.close.bind(this)
- if (V instanceof URLSearchParams) {
- return webidl.converters.URLSearchParams(V, prefix, name)
+ this.dispatch = buildMockDispatch.call(this)
+ this.close = this[kClose]
}
- return webidl.converters.DOMString(V, prefix, name)
-}
-
-// https://fetch.spec.whatwg.org/#bodyinit
-webidl.converters.BodyInit = function (V, prefix, argument) {
- if (V instanceof ReadableStream) {
- return webidl.converters.ReadableStream(V, prefix, argument)
+ get [Symbols.kConnected] () {
+ return this[kConnected]
}
- // Note: the spec doesn't include async iterables,
- // this is an undici extension.
- if (V?.[Symbol.asyncIterator]) {
- return V
+ /**
+ * Sets up the base interceptor for mocking replies from undici.
+ */
+ intercept (opts) {
+ return new MockInterceptor(opts, this[kDispatches])
}
- return webidl.converters.XMLHttpRequestBodyInit(V, prefix, argument)
-}
-
-webidl.converters.ResponseInit = webidl.dictionaryConverter([
- {
- key: 'status',
- converter: webidl.converters['unsigned short'],
- defaultValue: () => 200
- },
- {
- key: 'statusText',
- converter: webidl.converters.ByteString,
- defaultValue: () => ''
- },
- {
- key: 'headers',
- converter: webidl.converters.HeadersInit
+ async [kClose] () {
+ await promisify(this[kOriginalClose])()
+ this[kConnected] = 0
+ this[kMockAgent][Symbols.kClients].delete(this[kOrigin])
}
-])
-
-module.exports = {
- isNetworkError,
- makeNetworkError,
- makeResponse,
- makeAppropriateNetworkError,
- filterResponse,
- Response,
- cloneResponse,
- fromInnerResponse
}
+module.exports = MockPool
+
/***/ }),
-/***/ 1944:
+/***/ 1117:
/***/ ((module) => {
module.exports = {
- kUrl: Symbol('url'),
- kHeaders: Symbol('headers'),
- kSignal: Symbol('signal'),
- kState: Symbol('state'),
- kDispatcher: Symbol('dispatcher')
+ kAgent: Symbol('agent'),
+ kOptions: Symbol('options'),
+ kFactory: Symbol('factory'),
+ kDispatches: Symbol('dispatches'),
+ kDispatchKey: Symbol('dispatch key'),
+ kDefaultHeaders: Symbol('default headers'),
+ kDefaultTrailers: Symbol('default trailers'),
+ kContentLength: Symbol('content length'),
+ kMockAgent: Symbol('mock agent'),
+ kMockAgentSet: Symbol('mock agent set'),
+ kMockAgentGet: Symbol('mock agent get'),
+ kMockDispatch: Symbol('mock dispatch'),
+ kClose: Symbol('close'),
+ kOriginalClose: Symbol('original agent close'),
+ kOrigin: Symbol('origin'),
+ kIsMockActive: Symbol('is mock active'),
+ kNetConnect: Symbol('net connect'),
+ kGetNetConnect: Symbol('get net connect'),
+ kConnected: Symbol('connected')
}
/***/ }),
-/***/ 7241:
+/***/ 3397:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const { Transform } = __nccwpck_require__(7075)
-const zlib = __nccwpck_require__(8522)
-const { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = __nccwpck_require__(5336)
-const { getGlobalOrigin } = __nccwpck_require__(7038)
-const { collectASequenceOfCodePoints, collectAnHTTPQuotedString, removeChars, parseMIMEType } = __nccwpck_require__(2121)
-const { performance } = __nccwpck_require__(643)
-const { isBlobLike, ReadableStreamFrom, isValidHTTPToken, normalizedMethodRecordsBase } = __nccwpck_require__(7375)
-const assert = __nccwpck_require__(4589)
-const { isUint8Array } = __nccwpck_require__(3429)
-const { webidl } = __nccwpck_require__(220)
-
-let supportedHashes = []
-
-// https://nodejs.org/api/crypto.html#determining-if-crypto-support-is-unavailable
-/** @type {import('crypto')} */
-let crypto
-try {
- crypto = __nccwpck_require__(7598)
- const possibleRelevantHashes = ['sha256', 'sha384', 'sha512']
- supportedHashes = crypto.getHashes().filter((hash) => possibleRelevantHashes.includes(hash))
-/* c8 ignore next 3 */
-} catch {
+const { MockNotMatchedError } = __nccwpck_require__(2429)
+const {
+ kDispatches,
+ kMockAgent,
+ kOriginalDispatch,
+ kOrigin,
+ kGetNetConnect
+} = __nccwpck_require__(1117)
+const { buildURL } = __nccwpck_require__(3440)
+const { STATUS_CODES } = __nccwpck_require__(7067)
+const {
+ types: {
+ isPromise
+ }
+} = __nccwpck_require__(7975)
+function matchValue (match, value) {
+ if (typeof match === 'string') {
+ return match === value
+ }
+ if (match instanceof RegExp) {
+ return match.test(value)
+ }
+ if (typeof match === 'function') {
+ return match(value) === true
+ }
+ return false
}
-function responseURL (response) {
- // https://fetch.spec.whatwg.org/#responses
- // A response has an associated URL. It is a pointer to the last URL
- // in response’s URL list and null if response’s URL list is empty.
- const urlList = response.urlList
- const length = urlList.length
- return length === 0 ? null : urlList[length - 1].toString()
+function lowerCaseEntries (headers) {
+ return Object.fromEntries(
+ Object.entries(headers).map(([headerName, headerValue]) => {
+ return [headerName.toLocaleLowerCase(), headerValue]
+ })
+ )
}
-// https://fetch.spec.whatwg.org/#concept-response-location-url
-function responseLocationURL (response, requestFragment) {
- // 1. If response’s status is not a redirect status, then return null.
- if (!redirectStatusSet.has(response.status)) {
- return null
- }
+/**
+ * @param {import('../../index').Headers|string[]|Record} headers
+ * @param {string} key
+ */
+function getHeaderByName (headers, key) {
+ if (Array.isArray(headers)) {
+ for (let i = 0; i < headers.length; i += 2) {
+ if (headers[i].toLocaleLowerCase() === key.toLocaleLowerCase()) {
+ return headers[i + 1]
+ }
+ }
- // 2. Let location be the result of extracting header list values given
- // `Location` and response’s header list.
- let location = response.headersList.get('location', true)
-
- // 3. If location is a header value, then set location to the result of
- // parsing location with response’s URL.
- if (location !== null && isValidHeaderValue(location)) {
- if (!isValidEncodedURL(location)) {
- // Some websites respond location header in UTF-8 form without encoding them as ASCII
- // and major browsers redirect them to correctly UTF-8 encoded addresses.
- // Here, we handle that behavior in the same way.
- location = normalizeBinaryStringToUtf8(location)
- }
- location = new URL(location, responseURL(response))
+ return undefined
+ } else if (typeof headers.get === 'function') {
+ return headers.get(key)
+ } else {
+ return lowerCaseEntries(headers)[key.toLocaleLowerCase()]
}
+}
- // 4. If location is a URL whose fragment is null, then set location’s
- // fragment to requestFragment.
- if (location && !location.hash) {
- location.hash = requestFragment
+/** @param {string[]} headers */
+function buildHeadersFromArray (headers) { // fetch HeadersList
+ const clone = headers.slice()
+ const entries = []
+ for (let index = 0; index < clone.length; index += 2) {
+ entries.push([clone[index], clone[index + 1]])
}
-
- // 5. Return location.
- return location
+ return Object.fromEntries(entries)
}
-/**
- * @see https://www.rfc-editor.org/rfc/rfc1738#section-2.2
- * @param {string} url
- * @returns {boolean}
- */
-function isValidEncodedURL (url) {
- for (let i = 0; i < url.length; ++i) {
- const code = url.charCodeAt(i)
+function matchHeaders (mockDispatch, headers) {
+ if (typeof mockDispatch.headers === 'function') {
+ if (Array.isArray(headers)) { // fetch HeadersList
+ headers = buildHeadersFromArray(headers)
+ }
+ return mockDispatch.headers(headers ? lowerCaseEntries(headers) : {})
+ }
+ if (typeof mockDispatch.headers === 'undefined') {
+ return true
+ }
+ if (typeof headers !== 'object' || typeof mockDispatch.headers !== 'object') {
+ return false
+ }
- if (
- code > 0x7E || // Non-US-ASCII + DEL
- code < 0x20 // Control characters NUL - US
- ) {
+ for (const [matchHeaderName, matchHeaderValue] of Object.entries(mockDispatch.headers)) {
+ const headerValue = getHeaderByName(headers, matchHeaderName)
+
+ if (!matchValue(matchHeaderValue, headerValue)) {
return false
}
}
return true
}
-/**
- * If string contains non-ASCII characters, assumes it's UTF-8 encoded and decodes it.
- * Since UTF-8 is a superset of ASCII, this will work for ASCII strings as well.
- * @param {string} value
- * @returns {string}
- */
-function normalizeBinaryStringToUtf8 (value) {
- return Buffer.from(value, 'binary').toString('utf8')
-}
-
-/** @returns {URL} */
-function requestCurrentURL (request) {
- return request.urlList[request.urlList.length - 1]
-}
+function safeUrl (path) {
+ if (typeof path !== 'string') {
+ return path
+ }
-function requestBadPort (request) {
- // 1. Let url be request’s current URL.
- const url = requestCurrentURL(request)
+ const pathSegments = path.split('?')
- // 2. If url’s scheme is an HTTP(S) scheme and url’s port is a bad port,
- // then return blocked.
- if (urlIsHttpHttpsScheme(url) && badPortsSet.has(url.port)) {
- return 'blocked'
+ if (pathSegments.length !== 2) {
+ return path
}
- // 3. Return allowed.
- return 'allowed'
+ const qp = new URLSearchParams(pathSegments.pop())
+ qp.sort()
+ return [...pathSegments, qp.toString()].join('?')
}
-function isErrorLike (object) {
- return object instanceof Error || (
- object?.constructor?.name === 'Error' ||
- object?.constructor?.name === 'DOMException'
- )
+function matchKey (mockDispatch, { path, method, body, headers }) {
+ const pathMatch = matchValue(mockDispatch.path, path)
+ const methodMatch = matchValue(mockDispatch.method, method)
+ const bodyMatch = typeof mockDispatch.body !== 'undefined' ? matchValue(mockDispatch.body, body) : true
+ const headersMatch = matchHeaders(mockDispatch, headers)
+ return pathMatch && methodMatch && bodyMatch && headersMatch
}
-// Check whether |statusText| is a ByteString and
-// matches the Reason-Phrase token production.
-// RFC 2616: https://tools.ietf.org/html/rfc2616
-// RFC 7230: https://tools.ietf.org/html/rfc7230
-// "reason-phrase = *( HTAB / SP / VCHAR / obs-text )"
-// https://github.com/chromium/chromium/blob/94.0.4604.1/third_party/blink/renderer/core/fetch/response.cc#L116
-function isValidReasonPhrase (statusText) {
- for (let i = 0; i < statusText.length; ++i) {
- const c = statusText.charCodeAt(i)
- if (
- !(
- (
- c === 0x09 || // HTAB
- (c >= 0x20 && c <= 0x7e) || // SP / VCHAR
- (c >= 0x80 && c <= 0xff)
- ) // obs-text
- )
- ) {
- return false
- }
+function getResponseData (data) {
+ if (Buffer.isBuffer(data)) {
+ return data
+ } else if (data instanceof Uint8Array) {
+ return data
+ } else if (data instanceof ArrayBuffer) {
+ return data
+ } else if (typeof data === 'object') {
+ return JSON.stringify(data)
+ } else {
+ return data.toString()
}
- return true
}
-/**
- * @see https://fetch.spec.whatwg.org/#header-name
- * @param {string} potentialValue
- */
-const isValidHeaderName = isValidHTTPToken
+function getMockDispatch (mockDispatches, key) {
+ const basePath = key.query ? buildURL(key.path, key.query) : key.path
+ const resolvedPath = typeof basePath === 'string' ? safeUrl(basePath) : basePath
-/**
- * @see https://fetch.spec.whatwg.org/#header-value
- * @param {string} potentialValue
- */
-function isValidHeaderValue (potentialValue) {
- // - Has no leading or trailing HTTP tab or space bytes.
- // - Contains no 0x00 (NUL) or HTTP newline bytes.
- return (
- potentialValue[0] === '\t' ||
- potentialValue[0] === ' ' ||
- potentialValue[potentialValue.length - 1] === '\t' ||
- potentialValue[potentialValue.length - 1] === ' ' ||
- potentialValue.includes('\n') ||
- potentialValue.includes('\r') ||
- potentialValue.includes('\0')
- ) === false
-}
+ // Match path
+ let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path }) => matchValue(safeUrl(path), resolvedPath))
+ if (matchedMockDispatches.length === 0) {
+ throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`)
+ }
-// https://w3c.github.io/webappsec-referrer-policy/#set-requests-referrer-policy-on-redirect
-function setRequestReferrerPolicyOnRedirect (request, actualResponse) {
- // Given a request request and a response actualResponse, this algorithm
- // updates request’s referrer policy according to the Referrer-Policy
- // header (if any) in actualResponse.
+ // Match method
+ matchedMockDispatches = matchedMockDispatches.filter(({ method }) => matchValue(method, key.method))
+ if (matchedMockDispatches.length === 0) {
+ throw new MockNotMatchedError(`Mock dispatch not matched for method '${key.method}' on path '${resolvedPath}'`)
+ }
- // 1. Let policy be the result of executing § 8.1 Parse a referrer policy
- // from a Referrer-Policy header on actualResponse.
+ // Match body
+ matchedMockDispatches = matchedMockDispatches.filter(({ body }) => typeof body !== 'undefined' ? matchValue(body, key.body) : true)
+ if (matchedMockDispatches.length === 0) {
+ throw new MockNotMatchedError(`Mock dispatch not matched for body '${key.body}' on path '${resolvedPath}'`)
+ }
- // 8.1 Parse a referrer policy from a Referrer-Policy header
- // 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy` and response’s header list.
- const { headersList } = actualResponse
- // 2. Let policy be the empty string.
- // 3. For each token in policy-tokens, if token is a referrer policy and token is not the empty string, then set policy to token.
- // 4. Return policy.
- const policyHeader = (headersList.get('referrer-policy', true) ?? '').split(',')
+ // Match headers
+ matchedMockDispatches = matchedMockDispatches.filter((mockDispatch) => matchHeaders(mockDispatch, key.headers))
+ if (matchedMockDispatches.length === 0) {
+ const headers = typeof key.headers === 'object' ? JSON.stringify(key.headers) : key.headers
+ throw new MockNotMatchedError(`Mock dispatch not matched for headers '${headers}' on path '${resolvedPath}'`)
+ }
- // Note: As the referrer-policy can contain multiple policies
- // separated by comma, we need to loop through all of them
- // and pick the first valid one.
- // Ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy#specify_a_fallback_policy
- let policy = ''
- if (policyHeader.length > 0) {
- // The right-most policy takes precedence.
- // The left-most policy is the fallback.
- for (let i = policyHeader.length; i !== 0; i--) {
- const token = policyHeader[i - 1].trim()
- if (referrerPolicyTokens.has(token)) {
- policy = token
- break
- }
+ return matchedMockDispatches[0]
+}
+
+function addMockDispatch (mockDispatches, key, data) {
+ const baseData = { timesInvoked: 0, times: 1, persist: false, consumed: false }
+ const replyData = typeof data === 'function' ? { callback: data } : { ...data }
+ const newMockDispatch = { ...baseData, ...key, pending: true, data: { error: null, ...replyData } }
+ mockDispatches.push(newMockDispatch)
+ return newMockDispatch
+}
+
+function deleteMockDispatch (mockDispatches, key) {
+ const index = mockDispatches.findIndex(dispatch => {
+ if (!dispatch.consumed) {
+ return false
}
+ return matchKey(dispatch, key)
+ })
+ if (index !== -1) {
+ mockDispatches.splice(index, 1)
}
+}
- // 2. If policy is not the empty string, then set request’s referrer policy to policy.
- if (policy !== '') {
- request.referrerPolicy = policy
+function buildKey (opts) {
+ const { path, method, body, headers, query } = opts
+ return {
+ path,
+ method,
+ body,
+ headers,
+ query
}
}
-// https://fetch.spec.whatwg.org/#cross-origin-resource-policy-check
-function crossOriginResourcePolicyCheck () {
- // TODO
- return 'allowed'
+function generateKeyValues (data) {
+ const keys = Object.keys(data)
+ const result = []
+ for (let i = 0; i < keys.length; ++i) {
+ const key = keys[i]
+ const value = data[key]
+ const name = Buffer.from(`${key}`)
+ if (Array.isArray(value)) {
+ for (let j = 0; j < value.length; ++j) {
+ result.push(name, Buffer.from(`${value[j]}`))
+ }
+ } else {
+ result.push(name, Buffer.from(`${value}`))
+ }
+ }
+ return result
}
-// https://fetch.spec.whatwg.org/#concept-cors-check
-function corsCheck () {
- // TODO
- return 'success'
+/**
+ * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
+ * @param {number} statusCode
+ */
+function getStatusText (statusCode) {
+ return STATUS_CODES[statusCode] || 'unknown'
}
-// https://fetch.spec.whatwg.org/#concept-tao-check
-function TAOCheck () {
- // TODO
- return 'success'
+async function getResponse (body) {
+ const buffers = []
+ for await (const data of body) {
+ buffers.push(data)
+ }
+ return Buffer.concat(buffers).toString('utf8')
}
-function appendFetchMetadata (httpRequest) {
- // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-dest-header
- // TODO
+/**
+ * Mock dispatch function used to simulate undici dispatches
+ */
+function mockDispatch (opts, handler) {
+ // Get mock dispatch from built key
+ const key = buildKey(opts)
+ const mockDispatch = getMockDispatch(this[kDispatches], key)
- // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-mode-header
+ mockDispatch.timesInvoked++
- // 1. Assert: r’s url is a potentially trustworthy URL.
- // TODO
+ // Here's where we resolve a callback if a callback is present for the dispatch data.
+ if (mockDispatch.data.callback) {
+ mockDispatch.data = { ...mockDispatch.data, ...mockDispatch.data.callback(opts) }
+ }
- // 2. Let header be a Structured Header whose value is a token.
- let header = null
+ // Parse mockDispatch data
+ const { data: { statusCode, data, headers, trailers, error }, delay, persist } = mockDispatch
+ const { timesInvoked, times } = mockDispatch
- // 3. Set header’s value to r’s mode.
- header = httpRequest.mode
+ // If it's used up and not persistent, mark as consumed
+ mockDispatch.consumed = !persist && timesInvoked >= times
+ mockDispatch.pending = timesInvoked < times
- // 4. Set a structured field value `Sec-Fetch-Mode`/header in r’s header list.
- httpRequest.headersList.set('sec-fetch-mode', header, true)
+ // If specified, trigger dispatch error
+ if (error !== null) {
+ deleteMockDispatch(this[kDispatches], key)
+ handler.onError(error)
+ return true
+ }
- // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-site-header
- // TODO
+ // Handle the request with a delay if necessary
+ if (typeof delay === 'number' && delay > 0) {
+ setTimeout(() => {
+ handleReply(this[kDispatches])
+ }, delay)
+ } else {
+ handleReply(this[kDispatches])
+ }
- // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-user-header
- // TODO
-}
+ function handleReply (mockDispatches, _data = data) {
+ // fetch's HeadersList is a 1D string array
+ const optsHeaders = Array.isArray(opts.headers)
+ ? buildHeadersFromArray(opts.headers)
+ : opts.headers
+ const body = typeof _data === 'function'
+ ? _data({ ...opts, headers: optsHeaders })
+ : _data
-// https://fetch.spec.whatwg.org/#append-a-request-origin-header
-function appendRequestOriginHeader (request) {
- // 1. Let serializedOrigin be the result of byte-serializing a request origin
- // with request.
- // TODO: implement "byte-serializing a request origin"
- let serializedOrigin = request.origin
+ // util.types.isPromise is likely needed for jest.
+ if (isPromise(body)) {
+ // If handleReply is asynchronous, throwing an error
+ // in the callback will reject the promise, rather than
+ // synchronously throw the error, which breaks some tests.
+ // Rather, we wait for the callback to resolve if it is a
+ // promise, and then re-run handleReply with the new body.
+ body.then((newData) => handleReply(mockDispatches, newData))
+ return
+ }
- // - "'client' is changed to an origin during fetching."
- // This doesn't happen in undici (in most cases) because undici, by default,
- // has no concept of origin.
- // - request.origin can also be set to request.client.origin (client being
- // an environment settings object), which is undefined without using
- // setGlobalOrigin.
- if (serializedOrigin === 'client' || serializedOrigin === undefined) {
- return
+ const responseData = getResponseData(body)
+ const responseHeaders = generateKeyValues(headers)
+ const responseTrailers = generateKeyValues(trailers)
+
+ handler.onConnect?.(err => handler.onError(err), null)
+ handler.onHeaders?.(statusCode, responseHeaders, resume, getStatusText(statusCode))
+ handler.onData?.(Buffer.from(responseData))
+ handler.onComplete?.(responseTrailers)
+ deleteMockDispatch(mockDispatches, key)
}
- // 2. If request’s response tainting is "cors" or request’s mode is "websocket",
- // then append (`Origin`, serializedOrigin) to request’s header list.
- // 3. Otherwise, if request’s method is neither `GET` nor `HEAD`, then:
- if (request.responseTainting === 'cors' || request.mode === 'websocket') {
- request.headersList.append('origin', serializedOrigin, true)
- } else if (request.method !== 'GET' && request.method !== 'HEAD') {
- // 1. Switch on request’s referrer policy:
- switch (request.referrerPolicy) {
- case 'no-referrer':
- // Set serializedOrigin to `null`.
- serializedOrigin = null
- break
- case 'no-referrer-when-downgrade':
- case 'strict-origin':
- case 'strict-origin-when-cross-origin':
- // If request’s origin is a tuple origin, its scheme is "https", and
- // request’s current URL’s scheme is not "https", then set
- // serializedOrigin to `null`.
- if (request.origin && urlHasHttpsScheme(request.origin) && !urlHasHttpsScheme(requestCurrentURL(request))) {
- serializedOrigin = null
- }
- break
- case 'same-origin':
- // If request’s origin is not same origin with request’s current URL’s
- // origin, then set serializedOrigin to `null`.
- if (!sameOrigin(request, requestCurrentURL(request))) {
- serializedOrigin = null
- }
- break
- default:
- // Do nothing.
- }
+ function resume () {}
- // 2. Append (`Origin`, serializedOrigin) to request’s header list.
- request.headersList.append('origin', serializedOrigin, true)
- }
+ return true
}
-// https://w3c.github.io/hr-time/#dfn-coarsen-time
-function coarsenTime (timestamp, crossOriginIsolatedCapability) {
- // TODO
- return timestamp
-}
+function buildMockDispatch () {
+ const agent = this[kMockAgent]
+ const origin = this[kOrigin]
+ const originalDispatch = this[kOriginalDispatch]
-// https://fetch.spec.whatwg.org/#clamp-and-coarsen-connection-timing-info
-function clampAndCoarsenConnectionTimingInfo (connectionTimingInfo, defaultStartTime, crossOriginIsolatedCapability) {
- if (!connectionTimingInfo?.startTime || connectionTimingInfo.startTime < defaultStartTime) {
- return {
- domainLookupStartTime: defaultStartTime,
- domainLookupEndTime: defaultStartTime,
- connectionStartTime: defaultStartTime,
- connectionEndTime: defaultStartTime,
- secureConnectionStartTime: defaultStartTime,
- ALPNNegotiatedProtocol: connectionTimingInfo?.ALPNNegotiatedProtocol
+ return function dispatch (opts, handler) {
+ if (agent.isMockActive) {
+ try {
+ mockDispatch.call(this, opts, handler)
+ } catch (error) {
+ if (error instanceof MockNotMatchedError) {
+ const netConnect = agent[kGetNetConnect]()
+ if (netConnect === false) {
+ throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)`)
+ }
+ if (checkNetConnect(netConnect, origin)) {
+ originalDispatch.call(this, opts, handler)
+ } else {
+ throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)`)
+ }
+ } else {
+ throw error
+ }
+ }
+ } else {
+ originalDispatch.call(this, opts, handler)
}
}
-
- return {
- domainLookupStartTime: coarsenTime(connectionTimingInfo.domainLookupStartTime, crossOriginIsolatedCapability),
- domainLookupEndTime: coarsenTime(connectionTimingInfo.domainLookupEndTime, crossOriginIsolatedCapability),
- connectionStartTime: coarsenTime(connectionTimingInfo.connectionStartTime, crossOriginIsolatedCapability),
- connectionEndTime: coarsenTime(connectionTimingInfo.connectionEndTime, crossOriginIsolatedCapability),
- secureConnectionStartTime: coarsenTime(connectionTimingInfo.secureConnectionStartTime, crossOriginIsolatedCapability),
- ALPNNegotiatedProtocol: connectionTimingInfo.ALPNNegotiatedProtocol
- }
}
-// https://w3c.github.io/hr-time/#dfn-coarsened-shared-current-time
-function coarsenedSharedCurrentTime (crossOriginIsolatedCapability) {
- return coarsenTime(performance.now(), crossOriginIsolatedCapability)
+function checkNetConnect (netConnect, origin) {
+ const url = new URL(origin)
+ if (netConnect === true) {
+ return true
+ } else if (Array.isArray(netConnect) && netConnect.some((matcher) => matchValue(matcher, url.host))) {
+ return true
+ }
+ return false
}
-// https://fetch.spec.whatwg.org/#create-an-opaque-timing-info
-function createOpaqueTimingInfo (timingInfo) {
- return {
- startTime: timingInfo.startTime ?? 0,
- redirectStartTime: 0,
- redirectEndTime: 0,
- postRedirectStartTime: timingInfo.startTime ?? 0,
- finalServiceWorkerStartTime: 0,
- finalNetworkResponseStartTime: 0,
- finalNetworkRequestStartTime: 0,
- endTime: 0,
- encodedBodySize: 0,
- decodedBodySize: 0,
- finalConnectionTimingInfo: null
+function buildMockOptions (opts) {
+ if (opts) {
+ const { agent, ...mockOptions } = opts
+ return mockOptions
}
}
-// https://html.spec.whatwg.org/multipage/origin.html#policy-container
-function makePolicyContainer () {
- // Note: the fetch spec doesn't make use of embedder policy or CSP list
- return {
- referrerPolicy: 'strict-origin-when-cross-origin'
- }
+module.exports = {
+ getResponseData,
+ getMockDispatch,
+ addMockDispatch,
+ deleteMockDispatch,
+ buildKey,
+ generateKeyValues,
+ matchValue,
+ getResponse,
+ getStatusText,
+ mockDispatch,
+ buildMockDispatch,
+ checkNetConnect,
+ buildMockOptions,
+ getHeaderByName,
+ buildHeadersFromArray
}
-// https://html.spec.whatwg.org/multipage/origin.html#clone-a-policy-container
-function clonePolicyContainer (policyContainer) {
- return {
- referrerPolicy: policyContainer.referrerPolicy
- }
-}
-
-// https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer
-function determineRequestsReferrer (request) {
- // 1. Let policy be request's referrer policy.
- const policy = request.referrerPolicy
-
- // Note: policy cannot (shouldn't) be null or an empty string.
- assert(policy)
-
- // 2. Let environment be request’s client.
-
- let referrerSource = null
-
- // 3. Switch on request’s referrer:
- if (request.referrer === 'client') {
- // Note: node isn't a browser and doesn't implement document/iframes,
- // so we bypass this step and replace it with our own.
-
- const globalOrigin = getGlobalOrigin()
- if (!globalOrigin || globalOrigin.origin === 'null') {
- return 'no-referrer'
- }
-
- // note: we need to clone it as it's mutated
- referrerSource = new URL(globalOrigin)
- } else if (request.referrer instanceof URL) {
- // Let referrerSource be request’s referrer.
- referrerSource = request.referrer
- }
+/***/ }),
- // 4. Let request’s referrerURL be the result of stripping referrerSource for
- // use as a referrer.
- let referrerURL = stripURLForReferrer(referrerSource)
+/***/ 6142:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 5. Let referrerOrigin be the result of stripping referrerSource for use as
- // a referrer, with the origin-only flag set to true.
- const referrerOrigin = stripURLForReferrer(referrerSource, true)
- // 6. If the result of serializing referrerURL is a string whose length is
- // greater than 4096, set referrerURL to referrerOrigin.
- if (referrerURL.toString().length > 4096) {
- referrerURL = referrerOrigin
- }
- const areSameOrigin = sameOrigin(request, referrerURL)
- const isNonPotentiallyTrustWorthy = isURLPotentiallyTrustworthy(referrerURL) &&
- !isURLPotentiallyTrustworthy(request.url)
+const { Transform } = __nccwpck_require__(7075)
+const { Console } = __nccwpck_require__(7540)
- // 8. Execute the switch statements corresponding to the value of policy:
- switch (policy) {
- case 'origin': return referrerOrigin != null ? referrerOrigin : stripURLForReferrer(referrerSource, true)
- case 'unsafe-url': return referrerURL
- case 'same-origin':
- return areSameOrigin ? referrerOrigin : 'no-referrer'
- case 'origin-when-cross-origin':
- return areSameOrigin ? referrerURL : referrerOrigin
- case 'strict-origin-when-cross-origin': {
- const currentURL = requestCurrentURL(request)
+const PERSISTENT = process.versions.icu ? '✅' : 'Y '
+const NOT_PERSISTENT = process.versions.icu ? '❌' : 'N '
- // 1. If the origin of referrerURL and the origin of request’s current
- // URL are the same, then return referrerURL.
- if (sameOrigin(referrerURL, currentURL)) {
- return referrerURL
+/**
+ * Gets the output of `console.table(…)` as a string.
+ */
+module.exports = class PendingInterceptorsFormatter {
+ constructor ({ disableColors } = {}) {
+ this.transform = new Transform({
+ transform (chunk, _enc, cb) {
+ cb(null, chunk)
}
+ })
- // 2. If referrerURL is a potentially trustworthy URL and request’s
- // current URL is not a potentially trustworthy URL, then return no
- // referrer.
- if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) {
- return 'no-referrer'
+ this.logger = new Console({
+ stdout: this.transform,
+ inspectOptions: {
+ colors: !disableColors && !process.env.CI
}
+ })
+ }
- // 3. Return referrerOrigin.
- return referrerOrigin
- }
- case 'strict-origin': // eslint-disable-line
- /**
- * 1. If referrerURL is a potentially trustworthy URL and
- * request’s current URL is not a potentially trustworthy URL,
- * then return no referrer.
- * 2. Return referrerOrigin
- */
- case 'no-referrer-when-downgrade': // eslint-disable-line
- /**
- * 1. If referrerURL is a potentially trustworthy URL and
- * request’s current URL is not a potentially trustworthy URL,
- * then return no referrer.
- * 2. Return referrerOrigin
- */
+ format (pendingInterceptors) {
+ const withPrettyHeaders = pendingInterceptors.map(
+ ({ method, path, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
+ Method: method,
+ Origin: origin,
+ Path: path,
+ 'Status code': statusCode,
+ Persistent: persist ? PERSISTENT : NOT_PERSISTENT,
+ Invocations: timesInvoked,
+ Remaining: persist ? Infinity : times - timesInvoked
+ }))
- default: // eslint-disable-line
- return isNonPotentiallyTrustWorthy ? 'no-referrer' : referrerOrigin
+ this.logger.table(withPrettyHeaders)
+ return this.transform.read().toString()
}
}
-/**
- * @see https://w3c.github.io/webappsec-referrer-policy/#strip-url
- * @param {URL} url
- * @param {boolean|undefined} originOnly
- */
-function stripURLForReferrer (url, originOnly) {
- // 1. Assert: url is a URL.
- assert(url instanceof URL)
-
- url = new URL(url)
-
- // 2. If url’s scheme is a local scheme, then return no referrer.
- if (url.protocol === 'file:' || url.protocol === 'about:' || url.protocol === 'blank:') {
- return 'no-referrer'
- }
- // 3. Set url’s username to the empty string.
- url.username = ''
+/***/ }),
- // 4. Set url’s password to the empty string.
- url.password = ''
+/***/ 1529:
+/***/ ((module) => {
- // 5. Set url’s fragment to null.
- url.hash = ''
- // 6. If the origin-only flag is true, then:
- if (originOnly) {
- // 1. Set url’s path to « the empty string ».
- url.pathname = ''
- // 2. Set url’s query to null.
- url.search = ''
- }
+const singulars = {
+ pronoun: 'it',
+ is: 'is',
+ was: 'was',
+ this: 'this'
+}
- // 7. Return url.
- return url
+const plurals = {
+ pronoun: 'they',
+ is: 'are',
+ was: 'were',
+ this: 'these'
}
-function isURLPotentiallyTrustworthy (url) {
- if (!(url instanceof URL)) {
- return false
+module.exports = class Pluralizer {
+ constructor (singular, plural) {
+ this.singular = singular
+ this.plural = plural
}
- // If child of about, return true
- if (url.href === 'about:blank' || url.href === 'about:srcdoc') {
- return true
+ pluralize (count) {
+ const one = count === 1
+ const keys = one ? singulars : plurals
+ const noun = one ? this.singular : this.plural
+ return { ...keys, count, noun }
}
+}
- // If scheme is data, return true
- if (url.protocol === 'data:') return true
-
- // If file, return true
- if (url.protocol === 'file:') return true
-
- return isOriginPotentiallyTrustworthy(url.origin)
-
- function isOriginPotentiallyTrustworthy (origin) {
- // If origin is explicitly null, return false
- if (origin == null || origin === 'null') return false
- const originAsURL = new URL(origin)
+/***/ }),
- // If secure, return true
- if (originAsURL.protocol === 'https:' || originAsURL.protocol === 'wss:') {
- return true
- }
+/***/ 6603:
+/***/ ((module) => {
- // If localhost or variants, return true
- if (/^127(?:\.[0-9]+){0,2}\.[0-9]+$|^\[(?:0*:)*?:?0*1\]$/.test(originAsURL.hostname) ||
- (originAsURL.hostname === 'localhost' || originAsURL.hostname.includes('localhost.')) ||
- (originAsURL.hostname.endsWith('.localhost'))) {
- return true
- }
- // If any other, return false
- return false
- }
-}
/**
- * @see https://w3c.github.io/webappsec-subresource-integrity/#does-response-match-metadatalist
- * @param {Uint8Array} bytes
- * @param {string} metadataList
+ * This module offers an optimized timer implementation designed for scenarios
+ * where high precision is not critical.
+ *
+ * The timer achieves faster performance by using a low-resolution approach,
+ * with an accuracy target of within 500ms. This makes it particularly useful
+ * for timers with delays of 1 second or more, where exact timing is less
+ * crucial.
+ *
+ * It's important to note that Node.js timers are inherently imprecise, as
+ * delays can occur due to the event loop being blocked by other operations.
+ * Consequently, timers may trigger later than their scheduled time.
*/
-function bytesMatch (bytes, metadataList) {
- // If node is not built with OpenSSL support, we cannot check
- // a request's integrity, so allow it by default (the spec will
- // allow requests if an invalid hash is given, as precedence).
- /* istanbul ignore if: only if node is built with --without-ssl */
- if (crypto === undefined) {
- return true
- }
-
- // 1. Let parsedMetadata be the result of parsing metadataList.
- const parsedMetadata = parseMetadata(metadataList)
- // 2. If parsedMetadata is no metadata, return true.
- if (parsedMetadata === 'no metadata') {
- return true
- }
-
- // 3. If response is not eligible for integrity validation, return false.
- // TODO
+/**
+ * The fastNow variable contains the internal fast timer clock value.
+ *
+ * @type {number}
+ */
+let fastNow = 0
- // 4. If parsedMetadata is the empty set, return true.
- if (parsedMetadata.length === 0) {
- return true
- }
+/**
+ * RESOLUTION_MS represents the target resolution time in milliseconds.
+ *
+ * @type {number}
+ * @default 1000
+ */
+const RESOLUTION_MS = 1e3
- // 5. Let metadata be the result of getting the strongest
- // metadata from parsedMetadata.
- const strongest = getStrongestMetadata(parsedMetadata)
- const metadata = filterMetadataListByAlgorithm(parsedMetadata, strongest)
+/**
+ * TICK_MS defines the desired interval in milliseconds between each tick.
+ * The target value is set to half the resolution time, minus 1 ms, to account
+ * for potential event loop overhead.
+ *
+ * @type {number}
+ * @default 499
+ */
+const TICK_MS = (RESOLUTION_MS >> 1) - 1
- // 6. For each item in metadata:
- for (const item of metadata) {
- // 1. Let algorithm be the alg component of item.
- const algorithm = item.algo
+/**
+ * fastNowTimeout is a Node.js timer used to manage and process
+ * the FastTimers stored in the `fastTimers` array.
+ *
+ * @type {NodeJS.Timeout}
+ */
+let fastNowTimeout
- // 2. Let expectedValue be the val component of item.
- const expectedValue = item.hash
+/**
+ * The kFastTimer symbol is used to identify FastTimer instances.
+ *
+ * @type {Symbol}
+ */
+const kFastTimer = Symbol('kFastTimer')
- // See https://github.com/web-platform-tests/wpt/commit/e4c5cc7a5e48093220528dfdd1c4012dc3837a0e
- // "be liberal with padding". This is annoying, and it's not even in the spec.
+/**
+ * The fastTimers array contains all active FastTimers.
+ *
+ * @type {FastTimer[]}
+ */
+const fastTimers = []
- // 3. Let actualValue be the result of applying algorithm to bytes.
- let actualValue = crypto.createHash(algorithm).update(bytes).digest('base64')
+/**
+ * These constants represent the various states of a FastTimer.
+ */
- if (actualValue[actualValue.length - 1] === '=') {
- if (actualValue[actualValue.length - 2] === '=') {
- actualValue = actualValue.slice(0, -2)
- } else {
- actualValue = actualValue.slice(0, -1)
- }
- }
+/**
+ * The `NOT_IN_LIST` constant indicates that the FastTimer is not included
+ * in the `fastTimers` array. Timers with this status will not be processed
+ * during the next tick by the `onTick` function.
+ *
+ * A FastTimer can be re-added to the `fastTimers` array by invoking the
+ * `refresh` method on the FastTimer instance.
+ *
+ * @type {-2}
+ */
+const NOT_IN_LIST = -2
- // 4. If actualValue is a case-sensitive match for expectedValue,
- // return true.
- if (compareBase64Mixed(actualValue, expectedValue)) {
- return true
- }
- }
+/**
+ * The `TO_BE_CLEARED` constant indicates that the FastTimer is scheduled
+ * for removal from the `fastTimers` array. A FastTimer in this state will
+ * be removed in the next tick by the `onTick` function and will no longer
+ * be processed.
+ *
+ * This status is also set when the `clear` method is called on the FastTimer instance.
+ *
+ * @type {-1}
+ */
+const TO_BE_CLEARED = -1
- // 7. Return false.
- return false
-}
+/**
+ * The `PENDING` constant signifies that the FastTimer is awaiting processing
+ * in the next tick by the `onTick` function. Timers with this status will have
+ * their `_idleStart` value set and their status updated to `ACTIVE` in the next tick.
+ *
+ * @type {0}
+ */
+const PENDING = 0
-// https://w3c.github.io/webappsec-subresource-integrity/#grammardef-hash-with-options
-// https://www.w3.org/TR/CSP2/#source-list-syntax
-// https://www.rfc-editor.org/rfc/rfc5234#appendix-B.1
-const parseHashWithOptions = /(?sha256|sha384|sha512)-((?[A-Za-z0-9+/]+|[A-Za-z0-9_-]+)={0,2}(?:\s|$)( +[!-~]*)?)?/i
+/**
+ * The `ACTIVE` constant indicates that the FastTimer is active and waiting
+ * for its timer to expire. During the next tick, the `onTick` function will
+ * check if the timer has expired, and if so, it will execute the associated callback.
+ *
+ * @type {1}
+ */
+const ACTIVE = 1
/**
- * @see https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata
- * @param {string} metadata
+ * The onTick function processes the fastTimers array.
+ *
+ * @returns {void}
*/
-function parseMetadata (metadata) {
- // 1. Let result be the empty set.
- /** @type {{ algo: string, hash: string }[]} */
- const result = []
+function onTick () {
+ /**
+ * Increment the fastNow value by the TICK_MS value, despite the actual time
+ * that has passed since the last tick. This approach ensures independence
+ * from the system clock and delays caused by a blocked event loop.
+ *
+ * @type {number}
+ */
+ fastNow += TICK_MS
- // 2. Let empty be equal to true.
- let empty = true
+ /**
+ * The `idx` variable is used to iterate over the `fastTimers` array.
+ * Expired timers are removed by replacing them with the last element in the array.
+ * Consequently, `idx` is only incremented when the current element is not removed.
+ *
+ * @type {number}
+ */
+ let idx = 0
- // 3. For each token returned by splitting metadata on spaces:
- for (const token of metadata.split(' ')) {
- // 1. Set empty to false.
- empty = false
+ /**
+ * The len variable will contain the length of the fastTimers array
+ * and will be decremented when a FastTimer should be removed from the
+ * fastTimers array.
+ *
+ * @type {number}
+ */
+ let len = fastTimers.length
- // 2. Parse token as a hash-with-options.
- const parsedToken = parseHashWithOptions.exec(token)
+ while (idx < len) {
+ /**
+ * @type {FastTimer}
+ */
+ const timer = fastTimers[idx]
- // 3. If token does not parse, continue to the next token.
- if (
- parsedToken === null ||
- parsedToken.groups === undefined ||
- parsedToken.groups.algo === undefined
+ // If the timer is in the ACTIVE state and the timer has expired, it will
+ // be processed in the next tick.
+ if (timer._state === PENDING) {
+ // Set the _idleStart value to the fastNow value minus the TICK_MS value
+ // to account for the time the timer was in the PENDING state.
+ timer._idleStart = fastNow - TICK_MS
+ timer._state = ACTIVE
+ } else if (
+ timer._state === ACTIVE &&
+ fastNow >= timer._idleStart + timer._idleTimeout
) {
- // Note: Chromium blocks the request at this point, but Firefox
- // gives a warning that an invalid integrity was given. The
- // correct behavior is to ignore these, and subsequently not
- // check the integrity of the resource.
- continue
+ timer._state = TO_BE_CLEARED
+ timer._idleStart = -1
+ timer._onTimeout(timer._timerArg)
}
- // 4. Let algorithm be the hash-algo component of token.
- const algorithm = parsedToken.groups.algo.toLowerCase()
+ if (timer._state === TO_BE_CLEARED) {
+ timer._state = NOT_IN_LIST
- // 5. If algorithm is a hash function recognized by the user
- // agent, add the parsed token to result.
- if (supportedHashes.includes(algorithm)) {
- result.push(parsedToken.groups)
+ // Move the last element to the current index and decrement len if it is
+ // not the only element in the array.
+ if (--len !== 0) {
+ fastTimers[idx] = fastTimers[len]
+ }
+ } else {
+ ++idx
}
}
- // 4. Return no metadata if empty is true, otherwise return result.
- if (empty === true) {
- return 'no metadata'
- }
-
- return result
-}
-
-/**
- * @param {{ algo: 'sha256' | 'sha384' | 'sha512' }[]} metadataList
- */
-function getStrongestMetadata (metadataList) {
- // Let algorithm be the algo component of the first item in metadataList.
- // Can be sha256
- let algorithm = metadataList[0].algo
- // If the algorithm is sha512, then it is the strongest
- // and we can return immediately
- if (algorithm[3] === '5') {
- return algorithm
- }
+ // Set the length of the fastTimers array to the new length and thus
+ // removing the excess FastTimers elements from the array.
+ fastTimers.length = len
- for (let i = 1; i < metadataList.length; ++i) {
- const metadata = metadataList[i]
- // If the algorithm is sha512, then it is the strongest
- // and we can break the loop immediately
- if (metadata.algo[3] === '5') {
- algorithm = 'sha512'
- break
- // If the algorithm is sha384, then a potential sha256 or sha384 is ignored
- } else if (algorithm[3] === '3') {
- continue
- // algorithm is sha256, check if algorithm is sha384 and if so, set it as
- // the strongest
- } else if (metadata.algo[3] === '3') {
- algorithm = 'sha384'
- }
+ // If there are still active FastTimers in the array, refresh the Timer.
+ // If there are no active FastTimers, the timer will be refreshed again
+ // when a new FastTimer is instantiated.
+ if (fastTimers.length !== 0) {
+ refreshTimeout()
}
- return algorithm
}
-function filterMetadataListByAlgorithm (metadataList, algorithm) {
- if (metadataList.length === 1) {
- return metadataList
- }
+function refreshTimeout () {
+ // If the fastNowTimeout is already set, refresh it.
+ if (fastNowTimeout) {
+ fastNowTimeout.refresh()
+ // fastNowTimeout is not instantiated yet, create a new Timer.
+ } else {
+ clearTimeout(fastNowTimeout)
+ fastNowTimeout = setTimeout(onTick, TICK_MS)
- let pos = 0
- for (let i = 0; i < metadataList.length; ++i) {
- if (metadataList[i].algo === algorithm) {
- metadataList[pos++] = metadataList[i]
+ // If the Timer has an unref method, call it to allow the process to exit if
+ // there are no other active handles.
+ if (fastNowTimeout.unref) {
+ fastNowTimeout.unref()
}
}
-
- metadataList.length = pos
-
- return metadataList
}
/**
- * Compares two base64 strings, allowing for base64url
- * in the second string.
- *
-* @param {string} actualValue always base64
- * @param {string} expectedValue base64 or base64url
- * @returns {boolean}
+ * The `FastTimer` class is a data structure designed to store and manage
+ * timer information.
*/
-function compareBase64Mixed (actualValue, expectedValue) {
- if (actualValue.length !== expectedValue.length) {
- return false
+class FastTimer {
+ [kFastTimer] = true
+
+ /**
+ * The state of the timer, which can be one of the following:
+ * - NOT_IN_LIST (-2)
+ * - TO_BE_CLEARED (-1)
+ * - PENDING (0)
+ * - ACTIVE (1)
+ *
+ * @type {-2|-1|0|1}
+ * @private
+ */
+ _state = NOT_IN_LIST
+
+ /**
+ * The number of milliseconds to wait before calling the callback.
+ *
+ * @type {number}
+ * @private
+ */
+ _idleTimeout = -1
+
+ /**
+ * The time in milliseconds when the timer was started. This value is used to
+ * calculate when the timer should expire.
+ *
+ * @type {number}
+ * @default -1
+ * @private
+ */
+ _idleStart = -1
+
+ /**
+ * The function to be executed when the timer expires.
+ * @type {Function}
+ * @private
+ */
+ _onTimeout
+
+ /**
+ * The argument to be passed to the callback when the timer expires.
+ *
+ * @type {*}
+ * @private
+ */
+ _timerArg
+
+ /**
+ * @constructor
+ * @param {Function} callback A function to be executed after the timer
+ * expires.
+ * @param {number} delay The time, in milliseconds that the timer should wait
+ * before the specified function or code is executed.
+ * @param {*} arg
+ */
+ constructor (callback, delay, arg) {
+ this._onTimeout = callback
+ this._idleTimeout = delay
+ this._timerArg = arg
+
+ this.refresh()
}
- for (let i = 0; i < actualValue.length; ++i) {
- if (actualValue[i] !== expectedValue[i]) {
- if (
- (actualValue[i] === '+' && expectedValue[i] === '-') ||
- (actualValue[i] === '/' && expectedValue[i] === '_')
- ) {
- continue
- }
- return false
+
+ /**
+ * Sets the timer's start time to the current time, and reschedules the timer
+ * to call its callback at the previously specified duration adjusted to the
+ * current time.
+ * Using this on a timer that has already called its callback will reactivate
+ * the timer.
+ *
+ * @returns {void}
+ */
+ refresh () {
+ // In the special case that the timer is not in the list of active timers,
+ // add it back to the array to be processed in the next tick by the onTick
+ // function.
+ if (this._state === NOT_IN_LIST) {
+ fastTimers.push(this)
+ }
+
+ // If the timer is the only active timer, refresh the fastNowTimeout for
+ // better resolution.
+ if (!fastNowTimeout || fastTimers.length === 1) {
+ refreshTimeout()
}
+
+ // Setting the state to PENDING will cause the timer to be reset in the
+ // next tick by the onTick function.
+ this._state = PENDING
}
- return true
-}
+ /**
+ * The `clear` method cancels the timer, preventing it from executing.
+ *
+ * @returns {void}
+ * @private
+ */
+ clear () {
+ // Set the state to TO_BE_CLEARED to mark the timer for removal in the next
+ // tick by the onTick function.
+ this._state = TO_BE_CLEARED
-// https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-request
-function tryUpgradeRequestToAPotentiallyTrustworthyURL (request) {
- // TODO
+ // Reset the _idleStart value to -1 to indicate that the timer is no longer
+ // active.
+ this._idleStart = -1
+ }
}
/**
- * @link {https://html.spec.whatwg.org/multipage/origin.html#same-origin}
- * @param {URL} A
- * @param {URL} B
+ * This module exports a setTimeout and clearTimeout function that can be
+ * used as a drop-in replacement for the native functions.
*/
-function sameOrigin (A, B) {
- // 1. If A and B are the same opaque origin, then return true.
- if (A.origin === B.origin && A.origin === 'null') {
- return true
- }
+module.exports = {
+ /**
+ * The setTimeout() method sets a timer which executes a function once the
+ * timer expires.
+ * @param {Function} callback A function to be executed after the timer
+ * expires.
+ * @param {number} delay The time, in milliseconds that the timer should
+ * wait before the specified function or code is executed.
+ * @param {*} [arg] An optional argument to be passed to the callback function
+ * when the timer expires.
+ * @returns {NodeJS.Timeout|FastTimer}
+ */
+ setTimeout (callback, delay, arg) {
+ // If the delay is less than or equal to the RESOLUTION_MS value return a
+ // native Node.js Timer instance.
+ return delay <= RESOLUTION_MS
+ ? setTimeout(callback, delay, arg)
+ : new FastTimer(callback, delay, arg)
+ },
+ /**
+ * The clearTimeout method cancels an instantiated Timer previously created
+ * by calling setTimeout.
+ *
+ * @param {NodeJS.Timeout|FastTimer} timeout
+ */
+ clearTimeout (timeout) {
+ // If the timeout is a FastTimer, call its own clear method.
+ if (timeout[kFastTimer]) {
+ /**
+ * @type {FastTimer}
+ */
+ timeout.clear()
+ // Otherwise it is an instance of a native NodeJS.Timeout, so call the
+ // Node.js native clearTimeout function.
+ } else {
+ clearTimeout(timeout)
+ }
+ },
+ /**
+ * The setFastTimeout() method sets a fastTimer which executes a function once
+ * the timer expires.
+ * @param {Function} callback A function to be executed after the timer
+ * expires.
+ * @param {number} delay The time, in milliseconds that the timer should
+ * wait before the specified function or code is executed.
+ * @param {*} [arg] An optional argument to be passed to the callback function
+ * when the timer expires.
+ * @returns {FastTimer}
+ */
+ setFastTimeout (callback, delay, arg) {
+ return new FastTimer(callback, delay, arg)
+ },
+ /**
+ * The clearTimeout method cancels an instantiated FastTimer previously
+ * created by calling setFastTimeout.
+ *
+ * @param {FastTimer} timeout
+ */
+ clearFastTimeout (timeout) {
+ timeout.clear()
+ },
+ /**
+ * The now method returns the value of the internal fast timer clock.
+ *
+ * @returns {number}
+ */
+ now () {
+ return fastNow
+ },
+ /**
+ * Trigger the onTick function to process the fastTimers array.
+ * Exported for testing purposes only.
+ * Marking as deprecated to discourage any use outside of testing.
+ * @deprecated
+ * @param {number} [delay=0] The delay in milliseconds to add to the now value.
+ */
+ tick (delay = 0) {
+ fastNow += delay - RESOLUTION_MS + 1
+ onTick()
+ onTick()
+ },
+ /**
+ * Reset FastTimers.
+ * Exported for testing purposes only.
+ * Marking as deprecated to discourage any use outside of testing.
+ * @deprecated
+ */
+ reset () {
+ fastNow = 0
+ fastTimers.length = 0
+ clearTimeout(fastNowTimeout)
+ fastNowTimeout = null
+ },
+ /**
+ * Exporting for testing purposes only.
+ * Marking as deprecated to discourage any use outside of testing.
+ * @deprecated
+ */
+ kFastTimer
+}
- // 2. If A and B are both tuple origins and their schemes,
- // hosts, and port are identical, then return true.
- if (A.protocol === B.protocol && A.hostname === B.hostname && A.port === B.port) {
- return true
- }
- // 3. Return false.
- return false
-}
+/***/ }),
-function createDeferredPromise () {
- let res
- let rej
- const promise = new Promise((resolve, reject) => {
- res = resolve
- rej = reject
- })
+/***/ 9634:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- return { promise, resolve: res, reject: rej }
-}
-function isAborted (fetchParams) {
- return fetchParams.controller.state === 'aborted'
-}
-function isCancelled (fetchParams) {
- return fetchParams.controller.state === 'aborted' ||
- fetchParams.controller.state === 'terminated'
-}
+const { kConstruct } = __nccwpck_require__(109)
+const { urlEquals, getFieldValues } = __nccwpck_require__(6798)
+const { kEnumerableProperty, isDisturbed } = __nccwpck_require__(3440)
+const { webidl } = __nccwpck_require__(5893)
+const { Response, cloneResponse, fromInnerResponse } = __nccwpck_require__(9051)
+const { Request, fromInnerRequest } = __nccwpck_require__(9967)
+const { kState } = __nccwpck_require__(3627)
+const { fetching } = __nccwpck_require__(4398)
+const { urlIsHttpHttpsScheme, createDeferredPromise, readAllBytes } = __nccwpck_require__(3168)
+const assert = __nccwpck_require__(4589)
/**
- * @see https://fetch.spec.whatwg.org/#concept-method-normalize
- * @param {string} method
+ * @see https://w3c.github.io/ServiceWorker/#dfn-cache-batch-operation
+ * @typedef {Object} CacheBatchOperation
+ * @property {'delete' | 'put'} type
+ * @property {any} request
+ * @property {any} response
+ * @property {import('../../types/cache').CacheQueryOptions} options
*/
-function normalizeMethod (method) {
- return normalizedMethodRecordsBase[method.toLowerCase()] ?? method
-}
-// https://infra.spec.whatwg.org/#serialize-a-javascript-value-to-a-json-string
-function serializeJavascriptValueToJSONString (value) {
- // 1. Let result be ? Call(%JSON.stringify%, undefined, « value »).
- const result = JSON.stringify(value)
+/**
+ * @see https://w3c.github.io/ServiceWorker/#dfn-request-response-list
+ * @typedef {[any, any][]} requestResponseList
+ */
- // 2. If result is undefined, then throw a TypeError.
- if (result === undefined) {
- throw new TypeError('Value is not JSON serializable')
+class Cache {
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list
+ * @type {requestResponseList}
+ */
+ #relevantRequestResponseList
+
+ constructor () {
+ if (arguments[0] !== kConstruct) {
+ webidl.illegalConstructor()
+ }
+
+ webidl.util.markAsUncloneable(this)
+ this.#relevantRequestResponseList = arguments[1]
}
- // 3. Assert: result is a string.
- assert(typeof result === 'string')
+ async match (request, options = {}) {
+ webidl.brandCheck(this, Cache)
- // 4. Return result.
- return result
-}
+ const prefix = 'Cache.match'
+ webidl.argumentLengthCheck(arguments, 1, prefix)
-// https://tc39.es/ecma262/#sec-%25iteratorprototype%25-object
-const esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))
+ request = webidl.converters.RequestInfo(request, prefix, 'request')
+ options = webidl.converters.CacheQueryOptions(options, prefix, 'options')
-/**
- * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object
- * @param {string} name name of the instance
- * @param {symbol} kInternalIterator
- * @param {string | number} [keyIndex]
- * @param {string | number} [valueIndex]
- */
-function createIterator (name, kInternalIterator, keyIndex = 0, valueIndex = 1) {
- class FastIterableIterator {
- /** @type {any} */
- #target
- /** @type {'key' | 'value' | 'key+value'} */
- #kind
- /** @type {number} */
- #index
+ const p = this.#internalMatchAll(request, options, 1)
- /**
- * @see https://webidl.spec.whatwg.org/#dfn-default-iterator-object
- * @param {unknown} target
- * @param {'key' | 'value' | 'key+value'} kind
- */
- constructor (target, kind) {
- this.#target = target
- this.#kind = kind
- this.#index = 0
+ if (p.length === 0) {
+ return
}
- next () {
- // 1. Let interface be the interface for which the iterator prototype object exists.
- // 2. Let thisValue be the this value.
- // 3. Let object be ? ToObject(thisValue).
- // 4. If object is a platform object, then perform a security
- // check, passing:
- // 5. If object is not a default iterator object for interface,
- // then throw a TypeError.
- if (typeof this !== 'object' || this === null || !(#target in this)) {
- throw new TypeError(
- `'next' called on an object that does not implement interface ${name} Iterator.`
- )
- }
+ return p[0]
+ }
- // 6. Let index be object’s index.
- // 7. Let kind be object’s kind.
- // 8. Let values be object’s target's value pairs to iterate over.
- const index = this.#index
- const values = this.#target[kInternalIterator]
+ async matchAll (request = undefined, options = {}) {
+ webidl.brandCheck(this, Cache)
- // 9. Let len be the length of values.
- const len = values.length
+ const prefix = 'Cache.matchAll'
+ if (request !== undefined) request = webidl.converters.RequestInfo(request, prefix, 'request')
+ options = webidl.converters.CacheQueryOptions(options, prefix, 'options')
- // 10. If index is greater than or equal to len, then return
- // CreateIterResultObject(undefined, true).
- if (index >= len) {
- return {
- value: undefined,
- done: true
- }
- }
+ return this.#internalMatchAll(request, options)
+ }
- // 11. Let pair be the entry in values at index index.
- const { [keyIndex]: key, [valueIndex]: value } = values[index]
+ async add (request) {
+ webidl.brandCheck(this, Cache)
- // 12. Set object’s index to index + 1.
- this.#index = index + 1
+ const prefix = 'Cache.add'
+ webidl.argumentLengthCheck(arguments, 1, prefix)
- // 13. Return the iterator result for pair and kind.
+ request = webidl.converters.RequestInfo(request, prefix, 'request')
- // https://webidl.spec.whatwg.org/#iterator-result
+ // 1.
+ const requests = [request]
- // 1. Let result be a value determined by the value of kind:
- let result
- switch (this.#kind) {
- case 'key':
- // 1. Let idlKey be pair’s key.
- // 2. Let key be the result of converting idlKey to an
- // ECMAScript value.
- // 3. result is key.
- result = key
- break
- case 'value':
- // 1. Let idlValue be pair’s value.
- // 2. Let value be the result of converting idlValue to
- // an ECMAScript value.
- // 3. result is value.
- result = value
- break
- case 'key+value':
- // 1. Let idlKey be pair’s key.
- // 2. Let idlValue be pair’s value.
- // 3. Let key be the result of converting idlKey to an
- // ECMAScript value.
- // 4. Let value be the result of converting idlValue to
- // an ECMAScript value.
- // 5. Let array be ! ArrayCreate(2).
- // 6. Call ! CreateDataProperty(array, "0", key).
- // 7. Call ! CreateDataProperty(array, "1", value).
- // 8. result is array.
- result = [key, value]
- break
- }
+ // 2.
+ const responseArrayPromise = this.addAll(requests)
- // 2. Return CreateIterResultObject(result, false).
- return {
- value: result,
- done: false
- }
- }
+ // 3.
+ return await responseArrayPromise
}
- // https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object
- // @ts-ignore
- delete FastIterableIterator.prototype.constructor
+ async addAll (requests) {
+ webidl.brandCheck(this, Cache)
- Object.setPrototypeOf(FastIterableIterator.prototype, esIteratorPrototype)
+ const prefix = 'Cache.addAll'
+ webidl.argumentLengthCheck(arguments, 1, prefix)
- Object.defineProperties(FastIterableIterator.prototype, {
- [Symbol.toStringTag]: {
- writable: false,
- enumerable: false,
- configurable: true,
- value: `${name} Iterator`
- },
- next: { writable: true, enumerable: true, configurable: true }
- })
+ // 1.
+ const responsePromises = []
- /**
- * @param {unknown} target
- * @param {'key' | 'value' | 'key+value'} kind
- * @returns {IterableIterator}
- */
- return function (target, kind) {
- return new FastIterableIterator(target, kind)
- }
-}
+ // 2.
+ const requestList = []
-/**
- * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object
- * @param {string} name name of the instance
- * @param {any} object class
- * @param {symbol} kInternalIterator
- * @param {string | number} [keyIndex]
- * @param {string | number} [valueIndex]
- */
-function iteratorMixin (name, object, kInternalIterator, keyIndex = 0, valueIndex = 1) {
- const makeIterator = createIterator(name, kInternalIterator, keyIndex, valueIndex)
+ // 3.
+ for (let request of requests) {
+ if (request === undefined) {
+ throw webidl.errors.conversionFailed({
+ prefix,
+ argument: 'Argument 1',
+ types: ['undefined is not allowed']
+ })
+ }
- const properties = {
- keys: {
- writable: true,
- enumerable: true,
- configurable: true,
- value: function keys () {
- webidl.brandCheck(this, object)
- return makeIterator(this, 'key')
+ request = webidl.converters.RequestInfo(request)
+
+ if (typeof request === 'string') {
+ continue
}
- },
- values: {
- writable: true,
- enumerable: true,
- configurable: true,
- value: function values () {
- webidl.brandCheck(this, object)
- return makeIterator(this, 'value')
- }
- },
- entries: {
- writable: true,
- enumerable: true,
- configurable: true,
- value: function entries () {
- webidl.brandCheck(this, object)
- return makeIterator(this, 'key+value')
- }
- },
- forEach: {
- writable: true,
- enumerable: true,
- configurable: true,
- value: function forEach (callbackfn, thisArg = globalThis) {
- webidl.brandCheck(this, object)
- webidl.argumentLengthCheck(arguments, 1, `${name}.forEach`)
- if (typeof callbackfn !== 'function') {
- throw new TypeError(
- `Failed to execute 'forEach' on '${name}': parameter 1 is not of type 'Function'.`
- )
- }
- for (const { 0: key, 1: value } of makeIterator(this, 'key+value')) {
- callbackfn.call(thisArg, value, key, this)
- }
+
+ // 3.1
+ const r = request[kState]
+
+ // 3.2
+ if (!urlIsHttpHttpsScheme(r.url) || r.method !== 'GET') {
+ throw webidl.errors.exception({
+ header: prefix,
+ message: 'Expected http/s scheme when method is not GET.'
+ })
}
}
- }
- return Object.defineProperties(object.prototype, {
- ...properties,
- [Symbol.iterator]: {
- writable: true,
- enumerable: false,
- configurable: true,
- value: properties.entries.value
- }
- })
-}
+ // 4.
+ /** @type {ReturnType[]} */
+ const fetchControllers = []
-/**
- * @see https://fetch.spec.whatwg.org/#body-fully-read
- */
-async function fullyReadBody (body, processBody, processBodyError) {
- // 1. If taskDestination is null, then set taskDestination to
- // the result of starting a new parallel queue.
+ // 5.
+ for (const request of requests) {
+ // 5.1
+ const r = new Request(request)[kState]
- // 2. Let successSteps given a byte sequence bytes be to queue a
- // fetch task to run processBody given bytes, with taskDestination.
- const successSteps = processBody
+ // 5.2
+ if (!urlIsHttpHttpsScheme(r.url)) {
+ throw webidl.errors.exception({
+ header: prefix,
+ message: 'Expected http/s scheme.'
+ })
+ }
- // 3. Let errorSteps be to queue a fetch task to run processBodyError,
- // with taskDestination.
- const errorSteps = processBodyError
+ // 5.4
+ r.initiator = 'fetch'
+ r.destination = 'subresource'
- // 4. Let reader be the result of getting a reader for body’s stream.
- // If that threw an exception, then run errorSteps with that
- // exception and return.
- let reader
+ // 5.5
+ requestList.push(r)
- try {
- reader = body.stream.getReader()
- } catch (e) {
- errorSteps(e)
- return
- }
+ // 5.6
+ const responsePromise = createDeferredPromise()
- // 5. Read all bytes from reader, given successSteps and errorSteps.
- try {
- successSteps(await readAllBytes(reader))
- } catch (e) {
- errorSteps(e)
- }
-}
+ // 5.7
+ fetchControllers.push(fetching({
+ request: r,
+ processResponse (response) {
+ // 1.
+ if (response.type === 'error' || response.status === 206 || response.status < 200 || response.status > 299) {
+ responsePromise.reject(webidl.errors.exception({
+ header: 'Cache.addAll',
+ message: 'Received an invalid status code or the request failed.'
+ }))
+ } else if (response.headersList.contains('vary')) { // 2.
+ // 2.1
+ const fieldValues = getFieldValues(response.headersList.get('vary'))
-function isReadableStreamLike (stream) {
- return stream instanceof ReadableStream || (
- stream[Symbol.toStringTag] === 'ReadableStream' &&
- typeof stream.tee === 'function'
- )
-}
+ // 2.2
+ for (const fieldValue of fieldValues) {
+ // 2.2.1
+ if (fieldValue === '*') {
+ responsePromise.reject(webidl.errors.exception({
+ header: 'Cache.addAll',
+ message: 'invalid vary field value'
+ }))
-/**
- * @param {ReadableStreamController} controller
- */
-function readableStreamClose (controller) {
- try {
- controller.close()
- controller.byobRequest?.respond(0)
- } catch (err) {
- // TODO: add comment explaining why this error occurs.
- if (!err.message.includes('Controller is already closed') && !err.message.includes('ReadableStream is already closed')) {
- throw err
+ for (const controller of fetchControllers) {
+ controller.abort()
+ }
+
+ return
+ }
+ }
+ }
+ },
+ processResponseEndOfBody (response) {
+ // 1.
+ if (response.aborted) {
+ responsePromise.reject(new DOMException('aborted', 'AbortError'))
+ return
+ }
+
+ // 2.
+ responsePromise.resolve(response)
+ }
+ }))
+
+ // 5.8
+ responsePromises.push(responsePromise.promise)
}
- }
-}
-const invalidIsomorphicEncodeValueRegex = /[^\x00-\xFF]/ // eslint-disable-line
+ // 6.
+ const p = Promise.all(responsePromises)
-/**
- * @see https://infra.spec.whatwg.org/#isomorphic-encode
- * @param {string} input
- */
-function isomorphicEncode (input) {
- // 1. Assert: input contains no code points greater than U+00FF.
- assert(!invalidIsomorphicEncodeValueRegex.test(input))
+ // 7.
+ const responses = await p
- // 2. Return a byte sequence whose length is equal to input’s code
- // point length and whose bytes have the same values as the
- // values of input’s code points, in the same order
- return input
-}
+ // 7.1
+ const operations = []
-/**
- * @see https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-all-bytes
- * @see https://streams.spec.whatwg.org/#read-loop
- * @param {ReadableStreamDefaultReader} reader
- */
-async function readAllBytes (reader) {
- const bytes = []
- let byteLength = 0
+ // 7.2
+ let index = 0
- while (true) {
- const { done, value: chunk } = await reader.read()
+ // 7.3
+ for (const response of responses) {
+ // 7.3.1
+ /** @type {CacheBatchOperation} */
+ const operation = {
+ type: 'put', // 7.3.2
+ request: requestList[index], // 7.3.3
+ response // 7.3.4
+ }
- if (done) {
- // 1. Call successSteps with bytes.
- return Buffer.concat(bytes, byteLength)
+ operations.push(operation) // 7.3.5
+
+ index++ // 7.3.6
}
- // 1. If chunk is not a Uint8Array object, call failureSteps
- // with a TypeError and abort these steps.
- if (!isUint8Array(chunk)) {
- throw new TypeError('Received non-Uint8Array chunk')
+ // 7.5
+ const cacheJobPromise = createDeferredPromise()
+
+ // 7.6.1
+ let errorData = null
+
+ // 7.6.2
+ try {
+ this.#batchCacheOperations(operations)
+ } catch (e) {
+ errorData = e
}
- // 2. Append the bytes represented by chunk to bytes.
- bytes.push(chunk)
- byteLength += chunk.length
+ // 7.6.3
+ queueMicrotask(() => {
+ // 7.6.3.1
+ if (errorData === null) {
+ cacheJobPromise.resolve(undefined)
+ } else {
+ // 7.6.3.2
+ cacheJobPromise.reject(errorData)
+ }
+ })
- // 3. Read-loop given reader, bytes, successSteps, and failureSteps.
+ // 7.7
+ return cacheJobPromise.promise
}
-}
-/**
- * @see https://fetch.spec.whatwg.org/#is-local
- * @param {URL} url
- */
-function urlIsLocal (url) {
- assert('protocol' in url) // ensure it's a url object
+ async put (request, response) {
+ webidl.brandCheck(this, Cache)
- const protocol = url.protocol
+ const prefix = 'Cache.put'
+ webidl.argumentLengthCheck(arguments, 2, prefix)
- return protocol === 'about:' || protocol === 'blob:' || protocol === 'data:'
-}
+ request = webidl.converters.RequestInfo(request, prefix, 'request')
+ response = webidl.converters.Response(response, prefix, 'response')
-/**
- * @param {string|URL} url
- * @returns {boolean}
- */
-function urlHasHttpsScheme (url) {
- return (
- (
- typeof url === 'string' &&
- url[5] === ':' &&
- url[0] === 'h' &&
- url[1] === 't' &&
- url[2] === 't' &&
- url[3] === 'p' &&
- url[4] === 's'
- ) ||
- url.protocol === 'https:'
- )
-}
+ // 1.
+ let innerRequest = null
-/**
- * @see https://fetch.spec.whatwg.org/#http-scheme
- * @param {URL} url
- */
-function urlIsHttpHttpsScheme (url) {
- assert('protocol' in url) // ensure it's a url object
+ // 2.
+ if (request instanceof Request) {
+ innerRequest = request[kState]
+ } else { // 3.
+ innerRequest = new Request(request)[kState]
+ }
- const protocol = url.protocol
+ // 4.
+ if (!urlIsHttpHttpsScheme(innerRequest.url) || innerRequest.method !== 'GET') {
+ throw webidl.errors.exception({
+ header: prefix,
+ message: 'Expected an http/s scheme when method is not GET'
+ })
+ }
- return protocol === 'http:' || protocol === 'https:'
-}
+ // 5.
+ const innerResponse = response[kState]
-/**
- * @see https://fetch.spec.whatwg.org/#simple-range-header-value
- * @param {string} value
- * @param {boolean} allowWhitespace
- */
-function simpleRangeHeaderValue (value, allowWhitespace) {
- // 1. Let data be the isomorphic decoding of value.
- // Note: isomorphic decoding takes a sequence of bytes (ie. a Uint8Array) and turns it into a string,
- // nothing more. We obviously don't need to do that if value is a string already.
- const data = value
+ // 6.
+ if (innerResponse.status === 206) {
+ throw webidl.errors.exception({
+ header: prefix,
+ message: 'Got 206 status'
+ })
+ }
- // 2. If data does not start with "bytes", then return failure.
- if (!data.startsWith('bytes')) {
- return 'failure'
- }
+ // 7.
+ if (innerResponse.headersList.contains('vary')) {
+ // 7.1.
+ const fieldValues = getFieldValues(innerResponse.headersList.get('vary'))
- // 3. Let position be a position variable for data, initially pointing at the 5th code point of data.
- const position = { position: 5 }
+ // 7.2.
+ for (const fieldValue of fieldValues) {
+ // 7.2.1
+ if (fieldValue === '*') {
+ throw webidl.errors.exception({
+ header: prefix,
+ message: 'Got * vary field value'
+ })
+ }
+ }
+ }
- // 4. If allowWhitespace is true, collect a sequence of code points that are HTTP tab or space,
- // from data given position.
- if (allowWhitespace) {
- collectASequenceOfCodePoints(
- (char) => char === '\t' || char === ' ',
- data,
- position
- )
- }
+ // 8.
+ if (innerResponse.body && (isDisturbed(innerResponse.body.stream) || innerResponse.body.stream.locked)) {
+ throw webidl.errors.exception({
+ header: prefix,
+ message: 'Response body is locked or disturbed'
+ })
+ }
- // 5. If the code point at position within data is not U+003D (=), then return failure.
- if (data.charCodeAt(position.position) !== 0x3D) {
- return 'failure'
- }
+ // 9.
+ const clonedResponse = cloneResponse(innerResponse)
- // 6. Advance position by 1.
- position.position++
+ // 10.
+ const bodyReadPromise = createDeferredPromise()
- // 7. If allowWhitespace is true, collect a sequence of code points that are HTTP tab or space, from
- // data given position.
- if (allowWhitespace) {
- collectASequenceOfCodePoints(
- (char) => char === '\t' || char === ' ',
- data,
- position
- )
- }
+ // 11.
+ if (innerResponse.body != null) {
+ // 11.1
+ const stream = innerResponse.body.stream
- // 8. Let rangeStart be the result of collecting a sequence of code points that are ASCII digits,
- // from data given position.
- const rangeStart = collectASequenceOfCodePoints(
- (char) => {
- const code = char.charCodeAt(0)
+ // 11.2
+ const reader = stream.getReader()
- return code >= 0x30 && code <= 0x39
- },
- data,
- position
- )
+ // 11.3
+ readAllBytes(reader).then(bodyReadPromise.resolve, bodyReadPromise.reject)
+ } else {
+ bodyReadPromise.resolve(undefined)
+ }
- // 9. Let rangeStartValue be rangeStart, interpreted as decimal number, if rangeStart is not the
- // empty string; otherwise null.
- const rangeStartValue = rangeStart.length ? Number(rangeStart) : null
+ // 12.
+ /** @type {CacheBatchOperation[]} */
+ const operations = []
- // 10. If allowWhitespace is true, collect a sequence of code points that are HTTP tab or space,
- // from data given position.
- if (allowWhitespace) {
- collectASequenceOfCodePoints(
- (char) => char === '\t' || char === ' ',
- data,
- position
- )
- }
+ // 13.
+ /** @type {CacheBatchOperation} */
+ const operation = {
+ type: 'put', // 14.
+ request: innerRequest, // 15.
+ response: clonedResponse // 16.
+ }
- // 11. If the code point at position within data is not U+002D (-), then return failure.
- if (data.charCodeAt(position.position) !== 0x2D) {
- return 'failure'
- }
+ // 17.
+ operations.push(operation)
- // 12. Advance position by 1.
- position.position++
+ // 19.
+ const bytes = await bodyReadPromise.promise
- // 13. If allowWhitespace is true, collect a sequence of code points that are HTTP tab
- // or space, from data given position.
- // Note from Khafra: its the same step as in #8 again lol
- if (allowWhitespace) {
- collectASequenceOfCodePoints(
- (char) => char === '\t' || char === ' ',
- data,
- position
- )
- }
+ if (clonedResponse.body != null) {
+ clonedResponse.body.source = bytes
+ }
- // 14. Let rangeEnd be the result of collecting a sequence of code points that are
- // ASCII digits, from data given position.
- // Note from Khafra: you wouldn't guess it, but this is also the same step as #8
- const rangeEnd = collectASequenceOfCodePoints(
- (char) => {
- const code = char.charCodeAt(0)
+ // 19.1
+ const cacheJobPromise = createDeferredPromise()
- return code >= 0x30 && code <= 0x39
- },
- data,
- position
- )
+ // 19.2.1
+ let errorData = null
- // 15. Let rangeEndValue be rangeEnd, interpreted as decimal number, if rangeEnd
- // is not the empty string; otherwise null.
- // Note from Khafra: THE SAME STEP, AGAIN!!!
- // Note: why interpret as a decimal if we only collect ascii digits?
- const rangeEndValue = rangeEnd.length ? Number(rangeEnd) : null
+ // 19.2.2
+ try {
+ this.#batchCacheOperations(operations)
+ } catch (e) {
+ errorData = e
+ }
- // 16. If position is not past the end of data, then return failure.
- if (position.position < data.length) {
- return 'failure'
- }
+ // 19.2.3
+ queueMicrotask(() => {
+ // 19.2.3.1
+ if (errorData === null) {
+ cacheJobPromise.resolve()
+ } else { // 19.2.3.2
+ cacheJobPromise.reject(errorData)
+ }
+ })
- // 17. If rangeEndValue and rangeStartValue are null, then return failure.
- if (rangeEndValue === null && rangeStartValue === null) {
- return 'failure'
+ return cacheJobPromise.promise
}
- // 18. If rangeStartValue and rangeEndValue are numbers, and rangeStartValue is
- // greater than rangeEndValue, then return failure.
- // Note: ... when can they not be numbers?
- if (rangeStartValue > rangeEndValue) {
- return 'failure'
- }
+ async delete (request, options = {}) {
+ webidl.brandCheck(this, Cache)
- // 19. Return (rangeStartValue, rangeEndValue).
- return { rangeStartValue, rangeEndValue }
-}
+ const prefix = 'Cache.delete'
+ webidl.argumentLengthCheck(arguments, 1, prefix)
-/**
- * @see https://fetch.spec.whatwg.org/#build-a-content-range
- * @param {number} rangeStart
- * @param {number} rangeEnd
- * @param {number} fullLength
- */
-function buildContentRange (rangeStart, rangeEnd, fullLength) {
- // 1. Let contentRange be `bytes `.
- let contentRange = 'bytes '
+ request = webidl.converters.RequestInfo(request, prefix, 'request')
+ options = webidl.converters.CacheQueryOptions(options, prefix, 'options')
- // 2. Append rangeStart, serialized and isomorphic encoded, to contentRange.
- contentRange += isomorphicEncode(`${rangeStart}`)
+ /**
+ * @type {Request}
+ */
+ let r = null
- // 3. Append 0x2D (-) to contentRange.
- contentRange += '-'
+ if (request instanceof Request) {
+ r = request[kState]
- // 4. Append rangeEnd, serialized and isomorphic encoded to contentRange.
- contentRange += isomorphicEncode(`${rangeEnd}`)
+ if (r.method !== 'GET' && !options.ignoreMethod) {
+ return false
+ }
+ } else {
+ assert(typeof request === 'string')
- // 5. Append 0x2F (/) to contentRange.
- contentRange += '/'
+ r = new Request(request)[kState]
+ }
- // 6. Append fullLength, serialized and isomorphic encoded to contentRange.
- contentRange += isomorphicEncode(`${fullLength}`)
+ /** @type {CacheBatchOperation[]} */
+ const operations = []
- // 7. Return contentRange.
- return contentRange
-}
+ /** @type {CacheBatchOperation} */
+ const operation = {
+ type: 'delete',
+ request: r,
+ options
+ }
-// A Stream, which pipes the response to zlib.createInflate() or
-// zlib.createInflateRaw() depending on the first byte of the Buffer.
-// If the lower byte of the first byte is 0x08, then the stream is
-// interpreted as a zlib stream, otherwise it's interpreted as a
-// raw deflate stream.
-class InflateStream extends Transform {
- #zlibOptions
+ operations.push(operation)
- /** @param {zlib.ZlibOptions} [zlibOptions] */
- constructor (zlibOptions) {
- super()
- this.#zlibOptions = zlibOptions
- }
+ const cacheJobPromise = createDeferredPromise()
- _transform (chunk, encoding, callback) {
- if (!this._inflateStream) {
- if (chunk.length === 0) {
- callback()
- return
- }
- this._inflateStream = (chunk[0] & 0x0F) === 0x08
- ? zlib.createInflate(this.#zlibOptions)
- : zlib.createInflateRaw(this.#zlibOptions)
+ let errorData = null
+ let requestResponses
- this._inflateStream.on('data', this.push.bind(this))
- this._inflateStream.on('end', () => this.push(null))
- this._inflateStream.on('error', (err) => this.destroy(err))
+ try {
+ requestResponses = this.#batchCacheOperations(operations)
+ } catch (e) {
+ errorData = e
}
- this._inflateStream.write(chunk, encoding, callback)
- }
+ queueMicrotask(() => {
+ if (errorData === null) {
+ cacheJobPromise.resolve(!!requestResponses?.length)
+ } else {
+ cacheJobPromise.reject(errorData)
+ }
+ })
- _final (callback) {
- if (this._inflateStream) {
- this._inflateStream.end()
- this._inflateStream = null
- }
- callback()
+ return cacheJobPromise.promise
}
-}
-
-/**
- * @param {zlib.ZlibOptions} [zlibOptions]
- * @returns {InflateStream}
- */
-function createInflate (zlibOptions) {
- return new InflateStream(zlibOptions)
-}
-
-/**
- * @see https://fetch.spec.whatwg.org/#concept-header-extract-mime-type
- * @param {import('./headers').HeadersList} headers
- */
-function extractMimeType (headers) {
- // 1. Let charset be null.
- let charset = null
- // 2. Let essence be null.
- let essence = null
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#dom-cache-keys
+ * @param {any} request
+ * @param {import('../../types/cache').CacheQueryOptions} options
+ * @returns {Promise}
+ */
+ async keys (request = undefined, options = {}) {
+ webidl.brandCheck(this, Cache)
- // 3. Let mimeType be null.
- let mimeType = null
+ const prefix = 'Cache.keys'
- // 4. Let values be the result of getting, decoding, and splitting `Content-Type` from headers.
- const values = getDecodeSplit('content-type', headers)
+ if (request !== undefined) request = webidl.converters.RequestInfo(request, prefix, 'request')
+ options = webidl.converters.CacheQueryOptions(options, prefix, 'options')
- // 5. If values is null, then return failure.
- if (values === null) {
- return 'failure'
- }
+ // 1.
+ let r = null
- // 6. For each value of values:
- for (const value of values) {
- // 6.1. Let temporaryMimeType be the result of parsing value.
- const temporaryMimeType = parseMIMEType(value)
+ // 2.
+ if (request !== undefined) {
+ // 2.1
+ if (request instanceof Request) {
+ // 2.1.1
+ r = request[kState]
- // 6.2. If temporaryMimeType is failure or its essence is "*/*", then continue.
- if (temporaryMimeType === 'failure' || temporaryMimeType.essence === '*/*') {
- continue
+ // 2.1.2
+ if (r.method !== 'GET' && !options.ignoreMethod) {
+ return []
+ }
+ } else if (typeof request === 'string') { // 2.2
+ r = new Request(request)[kState]
+ }
}
- // 6.3. Set mimeType to temporaryMimeType.
- mimeType = temporaryMimeType
+ // 4.
+ const promise = createDeferredPromise()
- // 6.4. If mimeType’s essence is not essence, then:
- if (mimeType.essence !== essence) {
- // 6.4.1. Set charset to null.
- charset = null
+ // 5.
+ // 5.1
+ const requests = []
- // 6.4.2. If mimeType’s parameters["charset"] exists, then set charset to
- // mimeType’s parameters["charset"].
- if (mimeType.parameters.has('charset')) {
- charset = mimeType.parameters.get('charset')
+ // 5.2
+ if (request === undefined) {
+ // 5.2.1
+ for (const requestResponse of this.#relevantRequestResponseList) {
+ // 5.2.1.1
+ requests.push(requestResponse[0])
}
+ } else { // 5.3
+ // 5.3.1
+ const requestResponses = this.#queryCache(r, options)
- // 6.4.3. Set essence to mimeType’s essence.
- essence = mimeType.essence
- } else if (!mimeType.parameters.has('charset') && charset !== null) {
- // 6.5. Otherwise, if mimeType’s parameters["charset"] does not exist, and
- // charset is non-null, set mimeType’s parameters["charset"] to charset.
- mimeType.parameters.set('charset', charset)
+ // 5.3.2
+ for (const requestResponse of requestResponses) {
+ // 5.3.2.1
+ requests.push(requestResponse[0])
+ }
}
- }
- // 7. If mimeType is null, then return failure.
- if (mimeType == null) {
- return 'failure'
- }
+ // 5.4
+ queueMicrotask(() => {
+ // 5.4.1
+ const requestList = []
- // 8. Return mimeType.
- return mimeType
-}
+ // 5.4.2
+ for (const request of requests) {
+ const requestObject = fromInnerRequest(
+ request,
+ new AbortController().signal,
+ 'immutable'
+ )
+ // 5.4.2.1
+ requestList.push(requestObject)
+ }
-/**
- * @see https://fetch.spec.whatwg.org/#header-value-get-decode-and-split
- * @param {string|null} value
- */
-function gettingDecodingSplitting (value) {
- // 1. Let input be the result of isomorphic decoding value.
- const input = value
+ // 5.4.3
+ promise.resolve(Object.freeze(requestList))
+ })
- // 2. Let position be a position variable for input, initially pointing at the start of input.
- const position = { position: 0 }
+ return promise.promise
+ }
- // 3. Let values be a list of strings, initially empty.
- const values = []
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#batch-cache-operations-algorithm
+ * @param {CacheBatchOperation[]} operations
+ * @returns {requestResponseList}
+ */
+ #batchCacheOperations (operations) {
+ // 1.
+ const cache = this.#relevantRequestResponseList
- // 4. Let temporaryValue be the empty string.
- let temporaryValue = ''
+ // 2.
+ const backupCache = [...cache]
- // 5. While position is not past the end of input:
- while (position.position < input.length) {
- // 5.1. Append the result of collecting a sequence of code points that are not U+0022 (")
- // or U+002C (,) from input, given position, to temporaryValue.
- temporaryValue += collectASequenceOfCodePoints(
- (char) => char !== '"' && char !== ',',
- input,
- position
- )
+ // 3.
+ const addedItems = []
- // 5.2. If position is not past the end of input, then:
- if (position.position < input.length) {
- // 5.2.1. If the code point at position within input is U+0022 ("), then:
- if (input.charCodeAt(position.position) === 0x22) {
- // 5.2.1.1. Append the result of collecting an HTTP quoted string from input, given position, to temporaryValue.
- temporaryValue += collectAnHTTPQuotedString(
- input,
- position
- )
+ // 4.1
+ const resultList = []
- // 5.2.1.2. If position is not past the end of input, then continue.
- if (position.position < input.length) {
- continue
+ try {
+ // 4.2
+ for (const operation of operations) {
+ // 4.2.1
+ if (operation.type !== 'delete' && operation.type !== 'put') {
+ throw webidl.errors.exception({
+ header: 'Cache.#batchCacheOperations',
+ message: 'operation type does not match "delete" or "put"'
+ })
}
- } else {
- // 5.2.2. Otherwise:
-
- // 5.2.2.1. Assert: the code point at position within input is U+002C (,).
- assert(input.charCodeAt(position.position) === 0x2C)
- // 5.2.2.2. Advance position by 1.
- position.position++
- }
- }
+ // 4.2.2
+ if (operation.type === 'delete' && operation.response != null) {
+ throw webidl.errors.exception({
+ header: 'Cache.#batchCacheOperations',
+ message: 'delete operation should not have an associated response'
+ })
+ }
- // 5.3. Remove all HTTP tab or space from the start and end of temporaryValue.
- temporaryValue = removeChars(temporaryValue, true, true, (char) => char === 0x9 || char === 0x20)
+ // 4.2.3
+ if (this.#queryCache(operation.request, operation.options, addedItems).length) {
+ throw new DOMException('???', 'InvalidStateError')
+ }
- // 5.4. Append temporaryValue to values.
- values.push(temporaryValue)
+ // 4.2.4
+ let requestResponses
- // 5.6. Set temporaryValue to the empty string.
- temporaryValue = ''
- }
+ // 4.2.5
+ if (operation.type === 'delete') {
+ // 4.2.5.1
+ requestResponses = this.#queryCache(operation.request, operation.options)
- // 6. Return values.
- return values
-}
+ // TODO: the spec is wrong, this is needed to pass WPTs
+ if (requestResponses.length === 0) {
+ return []
+ }
-/**
- * @see https://fetch.spec.whatwg.org/#concept-header-list-get-decode-split
- * @param {string} name lowercase header name
- * @param {import('./headers').HeadersList} list
- */
-function getDecodeSplit (name, list) {
- // 1. Let value be the result of getting name from list.
- const value = list.get(name, true)
+ // 4.2.5.2
+ for (const requestResponse of requestResponses) {
+ const idx = cache.indexOf(requestResponse)
+ assert(idx !== -1)
- // 2. If value is null, then return null.
- if (value === null) {
- return null
- }
+ // 4.2.5.2.1
+ cache.splice(idx, 1)
+ }
+ } else if (operation.type === 'put') { // 4.2.6
+ // 4.2.6.1
+ if (operation.response == null) {
+ throw webidl.errors.exception({
+ header: 'Cache.#batchCacheOperations',
+ message: 'put operation should have an associated response'
+ })
+ }
- // 3. Return the result of getting, decoding, and splitting value.
- return gettingDecodingSplitting(value)
-}
+ // 4.2.6.2
+ const r = operation.request
-const textDecoder = new TextDecoder()
+ // 4.2.6.3
+ if (!urlIsHttpHttpsScheme(r.url)) {
+ throw webidl.errors.exception({
+ header: 'Cache.#batchCacheOperations',
+ message: 'expected http or https scheme'
+ })
+ }
-/**
- * @see https://encoding.spec.whatwg.org/#utf-8-decode
- * @param {Buffer} buffer
- */
-function utf8DecodeBytes (buffer) {
- if (buffer.length === 0) {
- return ''
- }
+ // 4.2.6.4
+ if (r.method !== 'GET') {
+ throw webidl.errors.exception({
+ header: 'Cache.#batchCacheOperations',
+ message: 'not get method'
+ })
+ }
- // 1. Let buffer be the result of peeking three bytes from
- // ioQueue, converted to a byte sequence.
+ // 4.2.6.5
+ if (operation.options != null) {
+ throw webidl.errors.exception({
+ header: 'Cache.#batchCacheOperations',
+ message: 'options must not be defined'
+ })
+ }
- // 2. If buffer is 0xEF 0xBB 0xBF, then read three
- // bytes from ioQueue. (Do nothing with those bytes.)
- if (buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) {
- buffer = buffer.subarray(3)
- }
+ // 4.2.6.6
+ requestResponses = this.#queryCache(operation.request)
- // 3. Process a queue with an instance of UTF-8’s
- // decoder, ioQueue, output, and "replacement".
- const output = textDecoder.decode(buffer)
+ // 4.2.6.7
+ for (const requestResponse of requestResponses) {
+ const idx = cache.indexOf(requestResponse)
+ assert(idx !== -1)
- // 4. Return output.
- return output
-}
+ // 4.2.6.7.1
+ cache.splice(idx, 1)
+ }
-class EnvironmentSettingsObjectBase {
- get baseUrl () {
- return getGlobalOrigin()
- }
+ // 4.2.6.8
+ cache.push([operation.request, operation.response])
- get origin () {
- return this.baseUrl?.origin
- }
+ // 4.2.6.10
+ addedItems.push([operation.request, operation.response])
+ }
- policyContainer = makePolicyContainer()
-}
+ // 4.2.7
+ resultList.push([operation.request, operation.response])
+ }
-class EnvironmentSettingsObject {
- settingsObject = new EnvironmentSettingsObjectBase()
-}
+ // 4.3
+ return resultList
+ } catch (e) { // 5.
+ // 5.1
+ this.#relevantRequestResponseList.length = 0
-const environmentSettingsObject = new EnvironmentSettingsObject()
+ // 5.2
+ this.#relevantRequestResponseList = backupCache
-module.exports = {
- isAborted,
- isCancelled,
- isValidEncodedURL,
- createDeferredPromise,
- ReadableStreamFrom,
- tryUpgradeRequestToAPotentiallyTrustworthyURL,
- clampAndCoarsenConnectionTimingInfo,
- coarsenedSharedCurrentTime,
- determineRequestsReferrer,
- makePolicyContainer,
- clonePolicyContainer,
- appendFetchMetadata,
- appendRequestOriginHeader,
- TAOCheck,
- corsCheck,
- crossOriginResourcePolicyCheck,
- createOpaqueTimingInfo,
- setRequestReferrerPolicyOnRedirect,
- isValidHTTPToken,
- requestBadPort,
- requestCurrentURL,
- responseURL,
- responseLocationURL,
- isBlobLike,
- isURLPotentiallyTrustworthy,
- isValidReasonPhrase,
- sameOrigin,
- normalizeMethod,
- serializeJavascriptValueToJSONString,
- iteratorMixin,
- createIterator,
- isValidHeaderName,
- isValidHeaderValue,
- isErrorLike,
- fullyReadBody,
- bytesMatch,
- isReadableStreamLike,
- readableStreamClose,
- isomorphicEncode,
- urlIsLocal,
- urlHasHttpsScheme,
- urlIsHttpHttpsScheme,
- readAllBytes,
- simpleRangeHeaderValue,
- buildContentRange,
- parseMetadata,
- createInflate,
- extractMimeType,
- getDecodeSplit,
- utf8DecodeBytes,
- environmentSettingsObject
-}
+ // 5.3
+ throw e
+ }
+ }
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#query-cache
+ * @param {any} requestQuery
+ * @param {import('../../types/cache').CacheQueryOptions} options
+ * @param {requestResponseList} targetStorage
+ * @returns {requestResponseList}
+ */
+ #queryCache (requestQuery, options, targetStorage) {
+ /** @type {requestResponseList} */
+ const resultList = []
-/***/ }),
+ const storage = targetStorage ?? this.#relevantRequestResponseList
-/***/ 220:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ for (const requestResponse of storage) {
+ const [cachedRequest, cachedResponse] = requestResponse
+ if (this.#requestMatchesCachedItem(requestQuery, cachedRequest, cachedResponse, options)) {
+ resultList.push(requestResponse)
+ }
+ }
+ return resultList
+ }
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#request-matches-cached-item-algorithm
+ * @param {any} requestQuery
+ * @param {any} request
+ * @param {any | null} response
+ * @param {import('../../types/cache').CacheQueryOptions | undefined} options
+ * @returns {boolean}
+ */
+ #requestMatchesCachedItem (requestQuery, request, response = null, options) {
+ // if (options?.ignoreMethod === false && request.method === 'GET') {
+ // return false
+ // }
-const { types, inspect } = __nccwpck_require__(7975)
-const { markAsUncloneable } = __nccwpck_require__(5919)
-const { toUSVString } = __nccwpck_require__(7375)
+ const queryURL = new URL(requestQuery.url)
-/** @type {import('../../../types/webidl').Webidl} */
-const webidl = {}
-webidl.converters = {}
-webidl.util = {}
-webidl.errors = {}
+ const cachedURL = new URL(request.url)
-webidl.errors.exception = function (message) {
- return new TypeError(`${message.header}: ${message.message}`)
-}
+ if (options?.ignoreSearch) {
+ cachedURL.search = ''
-webidl.errors.conversionFailed = function (context) {
- const plural = context.types.length === 1 ? '' : ' one of'
- const message =
- `${context.argument} could not be converted to` +
- `${plural}: ${context.types.join(', ')}.`
+ queryURL.search = ''
+ }
- return webidl.errors.exception({
- header: context.prefix,
- message
- })
-}
+ if (!urlEquals(queryURL, cachedURL, true)) {
+ return false
+ }
-webidl.errors.invalidArgument = function (context) {
- return webidl.errors.exception({
- header: context.prefix,
- message: `"${context.value}" is an invalid ${context.type}.`
- })
-}
-
-// https://webidl.spec.whatwg.org/#implements
-webidl.brandCheck = function (V, I, opts) {
- if (opts?.strict !== false) {
- if (!(V instanceof I)) {
- const err = new TypeError('Illegal invocation')
- err.code = 'ERR_INVALID_THIS' // node compat.
- throw err
- }
- } else {
- if (V?.[Symbol.toStringTag] !== I.prototype[Symbol.toStringTag]) {
- const err = new TypeError('Illegal invocation')
- err.code = 'ERR_INVALID_THIS' // node compat.
- throw err
+ if (
+ response == null ||
+ options?.ignoreVary ||
+ !response.headersList.contains('vary')
+ ) {
+ return true
}
- }
-}
-
-webidl.argumentLengthCheck = function ({ length }, min, ctx) {
- if (length < min) {
- throw webidl.errors.exception({
- message: `${min} argument${min !== 1 ? 's' : ''} required, ` +
- `but${length ? ' only' : ''} ${length} found.`,
- header: ctx
- })
- }
-}
-webidl.illegalConstructor = function () {
- throw webidl.errors.exception({
- header: 'TypeError',
- message: 'Illegal constructor'
- })
-}
+ const fieldValues = getFieldValues(response.headersList.get('vary'))
-// https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values
-webidl.util.Type = function (V) {
- switch (typeof V) {
- case 'undefined': return 'Undefined'
- case 'boolean': return 'Boolean'
- case 'string': return 'String'
- case 'symbol': return 'Symbol'
- case 'number': return 'Number'
- case 'bigint': return 'BigInt'
- case 'function':
- case 'object': {
- if (V === null) {
- return 'Null'
+ for (const fieldValue of fieldValues) {
+ if (fieldValue === '*') {
+ return false
}
- return 'Object'
- }
- }
-}
-
-webidl.util.markAsUncloneable = markAsUncloneable || (() => {})
-// https://webidl.spec.whatwg.org/#abstract-opdef-converttoint
-webidl.util.ConvertToInt = function (V, bitLength, signedness, opts) {
- let upperBound
- let lowerBound
-
- // 1. If bitLength is 64, then:
- if (bitLength === 64) {
- // 1. Let upperBound be 2^53 − 1.
- upperBound = Math.pow(2, 53) - 1
+ const requestValue = request.headersList.get(fieldValue)
+ const queryValue = requestQuery.headersList.get(fieldValue)
- // 2. If signedness is "unsigned", then let lowerBound be 0.
- if (signedness === 'unsigned') {
- lowerBound = 0
- } else {
- // 3. Otherwise let lowerBound be −2^53 + 1.
- lowerBound = Math.pow(-2, 53) + 1
+ // If one has the header and the other doesn't, or one has
+ // a different value than the other, return false
+ if (requestValue !== queryValue) {
+ return false
+ }
}
- } else if (signedness === 'unsigned') {
- // 2. Otherwise, if signedness is "unsigned", then:
- // 1. Let lowerBound be 0.
- lowerBound = 0
+ return true
+ }
- // 2. Let upperBound be 2^bitLength − 1.
- upperBound = Math.pow(2, bitLength) - 1
- } else {
- // 3. Otherwise:
+ #internalMatchAll (request, options, maxResponses = Infinity) {
+ // 1.
+ let r = null
- // 1. Let lowerBound be -2^bitLength − 1.
- lowerBound = Math.pow(-2, bitLength) - 1
+ // 2.
+ if (request !== undefined) {
+ if (request instanceof Request) {
+ // 2.1.1
+ r = request[kState]
- // 2. Let upperBound be 2^bitLength − 1 − 1.
- upperBound = Math.pow(2, bitLength - 1) - 1
- }
+ // 2.1.2
+ if (r.method !== 'GET' && !options.ignoreMethod) {
+ return []
+ }
+ } else if (typeof request === 'string') {
+ // 2.2.1
+ r = new Request(request)[kState]
+ }
+ }
- // 4. Let x be ? ToNumber(V).
- let x = Number(V)
+ // 5.
+ // 5.1
+ const responses = []
- // 5. If x is −0, then set x to +0.
- if (x === 0) {
- x = 0
- }
+ // 5.2
+ if (request === undefined) {
+ // 5.2.1
+ for (const requestResponse of this.#relevantRequestResponseList) {
+ responses.push(requestResponse[1])
+ }
+ } else { // 5.3
+ // 5.3.1
+ const requestResponses = this.#queryCache(r, options)
- // 6. If the conversion is to an IDL type associated
- // with the [EnforceRange] extended attribute, then:
- if (opts?.enforceRange === true) {
- // 1. If x is NaN, +∞, or −∞, then throw a TypeError.
- if (
- Number.isNaN(x) ||
- x === Number.POSITIVE_INFINITY ||
- x === Number.NEGATIVE_INFINITY
- ) {
- throw webidl.errors.exception({
- header: 'Integer conversion',
- message: `Could not convert ${webidl.util.Stringify(V)} to an integer.`
- })
+ // 5.3.2
+ for (const requestResponse of requestResponses) {
+ responses.push(requestResponse[1])
+ }
}
- // 2. Set x to IntegerPart(x).
- x = webidl.util.IntegerPart(x)
+ // 5.4
+ // We don't implement CORs so we don't need to loop over the responses, yay!
- // 3. If x < lowerBound or x > upperBound, then
- // throw a TypeError.
- if (x < lowerBound || x > upperBound) {
- throw webidl.errors.exception({
- header: 'Integer conversion',
- message: `Value must be between ${lowerBound}-${upperBound}, got ${x}.`
- })
- }
+ // 5.5.1
+ const responseList = []
- // 4. Return x.
- return x
- }
+ // 5.5.2
+ for (const response of responses) {
+ // 5.5.2.1
+ const responseObject = fromInnerResponse(response, 'immutable')
- // 7. If x is not NaN and the conversion is to an IDL
- // type associated with the [Clamp] extended
- // attribute, then:
- if (!Number.isNaN(x) && opts?.clamp === true) {
- // 1. Set x to min(max(x, lowerBound), upperBound).
- x = Math.min(Math.max(x, lowerBound), upperBound)
+ responseList.push(responseObject.clone())
- // 2. Round x to the nearest integer, choosing the
- // even integer if it lies halfway between two,
- // and choosing +0 rather than −0.
- if (Math.floor(x) % 2 === 0) {
- x = Math.floor(x)
- } else {
- x = Math.ceil(x)
+ if (responseList.length >= maxResponses) {
+ break
+ }
}
- // 3. Return x.
- return x
+ // 6.
+ return Object.freeze(responseList)
}
+}
- // 8. If x is NaN, +0, +∞, or −∞, then return +0.
- if (
- Number.isNaN(x) ||
- (x === 0 && Object.is(0, x)) ||
- x === Number.POSITIVE_INFINITY ||
- x === Number.NEGATIVE_INFINITY
- ) {
- return 0
- }
+Object.defineProperties(Cache.prototype, {
+ [Symbol.toStringTag]: {
+ value: 'Cache',
+ configurable: true
+ },
+ match: kEnumerableProperty,
+ matchAll: kEnumerableProperty,
+ add: kEnumerableProperty,
+ addAll: kEnumerableProperty,
+ put: kEnumerableProperty,
+ delete: kEnumerableProperty,
+ keys: kEnumerableProperty
+})
- // 9. Set x to IntegerPart(x).
- x = webidl.util.IntegerPart(x)
+const cacheQueryOptionConverters = [
+ {
+ key: 'ignoreSearch',
+ converter: webidl.converters.boolean,
+ defaultValue: () => false
+ },
+ {
+ key: 'ignoreMethod',
+ converter: webidl.converters.boolean,
+ defaultValue: () => false
+ },
+ {
+ key: 'ignoreVary',
+ converter: webidl.converters.boolean,
+ defaultValue: () => false
+ }
+]
- // 10. Set x to x modulo 2^bitLength.
- x = x % Math.pow(2, bitLength)
+webidl.converters.CacheQueryOptions = webidl.dictionaryConverter(cacheQueryOptionConverters)
- // 11. If signedness is "signed" and x ≥ 2^bitLength − 1,
- // then return x − 2^bitLength.
- if (signedness === 'signed' && x >= Math.pow(2, bitLength) - 1) {
- return x - Math.pow(2, bitLength)
+webidl.converters.MultiCacheQueryOptions = webidl.dictionaryConverter([
+ ...cacheQueryOptionConverters,
+ {
+ key: 'cacheName',
+ converter: webidl.converters.DOMString
}
+])
- // 12. Otherwise, return x.
- return x
-}
-
-// https://webidl.spec.whatwg.org/#abstract-opdef-integerpart
-webidl.util.IntegerPart = function (n) {
- // 1. Let r be floor(abs(n)).
- const r = Math.floor(Math.abs(n))
+webidl.converters.Response = webidl.interfaceConverter(Response)
- // 2. If n < 0, then return -1 × r.
- if (n < 0) {
- return -1 * r
- }
+webidl.converters['sequence'] = webidl.sequenceConverter(
+ webidl.converters.RequestInfo
+)
- // 3. Otherwise, return r.
- return r
+module.exports = {
+ Cache
}
-webidl.util.Stringify = function (V) {
- const type = webidl.util.Type(V)
- switch (type) {
- case 'Symbol':
- return `Symbol(${V.description})`
- case 'Object':
- return inspect(V)
- case 'String':
- return `"${V}"`
- default:
- return `${V}`
- }
-}
+/***/ }),
-// https://webidl.spec.whatwg.org/#es-sequence
-webidl.sequenceConverter = function (converter) {
- return (V, prefix, argument, Iterable) => {
- // 1. If Type(V) is not Object, throw a TypeError.
- if (webidl.util.Type(V) !== 'Object') {
- throw webidl.errors.exception({
- header: prefix,
- message: `${argument} (${webidl.util.Stringify(V)}) is not iterable.`
- })
- }
+/***/ 3245:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 2. Let method be ? GetMethod(V, @@iterator).
- /** @type {Generator} */
- const method = typeof Iterable === 'function' ? Iterable() : V?.[Symbol.iterator]?.()
- const seq = []
- let index = 0
- // 3. If method is undefined, throw a TypeError.
- if (
- method === undefined ||
- typeof method.next !== 'function'
- ) {
- throw webidl.errors.exception({
- header: prefix,
- message: `${argument} is not iterable.`
- })
- }
- // https://webidl.spec.whatwg.org/#create-sequence-from-iterable
- while (true) {
- const { done, value } = method.next()
+const { kConstruct } = __nccwpck_require__(109)
+const { Cache } = __nccwpck_require__(9634)
+const { webidl } = __nccwpck_require__(5893)
+const { kEnumerableProperty } = __nccwpck_require__(3440)
- if (done) {
- break
- }
+class CacheStorage {
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-name-to-cache-map
+ * @type {Map {
- // 1. If Type(O) is not Object, throw a TypeError.
- if (webidl.util.Type(O) !== 'Object') {
- throw webidl.errors.exception({
- header: prefix,
- message: `${argument} ("${webidl.util.Type(O)}") is not an Object.`
- })
- }
+ async match (request, options = {}) {
+ webidl.brandCheck(this, CacheStorage)
+ webidl.argumentLengthCheck(arguments, 1, 'CacheStorage.match')
- // 2. Let result be a new empty instance of record.
- const result = {}
+ request = webidl.converters.RequestInfo(request)
+ options = webidl.converters.MultiCacheQueryOptions(options)
- if (!types.isProxy(O)) {
- // 1. Let desc be ? O.[[GetOwnProperty]](key).
- const keys = [...Object.getOwnPropertyNames(O), ...Object.getOwnPropertySymbols(O)]
+ // 1.
+ if (options.cacheName != null) {
+ // 1.1.1.1
+ if (this.#caches.has(options.cacheName)) {
+ // 1.1.1.1.1
+ const cacheList = this.#caches.get(options.cacheName)
+ const cache = new Cache(kConstruct, cacheList)
- for (const key of keys) {
- // 1. Let typedKey be key converted to an IDL value of type K.
- const typedKey = keyConverter(key, prefix, argument)
+ return await cache.match(request, options)
+ }
+ } else { // 2.
+ // 2.2
+ for (const cacheList of this.#caches.values()) {
+ const cache = new Cache(kConstruct, cacheList)
- // 2. Let value be ? Get(O, key).
- // 3. Let typedValue be value converted to an IDL value of type V.
- const typedValue = valueConverter(O[key], prefix, argument)
+ // 2.2.1.2
+ const response = await cache.match(request, options)
- // 4. Set result[typedKey] to typedValue.
- result[typedKey] = typedValue
+ if (response !== undefined) {
+ return response
+ }
}
-
- // 5. Return result.
- return result
}
+ }
- // 3. Let keys be ? O.[[OwnPropertyKeys]]().
- const keys = Reflect.ownKeys(O)
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#cache-storage-has
+ * @param {string} cacheName
+ * @returns {Promise}
+ */
+ async has (cacheName) {
+ webidl.brandCheck(this, CacheStorage)
- // 4. For each key of keys.
- for (const key of keys) {
- // 1. Let desc be ? O.[[GetOwnProperty]](key).
- const desc = Reflect.getOwnPropertyDescriptor(O, key)
+ const prefix = 'CacheStorage.has'
+ webidl.argumentLengthCheck(arguments, 1, prefix)
- // 2. If desc is not undefined and desc.[[Enumerable]] is true:
- if (desc?.enumerable) {
- // 1. Let typedKey be key converted to an IDL value of type K.
- const typedKey = keyConverter(key, prefix, argument)
+ cacheName = webidl.converters.DOMString(cacheName, prefix, 'cacheName')
- // 2. Let value be ? Get(O, key).
- // 3. Let typedValue be value converted to an IDL value of type V.
- const typedValue = valueConverter(O[key], prefix, argument)
+ // 2.1.1
+ // 2.2
+ return this.#caches.has(cacheName)
+ }
- // 4. Set result[typedKey] to typedValue.
- result[typedKey] = typedValue
- }
- }
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#dom-cachestorage-open
+ * @param {string} cacheName
+ * @returns {Promise}
+ */
+ async open (cacheName) {
+ webidl.brandCheck(this, CacheStorage)
- // 5. Return result.
- return result
- }
-}
+ const prefix = 'CacheStorage.open'
+ webidl.argumentLengthCheck(arguments, 1, prefix)
-webidl.interfaceConverter = function (i) {
- return (V, prefix, argument, opts) => {
- if (opts?.strict !== false && !(V instanceof i)) {
- throw webidl.errors.exception({
- header: prefix,
- message: `Expected ${argument} ("${webidl.util.Stringify(V)}") to be an instance of ${i.name}.`
- })
- }
+ cacheName = webidl.converters.DOMString(cacheName, prefix, 'cacheName')
- return V
- }
-}
+ // 2.1
+ if (this.#caches.has(cacheName)) {
+ // await caches.open('v1') !== await caches.open('v1')
-webidl.dictionaryConverter = function (converters) {
- return (dictionary, prefix, argument) => {
- const type = webidl.util.Type(dictionary)
- const dict = {}
+ // 2.1.1
+ const cache = this.#caches.get(cacheName)
- if (type === 'Null' || type === 'Undefined') {
- return dict
- } else if (type !== 'Object') {
- throw webidl.errors.exception({
- header: prefix,
- message: `Expected ${dictionary} to be one of: Null, Undefined, Object.`
- })
+ // 2.1.1.1
+ return new Cache(kConstruct, cache)
}
- for (const options of converters) {
- const { key, defaultValue, required, converter } = options
-
- if (required === true) {
- if (!Object.hasOwn(dictionary, key)) {
- throw webidl.errors.exception({
- header: prefix,
- message: `Missing required key "${key}".`
- })
- }
- }
+ // 2.2
+ const cache = []
- let value = dictionary[key]
- const hasDefault = Object.hasOwn(options, 'defaultValue')
+ // 2.3
+ this.#caches.set(cacheName, cache)
- // Only use defaultValue if value is undefined and
- // a defaultValue options was provided.
- if (hasDefault && value !== null) {
- value ??= defaultValue()
- }
+ // 2.4
+ return new Cache(kConstruct, cache)
+ }
- // A key can be optional and have no default value.
- // When this happens, do not perform a conversion,
- // and do not assign the key a value.
- if (required || hasDefault || value !== undefined) {
- value = converter(value, prefix, `${argument}.${key}`)
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#cache-storage-delete
+ * @param {string} cacheName
+ * @returns {Promise}
+ */
+ async delete (cacheName) {
+ webidl.brandCheck(this, CacheStorage)
- if (
- options.allowedValues &&
- !options.allowedValues.includes(value)
- ) {
- throw webidl.errors.exception({
- header: prefix,
- message: `${value} is not an accepted type. Expected one of ${options.allowedValues.join(', ')}.`
- })
- }
+ const prefix = 'CacheStorage.delete'
+ webidl.argumentLengthCheck(arguments, 1, prefix)
- dict[key] = value
- }
- }
+ cacheName = webidl.converters.DOMString(cacheName, prefix, 'cacheName')
- return dict
+ return this.#caches.delete(cacheName)
}
-}
-webidl.nullableConverter = function (converter) {
- return (V, prefix, argument) => {
- if (V === null) {
- return V
- }
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#cache-storage-keys
+ * @returns {Promise}
+ */
+ async keys () {
+ webidl.brandCheck(this, CacheStorage)
- return converter(V, prefix, argument)
+ // 2.1
+ const keys = this.#caches.keys()
+
+ // 2.2
+ return [...keys]
}
}
-// https://webidl.spec.whatwg.org/#es-DOMString
-webidl.converters.DOMString = function (V, prefix, argument, opts) {
- // 1. If V is null and the conversion is to an IDL type
- // associated with the [LegacyNullToEmptyString]
- // extended attribute, then return the DOMString value
- // that represents the empty string.
- if (V === null && opts?.legacyNullToEmptyString) {
- return ''
- }
+Object.defineProperties(CacheStorage.prototype, {
+ [Symbol.toStringTag]: {
+ value: 'CacheStorage',
+ configurable: true
+ },
+ match: kEnumerableProperty,
+ has: kEnumerableProperty,
+ open: kEnumerableProperty,
+ delete: kEnumerableProperty,
+ keys: kEnumerableProperty
+})
- // 2. Let x be ? ToString(V).
- if (typeof V === 'symbol') {
- throw webidl.errors.exception({
- header: prefix,
- message: `${argument} is a symbol, which cannot be converted to a DOMString.`
- })
- }
+module.exports = {
+ CacheStorage
+}
- // 3. Return the IDL DOMString value that represents the
- // same sequence of code units as the one the
- // ECMAScript String value x represents.
- return String(V)
+
+/***/ }),
+
+/***/ 109:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+module.exports = {
+ kConstruct: (__nccwpck_require__(6443).kConstruct)
}
-// https://webidl.spec.whatwg.org/#es-ByteString
-webidl.converters.ByteString = function (V, prefix, argument) {
- // 1. Let x be ? ToString(V).
- // Note: DOMString converter perform ? ToString(V)
- const x = webidl.converters.DOMString(V, prefix, argument)
- // 2. If the value of any element of x is greater than
- // 255, then throw a TypeError.
- for (let index = 0; index < x.length; index++) {
- if (x.charCodeAt(index) > 255) {
- throw new TypeError(
- 'Cannot convert argument to a ByteString because the character at ' +
- `index ${index} has a value of ${x.charCodeAt(index)} which is greater than 255.`
- )
- }
- }
+/***/ }),
- // 3. Return an IDL ByteString value whose length is the
- // length of x, and where the value of each element is
- // the value of the corresponding element of x.
- return x
+/***/ 6798:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const assert = __nccwpck_require__(4589)
+const { URLSerializer } = __nccwpck_require__(1900)
+const { isValidHeaderName } = __nccwpck_require__(3168)
+
+/**
+ * @see https://url.spec.whatwg.org/#concept-url-equals
+ * @param {URL} A
+ * @param {URL} B
+ * @param {boolean | undefined} excludeFragment
+ * @returns {boolean}
+ */
+function urlEquals (A, B, excludeFragment = false) {
+ const serializedA = URLSerializer(A, excludeFragment)
+
+ const serializedB = URLSerializer(B, excludeFragment)
+
+ return serializedA === serializedB
}
-// https://webidl.spec.whatwg.org/#es-USVString
-// TODO: rewrite this so we can control the errors thrown
-webidl.converters.USVString = toUSVString
+/**
+ * @see https://github.com/chromium/chromium/blob/694d20d134cb553d8d89e5500b9148012b1ba299/content/browser/cache_storage/cache_storage_cache.cc#L260-L262
+ * @param {string} header
+ */
+function getFieldValues (header) {
+ assert(header !== null)
-// https://webidl.spec.whatwg.org/#es-boolean
-webidl.converters.boolean = function (V) {
- // 1. Let x be the result of computing ToBoolean(V).
- const x = Boolean(V)
+ const values = []
- // 2. Return the IDL boolean value that is the one that represents
- // the same truth value as the ECMAScript Boolean value x.
- return x
+ for (let value of header.split(',')) {
+ value = value.trim()
+
+ if (isValidHeaderName(value)) {
+ values.push(value)
+ }
+ }
+
+ return values
}
-// https://webidl.spec.whatwg.org/#es-any
-webidl.converters.any = function (V) {
- return V
+module.exports = {
+ urlEquals,
+ getFieldValues
}
-// https://webidl.spec.whatwg.org/#es-long-long
-webidl.converters['long long'] = function (V, prefix, argument) {
- // 1. Let x be ? ConvertToInt(V, 64, "signed").
- const x = webidl.util.ConvertToInt(V, 64, 'signed', undefined, prefix, argument)
- // 2. Return the IDL long long value that represents
- // the same numeric value as x.
- return x
-}
+/***/ }),
-// https://webidl.spec.whatwg.org/#es-unsigned-long-long
-webidl.converters['unsigned long long'] = function (V, prefix, argument) {
- // 1. Let x be ? ConvertToInt(V, 64, "unsigned").
- const x = webidl.util.ConvertToInt(V, 64, 'unsigned', undefined, prefix, argument)
+/***/ 1276:
+/***/ ((module) => {
- // 2. Return the IDL unsigned long long value that
- // represents the same numeric value as x.
- return x
-}
-// https://webidl.spec.whatwg.org/#es-unsigned-long
-webidl.converters['unsigned long'] = function (V, prefix, argument) {
- // 1. Let x be ? ConvertToInt(V, 32, "unsigned").
- const x = webidl.util.ConvertToInt(V, 32, 'unsigned', undefined, prefix, argument)
- // 2. Return the IDL unsigned long value that
- // represents the same numeric value as x.
- return x
-}
+// https://wicg.github.io/cookie-store/#cookie-maximum-attribute-value-size
+const maxAttributeValueSize = 1024
-// https://webidl.spec.whatwg.org/#es-unsigned-short
-webidl.converters['unsigned short'] = function (V, prefix, argument, opts) {
- // 1. Let x be ? ConvertToInt(V, 16, "unsigned").
- const x = webidl.util.ConvertToInt(V, 16, 'unsigned', opts, prefix, argument)
+// https://wicg.github.io/cookie-store/#cookie-maximum-name-value-pair-size
+const maxNameValuePairSize = 4096
- // 2. Return the IDL unsigned short value that represents
- // the same numeric value as x.
- return x
+module.exports = {
+ maxAttributeValueSize,
+ maxNameValuePairSize
}
-// https://webidl.spec.whatwg.org/#idl-ArrayBuffer
-webidl.converters.ArrayBuffer = function (V, prefix, argument, opts) {
- // 1. If Type(V) is not Object, or V does not have an
- // [[ArrayBufferData]] internal slot, then throw a
- // TypeError.
- // see: https://tc39.es/ecma262/#sec-properties-of-the-arraybuffer-instances
- // see: https://tc39.es/ecma262/#sec-properties-of-the-sharedarraybuffer-instances
- if (
- webidl.util.Type(V) !== 'Object' ||
- !types.isAnyArrayBuffer(V)
- ) {
- throw webidl.errors.conversionFailed({
- prefix,
- argument: `${argument} ("${webidl.util.Stringify(V)}")`,
- types: ['ArrayBuffer']
- })
- }
- // 2. If the conversion is not to an IDL type associated
- // with the [AllowShared] extended attribute, and
- // IsSharedArrayBuffer(V) is true, then throw a
- // TypeError.
- if (opts?.allowShared === false && types.isSharedArrayBuffer(V)) {
- throw webidl.errors.exception({
- header: 'ArrayBuffer',
- message: 'SharedArrayBuffer is not allowed.'
- })
- }
+/***/ }),
- // 3. If the conversion is not to an IDL type associated
- // with the [AllowResizable] extended attribute, and
- // IsResizableArrayBuffer(V) is true, then throw a
- // TypeError.
- if (V.resizable || V.growable) {
- throw webidl.errors.exception({
- header: 'ArrayBuffer',
- message: 'Received a resizable ArrayBuffer.'
- })
- }
+/***/ 9061:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 4. Return the IDL ArrayBuffer value that is a
- // reference to the same object as V.
- return V
-}
-webidl.converters.TypedArray = function (V, T, prefix, name, opts) {
- // 1. Let T be the IDL type V is being converted to.
- // 2. If Type(V) is not Object, or V does not have a
- // [[TypedArrayName]] internal slot with a value
- // equal to T’s name, then throw a TypeError.
- if (
- webidl.util.Type(V) !== 'Object' ||
- !types.isTypedArray(V) ||
- V.constructor.name !== T.name
- ) {
- throw webidl.errors.conversionFailed({
- prefix,
- argument: `${name} ("${webidl.util.Stringify(V)}")`,
- types: [T.name]
- })
- }
+const { parseSetCookie } = __nccwpck_require__(1978)
+const { stringify } = __nccwpck_require__(7797)
+const { webidl } = __nccwpck_require__(5893)
+const { Headers } = __nccwpck_require__(660)
- // 3. If the conversion is not to an IDL type associated
- // with the [AllowShared] extended attribute, and
- // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is
- // true, then throw a TypeError.
- if (opts?.allowShared === false && types.isSharedArrayBuffer(V.buffer)) {
- throw webidl.errors.exception({
- header: 'ArrayBuffer',
- message: 'SharedArrayBuffer is not allowed.'
- })
+/**
+ * @typedef {Object} Cookie
+ * @property {string} name
+ * @property {string} value
+ * @property {Date|number|undefined} expires
+ * @property {number|undefined} maxAge
+ * @property {string|undefined} domain
+ * @property {string|undefined} path
+ * @property {boolean|undefined} secure
+ * @property {boolean|undefined} httpOnly
+ * @property {'Strict'|'Lax'|'None'} sameSite
+ * @property {string[]} unparsed
+ */
+
+/**
+ * @param {Headers} headers
+ * @returns {Record}
+ */
+function getCookies (headers) {
+ webidl.argumentLengthCheck(arguments, 1, 'getCookies')
+
+ webidl.brandCheck(headers, Headers, { strict: false })
+
+ const cookie = headers.get('cookie')
+ const out = {}
+
+ if (!cookie) {
+ return out
}
- // 4. If the conversion is not to an IDL type associated
- // with the [AllowResizable] extended attribute, and
- // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is
- // true, then throw a TypeError.
- if (V.buffer.resizable || V.buffer.growable) {
- throw webidl.errors.exception({
- header: 'ArrayBuffer',
- message: 'Received a resizable ArrayBuffer.'
- })
+ for (const piece of cookie.split(';')) {
+ const [name, ...value] = piece.split('=')
+
+ out[name.trim()] = value.join('=')
}
- // 5. Return the IDL value of type T that is a reference
- // to the same object as V.
- return V
+ return out
}
-webidl.converters.DataView = function (V, prefix, name, opts) {
- // 1. If Type(V) is not Object, or V does not have a
- // [[DataView]] internal slot, then throw a TypeError.
- if (webidl.util.Type(V) !== 'Object' || !types.isDataView(V)) {
- throw webidl.errors.exception({
- header: prefix,
- message: `${name} is not a DataView.`
- })
- }
+/**
+ * @param {Headers} headers
+ * @param {string} name
+ * @param {{ path?: string, domain?: string }|undefined} attributes
+ * @returns {void}
+ */
+function deleteCookie (headers, name, attributes) {
+ webidl.brandCheck(headers, Headers, { strict: false })
- // 2. If the conversion is not to an IDL type associated
- // with the [AllowShared] extended attribute, and
- // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true,
- // then throw a TypeError.
- if (opts?.allowShared === false && types.isSharedArrayBuffer(V.buffer)) {
- throw webidl.errors.exception({
- header: 'ArrayBuffer',
- message: 'SharedArrayBuffer is not allowed.'
- })
- }
+ const prefix = 'deleteCookie'
+ webidl.argumentLengthCheck(arguments, 2, prefix)
- // 3. If the conversion is not to an IDL type associated
- // with the [AllowResizable] extended attribute, and
- // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is
- // true, then throw a TypeError.
- if (V.buffer.resizable || V.buffer.growable) {
- throw webidl.errors.exception({
- header: 'ArrayBuffer',
- message: 'Received a resizable ArrayBuffer.'
- })
- }
+ name = webidl.converters.DOMString(name, prefix, 'name')
+ attributes = webidl.converters.DeleteCookieAttributes(attributes)
- // 4. Return the IDL DataView value that is a reference
- // to the same object as V.
- return V
+ // Matches behavior of
+ // https://github.com/denoland/deno_std/blob/63827b16330b82489a04614027c33b7904e08be5/http/cookie.ts#L278
+ setCookie(headers, {
+ name,
+ value: '',
+ expires: new Date(0),
+ ...attributes
+ })
}
-// https://webidl.spec.whatwg.org/#BufferSource
-webidl.converters.BufferSource = function (V, prefix, name, opts) {
- if (types.isAnyArrayBuffer(V)) {
- return webidl.converters.ArrayBuffer(V, prefix, name, { ...opts, allowShared: false })
- }
+/**
+ * @param {Headers} headers
+ * @returns {Cookie[]}
+ */
+function getSetCookies (headers) {
+ webidl.argumentLengthCheck(arguments, 1, 'getSetCookies')
- if (types.isTypedArray(V)) {
- return webidl.converters.TypedArray(V, V.constructor, prefix, name, { ...opts, allowShared: false })
- }
+ webidl.brandCheck(headers, Headers, { strict: false })
- if (types.isDataView(V)) {
- return webidl.converters.DataView(V, prefix, name, { ...opts, allowShared: false })
+ const cookies = headers.getSetCookie()
+
+ if (!cookies) {
+ return []
}
- throw webidl.errors.conversionFailed({
- prefix,
- argument: `${name} ("${webidl.util.Stringify(V)}")`,
- types: ['BufferSource']
- })
+ return cookies.map((pair) => parseSetCookie(pair))
}
-webidl.converters['sequence'] = webidl.sequenceConverter(
- webidl.converters.ByteString
-)
+/**
+ * @param {Headers} headers
+ * @param {Cookie} cookie
+ * @returns {void}
+ */
+function setCookie (headers, cookie) {
+ webidl.argumentLengthCheck(arguments, 2, 'setCookie')
-webidl.converters['sequence>'] = webidl.sequenceConverter(
- webidl.converters['sequence']
-)
+ webidl.brandCheck(headers, Headers, { strict: false })
-webidl.converters['record'] = webidl.recordConverter(
- webidl.converters.ByteString,
- webidl.converters.ByteString
-)
+ cookie = webidl.converters.Cookie(cookie)
+
+ const str = stringify(cookie)
+
+ if (str) {
+ headers.append('Set-Cookie', str)
+ }
+}
+
+webidl.converters.DeleteCookieAttributes = webidl.dictionaryConverter([
+ {
+ converter: webidl.nullableConverter(webidl.converters.DOMString),
+ key: 'path',
+ defaultValue: () => null
+ },
+ {
+ converter: webidl.nullableConverter(webidl.converters.DOMString),
+ key: 'domain',
+ defaultValue: () => null
+ }
+])
+
+webidl.converters.Cookie = webidl.dictionaryConverter([
+ {
+ converter: webidl.converters.DOMString,
+ key: 'name'
+ },
+ {
+ converter: webidl.converters.DOMString,
+ key: 'value'
+ },
+ {
+ converter: webidl.nullableConverter((value) => {
+ if (typeof value === 'number') {
+ return webidl.converters['unsigned long long'](value)
+ }
+
+ return new Date(value)
+ }),
+ key: 'expires',
+ defaultValue: () => null
+ },
+ {
+ converter: webidl.nullableConverter(webidl.converters['long long']),
+ key: 'maxAge',
+ defaultValue: () => null
+ },
+ {
+ converter: webidl.nullableConverter(webidl.converters.DOMString),
+ key: 'domain',
+ defaultValue: () => null
+ },
+ {
+ converter: webidl.nullableConverter(webidl.converters.DOMString),
+ key: 'path',
+ defaultValue: () => null
+ },
+ {
+ converter: webidl.nullableConverter(webidl.converters.boolean),
+ key: 'secure',
+ defaultValue: () => null
+ },
+ {
+ converter: webidl.nullableConverter(webidl.converters.boolean),
+ key: 'httpOnly',
+ defaultValue: () => null
+ },
+ {
+ converter: webidl.converters.USVString,
+ key: 'sameSite',
+ allowedValues: ['Strict', 'Lax', 'None']
+ },
+ {
+ converter: webidl.sequenceConverter(webidl.converters.DOMString),
+ key: 'unparsed',
+ defaultValue: () => new Array(0)
+ }
+])
module.exports = {
- webidl
+ getCookies,
+ deleteCookie,
+ getSetCookies,
+ setCookie
}
/***/ }),
-/***/ 3922:
-/***/ ((module) => {
+/***/ 1978:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+const { maxNameValuePairSize, maxAttributeValueSize } = __nccwpck_require__(1276)
+const { isCTLExcludingHtab } = __nccwpck_require__(7797)
+const { collectASequenceOfCodePointsFast } = __nccwpck_require__(1900)
+const assert = __nccwpck_require__(4589)
/**
- * @see https://encoding.spec.whatwg.org/#concept-encoding-get
- * @param {string|undefined} label
+ * @description Parses the field-value attributes of a set-cookie header string.
+ * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4
+ * @param {string} header
+ * @returns if the header is invalid, null will be returned
*/
-function getEncoding (label) {
- if (!label) {
- return 'failure'
+function parseSetCookie (header) {
+ // 1. If the set-cookie-string contains a %x00-08 / %x0A-1F / %x7F
+ // character (CTL characters excluding HTAB): Abort these steps and
+ // ignore the set-cookie-string entirely.
+ if (isCTLExcludingHtab(header)) {
+ return null
}
- // 1. Remove any leading and trailing ASCII whitespace from label.
- // 2. If label is an ASCII case-insensitive match for any of the
- // labels listed in the table below, then return the
- // corresponding encoding; otherwise return failure.
- switch (label.trim().toLowerCase()) {
- case 'unicode-1-1-utf-8':
- case 'unicode11utf8':
- case 'unicode20utf8':
- case 'utf-8':
- case 'utf8':
- case 'x-unicode20utf8':
- return 'UTF-8'
- case '866':
- case 'cp866':
- case 'csibm866':
- case 'ibm866':
- return 'IBM866'
- case 'csisolatin2':
- case 'iso-8859-2':
- case 'iso-ir-101':
- case 'iso8859-2':
- case 'iso88592':
- case 'iso_8859-2':
- case 'iso_8859-2:1987':
- case 'l2':
- case 'latin2':
- return 'ISO-8859-2'
- case 'csisolatin3':
- case 'iso-8859-3':
- case 'iso-ir-109':
- case 'iso8859-3':
- case 'iso88593':
- case 'iso_8859-3':
- case 'iso_8859-3:1988':
- case 'l3':
- case 'latin3':
- return 'ISO-8859-3'
- case 'csisolatin4':
- case 'iso-8859-4':
- case 'iso-ir-110':
- case 'iso8859-4':
- case 'iso88594':
- case 'iso_8859-4':
- case 'iso_8859-4:1988':
- case 'l4':
- case 'latin4':
- return 'ISO-8859-4'
- case 'csisolatincyrillic':
- case 'cyrillic':
- case 'iso-8859-5':
- case 'iso-ir-144':
- case 'iso8859-5':
- case 'iso88595':
- case 'iso_8859-5':
- case 'iso_8859-5:1988':
- return 'ISO-8859-5'
- case 'arabic':
- case 'asmo-708':
- case 'csiso88596e':
- case 'csiso88596i':
- case 'csisolatinarabic':
- case 'ecma-114':
- case 'iso-8859-6':
- case 'iso-8859-6-e':
- case 'iso-8859-6-i':
- case 'iso-ir-127':
- case 'iso8859-6':
- case 'iso88596':
- case 'iso_8859-6':
- case 'iso_8859-6:1987':
- return 'ISO-8859-6'
- case 'csisolatingreek':
- case 'ecma-118':
- case 'elot_928':
- case 'greek':
- case 'greek8':
- case 'iso-8859-7':
- case 'iso-ir-126':
- case 'iso8859-7':
- case 'iso88597':
- case 'iso_8859-7':
- case 'iso_8859-7:1987':
- case 'sun_eu_greek':
- return 'ISO-8859-7'
- case 'csiso88598e':
- case 'csisolatinhebrew':
- case 'hebrew':
- case 'iso-8859-8':
- case 'iso-8859-8-e':
- case 'iso-ir-138':
- case 'iso8859-8':
- case 'iso88598':
- case 'iso_8859-8':
- case 'iso_8859-8:1988':
- case 'visual':
- return 'ISO-8859-8'
- case 'csiso88598i':
- case 'iso-8859-8-i':
- case 'logical':
- return 'ISO-8859-8-I'
- case 'csisolatin6':
- case 'iso-8859-10':
- case 'iso-ir-157':
- case 'iso8859-10':
- case 'iso885910':
- case 'l6':
- case 'latin6':
- return 'ISO-8859-10'
- case 'iso-8859-13':
- case 'iso8859-13':
- case 'iso885913':
- return 'ISO-8859-13'
- case 'iso-8859-14':
- case 'iso8859-14':
- case 'iso885914':
- return 'ISO-8859-14'
- case 'csisolatin9':
- case 'iso-8859-15':
- case 'iso8859-15':
- case 'iso885915':
- case 'iso_8859-15':
- case 'l9':
- return 'ISO-8859-15'
- case 'iso-8859-16':
- return 'ISO-8859-16'
- case 'cskoi8r':
- case 'koi':
- case 'koi8':
- case 'koi8-r':
- case 'koi8_r':
- return 'KOI8-R'
- case 'koi8-ru':
- case 'koi8-u':
- return 'KOI8-U'
- case 'csmacintosh':
- case 'mac':
- case 'macintosh':
- case 'x-mac-roman':
- return 'macintosh'
- case 'iso-8859-11':
- case 'iso8859-11':
- case 'iso885911':
- case 'tis-620':
- case 'windows-874':
- return 'windows-874'
- case 'cp1250':
- case 'windows-1250':
- case 'x-cp1250':
- return 'windows-1250'
- case 'cp1251':
- case 'windows-1251':
- case 'x-cp1251':
- return 'windows-1251'
- case 'ansi_x3.4-1968':
- case 'ascii':
- case 'cp1252':
- case 'cp819':
- case 'csisolatin1':
- case 'ibm819':
- case 'iso-8859-1':
- case 'iso-ir-100':
- case 'iso8859-1':
- case 'iso88591':
- case 'iso_8859-1':
- case 'iso_8859-1:1987':
- case 'l1':
- case 'latin1':
- case 'us-ascii':
- case 'windows-1252':
- case 'x-cp1252':
- return 'windows-1252'
- case 'cp1253':
- case 'windows-1253':
- case 'x-cp1253':
- return 'windows-1253'
- case 'cp1254':
- case 'csisolatin5':
- case 'iso-8859-9':
- case 'iso-ir-148':
- case 'iso8859-9':
- case 'iso88599':
- case 'iso_8859-9':
- case 'iso_8859-9:1989':
- case 'l5':
- case 'latin5':
- case 'windows-1254':
- case 'x-cp1254':
- return 'windows-1254'
- case 'cp1255':
- case 'windows-1255':
- case 'x-cp1255':
- return 'windows-1255'
- case 'cp1256':
- case 'windows-1256':
- case 'x-cp1256':
- return 'windows-1256'
- case 'cp1257':
- case 'windows-1257':
- case 'x-cp1257':
- return 'windows-1257'
- case 'cp1258':
- case 'windows-1258':
- case 'x-cp1258':
- return 'windows-1258'
- case 'x-mac-cyrillic':
- case 'x-mac-ukrainian':
- return 'x-mac-cyrillic'
- case 'chinese':
- case 'csgb2312':
- case 'csiso58gb231280':
- case 'gb2312':
- case 'gb_2312':
- case 'gb_2312-80':
- case 'gbk':
- case 'iso-ir-58':
- case 'x-gbk':
- return 'GBK'
- case 'gb18030':
- return 'gb18030'
- case 'big5':
- case 'big5-hkscs':
- case 'cn-big5':
- case 'csbig5':
- case 'x-x-big5':
- return 'Big5'
- case 'cseucpkdfmtjapanese':
- case 'euc-jp':
- case 'x-euc-jp':
- return 'EUC-JP'
- case 'csiso2022jp':
- case 'iso-2022-jp':
- return 'ISO-2022-JP'
- case 'csshiftjis':
- case 'ms932':
- case 'ms_kanji':
- case 'shift-jis':
- case 'shift_jis':
- case 'sjis':
- case 'windows-31j':
- case 'x-sjis':
- return 'Shift_JIS'
- case 'cseuckr':
- case 'csksc56011987':
- case 'euc-kr':
- case 'iso-ir-149':
- case 'korean':
- case 'ks_c_5601-1987':
- case 'ks_c_5601-1989':
- case 'ksc5601':
- case 'ksc_5601':
- case 'windows-949':
- return 'EUC-KR'
- case 'csiso2022kr':
- case 'hz-gb-2312':
- case 'iso-2022-cn':
- case 'iso-2022-cn-ext':
- case 'iso-2022-kr':
- case 'replacement':
- return 'replacement'
- case 'unicodefffe':
- case 'utf-16be':
- return 'UTF-16BE'
- case 'csunicode':
- case 'iso-10646-ucs-2':
- case 'ucs-2':
- case 'unicode':
- case 'unicodefeff':
- case 'utf-16':
- case 'utf-16le':
- return 'UTF-16LE'
- case 'x-user-defined':
- return 'x-user-defined'
- default: return 'failure'
- }
-}
-
-module.exports = {
- getEncoding
-}
+ let nameValuePair = ''
+ let unparsedAttributes = ''
+ let name = ''
+ let value = ''
+ // 2. If the set-cookie-string contains a %x3B (";") character:
+ if (header.includes(';')) {
+ // 1. The name-value-pair string consists of the characters up to,
+ // but not including, the first %x3B (";"), and the unparsed-
+ // attributes consist of the remainder of the set-cookie-string
+ // (including the %x3B (";") in question).
+ const position = { position: 0 }
-/***/ }),
+ nameValuePair = collectASequenceOfCodePointsFast(';', header, position)
+ unparsedAttributes = header.slice(position.position)
+ } else {
+ // Otherwise:
-/***/ 9190:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 1. The name-value-pair string consists of all the characters
+ // contained in the set-cookie-string, and the unparsed-
+ // attributes is the empty string.
+ nameValuePair = header
+ }
+ // 3. If the name-value-pair string lacks a %x3D ("=") character, then
+ // the name string is empty, and the value string is the value of
+ // name-value-pair.
+ if (!nameValuePair.includes('=')) {
+ value = nameValuePair
+ } else {
+ // Otherwise, the name string consists of the characters up to, but
+ // not including, the first %x3D ("=") character, and the (possibly
+ // empty) value string consists of the characters after the first
+ // %x3D ("=") character.
+ const position = { position: 0 }
+ name = collectASequenceOfCodePointsFast(
+ '=',
+ nameValuePair,
+ position
+ )
+ value = nameValuePair.slice(position.position + 1)
+ }
+ // 4. Remove any leading or trailing WSP characters from the name
+ // string and the value string.
+ name = name.trim()
+ value = value.trim()
-const {
- staticPropertyDescriptors,
- readOperation,
- fireAProgressEvent
-} = __nccwpck_require__(1735)
-const {
- kState,
- kError,
- kResult,
- kEvents,
- kAborted
-} = __nccwpck_require__(5178)
-const { webidl } = __nccwpck_require__(220)
-const { kEnumerableProperty } = __nccwpck_require__(7375)
+ // 5. If the sum of the lengths of the name string and the value string
+ // is more than 4096 octets, abort these steps and ignore the set-
+ // cookie-string entirely.
+ if (name.length + value.length > maxNameValuePairSize) {
+ return null
+ }
-class FileReader extends EventTarget {
- constructor () {
- super()
+ // 6. The cookie-name is the name string, and the cookie-value is the
+ // value string.
+ return {
+ name, value, ...parseUnparsedAttributes(unparsedAttributes)
+ }
+}
- this[kState] = 'empty'
- this[kResult] = null
- this[kError] = null
- this[kEvents] = {
- loadend: null,
- error: null,
- abort: null,
- load: null,
- progress: null,
- loadstart: null
- }
+/**
+ * Parses the remaining attributes of a set-cookie header
+ * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4
+ * @param {string} unparsedAttributes
+ * @param {[Object.]={}} cookieAttributeList
+ */
+function parseUnparsedAttributes (unparsedAttributes, cookieAttributeList = {}) {
+ // 1. If the unparsed-attributes string is empty, skip the rest of
+ // these steps.
+ if (unparsedAttributes.length === 0) {
+ return cookieAttributeList
}
- /**
- * @see https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer
- * @param {import('buffer').Blob} blob
- */
- readAsArrayBuffer (blob) {
- webidl.brandCheck(this, FileReader)
+ // 2. Discard the first character of the unparsed-attributes (which
+ // will be a %x3B (";") character).
+ assert(unparsedAttributes[0] === ';')
+ unparsedAttributes = unparsedAttributes.slice(1)
- webidl.argumentLengthCheck(arguments, 1, 'FileReader.readAsArrayBuffer')
+ let cookieAv = ''
- blob = webidl.converters.Blob(blob, { strict: false })
+ // 3. If the remaining unparsed-attributes contains a %x3B (";")
+ // character:
+ if (unparsedAttributes.includes(';')) {
+ // 1. Consume the characters of the unparsed-attributes up to, but
+ // not including, the first %x3B (";") character.
+ cookieAv = collectASequenceOfCodePointsFast(
+ ';',
+ unparsedAttributes,
+ { position: 0 }
+ )
+ unparsedAttributes = unparsedAttributes.slice(cookieAv.length)
+ } else {
+ // Otherwise:
- // The readAsArrayBuffer(blob) method, when invoked,
- // must initiate a read operation for blob with ArrayBuffer.
- readOperation(this, blob, 'ArrayBuffer')
+ // 1. Consume the remainder of the unparsed-attributes.
+ cookieAv = unparsedAttributes
+ unparsedAttributes = ''
}
- /**
- * @see https://w3c.github.io/FileAPI/#readAsBinaryString
- * @param {import('buffer').Blob} blob
- */
- readAsBinaryString (blob) {
- webidl.brandCheck(this, FileReader)
-
- webidl.argumentLengthCheck(arguments, 1, 'FileReader.readAsBinaryString')
-
- blob = webidl.converters.Blob(blob, { strict: false })
+ // Let the cookie-av string be the characters consumed in this step.
- // The readAsBinaryString(blob) method, when invoked,
- // must initiate a read operation for blob with BinaryString.
- readOperation(this, blob, 'BinaryString')
- }
+ let attributeName = ''
+ let attributeValue = ''
- /**
- * @see https://w3c.github.io/FileAPI/#readAsDataText
- * @param {import('buffer').Blob} blob
- * @param {string?} encoding
- */
- readAsText (blob, encoding = undefined) {
- webidl.brandCheck(this, FileReader)
+ // 4. If the cookie-av string contains a %x3D ("=") character:
+ if (cookieAv.includes('=')) {
+ // 1. The (possibly empty) attribute-name string consists of the
+ // characters up to, but not including, the first %x3D ("=")
+ // character, and the (possibly empty) attribute-value string
+ // consists of the characters after the first %x3D ("=")
+ // character.
+ const position = { position: 0 }
- webidl.argumentLengthCheck(arguments, 1, 'FileReader.readAsText')
+ attributeName = collectASequenceOfCodePointsFast(
+ '=',
+ cookieAv,
+ position
+ )
+ attributeValue = cookieAv.slice(position.position + 1)
+ } else {
+ // Otherwise:
- blob = webidl.converters.Blob(blob, { strict: false })
+ // 1. The attribute-name string consists of the entire cookie-av
+ // string, and the attribute-value string is empty.
+ attributeName = cookieAv
+ }
- if (encoding !== undefined) {
- encoding = webidl.converters.DOMString(encoding, 'FileReader.readAsText', 'encoding')
- }
+ // 5. Remove any leading or trailing WSP characters from the attribute-
+ // name string and the attribute-value string.
+ attributeName = attributeName.trim()
+ attributeValue = attributeValue.trim()
- // The readAsText(blob, encoding) method, when invoked,
- // must initiate a read operation for blob with Text and encoding.
- readOperation(this, blob, 'Text', encoding)
+ // 6. If the attribute-value is longer than 1024 octets, ignore the
+ // cookie-av string and return to Step 1 of this algorithm.
+ if (attributeValue.length > maxAttributeValueSize) {
+ return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
}
- /**
- * @see https://w3c.github.io/FileAPI/#dfn-readAsDataURL
- * @param {import('buffer').Blob} blob
- */
- readAsDataURL (blob) {
- webidl.brandCheck(this, FileReader)
+ // 7. Process the attribute-name and attribute-value according to the
+ // requirements in the following subsections. (Notice that
+ // attributes with unrecognized attribute-names are ignored.)
+ const attributeNameLowercase = attributeName.toLowerCase()
- webidl.argumentLengthCheck(arguments, 1, 'FileReader.readAsDataURL')
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.1
+ // If the attribute-name case-insensitively matches the string
+ // "Expires", the user agent MUST process the cookie-av as follows.
+ if (attributeNameLowercase === 'expires') {
+ // 1. Let the expiry-time be the result of parsing the attribute-value
+ // as cookie-date (see Section 5.1.1).
+ const expiryTime = new Date(attributeValue)
- blob = webidl.converters.Blob(blob, { strict: false })
+ // 2. If the attribute-value failed to parse as a cookie date, ignore
+ // the cookie-av.
- // The readAsDataURL(blob) method, when invoked, must
- // initiate a read operation for blob with DataURL.
- readOperation(this, blob, 'DataURL')
- }
+ cookieAttributeList.expires = expiryTime
+ } else if (attributeNameLowercase === 'max-age') {
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.2
+ // If the attribute-name case-insensitively matches the string "Max-
+ // Age", the user agent MUST process the cookie-av as follows.
- /**
- * @see https://w3c.github.io/FileAPI/#dfn-abort
- */
- abort () {
- // 1. If this's state is "empty" or if this's state is
- // "done" set this's result to null and terminate
- // this algorithm.
- if (this[kState] === 'empty' || this[kState] === 'done') {
- this[kResult] = null
- return
+ // 1. If the first character of the attribute-value is not a DIGIT or a
+ // "-" character, ignore the cookie-av.
+ const charCode = attributeValue.charCodeAt(0)
+
+ if ((charCode < 48 || charCode > 57) && attributeValue[0] !== '-') {
+ return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
}
- // 2. If this's state is "loading" set this's state to
- // "done" and set this's result to null.
- if (this[kState] === 'loading') {
- this[kState] = 'done'
- this[kResult] = null
+ // 2. If the remainder of attribute-value contains a non-DIGIT
+ // character, ignore the cookie-av.
+ if (!/^\d+$/.test(attributeValue)) {
+ return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
}
- // 3. If there are any tasks from this on the file reading
- // task source in an affiliated task queue, then remove
- // those tasks from that task queue.
- this[kAborted] = true
+ // 3. Let delta-seconds be the attribute-value converted to an integer.
+ const deltaSeconds = Number(attributeValue)
- // 4. Terminate the algorithm for the read method being processed.
- // TODO
+ // 4. Let cookie-age-limit be the maximum age of the cookie (which
+ // SHOULD be 400 days or less, see Section 4.1.2.2).
- // 5. Fire a progress event called abort at this.
- fireAProgressEvent('abort', this)
+ // 5. Set delta-seconds to the smaller of its present value and cookie-
+ // age-limit.
+ // deltaSeconds = Math.min(deltaSeconds * 1000, maxExpiresMs)
- // 6. If this's state is not "loading", fire a progress
- // event called loadend at this.
- if (this[kState] !== 'loading') {
- fireAProgressEvent('loadend', this)
- }
- }
+ // 6. If delta-seconds is less than or equal to zero (0), let expiry-
+ // time be the earliest representable date and time. Otherwise, let
+ // the expiry-time be the current date and time plus delta-seconds
+ // seconds.
+ // const expiryTime = deltaSeconds <= 0 ? Date.now() : Date.now() + deltaSeconds
- /**
- * @see https://w3c.github.io/FileAPI/#dom-filereader-readystate
- */
- get readyState () {
- webidl.brandCheck(this, FileReader)
+ // 7. Append an attribute to the cookie-attribute-list with an
+ // attribute-name of Max-Age and an attribute-value of expiry-time.
+ cookieAttributeList.maxAge = deltaSeconds
+ } else if (attributeNameLowercase === 'domain') {
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.3
+ // If the attribute-name case-insensitively matches the string "Domain",
+ // the user agent MUST process the cookie-av as follows.
- switch (this[kState]) {
- case 'empty': return this.EMPTY
- case 'loading': return this.LOADING
- case 'done': return this.DONE
+ // 1. Let cookie-domain be the attribute-value.
+ let cookieDomain = attributeValue
+
+ // 2. If cookie-domain starts with %x2E ("."), let cookie-domain be
+ // cookie-domain without its leading %x2E (".").
+ if (cookieDomain[0] === '.') {
+ cookieDomain = cookieDomain.slice(1)
}
- }
- /**
- * @see https://w3c.github.io/FileAPI/#dom-filereader-result
- */
- get result () {
- webidl.brandCheck(this, FileReader)
+ // 3. Convert the cookie-domain to lower case.
+ cookieDomain = cookieDomain.toLowerCase()
- // The result attribute’s getter, when invoked, must return
- // this's result.
- return this[kResult]
- }
+ // 4. Append an attribute to the cookie-attribute-list with an
+ // attribute-name of Domain and an attribute-value of cookie-domain.
+ cookieAttributeList.domain = cookieDomain
+ } else if (attributeNameLowercase === 'path') {
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.4
+ // If the attribute-name case-insensitively matches the string "Path",
+ // the user agent MUST process the cookie-av as follows.
- /**
- * @see https://w3c.github.io/FileAPI/#dom-filereader-error
- */
- get error () {
- webidl.brandCheck(this, FileReader)
+ // 1. If the attribute-value is empty or if the first character of the
+ // attribute-value is not %x2F ("/"):
+ let cookiePath = ''
+ if (attributeValue.length === 0 || attributeValue[0] !== '/') {
+ // 1. Let cookie-path be the default-path.
+ cookiePath = '/'
+ } else {
+ // Otherwise:
- // The error attribute’s getter, when invoked, must return
- // this's error.
- return this[kError]
- }
+ // 1. Let cookie-path be the attribute-value.
+ cookiePath = attributeValue
+ }
- get onloadend () {
- webidl.brandCheck(this, FileReader)
+ // 2. Append an attribute to the cookie-attribute-list with an
+ // attribute-name of Path and an attribute-value of cookie-path.
+ cookieAttributeList.path = cookiePath
+ } else if (attributeNameLowercase === 'secure') {
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.5
+ // If the attribute-name case-insensitively matches the string "Secure",
+ // the user agent MUST append an attribute to the cookie-attribute-list
+ // with an attribute-name of Secure and an empty attribute-value.
- return this[kEvents].loadend
- }
+ cookieAttributeList.secure = true
+ } else if (attributeNameLowercase === 'httponly') {
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.6
+ // If the attribute-name case-insensitively matches the string
+ // "HttpOnly", the user agent MUST append an attribute to the cookie-
+ // attribute-list with an attribute-name of HttpOnly and an empty
+ // attribute-value.
- set onloadend (fn) {
- webidl.brandCheck(this, FileReader)
+ cookieAttributeList.httpOnly = true
+ } else if (attributeNameLowercase === 'samesite') {
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.7
+ // If the attribute-name case-insensitively matches the string
+ // "SameSite", the user agent MUST process the cookie-av as follows:
- if (this[kEvents].loadend) {
- this.removeEventListener('loadend', this[kEvents].loadend)
- }
+ // 1. Let enforcement be "Default".
+ let enforcement = 'Default'
- if (typeof fn === 'function') {
- this[kEvents].loadend = fn
- this.addEventListener('loadend', fn)
- } else {
- this[kEvents].loadend = null
+ const attributeValueLowercase = attributeValue.toLowerCase()
+ // 2. If cookie-av's attribute-value is a case-insensitive match for
+ // "None", set enforcement to "None".
+ if (attributeValueLowercase.includes('none')) {
+ enforcement = 'None'
}
- }
-
- get onerror () {
- webidl.brandCheck(this, FileReader)
-
- return this[kEvents].error
- }
-
- set onerror (fn) {
- webidl.brandCheck(this, FileReader)
- if (this[kEvents].error) {
- this.removeEventListener('error', this[kEvents].error)
+ // 3. If cookie-av's attribute-value is a case-insensitive match for
+ // "Strict", set enforcement to "Strict".
+ if (attributeValueLowercase.includes('strict')) {
+ enforcement = 'Strict'
}
- if (typeof fn === 'function') {
- this[kEvents].error = fn
- this.addEventListener('error', fn)
- } else {
- this[kEvents].error = null
+ // 4. If cookie-av's attribute-value is a case-insensitive match for
+ // "Lax", set enforcement to "Lax".
+ if (attributeValueLowercase.includes('lax')) {
+ enforcement = 'Lax'
}
- }
- get onloadstart () {
- webidl.brandCheck(this, FileReader)
+ // 5. Append an attribute to the cookie-attribute-list with an
+ // attribute-name of "SameSite" and an attribute-value of
+ // enforcement.
+ cookieAttributeList.sameSite = enforcement
+ } else {
+ cookieAttributeList.unparsed ??= []
- return this[kEvents].loadstart
+ cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`)
}
- set onloadstart (fn) {
- webidl.brandCheck(this, FileReader)
+ // 8. Return to Step 1 of this algorithm.
+ return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
+}
- if (this[kEvents].loadstart) {
- this.removeEventListener('loadstart', this[kEvents].loadstart)
- }
+module.exports = {
+ parseSetCookie,
+ parseUnparsedAttributes
+}
- if (typeof fn === 'function') {
- this[kEvents].loadstart = fn
- this.addEventListener('loadstart', fn)
- } else {
- this[kEvents].loadstart = null
- }
- }
- get onprogress () {
- webidl.brandCheck(this, FileReader)
+/***/ }),
- return this[kEvents].progress
- }
+/***/ 7797:
+/***/ ((module) => {
- set onprogress (fn) {
- webidl.brandCheck(this, FileReader)
- if (this[kEvents].progress) {
- this.removeEventListener('progress', this[kEvents].progress)
- }
- if (typeof fn === 'function') {
- this[kEvents].progress = fn
- this.addEventListener('progress', fn)
- } else {
- this[kEvents].progress = null
+/**
+ * @param {string} value
+ * @returns {boolean}
+ */
+function isCTLExcludingHtab (value) {
+ for (let i = 0; i < value.length; ++i) {
+ const code = value.charCodeAt(i)
+
+ if (
+ (code >= 0x00 && code <= 0x08) ||
+ (code >= 0x0A && code <= 0x1F) ||
+ code === 0x7F
+ ) {
+ return true
}
}
+ return false
+}
- get onload () {
- webidl.brandCheck(this, FileReader)
+/**
+ CHAR =
+ token = 1*
+ separators = "(" | ")" | "<" | ">" | "@"
+ | "," | ";" | ":" | "\" | <">
+ | "/" | "[" | "]" | "?" | "="
+ | "{" | "}" | SP | HT
+ * @param {string} name
+ */
+function validateCookieName (name) {
+ for (let i = 0; i < name.length; ++i) {
+ const code = name.charCodeAt(i)
- return this[kEvents].load
+ if (
+ code < 0x21 || // exclude CTLs (0-31), SP and HT
+ code > 0x7E || // exclude non-ascii and DEL
+ code === 0x22 || // "
+ code === 0x28 || // (
+ code === 0x29 || // )
+ code === 0x3C || // <
+ code === 0x3E || // >
+ code === 0x40 || // @
+ code === 0x2C || // ,
+ code === 0x3B || // ;
+ code === 0x3A || // :
+ code === 0x5C || // \
+ code === 0x2F || // /
+ code === 0x5B || // [
+ code === 0x5D || // ]
+ code === 0x3F || // ?
+ code === 0x3D || // =
+ code === 0x7B || // {
+ code === 0x7D // }
+ ) {
+ throw new Error('Invalid cookie name')
+ }
}
+}
- set onload (fn) {
- webidl.brandCheck(this, FileReader)
-
- if (this[kEvents].load) {
- this.removeEventListener('load', this[kEvents].load)
- }
+/**
+ cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )
+ cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E
+ ; US-ASCII characters excluding CTLs,
+ ; whitespace DQUOTE, comma, semicolon,
+ ; and backslash
+ * @param {string} value
+ */
+function validateCookieValue (value) {
+ let len = value.length
+ let i = 0
- if (typeof fn === 'function') {
- this[kEvents].load = fn
- this.addEventListener('load', fn)
- } else {
- this[kEvents].load = null
+ // if the value is wrapped in DQUOTE
+ if (value[0] === '"') {
+ if (len === 1 || value[len - 1] !== '"') {
+ throw new Error('Invalid cookie value')
}
+ --len
+ ++i
}
- get onabort () {
- webidl.brandCheck(this, FileReader)
+ while (i < len) {
+ const code = value.charCodeAt(i++)
- return this[kEvents].abort
+ if (
+ code < 0x21 || // exclude CTLs (0-31)
+ code > 0x7E || // non-ascii and DEL (127)
+ code === 0x22 || // "
+ code === 0x2C || // ,
+ code === 0x3B || // ;
+ code === 0x5C // \
+ ) {
+ throw new Error('Invalid cookie value')
+ }
}
+}
- set onabort (fn) {
- webidl.brandCheck(this, FileReader)
+/**
+ * path-value =
+ * @param {string} path
+ */
+function validateCookiePath (path) {
+ for (let i = 0; i < path.length; ++i) {
+ const code = path.charCodeAt(i)
- if (this[kEvents].abort) {
- this.removeEventListener('abort', this[kEvents].abort)
+ if (
+ code < 0x20 || // exclude CTLs (0-31)
+ code === 0x7F || // DEL
+ code === 0x3B // ;
+ ) {
+ throw new Error('Invalid cookie path')
}
+ }
+}
- if (typeof fn === 'function') {
- this[kEvents].abort = fn
- this.addEventListener('abort', fn)
- } else {
- this[kEvents].abort = null
- }
+/**
+ * I have no idea why these values aren't allowed to be honest,
+ * but Deno tests these. - Khafra
+ * @param {string} domain
+ */
+function validateCookieDomain (domain) {
+ if (
+ domain.startsWith('-') ||
+ domain.endsWith('.') ||
+ domain.endsWith('-')
+ ) {
+ throw new Error('Invalid cookie domain')
}
}
-// https://w3c.github.io/FileAPI/#dom-filereader-empty
-FileReader.EMPTY = FileReader.prototype.EMPTY = 0
-// https://w3c.github.io/FileAPI/#dom-filereader-loading
-FileReader.LOADING = FileReader.prototype.LOADING = 1
-// https://w3c.github.io/FileAPI/#dom-filereader-done
-FileReader.DONE = FileReader.prototype.DONE = 2
+const IMFDays = [
+ 'Sun', 'Mon', 'Tue', 'Wed',
+ 'Thu', 'Fri', 'Sat'
+]
-Object.defineProperties(FileReader.prototype, {
- EMPTY: staticPropertyDescriptors,
- LOADING: staticPropertyDescriptors,
- DONE: staticPropertyDescriptors,
- readAsArrayBuffer: kEnumerableProperty,
- readAsBinaryString: kEnumerableProperty,
- readAsText: kEnumerableProperty,
- readAsDataURL: kEnumerableProperty,
- abort: kEnumerableProperty,
- readyState: kEnumerableProperty,
- result: kEnumerableProperty,
- error: kEnumerableProperty,
- onloadstart: kEnumerableProperty,
- onprogress: kEnumerableProperty,
- onload: kEnumerableProperty,
- onabort: kEnumerableProperty,
- onerror: kEnumerableProperty,
- onloadend: kEnumerableProperty,
- [Symbol.toStringTag]: {
- value: 'FileReader',
- writable: false,
- enumerable: false,
- configurable: true
- }
-})
+const IMFMonths = [
+ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
+ 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
+]
-Object.defineProperties(FileReader, {
- EMPTY: staticPropertyDescriptors,
- LOADING: staticPropertyDescriptors,
- DONE: staticPropertyDescriptors
-})
+const IMFPaddedNumbers = Array(61).fill(0).map((_, i) => i.toString().padStart(2, '0'))
-module.exports = {
- FileReader
-}
+/**
+ * @see https://www.rfc-editor.org/rfc/rfc7231#section-7.1.1.1
+ * @param {number|Date} date
+ IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
+ ; fixed length/zone/capitalization subset of the format
+ ; see Section 3.3 of [RFC5322]
+ day-name = %x4D.6F.6E ; "Mon", case-sensitive
+ / %x54.75.65 ; "Tue", case-sensitive
+ / %x57.65.64 ; "Wed", case-sensitive
+ / %x54.68.75 ; "Thu", case-sensitive
+ / %x46.72.69 ; "Fri", case-sensitive
+ / %x53.61.74 ; "Sat", case-sensitive
+ / %x53.75.6E ; "Sun", case-sensitive
+ date1 = day SP month SP year
+ ; e.g., 02 Jun 1982
-/***/ }),
+ day = 2DIGIT
+ month = %x4A.61.6E ; "Jan", case-sensitive
+ / %x46.65.62 ; "Feb", case-sensitive
+ / %x4D.61.72 ; "Mar", case-sensitive
+ / %x41.70.72 ; "Apr", case-sensitive
+ / %x4D.61.79 ; "May", case-sensitive
+ / %x4A.75.6E ; "Jun", case-sensitive
+ / %x4A.75.6C ; "Jul", case-sensitive
+ / %x41.75.67 ; "Aug", case-sensitive
+ / %x53.65.70 ; "Sep", case-sensitive
+ / %x4F.63.74 ; "Oct", case-sensitive
+ / %x4E.6F.76 ; "Nov", case-sensitive
+ / %x44.65.63 ; "Dec", case-sensitive
+ year = 4DIGIT
-/***/ 558:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ GMT = %x47.4D.54 ; "GMT", case-sensitive
+ time-of-day = hour ":" minute ":" second
+ ; 00:00:00 - 23:59:60 (leap second)
+ hour = 2DIGIT
+ minute = 2DIGIT
+ second = 2DIGIT
+ */
+function toIMFDate (date) {
+ if (typeof date === 'number') {
+ date = new Date(date)
+ }
-const { webidl } = __nccwpck_require__(220)
+ return `${IMFDays[date.getUTCDay()]}, ${IMFPaddedNumbers[date.getUTCDate()]} ${IMFMonths[date.getUTCMonth()]} ${date.getUTCFullYear()} ${IMFPaddedNumbers[date.getUTCHours()]}:${IMFPaddedNumbers[date.getUTCMinutes()]}:${IMFPaddedNumbers[date.getUTCSeconds()]} GMT`
+}
-const kState = Symbol('ProgressEvent state')
+/**
+ max-age-av = "Max-Age=" non-zero-digit *DIGIT
+ ; In practice, both expires-av and max-age-av
+ ; are limited to dates representable by the
+ ; user agent.
+ * @param {number} maxAge
+ */
+function validateCookieMaxAge (maxAge) {
+ if (maxAge < 0) {
+ throw new Error('Invalid cookie max-age')
+ }
+}
/**
- * @see https://xhr.spec.whatwg.org/#progressevent
+ * @see https://www.rfc-editor.org/rfc/rfc6265#section-4.1.1
+ * @param {import('./index').Cookie} cookie
*/
-class ProgressEvent extends Event {
- constructor (type, eventInitDict = {}) {
- type = webidl.converters.DOMString(type, 'ProgressEvent constructor', 'type')
- eventInitDict = webidl.converters.ProgressEventInit(eventInitDict ?? {})
+function stringify (cookie) {
+ if (cookie.name.length === 0) {
+ return null
+ }
- super(type, eventInitDict)
+ validateCookieName(cookie.name)
+ validateCookieValue(cookie.value)
- this[kState] = {
- lengthComputable: eventInitDict.lengthComputable,
- loaded: eventInitDict.loaded,
- total: eventInitDict.total
- }
+ const out = [`${cookie.name}=${cookie.value}`]
+
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.1
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.2
+ if (cookie.name.startsWith('__Secure-')) {
+ cookie.secure = true
}
- get lengthComputable () {
- webidl.brandCheck(this, ProgressEvent)
+ if (cookie.name.startsWith('__Host-')) {
+ cookie.secure = true
+ cookie.domain = null
+ cookie.path = '/'
+ }
- return this[kState].lengthComputable
+ if (cookie.secure) {
+ out.push('Secure')
}
- get loaded () {
- webidl.brandCheck(this, ProgressEvent)
+ if (cookie.httpOnly) {
+ out.push('HttpOnly')
+ }
- return this[kState].loaded
+ if (typeof cookie.maxAge === 'number') {
+ validateCookieMaxAge(cookie.maxAge)
+ out.push(`Max-Age=${cookie.maxAge}`)
}
- get total () {
- webidl.brandCheck(this, ProgressEvent)
+ if (cookie.domain) {
+ validateCookieDomain(cookie.domain)
+ out.push(`Domain=${cookie.domain}`)
+ }
- return this[kState].total
+ if (cookie.path) {
+ validateCookiePath(cookie.path)
+ out.push(`Path=${cookie.path}`)
}
-}
-webidl.converters.ProgressEventInit = webidl.dictionaryConverter([
- {
- key: 'lengthComputable',
- converter: webidl.converters.boolean,
- defaultValue: () => false
- },
- {
- key: 'loaded',
- converter: webidl.converters['unsigned long long'],
- defaultValue: () => 0
- },
- {
- key: 'total',
- converter: webidl.converters['unsigned long long'],
- defaultValue: () => 0
- },
- {
- key: 'bubbles',
- converter: webidl.converters.boolean,
- defaultValue: () => false
- },
- {
- key: 'cancelable',
- converter: webidl.converters.boolean,
- defaultValue: () => false
- },
- {
- key: 'composed',
- converter: webidl.converters.boolean,
- defaultValue: () => false
+ if (cookie.expires && cookie.expires.toString() !== 'Invalid Date') {
+ out.push(`Expires=${toIMFDate(cookie.expires)}`)
}
-])
-module.exports = {
- ProgressEvent
-}
+ if (cookie.sameSite) {
+ out.push(`SameSite=${cookie.sameSite}`)
+ }
+ for (const part of cookie.unparsed) {
+ if (!part.includes('=')) {
+ throw new Error('Invalid unparsed')
+ }
-/***/ }),
-
-/***/ 5178:
-/***/ ((module) => {
+ const [key, ...value] = part.split('=')
+ out.push(`${key.trim()}=${value.join('=')}`)
+ }
+ return out.join('; ')
+}
module.exports = {
- kState: Symbol('FileReader state'),
- kResult: Symbol('FileReader result'),
- kError: Symbol('FileReader error'),
- kLastProgressEventFired: Symbol('FileReader last progress event fired timestamp'),
- kEvents: Symbol('FileReader events'),
- kAborted: Symbol('FileReader aborted')
+ isCTLExcludingHtab,
+ validateCookieName,
+ validateCookiePath,
+ validateCookieValue,
+ toIMFDate,
+ stringify
}
/***/ }),
-/***/ 1735:
+/***/ 4031:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+const { Transform } = __nccwpck_require__(7075)
+const { isASCIINumber, isValidLastEventId } = __nccwpck_require__(4811)
-const {
- kState,
- kError,
- kResult,
- kAborted,
- kLastProgressEventFired
-} = __nccwpck_require__(5178)
-const { ProgressEvent } = __nccwpck_require__(558)
-const { getEncoding } = __nccwpck_require__(3922)
-const { serializeAMimeType, parseMIMEType } = __nccwpck_require__(2121)
-const { types } = __nccwpck_require__(7975)
-const { StringDecoder } = __nccwpck_require__(3193)
-const { btoa } = __nccwpck_require__(4573)
+/**
+ * @type {number[]} BOM
+ */
+const BOM = [0xEF, 0xBB, 0xBF]
+/**
+ * @type {10} LF
+ */
+const LF = 0x0A
+/**
+ * @type {13} CR
+ */
+const CR = 0x0D
+/**
+ * @type {58} COLON
+ */
+const COLON = 0x3A
+/**
+ * @type {32} SPACE
+ */
+const SPACE = 0x20
-/** @type {PropertyDescriptor} */
-const staticPropertyDescriptors = {
- enumerable: true,
- writable: false,
- configurable: false
-}
+/**
+ * @typedef {object} EventSourceStreamEvent
+ * @type {object}
+ * @property {string} [event] The event type.
+ * @property {string} [data] The data of the message.
+ * @property {string} [id] A unique ID for the event.
+ * @property {string} [retry] The reconnection time, in milliseconds.
+ */
/**
- * @see https://w3c.github.io/FileAPI/#readOperation
- * @param {import('./filereader').FileReader} fr
- * @param {import('buffer').Blob} blob
- * @param {string} type
- * @param {string?} encodingName
+ * @typedef eventSourceSettings
+ * @type {object}
+ * @property {string} lastEventId The last event ID received from the server.
+ * @property {string} origin The origin of the event source.
+ * @property {number} reconnectionTime The reconnection time, in milliseconds.
*/
-function readOperation (fr, blob, type, encodingName) {
- // 1. If fr’s state is "loading", throw an InvalidStateError
- // DOMException.
- if (fr[kState] === 'loading') {
- throw new DOMException('Invalid state', 'InvalidStateError')
- }
- // 2. Set fr’s state to "loading".
- fr[kState] = 'loading'
+class EventSourceStream extends Transform {
+ /**
+ * @type {eventSourceSettings}
+ */
+ state = null
- // 3. Set fr’s result to null.
- fr[kResult] = null
+ /**
+ * Leading byte-order-mark check.
+ * @type {boolean}
+ */
+ checkBOM = true
- // 4. Set fr’s error to null.
- fr[kError] = null
+ /**
+ * @type {boolean}
+ */
+ crlfCheck = false
- // 5. Let stream be the result of calling get stream on blob.
- /** @type {import('stream/web').ReadableStream} */
- const stream = blob.stream()
+ /**
+ * @type {boolean}
+ */
+ eventEndCheck = false
- // 6. Let reader be the result of getting a reader from stream.
- const reader = stream.getReader()
+ /**
+ * @type {Buffer}
+ */
+ buffer = null
- // 7. Let bytes be an empty byte sequence.
- /** @type {Uint8Array[]} */
- const bytes = []
+ pos = 0
- // 8. Let chunkPromise be the result of reading a chunk from
- // stream with reader.
- let chunkPromise = reader.read()
+ event = {
+ data: undefined,
+ event: undefined,
+ id: undefined,
+ retry: undefined
+ }
- // 9. Let isFirstChunk be true.
- let isFirstChunk = true
+ /**
+ * @param {object} options
+ * @param {eventSourceSettings} options.eventSourceSettings
+ * @param {Function} [options.push]
+ */
+ constructor (options = {}) {
+ // Enable object mode as EventSourceStream emits objects of shape
+ // EventSourceStreamEvent
+ options.readableObjectMode = true
- // 10. In parallel, while true:
- // Note: "In parallel" just means non-blocking
- // Note 2: readOperation itself cannot be async as double
- // reading the body would then reject the promise, instead
- // of throwing an error.
- ;(async () => {
- while (!fr[kAborted]) {
- // 1. Wait for chunkPromise to be fulfilled or rejected.
- try {
- const { done, value } = await chunkPromise
+ super(options)
- // 2. If chunkPromise is fulfilled, and isFirstChunk is
- // true, queue a task to fire a progress event called
- // loadstart at fr.
- if (isFirstChunk && !fr[kAborted]) {
- queueMicrotask(() => {
- fireAProgressEvent('loadstart', fr)
- })
- }
+ this.state = options.eventSourceSettings || {}
+ if (options.push) {
+ this.push = options.push
+ }
+ }
- // 3. Set isFirstChunk to false.
- isFirstChunk = false
+ /**
+ * @param {Buffer} chunk
+ * @param {string} _encoding
+ * @param {Function} callback
+ * @returns {void}
+ */
+ _transform (chunk, _encoding, callback) {
+ if (chunk.length === 0) {
+ callback()
+ return
+ }
- // 4. If chunkPromise is fulfilled with an object whose
- // done property is false and whose value property is
- // a Uint8Array object, run these steps:
- if (!done && types.isUint8Array(value)) {
- // 1. Let bs be the byte sequence represented by the
- // Uint8Array object.
+ // Cache the chunk in the buffer, as the data might not be complete while
+ // processing it
+ // TODO: Investigate if there is a more performant way to handle
+ // incoming chunks
+ // see: https://github.com/nodejs/undici/issues/2630
+ if (this.buffer) {
+ this.buffer = Buffer.concat([this.buffer, chunk])
+ } else {
+ this.buffer = chunk
+ }
- // 2. Append bs to bytes.
- bytes.push(value)
+ // Strip leading byte-order-mark if we opened the stream and started
+ // the processing of the incoming data
+ if (this.checkBOM) {
+ switch (this.buffer.length) {
+ case 1:
+ // Check if the first byte is the same as the first byte of the BOM
+ if (this.buffer[0] === BOM[0]) {
+ // If it is, we need to wait for more data
+ callback()
+ return
+ }
+ // Set the checkBOM flag to false as we don't need to check for the
+ // BOM anymore
+ this.checkBOM = false
- // 3. If roughly 50ms have passed since these steps
- // were last invoked, queue a task to fire a
- // progress event called progress at fr.
+ // The buffer only contains one byte so we need to wait for more data
+ callback()
+ return
+ case 2:
+ // Check if the first two bytes are the same as the first two bytes
+ // of the BOM
if (
- (
- fr[kLastProgressEventFired] === undefined ||
- Date.now() - fr[kLastProgressEventFired] >= 50
- ) &&
- !fr[kAborted]
+ this.buffer[0] === BOM[0] &&
+ this.buffer[1] === BOM[1]
) {
- fr[kLastProgressEventFired] = Date.now()
- queueMicrotask(() => {
- fireAProgressEvent('progress', fr)
- })
+ // If it is, we need to wait for more data, because the third byte
+ // is needed to determine if it is the BOM or not
+ callback()
+ return
}
- // 4. Set chunkPromise to the result of reading a
- // chunk from stream with reader.
- chunkPromise = reader.read()
- } else if (done) {
- // 5. Otherwise, if chunkPromise is fulfilled with an
- // object whose done property is true, queue a task
- // to run the following steps and abort this algorithm:
- queueMicrotask(() => {
- // 1. Set fr’s state to "done".
- fr[kState] = 'done'
-
- // 2. Let result be the result of package data given
- // bytes, type, blob’s type, and encodingName.
- try {
- const result = packageData(bytes, type, blob.type, encodingName)
-
- // 4. Else:
-
- if (fr[kAborted]) {
- return
- }
+ // Set the checkBOM flag to false as we don't need to check for the
+ // BOM anymore
+ this.checkBOM = false
+ break
+ case 3:
+ // Check if the first three bytes are the same as the first three
+ // bytes of the BOM
+ if (
+ this.buffer[0] === BOM[0] &&
+ this.buffer[1] === BOM[1] &&
+ this.buffer[2] === BOM[2]
+ ) {
+ // If it is, we can drop the buffered data, as it is only the BOM
+ this.buffer = Buffer.alloc(0)
+ // Set the checkBOM flag to false as we don't need to check for the
+ // BOM anymore
+ this.checkBOM = false
- // 1. Set fr’s result to result.
- fr[kResult] = result
+ // Await more data
+ callback()
+ return
+ }
+ // If it is not the BOM, we can start processing the data
+ this.checkBOM = false
+ break
+ default:
+ // The buffer is longer than 3 bytes, so we can drop the BOM if it is
+ // present
+ if (
+ this.buffer[0] === BOM[0] &&
+ this.buffer[1] === BOM[1] &&
+ this.buffer[2] === BOM[2]
+ ) {
+ // Remove the BOM from the buffer
+ this.buffer = this.buffer.subarray(3)
+ }
- // 2. Fire a progress event called load at the fr.
- fireAProgressEvent('load', fr)
- } catch (error) {
- // 3. If package data threw an exception error:
+ // Set the checkBOM flag to false as we don't need to check for the
+ this.checkBOM = false
+ break
+ }
+ }
- // 1. Set fr’s error to error.
- fr[kError] = error
+ while (this.pos < this.buffer.length) {
+ // If the previous line ended with an end-of-line, we need to check
+ // if the next character is also an end-of-line.
+ if (this.eventEndCheck) {
+ // If the the current character is an end-of-line, then the event
+ // is finished and we can process it
- // 2. Fire a progress event called error at fr.
- fireAProgressEvent('error', fr)
- }
+ // If the previous line ended with a carriage return, we need to
+ // check if the current character is a line feed and remove it
+ // from the buffer.
+ if (this.crlfCheck) {
+ // If the current character is a line feed, we can remove it
+ // from the buffer and reset the crlfCheck flag
+ if (this.buffer[this.pos] === LF) {
+ this.buffer = this.buffer.subarray(this.pos + 1)
+ this.pos = 0
+ this.crlfCheck = false
- // 5. If fr’s state is not "loading", fire a progress
- // event called loadend at the fr.
- if (fr[kState] !== 'loading') {
- fireAProgressEvent('loadend', fr)
- }
- })
+ // It is possible that the line feed is not the end of the
+ // event. We need to check if the next character is an
+ // end-of-line character to determine if the event is
+ // finished. We simply continue the loop to check the next
+ // character.
- break
- }
- } catch (error) {
- if (fr[kAborted]) {
- return
+ // As we removed the line feed from the buffer and set the
+ // crlfCheck flag to false, we basically don't make any
+ // distinction between a line feed and a carriage return.
+ continue
+ }
+ this.crlfCheck = false
}
- // 6. Otherwise, if chunkPromise is rejected with an
- // error error, queue a task to run the following
- // steps and abort this algorithm:
- queueMicrotask(() => {
- // 1. Set fr’s state to "done".
- fr[kState] = 'done'
-
- // 2. Set fr’s error to error.
- fr[kError] = error
-
- // 3. Fire a progress event called error at fr.
- fireAProgressEvent('error', fr)
-
- // 4. If fr’s state is not "loading", fire a progress
- // event called loadend at fr.
- if (fr[kState] !== 'loading') {
- fireAProgressEvent('loadend', fr)
+ if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) {
+ // If the current character is a carriage return, we need to
+ // set the crlfCheck flag to true, as we need to check if the
+ // next character is a line feed so we can remove it from the
+ // buffer
+ if (this.buffer[this.pos] === CR) {
+ this.crlfCheck = true
}
- })
- break
+ this.buffer = this.buffer.subarray(this.pos + 1)
+ this.pos = 0
+ if (
+ this.event.data !== undefined || this.event.event || this.event.id || this.event.retry) {
+ this.processEvent(this.event)
+ }
+ this.clearEvent()
+ continue
+ }
+ // If the current character is not an end-of-line, then the event
+ // is not finished and we have to reset the eventEndCheck flag
+ this.eventEndCheck = false
+ continue
}
- }
- })()
-}
-/**
- * @see https://w3c.github.io/FileAPI/#fire-a-progress-event
- * @see https://dom.spec.whatwg.org/#concept-event-fire
- * @param {string} e The name of the event
- * @param {import('./filereader').FileReader} reader
- */
-function fireAProgressEvent (e, reader) {
- // The progress event e does not bubble. e.bubbles must be false
- // The progress event e is NOT cancelable. e.cancelable must be false
- const event = new ProgressEvent(e, {
- bubbles: false,
- cancelable: false
- })
+ // If the current character is an end-of-line, we can process the
+ // line
+ if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) {
+ // If the current character is a carriage return, we need to
+ // set the crlfCheck flag to true, as we need to check if the
+ // next character is a line feed
+ if (this.buffer[this.pos] === CR) {
+ this.crlfCheck = true
+ }
- reader.dispatchEvent(event)
-}
+ // In any case, we can process the line as we reached an
+ // end-of-line character
+ this.parseLine(this.buffer.subarray(0, this.pos), this.event)
-/**
- * @see https://w3c.github.io/FileAPI/#blob-package-data
- * @param {Uint8Array[]} bytes
- * @param {string} type
- * @param {string?} mimeType
- * @param {string?} encodingName
- */
-function packageData (bytes, type, mimeType, encodingName) {
- // 1. A Blob has an associated package data algorithm, given
- // bytes, a type, a optional mimeType, and a optional
- // encodingName, which switches on type and runs the
- // associated steps:
+ // Remove the processed line from the buffer
+ this.buffer = this.buffer.subarray(this.pos + 1)
+ // Reset the position as we removed the processed line from the buffer
+ this.pos = 0
+ // A line was processed and this could be the end of the event. We need
+ // to check if the next line is empty to determine if the event is
+ // finished.
+ this.eventEndCheck = true
+ continue
+ }
- switch (type) {
- case 'DataURL': {
- // 1. Return bytes as a DataURL [RFC2397] subject to
- // the considerations below:
- // * Use mimeType as part of the Data URL if it is
- // available in keeping with the Data URL
- // specification [RFC2397].
- // * If mimeType is not available return a Data URL
- // without a media-type. [RFC2397].
+ this.pos++
+ }
- // https://datatracker.ietf.org/doc/html/rfc2397#section-3
- // dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
- // mediatype := [ type "/" subtype ] *( ";" parameter )
- // data := *urlchar
- // parameter := attribute "=" value
- let dataURL = 'data:'
+ callback()
+ }
- const parsed = parseMIMEType(mimeType || 'application/octet-stream')
+ /**
+ * @param {Buffer} line
+ * @param {EventStreamEvent} event
+ */
+ parseLine (line, event) {
+ // If the line is empty (a blank line)
+ // Dispatch the event, as defined below.
+ // This will be handled in the _transform method
+ if (line.length === 0) {
+ return
+ }
- if (parsed !== 'failure') {
- dataURL += serializeAMimeType(parsed)
- }
+ // If the line starts with a U+003A COLON character (:)
+ // Ignore the line.
+ const colonPosition = line.indexOf(COLON)
+ if (colonPosition === 0) {
+ return
+ }
- dataURL += ';base64,'
+ let field = ''
+ let value = ''
- const decoder = new StringDecoder('latin1')
+ // If the line contains a U+003A COLON character (:)
+ if (colonPosition !== -1) {
+ // Collect the characters on the line before the first U+003A COLON
+ // character (:), and let field be that string.
+ // TODO: Investigate if there is a more performant way to extract the
+ // field
+ // see: https://github.com/nodejs/undici/issues/2630
+ field = line.subarray(0, colonPosition).toString('utf8')
- for (const chunk of bytes) {
- dataURL += btoa(decoder.write(chunk))
+ // Collect the characters on the line after the first U+003A COLON
+ // character (:), and let value be that string.
+ // If value starts with a U+0020 SPACE character, remove it from value.
+ let valueStart = colonPosition + 1
+ if (line[valueStart] === SPACE) {
+ ++valueStart
}
+ // TODO: Investigate if there is a more performant way to extract the
+ // value
+ // see: https://github.com/nodejs/undici/issues/2630
+ value = line.subarray(valueStart).toString('utf8')
- dataURL += btoa(decoder.end())
-
- return dataURL
+ // Otherwise, the string is not empty but does not contain a U+003A COLON
+ // character (:)
+ } else {
+ // Process the field using the steps described below, using the whole
+ // line as the field name, and the empty string as the field value.
+ field = line.toString('utf8')
+ value = ''
}
- case 'Text': {
- // 1. Let encoding be failure
- let encoding = 'failure'
- // 2. If the encodingName is present, set encoding to the
- // result of getting an encoding from encodingName.
- if (encodingName) {
- encoding = getEncoding(encodingName)
- }
-
- // 3. If encoding is failure, and mimeType is present:
- if (encoding === 'failure' && mimeType) {
- // 1. Let type be the result of parse a MIME type
- // given mimeType.
- const type = parseMIMEType(mimeType)
-
- // 2. If type is not failure, set encoding to the result
- // of getting an encoding from type’s parameters["charset"].
- if (type !== 'failure') {
- encoding = getEncoding(type.parameters.get('charset'))
+ // Modify the event with the field name and value. The value is also
+ // decoded as UTF-8
+ switch (field) {
+ case 'data':
+ if (event[field] === undefined) {
+ event[field] = value
+ } else {
+ event[field] += `\n${value}`
}
- }
-
- // 4. If encoding is failure, then set encoding to UTF-8.
- if (encoding === 'failure') {
- encoding = 'UTF-8'
- }
-
- // 5. Decode bytes using fallback encoding encoding, and
- // return the result.
- return decode(bytes, encoding)
+ break
+ case 'retry':
+ if (isASCIINumber(value)) {
+ event[field] = value
+ }
+ break
+ case 'id':
+ if (isValidLastEventId(value)) {
+ event[field] = value
+ }
+ break
+ case 'event':
+ if (value.length > 0) {
+ event[field] = value
+ }
+ break
}
- case 'ArrayBuffer': {
- // Return a new ArrayBuffer whose contents are bytes.
- const sequence = combineByteSequences(bytes)
+ }
- return sequence.buffer
+ /**
+ * @param {EventSourceStreamEvent} event
+ */
+ processEvent (event) {
+ if (event.retry && isASCIINumber(event.retry)) {
+ this.state.reconnectionTime = parseInt(event.retry, 10)
}
- case 'BinaryString': {
- // Return bytes as a binary string, in which every byte
- // is represented by a code unit of equal value [0..255].
- let binaryString = ''
-
- const decoder = new StringDecoder('latin1')
- for (const chunk of bytes) {
- binaryString += decoder.write(chunk)
- }
+ if (event.id && isValidLastEventId(event.id)) {
+ this.state.lastEventId = event.id
+ }
- binaryString += decoder.end()
+ // only dispatch event, when data is provided
+ if (event.data !== undefined) {
+ this.push({
+ type: event.event || 'message',
+ options: {
+ data: event.data,
+ lastEventId: this.state.lastEventId,
+ origin: this.state.origin
+ }
+ })
+ }
+ }
- return binaryString
+ clearEvent () {
+ this.event = {
+ data: undefined,
+ event: undefined,
+ id: undefined,
+ retry: undefined
}
}
}
-/**
- * @see https://encoding.spec.whatwg.org/#decode
- * @param {Uint8Array[]} ioQueue
- * @param {string} encoding
- */
-function decode (ioQueue, encoding) {
- const bytes = combineByteSequences(ioQueue)
+module.exports = {
+ EventSourceStream
+}
- // 1. Let BOMEncoding be the result of BOM sniffing ioQueue.
- const BOMEncoding = BOMSniffing(bytes)
- let slice = 0
+/***/ }),
- // 2. If BOMEncoding is non-null:
- if (BOMEncoding !== null) {
- // 1. Set encoding to BOMEncoding.
- encoding = BOMEncoding
+/***/ 1238:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 2. Read three bytes from ioQueue, if BOMEncoding is
- // UTF-8; otherwise read two bytes.
- // (Do nothing with those bytes.)
- slice = BOMEncoding === 'UTF-8' ? 3 : 2
- }
- // 3. Process a queue with an instance of encoding’s
- // decoder, ioQueue, output, and "replacement".
- // 4. Return output.
+const { pipeline } = __nccwpck_require__(7075)
+const { fetching } = __nccwpck_require__(4398)
+const { makeRequest } = __nccwpck_require__(9967)
+const { webidl } = __nccwpck_require__(5893)
+const { EventSourceStream } = __nccwpck_require__(4031)
+const { parseMIMEType } = __nccwpck_require__(1900)
+const { createFastMessageEvent } = __nccwpck_require__(5188)
+const { isNetworkError } = __nccwpck_require__(9051)
+const { delay } = __nccwpck_require__(4811)
+const { kEnumerableProperty } = __nccwpck_require__(3440)
+const { environmentSettingsObject } = __nccwpck_require__(3168)
- const sliced = bytes.slice(slice)
- return new TextDecoder(encoding).decode(sliced)
-}
+let experimentalWarned = false
/**
- * @see https://encoding.spec.whatwg.org/#bom-sniff
- * @param {Uint8Array} ioQueue
+ * A reconnection time, in milliseconds. This must initially be an implementation-defined value,
+ * probably in the region of a few seconds.
+ *
+ * In Comparison:
+ * - Chrome uses 3000ms.
+ * - Deno uses 5000ms.
+ *
+ * @type {3000}
*/
-function BOMSniffing (ioQueue) {
- // 1. Let BOM be the result of peeking 3 bytes from ioQueue,
- // converted to a byte sequence.
- const [a, b, c] = ioQueue
-
- // 2. For each of the rows in the table below, starting with
- // the first one and going down, if BOM starts with the
- // bytes given in the first column, then return the
- // encoding given in the cell in the second column of that
- // row. Otherwise, return null.
- if (a === 0xEF && b === 0xBB && c === 0xBF) {
- return 'UTF-8'
- } else if (a === 0xFE && b === 0xFF) {
- return 'UTF-16BE'
- } else if (a === 0xFF && b === 0xFE) {
- return 'UTF-16LE'
- }
+const defaultReconnectionTime = 3000
- return null
-}
+/**
+ * The readyState attribute represents the state of the connection.
+ * @enum
+ * @readonly
+ * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#dom-eventsource-readystate-dev
+ */
/**
- * @param {Uint8Array[]} sequences
+ * The connection has not yet been established, or it was closed and the user
+ * agent is reconnecting.
+ * @type {0}
*/
-function combineByteSequences (sequences) {
- const size = sequences.reduce((a, b) => {
- return a + b.byteLength
- }, 0)
+const CONNECTING = 0
- let offset = 0
+/**
+ * The user agent has an open connection and is dispatching events as it
+ * receives them.
+ * @type {1}
+ */
+const OPEN = 1
- return sequences.reduce((a, b) => {
- a.set(b, offset)
- offset += b.byteLength
- return a
- }, new Uint8Array(size))
-}
+/**
+ * The connection is not open, and the user agent is not trying to reconnect.
+ * @type {2}
+ */
+const CLOSED = 2
-module.exports = {
- staticPropertyDescriptors,
- readOperation,
- fireAProgressEvent
-}
+/**
+ * Requests for the element will have their mode set to "cors" and their credentials mode set to "same-origin".
+ * @type {'anonymous'}
+ */
+const ANONYMOUS = 'anonymous'
+/**
+ * Requests for the element will have their mode set to "cors" and their credentials mode set to "include".
+ * @type {'use-credentials'}
+ */
+const USE_CREDENTIALS = 'use-credentials'
-/***/ }),
+/**
+ * The EventSource interface is used to receive server-sent events. It
+ * connects to a server over HTTP and receives events in text/event-stream
+ * format without closing the connection.
+ * @extends {EventTarget}
+ * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#server-sent-events
+ * @api public
+ */
+class EventSource extends EventTarget {
+ #events = {
+ open: null,
+ error: null,
+ message: null
+ }
-/***/ 7032:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ #url = null
+ #withCredentials = false
+ #readyState = CONNECTING
+ #request = null
+ #controller = null
-const { uid, states, sentCloseFrameState, emptyBuffer, opcodes } = __nccwpck_require__(4411)
-const {
- kReadyState,
- kSentClose,
- kByteParser,
- kReceivedClose,
- kResponse
-} = __nccwpck_require__(2679)
-const { fireEvent, failWebsocketConnection, isClosing, isClosed, isEstablished, parseExtensions } = __nccwpck_require__(2148)
-const { channels } = __nccwpck_require__(4567)
-const { CloseEvent } = __nccwpck_require__(9617)
-const { makeRequest } = __nccwpck_require__(7412)
-const { fetching } = __nccwpck_require__(8033)
-const { Headers, getHeadersList } = __nccwpck_require__(1271)
-const { getDecodeSplit } = __nccwpck_require__(7241)
-const { WebsocketFrameSend } = __nccwpck_require__(3055)
+ #dispatcher
-/** @type {import('crypto')} */
-let crypto
-try {
- crypto = __nccwpck_require__(7598)
-/* c8 ignore next 3 */
-} catch {
+ /**
+ * @type {import('./eventsource-stream').eventSourceSettings}
+ */
+ #state
-}
+ /**
+ * Creates a new EventSource object.
+ * @param {string} url
+ * @param {EventSourceInit} [eventSourceInitDict]
+ * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#the-eventsource-interface
+ */
+ constructor (url, eventSourceInitDict = {}) {
+ // 1. Let ev be a new EventSource object.
+ super()
-/**
- * @see https://websockets.spec.whatwg.org/#concept-websocket-establish
- * @param {URL} url
- * @param {string|string[]} protocols
- * @param {import('./websocket').WebSocket} ws
- * @param {(response: any, extensions: string[] | undefined) => void} onEstablish
- * @param {Partial} options
- */
-function establishWebSocketConnection (url, protocols, client, ws, onEstablish, options) {
- // 1. Let requestURL be a copy of url, with its scheme set to "http", if url’s
- // scheme is "ws", and to "https" otherwise.
- const requestURL = url
+ webidl.util.markAsUncloneable(this)
- requestURL.protocol = url.protocol === 'ws:' ? 'http:' : 'https:'
+ const prefix = 'EventSource constructor'
+ webidl.argumentLengthCheck(arguments, 1, prefix)
- // 2. Let request be a new request, whose URL is requestURL, client is client,
- // service-workers mode is "none", referrer is "no-referrer", mode is
- // "websocket", credentials mode is "include", cache mode is "no-store" ,
- // and redirect mode is "error".
- const request = makeRequest({
- urlList: [requestURL],
- client,
- serviceWorkers: 'none',
- referrer: 'no-referrer',
- mode: 'websocket',
- credentials: 'include',
- cache: 'no-store',
- redirect: 'error'
- })
+ if (!experimentalWarned) {
+ experimentalWarned = true
+ process.emitWarning('EventSource is experimental, expect them to change at any time.', {
+ code: 'UNDICI-ES'
+ })
+ }
- // Note: undici extension, allow setting custom headers.
- if (options.headers) {
- const headersList = getHeadersList(new Headers(options.headers))
+ url = webidl.converters.USVString(url, prefix, 'url')
+ eventSourceInitDict = webidl.converters.EventSourceInitDict(eventSourceInitDict, prefix, 'eventSourceInitDict')
- request.headersList = headersList
- }
+ this.#dispatcher = eventSourceInitDict.dispatcher
+ this.#state = {
+ lastEventId: '',
+ reconnectionTime: defaultReconnectionTime
+ }
- // 3. Append (`Upgrade`, `websocket`) to request’s header list.
- // 4. Append (`Connection`, `Upgrade`) to request’s header list.
- // Note: both of these are handled by undici currently.
- // https://github.com/nodejs/undici/blob/68c269c4144c446f3f1220951338daef4a6b5ec4/lib/client.js#L1397
+ // 2. Let settings be ev's relevant settings object.
+ // https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object
+ const settings = environmentSettingsObject
- // 5. Let keyValue be a nonce consisting of a randomly selected
- // 16-byte value that has been forgiving-base64-encoded and
- // isomorphic encoded.
- const keyValue = crypto.randomBytes(16).toString('base64')
+ let urlRecord
- // 6. Append (`Sec-WebSocket-Key`, keyValue) to request’s
- // header list.
- request.headersList.append('sec-websocket-key', keyValue)
+ try {
+ // 3. Let urlRecord be the result of encoding-parsing a URL given url, relative to settings.
+ urlRecord = new URL(url, settings.settingsObject.baseUrl)
+ this.#state.origin = urlRecord.origin
+ } catch (e) {
+ // 4. If urlRecord is failure, then throw a "SyntaxError" DOMException.
+ throw new DOMException(e, 'SyntaxError')
+ }
- // 7. Append (`Sec-WebSocket-Version`, `13`) to request’s
- // header list.
- request.headersList.append('sec-websocket-version', '13')
+ // 5. Set ev's url to urlRecord.
+ this.#url = urlRecord.href
- // 8. For each protocol in protocols, combine
- // (`Sec-WebSocket-Protocol`, protocol) in request’s header
- // list.
- for (const protocol of protocols) {
- request.headersList.append('sec-websocket-protocol', protocol)
- }
+ // 6. Let corsAttributeState be Anonymous.
+ let corsAttributeState = ANONYMOUS
- // 9. Let permessageDeflate be a user-agent defined
- // "permessage-deflate" extension header value.
- // https://github.com/mozilla/gecko-dev/blob/ce78234f5e653a5d3916813ff990f053510227bc/netwerk/protocol/websocket/WebSocketChannel.cpp#L2673
- const permessageDeflate = 'permessage-deflate; client_max_window_bits'
+ // 7. If the value of eventSourceInitDict's withCredentials member is true,
+ // then set corsAttributeState to Use Credentials and set ev's
+ // withCredentials attribute to true.
+ if (eventSourceInitDict.withCredentials) {
+ corsAttributeState = USE_CREDENTIALS
+ this.#withCredentials = true
+ }
- // 10. Append (`Sec-WebSocket-Extensions`, permessageDeflate) to
- // request’s header list.
- request.headersList.append('sec-websocket-extensions', permessageDeflate)
+ // 8. Let request be the result of creating a potential-CORS request given
+ // urlRecord, the empty string, and corsAttributeState.
+ const initRequest = {
+ redirect: 'follow',
+ keepalive: true,
+ // @see https://html.spec.whatwg.org/multipage/urls-and-fetching.html#cors-settings-attributes
+ mode: 'cors',
+ credentials: corsAttributeState === 'anonymous'
+ ? 'same-origin'
+ : 'omit',
+ referrer: 'no-referrer'
+ }
- // 11. Fetch request with useParallelQueue set to true, and
- // processResponse given response being these steps:
- const controller = fetching({
- request,
- useParallelQueue: true,
- dispatcher: options.dispatcher,
- processResponse (response) {
- // 1. If response is a network error or its status is not 101,
- // fail the WebSocket connection.
- if (response.type === 'error' || response.status !== 101) {
- failWebsocketConnection(ws, 'Received network error or non-101 status code.')
- return
- }
+ // 9. Set request's client to settings.
+ initRequest.client = environmentSettingsObject.settingsObject
- // 2. If protocols is not the empty list and extracting header
- // list values given `Sec-WebSocket-Protocol` and response’s
- // header list results in null, failure, or the empty byte
- // sequence, then fail the WebSocket connection.
- if (protocols.length !== 0 && !response.headersList.get('Sec-WebSocket-Protocol')) {
- failWebsocketConnection(ws, 'Server did not respond with sent protocols.')
- return
- }
+ // 10. User agents may set (`Accept`, `text/event-stream`) in request's header list.
+ initRequest.headersList = [['accept', { name: 'accept', value: 'text/event-stream' }]]
- // 3. Follow the requirements stated step 2 to step 6, inclusive,
- // of the last set of steps in section 4.1 of The WebSocket
- // Protocol to validate response. This either results in fail
- // the WebSocket connection or the WebSocket connection is
- // established.
+ // 11. Set request's cache mode to "no-store".
+ initRequest.cache = 'no-store'
- // 2. If the response lacks an |Upgrade| header field or the |Upgrade|
- // header field contains a value that is not an ASCII case-
- // insensitive match for the value "websocket", the client MUST
- // _Fail the WebSocket Connection_.
- if (response.headersList.get('Upgrade')?.toLowerCase() !== 'websocket') {
- failWebsocketConnection(ws, 'Server did not set Upgrade header to "websocket".')
- return
- }
+ // 12. Set request's initiator type to "other".
+ initRequest.initiator = 'other'
- // 3. If the response lacks a |Connection| header field or the
- // |Connection| header field doesn't contain a token that is an
- // ASCII case-insensitive match for the value "Upgrade", the client
- // MUST _Fail the WebSocket Connection_.
- if (response.headersList.get('Connection')?.toLowerCase() !== 'upgrade') {
- failWebsocketConnection(ws, 'Server did not set Connection header to "upgrade".')
- return
- }
+ initRequest.urlList = [new URL(this.#url)]
- // 4. If the response lacks a |Sec-WebSocket-Accept| header field or
- // the |Sec-WebSocket-Accept| contains a value other than the
- // base64-encoded SHA-1 of the concatenation of the |Sec-WebSocket-
- // Key| (as a string, not base64-decoded) with the string "258EAFA5-
- // E914-47DA-95CA-C5AB0DC85B11" but ignoring any leading and
- // trailing whitespace, the client MUST _Fail the WebSocket
- // Connection_.
- const secWSAccept = response.headersList.get('Sec-WebSocket-Accept')
- const digest = crypto.createHash('sha1').update(keyValue + uid).digest('base64')
- if (secWSAccept !== digest) {
- failWebsocketConnection(ws, 'Incorrect hash received in Sec-WebSocket-Accept header.')
- return
- }
+ // 13. Set ev's request to request.
+ this.#request = makeRequest(initRequest)
- // 5. If the response includes a |Sec-WebSocket-Extensions| header
- // field and this header field indicates the use of an extension
- // that was not present in the client's handshake (the server has
- // indicated an extension not requested by the client), the client
- // MUST _Fail the WebSocket Connection_. (The parsing of this
- // header field to determine which extensions are requested is
- // discussed in Section 9.1.)
- const secExtension = response.headersList.get('Sec-WebSocket-Extensions')
- let extensions
+ this.#connect()
+ }
- if (secExtension !== null) {
- extensions = parseExtensions(secExtension)
+ /**
+ * Returns the state of this EventSource object's connection. It can have the
+ * values described below.
+ * @returns {0|1|2}
+ * @readonly
+ */
+ get readyState () {
+ return this.#readyState
+ }
- if (!extensions.has('permessage-deflate')) {
- failWebsocketConnection(ws, 'Sec-WebSocket-Extensions header does not match.')
- return
- }
- }
+ /**
+ * Returns the URL providing the event stream.
+ * @readonly
+ * @returns {string}
+ */
+ get url () {
+ return this.#url
+ }
- // 6. If the response includes a |Sec-WebSocket-Protocol| header field
- // and this header field indicates the use of a subprotocol that was
- // not present in the client's handshake (the server has indicated a
- // subprotocol not requested by the client), the client MUST _Fail
- // the WebSocket Connection_.
- const secProtocol = response.headersList.get('Sec-WebSocket-Protocol')
+ /**
+ * Returns a boolean indicating whether the EventSource object was
+ * instantiated with CORS credentials set (true), or not (false, the default).
+ */
+ get withCredentials () {
+ return this.#withCredentials
+ }
- if (secProtocol !== null) {
- const requestProtocols = getDecodeSplit('sec-websocket-protocol', request.headersList)
+ #connect () {
+ if (this.#readyState === CLOSED) return
- // The client can request that the server use a specific subprotocol by
- // including the |Sec-WebSocket-Protocol| field in its handshake. If it
- // is specified, the server needs to include the same field and one of
- // the selected subprotocol values in its response for the connection to
- // be established.
- if (!requestProtocols.includes(secProtocol)) {
- failWebsocketConnection(ws, 'Protocol was not set in the opening handshake.')
- return
- }
- }
+ this.#readyState = CONNECTING
- response.socket.on('data', onSocketData)
- response.socket.on('close', onSocketClose)
- response.socket.on('error', onSocketError)
+ const fetchParams = {
+ request: this.#request,
+ dispatcher: this.#dispatcher
+ }
- if (channels.open.hasSubscribers) {
- channels.open.publish({
- address: response.socket.address(),
- protocol: secProtocol,
- extensions: secExtension
- })
+ // 14. Let processEventSourceEndOfBody given response res be the following step: if res is not a network error, then reestablish the connection.
+ const processEventSourceEndOfBody = (response) => {
+ if (isNetworkError(response)) {
+ this.dispatchEvent(new Event('error'))
+ this.close()
}
- onEstablish(response, extensions)
+ this.#reconnect()
}
- })
- return controller
-}
+ // 15. Fetch request, with processResponseEndOfBody set to processEventSourceEndOfBody...
+ fetchParams.processResponseEndOfBody = processEventSourceEndOfBody
-function closeWebSocketConnection (ws, code, reason, reasonByteLength) {
- if (isClosing(ws) || isClosed(ws)) {
- // If this's ready state is CLOSING (2) or CLOSED (3)
- // Do nothing.
- } else if (!isEstablished(ws)) {
- // If the WebSocket connection is not yet established
- // Fail the WebSocket connection and set this's ready state
- // to CLOSING (2).
- failWebsocketConnection(ws, 'Connection was closed before it was established.')
- ws[kReadyState] = states.CLOSING
- } else if (ws[kSentClose] === sentCloseFrameState.NOT_SENT) {
- // If the WebSocket closing handshake has not yet been started
- // Start the WebSocket closing handshake and set this's ready
- // state to CLOSING (2).
- // - If neither code nor reason is present, the WebSocket Close
- // message must not have a body.
- // - If code is present, then the status code to use in the
- // WebSocket Close message must be the integer given by code.
- // - If reason is also present, then reasonBytes must be
- // provided in the Close message after the status code.
+ // and processResponse set to the following steps given response res:
+ fetchParams.processResponse = (response) => {
+ // 1. If res is an aborted network error, then fail the connection.
- ws[kSentClose] = sentCloseFrameState.PROCESSING
+ if (isNetworkError(response)) {
+ // 1. When a user agent is to fail the connection, the user agent
+ // must queue a task which, if the readyState attribute is set to a
+ // value other than CLOSED, sets the readyState attribute to CLOSED
+ // and fires an event named error at the EventSource object. Once the
+ // user agent has failed the connection, it does not attempt to
+ // reconnect.
+ if (response.aborted) {
+ this.close()
+ this.dispatchEvent(new Event('error'))
+ return
+ // 2. Otherwise, if res is a network error, then reestablish the
+ // connection, unless the user agent knows that to be futile, in
+ // which case the user agent may fail the connection.
+ } else {
+ this.#reconnect()
+ return
+ }
+ }
- const frame = new WebsocketFrameSend()
+ // 3. Otherwise, if res's status is not 200, or if res's `Content-Type`
+ // is not `text/event-stream`, then fail the connection.
+ const contentType = response.headersList.get('content-type', true)
+ const mimeType = contentType !== null ? parseMIMEType(contentType) : 'failure'
+ const contentTypeValid = mimeType !== 'failure' && mimeType.essence === 'text/event-stream'
+ if (
+ response.status !== 200 ||
+ contentTypeValid === false
+ ) {
+ this.close()
+ this.dispatchEvent(new Event('error'))
+ return
+ }
- // If neither code nor reason is present, the WebSocket Close
- // message must not have a body.
+ // 4. Otherwise, announce the connection and interpret res's body
+ // line by line.
- // If code is present, then the status code to use in the
- // WebSocket Close message must be the integer given by code.
- if (code !== undefined && reason === undefined) {
- frame.frameData = Buffer.allocUnsafe(2)
- frame.frameData.writeUInt16BE(code, 0)
- } else if (code !== undefined && reason !== undefined) {
- // If reason is also present, then reasonBytes must be
- // provided in the Close message after the status code.
- frame.frameData = Buffer.allocUnsafe(2 + reasonByteLength)
- frame.frameData.writeUInt16BE(code, 0)
- // the body MAY contain UTF-8-encoded data with value /reason/
- frame.frameData.write(reason, 2, 'utf-8')
- } else {
- frame.frameData = emptyBuffer
- }
+ // When a user agent is to announce the connection, the user agent
+ // must queue a task which, if the readyState attribute is set to a
+ // value other than CLOSED, sets the readyState attribute to OPEN
+ // and fires an event named open at the EventSource object.
+ // @see https://html.spec.whatwg.org/multipage/server-sent-events.html#sse-processing-model
+ this.#readyState = OPEN
+ this.dispatchEvent(new Event('open'))
- /** @type {import('stream').Duplex} */
- const socket = ws[kResponse].socket
+ // If redirected to a different origin, set the origin to the new origin.
+ this.#state.origin = response.urlList[response.urlList.length - 1].origin
- socket.write(frame.createFrame(opcodes.CLOSE))
+ const eventSourceStream = new EventSourceStream({
+ eventSourceSettings: this.#state,
+ push: (event) => {
+ this.dispatchEvent(createFastMessageEvent(
+ event.type,
+ event.options
+ ))
+ }
+ })
- ws[kSentClose] = sentCloseFrameState.SENT
+ pipeline(response.body.stream,
+ eventSourceStream,
+ (error) => {
+ if (
+ error?.aborted === false
+ ) {
+ this.close()
+ this.dispatchEvent(new Event('error'))
+ }
+ })
+ }
- // Upon either sending or receiving a Close control frame, it is said
- // that _The WebSocket Closing Handshake is Started_ and that the
- // WebSocket connection is in the CLOSING state.
- ws[kReadyState] = states.CLOSING
- } else {
- // Otherwise
- // Set this's ready state to CLOSING (2).
- ws[kReadyState] = states.CLOSING
+ this.#controller = fetching(fetchParams)
}
-}
-/**
- * @param {Buffer} chunk
- */
-function onSocketData (chunk) {
- if (!this.ws[kByteParser].write(chunk)) {
- this.pause()
- }
-}
+ /**
+ * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#sse-processing-model
+ * @returns {Promise}
+ */
+ async #reconnect () {
+ // When a user agent is to reestablish the connection, the user agent must
+ // run the following steps. These steps are run in parallel, not as part of
+ // a task. (The tasks that it queues, of course, are run like normal tasks
+ // and not themselves in parallel.)
-/**
- * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
- * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4
- */
-function onSocketClose () {
- const { ws } = this
- const { [kResponse]: response } = ws
+ // 1. Queue a task to run the following steps:
- response.socket.off('data', onSocketData)
- response.socket.off('close', onSocketClose)
- response.socket.off('error', onSocketError)
+ // 1. If the readyState attribute is set to CLOSED, abort the task.
+ if (this.#readyState === CLOSED) return
- // If the TCP connection was closed after the
- // WebSocket closing handshake was completed, the WebSocket connection
- // is said to have been closed _cleanly_.
- const wasClean = ws[kSentClose] === sentCloseFrameState.SENT && ws[kReceivedClose]
+ // 2. Set the readyState attribute to CONNECTING.
+ this.#readyState = CONNECTING
- let code = 1005
- let reason = ''
+ // 3. Fire an event named error at the EventSource object.
+ this.dispatchEvent(new Event('error'))
- const result = ws[kByteParser].closingInfo
+ // 2. Wait a delay equal to the reconnection time of the event source.
+ await delay(this.#state.reconnectionTime)
- if (result && !result.error) {
- code = result.code ?? 1005
- reason = result.reason
- } else if (!ws[kReceivedClose]) {
- // If _The WebSocket
- // Connection is Closed_ and no Close control frame was received by the
- // endpoint (such as could occur if the underlying transport connection
- // is lost), _The WebSocket Connection Close Code_ is considered to be
- // 1006.
- code = 1006
+ // 5. Queue a task to run the following steps:
+
+ // 1. If the EventSource object's readyState attribute is not set to
+ // CONNECTING, then return.
+ if (this.#readyState !== CONNECTING) return
+
+ // 2. Let request be the EventSource object's request.
+ // 3. If the EventSource object's last event ID string is not the empty
+ // string, then:
+ // 1. Let lastEventIDValue be the EventSource object's last event ID
+ // string, encoded as UTF-8.
+ // 2. Set (`Last-Event-ID`, lastEventIDValue) in request's header
+ // list.
+ if (this.#state.lastEventId.length) {
+ this.#request.headersList.set('last-event-id', this.#state.lastEventId, true)
+ }
+
+ // 4. Fetch request and process the response obtained in this fashion, if any, as described earlier in this section.
+ this.#connect()
}
- // 1. Change the ready state to CLOSED (3).
- ws[kReadyState] = states.CLOSED
+ /**
+ * Closes the connection, if any, and sets the readyState attribute to
+ * CLOSED.
+ */
+ close () {
+ webidl.brandCheck(this, EventSource)
- // 2. If the user agent was required to fail the WebSocket
- // connection, or if the WebSocket connection was closed
- // after being flagged as full, fire an event named error
- // at the WebSocket object.
- // TODO
+ if (this.#readyState === CLOSED) return
+ this.#readyState = CLOSED
+ this.#controller.abort()
+ this.#request = null
+ }
- // 3. Fire an event named close at the WebSocket object,
- // using CloseEvent, with the wasClean attribute
- // initialized to true if the connection closed cleanly
- // and false otherwise, the code attribute initialized to
- // the WebSocket connection close code, and the reason
- // attribute initialized to the result of applying UTF-8
- // decode without BOM to the WebSocket connection close
- // reason.
- // TODO: process.nextTick
- fireEvent('close', ws, (type, init) => new CloseEvent(type, init), {
- wasClean, code, reason
- })
+ get onopen () {
+ return this.#events.open
+ }
- if (channels.close.hasSubscribers) {
- channels.close.publish({
- websocket: ws,
- code,
- reason
- })
+ set onopen (fn) {
+ if (this.#events.open) {
+ this.removeEventListener('open', this.#events.open)
+ }
+
+ if (typeof fn === 'function') {
+ this.#events.open = fn
+ this.addEventListener('open', fn)
+ } else {
+ this.#events.open = null
+ }
}
-}
-function onSocketError (error) {
- const { ws } = this
+ get onmessage () {
+ return this.#events.message
+ }
- ws[kReadyState] = states.CLOSING
+ set onmessage (fn) {
+ if (this.#events.message) {
+ this.removeEventListener('message', this.#events.message)
+ }
- if (channels.socketError.hasSubscribers) {
- channels.socketError.publish(error)
+ if (typeof fn === 'function') {
+ this.#events.message = fn
+ this.addEventListener('message', fn)
+ } else {
+ this.#events.message = null
+ }
}
- this.destroy()
+ get onerror () {
+ return this.#events.error
+ }
+
+ set onerror (fn) {
+ if (this.#events.error) {
+ this.removeEventListener('error', this.#events.error)
+ }
+
+ if (typeof fn === 'function') {
+ this.#events.error = fn
+ this.addEventListener('error', fn)
+ } else {
+ this.#events.error = null
+ }
+ }
}
-module.exports = {
- establishWebSocketConnection,
- closeWebSocketConnection
+const constantsPropertyDescriptors = {
+ CONNECTING: {
+ __proto__: null,
+ configurable: false,
+ enumerable: true,
+ value: CONNECTING,
+ writable: false
+ },
+ OPEN: {
+ __proto__: null,
+ configurable: false,
+ enumerable: true,
+ value: OPEN,
+ writable: false
+ },
+ CLOSED: {
+ __proto__: null,
+ configurable: false,
+ enumerable: true,
+ value: CLOSED,
+ writable: false
+ }
}
+Object.defineProperties(EventSource, constantsPropertyDescriptors)
+Object.defineProperties(EventSource.prototype, constantsPropertyDescriptors)
-/***/ }),
+Object.defineProperties(EventSource.prototype, {
+ close: kEnumerableProperty,
+ onerror: kEnumerableProperty,
+ onmessage: kEnumerableProperty,
+ onopen: kEnumerableProperty,
+ readyState: kEnumerableProperty,
+ url: kEnumerableProperty,
+ withCredentials: kEnumerableProperty
+})
-/***/ 4411:
-/***/ ((module) => {
+webidl.converters.EventSourceInitDict = webidl.dictionaryConverter([
+ {
+ key: 'withCredentials',
+ converter: webidl.converters.boolean,
+ defaultValue: () => false
+ },
+ {
+ key: 'dispatcher', // undici only
+ converter: webidl.converters.any
+ }
+])
+module.exports = {
+ EventSource,
+ defaultReconnectionTime
+}
-// This is a Globally Unique Identifier unique used
-// to validate that the endpoint accepts websocket
-// connections.
-// See https://www.rfc-editor.org/rfc/rfc6455.html#section-1.3
-const uid = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
+/***/ }),
-/** @type {PropertyDescriptor} */
-const staticPropertyDescriptors = {
- enumerable: true,
- writable: false,
- configurable: false
-}
+/***/ 4811:
+/***/ ((module) => {
-const states = {
- CONNECTING: 0,
- OPEN: 1,
- CLOSING: 2,
- CLOSED: 3
-}
-const sentCloseFrameState = {
- NOT_SENT: 0,
- PROCESSING: 1,
- SENT: 2
-}
-const opcodes = {
- CONTINUATION: 0x0,
- TEXT: 0x1,
- BINARY: 0x2,
- CLOSE: 0x8,
- PING: 0x9,
- PONG: 0xA
+/**
+ * Checks if the given value is a valid LastEventId.
+ * @param {string} value
+ * @returns {boolean}
+ */
+function isValidLastEventId (value) {
+ // LastEventId should not contain U+0000 NULL
+ return value.indexOf('\u0000') === -1
}
-const maxUnsigned16Bit = 2 ** 16 - 1 // 65535
-
-const parserStates = {
- INFO: 0,
- PAYLOADLENGTH_16: 2,
- PAYLOADLENGTH_64: 3,
- READ_DATA: 4
+/**
+ * Checks if the given value is a base 10 digit.
+ * @param {string} value
+ * @returns {boolean}
+ */
+function isASCIINumber (value) {
+ if (value.length === 0) return false
+ for (let i = 0; i < value.length; i++) {
+ if (value.charCodeAt(i) < 0x30 || value.charCodeAt(i) > 0x39) return false
+ }
+ return true
}
-const emptyBuffer = Buffer.allocUnsafe(0)
-
-const sendHints = {
- string: 1,
- typedArray: 2,
- arrayBuffer: 3,
- blob: 4
+// https://github.com/nodejs/undici/issues/2664
+function delay (ms) {
+ return new Promise((resolve) => {
+ setTimeout(resolve, ms).unref()
+ })
}
module.exports = {
- uid,
- sentCloseFrameState,
- staticPropertyDescriptors,
- states,
- opcodes,
- maxUnsigned16Bit,
- parserStates,
- emptyBuffer,
- sendHints
+ isValidLastEventId,
+ isASCIINumber,
+ delay
}
/***/ }),
-/***/ 9617:
+/***/ 4492:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const { webidl } = __nccwpck_require__(220)
-const { kEnumerableProperty } = __nccwpck_require__(7375)
-const { kConstruct } = __nccwpck_require__(6130)
-const { MessagePort } = __nccwpck_require__(5919)
+const util = __nccwpck_require__(3440)
+const {
+ ReadableStreamFrom,
+ isBlobLike,
+ isReadableStreamLike,
+ readableStreamClose,
+ createDeferredPromise,
+ fullyReadBody,
+ extractMimeType,
+ utf8DecodeBytes
+} = __nccwpck_require__(3168)
+const { FormData } = __nccwpck_require__(5910)
+const { kState } = __nccwpck_require__(3627)
+const { webidl } = __nccwpck_require__(5893)
+const { Blob } = __nccwpck_require__(4573)
+const assert = __nccwpck_require__(4589)
+const { isErrored, isDisturbed } = __nccwpck_require__(7075)
+const { isArrayBuffer } = __nccwpck_require__(3429)
+const { serializeAMimeType } = __nccwpck_require__(1900)
+const { multipartFormDataParser } = __nccwpck_require__(116)
+let random
-/**
- * @see https://html.spec.whatwg.org/multipage/comms.html#messageevent
- */
-class MessageEvent extends Event {
- #eventInit
+try {
+ const crypto = __nccwpck_require__(7598)
+ random = (max) => crypto.randomInt(0, max)
+} catch {
+ random = (max) => Math.floor(Math.random(max))
+}
- constructor (type, eventInitDict = {}) {
- if (type === kConstruct) {
- super(arguments[1], arguments[2])
- webidl.util.markAsUncloneable(this)
- return
- }
+const textEncoder = new TextEncoder()
+function noop () {}
- const prefix = 'MessageEvent constructor'
- webidl.argumentLengthCheck(arguments, 1, prefix)
+const hasFinalizationRegistry = globalThis.FinalizationRegistry && process.version.indexOf('v18') !== 0
+let streamRegistry
- type = webidl.converters.DOMString(type, prefix, 'type')
- eventInitDict = webidl.converters.MessageEventInit(eventInitDict, prefix, 'eventInitDict')
+if (hasFinalizationRegistry) {
+ streamRegistry = new FinalizationRegistry((weakRef) => {
+ const stream = weakRef.deref()
+ if (stream && !stream.locked && !isDisturbed(stream) && !isErrored(stream)) {
+ stream.cancel('Response object has been garbage collected').catch(noop)
+ }
+ })
+}
- super(type, eventInitDict)
+// https://fetch.spec.whatwg.org/#concept-bodyinit-extract
+function extractBody (object, keepalive = false) {
+ // 1. Let stream be null.
+ let stream = null
- this.#eventInit = eventInitDict
- webidl.util.markAsUncloneable(this)
- }
+ // 2. If object is a ReadableStream object, then set stream to object.
+ if (object instanceof ReadableStream) {
+ stream = object
+ } else if (isBlobLike(object)) {
+ // 3. Otherwise, if object is a Blob object, set stream to the
+ // result of running object’s get stream.
+ stream = object.stream()
+ } else {
+ // 4. Otherwise, set stream to a new ReadableStream object, and set
+ // up stream with byte reading support.
+ stream = new ReadableStream({
+ async pull (controller) {
+ const buffer = typeof source === 'string' ? textEncoder.encode(source) : source
- get data () {
- webidl.brandCheck(this, MessageEvent)
+ if (buffer.byteLength) {
+ controller.enqueue(buffer)
+ }
- return this.#eventInit.data
+ queueMicrotask(() => readableStreamClose(controller))
+ },
+ start () {},
+ type: 'bytes'
+ })
}
- get origin () {
- webidl.brandCheck(this, MessageEvent)
+ // 5. Assert: stream is a ReadableStream object.
+ assert(isReadableStreamLike(stream))
- return this.#eventInit.origin
- }
+ // 6. Let action be null.
+ let action = null
- get lastEventId () {
- webidl.brandCheck(this, MessageEvent)
+ // 7. Let source be null.
+ let source = null
- return this.#eventInit.lastEventId
- }
+ // 8. Let length be null.
+ let length = null
- get source () {
- webidl.brandCheck(this, MessageEvent)
+ // 9. Let type be null.
+ let type = null
- return this.#eventInit.source
- }
+ // 10. Switch on object:
+ if (typeof object === 'string') {
+ // Set source to the UTF-8 encoding of object.
+ // Note: setting source to a Uint8Array here breaks some mocking assumptions.
+ source = object
- get ports () {
- webidl.brandCheck(this, MessageEvent)
+ // Set type to `text/plain;charset=UTF-8`.
+ type = 'text/plain;charset=UTF-8'
+ } else if (object instanceof URLSearchParams) {
+ // URLSearchParams
- if (!Object.isFrozen(this.#eventInit.ports)) {
- Object.freeze(this.#eventInit.ports)
- }
+ // spec says to run application/x-www-form-urlencoded on body.list
+ // this is implemented in Node.js as apart of an URLSearchParams instance toString method
+ // See: https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L490
+ // and https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L1100
- return this.#eventInit.ports
- }
+ // Set source to the result of running the application/x-www-form-urlencoded serializer with object’s list.
+ source = object.toString()
- initMessageEvent (
- type,
- bubbles = false,
- cancelable = false,
- data = null,
- origin = '',
- lastEventId = '',
- source = null,
- ports = []
- ) {
- webidl.brandCheck(this, MessageEvent)
+ // Set type to `application/x-www-form-urlencoded;charset=UTF-8`.
+ type = 'application/x-www-form-urlencoded;charset=UTF-8'
+ } else if (isArrayBuffer(object)) {
+ // BufferSource/ArrayBuffer
- webidl.argumentLengthCheck(arguments, 1, 'MessageEvent.initMessageEvent')
+ // Set source to a copy of the bytes held by object.
+ source = new Uint8Array(object.slice())
+ } else if (ArrayBuffer.isView(object)) {
+ // BufferSource/ArrayBufferView
- return new MessageEvent(type, {
- bubbles, cancelable, data, origin, lastEventId, source, ports
- })
- }
+ // Set source to a copy of the bytes held by object.
+ source = new Uint8Array(object.buffer.slice(object.byteOffset, object.byteOffset + object.byteLength))
+ } else if (util.isFormDataLike(object)) {
+ const boundary = `----formdata-undici-0${`${random(1e11)}`.padStart(11, '0')}`
+ const prefix = `--${boundary}\r\nContent-Disposition: form-data`
- static createFastMessageEvent (type, init) {
- const messageEvent = new MessageEvent(kConstruct, type, init)
- messageEvent.#eventInit = init
- messageEvent.#eventInit.data ??= null
- messageEvent.#eventInit.origin ??= ''
- messageEvent.#eventInit.lastEventId ??= ''
- messageEvent.#eventInit.source ??= null
- messageEvent.#eventInit.ports ??= []
- return messageEvent
- }
-}
+ /*! formdata-polyfill. MIT License. Jimmy Wärting */
+ const escape = (str) =>
+ str.replace(/\n/g, '%0A').replace(/\r/g, '%0D').replace(/"/g, '%22')
+ const normalizeLinefeeds = (value) => value.replace(/\r?\n|\r/g, '\r\n')
-const { createFastMessageEvent } = MessageEvent
-delete MessageEvent.createFastMessageEvent
+ // Set action to this step: run the multipart/form-data
+ // encoding algorithm, with object’s entry list and UTF-8.
+ // - This ensures that the body is immutable and can't be changed afterwords
+ // - That the content-length is calculated in advance.
+ // - And that all parts are pre-encoded and ready to be sent.
-/**
- * @see https://websockets.spec.whatwg.org/#the-closeevent-interface
- */
-class CloseEvent extends Event {
- #eventInit
+ const blobParts = []
+ const rn = new Uint8Array([13, 10]) // '\r\n'
+ length = 0
+ let hasUnknownSizeValue = false
- constructor (type, eventInitDict = {}) {
- const prefix = 'CloseEvent constructor'
- webidl.argumentLengthCheck(arguments, 1, prefix)
+ for (const [name, value] of object) {
+ if (typeof value === 'string') {
+ const chunk = textEncoder.encode(prefix +
+ `; name="${escape(normalizeLinefeeds(name))}"` +
+ `\r\n\r\n${normalizeLinefeeds(value)}\r\n`)
+ blobParts.push(chunk)
+ length += chunk.byteLength
+ } else {
+ const chunk = textEncoder.encode(`${prefix}; name="${escape(normalizeLinefeeds(name))}"` +
+ (value.name ? `; filename="${escape(value.name)}"` : '') + '\r\n' +
+ `Content-Type: ${
+ value.type || 'application/octet-stream'
+ }\r\n\r\n`)
+ blobParts.push(chunk, value, rn)
+ if (typeof value.size === 'number') {
+ length += chunk.byteLength + value.size + rn.byteLength
+ } else {
+ hasUnknownSizeValue = true
+ }
+ }
+ }
- type = webidl.converters.DOMString(type, prefix, 'type')
- eventInitDict = webidl.converters.CloseEventInit(eventInitDict)
+ // CRLF is appended to the body to function with legacy servers and match other implementations.
+ // https://github.com/curl/curl/blob/3434c6b46e682452973972e8313613dfa58cd690/lib/mime.c#L1029-L1030
+ // https://github.com/form-data/form-data/issues/63
+ const chunk = textEncoder.encode(`--${boundary}--\r\n`)
+ blobParts.push(chunk)
+ length += chunk.byteLength
+ if (hasUnknownSizeValue) {
+ length = null
+ }
- super(type, eventInitDict)
+ // Set source to object.
+ source = object
- this.#eventInit = eventInitDict
- webidl.util.markAsUncloneable(this)
- }
+ action = async function * () {
+ for (const part of blobParts) {
+ if (part.stream) {
+ yield * part.stream()
+ } else {
+ yield part
+ }
+ }
+ }
- get wasClean () {
- webidl.brandCheck(this, CloseEvent)
+ // Set type to `multipart/form-data; boundary=`,
+ // followed by the multipart/form-data boundary string generated
+ // by the multipart/form-data encoding algorithm.
+ type = `multipart/form-data; boundary=${boundary}`
+ } else if (isBlobLike(object)) {
+ // Blob
- return this.#eventInit.wasClean
- }
+ // Set source to object.
+ source = object
- get code () {
- webidl.brandCheck(this, CloseEvent)
+ // Set length to object’s size.
+ length = object.size
- return this.#eventInit.code
- }
+ // If object’s type attribute is not the empty byte sequence, set
+ // type to its value.
+ if (object.type) {
+ type = object.type
+ }
+ } else if (typeof object[Symbol.asyncIterator] === 'function') {
+ // If keepalive is true, then throw a TypeError.
+ if (keepalive) {
+ throw new TypeError('keepalive')
+ }
- get reason () {
- webidl.brandCheck(this, CloseEvent)
+ // If object is disturbed or locked, then throw a TypeError.
+ if (util.isDisturbed(object) || object.locked) {
+ throw new TypeError(
+ 'Response body object should not be disturbed or locked'
+ )
+ }
- return this.#eventInit.reason
+ stream =
+ object instanceof ReadableStream ? object : ReadableStreamFrom(object)
}
-}
-
-// https://html.spec.whatwg.org/multipage/webappapis.html#the-errorevent-interface
-class ErrorEvent extends Event {
- #eventInit
- constructor (type, eventInitDict) {
- const prefix = 'ErrorEvent constructor'
- webidl.argumentLengthCheck(arguments, 1, prefix)
+ // 11. If source is a byte sequence, then set action to a
+ // step that returns source and length to source’s length.
+ if (typeof source === 'string' || util.isBuffer(source)) {
+ length = Buffer.byteLength(source)
+ }
- super(type, eventInitDict)
- webidl.util.markAsUncloneable(this)
+ // 12. If action is non-null, then run these steps in in parallel:
+ if (action != null) {
+ // Run action.
+ let iterator
+ stream = new ReadableStream({
+ async start () {
+ iterator = action(object)[Symbol.asyncIterator]()
+ },
+ async pull (controller) {
+ const { value, done } = await iterator.next()
+ if (done) {
+ // When running action is done, close stream.
+ queueMicrotask(() => {
+ controller.close()
+ controller.byobRequest?.respond(0)
+ })
+ } else {
+ // Whenever one or more bytes are available and stream is not errored,
+ // enqueue a Uint8Array wrapping an ArrayBuffer containing the available
+ // bytes into stream.
+ if (!isErrored(stream)) {
+ const buffer = new Uint8Array(value)
+ if (buffer.byteLength) {
+ controller.enqueue(buffer)
+ }
+ }
+ }
+ return controller.desiredSize > 0
+ },
+ async cancel (reason) {
+ await iterator.return()
+ },
+ type: 'bytes'
+ })
+ }
- type = webidl.converters.DOMString(type, prefix, 'type')
- eventInitDict = webidl.converters.ErrorEventInit(eventInitDict ?? {})
+ // 13. Let body be a body whose stream is stream, source is source,
+ // and length is length.
+ const body = { stream, source, length }
- this.#eventInit = eventInitDict
- }
+ // 14. Return (body, type).
+ return [body, type]
+}
- get message () {
- webidl.brandCheck(this, ErrorEvent)
+// https://fetch.spec.whatwg.org/#bodyinit-safely-extract
+function safelyExtractBody (object, keepalive = false) {
+ // To safely extract a body and a `Content-Type` value from
+ // a byte sequence or BodyInit object object, run these steps:
- return this.#eventInit.message
+ // 1. If object is a ReadableStream object, then:
+ if (object instanceof ReadableStream) {
+ // Assert: object is neither disturbed nor locked.
+ // istanbul ignore next
+ assert(!util.isDisturbed(object), 'The body has already been consumed.')
+ // istanbul ignore next
+ assert(!object.locked, 'The stream is locked.')
}
- get filename () {
- webidl.brandCheck(this, ErrorEvent)
+ // 2. Return the results of extracting object.
+ return extractBody(object, keepalive)
+}
- return this.#eventInit.filename
- }
+function cloneBody (instance, body) {
+ // To clone a body body, run these steps:
- get lineno () {
- webidl.brandCheck(this, ErrorEvent)
+ // https://fetch.spec.whatwg.org/#concept-body-clone
- return this.#eventInit.lineno
- }
+ // 1. Let « out1, out2 » be the result of teeing body’s stream.
+ const [out1, out2] = body.stream.tee()
- get colno () {
- webidl.brandCheck(this, ErrorEvent)
+ // 2. Set body’s stream to out1.
+ body.stream = out1
- return this.#eventInit.colno
+ // 3. Return a body whose stream is out2 and other members are copied from body.
+ return {
+ stream: out2,
+ length: body.length,
+ source: body.source
}
+}
- get error () {
- webidl.brandCheck(this, ErrorEvent)
-
- return this.#eventInit.error
+function throwIfAborted (state) {
+ if (state.aborted) {
+ throw new DOMException('The operation was aborted.', 'AbortError')
}
}
-Object.defineProperties(MessageEvent.prototype, {
- [Symbol.toStringTag]: {
- value: 'MessageEvent',
- configurable: true
- },
- data: kEnumerableProperty,
- origin: kEnumerableProperty,
- lastEventId: kEnumerableProperty,
- source: kEnumerableProperty,
- ports: kEnumerableProperty,
- initMessageEvent: kEnumerableProperty
-})
+function bodyMixinMethods (instance) {
+ const methods = {
+ blob () {
+ // The blob() method steps are to return the result of
+ // running consume body with this and the following step
+ // given a byte sequence bytes: return a Blob whose
+ // contents are bytes and whose type attribute is this’s
+ // MIME type.
+ return consumeBody(this, (bytes) => {
+ let mimeType = bodyMimeType(this)
-Object.defineProperties(CloseEvent.prototype, {
- [Symbol.toStringTag]: {
- value: 'CloseEvent',
- configurable: true
- },
- reason: kEnumerableProperty,
- code: kEnumerableProperty,
- wasClean: kEnumerableProperty
-})
+ if (mimeType === null) {
+ mimeType = ''
+ } else if (mimeType) {
+ mimeType = serializeAMimeType(mimeType)
+ }
-Object.defineProperties(ErrorEvent.prototype, {
- [Symbol.toStringTag]: {
- value: 'ErrorEvent',
- configurable: true
- },
- message: kEnumerableProperty,
- filename: kEnumerableProperty,
- lineno: kEnumerableProperty,
- colno: kEnumerableProperty,
- error: kEnumerableProperty
-})
+ // Return a Blob whose contents are bytes and type attribute
+ // is mimeType.
+ return new Blob([bytes], { type: mimeType })
+ }, instance)
+ },
-webidl.converters.MessagePort = webidl.interfaceConverter(MessagePort)
+ arrayBuffer () {
+ // The arrayBuffer() method steps are to return the result
+ // of running consume body with this and the following step
+ // given a byte sequence bytes: return a new ArrayBuffer
+ // whose contents are bytes.
+ return consumeBody(this, (bytes) => {
+ return new Uint8Array(bytes).buffer
+ }, instance)
+ },
-webidl.converters['sequence'] = webidl.sequenceConverter(
- webidl.converters.MessagePort
-)
+ text () {
+ // The text() method steps are to return the result of running
+ // consume body with this and UTF-8 decode.
+ return consumeBody(this, utf8DecodeBytes, instance)
+ },
-const eventInit = [
- {
- key: 'bubbles',
- converter: webidl.converters.boolean,
- defaultValue: () => false
- },
- {
- key: 'cancelable',
- converter: webidl.converters.boolean,
- defaultValue: () => false
- },
- {
- key: 'composed',
- converter: webidl.converters.boolean,
- defaultValue: () => false
- }
-]
+ json () {
+ // The json() method steps are to return the result of running
+ // consume body with this and parse JSON from bytes.
+ return consumeBody(this, parseJSONFromBytes, instance)
+ },
-webidl.converters.MessageEventInit = webidl.dictionaryConverter([
- ...eventInit,
- {
- key: 'data',
- converter: webidl.converters.any,
- defaultValue: () => null
- },
- {
- key: 'origin',
- converter: webidl.converters.USVString,
- defaultValue: () => ''
- },
- {
- key: 'lastEventId',
- converter: webidl.converters.DOMString,
- defaultValue: () => ''
- },
- {
- key: 'source',
- // Node doesn't implement WindowProxy or ServiceWorker, so the only
- // valid value for source is a MessagePort.
- converter: webidl.nullableConverter(webidl.converters.MessagePort),
- defaultValue: () => null
- },
- {
- key: 'ports',
- converter: webidl.converters['sequence'],
- defaultValue: () => new Array(0)
- }
-])
+ formData () {
+ // The formData() method steps are to return the result of running
+ // consume body with this and the following step given a byte sequence bytes:
+ return consumeBody(this, (value) => {
+ // 1. Let mimeType be the result of get the MIME type with this.
+ const mimeType = bodyMimeType(this)
-webidl.converters.CloseEventInit = webidl.dictionaryConverter([
- ...eventInit,
- {
- key: 'wasClean',
- converter: webidl.converters.boolean,
- defaultValue: () => false
- },
- {
- key: 'code',
- converter: webidl.converters['unsigned short'],
- defaultValue: () => 0
- },
- {
- key: 'reason',
- converter: webidl.converters.USVString,
- defaultValue: () => ''
- }
-])
+ // 2. If mimeType is non-null, then switch on mimeType’s essence and run
+ // the corresponding steps:
+ if (mimeType !== null) {
+ switch (mimeType.essence) {
+ case 'multipart/form-data': {
+ // 1. ... [long step]
+ const parsed = multipartFormDataParser(value, mimeType)
-webidl.converters.ErrorEventInit = webidl.dictionaryConverter([
- ...eventInit,
- {
- key: 'message',
- converter: webidl.converters.DOMString,
- defaultValue: () => ''
- },
- {
- key: 'filename',
- converter: webidl.converters.USVString,
- defaultValue: () => ''
- },
- {
- key: 'lineno',
- converter: webidl.converters['unsigned long'],
- defaultValue: () => 0
- },
- {
- key: 'colno',
- converter: webidl.converters['unsigned long'],
- defaultValue: () => 0
- },
- {
- key: 'error',
- converter: webidl.converters.any
- }
-])
+ // 2. If that fails for some reason, then throw a TypeError.
+ if (parsed === 'failure') {
+ throw new TypeError('Failed to parse body as FormData.')
+ }
-module.exports = {
- MessageEvent,
- CloseEvent,
- ErrorEvent,
- createFastMessageEvent
-}
+ // 3. Return a new FormData object, appending each entry,
+ // resulting from the parsing operation, to its entry list.
+ const fd = new FormData()
+ fd[kState] = parsed
+ return fd
+ }
+ case 'application/x-www-form-urlencoded': {
+ // 1. Let entries be the result of parsing bytes.
+ const entries = new URLSearchParams(value.toString())
-/***/ }),
+ // 2. If entries is failure, then throw a TypeError.
-/***/ 3055:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 3. Return a new FormData object whose entry list is entries.
+ const fd = new FormData()
+ for (const [name, value] of entries) {
+ fd.append(name, value)
+ }
+ return fd
+ }
+ }
+ }
-const { maxUnsigned16Bit } = __nccwpck_require__(4411)
+ // 3. Throw a TypeError.
+ throw new TypeError(
+ 'Content-Type was not one of "multipart/form-data" or "application/x-www-form-urlencoded".'
+ )
+ }, instance)
+ },
-const BUFFER_SIZE = 16386
+ bytes () {
+ // The bytes() method steps are to return the result of running consume body
+ // with this and the following step given a byte sequence bytes: return the
+ // result of creating a Uint8Array from bytes in this’s relevant realm.
+ return consumeBody(this, (bytes) => {
+ return new Uint8Array(bytes)
+ }, instance)
+ }
+ }
-/** @type {import('crypto')} */
-let crypto
-let buffer = null
-let bufIdx = BUFFER_SIZE
+ return methods
+}
-try {
- crypto = __nccwpck_require__(7598)
-/* c8 ignore next 3 */
-} catch {
- crypto = {
- // not full compatibility, but minimum.
- randomFillSync: function randomFillSync (buffer, _offset, _size) {
- for (let i = 0; i < buffer.length; ++i) {
- buffer[i] = Math.random() * 255 | 0
- }
- return buffer
- }
- }
+function mixinBody (prototype) {
+ Object.assign(prototype.prototype, bodyMixinMethods(prototype))
}
-function generateMask () {
- if (bufIdx === BUFFER_SIZE) {
- bufIdx = 0
- crypto.randomFillSync((buffer ??= Buffer.allocUnsafe(BUFFER_SIZE)), 0, BUFFER_SIZE)
- }
- return [buffer[bufIdx++], buffer[bufIdx++], buffer[bufIdx++], buffer[bufIdx++]]
-}
+/**
+ * @see https://fetch.spec.whatwg.org/#concept-body-consume-body
+ * @param {Response|Request} object
+ * @param {(value: unknown) => unknown} convertBytesToJSValue
+ * @param {Response|Request} instance
+ */
+async function consumeBody (object, convertBytesToJSValue, instance) {
+ webidl.brandCheck(object, instance)
-class WebsocketFrameSend {
- /**
- * @param {Buffer|undefined} data
- */
- constructor (data) {
- this.frameData = data
+ // 1. If object is unusable, then return a promise rejected
+ // with a TypeError.
+ if (bodyUnusable(object)) {
+ throw new TypeError('Body is unusable: Body has already been read')
}
- createFrame (opcode) {
- const frameData = this.frameData
- const maskKey = generateMask()
- const bodyLength = frameData?.byteLength ?? 0
+ throwIfAborted(object[kState])
- /** @type {number} */
- let payloadLength = bodyLength // 0-125
- let offset = 6
+ // 2. Let promise be a new promise.
+ const promise = createDeferredPromise()
- if (bodyLength > maxUnsigned16Bit) {
- offset += 8 // payload length is next 8 bytes
- payloadLength = 127
- } else if (bodyLength > 125) {
- offset += 2 // payload length is next 2 bytes
- payloadLength = 126
+ // 3. Let errorSteps given error be to reject promise with error.
+ const errorSteps = (error) => promise.reject(error)
+
+ // 4. Let successSteps given a byte sequence data be to resolve
+ // promise with the result of running convertBytesToJSValue
+ // with data. If that threw an exception, then run errorSteps
+ // with that exception.
+ const successSteps = (data) => {
+ try {
+ promise.resolve(convertBytesToJSValue(data))
+ } catch (e) {
+ errorSteps(e)
}
+ }
- const buffer = Buffer.allocUnsafe(bodyLength + offset)
+ // 5. If object’s body is null, then run successSteps with an
+ // empty byte sequence.
+ if (object[kState].body == null) {
+ successSteps(Buffer.allocUnsafe(0))
+ return promise.promise
+ }
- // Clear first 2 bytes, everything else is overwritten
- buffer[0] = buffer[1] = 0
- buffer[0] |= 0x80 // FIN
- buffer[0] = (buffer[0] & 0xF0) + opcode // opcode
+ // 6. Otherwise, fully read object’s body given successSteps,
+ // errorSteps, and object’s relevant global object.
+ await fullyReadBody(object[kState].body, successSteps, errorSteps)
- /*! ws. MIT License. Einar Otto Stangvik */
- buffer[offset - 4] = maskKey[0]
- buffer[offset - 3] = maskKey[1]
- buffer[offset - 2] = maskKey[2]
- buffer[offset - 1] = maskKey[3]
+ // 7. Return promise.
+ return promise.promise
+}
- buffer[1] = payloadLength
+// https://fetch.spec.whatwg.org/#body-unusable
+function bodyUnusable (object) {
+ const body = object[kState].body
- if (payloadLength === 126) {
- buffer.writeUInt16BE(bodyLength, 2)
- } else if (payloadLength === 127) {
- // Clear extended payload length
- buffer[2] = buffer[3] = 0
- buffer.writeUIntBE(bodyLength, 4, 6)
- }
+ // An object including the Body interface mixin is
+ // said to be unusable if its body is non-null and
+ // its body’s stream is disturbed or locked.
+ return body != null && (body.stream.locked || util.isDisturbed(body.stream))
+}
- buffer[1] |= 0x80 // MASK
+/**
+ * @see https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value
+ * @param {Uint8Array} bytes
+ */
+function parseJSONFromBytes (bytes) {
+ return JSON.parse(utf8DecodeBytes(bytes))
+}
- // mask body
- for (let i = 0; i < bodyLength; ++i) {
- buffer[offset + i] = frameData[i] ^ maskKey[i & 3]
- }
+/**
+ * @see https://fetch.spec.whatwg.org/#concept-body-mime-type
+ * @param {import('./response').Response|import('./request').Request} requestOrResponse
+ */
+function bodyMimeType (requestOrResponse) {
+ // 1. Let headers be null.
+ // 2. If requestOrResponse is a Request object, then set headers to requestOrResponse’s request’s header list.
+ // 3. Otherwise, set headers to requestOrResponse’s response’s header list.
+ /** @type {import('./headers').HeadersList} */
+ const headers = requestOrResponse[kState].headersList
- return buffer
+ // 4. Let mimeType be the result of extracting a MIME type from headers.
+ const mimeType = extractMimeType(headers)
+
+ // 5. If mimeType is failure, then return null.
+ if (mimeType === 'failure') {
+ return null
}
+
+ // 6. Return mimeType.
+ return mimeType
}
module.exports = {
- WebsocketFrameSend
+ extractBody,
+ safelyExtractBody,
+ cloneBody,
+ mixinBody,
+ streamRegistry,
+ hasFinalizationRegistry,
+ bodyUnusable
}
/***/ }),
-/***/ 4836:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
+/***/ 4495:
+/***/ ((module) => {
-const { createInflateRaw, Z_DEFAULT_WINDOWBITS } = __nccwpck_require__(8522)
-const { isValidClientWindowBits } = __nccwpck_require__(2148)
-const tail = Buffer.from([0x00, 0x00, 0xff, 0xff])
-const kBuffer = Symbol('kBuffer')
-const kLength = Symbol('kLength')
+const corsSafeListedMethods = /** @type {const} */ (['GET', 'HEAD', 'POST'])
+const corsSafeListedMethodsSet = new Set(corsSafeListedMethods)
-class PerMessageDeflate {
- /** @type {import('node:zlib').InflateRaw} */
- #inflate
+const nullBodyStatus = /** @type {const} */ ([101, 204, 205, 304])
- #options = {}
+const redirectStatus = /** @type {const} */ ([301, 302, 303, 307, 308])
+const redirectStatusSet = new Set(redirectStatus)
- constructor (extensions) {
- this.#options.serverNoContextTakeover = extensions.has('server_no_context_takeover')
- this.#options.serverMaxWindowBits = extensions.get('server_max_window_bits')
- }
+/**
+ * @see https://fetch.spec.whatwg.org/#block-bad-port
+ */
+const badPorts = /** @type {const} */ ([
+ '1', '7', '9', '11', '13', '15', '17', '19', '20', '21', '22', '23', '25', '37', '42', '43', '53', '69', '77', '79',
+ '87', '95', '101', '102', '103', '104', '109', '110', '111', '113', '115', '117', '119', '123', '135', '137',
+ '139', '143', '161', '179', '389', '427', '465', '512', '513', '514', '515', '526', '530', '531', '532',
+ '540', '548', '554', '556', '563', '587', '601', '636', '989', '990', '993', '995', '1719', '1720', '1723',
+ '2049', '3659', '4045', '4190', '5060', '5061', '6000', '6566', '6665', '6666', '6667', '6668', '6669', '6679',
+ '6697', '10080'
+])
+const badPortsSet = new Set(badPorts)
- decompress (chunk, fin, callback) {
- // An endpoint uses the following algorithm to decompress a message.
- // 1. Append 4 octets of 0x00 0x00 0xff 0xff to the tail end of the
- // payload of the message.
- // 2. Decompress the resulting data using DEFLATE.
+/**
+ * @see https://w3c.github.io/webappsec-referrer-policy/#referrer-policies
+ */
+const referrerPolicy = /** @type {const} */ ([
+ '',
+ 'no-referrer',
+ 'no-referrer-when-downgrade',
+ 'same-origin',
+ 'origin',
+ 'strict-origin',
+ 'origin-when-cross-origin',
+ 'strict-origin-when-cross-origin',
+ 'unsafe-url'
+])
+const referrerPolicySet = new Set(referrerPolicy)
- if (!this.#inflate) {
- let windowBits = Z_DEFAULT_WINDOWBITS
+const requestRedirect = /** @type {const} */ (['follow', 'manual', 'error'])
- if (this.#options.serverMaxWindowBits) { // empty values default to Z_DEFAULT_WINDOWBITS
- if (!isValidClientWindowBits(this.#options.serverMaxWindowBits)) {
- callback(new Error('Invalid server_max_window_bits'))
- return
- }
+const safeMethods = /** @type {const} */ (['GET', 'HEAD', 'OPTIONS', 'TRACE'])
+const safeMethodsSet = new Set(safeMethods)
- windowBits = Number.parseInt(this.#options.serverMaxWindowBits)
- }
+const requestMode = /** @type {const} */ (['navigate', 'same-origin', 'no-cors', 'cors'])
- this.#inflate = createInflateRaw({ windowBits })
- this.#inflate[kBuffer] = []
- this.#inflate[kLength] = 0
+const requestCredentials = /** @type {const} */ (['omit', 'same-origin', 'include'])
- this.#inflate.on('data', (data) => {
- this.#inflate[kBuffer].push(data)
- this.#inflate[kLength] += data.length
- })
+const requestCache = /** @type {const} */ ([
+ 'default',
+ 'no-store',
+ 'reload',
+ 'no-cache',
+ 'force-cache',
+ 'only-if-cached'
+])
- this.#inflate.on('error', (err) => {
- this.#inflate = null
- callback(err)
- })
- }
+/**
+ * @see https://fetch.spec.whatwg.org/#request-body-header-name
+ */
+const requestBodyHeader = /** @type {const} */ ([
+ 'content-encoding',
+ 'content-language',
+ 'content-location',
+ 'content-type',
+ // See https://github.com/nodejs/undici/issues/2021
+ // 'Content-Length' is a forbidden header name, which is typically
+ // removed in the Headers implementation. However, undici doesn't
+ // filter out headers, so we add it here.
+ 'content-length'
+])
- this.#inflate.write(chunk)
- if (fin) {
- this.#inflate.write(tail)
- }
+/**
+ * @see https://fetch.spec.whatwg.org/#enumdef-requestduplex
+ */
+const requestDuplex = /** @type {const} */ ([
+ 'half'
+])
- this.#inflate.flush(() => {
- const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength])
+/**
+ * @see http://fetch.spec.whatwg.org/#forbidden-method
+ */
+const forbiddenMethods = /** @type {const} */ (['CONNECT', 'TRACE', 'TRACK'])
+const forbiddenMethodsSet = new Set(forbiddenMethods)
- this.#inflate[kBuffer].length = 0
- this.#inflate[kLength] = 0
+const subresource = /** @type {const} */ ([
+ 'audio',
+ 'audioworklet',
+ 'font',
+ 'image',
+ 'manifest',
+ 'paintworklet',
+ 'script',
+ 'style',
+ 'track',
+ 'video',
+ 'xslt',
+ ''
+])
+const subresourceSet = new Set(subresource)
- callback(null, full)
- })
- }
+module.exports = {
+ subresource,
+ forbiddenMethods,
+ requestBodyHeader,
+ referrerPolicy,
+ requestRedirect,
+ requestMode,
+ requestCredentials,
+ requestCache,
+ redirectStatus,
+ corsSafeListedMethods,
+ nullBodyStatus,
+ safeMethods,
+ badPorts,
+ requestDuplex,
+ subresourceSet,
+ badPortsSet,
+ redirectStatusSet,
+ corsSafeListedMethodsSet,
+ safeMethodsSet,
+ forbiddenMethodsSet,
+ referrerPolicySet
}
-module.exports = { PerMessageDeflate }
-
/***/ }),
-/***/ 8265:
+/***/ 1900:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const { Writable } = __nccwpck_require__(7075)
const assert = __nccwpck_require__(4589)
-const { parserStates, opcodes, states, emptyBuffer, sentCloseFrameState } = __nccwpck_require__(4411)
-const { kReadyState, kSentClose, kResponse, kReceivedClose } = __nccwpck_require__(2679)
-const { channels } = __nccwpck_require__(4567)
-const {
- isValidStatusCode,
- isValidOpcode,
- failWebsocketConnection,
- websocketMessageReceived,
- utf8Decode,
- isControlFrame,
- isTextBinaryFrame,
- isContinuationFrame
-} = __nccwpck_require__(2148)
-const { WebsocketFrameSend } = __nccwpck_require__(3055)
-const { closeWebSocketConnection } = __nccwpck_require__(7032)
-const { PerMessageDeflate } = __nccwpck_require__(4836)
-
-// This code was influenced by ws released under the MIT license.
-// Copyright (c) 2011 Einar Otto Stangvik
-// Copyright (c) 2013 Arnout Kazemier and contributors
-// Copyright (c) 2016 Luigi Pinca and contributors
-class ByteParser extends Writable {
- #buffers = []
- #byteOffset = 0
- #loop = false
+const encoder = new TextEncoder()
- #state = parserStates.INFO
+/**
+ * @see https://mimesniff.spec.whatwg.org/#http-token-code-point
+ */
+const HTTP_TOKEN_CODEPOINTS = /^[!#$%&'*+\-.^_|~A-Za-z0-9]+$/
+const HTTP_WHITESPACE_REGEX = /[\u000A\u000D\u0009\u0020]/ // eslint-disable-line
+const ASCII_WHITESPACE_REPLACE_REGEX = /[\u0009\u000A\u000C\u000D\u0020]/g // eslint-disable-line
+/**
+ * @see https://mimesniff.spec.whatwg.org/#http-quoted-string-token-code-point
+ */
+const HTTP_QUOTED_STRING_TOKENS = /^[\u0009\u0020-\u007E\u0080-\u00FF]+$/ // eslint-disable-line
- #info = {}
- #fragments = []
+// https://fetch.spec.whatwg.org/#data-url-processor
+/** @param {URL} dataURL */
+function dataURLProcessor (dataURL) {
+ // 1. Assert: dataURL’s scheme is "data".
+ assert(dataURL.protocol === 'data:')
- /** @type {Map} */
- #extensions
+ // 2. Let input be the result of running the URL
+ // serializer on dataURL with exclude fragment
+ // set to true.
+ let input = URLSerializer(dataURL, true)
- constructor (ws, extensions) {
- super()
+ // 3. Remove the leading "data:" string from input.
+ input = input.slice(5)
- this.ws = ws
- this.#extensions = extensions == null ? new Map() : extensions
+ // 4. Let position point at the start of input.
+ const position = { position: 0 }
- if (this.#extensions.has('permessage-deflate')) {
- this.#extensions.set('permessage-deflate', new PerMessageDeflate(extensions))
- }
- }
+ // 5. Let mimeType be the result of collecting a
+ // sequence of code points that are not equal
+ // to U+002C (,), given position.
+ let mimeType = collectASequenceOfCodePointsFast(
+ ',',
+ input,
+ position
+ )
- /**
- * @param {Buffer} chunk
- * @param {() => void} callback
- */
- _write (chunk, _, callback) {
- this.#buffers.push(chunk)
- this.#byteOffset += chunk.length
- this.#loop = true
+ // 6. Strip leading and trailing ASCII whitespace
+ // from mimeType.
+ // Undici implementation note: we need to store the
+ // length because if the mimetype has spaces removed,
+ // the wrong amount will be sliced from the input in
+ // step #9
+ const mimeTypeLength = mimeType.length
+ mimeType = removeASCIIWhitespace(mimeType, true, true)
- this.run(callback)
+ // 7. If position is past the end of input, then
+ // return failure
+ if (position.position >= input.length) {
+ return 'failure'
}
- /**
- * Runs whenever a new chunk is received.
- * Callback is called whenever there are no more chunks buffering,
- * or not enough bytes are buffered to parse.
- */
- run (callback) {
- while (this.#loop) {
- if (this.#state === parserStates.INFO) {
- // If there aren't enough bytes to parse the payload length, etc.
- if (this.#byteOffset < 2) {
- return callback()
- }
+ // 8. Advance position by 1.
+ position.position++
- const buffer = this.consume(2)
- const fin = (buffer[0] & 0x80) !== 0
- const opcode = buffer[0] & 0x0F
- const masked = (buffer[1] & 0x80) === 0x80
+ // 9. Let encodedBody be the remainder of input.
+ const encodedBody = input.slice(mimeTypeLength + 1)
- const fragmented = !fin && opcode !== opcodes.CONTINUATION
- const payloadLength = buffer[1] & 0x7F
+ // 10. Let body be the percent-decoding of encodedBody.
+ let body = stringPercentDecode(encodedBody)
- const rsv1 = buffer[0] & 0x40
- const rsv2 = buffer[0] & 0x20
- const rsv3 = buffer[0] & 0x10
+ // 11. If mimeType ends with U+003B (;), followed by
+ // zero or more U+0020 SPACE, followed by an ASCII
+ // case-insensitive match for "base64", then:
+ if (/;(\u0020){0,}base64$/i.test(mimeType)) {
+ // 1. Let stringBody be the isomorphic decode of body.
+ const stringBody = isomorphicDecode(body)
- if (!isValidOpcode(opcode)) {
- failWebsocketConnection(this.ws, 'Invalid opcode received')
- return callback()
- }
+ // 2. Set body to the forgiving-base64 decode of
+ // stringBody.
+ body = forgivingBase64(stringBody)
- if (masked) {
- failWebsocketConnection(this.ws, 'Frame cannot be masked')
- return callback()
- }
+ // 3. If body is failure, then return failure.
+ if (body === 'failure') {
+ return 'failure'
+ }
- // MUST be 0 unless an extension is negotiated that defines meanings
- // for non-zero values. If a nonzero value is received and none of
- // the negotiated extensions defines the meaning of such a nonzero
- // value, the receiving endpoint MUST _Fail the WebSocket
- // Connection_.
- // This document allocates the RSV1 bit of the WebSocket header for
- // PMCEs and calls the bit the "Per-Message Compressed" bit. On a
- // WebSocket connection where a PMCE is in use, this bit indicates
- // whether a message is compressed or not.
- if (rsv1 !== 0 && !this.#extensions.has('permessage-deflate')) {
- failWebsocketConnection(this.ws, 'Expected RSV1 to be clear.')
- return
- }
+ // 4. Remove the last 6 code points from mimeType.
+ mimeType = mimeType.slice(0, -6)
- if (rsv2 !== 0 || rsv3 !== 0) {
- failWebsocketConnection(this.ws, 'RSV1, RSV2, RSV3 must be clear')
- return
- }
+ // 5. Remove trailing U+0020 SPACE code points from mimeType,
+ // if any.
+ mimeType = mimeType.replace(/(\u0020)+$/, '')
- if (fragmented && !isTextBinaryFrame(opcode)) {
- // Only text and binary frames can be fragmented
- failWebsocketConnection(this.ws, 'Invalid frame type was fragmented.')
- return
- }
+ // 6. Remove the last U+003B (;) code point from mimeType.
+ mimeType = mimeType.slice(0, -1)
+ }
- // If we are already parsing a text/binary frame and do not receive either
- // a continuation frame or close frame, fail the connection.
- if (isTextBinaryFrame(opcode) && this.#fragments.length > 0) {
- failWebsocketConnection(this.ws, 'Expected continuation frame')
- return
- }
+ // 12. If mimeType starts with U+003B (;), then prepend
+ // "text/plain" to mimeType.
+ if (mimeType.startsWith(';')) {
+ mimeType = 'text/plain' + mimeType
+ }
- if (this.#info.fragmented && fragmented) {
- // A fragmented frame can't be fragmented itself
- failWebsocketConnection(this.ws, 'Fragmented frame exceeded 125 bytes.')
- return
- }
+ // 13. Let mimeTypeRecord be the result of parsing
+ // mimeType.
+ let mimeTypeRecord = parseMIMEType(mimeType)
- // "All control frames MUST have a payload length of 125 bytes or less
- // and MUST NOT be fragmented."
- if ((payloadLength > 125 || fragmented) && isControlFrame(opcode)) {
- failWebsocketConnection(this.ws, 'Control frame either too large or fragmented')
- return
- }
+ // 14. If mimeTypeRecord is failure, then set
+ // mimeTypeRecord to text/plain;charset=US-ASCII.
+ if (mimeTypeRecord === 'failure') {
+ mimeTypeRecord = parseMIMEType('text/plain;charset=US-ASCII')
+ }
- if (isContinuationFrame(opcode) && this.#fragments.length === 0 && !this.#info.compressed) {
- failWebsocketConnection(this.ws, 'Unexpected continuation frame')
- return
- }
+ // 15. Return a new data: URL struct whose MIME
+ // type is mimeTypeRecord and body is body.
+ // https://fetch.spec.whatwg.org/#data-url-struct
+ return { mimeType: mimeTypeRecord, body }
+}
- if (payloadLength <= 125) {
- this.#info.payloadLength = payloadLength
- this.#state = parserStates.READ_DATA
- } else if (payloadLength === 126) {
- this.#state = parserStates.PAYLOADLENGTH_16
- } else if (payloadLength === 127) {
- this.#state = parserStates.PAYLOADLENGTH_64
- }
+// https://url.spec.whatwg.org/#concept-url-serializer
+/**
+ * @param {URL} url
+ * @param {boolean} excludeFragment
+ */
+function URLSerializer (url, excludeFragment = false) {
+ if (!excludeFragment) {
+ return url.href
+ }
- if (isTextBinaryFrame(opcode)) {
- this.#info.binaryType = opcode
- this.#info.compressed = rsv1 !== 0
- }
+ const href = url.href
+ const hashLength = url.hash.length
- this.#info.opcode = opcode
- this.#info.masked = masked
- this.#info.fin = fin
- this.#info.fragmented = fragmented
- } else if (this.#state === parserStates.PAYLOADLENGTH_16) {
- if (this.#byteOffset < 2) {
- return callback()
- }
+ const serialized = hashLength === 0 ? href : href.substring(0, href.length - hashLength)
- const buffer = this.consume(2)
+ if (!hashLength && href.endsWith('#')) {
+ return serialized.slice(0, -1)
+ }
- this.#info.payloadLength = buffer.readUInt16BE(0)
- this.#state = parserStates.READ_DATA
- } else if (this.#state === parserStates.PAYLOADLENGTH_64) {
- if (this.#byteOffset < 8) {
- return callback()
- }
+ return serialized
+}
- const buffer = this.consume(8)
- const upper = buffer.readUInt32BE(0)
+// https://infra.spec.whatwg.org/#collect-a-sequence-of-code-points
+/**
+ * @param {(char: string) => boolean} condition
+ * @param {string} input
+ * @param {{ position: number }} position
+ */
+function collectASequenceOfCodePoints (condition, input, position) {
+ // 1. Let result be the empty string.
+ let result = ''
- // 2^31 is the maximum bytes an arraybuffer can contain
- // on 32-bit systems. Although, on 64-bit systems, this is
- // 2^53-1 bytes.
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_array_length
- // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/common/globals.h;drc=1946212ac0100668f14eb9e2843bdd846e510a1e;bpv=1;bpt=1;l=1275
- // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/js-array-buffer.h;l=34;drc=1946212ac0100668f14eb9e2843bdd846e510a1e
- if (upper > 2 ** 31 - 1) {
- failWebsocketConnection(this.ws, 'Received payload length > 2^31 bytes.')
- return
- }
+ // 2. While position doesn’t point past the end of input and the
+ // code point at position within input meets the condition condition:
+ while (position.position < input.length && condition(input[position.position])) {
+ // 1. Append that code point to the end of result.
+ result += input[position.position]
- const lower = buffer.readUInt32BE(4)
+ // 2. Advance position by 1.
+ position.position++
+ }
- this.#info.payloadLength = (upper << 8) + lower
- this.#state = parserStates.READ_DATA
- } else if (this.#state === parserStates.READ_DATA) {
- if (this.#byteOffset < this.#info.payloadLength) {
- return callback()
- }
+ // 3. Return result.
+ return result
+}
- const body = this.consume(this.#info.payloadLength)
+/**
+ * A faster collectASequenceOfCodePoints that only works when comparing a single character.
+ * @param {string} char
+ * @param {string} input
+ * @param {{ position: number }} position
+ */
+function collectASequenceOfCodePointsFast (char, input, position) {
+ const idx = input.indexOf(char, position.position)
+ const start = position.position
- if (isControlFrame(this.#info.opcode)) {
- this.#loop = this.parseControlFrame(body)
- this.#state = parserStates.INFO
- } else {
- if (!this.#info.compressed) {
- this.#fragments.push(body)
+ if (idx === -1) {
+ position.position = input.length
+ return input.slice(start)
+ }
- // If the frame is not fragmented, a message has been received.
- // If the frame is fragmented, it will terminate with a fin bit set
- // and an opcode of 0 (continuation), therefore we handle that when
- // parsing continuation frames, not here.
- if (!this.#info.fragmented && this.#info.fin) {
- const fullMessage = Buffer.concat(this.#fragments)
- websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage)
- this.#fragments.length = 0
- }
+ position.position = idx
+ return input.slice(start, position.position)
+}
- this.#state = parserStates.INFO
- } else {
- this.#extensions.get('permessage-deflate').decompress(body, this.#info.fin, (error, data) => {
- if (error) {
- closeWebSocketConnection(this.ws, 1007, error.message, error.message.length)
- return
- }
+// https://url.spec.whatwg.org/#string-percent-decode
+/** @param {string} input */
+function stringPercentDecode (input) {
+ // 1. Let bytes be the UTF-8 encoding of input.
+ const bytes = encoder.encode(input)
- this.#fragments.push(data)
+ // 2. Return the percent-decoding of bytes.
+ return percentDecode(bytes)
+}
- if (!this.#info.fin) {
- this.#state = parserStates.INFO
- this.#loop = true
- this.run(callback)
- return
- }
+/**
+ * @param {number} byte
+ */
+function isHexCharByte (byte) {
+ // 0-9 A-F a-f
+ return (byte >= 0x30 && byte <= 0x39) || (byte >= 0x41 && byte <= 0x46) || (byte >= 0x61 && byte <= 0x66)
+}
- websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments))
+/**
+ * @param {number} byte
+ */
+function hexByteToNumber (byte) {
+ return (
+ // 0-9
+ byte >= 0x30 && byte <= 0x39
+ ? (byte - 48)
+ // Convert to uppercase
+ // ((byte & 0xDF) - 65) + 10
+ : ((byte & 0xDF) - 55)
+ )
+}
- this.#loop = true
- this.#state = parserStates.INFO
- this.#fragments.length = 0
- this.run(callback)
- })
+// https://url.spec.whatwg.org/#percent-decode
+/** @param {Uint8Array} input */
+function percentDecode (input) {
+ const length = input.length
+ // 1. Let output be an empty byte sequence.
+ /** @type {Uint8Array} */
+ const output = new Uint8Array(length)
+ let j = 0
+ // 2. For each byte byte in input:
+ for (let i = 0; i < length; ++i) {
+ const byte = input[i]
- this.#loop = false
- break
- }
- }
- }
- }
- }
+ // 1. If byte is not 0x25 (%), then append byte to output.
+ if (byte !== 0x25) {
+ output[j++] = byte
- /**
- * Take n bytes from the buffered Buffers
- * @param {number} n
- * @returns {Buffer}
- */
- consume (n) {
- if (n > this.#byteOffset) {
- throw new Error('Called consume() before buffers satiated.')
- } else if (n === 0) {
- return emptyBuffer
- }
+ // 2. Otherwise, if byte is 0x25 (%) and the next two bytes
+ // after byte in input are not in the ranges
+ // 0x30 (0) to 0x39 (9), 0x41 (A) to 0x46 (F),
+ // and 0x61 (a) to 0x66 (f), all inclusive, append byte
+ // to output.
+ } else if (
+ byte === 0x25 &&
+ !(isHexCharByte(input[i + 1]) && isHexCharByte(input[i + 2]))
+ ) {
+ output[j++] = 0x25
- if (this.#buffers[0].length === n) {
- this.#byteOffset -= this.#buffers[0].length
- return this.#buffers.shift()
+ // 3. Otherwise:
+ } else {
+ // 1. Let bytePoint be the two bytes after byte in input,
+ // decoded, and then interpreted as hexadecimal number.
+ // 2. Append a byte whose value is bytePoint to output.
+ output[j++] = (hexByteToNumber(input[i + 1]) << 4) | hexByteToNumber(input[i + 2])
+
+ // 3. Skip the next two bytes in input.
+ i += 2
}
+ }
- const buffer = Buffer.allocUnsafe(n)
- let offset = 0
+ // 3. Return output.
+ return length === j ? output : output.subarray(0, j)
+}
- while (offset !== n) {
- const next = this.#buffers[0]
- const { length } = next
+// https://mimesniff.spec.whatwg.org/#parse-a-mime-type
+/** @param {string} input */
+function parseMIMEType (input) {
+ // 1. Remove any leading and trailing HTTP whitespace
+ // from input.
+ input = removeHTTPWhitespace(input, true, true)
- if (length + offset === n) {
- buffer.set(this.#buffers.shift(), offset)
- break
- } else if (length + offset > n) {
- buffer.set(next.subarray(0, n - offset), offset)
- this.#buffers[0] = next.subarray(n - offset)
- break
- } else {
- buffer.set(this.#buffers.shift(), offset)
- offset += next.length
- }
- }
+ // 2. Let position be a position variable for input,
+ // initially pointing at the start of input.
+ const position = { position: 0 }
- this.#byteOffset -= n
+ // 3. Let type be the result of collecting a sequence
+ // of code points that are not U+002F (/) from
+ // input, given position.
+ const type = collectASequenceOfCodePointsFast(
+ '/',
+ input,
+ position
+ )
- return buffer
+ // 4. If type is the empty string or does not solely
+ // contain HTTP token code points, then return failure.
+ // https://mimesniff.spec.whatwg.org/#http-token-code-point
+ if (type.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(type)) {
+ return 'failure'
}
- parseCloseBody (data) {
- assert(data.length !== 1)
-
- // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5
- /** @type {number|undefined} */
- let code
+ // 5. If position is past the end of input, then return
+ // failure
+ if (position.position > input.length) {
+ return 'failure'
+ }
- if (data.length >= 2) {
- // _The WebSocket Connection Close Code_ is
- // defined as the status code (Section 7.4) contained in the first Close
- // control frame received by the application
- code = data.readUInt16BE(0)
- }
+ // 6. Advance position by 1. (This skips past U+002F (/).)
+ position.position++
- if (code !== undefined && !isValidStatusCode(code)) {
- return { code: 1002, reason: 'Invalid status code', error: true }
- }
+ // 7. Let subtype be the result of collecting a sequence of
+ // code points that are not U+003B (;) from input, given
+ // position.
+ let subtype = collectASequenceOfCodePointsFast(
+ ';',
+ input,
+ position
+ )
- // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6
- /** @type {Buffer} */
- let reason = data.subarray(2)
+ // 8. Remove any trailing HTTP whitespace from subtype.
+ subtype = removeHTTPWhitespace(subtype, false, true)
- // Remove BOM
- if (reason[0] === 0xEF && reason[1] === 0xBB && reason[2] === 0xBF) {
- reason = reason.subarray(3)
- }
+ // 9. If subtype is the empty string or does not solely
+ // contain HTTP token code points, then return failure.
+ if (subtype.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(subtype)) {
+ return 'failure'
+ }
- try {
- reason = utf8Decode(reason)
- } catch {
- return { code: 1007, reason: 'Invalid UTF-8', error: true }
- }
+ const typeLowercase = type.toLowerCase()
+ const subtypeLowercase = subtype.toLowerCase()
- return { code, reason, error: false }
+ // 10. Let mimeType be a new MIME type record whose type
+ // is type, in ASCII lowercase, and subtype is subtype,
+ // in ASCII lowercase.
+ // https://mimesniff.spec.whatwg.org/#mime-type
+ const mimeType = {
+ type: typeLowercase,
+ subtype: subtypeLowercase,
+ /** @type {Map} */
+ parameters: new Map(),
+ // https://mimesniff.spec.whatwg.org/#mime-type-essence
+ essence: `${typeLowercase}/${subtypeLowercase}`
}
- /**
- * Parses control frames.
- * @param {Buffer} body
- */
- parseControlFrame (body) {
- const { opcode, payloadLength } = this.#info
+ // 11. While position is not past the end of input:
+ while (position.position < input.length) {
+ // 1. Advance position by 1. (This skips past U+003B (;).)
+ position.position++
- if (opcode === opcodes.CLOSE) {
- if (payloadLength === 1) {
- failWebsocketConnection(this.ws, 'Received close frame with a 1-byte body.')
- return false
- }
+ // 2. Collect a sequence of code points that are HTTP
+ // whitespace from input given position.
+ collectASequenceOfCodePoints(
+ // https://fetch.spec.whatwg.org/#http-whitespace
+ char => HTTP_WHITESPACE_REGEX.test(char),
+ input,
+ position
+ )
- this.#info.closeInfo = this.parseCloseBody(body)
+ // 3. Let parameterName be the result of collecting a
+ // sequence of code points that are not U+003B (;)
+ // or U+003D (=) from input, given position.
+ let parameterName = collectASequenceOfCodePoints(
+ (char) => char !== ';' && char !== '=',
+ input,
+ position
+ )
- if (this.#info.closeInfo.error) {
- const { code, reason } = this.#info.closeInfo
+ // 4. Set parameterName to parameterName, in ASCII
+ // lowercase.
+ parameterName = parameterName.toLowerCase()
- closeWebSocketConnection(this.ws, code, reason, reason.length)
- failWebsocketConnection(this.ws, reason)
- return false
+ // 5. If position is not past the end of input, then:
+ if (position.position < input.length) {
+ // 1. If the code point at position within input is
+ // U+003B (;), then continue.
+ if (input[position.position] === ';') {
+ continue
}
- if (this.ws[kSentClose] !== sentCloseFrameState.SENT) {
- // If an endpoint receives a Close frame and did not previously send a
- // Close frame, the endpoint MUST send a Close frame in response. (When
- // sending a Close frame in response, the endpoint typically echos the
- // status code it received.)
- let body = emptyBuffer
- if (this.#info.closeInfo.code) {
- body = Buffer.allocUnsafe(2)
- body.writeUInt16BE(this.#info.closeInfo.code, 0)
- }
- const closeFrame = new WebsocketFrameSend(body)
+ // 2. Advance position by 1. (This skips past U+003D (=).)
+ position.position++
+ }
- this.ws[kResponse].socket.write(
- closeFrame.createFrame(opcodes.CLOSE),
- (err) => {
- if (!err) {
- this.ws[kSentClose] = sentCloseFrameState.SENT
- }
- }
- )
- }
+ // 6. If position is past the end of input, then break.
+ if (position.position > input.length) {
+ break
+ }
- // Upon either sending or receiving a Close control frame, it is said
- // that _The WebSocket Closing Handshake is Started_ and that the
- // WebSocket connection is in the CLOSING state.
- this.ws[kReadyState] = states.CLOSING
- this.ws[kReceivedClose] = true
+ // 7. Let parameterValue be null.
+ let parameterValue = null
- return false
- } else if (opcode === opcodes.PING) {
- // Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in
- // response, unless it already received a Close frame.
- // A Pong frame sent in response to a Ping frame must have identical
- // "Application data"
+ // 8. If the code point at position within input is
+ // U+0022 ("), then:
+ if (input[position.position] === '"') {
+ // 1. Set parameterValue to the result of collecting
+ // an HTTP quoted string from input, given position
+ // and the extract-value flag.
+ parameterValue = collectAnHTTPQuotedString(input, position, true)
- if (!this.ws[kReceivedClose]) {
- const frame = new WebsocketFrameSend(body)
+ // 2. Collect a sequence of code points that are not
+ // U+003B (;) from input, given position.
+ collectASequenceOfCodePointsFast(
+ ';',
+ input,
+ position
+ )
- this.ws[kResponse].socket.write(frame.createFrame(opcodes.PONG))
+ // 9. Otherwise:
+ } else {
+ // 1. Set parameterValue to the result of collecting
+ // a sequence of code points that are not U+003B (;)
+ // from input, given position.
+ parameterValue = collectASequenceOfCodePointsFast(
+ ';',
+ input,
+ position
+ )
- if (channels.ping.hasSubscribers) {
- channels.ping.publish({
- payload: body
- })
- }
- }
- } else if (opcode === opcodes.PONG) {
- // A Pong frame MAY be sent unsolicited. This serves as a
- // unidirectional heartbeat. A response to an unsolicited Pong frame is
- // not expected.
+ // 2. Remove any trailing HTTP whitespace from parameterValue.
+ parameterValue = removeHTTPWhitespace(parameterValue, false, true)
- if (channels.pong.hasSubscribers) {
- channels.pong.publish({
- payload: body
- })
+ // 3. If parameterValue is the empty string, then continue.
+ if (parameterValue.length === 0) {
+ continue
}
}
- return true
- }
-
- get closingInfo () {
- return this.#info.closeInfo
+ // 10. If all of the following are true
+ // - parameterName is not the empty string
+ // - parameterName solely contains HTTP token code points
+ // - parameterValue solely contains HTTP quoted-string token code points
+ // - mimeType’s parameters[parameterName] does not exist
+ // then set mimeType’s parameters[parameterName] to parameterValue.
+ if (
+ parameterName.length !== 0 &&
+ HTTP_TOKEN_CODEPOINTS.test(parameterName) &&
+ (parameterValue.length === 0 || HTTP_QUOTED_STRING_TOKENS.test(parameterValue)) &&
+ !mimeType.parameters.has(parameterName)
+ ) {
+ mimeType.parameters.set(parameterName, parameterValue)
+ }
}
-}
-module.exports = {
- ByteParser
+ // 12. Return mimeType.
+ return mimeType
}
+// https://infra.spec.whatwg.org/#forgiving-base64-decode
+/** @param {string} data */
+function forgivingBase64 (data) {
+ // 1. Remove all ASCII whitespace from data.
+ data = data.replace(ASCII_WHITESPACE_REPLACE_REGEX, '') // eslint-disable-line
-/***/ }),
-
-/***/ 1577:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ let dataLength = data.length
+ // 2. If data’s code point length divides by 4 leaving
+ // no remainder, then:
+ if (dataLength % 4 === 0) {
+ // 1. If data ends with one or two U+003D (=) code points,
+ // then remove them from data.
+ if (data.charCodeAt(dataLength - 1) === 0x003D) {
+ --dataLength
+ if (data.charCodeAt(dataLength - 1) === 0x003D) {
+ --dataLength
+ }
+ }
+ }
+ // 3. If data’s code point length divides by 4 leaving
+ // a remainder of 1, then return failure.
+ if (dataLength % 4 === 1) {
+ return 'failure'
+ }
+ // 4. If data contains a code point that is not one of
+ // U+002B (+)
+ // U+002F (/)
+ // ASCII alphanumeric
+ // then return failure.
+ if (/[^+/0-9A-Za-z]/.test(data.length === dataLength ? data : data.substring(0, dataLength))) {
+ return 'failure'
+ }
-const { WebsocketFrameSend } = __nccwpck_require__(3055)
-const { opcodes, sendHints } = __nccwpck_require__(4411)
-const FixedQueue = __nccwpck_require__(5533)
-
-/** @type {typeof Uint8Array} */
-const FastBuffer = Buffer[Symbol.species]
+ const buffer = Buffer.from(data, 'base64')
+ return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength)
+}
+// https://fetch.spec.whatwg.org/#collect-an-http-quoted-string
+// tests: https://fetch.spec.whatwg.org/#example-http-quoted-string
/**
- * @typedef {object} SendQueueNode
- * @property {Promise | null} promise
- * @property {((...args: any[]) => any)} callback
- * @property {Buffer | null} frame
+ * @param {string} input
+ * @param {{ position: number }} position
+ * @param {boolean?} extractValue
*/
+function collectAnHTTPQuotedString (input, position, extractValue) {
+ // 1. Let positionStart be position.
+ const positionStart = position.position
-class SendQueue {
- /**
- * @type {FixedQueue}
- */
- #queue = new FixedQueue()
-
- /**
- * @type {boolean}
- */
- #running = false
+ // 2. Let value be the empty string.
+ let value = ''
- /** @type {import('node:net').Socket} */
- #socket
+ // 3. Assert: the code point at position within input
+ // is U+0022 (").
+ assert(input[position.position] === '"')
- constructor (socket) {
- this.#socket = socket
- }
+ // 4. Advance position by 1.
+ position.position++
- add (item, cb, hint) {
- if (hint !== sendHints.blob) {
- const frame = createFrame(item, hint)
- if (!this.#running) {
- // fast-path
- this.#socket.write(frame, cb)
- } else {
- /** @type {SendQueueNode} */
- const node = {
- promise: null,
- callback: cb,
- frame
- }
- this.#queue.push(node)
- }
- return
- }
+ // 5. While true:
+ while (true) {
+ // 1. Append the result of collecting a sequence of code points
+ // that are not U+0022 (") or U+005C (\) from input, given
+ // position, to value.
+ value += collectASequenceOfCodePoints(
+ (char) => char !== '"' && char !== '\\',
+ input,
+ position
+ )
- /** @type {SendQueueNode} */
- const node = {
- promise: item.arrayBuffer().then((ab) => {
- node.promise = null
- node.frame = createFrame(ab, hint)
- }),
- callback: cb,
- frame: null
+ // 2. If position is past the end of input, then break.
+ if (position.position >= input.length) {
+ break
}
- this.#queue.push(node)
+ // 3. Let quoteOrBackslash be the code point at position within
+ // input.
+ const quoteOrBackslash = input[position.position]
- if (!this.#running) {
- this.#run()
- }
- }
+ // 4. Advance position by 1.
+ position.position++
- async #run () {
- this.#running = true
- const queue = this.#queue
- while (!queue.isEmpty()) {
- const node = queue.shift()
- // wait pending promise
- if (node.promise !== null) {
- await node.promise
+ // 5. If quoteOrBackslash is U+005C (\), then:
+ if (quoteOrBackslash === '\\') {
+ // 1. If position is past the end of input, then append
+ // U+005C (\) to value and break.
+ if (position.position >= input.length) {
+ value += '\\'
+ break
}
- // write
- this.#socket.write(node.frame, node.callback)
- // cleanup
- node.callback = node.frame = null
- }
- this.#running = false
- }
-}
-function createFrame (data, hint) {
- return new WebsocketFrameSend(toBuffer(data, hint)).createFrame(hint === sendHints.string ? opcodes.TEXT : opcodes.BINARY)
-}
+ // 2. Append the code point at position within input to value.
+ value += input[position.position]
-function toBuffer (data, hint) {
- switch (hint) {
- case sendHints.string:
- return Buffer.from(data)
- case sendHints.arrayBuffer:
- case sendHints.blob:
- return new FastBuffer(data)
- case sendHints.typedArray:
- return new FastBuffer(data.buffer, data.byteOffset, data.byteLength)
- }
-}
+ // 3. Advance position by 1.
+ position.position++
-module.exports = { SendQueue }
+ // 6. Otherwise:
+ } else {
+ // 1. Assert: quoteOrBackslash is U+0022 (").
+ assert(quoteOrBackslash === '"')
+ // 2. Break.
+ break
+ }
+ }
-/***/ }),
+ // 6. If the extract-value flag is set, then return value.
+ if (extractValue) {
+ return value
+ }
-/***/ 2679:
-/***/ ((module) => {
+ // 7. Return the code points from positionStart to position,
+ // inclusive, within input.
+ return input.slice(positionStart, position.position)
+}
+/**
+ * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type
+ */
+function serializeAMimeType (mimeType) {
+ assert(mimeType !== 'failure')
+ const { parameters, essence } = mimeType
+ // 1. Let serialization be the concatenation of mimeType’s
+ // type, U+002F (/), and mimeType’s subtype.
+ let serialization = essence
-module.exports = {
- kWebSocketURL: Symbol('url'),
- kReadyState: Symbol('ready state'),
- kController: Symbol('controller'),
- kResponse: Symbol('response'),
- kBinaryType: Symbol('binary type'),
- kSentClose: Symbol('sent close'),
- kReceivedClose: Symbol('received close'),
- kByteParser: Symbol('byte parser')
-}
+ // 2. For each name → value of mimeType’s parameters:
+ for (let [name, value] of parameters.entries()) {
+ // 1. Append U+003B (;) to serialization.
+ serialization += ';'
+ // 2. Append name to serialization.
+ serialization += name
-/***/ }),
+ // 3. Append U+003D (=) to serialization.
+ serialization += '='
-/***/ 2148:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 4. If value does not solely contain HTTP token code
+ // points or value is the empty string, then:
+ if (!HTTP_TOKEN_CODEPOINTS.test(value)) {
+ // 1. Precede each occurrence of U+0022 (") or
+ // U+005C (\) in value with U+005C (\).
+ value = value.replace(/(\\|")/g, '\\$1')
+ // 2. Prepend U+0022 (") to value.
+ value = '"' + value
+ // 3. Append U+0022 (") to value.
+ value += '"'
+ }
-const { kReadyState, kController, kResponse, kBinaryType, kWebSocketURL } = __nccwpck_require__(2679)
-const { states, opcodes } = __nccwpck_require__(4411)
-const { ErrorEvent, createFastMessageEvent } = __nccwpck_require__(9617)
-const { isUtf8 } = __nccwpck_require__(4573)
-const { collectASequenceOfCodePointsFast, removeHTTPWhitespace } = __nccwpck_require__(2121)
+ // 5. Append value to serialization.
+ serialization += value
+ }
-/* globals Blob */
+ // 3. Return serialization.
+ return serialization
+}
/**
- * @param {import('./websocket').WebSocket} ws
- * @returns {boolean}
+ * @see https://fetch.spec.whatwg.org/#http-whitespace
+ * @param {number} char
*/
-function isConnecting (ws) {
- // If the WebSocket connection is not yet established, and the connection
- // is not yet closed, then the WebSocket connection is in the CONNECTING state.
- return ws[kReadyState] === states.CONNECTING
+function isHTTPWhiteSpace (char) {
+ // "\r\n\t "
+ return char === 0x00d || char === 0x00a || char === 0x009 || char === 0x020
}
/**
- * @param {import('./websocket').WebSocket} ws
- * @returns {boolean}
+ * @see https://fetch.spec.whatwg.org/#http-whitespace
+ * @param {string} str
+ * @param {boolean} [leading=true]
+ * @param {boolean} [trailing=true]
*/
-function isEstablished (ws) {
- // If the server's response is validated as provided for above, it is
- // said that _The WebSocket Connection is Established_ and that the
- // WebSocket Connection is in the OPEN state.
- return ws[kReadyState] === states.OPEN
+function removeHTTPWhitespace (str, leading = true, trailing = true) {
+ return removeChars(str, leading, trailing, isHTTPWhiteSpace)
}
/**
- * @param {import('./websocket').WebSocket} ws
- * @returns {boolean}
+ * @see https://infra.spec.whatwg.org/#ascii-whitespace
+ * @param {number} char
*/
-function isClosing (ws) {
- // Upon either sending or receiving a Close control frame, it is said
- // that _The WebSocket Closing Handshake is Started_ and that the
- // WebSocket connection is in the CLOSING state.
- return ws[kReadyState] === states.CLOSING
+function isASCIIWhitespace (char) {
+ // "\r\n\t\f "
+ return char === 0x00d || char === 0x00a || char === 0x009 || char === 0x00c || char === 0x020
}
/**
- * @param {import('./websocket').WebSocket} ws
- * @returns {boolean}
+ * @see https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace
+ * @param {string} str
+ * @param {boolean} [leading=true]
+ * @param {boolean} [trailing=true]
*/
-function isClosed (ws) {
- return ws[kReadyState] === states.CLOSED
+function removeASCIIWhitespace (str, leading = true, trailing = true) {
+ return removeChars(str, leading, trailing, isASCIIWhitespace)
}
/**
- * @see https://dom.spec.whatwg.org/#concept-event-fire
- * @param {string} e
- * @param {EventTarget} target
- * @param {(...args: ConstructorParameters) => Event} eventFactory
- * @param {EventInit | undefined} eventInitDict
+ * @param {string} str
+ * @param {boolean} leading
+ * @param {boolean} trailing
+ * @param {(charCode: number) => boolean} predicate
+ * @returns
*/
-function fireEvent (e, target, eventFactory = (type, init) => new Event(type, init), eventInitDict = {}) {
- // 1. If eventConstructor is not given, then let eventConstructor be Event.
+function removeChars (str, leading, trailing, predicate) {
+ let lead = 0
+ let trail = str.length - 1
- // 2. Let event be the result of creating an event given eventConstructor,
- // in the relevant realm of target.
- // 3. Initialize event’s type attribute to e.
- const event = eventFactory(e, eventInitDict)
+ if (leading) {
+ while (lead < str.length && predicate(str.charCodeAt(lead))) lead++
+ }
- // 4. Initialize any other IDL attributes of event as described in the
- // invocation of this algorithm.
+ if (trailing) {
+ while (trail > 0 && predicate(str.charCodeAt(trail))) trail--
+ }
- // 5. Return the result of dispatching event at target, with legacy target
- // override flag set if set.
- target.dispatchEvent(event)
+ return lead === 0 && trail === str.length - 1 ? str : str.slice(lead, trail + 1)
}
/**
- * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
- * @param {import('./websocket').WebSocket} ws
- * @param {number} type Opcode
- * @param {Buffer} data application data
+ * @see https://infra.spec.whatwg.org/#isomorphic-decode
+ * @param {Uint8Array} input
+ * @returns {string}
*/
-function websocketMessageReceived (ws, type, data) {
- // 1. If ready state is not OPEN (1), then return.
- if (ws[kReadyState] !== states.OPEN) {
- return
+function isomorphicDecode (input) {
+ // 1. To isomorphic decode a byte sequence input, return a string whose code point
+ // length is equal to input’s length and whose code points have the same values
+ // as the values of input’s bytes, in the same order.
+ const length = input.length
+ if ((2 << 15) - 1 > length) {
+ return String.fromCharCode.apply(null, input)
}
-
- // 2. Let dataForEvent be determined by switching on type and binary type:
- let dataForEvent
-
- if (type === opcodes.TEXT) {
- // -> type indicates that the data is Text
- // a new DOMString containing data
- try {
- dataForEvent = utf8Decode(data)
- } catch {
- failWebsocketConnection(ws, 'Received invalid UTF-8 in text frame.')
- return
- }
- } else if (type === opcodes.BINARY) {
- if (ws[kBinaryType] === 'blob') {
- // -> type indicates that the data is Binary and binary type is "blob"
- // a new Blob object, created in the relevant Realm of the WebSocket
- // object, that represents data as its raw data
- dataForEvent = new Blob([data])
- } else {
- // -> type indicates that the data is Binary and binary type is "arraybuffer"
- // a new ArrayBuffer object, created in the relevant Realm of the
- // WebSocket object, whose contents are data
- dataForEvent = toArrayBuffer(data)
+ let result = ''; let i = 0
+ let addition = (2 << 15) - 1
+ while (i < length) {
+ if (i + addition > length) {
+ addition = length - i
}
+ result += String.fromCharCode.apply(null, input.subarray(i, i += addition))
}
-
- // 3. Fire an event named message at the WebSocket object, using MessageEvent,
- // with the origin attribute initialized to the serialization of the WebSocket
- // object’s url's origin, and the data attribute initialized to dataForEvent.
- fireEvent('message', ws, createFastMessageEvent, {
- origin: ws[kWebSocketURL].origin,
- data: dataForEvent
- })
-}
-
-function toArrayBuffer (buffer) {
- if (buffer.byteLength === buffer.buffer.byteLength) {
- return buffer.buffer
- }
- return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength)
+ return result
}
/**
- * @see https://datatracker.ietf.org/doc/html/rfc6455
- * @see https://datatracker.ietf.org/doc/html/rfc2616
- * @see https://bugs.chromium.org/p/chromium/issues/detail?id=398407
- * @param {string} protocol
+ * @see https://mimesniff.spec.whatwg.org/#minimize-a-supported-mime-type
+ * @param {Exclude, 'failure'>} mimeType
*/
-function isValidSubprotocol (protocol) {
- // If present, this value indicates one
- // or more comma-separated subprotocol the client wishes to speak,
- // ordered by preference. The elements that comprise this value
- // MUST be non-empty strings with characters in the range U+0021 to
- // U+007E not including separator characters as defined in
- // [RFC2616] and MUST all be unique strings.
- if (protocol.length === 0) {
- return false
+function minimizeSupportedMimeType (mimeType) {
+ switch (mimeType.essence) {
+ case 'application/ecmascript':
+ case 'application/javascript':
+ case 'application/x-ecmascript':
+ case 'application/x-javascript':
+ case 'text/ecmascript':
+ case 'text/javascript':
+ case 'text/javascript1.0':
+ case 'text/javascript1.1':
+ case 'text/javascript1.2':
+ case 'text/javascript1.3':
+ case 'text/javascript1.4':
+ case 'text/javascript1.5':
+ case 'text/jscript':
+ case 'text/livescript':
+ case 'text/x-ecmascript':
+ case 'text/x-javascript':
+ // 1. If mimeType is a JavaScript MIME type, then return "text/javascript".
+ return 'text/javascript'
+ case 'application/json':
+ case 'text/json':
+ // 2. If mimeType is a JSON MIME type, then return "application/json".
+ return 'application/json'
+ case 'image/svg+xml':
+ // 3. If mimeType’s essence is "image/svg+xml", then return "image/svg+xml".
+ return 'image/svg+xml'
+ case 'text/xml':
+ case 'application/xml':
+ // 4. If mimeType is an XML MIME type, then return "application/xml".
+ return 'application/xml'
}
- for (let i = 0; i < protocol.length; ++i) {
- const code = protocol.charCodeAt(i)
+ // 2. If mimeType is a JSON MIME type, then return "application/json".
+ if (mimeType.subtype.endsWith('+json')) {
+ return 'application/json'
+ }
- if (
- code < 0x21 || // CTL, contains SP (0x20) and HT (0x09)
- code > 0x7E ||
- code === 0x22 || // "
- code === 0x28 || // (
- code === 0x29 || // )
- code === 0x2C || // ,
- code === 0x2F || // /
- code === 0x3A || // :
- code === 0x3B || // ;
- code === 0x3C || // <
- code === 0x3D || // =
- code === 0x3E || // >
- code === 0x3F || // ?
- code === 0x40 || // @
- code === 0x5B || // [
- code === 0x5C || // \
- code === 0x5D || // ]
- code === 0x7B || // {
- code === 0x7D // }
- ) {
- return false
- }
+ // 4. If mimeType is an XML MIME type, then return "application/xml".
+ if (mimeType.subtype.endsWith('+xml')) {
+ return 'application/xml'
}
- return true
-}
+ // 5. If mimeType is supported by the user agent, then return mimeType’s essence.
+ // Technically, node doesn't support any mimetypes.
-/**
- * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7-4
- * @param {number} code
- */
-function isValidStatusCode (code) {
- if (code >= 1000 && code < 1015) {
- return (
- code !== 1004 && // reserved
- code !== 1005 && // "MUST NOT be set as a status code"
- code !== 1006 // "MUST NOT be set as a status code"
- )
- }
+ // 6. Return the empty string.
+ return ''
+}
- return code >= 3000 && code <= 4999
+module.exports = {
+ dataURLProcessor,
+ URLSerializer,
+ collectASequenceOfCodePoints,
+ collectASequenceOfCodePointsFast,
+ stringPercentDecode,
+ parseMIMEType,
+ collectAnHTTPQuotedString,
+ serializeAMimeType,
+ removeChars,
+ removeHTTPWhitespace,
+ minimizeSupportedMimeType,
+ HTTP_TOKEN_CODEPOINTS,
+ isomorphicDecode
}
-/**
- * @param {import('./websocket').WebSocket} ws
- * @param {string|undefined} reason
- */
-function failWebsocketConnection (ws, reason) {
- const { [kController]: controller, [kResponse]: response } = ws
- controller.abort()
+/***/ }),
- if (response?.socket && !response.socket.destroyed) {
- response.socket.destroy()
- }
+/***/ 6653:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- if (reason) {
- // TODO: process.nextTick
- fireEvent('error', ws, (type, init) => new ErrorEvent(type, init), {
- error: new Error(reason),
- message: reason
- })
+
+
+const { kConnected, kSize } = __nccwpck_require__(6443)
+
+class CompatWeakRef {
+ constructor (value) {
+ this.value = value
}
-}
-/**
- * @see https://datatracker.ietf.org/doc/html/rfc6455#section-5.5
- * @param {number} opcode
- */
-function isControlFrame (opcode) {
- return (
- opcode === opcodes.CLOSE ||
- opcode === opcodes.PING ||
- opcode === opcodes.PONG
- )
+ deref () {
+ return this.value[kConnected] === 0 && this.value[kSize] === 0
+ ? undefined
+ : this.value
+ }
}
-function isContinuationFrame (opcode) {
- return opcode === opcodes.CONTINUATION
-}
+class CompatFinalizer {
+ constructor (finalizer) {
+ this.finalizer = finalizer
+ }
-function isTextBinaryFrame (opcode) {
- return opcode === opcodes.TEXT || opcode === opcodes.BINARY
-}
+ register (dispatcher, key) {
+ if (dispatcher.on) {
+ dispatcher.on('disconnect', () => {
+ if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) {
+ this.finalizer(key)
+ }
+ })
+ }
+ }
-function isValidOpcode (opcode) {
- return isTextBinaryFrame(opcode) || isContinuationFrame(opcode) || isControlFrame(opcode)
+ unregister (key) {}
}
-/**
- * Parses a Sec-WebSocket-Extensions header value.
- * @param {string} extensions
- * @returns {Map}
- */
-// TODO(@Uzlopak, @KhafraDev): make compliant https://datatracker.ietf.org/doc/html/rfc6455#section-9.1
-function parseExtensions (extensions) {
- const position = { position: 0 }
- const extensionList = new Map()
-
- while (position.position < extensions.length) {
- const pair = collectASequenceOfCodePointsFast(';', extensions, position)
- const [name, value = ''] = pair.split('=')
-
- extensionList.set(
- removeHTTPWhitespace(name, true, false),
- removeHTTPWhitespace(value, false, true)
- )
-
- position.position++
- }
-
- return extensionList
-}
-
-/**
- * @see https://www.rfc-editor.org/rfc/rfc7692#section-7.1.2.2
- * @description "client-max-window-bits = 1*DIGIT"
- * @param {string} value
- */
-function isValidClientWindowBits (value) {
- for (let i = 0; i < value.length; i++) {
- const byte = value.charCodeAt(i)
-
- if (byte < 0x30 || byte > 0x39) {
- return false
- }
- }
-
- return true
-}
-
-// https://nodejs.org/api/intl.html#detecting-internationalization-support
-const hasIntl = typeof process.versions.icu === 'string'
-const fatalDecoder = hasIntl ? new TextDecoder('utf-8', { fatal: true }) : undefined
-
-/**
- * Converts a Buffer to utf-8, even on platforms without icu.
- * @param {Buffer} buffer
- */
-const utf8Decode = hasIntl
- ? fatalDecoder.decode.bind(fatalDecoder)
- : function (buffer) {
- if (isUtf8(buffer)) {
- return buffer.toString('utf-8')
+module.exports = function () {
+ // FIXME: remove workaround when the Node bug is backported to v18
+ // https://github.com/nodejs/node/issues/49344#issuecomment-1741776308
+ if (process.env.NODE_V8_COVERAGE && process.version.startsWith('v18')) {
+ process._rawDebug('Using compatibility WeakRef and FinalizationRegistry')
+ return {
+ WeakRef: CompatWeakRef,
+ FinalizationRegistry: CompatFinalizer
}
- throw new TypeError('Invalid utf-8 received.')
}
-
-module.exports = {
- isConnecting,
- isEstablished,
- isClosing,
- isClosed,
- fireEvent,
- isValidSubprotocol,
- isValidStatusCode,
- failWebsocketConnection,
- websocketMessageReceived,
- utf8Decode,
- isControlFrame,
- isContinuationFrame,
- isTextBinaryFrame,
- isValidOpcode,
- parseExtensions,
- isValidClientWindowBits
+ return { WeakRef, FinalizationRegistry }
}
/***/ }),
-/***/ 3061:
+/***/ 7114:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const { webidl } = __nccwpck_require__(220)
-const { URLSerializer } = __nccwpck_require__(2121)
-const { environmentSettingsObject } = __nccwpck_require__(7241)
-const { staticPropertyDescriptors, states, sentCloseFrameState, sendHints } = __nccwpck_require__(4411)
-const {
- kWebSocketURL,
- kReadyState,
- kController,
- kBinaryType,
- kResponse,
- kSentClose,
- kByteParser
-} = __nccwpck_require__(2679)
-const {
- isConnecting,
- isEstablished,
- isClosing,
- isValidSubprotocol,
- fireEvent
-} = __nccwpck_require__(2148)
-const { establishWebSocketConnection, closeWebSocketConnection } = __nccwpck_require__(7032)
-const { ByteParser } = __nccwpck_require__(8265)
-const { kEnumerableProperty, isBlobLike } = __nccwpck_require__(7375)
-const { getGlobalDispatcher } = __nccwpck_require__(1088)
-const { types } = __nccwpck_require__(7975)
-const { ErrorEvent, CloseEvent } = __nccwpck_require__(9617)
-const { SendQueue } = __nccwpck_require__(1577)
-
-// https://websockets.spec.whatwg.org/#interface-definition
-class WebSocket extends EventTarget {
- #events = {
- open: null,
- error: null,
- close: null,
- message: null
- }
-
- #bufferedAmount = 0
- #protocol = ''
- #extensions = ''
-
- /** @type {SendQueue} */
- #sendQueue
-
- /**
- * @param {string} url
- * @param {string|string[]} protocols
- */
- constructor (url, protocols = []) {
- super()
-
- webidl.util.markAsUncloneable(this)
-
- const prefix = 'WebSocket constructor'
- webidl.argumentLengthCheck(arguments, 1, prefix)
-
- const options = webidl.converters['DOMString or sequence or WebSocketInit'](protocols, prefix, 'options')
+const { Blob, File } = __nccwpck_require__(4573)
+const { kState } = __nccwpck_require__(3627)
+const { webidl } = __nccwpck_require__(5893)
- url = webidl.converters.USVString(url, prefix, 'url')
- protocols = options.protocols
+// TODO(@KhafraDev): remove
+class FileLike {
+ constructor (blobLike, fileName, options = {}) {
+ // TODO: argument idl type check
- // 1. Let baseURL be this's relevant settings object's API base URL.
- const baseURL = environmentSettingsObject.settingsObject.baseUrl
+ // The File constructor is invoked with two or three parameters, depending
+ // on whether the optional dictionary parameter is used. When the File()
+ // constructor is invoked, user agents must run the following steps:
- // 1. Let urlRecord be the result of applying the URL parser to url with baseURL.
- let urlRecord
+ // 1. Let bytes be the result of processing blob parts given fileBits and
+ // options.
- try {
- urlRecord = new URL(url, baseURL)
- } catch (e) {
- // 3. If urlRecord is failure, then throw a "SyntaxError" DOMException.
- throw new DOMException(e, 'SyntaxError')
- }
+ // 2. Let n be the fileName argument to the constructor.
+ const n = fileName
- // 4. If urlRecord’s scheme is "http", then set urlRecord’s scheme to "ws".
- if (urlRecord.protocol === 'http:') {
- urlRecord.protocol = 'ws:'
- } else if (urlRecord.protocol === 'https:') {
- // 5. Otherwise, if urlRecord’s scheme is "https", set urlRecord’s scheme to "wss".
- urlRecord.protocol = 'wss:'
- }
+ // 3. Process FilePropertyBag dictionary argument by running the following
+ // substeps:
- // 6. If urlRecord’s scheme is not "ws" or "wss", then throw a "SyntaxError" DOMException.
- if (urlRecord.protocol !== 'ws:' && urlRecord.protocol !== 'wss:') {
- throw new DOMException(
- `Expected a ws: or wss: protocol, got ${urlRecord.protocol}`,
- 'SyntaxError'
- )
- }
+ // 1. If the type member is provided and is not the empty string, let t
+ // be set to the type dictionary member. If t contains any characters
+ // outside the range U+0020 to U+007E, then set t to the empty string
+ // and return from these substeps.
+ // TODO
+ const t = options.type
- // 7. If urlRecord’s fragment is non-null, then throw a "SyntaxError"
- // DOMException.
- if (urlRecord.hash || urlRecord.href.endsWith('#')) {
- throw new DOMException('Got fragment', 'SyntaxError')
- }
+ // 2. Convert every character in t to ASCII lowercase.
+ // TODO
- // 8. If protocols is a string, set protocols to a sequence consisting
- // of just that string.
- if (typeof protocols === 'string') {
- protocols = [protocols]
- }
+ // 3. If the lastModified member is provided, let d be set to the
+ // lastModified dictionary member. If it is not provided, set d to the
+ // current date and time represented as the number of milliseconds since
+ // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]).
+ const d = options.lastModified ?? Date.now()
- // 9. If any of the values in protocols occur more than once or otherwise
- // fail to match the requirements for elements that comprise the value
- // of `Sec-WebSocket-Protocol` fields as defined by The WebSocket
- // protocol, then throw a "SyntaxError" DOMException.
- if (protocols.length !== new Set(protocols.map(p => p.toLowerCase())).size) {
- throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError')
- }
+ // 4. Return a new File object F such that:
+ // F refers to the bytes byte sequence.
+ // F.size is set to the number of total bytes in bytes.
+ // F.name is set to n.
+ // F.type is set to t.
+ // F.lastModified is set to d.
- if (protocols.length > 0 && !protocols.every(p => isValidSubprotocol(p))) {
- throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError')
+ this[kState] = {
+ blobLike,
+ name: n,
+ type: t,
+ lastModified: d
}
+ }
- // 10. Set this's url to urlRecord.
- this[kWebSocketURL] = new URL(urlRecord.href)
-
- // 11. Let client be this's relevant settings object.
- const client = environmentSettingsObject.settingsObject
+ stream (...args) {
+ webidl.brandCheck(this, FileLike)
- // 12. Run this step in parallel:
+ return this[kState].blobLike.stream(...args)
+ }
- // 1. Establish a WebSocket connection given urlRecord, protocols,
- // and client.
- this[kController] = establishWebSocketConnection(
- urlRecord,
- protocols,
- client,
- this,
- (response, extensions) => this.#onConnectionEstablished(response, extensions),
- options
- )
+ arrayBuffer (...args) {
+ webidl.brandCheck(this, FileLike)
- // Each WebSocket object has an associated ready state, which is a
- // number representing the state of the connection. Initially it must
- // be CONNECTING (0).
- this[kReadyState] = WebSocket.CONNECTING
+ return this[kState].blobLike.arrayBuffer(...args)
+ }
- this[kSentClose] = sentCloseFrameState.NOT_SENT
+ slice (...args) {
+ webidl.brandCheck(this, FileLike)
- // The extensions attribute must initially return the empty string.
+ return this[kState].blobLike.slice(...args)
+ }
- // The protocol attribute must initially return the empty string.
+ text (...args) {
+ webidl.brandCheck(this, FileLike)
- // Each WebSocket object has an associated binary type, which is a
- // BinaryType. Initially it must be "blob".
- this[kBinaryType] = 'blob'
+ return this[kState].blobLike.text(...args)
}
- /**
- * @see https://websockets.spec.whatwg.org/#dom-websocket-close
- * @param {number|undefined} code
- * @param {string|undefined} reason
- */
- close (code = undefined, reason = undefined) {
- webidl.brandCheck(this, WebSocket)
+ get size () {
+ webidl.brandCheck(this, FileLike)
- const prefix = 'WebSocket.close'
+ return this[kState].blobLike.size
+ }
- if (code !== undefined) {
- code = webidl.converters['unsigned short'](code, prefix, 'code', { clamp: true })
- }
+ get type () {
+ webidl.brandCheck(this, FileLike)
- if (reason !== undefined) {
- reason = webidl.converters.USVString(reason, prefix, 'reason')
- }
+ return this[kState].blobLike.type
+ }
- // 1. If code is present, but is neither an integer equal to 1000 nor an
- // integer in the range 3000 to 4999, inclusive, throw an
- // "InvalidAccessError" DOMException.
- if (code !== undefined) {
- if (code !== 1000 && (code < 3000 || code > 4999)) {
- throw new DOMException('invalid code', 'InvalidAccessError')
- }
- }
+ get name () {
+ webidl.brandCheck(this, FileLike)
- let reasonByteLength = 0
+ return this[kState].name
+ }
- // 2. If reason is present, then run these substeps:
- if (reason !== undefined) {
- // 1. Let reasonBytes be the result of encoding reason.
- // 2. If reasonBytes is longer than 123 bytes, then throw a
- // "SyntaxError" DOMException.
- reasonByteLength = Buffer.byteLength(reason)
+ get lastModified () {
+ webidl.brandCheck(this, FileLike)
- if (reasonByteLength > 123) {
- throw new DOMException(
- `Reason must be less than 123 bytes; received ${reasonByteLength}`,
- 'SyntaxError'
- )
- }
- }
+ return this[kState].lastModified
+ }
- // 3. Run the first matching steps from the following list:
- closeWebSocketConnection(this, code, reason, reasonByteLength)
+ get [Symbol.toStringTag] () {
+ return 'File'
}
+}
- /**
- * @see https://websockets.spec.whatwg.org/#dom-websocket-send
- * @param {NodeJS.TypedArray|ArrayBuffer|Blob|string} data
- */
- send (data) {
- webidl.brandCheck(this, WebSocket)
+webidl.converters.Blob = webidl.interfaceConverter(Blob)
- const prefix = 'WebSocket.send'
- webidl.argumentLengthCheck(arguments, 1, prefix)
+// If this function is moved to ./util.js, some tools (such as
+// rollup) will warn about circular dependencies. See:
+// https://github.com/nodejs/undici/issues/1629
+function isFileLike (object) {
+ return (
+ (object instanceof File) ||
+ (
+ object &&
+ (typeof object.stream === 'function' ||
+ typeof object.arrayBuffer === 'function') &&
+ object[Symbol.toStringTag] === 'File'
+ )
+ )
+}
- data = webidl.converters.WebSocketSendData(data, prefix, 'data')
+module.exports = { FileLike, isFileLike }
- // 1. If this's ready state is CONNECTING, then throw an
- // "InvalidStateError" DOMException.
- if (isConnecting(this)) {
- throw new DOMException('Sent before connected.', 'InvalidStateError')
- }
- // 2. Run the appropriate set of steps from the following list:
- // https://datatracker.ietf.org/doc/html/rfc6455#section-6.1
- // https://datatracker.ietf.org/doc/html/rfc6455#section-5.2
+/***/ }),
- if (!isEstablished(this) || isClosing(this)) {
- return
- }
+/***/ 116:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // If data is a string
- if (typeof data === 'string') {
- // If the WebSocket connection is established and the WebSocket
- // closing handshake has not yet started, then the user agent
- // must send a WebSocket Message comprised of the data argument
- // using a text frame opcode; if the data cannot be sent, e.g.
- // because it would need to be buffered but the buffer is full,
- // the user agent must flag the WebSocket as full and then close
- // the WebSocket connection. Any invocation of this method with a
- // string argument that does not throw an exception must increase
- // the bufferedAmount attribute by the number of bytes needed to
- // express the argument as UTF-8.
- const length = Buffer.byteLength(data)
- this.#bufferedAmount += length
- this.#sendQueue.add(data, () => {
- this.#bufferedAmount -= length
- }, sendHints.string)
- } else if (types.isArrayBuffer(data)) {
- // If the WebSocket connection is established, and the WebSocket
- // closing handshake has not yet started, then the user agent must
- // send a WebSocket Message comprised of data using a binary frame
- // opcode; if the data cannot be sent, e.g. because it would need
- // to be buffered but the buffer is full, the user agent must flag
- // the WebSocket as full and then close the WebSocket connection.
- // The data to be sent is the data stored in the buffer described
- // by the ArrayBuffer object. Any invocation of this method with an
- // ArrayBuffer argument that does not throw an exception must
- // increase the bufferedAmount attribute by the length of the
- // ArrayBuffer in bytes.
+const { isUSVString, bufferToLowerCasedHeaderName } = __nccwpck_require__(3440)
+const { utf8DecodeBytes } = __nccwpck_require__(3168)
+const { HTTP_TOKEN_CODEPOINTS, isomorphicDecode } = __nccwpck_require__(1900)
+const { isFileLike } = __nccwpck_require__(7114)
+const { makeEntry } = __nccwpck_require__(5910)
+const assert = __nccwpck_require__(4589)
+const { File: NodeFile } = __nccwpck_require__(4573)
- this.#bufferedAmount += data.byteLength
- this.#sendQueue.add(data, () => {
- this.#bufferedAmount -= data.byteLength
- }, sendHints.arrayBuffer)
- } else if (ArrayBuffer.isView(data)) {
- // If the WebSocket connection is established, and the WebSocket
- // closing handshake has not yet started, then the user agent must
- // send a WebSocket Message comprised of data using a binary frame
- // opcode; if the data cannot be sent, e.g. because it would need to
- // be buffered but the buffer is full, the user agent must flag the
- // WebSocket as full and then close the WebSocket connection. The
- // data to be sent is the data stored in the section of the buffer
- // described by the ArrayBuffer object that data references. Any
- // invocation of this method with this kind of argument that does
- // not throw an exception must increase the bufferedAmount attribute
- // by the length of data’s buffer in bytes.
+const File = globalThis.File ?? NodeFile
- this.#bufferedAmount += data.byteLength
- this.#sendQueue.add(data, () => {
- this.#bufferedAmount -= data.byteLength
- }, sendHints.typedArray)
- } else if (isBlobLike(data)) {
- // If the WebSocket connection is established, and the WebSocket
- // closing handshake has not yet started, then the user agent must
- // send a WebSocket Message comprised of data using a binary frame
- // opcode; if the data cannot be sent, e.g. because it would need to
- // be buffered but the buffer is full, the user agent must flag the
- // WebSocket as full and then close the WebSocket connection. The data
- // to be sent is the raw data represented by the Blob object. Any
- // invocation of this method with a Blob argument that does not throw
- // an exception must increase the bufferedAmount attribute by the size
- // of the Blob object’s raw data, in bytes.
+const formDataNameBuffer = Buffer.from('form-data; name="')
+const filenameBuffer = Buffer.from('; filename')
+const dd = Buffer.from('--')
+const ddcrlf = Buffer.from('--\r\n')
- this.#bufferedAmount += data.size
- this.#sendQueue.add(data, () => {
- this.#bufferedAmount -= data.size
- }, sendHints.blob)
+/**
+ * @param {string} chars
+ */
+function isAsciiString (chars) {
+ for (let i = 0; i < chars.length; ++i) {
+ if ((chars.charCodeAt(i) & ~0x7F) !== 0) {
+ return false
}
}
+ return true
+}
- get readyState () {
- webidl.brandCheck(this, WebSocket)
+/**
+ * @see https://andreubotella.github.io/multipart-form-data/#multipart-form-data-boundary
+ * @param {string} boundary
+ */
+function validateBoundary (boundary) {
+ const length = boundary.length
- // The readyState getter steps are to return this's ready state.
- return this[kReadyState]
+ // - its length is greater or equal to 27 and lesser or equal to 70, and
+ if (length < 27 || length > 70) {
+ return false
}
- get bufferedAmount () {
- webidl.brandCheck(this, WebSocket)
+ // - it is composed by bytes in the ranges 0x30 to 0x39, 0x41 to 0x5A, or
+ // 0x61 to 0x7A, inclusive (ASCII alphanumeric), or which are 0x27 ('),
+ // 0x2D (-) or 0x5F (_).
+ for (let i = 0; i < length; ++i) {
+ const cp = boundary.charCodeAt(i)
- return this.#bufferedAmount
+ if (!(
+ (cp >= 0x30 && cp <= 0x39) ||
+ (cp >= 0x41 && cp <= 0x5a) ||
+ (cp >= 0x61 && cp <= 0x7a) ||
+ cp === 0x27 ||
+ cp === 0x2d ||
+ cp === 0x5f
+ )) {
+ return false
+ }
}
- get url () {
- webidl.brandCheck(this, WebSocket)
+ return true
+}
- // The url getter steps are to return this's url, serialized.
- return URLSerializer(this[kWebSocketURL])
- }
+/**
+ * @see https://andreubotella.github.io/multipart-form-data/#multipart-form-data-parser
+ * @param {Buffer} input
+ * @param {ReturnType} mimeType
+ */
+function multipartFormDataParser (input, mimeType) {
+ // 1. Assert: mimeType’s essence is "multipart/form-data".
+ assert(mimeType !== 'failure' && mimeType.essence === 'multipart/form-data')
- get extensions () {
- webidl.brandCheck(this, WebSocket)
+ const boundaryString = mimeType.parameters.get('boundary')
- return this.#extensions
+ // 2. If mimeType’s parameters["boundary"] does not exist, return failure.
+ // Otherwise, let boundary be the result of UTF-8 decoding mimeType’s
+ // parameters["boundary"].
+ if (boundaryString === undefined) {
+ return 'failure'
}
- get protocol () {
- webidl.brandCheck(this, WebSocket)
+ const boundary = Buffer.from(`--${boundaryString}`, 'utf8')
- return this.#protocol
- }
+ // 3. Let entry list be an empty entry list.
+ const entryList = []
- get onopen () {
- webidl.brandCheck(this, WebSocket)
+ // 4. Let position be a pointer to a byte in input, initially pointing at
+ // the first byte.
+ const position = { position: 0 }
- return this.#events.open
+ // Note: undici addition, allows leading and trailing CRLFs.
+ while (input[position.position] === 0x0d && input[position.position + 1] === 0x0a) {
+ position.position += 2
}
- set onopen (fn) {
- webidl.brandCheck(this, WebSocket)
-
- if (this.#events.open) {
- this.removeEventListener('open', this.#events.open)
- }
+ let trailing = input.length
- if (typeof fn === 'function') {
- this.#events.open = fn
- this.addEventListener('open', fn)
- } else {
- this.#events.open = null
- }
+ while (input[trailing - 1] === 0x0a && input[trailing - 2] === 0x0d) {
+ trailing -= 2
}
- get onerror () {
- webidl.brandCheck(this, WebSocket)
-
- return this.#events.error
+ if (trailing !== input.length) {
+ input = input.subarray(0, trailing)
}
- set onerror (fn) {
- webidl.brandCheck(this, WebSocket)
-
- if (this.#events.error) {
- this.removeEventListener('error', this.#events.error)
- }
-
- if (typeof fn === 'function') {
- this.#events.error = fn
- this.addEventListener('error', fn)
+ // 5. While true:
+ while (true) {
+ // 5.1. If position points to a sequence of bytes starting with 0x2D 0x2D
+ // (`--`) followed by boundary, advance position by 2 + the length of
+ // boundary. Otherwise, return failure.
+ // Note: boundary is padded with 2 dashes already, no need to add 2.
+ if (input.subarray(position.position, position.position + boundary.length).equals(boundary)) {
+ position.position += boundary.length
} else {
- this.#events.error = null
+ return 'failure'
}
- }
- get onclose () {
- webidl.brandCheck(this, WebSocket)
+ // 5.2. If position points to the sequence of bytes 0x2D 0x2D 0x0D 0x0A
+ // (`--` followed by CR LF) followed by the end of input, return entry list.
+ // Note: a body does NOT need to end with CRLF. It can end with --.
+ if (
+ (position.position === input.length - 2 && bufferStartsWith(input, dd, position)) ||
+ (position.position === input.length - 4 && bufferStartsWith(input, ddcrlf, position))
+ ) {
+ return entryList
+ }
- return this.#events.close
- }
+ // 5.3. If position does not point to a sequence of bytes starting with 0x0D
+ // 0x0A (CR LF), return failure.
+ if (input[position.position] !== 0x0d || input[position.position + 1] !== 0x0a) {
+ return 'failure'
+ }
- set onclose (fn) {
- webidl.brandCheck(this, WebSocket)
+ // 5.4. Advance position by 2. (This skips past the newline.)
+ position.position += 2
- if (this.#events.close) {
- this.removeEventListener('close', this.#events.close)
- }
+ // 5.5. Let name, filename and contentType be the result of parsing
+ // multipart/form-data headers on input and position, if the result
+ // is not failure. Otherwise, return failure.
+ const result = parseMultipartFormDataHeaders(input, position)
- if (typeof fn === 'function') {
- this.#events.close = fn
- this.addEventListener('close', fn)
- } else {
- this.#events.close = null
+ if (result === 'failure') {
+ return 'failure'
}
- }
- get onmessage () {
- webidl.brandCheck(this, WebSocket)
+ let { name, filename, contentType, encoding } = result
- return this.#events.message
- }
+ // 5.6. Advance position by 2. (This skips past the empty line that marks
+ // the end of the headers.)
+ position.position += 2
- set onmessage (fn) {
- webidl.brandCheck(this, WebSocket)
+ // 5.7. Let body be the empty byte sequence.
+ let body
- if (this.#events.message) {
- this.removeEventListener('message', this.#events.message)
- }
+ // 5.8. Body loop: While position is not past the end of input:
+ // TODO: the steps here are completely wrong
+ {
+ const boundaryIndex = input.indexOf(boundary.subarray(2), position.position)
- if (typeof fn === 'function') {
- this.#events.message = fn
- this.addEventListener('message', fn)
- } else {
- this.#events.message = null
- }
- }
+ if (boundaryIndex === -1) {
+ return 'failure'
+ }
- get binaryType () {
- webidl.brandCheck(this, WebSocket)
+ body = input.subarray(position.position, boundaryIndex - 4)
- return this[kBinaryType]
- }
+ position.position += body.length
- set binaryType (type) {
- webidl.brandCheck(this, WebSocket)
+ // Note: position must be advanced by the body's length before being
+ // decoded, otherwise the parsing will fail.
+ if (encoding === 'base64') {
+ body = Buffer.from(body.toString(), 'base64')
+ }
+ }
- if (type !== 'blob' && type !== 'arraybuffer') {
- this[kBinaryType] = 'blob'
+ // 5.9. If position does not point to a sequence of bytes starting with
+ // 0x0D 0x0A (CR LF), return failure. Otherwise, advance position by 2.
+ if (input[position.position] !== 0x0d || input[position.position + 1] !== 0x0a) {
+ return 'failure'
} else {
- this[kBinaryType] = type
+ position.position += 2
}
- }
-
- /**
- * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
- */
- #onConnectionEstablished (response, parsedExtensions) {
- // processResponse is called when the "response’s header list has been received and initialized."
- // once this happens, the connection is open
- this[kResponse] = response
- const parser = new ByteParser(this, parsedExtensions)
- parser.on('drain', onParserDrain)
- parser.on('error', onParserError.bind(this))
+ // 5.10. If filename is not null:
+ let value
- response.socket.ws = this
- this[kByteParser] = parser
+ if (filename !== null) {
+ // 5.10.1. If contentType is null, set contentType to "text/plain".
+ contentType ??= 'text/plain'
- this.#sendQueue = new SendQueue(response.socket)
+ // 5.10.2. If contentType is not an ASCII string, set contentType to the empty string.
- // 1. Change the ready state to OPEN (1).
- this[kReadyState] = states.OPEN
+ // Note: `buffer.isAscii` can be used at zero-cost, but converting a string to a buffer is a high overhead.
+ // Content-Type is a relatively small string, so it is faster to use `String#charCodeAt`.
+ if (!isAsciiString(contentType)) {
+ contentType = ''
+ }
- // 2. Change the extensions attribute’s value to the extensions in use, if
- // it is not the null value.
- // https://datatracker.ietf.org/doc/html/rfc6455#section-9.1
- const extensions = response.headersList.get('sec-websocket-extensions')
+ // 5.10.3. Let value be a new File object with name filename, type contentType, and body body.
+ value = new File([body], filename, { type: contentType })
+ } else {
+ // 5.11. Otherwise:
- if (extensions !== null) {
- this.#extensions = extensions
+ // 5.11.1. Let value be the UTF-8 decoding without BOM of body.
+ value = utf8DecodeBytes(Buffer.from(body))
}
- // 3. Change the protocol attribute’s value to the subprotocol in use, if
- // it is not the null value.
- // https://datatracker.ietf.org/doc/html/rfc6455#section-1.9
- const protocol = response.headersList.get('sec-websocket-protocol')
-
- if (protocol !== null) {
- this.#protocol = protocol
- }
+ // 5.12. Assert: name is a scalar value string and value is either a scalar value string or a File object.
+ assert(isUSVString(name))
+ assert((typeof value === 'string' && isUSVString(value)) || isFileLike(value))
- // 4. Fire an event named open at the WebSocket object.
- fireEvent('open', this)
+ // 5.13. Create an entry with name and value, and append it to entry list.
+ entryList.push(makeEntry(name, value, filename))
}
}
-// https://websockets.spec.whatwg.org/#dom-websocket-connecting
-WebSocket.CONNECTING = WebSocket.prototype.CONNECTING = states.CONNECTING
-// https://websockets.spec.whatwg.org/#dom-websocket-open
-WebSocket.OPEN = WebSocket.prototype.OPEN = states.OPEN
-// https://websockets.spec.whatwg.org/#dom-websocket-closing
-WebSocket.CLOSING = WebSocket.prototype.CLOSING = states.CLOSING
-// https://websockets.spec.whatwg.org/#dom-websocket-closed
-WebSocket.CLOSED = WebSocket.prototype.CLOSED = states.CLOSED
-
-Object.defineProperties(WebSocket.prototype, {
- CONNECTING: staticPropertyDescriptors,
- OPEN: staticPropertyDescriptors,
- CLOSING: staticPropertyDescriptors,
- CLOSED: staticPropertyDescriptors,
- url: kEnumerableProperty,
- readyState: kEnumerableProperty,
- bufferedAmount: kEnumerableProperty,
- onopen: kEnumerableProperty,
- onerror: kEnumerableProperty,
- onclose: kEnumerableProperty,
- close: kEnumerableProperty,
- onmessage: kEnumerableProperty,
- binaryType: kEnumerableProperty,
- send: kEnumerableProperty,
- extensions: kEnumerableProperty,
- protocol: kEnumerableProperty,
- [Symbol.toStringTag]: {
- value: 'WebSocket',
- writable: false,
- enumerable: false,
- configurable: true
- }
-})
-
-Object.defineProperties(WebSocket, {
- CONNECTING: staticPropertyDescriptors,
- OPEN: staticPropertyDescriptors,
- CLOSING: staticPropertyDescriptors,
- CLOSED: staticPropertyDescriptors
-})
-
-webidl.converters['sequence'] = webidl.sequenceConverter(
- webidl.converters.DOMString
-)
-
-webidl.converters['DOMString or sequence'] = function (V, prefix, argument) {
- if (webidl.util.Type(V) === 'Object' && Symbol.iterator in V) {
- return webidl.converters['sequence'](V)
- }
+/**
+ * @see https://andreubotella.github.io/multipart-form-data/#parse-multipart-form-data-headers
+ * @param {Buffer} input
+ * @param {{ position: number }} position
+ */
+function parseMultipartFormDataHeaders (input, position) {
+ // 1. Let name, filename and contentType be null.
+ let name = null
+ let filename = null
+ let contentType = null
+ let encoding = null
- return webidl.converters.DOMString(V, prefix, argument)
-}
+ // 2. While true:
+ while (true) {
+ // 2.1. If position points to a sequence of bytes starting with 0x0D 0x0A (CR LF):
+ if (input[position.position] === 0x0d && input[position.position + 1] === 0x0a) {
+ // 2.1.1. If name is null, return failure.
+ if (name === null) {
+ return 'failure'
+ }
-// This implements the proposal made in https://github.com/whatwg/websockets/issues/42
-webidl.converters.WebSocketInit = webidl.dictionaryConverter([
- {
- key: 'protocols',
- converter: webidl.converters['DOMString or sequence'],
- defaultValue: () => new Array(0)
- },
- {
- key: 'dispatcher',
- converter: webidl.converters.any,
- defaultValue: () => getGlobalDispatcher()
- },
- {
- key: 'headers',
- converter: webidl.nullableConverter(webidl.converters.HeadersInit)
- }
-])
+ // 2.1.2. Return name, filename and contentType.
+ return { name, filename, contentType, encoding }
+ }
-webidl.converters['DOMString or sequence or WebSocketInit'] = function (V) {
- if (webidl.util.Type(V) === 'Object' && !(Symbol.iterator in V)) {
- return webidl.converters.WebSocketInit(V)
- }
+ // 2.2. Let header name be the result of collecting a sequence of bytes that are
+ // not 0x0A (LF), 0x0D (CR) or 0x3A (:), given position.
+ let headerName = collectASequenceOfBytes(
+ (char) => char !== 0x0a && char !== 0x0d && char !== 0x3a,
+ input,
+ position
+ )
- return { protocols: webidl.converters['DOMString or sequence'](V) }
-}
+ // 2.3. Remove any HTTP tab or space bytes from the start or end of header name.
+ headerName = removeChars(headerName, true, true, (char) => char === 0x9 || char === 0x20)
-webidl.converters.WebSocketSendData = function (V) {
- if (webidl.util.Type(V) === 'Object') {
- if (isBlobLike(V)) {
- return webidl.converters.Blob(V, { strict: false })
+ // 2.4. If header name does not match the field-name token production, return failure.
+ if (!HTTP_TOKEN_CODEPOINTS.test(headerName.toString())) {
+ return 'failure'
}
- if (ArrayBuffer.isView(V) || types.isArrayBuffer(V)) {
- return webidl.converters.BufferSource(V)
+ // 2.5. If the byte at position is not 0x3A (:), return failure.
+ if (input[position.position] !== 0x3a) {
+ return 'failure'
}
- }
- return webidl.converters.USVString(V)
-}
+ // 2.6. Advance position by 1.
+ position.position++
-function onParserDrain () {
- this.ws[kResponse].socket.resume()
-}
+ // 2.7. Collect a sequence of bytes that are HTTP tab or space bytes given position.
+ // (Do nothing with those bytes.)
+ collectASequenceOfBytes(
+ (char) => char === 0x20 || char === 0x09,
+ input,
+ position
+ )
-function onParserError (err) {
- let message
- let code
+ // 2.8. Byte-lowercase header name and switch on the result:
+ switch (bufferToLowerCasedHeaderName(headerName)) {
+ case 'content-disposition': {
+ // 1. Set name and filename to null.
+ name = filename = null
- if (err instanceof CloseEvent) {
- message = err.reason
- code = err.code
- } else {
- message = err.message
- }
+ // 2. If position does not point to a sequence of bytes starting with
+ // `form-data; name="`, return failure.
+ if (!bufferStartsWith(input, formDataNameBuffer, position)) {
+ return 'failure'
+ }
- fireEvent('error', this, () => new ErrorEvent('error', { error: err, message }))
+ // 3. Advance position so it points at the byte after the next 0x22 (")
+ // byte (the one in the sequence of bytes matched above).
+ position.position += 17
- closeWebSocketConnection(this, code)
-}
+ // 4. Set name to the result of parsing a multipart/form-data name given
+ // input and position, if the result is not failure. Otherwise, return
+ // failure.
+ name = parseMultipartFormDataName(input, position)
-module.exports = {
- WebSocket
-}
+ if (name === null) {
+ return 'failure'
+ }
+ // 5. If position points to a sequence of bytes starting with `; filename="`:
+ if (bufferStartsWith(input, filenameBuffer, position)) {
+ // Note: undici also handles filename*
+ let check = position.position + filenameBuffer.length
-/***/ }),
+ if (input[check] === 0x2a) {
+ position.position += 1
+ check += 1
+ }
-/***/ 3368:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ if (input[check] !== 0x3d || input[check + 1] !== 0x22) { // ="
+ return 'failure'
+ }
-var __webpack_unused_export__;
+ // 1. Advance position so it points at the byte after the next 0x22 (") byte
+ // (the one in the sequence of bytes matched above).
+ position.position += 12
+ // 2. Set filename to the result of parsing a multipart/form-data name given
+ // input and position, if the result is not failure. Otherwise, return failure.
+ filename = parseMultipartFormDataName(input, position)
-const Client = __nccwpck_require__(3069)
-const Dispatcher = __nccwpck_require__(2091)
-const Pool = __nccwpck_require__(7404)
-const BalancedPool = __nccwpck_require__(8973)
-const Agent = __nccwpck_require__(6261)
-const ProxyAgent = __nccwpck_require__(9848)
-const EnvHttpProxyAgent = __nccwpck_require__(7897)
-const RetryAgent = __nccwpck_require__(1882)
-const errors = __nccwpck_require__(8091)
-const util = __nccwpck_require__(1544)
-const { InvalidArgumentError } = errors
-const api = __nccwpck_require__(5407)
-const buildConnector = __nccwpck_require__(2296)
-const MockClient = __nccwpck_require__(8957)
-const MockAgent = __nccwpck_require__(5973)
-const MockPool = __nccwpck_require__(8780)
-const mockErrors = __nccwpck_require__(5445)
-const RetryHandler = __nccwpck_require__(112)
-const { getGlobalDispatcher, setGlobalDispatcher } = __nccwpck_require__(5837)
-const DecoratorHandler = __nccwpck_require__(7011)
-const RedirectHandler = __nccwpck_require__(5050)
-const createRedirectInterceptor = __nccwpck_require__(1676)
+ if (filename === null) {
+ return 'failure'
+ }
+ }
-Object.assign(Dispatcher.prototype, api)
+ break
+ }
+ case 'content-type': {
+ // 1. Let header value be the result of collecting a sequence of bytes that are
+ // not 0x0A (LF) or 0x0D (CR), given position.
+ let headerValue = collectASequenceOfBytes(
+ (char) => char !== 0x0a && char !== 0x0d,
+ input,
+ position
+ )
-__webpack_unused_export__ = Dispatcher
-__webpack_unused_export__ = Client
-__webpack_unused_export__ = Pool
-__webpack_unused_export__ = BalancedPool
-__webpack_unused_export__ = Agent
-module.exports.kT = ProxyAgent
-__webpack_unused_export__ = EnvHttpProxyAgent
-__webpack_unused_export__ = RetryAgent
-__webpack_unused_export__ = RetryHandler
-
-__webpack_unused_export__ = DecoratorHandler
-__webpack_unused_export__ = RedirectHandler
-__webpack_unused_export__ = createRedirectInterceptor
-__webpack_unused_export__ = {
- redirect: __nccwpck_require__(3650),
- retry: __nccwpck_require__(3874),
- dump: __nccwpck_require__(2375),
- dns: __nccwpck_require__(7251)
-}
-
-__webpack_unused_export__ = buildConnector
-__webpack_unused_export__ = errors
-__webpack_unused_export__ = {
- parseHeaders: util.parseHeaders,
- headerNameToString: util.headerNameToString
-}
+ // 2. Remove any HTTP tab or space bytes from the end of header value.
+ headerValue = removeChars(headerValue, false, true, (char) => char === 0x9 || char === 0x20)
-function makeDispatcher (fn) {
- return (url, opts, handler) => {
- if (typeof opts === 'function') {
- handler = opts
- opts = null
- }
+ // 3. Set contentType to the isomorphic decoding of header value.
+ contentType = isomorphicDecode(headerValue)
- if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) {
- throw new InvalidArgumentError('invalid url')
- }
+ break
+ }
+ case 'content-transfer-encoding': {
+ let headerValue = collectASequenceOfBytes(
+ (char) => char !== 0x0a && char !== 0x0d,
+ input,
+ position
+ )
- if (opts != null && typeof opts !== 'object') {
- throw new InvalidArgumentError('invalid opts')
- }
+ headerValue = removeChars(headerValue, false, true, (char) => char === 0x9 || char === 0x20)
- if (opts && opts.path != null) {
- if (typeof opts.path !== 'string') {
- throw new InvalidArgumentError('invalid opts.path')
- }
+ encoding = isomorphicDecode(headerValue)
- let path = opts.path
- if (!opts.path.startsWith('/')) {
- path = `/${path}`
+ break
}
-
- url = new URL(util.parseOrigin(url).origin + path)
- } else {
- if (!opts) {
- opts = typeof url === 'object' ? url : {}
+ default: {
+ // Collect a sequence of bytes that are not 0x0A (LF) or 0x0D (CR), given position.
+ // (Do nothing with those bytes.)
+ collectASequenceOfBytes(
+ (char) => char !== 0x0a && char !== 0x0d,
+ input,
+ position
+ )
}
-
- url = util.parseURL(url)
}
- const { agent, dispatcher = getGlobalDispatcher() } = opts
-
- if (agent) {
- throw new InvalidArgumentError('unsupported opts.agent. Did you mean opts.client?')
+ // 2.9. If position does not point to a sequence of bytes starting with 0x0D 0x0A
+ // (CR LF), return failure. Otherwise, advance position by 2 (past the newline).
+ if (input[position.position] !== 0x0d && input[position.position + 1] !== 0x0a) {
+ return 'failure'
+ } else {
+ position.position += 2
}
-
- return fn.call(dispatcher, {
- ...opts,
- origin: url.origin,
- path: url.search ? `${url.pathname}${url.search}` : url.pathname,
- method: opts.method || (opts.body ? 'PUT' : 'GET')
- }, handler)
}
}
-__webpack_unused_export__ = setGlobalDispatcher
-__webpack_unused_export__ = getGlobalDispatcher
+/**
+ * @see https://andreubotella.github.io/multipart-form-data/#parse-a-multipart-form-data-name
+ * @param {Buffer} input
+ * @param {{ position: number }} position
+ */
+function parseMultipartFormDataName (input, position) {
+ // 1. Assert: The byte at (position - 1) is 0x22 (").
+ assert(input[position.position - 1] === 0x22)
-const fetchImpl = (__nccwpck_require__(7302).fetch)
-__webpack_unused_export__ = async function fetch (init, options = undefined) {
- try {
- return await fetchImpl(init, options)
- } catch (err) {
- if (err && typeof err === 'object') {
- Error.captureStackTrace(err)
- }
+ // 2. Let name be the result of collecting a sequence of bytes that are not 0x0A (LF), 0x0D (CR) or 0x22 ("), given position.
+ /** @type {string | Buffer} */
+ let name = collectASequenceOfBytes(
+ (char) => char !== 0x0a && char !== 0x0d && char !== 0x22,
+ input,
+ position
+ )
- throw err
+ // 3. If the byte at position is not 0x22 ("), return failure. Otherwise, advance position by 1.
+ if (input[position.position] !== 0x22) {
+ return null // name could be 'failure'
+ } else {
+ position.position++
}
-}
-/* unused reexport */ __nccwpck_require__(3676).Headers
-/* unused reexport */ __nccwpck_require__(9107).Response
-/* unused reexport */ __nccwpck_require__(6055).Request
-/* unused reexport */ __nccwpck_require__(9662).FormData
-__webpack_unused_export__ = globalThis.File ?? (__nccwpck_require__(4573).File)
-/* unused reexport */ __nccwpck_require__(6299).FileReader
-const { setGlobalOrigin, getGlobalOrigin } = __nccwpck_require__(2443)
-
-__webpack_unused_export__ = setGlobalOrigin
-__webpack_unused_export__ = getGlobalOrigin
+ // 4. Replace any occurrence of the following subsequences in name with the given byte:
+ // - `%0A`: 0x0A (LF)
+ // - `%0D`: 0x0D (CR)
+ // - `%22`: 0x22 (")
+ name = new TextDecoder().decode(name)
+ .replace(/%0A/ig, '\n')
+ .replace(/%0D/ig, '\r')
+ .replace(/%22/g, '"')
-const { CacheStorage } = __nccwpck_require__(6949)
-const { kConstruct } = __nccwpck_require__(7589)
+ // 5. Return the UTF-8 decoding without BOM of name.
+ return name
+}
-// Cache & CacheStorage are tightly coupled with fetch. Even if it may run
-// in an older version of Node, it doesn't have any use without fetch.
-__webpack_unused_export__ = new CacheStorage(kConstruct)
+/**
+ * @param {(char: number) => boolean} condition
+ * @param {Buffer} input
+ * @param {{ position: number }} position
+ */
+function collectASequenceOfBytes (condition, input, position) {
+ let start = position.position
-const { deleteCookie, getCookies, getSetCookies, setCookie } = __nccwpck_require__(5437)
+ while (start < input.length && condition(input[start])) {
+ ++start
+ }
-__webpack_unused_export__ = deleteCookie
-__webpack_unused_export__ = getCookies
-__webpack_unused_export__ = getSetCookies
-__webpack_unused_export__ = setCookie
+ return input.subarray(position.position, (position.position = start))
+}
-const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(980)
+/**
+ * @param {Buffer} buf
+ * @param {boolean} leading
+ * @param {boolean} trailing
+ * @param {(charCode: number) => boolean} predicate
+ * @returns {Buffer}
+ */
+function removeChars (buf, leading, trailing, predicate) {
+ let lead = 0
+ let trail = buf.length - 1
-__webpack_unused_export__ = parseMIMEType
-__webpack_unused_export__ = serializeAMimeType
+ if (leading) {
+ while (lead < buf.length && predicate(buf[lead])) lead++
+ }
-const { CloseEvent, ErrorEvent, MessageEvent } = __nccwpck_require__(44)
-/* unused reexport */ __nccwpck_require__(5366).WebSocket
-__webpack_unused_export__ = CloseEvent
-__webpack_unused_export__ = ErrorEvent
-__webpack_unused_export__ = MessageEvent
+ if (trailing) {
+ while (trail > 0 && predicate(buf[trail])) trail--
+ }
-__webpack_unused_export__ = makeDispatcher(api.request)
-__webpack_unused_export__ = makeDispatcher(api.stream)
-__webpack_unused_export__ = makeDispatcher(api.pipeline)
-__webpack_unused_export__ = makeDispatcher(api.connect)
-__webpack_unused_export__ = makeDispatcher(api.upgrade)
+ return lead === 0 && trail === buf.length - 1 ? buf : buf.subarray(lead, trail + 1)
+}
-__webpack_unused_export__ = MockClient
-__webpack_unused_export__ = MockPool
-__webpack_unused_export__ = MockAgent
-__webpack_unused_export__ = mockErrors
+/**
+ * Checks if {@param buffer} starts with {@param start}
+ * @param {Buffer} buffer
+ * @param {Buffer} start
+ * @param {{ position: number }} position
+ */
+function bufferStartsWith (buffer, start, position) {
+ if (buffer.length < start.length) {
+ return false
+ }
+
+ for (let i = 0; i < start.length; i++) {
+ if (start[i] !== buffer[position.position + i]) {
+ return false
+ }
+ }
-const { EventSource } = __nccwpck_require__(6942)
+ return true
+}
-__webpack_unused_export__ = EventSource
+module.exports = {
+ multipartFormDataParser,
+ validateBoundary
+}
/***/ }),
-/***/ 9318:
+/***/ 5910:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const { addAbortListener } = __nccwpck_require__(1544)
-const { RequestAbortedError } = __nccwpck_require__(8091)
-const kListener = Symbol('kListener')
-const kSignal = Symbol('kSignal')
-function abort (self) {
- if (self.abort) {
- self.abort(self[kSignal]?.reason)
- } else {
- self.reason = self[kSignal]?.reason ?? new RequestAbortedError()
- }
- removeSignal(self)
-}
+const { isBlobLike, iteratorMixin } = __nccwpck_require__(3168)
+const { kState } = __nccwpck_require__(3627)
+const { kEnumerableProperty } = __nccwpck_require__(3440)
+const { FileLike, isFileLike } = __nccwpck_require__(7114)
+const { webidl } = __nccwpck_require__(5893)
+const { File: NativeFile } = __nccwpck_require__(4573)
+const nodeUtil = __nccwpck_require__(7975)
-function addSignal (self, signal) {
- self.reason = null
+/** @type {globalThis['File']} */
+const File = globalThis.File ?? NativeFile
- self[kSignal] = null
- self[kListener] = null
+// https://xhr.spec.whatwg.org/#formdata
+class FormData {
+ constructor (form) {
+ webidl.util.markAsUncloneable(this)
- if (!signal) {
- return
- }
+ if (form !== undefined) {
+ throw webidl.errors.conversionFailed({
+ prefix: 'FormData constructor',
+ argument: 'Argument 1',
+ types: ['undefined']
+ })
+ }
- if (signal.aborted) {
- abort(self)
- return
+ this[kState] = []
}
- self[kSignal] = signal
- self[kListener] = () => {
- abort(self)
- }
+ append (name, value, filename = undefined) {
+ webidl.brandCheck(this, FormData)
- addAbortListener(self[kSignal], self[kListener])
-}
+ const prefix = 'FormData.append'
+ webidl.argumentLengthCheck(arguments, 2, prefix)
-function removeSignal (self) {
- if (!self[kSignal]) {
- return
- }
+ if (arguments.length === 3 && !isBlobLike(value)) {
+ throw new TypeError(
+ "Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'"
+ )
+ }
- if ('removeEventListener' in self[kSignal]) {
- self[kSignal].removeEventListener('abort', self[kListener])
- } else {
- self[kSignal].removeListener('abort', self[kListener])
- }
+ // 1. Let value be value if given; otherwise blobValue.
- self[kSignal] = null
- self[kListener] = null
-}
+ name = webidl.converters.USVString(name, prefix, 'name')
+ value = isBlobLike(value)
+ ? webidl.converters.Blob(value, prefix, 'value', { strict: false })
+ : webidl.converters.USVString(value, prefix, 'value')
+ filename = arguments.length === 3
+ ? webidl.converters.USVString(filename, prefix, 'filename')
+ : undefined
-module.exports = {
- addSignal,
- removeSignal
-}
+ // 2. Let entry be the result of creating an entry with
+ // name, value, and filename if given.
+ const entry = makeEntry(name, value, filename)
+ // 3. Append entry to this’s entry list.
+ this[kState].push(entry)
+ }
-/***/ }),
+ delete (name) {
+ webidl.brandCheck(this, FormData)
-/***/ 9724:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ const prefix = 'FormData.delete'
+ webidl.argumentLengthCheck(arguments, 1, prefix)
+ name = webidl.converters.USVString(name, prefix, 'name')
+ // The delete(name) method steps are to remove all entries whose name
+ // is name from this’s entry list.
+ this[kState] = this[kState].filter(entry => entry.name !== name)
+ }
-const assert = __nccwpck_require__(4589)
-const { AsyncResource } = __nccwpck_require__(6698)
-const { InvalidArgumentError, SocketError } = __nccwpck_require__(8091)
-const util = __nccwpck_require__(1544)
-const { addSignal, removeSignal } = __nccwpck_require__(9318)
+ get (name) {
+ webidl.brandCheck(this, FormData)
-class ConnectHandler extends AsyncResource {
- constructor (opts, callback) {
- if (!opts || typeof opts !== 'object') {
- throw new InvalidArgumentError('invalid opts')
- }
+ const prefix = 'FormData.get'
+ webidl.argumentLengthCheck(arguments, 1, prefix)
- if (typeof callback !== 'function') {
- throw new InvalidArgumentError('invalid callback')
+ name = webidl.converters.USVString(name, prefix, 'name')
+
+ // 1. If there is no entry whose name is name in this’s entry list,
+ // then return null.
+ const idx = this[kState].findIndex((entry) => entry.name === name)
+ if (idx === -1) {
+ return null
}
- const { signal, opaque, responseHeaders } = opts
+ // 2. Return the value of the first entry whose name is name from
+ // this’s entry list.
+ return this[kState][idx].value
+ }
- if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
- throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
- }
+ getAll (name) {
+ webidl.brandCheck(this, FormData)
- super('UNDICI_CONNECT')
+ const prefix = 'FormData.getAll'
+ webidl.argumentLengthCheck(arguments, 1, prefix)
- this.opaque = opaque || null
- this.responseHeaders = responseHeaders || null
- this.callback = callback
- this.abort = null
+ name = webidl.converters.USVString(name, prefix, 'name')
- addSignal(this, signal)
+ // 1. If there is no entry whose name is name in this’s entry list,
+ // then return the empty list.
+ // 2. Return the values of all entries whose name is name, in order,
+ // from this’s entry list.
+ return this[kState]
+ .filter((entry) => entry.name === name)
+ .map((entry) => entry.value)
}
- onConnect (abort, context) {
- if (this.reason) {
- abort(this.reason)
- return
- }
+ has (name) {
+ webidl.brandCheck(this, FormData)
- assert(this.callback)
+ const prefix = 'FormData.has'
+ webidl.argumentLengthCheck(arguments, 1, prefix)
- this.abort = abort
- this.context = context
- }
+ name = webidl.converters.USVString(name, prefix, 'name')
- onHeaders () {
- throw new SocketError('bad connect', null)
+ // The has(name) method steps are to return true if there is an entry
+ // whose name is name in this’s entry list; otherwise false.
+ return this[kState].findIndex((entry) => entry.name === name) !== -1
}
- onUpgrade (statusCode, rawHeaders, socket) {
- const { callback, opaque, context } = this
-
- removeSignal(this)
+ set (name, value, filename = undefined) {
+ webidl.brandCheck(this, FormData)
- this.callback = null
+ const prefix = 'FormData.set'
+ webidl.argumentLengthCheck(arguments, 2, prefix)
- let headers = rawHeaders
- // Indicates is an HTTP2Session
- if (headers != null) {
- headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
+ if (arguments.length === 3 && !isBlobLike(value)) {
+ throw new TypeError(
+ "Failed to execute 'set' on 'FormData': parameter 2 is not of type 'Blob'"
+ )
}
- this.runInAsyncScope(callback, null, null, {
- statusCode,
- headers,
- socket,
- opaque,
- context
- })
- }
-
- onError (err) {
- const { callback, opaque } = this
+ // The set(name, value) and set(name, blobValue, filename) method steps
+ // are:
- removeSignal(this)
+ // 1. Let value be value if given; otherwise blobValue.
- if (callback) {
- this.callback = null
- queueMicrotask(() => {
- this.runInAsyncScope(callback, null, err, { opaque })
- })
- }
- }
-}
+ name = webidl.converters.USVString(name, prefix, 'name')
+ value = isBlobLike(value)
+ ? webidl.converters.Blob(value, prefix, 'name', { strict: false })
+ : webidl.converters.USVString(value, prefix, 'name')
+ filename = arguments.length === 3
+ ? webidl.converters.USVString(filename, prefix, 'name')
+ : undefined
-function connect (opts, callback) {
- if (callback === undefined) {
- return new Promise((resolve, reject) => {
- connect.call(this, opts, (err, data) => {
- return err ? reject(err) : resolve(data)
- })
- })
- }
+ // 2. Let entry be the result of creating an entry with name, value, and
+ // filename if given.
+ const entry = makeEntry(name, value, filename)
- try {
- const connectHandler = new ConnectHandler(opts, callback)
- this.dispatch({ ...opts, method: 'CONNECT' }, connectHandler)
- } catch (err) {
- if (typeof callback !== 'function') {
- throw err
+ // 3. If there are entries in this’s entry list whose name is name, then
+ // replace the first such entry with entry and remove the others.
+ const idx = this[kState].findIndex((entry) => entry.name === name)
+ if (idx !== -1) {
+ this[kState] = [
+ ...this[kState].slice(0, idx),
+ entry,
+ ...this[kState].slice(idx + 1).filter((entry) => entry.name !== name)
+ ]
+ } else {
+ // 4. Otherwise, append entry to this’s entry list.
+ this[kState].push(entry)
}
- const opaque = opts?.opaque
- queueMicrotask(() => callback(err, { opaque }))
}
-}
-module.exports = connect
+ [nodeUtil.inspect.custom] (depth, options) {
+ const state = this[kState].reduce((a, b) => {
+ if (a[b.name]) {
+ if (Array.isArray(a[b.name])) {
+ a[b.name].push(b.value)
+ } else {
+ a[b.name] = [a[b.name], b.value]
+ }
+ } else {
+ a[b.name] = b.value
+ }
+ return a
+ }, { __proto__: null })
-/***/ }),
+ options.depth ??= depth
+ options.colors ??= true
-/***/ 6998:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ const output = nodeUtil.formatWithOptions(options, state)
+ // remove [Object null prototype]
+ return `FormData ${output.slice(output.indexOf(']') + 2)}`
+ }
+}
+iteratorMixin('FormData', FormData, kState, 'name', 'value')
-const {
- Readable,
- Duplex,
- PassThrough
-} = __nccwpck_require__(7075)
-const {
- InvalidArgumentError,
- InvalidReturnValueError,
- RequestAbortedError
-} = __nccwpck_require__(8091)
-const util = __nccwpck_require__(1544)
-const { AsyncResource } = __nccwpck_require__(6698)
-const { addSignal, removeSignal } = __nccwpck_require__(9318)
-const assert = __nccwpck_require__(4589)
+Object.defineProperties(FormData.prototype, {
+ append: kEnumerableProperty,
+ delete: kEnumerableProperty,
+ get: kEnumerableProperty,
+ getAll: kEnumerableProperty,
+ has: kEnumerableProperty,
+ set: kEnumerableProperty,
+ [Symbol.toStringTag]: {
+ value: 'FormData',
+ configurable: true
+ }
+})
-const kResume = Symbol('resume')
+/**
+ * @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#create-an-entry
+ * @param {string} name
+ * @param {string|Blob} value
+ * @param {?string} filename
+ * @returns
+ */
+function makeEntry (name, value, filename) {
+ // 1. Set name to the result of converting name into a scalar value string.
+ // Note: This operation was done by the webidl converter USVString.
-class PipelineRequest extends Readable {
- constructor () {
- super({ autoDestroy: true })
+ // 2. If value is a string, then set value to the result of converting
+ // value into a scalar value string.
+ if (typeof value === 'string') {
+ // Note: This operation was done by the webidl converter USVString.
+ } else {
+ // 3. Otherwise:
- this[kResume] = null
- }
+ // 1. If value is not a File object, then set value to a new File object,
+ // representing the same bytes, whose name attribute value is "blob"
+ if (!isFileLike(value)) {
+ value = value instanceof Blob
+ ? new File([value], 'blob', { type: value.type })
+ : new FileLike(value, 'blob', { type: value.type })
+ }
- _read () {
- const { [kResume]: resume } = this
+ // 2. If filename is given, then set value to a new File object,
+ // representing the same bytes, whose name attribute is filename.
+ if (filename !== undefined) {
+ /** @type {FilePropertyBag} */
+ const options = {
+ type: value.type,
+ lastModified: value.lastModified
+ }
- if (resume) {
- this[kResume] = null
- resume()
+ value = value instanceof NativeFile
+ ? new File([value], filename, options)
+ : new FileLike(value, filename, options)
}
}
- _destroy (err, callback) {
- this._read()
-
- callback(err)
- }
+ // 4. Return an entry whose name is name and whose value is value.
+ return { name, value }
}
-class PipelineResponse extends Readable {
- constructor (resume) {
- super({ autoDestroy: true })
- this[kResume] = resume
- }
+module.exports = { FormData, makeEntry }
- _read () {
- this[kResume]()
- }
- _destroy (err, callback) {
- if (!err && !this._readableState.endEmitted) {
- err = new RequestAbortedError()
- }
+/***/ }),
- callback(err)
- }
-}
+/***/ 1059:
+/***/ ((module) => {
-class PipelineHandler extends AsyncResource {
- constructor (opts, handler) {
- if (!opts || typeof opts !== 'object') {
- throw new InvalidArgumentError('invalid opts')
- }
- if (typeof handler !== 'function') {
- throw new InvalidArgumentError('invalid handler')
- }
- const { signal, method, opaque, onInfo, responseHeaders } = opts
+// In case of breaking changes, increase the version
+// number to avoid conflicts.
+const globalOrigin = Symbol.for('undici.globalOrigin.1')
- if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
- throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
- }
+function getGlobalOrigin () {
+ return globalThis[globalOrigin]
+}
- if (method === 'CONNECT') {
- throw new InvalidArgumentError('invalid method')
- }
+function setGlobalOrigin (newOrigin) {
+ if (newOrigin === undefined) {
+ Object.defineProperty(globalThis, globalOrigin, {
+ value: undefined,
+ writable: true,
+ enumerable: false,
+ configurable: false
+ })
- if (onInfo && typeof onInfo !== 'function') {
- throw new InvalidArgumentError('invalid onInfo callback')
- }
+ return
+ }
- super('UNDICI_PIPELINE')
+ const parsedURL = new URL(newOrigin)
- this.opaque = opaque || null
- this.responseHeaders = responseHeaders || null
- this.handler = handler
- this.abort = null
- this.context = null
- this.onInfo = onInfo || null
+ if (parsedURL.protocol !== 'http:' && parsedURL.protocol !== 'https:') {
+ throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`)
+ }
- this.req = new PipelineRequest().on('error', util.nop)
+ Object.defineProperty(globalThis, globalOrigin, {
+ value: parsedURL,
+ writable: true,
+ enumerable: false,
+ configurable: false
+ })
+}
- this.ret = new Duplex({
- readableObjectMode: opts.objectMode,
- autoDestroy: true,
- read: () => {
- const { body } = this
+module.exports = {
+ getGlobalOrigin,
+ setGlobalOrigin
+}
- if (body?.resume) {
- body.resume()
- }
- },
- write: (chunk, encoding, callback) => {
- const { req } = this
- if (req.push(chunk, encoding) || req._readableState.destroyed) {
- callback()
- } else {
- req[kResume] = callback
- }
- },
- destroy: (err, callback) => {
- const { body, req, res, ret, abort } = this
+/***/ }),
- if (!err && !ret._readableState.endEmitted) {
- err = new RequestAbortedError()
- }
+/***/ 660:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- if (abort && err) {
- abort()
- }
+// https://github.com/Ethan-Arrowood/undici-fetch
- util.destroy(body, err)
- util.destroy(req, err)
- util.destroy(res, err)
- removeSignal(this)
- callback(err)
- }
- }).on('prefinish', () => {
- const { req } = this
+const { kConstruct } = __nccwpck_require__(6443)
+const { kEnumerableProperty } = __nccwpck_require__(3440)
+const {
+ iteratorMixin,
+ isValidHeaderName,
+ isValidHeaderValue
+} = __nccwpck_require__(3168)
+const { webidl } = __nccwpck_require__(5893)
+const assert = __nccwpck_require__(4589)
+const util = __nccwpck_require__(7975)
- // Node < 15 does not call _final in same tick.
- req.push(null)
- })
+const kHeadersMap = Symbol('headers map')
+const kHeadersSortedMap = Symbol('headers map sorted')
- this.res = null
+/**
+ * @param {number} code
+ */
+function isHTTPWhiteSpaceCharCode (code) {
+ return code === 0x00a || code === 0x00d || code === 0x009 || code === 0x020
+}
- addSignal(this, signal)
- }
+/**
+ * @see https://fetch.spec.whatwg.org/#concept-header-value-normalize
+ * @param {string} potentialValue
+ */
+function headerValueNormalize (potentialValue) {
+ // To normalize a byte sequence potentialValue, remove
+ // any leading and trailing HTTP whitespace bytes from
+ // potentialValue.
+ let i = 0; let j = potentialValue.length
- onConnect (abort, context) {
- const { ret, res } = this
+ while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j - 1))) --j
+ while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i))) ++i
- if (this.reason) {
- abort(this.reason)
- return
- }
+ return i === 0 && j === potentialValue.length ? potentialValue : potentialValue.substring(i, j)
+}
- assert(!res, 'pipeline cannot be retried')
- assert(!ret.destroyed)
+function fill (headers, object) {
+ // To fill a Headers object headers with a given object object, run these steps:
- this.abort = abort
- this.context = context
- }
+ // 1. If object is a sequence, then for each header in object:
+ // Note: webidl conversion to array has already been done.
+ if (Array.isArray(object)) {
+ for (let i = 0; i < object.length; ++i) {
+ const header = object[i]
+ // 1. If header does not contain exactly two items, then throw a TypeError.
+ if (header.length !== 2) {
+ throw webidl.errors.exception({
+ header: 'Headers constructor',
+ message: `expected name/value pair to be length 2, found ${header.length}.`
+ })
+ }
- onHeaders (statusCode, rawHeaders, resume) {
- const { opaque, handler, context } = this
+ // 2. Append (header’s first item, header’s second item) to headers.
+ appendHeader(headers, header[0], header[1])
+ }
+ } else if (typeof object === 'object' && object !== null) {
+ // Note: null should throw
- if (statusCode < 200) {
- if (this.onInfo) {
- const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
- this.onInfo({ statusCode, headers })
- }
- return
+ // 2. Otherwise, object is a record, then for each key → value in object,
+ // append (key, value) to headers
+ const keys = Object.keys(object)
+ for (let i = 0; i < keys.length; ++i) {
+ appendHeader(headers, keys[i], object[keys[i]])
}
+ } else {
+ throw webidl.errors.conversionFailed({
+ prefix: 'Headers constructor',
+ argument: 'Argument 1',
+ types: ['sequence>', 'record']
+ })
+ }
+}
- this.res = new PipelineResponse(resume)
+/**
+ * @see https://fetch.spec.whatwg.org/#concept-headers-append
+ */
+function appendHeader (headers, name, value) {
+ // 1. Normalize value.
+ value = headerValueNormalize(value)
- let body
- try {
- this.handler = null
- const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
- body = this.runInAsyncScope(handler, null, {
- statusCode,
- headers,
- opaque,
- body: this.res,
- context
- })
- } catch (err) {
- this.res.on('error', util.nop)
- throw err
- }
+ // 2. If name is not a header name or value is not a
+ // header value, then throw a TypeError.
+ if (!isValidHeaderName(name)) {
+ throw webidl.errors.invalidArgument({
+ prefix: 'Headers.append',
+ value: name,
+ type: 'header name'
+ })
+ } else if (!isValidHeaderValue(value)) {
+ throw webidl.errors.invalidArgument({
+ prefix: 'Headers.append',
+ value,
+ type: 'header value'
+ })
+ }
- if (!body || typeof body.on !== 'function') {
- throw new InvalidReturnValueError('expected Readable')
- }
+ // 3. If headers’s guard is "immutable", then throw a TypeError.
+ // 4. Otherwise, if headers’s guard is "request" and name is a
+ // forbidden header name, return.
+ // 5. Otherwise, if headers’s guard is "request-no-cors":
+ // TODO
+ // Note: undici does not implement forbidden header names
+ if (getHeadersGuard(headers) === 'immutable') {
+ throw new TypeError('immutable')
+ }
- body
- .on('data', (chunk) => {
- const { ret, body } = this
+ // 6. Otherwise, if headers’s guard is "response" and name is a
+ // forbidden response-header name, return.
- if (!ret.push(chunk) && body.pause) {
- body.pause()
- }
- })
- .on('error', (err) => {
- const { ret } = this
+ // 7. Append (name, value) to headers’s header list.
+ return getHeadersList(headers).append(name, value, false)
- util.destroy(ret, err)
- })
- .on('end', () => {
- const { ret } = this
+ // 8. If headers’s guard is "request-no-cors", then remove
+ // privileged no-CORS request headers from headers
+}
- ret.push(null)
- })
- .on('close', () => {
- const { ret } = this
+function compareHeaderName (a, b) {
+ return a[0] < b[0] ? -1 : 1
+}
- if (!ret._readableState.ended) {
- util.destroy(ret, new RequestAbortedError())
- }
- })
+class HeadersList {
+ /** @type {[string, string][]|null} */
+ cookies = null
- this.body = body
+ constructor (init) {
+ if (init instanceof HeadersList) {
+ this[kHeadersMap] = new Map(init[kHeadersMap])
+ this[kHeadersSortedMap] = init[kHeadersSortedMap]
+ this.cookies = init.cookies === null ? null : [...init.cookies]
+ } else {
+ this[kHeadersMap] = new Map(init)
+ this[kHeadersSortedMap] = null
+ }
}
- onData (chunk) {
- const { res } = this
- return res.push(chunk)
- }
+ /**
+ * @see https://fetch.spec.whatwg.org/#header-list-contains
+ * @param {string} name
+ * @param {boolean} isLowerCase
+ */
+ contains (name, isLowerCase) {
+ // A header list list contains a header name name if list
+ // contains a header whose name is a byte-case-insensitive
+ // match for name.
- onComplete (trailers) {
- const { res } = this
- res.push(null)
+ return this[kHeadersMap].has(isLowerCase ? name : name.toLowerCase())
}
- onError (err) {
- const { ret } = this
- this.handler = null
- util.destroy(ret, err)
+ clear () {
+ this[kHeadersMap].clear()
+ this[kHeadersSortedMap] = null
+ this.cookies = null
}
-}
-function pipeline (opts, handler) {
- try {
- const pipelineHandler = new PipelineHandler(opts, handler)
- this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler)
- return pipelineHandler.ret
- } catch (err) {
- return new PassThrough().destroy(err)
- }
-}
+ /**
+ * @see https://fetch.spec.whatwg.org/#concept-header-list-append
+ * @param {string} name
+ * @param {string} value
+ * @param {boolean} isLowerCase
+ */
+ append (name, value, isLowerCase) {
+ this[kHeadersSortedMap] = null
-module.exports = pipeline
+ // 1. If list contains name, then set name to the first such
+ // header’s name.
+ const lowercaseName = isLowerCase ? name : name.toLowerCase()
+ const exists = this[kHeadersMap].get(lowercaseName)
+ // 2. Append (name, value) to list.
+ if (exists) {
+ const delimiter = lowercaseName === 'cookie' ? '; ' : ', '
+ this[kHeadersMap].set(lowercaseName, {
+ name: exists.name,
+ value: `${exists.value}${delimiter}${value}`
+ })
+ } else {
+ this[kHeadersMap].set(lowercaseName, { name, value })
+ }
-/***/ }),
+ if (lowercaseName === 'set-cookie') {
+ (this.cookies ??= []).push(value)
+ }
+ }
-/***/ 8675:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ /**
+ * @see https://fetch.spec.whatwg.org/#concept-header-list-set
+ * @param {string} name
+ * @param {string} value
+ * @param {boolean} isLowerCase
+ */
+ set (name, value, isLowerCase) {
+ this[kHeadersSortedMap] = null
+ const lowercaseName = isLowerCase ? name : name.toLowerCase()
+ if (lowercaseName === 'set-cookie') {
+ this.cookies = [value]
+ }
+ // 1. If list contains name, then set the value of
+ // the first such header to value and remove the
+ // others.
+ // 2. Otherwise, append header (name, value) to list.
+ this[kHeadersMap].set(lowercaseName, { name, value })
+ }
-const assert = __nccwpck_require__(4589)
-const { Readable } = __nccwpck_require__(3135)
-const { InvalidArgumentError, RequestAbortedError } = __nccwpck_require__(8091)
-const util = __nccwpck_require__(1544)
-const { getResolveErrorBodyCallback } = __nccwpck_require__(8447)
-const { AsyncResource } = __nccwpck_require__(6698)
+ /**
+ * @see https://fetch.spec.whatwg.org/#concept-header-list-delete
+ * @param {string} name
+ * @param {boolean} isLowerCase
+ */
+ delete (name, isLowerCase) {
+ this[kHeadersSortedMap] = null
+ if (!isLowerCase) name = name.toLowerCase()
-class RequestHandler extends AsyncResource {
- constructor (opts, callback) {
- if (!opts || typeof opts !== 'object') {
- throw new InvalidArgumentError('invalid opts')
+ if (name === 'set-cookie') {
+ this.cookies = null
}
- const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError, highWaterMark } = opts
-
- try {
- if (typeof callback !== 'function') {
- throw new InvalidArgumentError('invalid callback')
- }
-
- if (highWaterMark && (typeof highWaterMark !== 'number' || highWaterMark < 0)) {
- throw new InvalidArgumentError('invalid highWaterMark')
- }
+ this[kHeadersMap].delete(name)
+ }
- if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
- throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
- }
+ /**
+ * @see https://fetch.spec.whatwg.org/#concept-header-list-get
+ * @param {string} name
+ * @param {boolean} isLowerCase
+ * @returns {string | null}
+ */
+ get (name, isLowerCase) {
+ // 1. If list does not contain name, then return null.
+ // 2. Return the values of all headers in list whose name
+ // is a byte-case-insensitive match for name,
+ // separated from each other by 0x2C 0x20, in order.
+ return this[kHeadersMap].get(isLowerCase ? name : name.toLowerCase())?.value ?? null
+ }
- if (method === 'CONNECT') {
- throw new InvalidArgumentError('invalid method')
- }
+ * [Symbol.iterator] () {
+ // use the lowercased name
+ for (const { 0: name, 1: { value } } of this[kHeadersMap]) {
+ yield [name, value]
+ }
+ }
- if (onInfo && typeof onInfo !== 'function') {
- throw new InvalidArgumentError('invalid onInfo callback')
- }
+ get entries () {
+ const headers = {}
- super('UNDICI_REQUEST')
- } catch (err) {
- if (util.isStream(body)) {
- util.destroy(body.on('error', util.nop), err)
+ if (this[kHeadersMap].size !== 0) {
+ for (const { name, value } of this[kHeadersMap].values()) {
+ headers[name] = value
}
- throw err
}
- this.method = method
- this.responseHeaders = responseHeaders || null
- this.opaque = opaque || null
- this.callback = callback
- this.res = null
- this.abort = null
- this.body = body
- this.trailers = {}
- this.context = null
- this.onInfo = onInfo || null
- this.throwOnError = throwOnError
- this.highWaterMark = highWaterMark
- this.signal = signal
- this.reason = null
- this.removeAbortListener = null
+ return headers
+ }
- if (util.isStream(body)) {
- body.on('error', (err) => {
- this.onError(err)
- })
- }
+ rawValues () {
+ return this[kHeadersMap].values()
+ }
- if (this.signal) {
- if (this.signal.aborted) {
- this.reason = this.signal.reason ?? new RequestAbortedError()
- } else {
- this.removeAbortListener = util.addAbortListener(this.signal, () => {
- this.reason = this.signal.reason ?? new RequestAbortedError()
- if (this.res) {
- util.destroy(this.res.on('error', util.nop), this.reason)
- } else if (this.abort) {
- this.abort(this.reason)
- }
+ get entriesList () {
+ const headers = []
- if (this.removeAbortListener) {
- this.res?.off('close', this.removeAbortListener)
- this.removeAbortListener()
- this.removeAbortListener = null
+ if (this[kHeadersMap].size !== 0) {
+ for (const { 0: lowerName, 1: { name, value } } of this[kHeadersMap]) {
+ if (lowerName === 'set-cookie') {
+ for (const cookie of this.cookies) {
+ headers.push([name, cookie])
}
- })
+ } else {
+ headers.push([name, value])
+ }
}
}
+
+ return headers
}
- onConnect (abort, context) {
- if (this.reason) {
- abort(this.reason)
- return
+ // https://fetch.spec.whatwg.org/#convert-header-names-to-a-sorted-lowercase-set
+ toSortedArray () {
+ const size = this[kHeadersMap].size
+ const array = new Array(size)
+ // In most cases, you will use the fast-path.
+ // fast-path: Use binary insertion sort for small arrays.
+ if (size <= 32) {
+ if (size === 0) {
+ // If empty, it is an empty array. To avoid the first index assignment.
+ return array
+ }
+ // Improve performance by unrolling loop and avoiding double-loop.
+ // Double-loop-less version of the binary insertion sort.
+ const iterator = this[kHeadersMap][Symbol.iterator]()
+ const firstValue = iterator.next().value
+ // set [name, value] to first index.
+ array[0] = [firstValue[0], firstValue[1].value]
+ // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine
+ // 3.2.2. Assert: value is non-null.
+ assert(firstValue[1].value !== null)
+ for (
+ let i = 1, j = 0, right = 0, left = 0, pivot = 0, x, value;
+ i < size;
+ ++i
+ ) {
+ // get next value
+ value = iterator.next().value
+ // set [name, value] to current index.
+ x = array[i] = [value[0], value[1].value]
+ // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine
+ // 3.2.2. Assert: value is non-null.
+ assert(x[1] !== null)
+ left = 0
+ right = i
+ // binary search
+ while (left < right) {
+ // middle index
+ pivot = left + ((right - left) >> 1)
+ // compare header name
+ if (array[pivot][0] <= x[0]) {
+ left = pivot + 1
+ } else {
+ right = pivot
+ }
+ }
+ if (i !== pivot) {
+ j = i
+ while (j > left) {
+ array[j] = array[--j]
+ }
+ array[left] = x
+ }
+ }
+ /* c8 ignore next 4 */
+ if (!iterator.next().done) {
+ // This is for debugging and will never be called.
+ throw new TypeError('Unreachable')
+ }
+ return array
+ } else {
+ // This case would be a rare occurrence.
+ // slow-path: fallback
+ let i = 0
+ for (const { 0: name, 1: { value } } of this[kHeadersMap]) {
+ array[i++] = [name, value]
+ // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine
+ // 3.2.2. Assert: value is non-null.
+ assert(value !== null)
+ }
+ return array.sort(compareHeaderName)
}
-
- assert(this.callback)
-
- this.abort = abort
- this.context = context
}
+}
- onHeaders (statusCode, rawHeaders, resume, statusMessage) {
- const { callback, opaque, abort, context, responseHeaders, highWaterMark } = this
+// https://fetch.spec.whatwg.org/#headers-class
+class Headers {
+ #guard
+ #headersList
- const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
+ constructor (init = undefined) {
+ webidl.util.markAsUncloneable(this)
- if (statusCode < 200) {
- if (this.onInfo) {
- this.onInfo({ statusCode, headers })
- }
+ if (init === kConstruct) {
return
}
- const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers
- const contentType = parsedHeaders['content-type']
- const contentLength = parsedHeaders['content-length']
- const res = new Readable({
- resume,
- abort,
- contentType,
- contentLength: this.method !== 'HEAD' && contentLength
- ? Number(contentLength)
- : null,
- highWaterMark
- })
+ this.#headersList = new HeadersList()
- if (this.removeAbortListener) {
- res.on('close', this.removeAbortListener)
- }
+ // The new Headers(init) constructor steps are:
- this.callback = null
- this.res = res
- if (callback !== null) {
- if (this.throwOnError && statusCode >= 400) {
- this.runInAsyncScope(getResolveErrorBodyCallback, null,
- { callback, body: res, contentType, statusCode, statusMessage, headers }
- )
- } else {
- this.runInAsyncScope(callback, null, null, {
- statusCode,
- headers,
- trailers: this.trailers,
- opaque,
- body: res,
- context
- })
- }
+ // 1. Set this’s guard to "none".
+ this.#guard = 'none'
+
+ // 2. If init is given, then fill this with init.
+ if (init !== undefined) {
+ init = webidl.converters.HeadersInit(init, 'Headers contructor', 'init')
+ fill(this, init)
}
}
- onData (chunk) {
- return this.res.push(chunk)
- }
+ // https://fetch.spec.whatwg.org/#dom-headers-append
+ append (name, value) {
+ webidl.brandCheck(this, Headers)
- onComplete (trailers) {
- util.parseHeaders(trailers, this.trailers)
- this.res.push(null)
+ webidl.argumentLengthCheck(arguments, 2, 'Headers.append')
+
+ const prefix = 'Headers.append'
+ name = webidl.converters.ByteString(name, prefix, 'name')
+ value = webidl.converters.ByteString(value, prefix, 'value')
+
+ return appendHeader(this, name, value)
}
- onError (err) {
- const { res, callback, body, opaque } = this
+ // https://fetch.spec.whatwg.org/#dom-headers-delete
+ delete (name) {
+ webidl.brandCheck(this, Headers)
- if (callback) {
- // TODO: Does this need queueMicrotask?
- this.callback = null
- queueMicrotask(() => {
- this.runInAsyncScope(callback, null, err, { opaque })
- })
- }
+ webidl.argumentLengthCheck(arguments, 1, 'Headers.delete')
- if (res) {
- this.res = null
- // Ensure all queued handlers are invoked before destroying res.
- queueMicrotask(() => {
- util.destroy(res, err)
+ const prefix = 'Headers.delete'
+ name = webidl.converters.ByteString(name, prefix, 'name')
+
+ // 1. If name is not a header name, then throw a TypeError.
+ if (!isValidHeaderName(name)) {
+ throw webidl.errors.invalidArgument({
+ prefix: 'Headers.delete',
+ value: name,
+ type: 'header name'
})
}
- if (body) {
- this.body = null
- util.destroy(body, err)
+ // 2. If this’s guard is "immutable", then throw a TypeError.
+ // 3. Otherwise, if this’s guard is "request" and name is a
+ // forbidden header name, return.
+ // 4. Otherwise, if this’s guard is "request-no-cors", name
+ // is not a no-CORS-safelisted request-header name, and
+ // name is not a privileged no-CORS request-header name,
+ // return.
+ // 5. Otherwise, if this’s guard is "response" and name is
+ // a forbidden response-header name, return.
+ // Note: undici does not implement forbidden header names
+ if (this.#guard === 'immutable') {
+ throw new TypeError('immutable')
}
- if (this.removeAbortListener) {
- res?.off('close', this.removeAbortListener)
- this.removeAbortListener()
- this.removeAbortListener = null
+ // 6. If this’s header list does not contain name, then
+ // return.
+ if (!this.#headersList.contains(name, false)) {
+ return
}
- }
-}
-function request (opts, callback) {
- if (callback === undefined) {
- return new Promise((resolve, reject) => {
- request.call(this, opts, (err, data) => {
- return err ? reject(err) : resolve(data)
- })
- })
+ // 7. Delete name from this’s header list.
+ // 8. If this’s guard is "request-no-cors", then remove
+ // privileged no-CORS request headers from this.
+ this.#headersList.delete(name, false)
}
- try {
- this.dispatch(opts, new RequestHandler(opts, callback))
- } catch (err) {
- if (typeof callback !== 'function') {
- throw err
- }
- const opaque = opts?.opaque
- queueMicrotask(() => callback(err, { opaque }))
- }
-}
+ // https://fetch.spec.whatwg.org/#dom-headers-get
+ get (name) {
+ webidl.brandCheck(this, Headers)
-module.exports = request
-module.exports.RequestHandler = RequestHandler
+ webidl.argumentLengthCheck(arguments, 1, 'Headers.get')
+ const prefix = 'Headers.get'
+ name = webidl.converters.ByteString(name, prefix, 'name')
-/***/ }),
+ // 1. If name is not a header name, then throw a TypeError.
+ if (!isValidHeaderName(name)) {
+ throw webidl.errors.invalidArgument({
+ prefix,
+ value: name,
+ type: 'header name'
+ })
+ }
-/***/ 576:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 2. Return the result of getting name from this’s header
+ // list.
+ return this.#headersList.get(name, false)
+ }
+ // https://fetch.spec.whatwg.org/#dom-headers-has
+ has (name) {
+ webidl.brandCheck(this, Headers)
+ webidl.argumentLengthCheck(arguments, 1, 'Headers.has')
-const assert = __nccwpck_require__(4589)
-const { finished, PassThrough } = __nccwpck_require__(7075)
-const { InvalidArgumentError, InvalidReturnValueError } = __nccwpck_require__(8091)
-const util = __nccwpck_require__(1544)
-const { getResolveErrorBodyCallback } = __nccwpck_require__(8447)
-const { AsyncResource } = __nccwpck_require__(6698)
-const { addSignal, removeSignal } = __nccwpck_require__(9318)
+ const prefix = 'Headers.has'
+ name = webidl.converters.ByteString(name, prefix, 'name')
-class StreamHandler extends AsyncResource {
- constructor (opts, factory, callback) {
- if (!opts || typeof opts !== 'object') {
- throw new InvalidArgumentError('invalid opts')
+ // 1. If name is not a header name, then throw a TypeError.
+ if (!isValidHeaderName(name)) {
+ throw webidl.errors.invalidArgument({
+ prefix,
+ value: name,
+ type: 'header name'
+ })
}
- const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError } = opts
-
- try {
- if (typeof callback !== 'function') {
- throw new InvalidArgumentError('invalid callback')
- }
-
- if (typeof factory !== 'function') {
- throw new InvalidArgumentError('invalid factory')
- }
-
- if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
- throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
- }
+ // 2. Return true if this’s header list contains name;
+ // otherwise false.
+ return this.#headersList.contains(name, false)
+ }
- if (method === 'CONNECT') {
- throw new InvalidArgumentError('invalid method')
- }
+ // https://fetch.spec.whatwg.org/#dom-headers-set
+ set (name, value) {
+ webidl.brandCheck(this, Headers)
- if (onInfo && typeof onInfo !== 'function') {
- throw new InvalidArgumentError('invalid onInfo callback')
- }
+ webidl.argumentLengthCheck(arguments, 2, 'Headers.set')
- super('UNDICI_STREAM')
- } catch (err) {
- if (util.isStream(body)) {
- util.destroy(body.on('error', util.nop), err)
- }
- throw err
- }
+ const prefix = 'Headers.set'
+ name = webidl.converters.ByteString(name, prefix, 'name')
+ value = webidl.converters.ByteString(value, prefix, 'value')
- this.responseHeaders = responseHeaders || null
- this.opaque = opaque || null
- this.factory = factory
- this.callback = callback
- this.res = null
- this.abort = null
- this.context = null
- this.trailers = null
- this.body = body
- this.onInfo = onInfo || null
- this.throwOnError = throwOnError || false
+ // 1. Normalize value.
+ value = headerValueNormalize(value)
- if (util.isStream(body)) {
- body.on('error', (err) => {
- this.onError(err)
+ // 2. If name is not a header name or value is not a
+ // header value, then throw a TypeError.
+ if (!isValidHeaderName(name)) {
+ throw webidl.errors.invalidArgument({
+ prefix,
+ value: name,
+ type: 'header name'
+ })
+ } else if (!isValidHeaderValue(value)) {
+ throw webidl.errors.invalidArgument({
+ prefix,
+ value,
+ type: 'header value'
})
}
- addSignal(this, signal)
- }
-
- onConnect (abort, context) {
- if (this.reason) {
- abort(this.reason)
- return
+ // 3. If this’s guard is "immutable", then throw a TypeError.
+ // 4. Otherwise, if this’s guard is "request" and name is a
+ // forbidden header name, return.
+ // 5. Otherwise, if this’s guard is "request-no-cors" and
+ // name/value is not a no-CORS-safelisted request-header,
+ // return.
+ // 6. Otherwise, if this’s guard is "response" and name is a
+ // forbidden response-header name, return.
+ // Note: undici does not implement forbidden header names
+ if (this.#guard === 'immutable') {
+ throw new TypeError('immutable')
}
- assert(this.callback)
-
- this.abort = abort
- this.context = context
+ // 7. Set (name, value) in this’s header list.
+ // 8. If this’s guard is "request-no-cors", then remove
+ // privileged no-CORS request headers from this
+ this.#headersList.set(name, value, false)
}
- onHeaders (statusCode, rawHeaders, resume, statusMessage) {
- const { factory, opaque, context, callback, responseHeaders } = this
+ // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie
+ getSetCookie () {
+ webidl.brandCheck(this, Headers)
- const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
+ // 1. If this’s header list does not contain `Set-Cookie`, then return « ».
+ // 2. Return the values of all headers in this’s header list whose name is
+ // a byte-case-insensitive match for `Set-Cookie`, in order.
- if (statusCode < 200) {
- if (this.onInfo) {
- this.onInfo({ statusCode, headers })
- }
- return
+ const list = this.#headersList.cookies
+
+ if (list) {
+ return [...list]
}
- this.factory = null
+ return []
+ }
- let res
+ // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine
+ get [kHeadersSortedMap] () {
+ if (this.#headersList[kHeadersSortedMap]) {
+ return this.#headersList[kHeadersSortedMap]
+ }
- if (this.throwOnError && statusCode >= 400) {
- const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers
- const contentType = parsedHeaders['content-type']
- res = new PassThrough()
+ // 1. Let headers be an empty list of headers with the key being the name
+ // and value the value.
+ const headers = []
- this.callback = null
- this.runInAsyncScope(getResolveErrorBodyCallback, null,
- { callback, body: res, contentType, statusCode, statusMessage, headers }
- )
- } else {
- if (factory === null) {
- return
- }
+ // 2. Let names be the result of convert header names to a sorted-lowercase
+ // set with all the names of the headers in list.
+ const names = this.#headersList.toSortedArray()
- res = this.runInAsyncScope(factory, null, {
- statusCode,
- headers,
- opaque,
- context
- })
+ const cookies = this.#headersList.cookies
- if (
- !res ||
- typeof res.write !== 'function' ||
- typeof res.end !== 'function' ||
- typeof res.on !== 'function'
- ) {
- throw new InvalidReturnValueError('expected Writable')
- }
+ // fast-path
+ if (cookies === null || cookies.length === 1) {
+ // Note: The non-null assertion of value has already been done by `HeadersList#toSortedArray`
+ return (this.#headersList[kHeadersSortedMap] = names)
+ }
- // TODO: Avoid finished. It registers an unnecessary amount of listeners.
- finished(res, { readable: false }, (err) => {
- const { callback, res, opaque, trailers, abort } = this
+ // 3. For each name of names:
+ for (let i = 0; i < names.length; ++i) {
+ const { 0: name, 1: value } = names[i]
+ // 1. If name is `set-cookie`, then:
+ if (name === 'set-cookie') {
+ // 1. Let values be a list of all values of headers in list whose name
+ // is a byte-case-insensitive match for name, in order.
- this.res = null
- if (err || !res.readable) {
- util.destroy(res, err)
+ // 2. For each value of values:
+ // 1. Append (name, value) to headers.
+ for (let j = 0; j < cookies.length; ++j) {
+ headers.push([name, cookies[j]])
}
+ } else {
+ // 2. Otherwise:
- this.callback = null
- this.runInAsyncScope(callback, null, err || null, { opaque, trailers })
+ // 1. Let value be the result of getting name from list.
- if (err) {
- abort()
- }
- })
- }
+ // 2. Assert: value is non-null.
+ // Note: This operation was done by `HeadersList#toSortedArray`.
- res.on('drain', resume)
+ // 3. Append (name, value) to headers.
+ headers.push([name, value])
+ }
+ }
- this.res = res
+ // 4. Return headers.
+ return (this.#headersList[kHeadersSortedMap] = headers)
+ }
- const needDrain = res.writableNeedDrain !== undefined
- ? res.writableNeedDrain
- : res._writableState?.needDrain
+ [util.inspect.custom] (depth, options) {
+ options.depth ??= depth
- return needDrain !== true
+ return `Headers ${util.formatWithOptions(options, this.#headersList.entries)}`
}
- onData (chunk) {
- const { res } = this
+ static getHeadersGuard (o) {
+ return o.#guard
+ }
- return res ? res.write(chunk) : true
+ static setHeadersGuard (o, guard) {
+ o.#guard = guard
}
- onComplete (trailers) {
- const { res } = this
+ static getHeadersList (o) {
+ return o.#headersList
+ }
- removeSignal(this)
+ static setHeadersList (o, list) {
+ o.#headersList = list
+ }
+}
- if (!res) {
- return
- }
+const { getHeadersGuard, setHeadersGuard, getHeadersList, setHeadersList } = Headers
+Reflect.deleteProperty(Headers, 'getHeadersGuard')
+Reflect.deleteProperty(Headers, 'setHeadersGuard')
+Reflect.deleteProperty(Headers, 'getHeadersList')
+Reflect.deleteProperty(Headers, 'setHeadersList')
- this.trailers = util.parseHeaders(trailers)
+iteratorMixin('Headers', Headers, kHeadersSortedMap, 0, 1)
- res.end()
+Object.defineProperties(Headers.prototype, {
+ append: kEnumerableProperty,
+ delete: kEnumerableProperty,
+ get: kEnumerableProperty,
+ has: kEnumerableProperty,
+ set: kEnumerableProperty,
+ getSetCookie: kEnumerableProperty,
+ [Symbol.toStringTag]: {
+ value: 'Headers',
+ configurable: true
+ },
+ [util.inspect.custom]: {
+ enumerable: false
}
+})
- onError (err) {
- const { res, callback, opaque, body } = this
-
- removeSignal(this)
-
- this.factory = null
+webidl.converters.HeadersInit = function (V, prefix, argument) {
+ if (webidl.util.Type(V) === 'Object') {
+ const iterator = Reflect.get(V, Symbol.iterator)
- if (res) {
- this.res = null
- util.destroy(res, err)
- } else if (callback) {
- this.callback = null
- queueMicrotask(() => {
- this.runInAsyncScope(callback, null, err, { opaque })
- })
+ // A work-around to ensure we send the properly-cased Headers when V is a Headers object.
+ // Read https://github.com/nodejs/undici/pull/3159#issuecomment-2075537226 before touching, please.
+ if (!util.types.isProxy(V) && iterator === Headers.prototype.entries) { // Headers object
+ try {
+ return getHeadersList(V).entriesList
+ } catch {
+ // fall-through
+ }
}
- if (body) {
- this.body = null
- util.destroy(body, err)
+ if (typeof iterator === 'function') {
+ return webidl.converters['sequence>'](V, prefix, argument, iterator.bind(V))
}
- }
-}
-function stream (opts, factory, callback) {
- if (callback === undefined) {
- return new Promise((resolve, reject) => {
- stream.call(this, opts, factory, (err, data) => {
- return err ? reject(err) : resolve(data)
- })
- })
+ return webidl.converters['record'](V, prefix, argument)
}
- try {
- this.dispatch(opts, new StreamHandler(opts, factory, callback))
- } catch (err) {
- if (typeof callback !== 'function') {
- throw err
- }
- const opaque = opts?.opaque
- queueMicrotask(() => callback(err, { opaque }))
- }
+ throw webidl.errors.conversionFailed({
+ prefix: 'Headers constructor',
+ argument: 'Argument 1',
+ types: ['sequence>', 'record']
+ })
}
-module.exports = stream
+module.exports = {
+ fill,
+ // for test.
+ compareHeaderName,
+ Headers,
+ HeadersList,
+ getHeadersGuard,
+ setHeadersGuard,
+ setHeadersList,
+ getHeadersList
+}
/***/ }),
-/***/ 2274:
+/***/ 4398:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+// https://github.com/Ethan-Arrowood/undici-fetch
-const { InvalidArgumentError, SocketError } = __nccwpck_require__(8091)
-const { AsyncResource } = __nccwpck_require__(6698)
-const util = __nccwpck_require__(1544)
-const { addSignal, removeSignal } = __nccwpck_require__(9318)
-const assert = __nccwpck_require__(4589)
-
-class UpgradeHandler extends AsyncResource {
- constructor (opts, callback) {
- if (!opts || typeof opts !== 'object') {
- throw new InvalidArgumentError('invalid opts')
- }
-
- if (typeof callback !== 'function') {
- throw new InvalidArgumentError('invalid callback')
- }
- const { signal, opaque, responseHeaders } = opts
+const {
+ makeNetworkError,
+ makeAppropriateNetworkError,
+ filterResponse,
+ makeResponse,
+ fromInnerResponse
+} = __nccwpck_require__(9051)
+const { HeadersList } = __nccwpck_require__(660)
+const { Request, cloneRequest } = __nccwpck_require__(9967)
+const zlib = __nccwpck_require__(8522)
+const {
+ bytesMatch,
+ makePolicyContainer,
+ clonePolicyContainer,
+ requestBadPort,
+ TAOCheck,
+ appendRequestOriginHeader,
+ responseLocationURL,
+ requestCurrentURL,
+ setRequestReferrerPolicyOnRedirect,
+ tryUpgradeRequestToAPotentiallyTrustworthyURL,
+ createOpaqueTimingInfo,
+ appendFetchMetadata,
+ corsCheck,
+ crossOriginResourcePolicyCheck,
+ determineRequestsReferrer,
+ coarsenedSharedCurrentTime,
+ createDeferredPromise,
+ isBlobLike,
+ sameOrigin,
+ isCancelled,
+ isAborted,
+ isErrorLike,
+ fullyReadBody,
+ readableStreamClose,
+ isomorphicEncode,
+ urlIsLocal,
+ urlIsHttpHttpsScheme,
+ urlHasHttpsScheme,
+ clampAndCoarsenConnectionTimingInfo,
+ simpleRangeHeaderValue,
+ buildContentRange,
+ createInflate,
+ extractMimeType
+} = __nccwpck_require__(3168)
+const { kState, kDispatcher } = __nccwpck_require__(3627)
+const assert = __nccwpck_require__(4589)
+const { safelyExtractBody, extractBody } = __nccwpck_require__(4492)
+const {
+ redirectStatusSet,
+ nullBodyStatus,
+ safeMethodsSet,
+ requestBodyHeader,
+ subresourceSet
+} = __nccwpck_require__(4495)
+const EE = __nccwpck_require__(8474)
+const { Readable, pipeline, finished } = __nccwpck_require__(7075)
+const { addAbortListener, isErrored, isReadable, bufferToLowerCasedHeaderName } = __nccwpck_require__(3440)
+const { dataURLProcessor, serializeAMimeType, minimizeSupportedMimeType } = __nccwpck_require__(1900)
+const { getGlobalDispatcher } = __nccwpck_require__(2581)
+const { webidl } = __nccwpck_require__(5893)
+const { STATUS_CODES } = __nccwpck_require__(7067)
+const GET_OR_HEAD = ['GET', 'HEAD']
- if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
- throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
- }
+const defaultUserAgent = typeof __UNDICI_IS_NODE__ !== 'undefined' || typeof esbuildDetection !== 'undefined'
+ ? 'node'
+ : 'undici'
- super('UNDICI_UPGRADE')
+/** @type {import('buffer').resolveObjectURL} */
+let resolveObjectURL
- this.responseHeaders = responseHeaders || null
- this.opaque = opaque || null
- this.callback = callback
- this.abort = null
- this.context = null
+class Fetch extends EE {
+ constructor (dispatcher) {
+ super()
- addSignal(this, signal)
+ this.dispatcher = dispatcher
+ this.connection = null
+ this.dump = false
+ this.state = 'ongoing'
}
- onConnect (abort, context) {
- if (this.reason) {
- abort(this.reason)
+ terminate (reason) {
+ if (this.state !== 'ongoing') {
return
}
- assert(this.callback)
-
- this.abort = abort
- this.context = null
+ this.state = 'terminated'
+ this.connection?.destroy(reason)
+ this.emit('terminated', reason)
}
- onHeaders () {
- throw new SocketError('bad upgrade', null)
- }
+ // https://fetch.spec.whatwg.org/#fetch-controller-abort
+ abort (error) {
+ if (this.state !== 'ongoing') {
+ return
+ }
- onUpgrade (statusCode, rawHeaders, socket) {
- assert(statusCode === 101)
+ // 1. Set controller’s state to "aborted".
+ this.state = 'aborted'
- const { callback, opaque, context } = this
-
- removeSignal(this)
-
- this.callback = null
- const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
- this.runInAsyncScope(callback, null, null, {
- headers,
- socket,
- opaque,
- context
- })
- }
+ // 2. Let fallbackError be an "AbortError" DOMException.
+ // 3. Set error to fallbackError if it is not given.
+ if (!error) {
+ error = new DOMException('The operation was aborted.', 'AbortError')
+ }
- onError (err) {
- const { callback, opaque } = this
+ // 4. Let serializedError be StructuredSerialize(error).
+ // If that threw an exception, catch it, and let
+ // serializedError be StructuredSerialize(fallbackError).
- removeSignal(this)
+ // 5. Set controller’s serialized abort reason to serializedError.
+ this.serializedAbortReason = error
- if (callback) {
- this.callback = null
- queueMicrotask(() => {
- this.runInAsyncScope(callback, null, err, { opaque })
- })
- }
+ this.connection?.destroy(error)
+ this.emit('terminated', error)
}
}
-function upgrade (opts, callback) {
- if (callback === undefined) {
- return new Promise((resolve, reject) => {
- upgrade.call(this, opts, (err, data) => {
- return err ? reject(err) : resolve(data)
- })
- })
- }
-
- try {
- const upgradeHandler = new UpgradeHandler(opts, callback)
- this.dispatch({
- ...opts,
- method: opts.method || 'GET',
- upgrade: opts.protocol || 'Websocket'
- }, upgradeHandler)
- } catch (err) {
- if (typeof callback !== 'function') {
- throw err
- }
- const opaque = opts?.opaque
- queueMicrotask(() => callback(err, { opaque }))
- }
+function handleFetchDone (response) {
+ finalizeAndReportTiming(response, 'fetch')
}
-module.exports = upgrade
+// https://fetch.spec.whatwg.org/#fetch-method
+function fetch (input, init = undefined) {
+ webidl.argumentLengthCheck(arguments, 1, 'globalThis.fetch')
+ // 1. Let p be a new promise.
+ let p = createDeferredPromise()
-/***/ }),
+ // 2. Let requestObject be the result of invoking the initial value of
+ // Request as constructor with input and init as arguments. If this throws
+ // an exception, reject p with it and return p.
+ let requestObject
-/***/ 5407:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ try {
+ requestObject = new Request(input, init)
+ } catch (e) {
+ p.reject(e)
+ return p.promise
+ }
+ // 3. Let request be requestObject’s request.
+ const request = requestObject[kState]
+ // 4. If requestObject’s signal’s aborted flag is set, then:
+ if (requestObject.signal.aborted) {
+ // 1. Abort the fetch() call with p, request, null, and
+ // requestObject’s signal’s abort reason.
+ abortFetch(p, request, null, requestObject.signal.reason)
-module.exports.request = __nccwpck_require__(8675)
-module.exports.stream = __nccwpck_require__(576)
-module.exports.pipeline = __nccwpck_require__(6998)
-module.exports.upgrade = __nccwpck_require__(2274)
-module.exports.connect = __nccwpck_require__(9724)
+ // 2. Return p.
+ return p.promise
+ }
+ // 5. Let globalObject be request’s client’s global object.
+ const globalObject = request.client.globalObject
-/***/ }),
+ // 6. If globalObject is a ServiceWorkerGlobalScope object, then set
+ // request’s service-workers mode to "none".
+ if (globalObject?.constructor?.name === 'ServiceWorkerGlobalScope') {
+ request.serviceWorkers = 'none'
+ }
-/***/ 3135:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 7. Let responseObject be null.
+ let responseObject = null
-// Ported from https://github.com/nodejs/undici/pull/907
+ // 8. Let relevantRealm be this’s relevant Realm.
+ // 9. Let locallyAborted be false.
+ let locallyAborted = false
+ // 10. Let controller be null.
+ let controller = null
-const assert = __nccwpck_require__(4589)
-const { Readable } = __nccwpck_require__(7075)
-const { RequestAbortedError, NotSupportedError, InvalidArgumentError, AbortError } = __nccwpck_require__(8091)
-const util = __nccwpck_require__(1544)
-const { ReadableStreamFrom } = __nccwpck_require__(1544)
+ // 11. Add the following abort steps to requestObject’s signal:
+ addAbortListener(
+ requestObject.signal,
+ () => {
+ // 1. Set locallyAborted to true.
+ locallyAborted = true
-const kConsume = Symbol('kConsume')
-const kReading = Symbol('kReading')
-const kBody = Symbol('kBody')
-const kAbort = Symbol('kAbort')
-const kContentType = Symbol('kContentType')
-const kContentLength = Symbol('kContentLength')
+ // 2. Assert: controller is non-null.
+ assert(controller != null)
-const noop = () => {}
+ // 3. Abort controller with requestObject’s signal’s abort reason.
+ controller.abort(requestObject.signal.reason)
-class BodyReadable extends Readable {
- constructor ({
- resume,
- abort,
- contentType = '',
- contentLength,
- highWaterMark = 64 * 1024 // Same as nodejs fs streams.
- }) {
- super({
- autoDestroy: true,
- read: resume,
- highWaterMark
- })
+ const realResponse = responseObject?.deref()
- this._readableState.dataEmitted = false
+ // 4. Abort the fetch() call with p, request, responseObject,
+ // and requestObject’s signal’s abort reason.
+ abortFetch(p, request, realResponse, requestObject.signal.reason)
+ }
+ )
- this[kAbort] = abort
- this[kConsume] = null
- this[kBody] = null
- this[kContentType] = contentType
- this[kContentLength] = contentLength
+ // 12. Let handleFetchDone given response response be to finalize and
+ // report timing with response, globalObject, and "fetch".
+ // see function handleFetchDone
- // Is stream being consumed through Readable API?
- // This is an optimization so that we avoid checking
- // for 'data' and 'readable' listeners in the hot path
- // inside push().
- this[kReading] = false
- }
+ // 13. Set controller to the result of calling fetch given request,
+ // with processResponseEndOfBody set to handleFetchDone, and processResponse
+ // given response being these substeps:
- destroy (err) {
- if (!err && !this._readableState.endEmitted) {
- err = new RequestAbortedError()
+ const processResponse = (response) => {
+ // 1. If locallyAborted is true, terminate these substeps.
+ if (locallyAborted) {
+ return
}
- if (err) {
- this[kAbort]()
- }
+ // 2. If response’s aborted flag is set, then:
+ if (response.aborted) {
+ // 1. Let deserializedError be the result of deserialize a serialized
+ // abort reason given controller’s serialized abort reason and
+ // relevantRealm.
- return super.destroy(err)
- }
+ // 2. Abort the fetch() call with p, request, responseObject, and
+ // deserializedError.
- _destroy (err, callback) {
- // Workaround for Node "bug". If the stream is destroyed in same
- // tick as it is created, then a user who is waiting for a
- // promise (i.e micro tick) for installing a 'error' listener will
- // never get a chance and will always encounter an unhandled exception.
- if (!this[kReading]) {
- setImmediate(() => {
- callback(err)
- })
- } else {
- callback(err)
+ abortFetch(p, request, responseObject, controller.serializedAbortReason)
+ return
}
- }
- on (ev, ...args) {
- if (ev === 'data' || ev === 'readable') {
- this[kReading] = true
+ // 3. If response is a network error, then reject p with a TypeError
+ // and terminate these substeps.
+ if (response.type === 'error') {
+ p.reject(new TypeError('fetch failed', { cause: response.error }))
+ return
}
- return super.on(ev, ...args)
- }
- addListener (ev, ...args) {
- return this.on(ev, ...args)
- }
+ // 4. Set responseObject to the result of creating a Response object,
+ // given response, "immutable", and relevantRealm.
+ responseObject = new WeakRef(fromInnerResponse(response, 'immutable'))
- off (ev, ...args) {
- const ret = super.off(ev, ...args)
- if (ev === 'data' || ev === 'readable') {
- this[kReading] = (
- this.listenerCount('data') > 0 ||
- this.listenerCount('readable') > 0
- )
- }
- return ret
+ // 5. Resolve p with responseObject.
+ p.resolve(responseObject.deref())
+ p = null
}
- removeListener (ev, ...args) {
- return this.off(ev, ...args)
- }
+ controller = fetching({
+ request,
+ processResponseEndOfBody: handleFetchDone,
+ processResponse,
+ dispatcher: requestObject[kDispatcher] // undici
+ })
- push (chunk) {
- if (this[kConsume] && chunk !== null) {
- consumePush(this[kConsume], chunk)
- return this[kReading] ? super.push(chunk) : true
- }
- return super.push(chunk)
- }
+ // 14. Return p.
+ return p.promise
+}
- // https://fetch.spec.whatwg.org/#dom-body-text
- async text () {
- return consume(this, 'text')
+// https://fetch.spec.whatwg.org/#finalize-and-report-timing
+function finalizeAndReportTiming (response, initiatorType = 'other') {
+ // 1. If response is an aborted network error, then return.
+ if (response.type === 'error' && response.aborted) {
+ return
}
- // https://fetch.spec.whatwg.org/#dom-body-json
- async json () {
- return consume(this, 'json')
+ // 2. If response’s URL list is null or empty, then return.
+ if (!response.urlList?.length) {
+ return
}
- // https://fetch.spec.whatwg.org/#dom-body-blob
- async blob () {
- return consume(this, 'blob')
- }
+ // 3. Let originalURL be response’s URL list[0].
+ const originalURL = response.urlList[0]
- // https://fetch.spec.whatwg.org/#dom-body-bytes
- async bytes () {
- return consume(this, 'bytes')
- }
+ // 4. Let timingInfo be response’s timing info.
+ let timingInfo = response.timingInfo
- // https://fetch.spec.whatwg.org/#dom-body-arraybuffer
- async arrayBuffer () {
- return consume(this, 'arrayBuffer')
- }
+ // 5. Let cacheState be response’s cache state.
+ let cacheState = response.cacheState
- // https://fetch.spec.whatwg.org/#dom-body-formdata
- async formData () {
- // TODO: Implement.
- throw new NotSupportedError()
+ // 6. If originalURL’s scheme is not an HTTP(S) scheme, then return.
+ if (!urlIsHttpHttpsScheme(originalURL)) {
+ return
}
- // https://fetch.spec.whatwg.org/#dom-body-bodyused
- get bodyUsed () {
- return util.isDisturbed(this)
+ // 7. If timingInfo is null, then return.
+ if (timingInfo === null) {
+ return
}
- // https://fetch.spec.whatwg.org/#dom-body-body
- get body () {
- if (!this[kBody]) {
- this[kBody] = ReadableStreamFrom(this)
- if (this[kConsume]) {
- // TODO: Is this the best way to force a lock?
- this[kBody].getReader() // Ensure stream is locked.
- assert(this[kBody].locked)
- }
- }
- return this[kBody]
+ // 8. If response’s timing allow passed flag is not set, then:
+ if (!response.timingAllowPassed) {
+ // 1. Set timingInfo to a the result of creating an opaque timing info for timingInfo.
+ timingInfo = createOpaqueTimingInfo({
+ startTime: timingInfo.startTime
+ })
+
+ // 2. Set cacheState to the empty string.
+ cacheState = ''
}
- async dump (opts) {
- let limit = Number.isFinite(opts?.limit) ? opts.limit : 128 * 1024
- const signal = opts?.signal
+ // 9. Set timingInfo’s end time to the coarsened shared current time
+ // given global’s relevant settings object’s cross-origin isolated
+ // capability.
+ // TODO: given global’s relevant settings object’s cross-origin isolated
+ // capability?
+ timingInfo.endTime = coarsenedSharedCurrentTime()
- if (signal != null && (typeof signal !== 'object' || !('aborted' in signal))) {
- throw new InvalidArgumentError('signal must be an AbortSignal')
- }
+ // 10. Set response’s timing info to timingInfo.
+ response.timingInfo = timingInfo
- signal?.throwIfAborted()
+ // 11. Mark resource timing for timingInfo, originalURL, initiatorType,
+ // global, and cacheState.
+ markResourceTiming(
+ timingInfo,
+ originalURL.href,
+ initiatorType,
+ globalThis,
+ cacheState
+ )
+}
- if (this._readableState.closeEmitted) {
- return null
- }
+// https://w3c.github.io/resource-timing/#dfn-mark-resource-timing
+const markResourceTiming = performance.markResourceTiming
- return await new Promise((resolve, reject) => {
- if (this[kContentLength] > limit) {
- this.destroy(new AbortError())
- }
+// https://fetch.spec.whatwg.org/#abort-fetch
+function abortFetch (p, request, responseObject, error) {
+ // 1. Reject promise with error.
+ if (p) {
+ // We might have already resolved the promise at this stage
+ p.reject(error)
+ }
- const onAbort = () => {
- this.destroy(signal.reason ?? new AbortError())
+ // 2. If request’s body is not null and is readable, then cancel request’s
+ // body with error.
+ if (request.body != null && isReadable(request.body?.stream)) {
+ request.body.stream.cancel(error).catch((err) => {
+ if (err.code === 'ERR_INVALID_STATE') {
+ // Node bug?
+ return
}
- signal?.addEventListener('abort', onAbort)
-
- this
- .on('close', function () {
- signal?.removeEventListener('abort', onAbort)
- if (signal?.aborted) {
- reject(signal.reason ?? new AbortError())
- } else {
- resolve(null)
- }
- })
- .on('error', noop)
- .on('data', function (chunk) {
- limit -= chunk.length
- if (limit <= 0) {
- this.destroy()
- }
- })
- .resume()
+ throw err
})
}
-}
-// https://streams.spec.whatwg.org/#readablestream-locked
-function isLocked (self) {
- // Consume is an implicit lock.
- return (self[kBody] && self[kBody].locked === true) || self[kConsume]
-}
-
-// https://fetch.spec.whatwg.org/#body-unusable
-function isUnusable (self) {
- return util.isDisturbed(self) || isLocked(self)
-}
+ // 3. If responseObject is null, then return.
+ if (responseObject == null) {
+ return
+ }
-async function consume (stream, type) {
- assert(!stream[kConsume])
+ // 4. Let response be responseObject’s response.
+ const response = responseObject[kState]
- return new Promise((resolve, reject) => {
- if (isUnusable(stream)) {
- const rState = stream._readableState
- if (rState.destroyed && rState.closeEmitted === false) {
- stream
- .on('error', err => {
- reject(err)
- })
- .on('close', () => {
- reject(new TypeError('unusable'))
- })
- } else {
- reject(rState.errored ?? new TypeError('unusable'))
+ // 5. If response’s body is not null and is readable, then error response’s
+ // body with error.
+ if (response.body != null && isReadable(response.body?.stream)) {
+ response.body.stream.cancel(error).catch((err) => {
+ if (err.code === 'ERR_INVALID_STATE') {
+ // Node bug?
+ return
}
- } else {
- queueMicrotask(() => {
- stream[kConsume] = {
- type,
- stream,
- resolve,
- reject,
- length: 0,
- body: []
- }
-
- stream
- .on('error', function (err) {
- consumeFinish(this[kConsume], err)
- })
- .on('close', function () {
- if (this[kConsume].body !== null) {
- consumeFinish(this[kConsume], new RequestAbortedError())
- }
- })
-
- consumeStart(stream[kConsume])
- })
- }
- })
-}
-
-function consumeStart (consume) {
- if (consume.body === null) {
- return
+ throw err
+ })
}
+}
- const { _readableState: state } = consume.stream
+// https://fetch.spec.whatwg.org/#fetching
+function fetching ({
+ request,
+ processRequestBodyChunkLength,
+ processRequestEndOfBody,
+ processResponse,
+ processResponseEndOfBody,
+ processResponseConsumeBody,
+ useParallelQueue = false,
+ dispatcher = getGlobalDispatcher() // undici
+}) {
+ // Ensure that the dispatcher is set accordingly
+ assert(dispatcher)
- if (state.bufferIndex) {
- const start = state.bufferIndex
- const end = state.buffer.length
- for (let n = start; n < end; n++) {
- consumePush(consume, state.buffer[n])
- }
- } else {
- for (const chunk of state.buffer) {
- consumePush(consume, chunk)
- }
- }
+ // 1. Let taskDestination be null.
+ let taskDestination = null
- if (state.endEmitted) {
- consumeEnd(this[kConsume])
- } else {
- consume.stream.on('end', function () {
- consumeEnd(this[kConsume])
- })
- }
+ // 2. Let crossOriginIsolatedCapability be false.
+ let crossOriginIsolatedCapability = false
- consume.stream.resume()
+ // 3. If request’s client is non-null, then:
+ if (request.client != null) {
+ // 1. Set taskDestination to request’s client’s global object.
+ taskDestination = request.client.globalObject
- while (consume.stream.read() != null) {
- // Loop
+ // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin
+ // isolated capability.
+ crossOriginIsolatedCapability =
+ request.client.crossOriginIsolatedCapability
}
-}
-/**
- * @param {Buffer[]} chunks
- * @param {number} length
- */
-function chunksDecode (chunks, length) {
- if (chunks.length === 0 || length === 0) {
- return ''
- }
- const buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks, length)
- const bufferLength = buffer.length
+ // 4. If useParallelQueue is true, then set taskDestination to the result of
+ // starting a new parallel queue.
+ // TODO
- // Skip BOM.
- const start =
- bufferLength > 2 &&
- buffer[0] === 0xef &&
- buffer[1] === 0xbb &&
- buffer[2] === 0xbf
- ? 3
- : 0
- return buffer.utf8Slice(start, bufferLength)
-}
+ // 5. Let timingInfo be a new fetch timing info whose start time and
+ // post-redirect start time are the coarsened shared current time given
+ // crossOriginIsolatedCapability.
+ const currentTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability)
+ const timingInfo = createOpaqueTimingInfo({
+ startTime: currentTime
+ })
-/**
- * @param {Buffer[]} chunks
- * @param {number} length
- * @returns {Uint8Array}
- */
-function chunksConcat (chunks, length) {
- if (chunks.length === 0 || length === 0) {
- return new Uint8Array(0)
- }
- if (chunks.length === 1) {
- // fast-path
- return new Uint8Array(chunks[0])
+ // 6. Let fetchParams be a new fetch params whose
+ // request is request,
+ // timing info is timingInfo,
+ // process request body chunk length is processRequestBodyChunkLength,
+ // process request end-of-body is processRequestEndOfBody,
+ // process response is processResponse,
+ // process response consume body is processResponseConsumeBody,
+ // process response end-of-body is processResponseEndOfBody,
+ // task destination is taskDestination,
+ // and cross-origin isolated capability is crossOriginIsolatedCapability.
+ const fetchParams = {
+ controller: new Fetch(dispatcher),
+ request,
+ timingInfo,
+ processRequestBodyChunkLength,
+ processRequestEndOfBody,
+ processResponse,
+ processResponseConsumeBody,
+ processResponseEndOfBody,
+ taskDestination,
+ crossOriginIsolatedCapability
}
- const buffer = new Uint8Array(Buffer.allocUnsafeSlow(length).buffer)
- let offset = 0
- for (let i = 0; i < chunks.length; ++i) {
- const chunk = chunks[i]
- buffer.set(chunk, offset)
- offset += chunk.length
+ // 7. If request’s body is a byte sequence, then set request’s body to
+ // request’s body as a body.
+ // NOTE: Since fetching is only called from fetch, body should already be
+ // extracted.
+ assert(!request.body || request.body.stream)
+
+ // 8. If request’s window is "client", then set request’s window to request’s
+ // client, if request’s client’s global object is a Window object; otherwise
+ // "no-window".
+ if (request.window === 'client') {
+ // TODO: What if request.client is null?
+ request.window =
+ request.client?.globalObject?.constructor?.name === 'Window'
+ ? request.client
+ : 'no-window'
}
- return buffer
-}
+ // 9. If request’s origin is "client", then set request’s origin to request’s
+ // client’s origin.
+ if (request.origin === 'client') {
+ request.origin = request.client.origin
+ }
-function consumeEnd (consume) {
- const { type, body, resolve, stream, length } = consume
+ // 10. If all of the following conditions are true:
+ // TODO
- try {
- if (type === 'text') {
- resolve(chunksDecode(body, length))
- } else if (type === 'json') {
- resolve(JSON.parse(chunksDecode(body, length)))
- } else if (type === 'arrayBuffer') {
- resolve(chunksConcat(body, length).buffer)
- } else if (type === 'blob') {
- resolve(new Blob(body, { type: stream[kContentType] }))
- } else if (type === 'bytes') {
- resolve(chunksConcat(body, length))
+ // 11. If request’s policy container is "client", then:
+ if (request.policyContainer === 'client') {
+ // 1. If request’s client is non-null, then set request’s policy
+ // container to a clone of request’s client’s policy container. [HTML]
+ if (request.client != null) {
+ request.policyContainer = clonePolicyContainer(
+ request.client.policyContainer
+ )
+ } else {
+ // 2. Otherwise, set request’s policy container to a new policy
+ // container.
+ request.policyContainer = makePolicyContainer()
}
-
- consumeFinish(consume)
- } catch (err) {
- stream.destroy(err)
}
-}
-function consumePush (consume, chunk) {
- consume.length += chunk.length
- consume.body.push(chunk)
-}
+ // 12. If request’s header list does not contain `Accept`, then:
+ if (!request.headersList.contains('accept', true)) {
+ // 1. Let value be `*/*`.
+ const value = '*/*'
-function consumeFinish (consume, err) {
- if (consume.body === null) {
- return
+ // 2. A user agent should set value to the first matching statement, if
+ // any, switching on request’s destination:
+ // "document"
+ // "frame"
+ // "iframe"
+ // `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8`
+ // "image"
+ // `image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5`
+ // "style"
+ // `text/css,*/*;q=0.1`
+ // TODO
+
+ // 3. Append `Accept`/value to request’s header list.
+ request.headersList.append('accept', value, true)
}
- if (err) {
- consume.reject(err)
- } else {
- consume.resolve()
+ // 13. If request’s header list does not contain `Accept-Language`, then
+ // user agents should append `Accept-Language`/an appropriate value to
+ // request’s header list.
+ if (!request.headersList.contains('accept-language', true)) {
+ request.headersList.append('accept-language', '*', true)
}
- consume.type = null
- consume.stream = null
- consume.resolve = null
- consume.reject = null
- consume.length = 0
- consume.body = null
-}
+ // 14. If request’s priority is null, then use request’s initiator and
+ // destination appropriately in setting request’s priority to a
+ // user-agent-defined object.
+ if (request.priority === null) {
+ // TODO
+ }
-module.exports = { Readable: BodyReadable, chunksDecode }
+ // 15. If request is a subresource request, then:
+ if (subresourceSet.has(request.destination)) {
+ // TODO
+ }
+ // 16. Run main fetch given fetchParams.
+ mainFetch(fetchParams)
+ .catch(err => {
+ fetchParams.controller.terminate(err)
+ })
-/***/ }),
+ // 17. Return fetchParam's controller
+ return fetchParams.controller
+}
-/***/ 8447:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+// https://fetch.spec.whatwg.org/#concept-main-fetch
+async function mainFetch (fetchParams, recursive = false) {
+ // 1. Let request be fetchParams’s request.
+ const request = fetchParams.request
-const assert = __nccwpck_require__(4589)
-const {
- ResponseStatusCodeError
-} = __nccwpck_require__(8091)
+ // 2. Let response be null.
+ let response = null
-const { chunksDecode } = __nccwpck_require__(3135)
-const CHUNK_LIMIT = 128 * 1024
+ // 3. If request’s local-URLs-only flag is set and request’s current URL is
+ // not local, then set response to a network error.
+ if (request.localURLsOnly && !urlIsLocal(requestCurrentURL(request))) {
+ response = makeNetworkError('local URLs only')
+ }
-async function getResolveErrorBodyCallback ({ callback, body, contentType, statusCode, statusMessage, headers }) {
- assert(body)
+ // 4. Run report Content Security Policy violations for request.
+ // TODO
- let chunks = []
- let length = 0
+ // 5. Upgrade request to a potentially trustworthy URL, if appropriate.
+ tryUpgradeRequestToAPotentiallyTrustworthyURL(request)
- try {
- for await (const chunk of body) {
- chunks.push(chunk)
- length += chunk.length
- if (length > CHUNK_LIMIT) {
- chunks = []
- length = 0
- break
- }
- }
- } catch {
- chunks = []
- length = 0
- // Do nothing....
+ // 6. If should request be blocked due to a bad port, should fetching request
+ // be blocked as mixed content, or should request be blocked by Content
+ // Security Policy returns blocked, then set response to a network error.
+ if (requestBadPort(request) === 'blocked') {
+ response = makeNetworkError('bad port')
}
+ // TODO: should fetching request be blocked as mixed content?
+ // TODO: should request be blocked by Content Security Policy?
- const message = `Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`
-
- if (statusCode === 204 || !contentType || !length) {
- queueMicrotask(() => callback(new ResponseStatusCodeError(message, statusCode, headers)))
- return
+ // 7. If request’s referrer policy is the empty string, then set request’s
+ // referrer policy to request’s policy container’s referrer policy.
+ if (request.referrerPolicy === '') {
+ request.referrerPolicy = request.policyContainer.referrerPolicy
}
- const stackTraceLimit = Error.stackTraceLimit
- Error.stackTraceLimit = 0
- let payload
-
- try {
- if (isContentTypeApplicationJson(contentType)) {
- payload = JSON.parse(chunksDecode(chunks, length))
- } else if (isContentTypeText(contentType)) {
- payload = chunksDecode(chunks, length)
- }
- } catch {
- // process in a callback to avoid throwing in the microtask queue
- } finally {
- Error.stackTraceLimit = stackTraceLimit
+ // 8. If request’s referrer is not "no-referrer", then set request’s
+ // referrer to the result of invoking determine request’s referrer.
+ if (request.referrer !== 'no-referrer') {
+ request.referrer = determineRequestsReferrer(request)
}
- queueMicrotask(() => callback(new ResponseStatusCodeError(message, statusCode, headers, payload)))
-}
-const isContentTypeApplicationJson = (contentType) => {
- return (
- contentType.length > 15 &&
- contentType[11] === '/' &&
- contentType[0] === 'a' &&
- contentType[1] === 'p' &&
- contentType[2] === 'p' &&
- contentType[3] === 'l' &&
- contentType[4] === 'i' &&
- contentType[5] === 'c' &&
- contentType[6] === 'a' &&
- contentType[7] === 't' &&
- contentType[8] === 'i' &&
- contentType[9] === 'o' &&
- contentType[10] === 'n' &&
- contentType[12] === 'j' &&
- contentType[13] === 's' &&
- contentType[14] === 'o' &&
- contentType[15] === 'n'
- )
-}
+ // 9. Set request’s current URL’s scheme to "https" if all of the following
+ // conditions are true:
+ // - request’s current URL’s scheme is "http"
+ // - request’s current URL’s host is a domain
+ // - Matching request’s current URL’s host per Known HSTS Host Domain Name
+ // Matching results in either a superdomain match with an asserted
+ // includeSubDomains directive or a congruent match (with or without an
+ // asserted includeSubDomains directive). [HSTS]
+ // TODO
-const isContentTypeText = (contentType) => {
- return (
- contentType.length > 4 &&
- contentType[4] === '/' &&
- contentType[0] === 't' &&
- contentType[1] === 'e' &&
- contentType[2] === 'x' &&
- contentType[3] === 't'
- )
-}
+ // 10. If recursive is false, then run the remaining steps in parallel.
+ // TODO
-module.exports = {
- getResolveErrorBodyCallback,
- isContentTypeApplicationJson,
- isContentTypeText
-}
+ // 11. If response is null, then set response to the result of running
+ // the steps corresponding to the first matching statement:
+ if (response === null) {
+ response = await (async () => {
+ const currentURL = requestCurrentURL(request)
+
+ if (
+ // - request’s current URL’s origin is same origin with request’s origin,
+ // and request’s response tainting is "basic"
+ (sameOrigin(currentURL, request.url) && request.responseTainting === 'basic') ||
+ // request’s current URL’s scheme is "data"
+ (currentURL.protocol === 'data:') ||
+ // - request’s mode is "navigate" or "websocket"
+ (request.mode === 'navigate' || request.mode === 'websocket')
+ ) {
+ // 1. Set request’s response tainting to "basic".
+ request.responseTainting = 'basic'
+ // 2. Return the result of running scheme fetch given fetchParams.
+ return await schemeFetch(fetchParams)
+ }
-/***/ }),
+ // request’s mode is "same-origin"
+ if (request.mode === 'same-origin') {
+ // 1. Return a network error.
+ return makeNetworkError('request mode cannot be "same-origin"')
+ }
-/***/ 2296:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // request’s mode is "no-cors"
+ if (request.mode === 'no-cors') {
+ // 1. If request’s redirect mode is not "follow", then return a network
+ // error.
+ if (request.redirect !== 'follow') {
+ return makeNetworkError(
+ 'redirect mode cannot be "follow" for "no-cors" request'
+ )
+ }
+ // 2. Set request’s response tainting to "opaque".
+ request.responseTainting = 'opaque'
+ // 3. Return the result of running scheme fetch given fetchParams.
+ return await schemeFetch(fetchParams)
+ }
-const net = __nccwpck_require__(7030)
-const assert = __nccwpck_require__(4589)
-const util = __nccwpck_require__(1544)
-const { InvalidArgumentError, ConnectTimeoutError } = __nccwpck_require__(8091)
-const timers = __nccwpck_require__(2563)
+ // request’s current URL’s scheme is not an HTTP(S) scheme
+ if (!urlIsHttpHttpsScheme(requestCurrentURL(request))) {
+ // Return a network error.
+ return makeNetworkError('URL scheme must be a HTTP(S) scheme')
+ }
-function noop () {}
+ // - request’s use-CORS-preflight flag is set
+ // - request’s unsafe-request flag is set and either request’s method is
+ // not a CORS-safelisted method or CORS-unsafe request-header names with
+ // request’s header list is not empty
+ // 1. Set request’s response tainting to "cors".
+ // 2. Let corsWithPreflightResponse be the result of running HTTP fetch
+ // given fetchParams and true.
+ // 3. If corsWithPreflightResponse is a network error, then clear cache
+ // entries using request.
+ // 4. Return corsWithPreflightResponse.
+ // TODO
-let tls // include tls conditionally since it is not always available
+ // Otherwise
+ // 1. Set request’s response tainting to "cors".
+ request.responseTainting = 'cors'
-// TODO: session re-use does not wait for the first
-// connection to resolve the session and might therefore
-// resolve the same servername multiple times even when
-// re-use is enabled.
+ // 2. Return the result of running HTTP fetch given fetchParams.
+ return await httpFetch(fetchParams)
+ })()
+ }
-let SessionCache
-// FIXME: remove workaround when the Node bug is fixed
-// https://github.com/nodejs/node/issues/49344#issuecomment-1741776308
-if (global.FinalizationRegistry && !(process.env.NODE_V8_COVERAGE || process.env.UNDICI_NO_FG)) {
- SessionCache = class WeakSessionCache {
- constructor (maxCachedSessions) {
- this._maxCachedSessions = maxCachedSessions
- this._sessionCache = new Map()
- this._sessionRegistry = new global.FinalizationRegistry((key) => {
- if (this._sessionCache.size < this._maxCachedSessions) {
- return
- }
+ // 12. If recursive is true, then return response.
+ if (recursive) {
+ return response
+ }
- const ref = this._sessionCache.get(key)
- if (ref !== undefined && ref.deref() === undefined) {
- this._sessionCache.delete(key)
- }
- })
+ // 13. If response is not a network error and response is not a filtered
+ // response, then:
+ if (response.status !== 0 && !response.internalResponse) {
+ // If request’s response tainting is "cors", then:
+ if (request.responseTainting === 'cors') {
+ // 1. Let headerNames be the result of extracting header list values
+ // given `Access-Control-Expose-Headers` and response’s header list.
+ // TODO
+ // 2. If request’s credentials mode is not "include" and headerNames
+ // contains `*`, then set response’s CORS-exposed header-name list to
+ // all unique header names in response’s header list.
+ // TODO
+ // 3. Otherwise, if headerNames is not null or failure, then set
+ // response’s CORS-exposed header-name list to headerNames.
+ // TODO
}
- get (sessionKey) {
- const ref = this._sessionCache.get(sessionKey)
- return ref ? ref.deref() : null
+ // Set response to the following filtered response with response as its
+ // internal response, depending on request’s response tainting:
+ if (request.responseTainting === 'basic') {
+ response = filterResponse(response, 'basic')
+ } else if (request.responseTainting === 'cors') {
+ response = filterResponse(response, 'cors')
+ } else if (request.responseTainting === 'opaque') {
+ response = filterResponse(response, 'opaque')
+ } else {
+ assert(false)
}
+ }
- set (sessionKey, session) {
- if (this._maxCachedSessions === 0) {
- return
- }
+ // 14. Let internalResponse be response, if response is a network error,
+ // and response’s internal response otherwise.
+ let internalResponse =
+ response.status === 0 ? response : response.internalResponse
- this._sessionCache.set(sessionKey, new WeakRef(session))
- this._sessionRegistry.register(session, sessionKey)
- }
+ // 15. If internalResponse’s URL list is empty, then set it to a clone of
+ // request’s URL list.
+ if (internalResponse.urlList.length === 0) {
+ internalResponse.urlList.push(...request.urlList)
}
-} else {
- SessionCache = class SimpleSessionCache {
- constructor (maxCachedSessions) {
- this._maxCachedSessions = maxCachedSessions
- this._sessionCache = new Map()
- }
- get (sessionKey) {
- return this._sessionCache.get(sessionKey)
+ // 16. If request’s timing allow failed flag is unset, then set
+ // internalResponse’s timing allow passed flag.
+ if (!request.timingAllowFailed) {
+ response.timingAllowPassed = true
+ }
+
+ // 17. If response is not a network error and any of the following returns
+ // blocked
+ // - should internalResponse to request be blocked as mixed content
+ // - should internalResponse to request be blocked by Content Security Policy
+ // - should internalResponse to request be blocked due to its MIME type
+ // - should internalResponse to request be blocked due to nosniff
+ // TODO
+
+ // 18. If response’s type is "opaque", internalResponse’s status is 206,
+ // internalResponse’s range-requested flag is set, and request’s header
+ // list does not contain `Range`, then set response and internalResponse
+ // to a network error.
+ if (
+ response.type === 'opaque' &&
+ internalResponse.status === 206 &&
+ internalResponse.rangeRequested &&
+ !request.headers.contains('range', true)
+ ) {
+ response = internalResponse = makeNetworkError()
+ }
+
+ // 19. If response is not a network error and either request’s method is
+ // `HEAD` or `CONNECT`, or internalResponse’s status is a null body status,
+ // set internalResponse’s body to null and disregard any enqueuing toward
+ // it (if any).
+ if (
+ response.status !== 0 &&
+ (request.method === 'HEAD' ||
+ request.method === 'CONNECT' ||
+ nullBodyStatus.includes(internalResponse.status))
+ ) {
+ internalResponse.body = null
+ fetchParams.controller.dump = true
+ }
+
+ // 20. If request’s integrity metadata is not the empty string, then:
+ if (request.integrity) {
+ // 1. Let processBodyError be this step: run fetch finale given fetchParams
+ // and a network error.
+ const processBodyError = (reason) =>
+ fetchFinale(fetchParams, makeNetworkError(reason))
+
+ // 2. If request’s response tainting is "opaque", or response’s body is null,
+ // then run processBodyError and abort these steps.
+ if (request.responseTainting === 'opaque' || response.body == null) {
+ processBodyError(response.error)
+ return
}
- set (sessionKey, session) {
- if (this._maxCachedSessions === 0) {
+ // 3. Let processBody given bytes be these steps:
+ const processBody = (bytes) => {
+ // 1. If bytes do not match request’s integrity metadata,
+ // then run processBodyError and abort these steps. [SRI]
+ if (!bytesMatch(bytes, request.integrity)) {
+ processBodyError('integrity mismatch')
return
}
- if (this._sessionCache.size >= this._maxCachedSessions) {
- // remove the oldest session
- const { value: oldestKey } = this._sessionCache.keys().next()
- this._sessionCache.delete(oldestKey)
- }
+ // 2. Set response’s body to bytes as a body.
+ response.body = safelyExtractBody(bytes)[0]
- this._sessionCache.set(sessionKey, session)
+ // 3. Run fetch finale given fetchParams and response.
+ fetchFinale(fetchParams, response)
}
+
+ // 4. Fully read response’s body given processBody and processBodyError.
+ await fullyReadBody(response.body, processBody, processBodyError)
+ } else {
+ // 21. Otherwise, run fetch finale given fetchParams and response.
+ fetchFinale(fetchParams, response)
}
}
-function buildConnector ({ allowH2, maxCachedSessions, socketPath, timeout, session: customSession, ...opts }) {
- if (maxCachedSessions != null && (!Number.isInteger(maxCachedSessions) || maxCachedSessions < 0)) {
- throw new InvalidArgumentError('maxCachedSessions must be a positive integer or zero')
+// https://fetch.spec.whatwg.org/#concept-scheme-fetch
+// given a fetch params fetchParams
+function schemeFetch (fetchParams) {
+ // Note: since the connection is destroyed on redirect, which sets fetchParams to a
+ // cancelled state, we do not want this condition to trigger *unless* there have been
+ // no redirects. See https://github.com/nodejs/undici/issues/1776
+ // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
+ if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) {
+ return Promise.resolve(makeAppropriateNetworkError(fetchParams))
}
- const options = { path: socketPath, ...opts }
- const sessionCache = new SessionCache(maxCachedSessions == null ? 100 : maxCachedSessions)
- timeout = timeout == null ? 10e3 : timeout
- allowH2 = allowH2 != null ? allowH2 : false
- return function connect ({ hostname, host, protocol, port, servername, localAddress, httpSocket }, callback) {
- let socket
- if (protocol === 'https:') {
- if (!tls) {
- tls = __nccwpck_require__(1692)
+ // 2. Let request be fetchParams’s request.
+ const { request } = fetchParams
+
+ const { protocol: scheme } = requestCurrentURL(request)
+
+ // 3. Switch on request’s current URL’s scheme and run the associated steps:
+ switch (scheme) {
+ case 'about:': {
+ // If request’s current URL’s path is the string "blank", then return a new response
+ // whose status message is `OK`, header list is « (`Content-Type`, `text/html;charset=utf-8`) »,
+ // and body is the empty byte sequence as a body.
+
+ // Otherwise, return a network error.
+ return Promise.resolve(makeNetworkError('about scheme is not supported'))
+ }
+ case 'blob:': {
+ if (!resolveObjectURL) {
+ resolveObjectURL = (__nccwpck_require__(4573).resolveObjectURL)
}
- servername = servername || options.servername || util.getServerName(host) || null
- const sessionKey = servername || hostname
- assert(sessionKey)
+ // 1. Let blobURLEntry be request’s current URL’s blob URL entry.
+ const blobURLEntry = requestCurrentURL(request)
- const session = customSession || sessionCache.get(sessionKey) || null
+ // https://github.com/web-platform-tests/wpt/blob/7b0ebaccc62b566a1965396e5be7bb2bc06f841f/FileAPI/url/resources/fetch-tests.js#L52-L56
+ // Buffer.resolveObjectURL does not ignore URL queries.
+ if (blobURLEntry.search.length !== 0) {
+ return Promise.resolve(makeNetworkError('NetworkError when attempting to fetch resource.'))
+ }
- port = port || 443
+ const blob = resolveObjectURL(blobURLEntry.toString())
- socket = tls.connect({
- highWaterMark: 16384, // TLS in node can't have bigger HWM anyway...
- ...options,
- servername,
- session,
- localAddress,
- // TODO(HTTP/2): Add support for h2c
- ALPNProtocols: allowH2 ? ['http/1.1', 'h2'] : ['http/1.1'],
- socket: httpSocket, // upgrade socket connection
- port,
- host: hostname
- })
+ // 2. If request’s method is not `GET`, blobURLEntry is null, or blobURLEntry’s
+ // object is not a Blob object, then return a network error.
+ if (request.method !== 'GET' || !isBlobLike(blob)) {
+ return Promise.resolve(makeNetworkError('invalid method'))
+ }
- socket
- .on('session', function (session) {
- // TODO (fix): Can a session become invalid once established? Don't think so?
- sessionCache.set(sessionKey, session)
- })
- } else {
- assert(!httpSocket, 'httpSocket can only be sent on TLS update')
+ // 3. Let blob be blobURLEntry’s object.
+ // Note: done above
- port = port || 80
+ // 4. Let response be a new response.
+ const response = makeResponse()
- socket = net.connect({
- highWaterMark: 64 * 1024, // Same as nodejs fs streams.
- ...options,
- localAddress,
- port,
- host: hostname
- })
- }
+ // 5. Let fullLength be blob’s size.
+ const fullLength = blob.size
- // Set TCP keep alive options on the socket here instead of in connect() for the case of assigning the socket
- if (options.keepAlive == null || options.keepAlive) {
- const keepAliveInitialDelay = options.keepAliveInitialDelay === undefined ? 60e3 : options.keepAliveInitialDelay
- socket.setKeepAlive(true, keepAliveInitialDelay)
- }
+ // 6. Let serializedFullLength be fullLength, serialized and isomorphic encoded.
+ const serializedFullLength = isomorphicEncode(`${fullLength}`)
- const clearConnectTimeout = setupConnectTimeout(new WeakRef(socket), { timeout, hostname, port })
+ // 7. Let type be blob’s type.
+ const type = blob.type
- socket
- .setNoDelay(true)
- .once(protocol === 'https:' ? 'secureConnect' : 'connect', function () {
- queueMicrotask(clearConnectTimeout)
+ // 8. If request’s header list does not contain `Range`:
+ // 9. Otherwise:
+ if (!request.headersList.contains('range', true)) {
+ // 1. Let bodyWithType be the result of safely extracting blob.
+ // Note: in the FileAPI a blob "object" is a Blob *or* a MediaSource.
+ // In node, this can only ever be a Blob. Therefore we can safely
+ // use extractBody directly.
+ const bodyWithType = extractBody(blob)
- if (callback) {
- const cb = callback
- callback = null
- cb(null, this)
+ // 2. Set response’s status message to `OK`.
+ response.statusText = 'OK'
+
+ // 3. Set response’s body to bodyWithType’s body.
+ response.body = bodyWithType[0]
+
+ // 4. Set response’s header list to « (`Content-Length`, serializedFullLength), (`Content-Type`, type) ».
+ response.headersList.set('content-length', serializedFullLength, true)
+ response.headersList.set('content-type', type, true)
+ } else {
+ // 1. Set response’s range-requested flag.
+ response.rangeRequested = true
+
+ // 2. Let rangeHeader be the result of getting `Range` from request’s header list.
+ const rangeHeader = request.headersList.get('range', true)
+
+ // 3. Let rangeValue be the result of parsing a single range header value given rangeHeader and true.
+ const rangeValue = simpleRangeHeaderValue(rangeHeader, true)
+
+ // 4. If rangeValue is failure, then return a network error.
+ if (rangeValue === 'failure') {
+ return Promise.resolve(makeNetworkError('failed to fetch the data URL'))
}
- })
- .on('error', function (err) {
- queueMicrotask(clearConnectTimeout)
- if (callback) {
- const cb = callback
- callback = null
- cb(err)
+ // 5. Let (rangeStart, rangeEnd) be rangeValue.
+ let { rangeStartValue: rangeStart, rangeEndValue: rangeEnd } = rangeValue
+
+ // 6. If rangeStart is null:
+ // 7. Otherwise:
+ if (rangeStart === null) {
+ // 1. Set rangeStart to fullLength − rangeEnd.
+ rangeStart = fullLength - rangeEnd
+
+ // 2. Set rangeEnd to rangeStart + rangeEnd − 1.
+ rangeEnd = rangeStart + rangeEnd - 1
+ } else {
+ // 1. If rangeStart is greater than or equal to fullLength, then return a network error.
+ if (rangeStart >= fullLength) {
+ return Promise.resolve(makeNetworkError('Range start is greater than the blob\'s size.'))
+ }
+
+ // 2. If rangeEnd is null or rangeEnd is greater than or equal to fullLength, then set
+ // rangeEnd to fullLength − 1.
+ if (rangeEnd === null || rangeEnd >= fullLength) {
+ rangeEnd = fullLength - 1
+ }
}
- })
- return socket
- }
-}
+ // 8. Let slicedBlob be the result of invoking slice blob given blob, rangeStart,
+ // rangeEnd + 1, and type.
+ const slicedBlob = blob.slice(rangeStart, rangeEnd, type)
-/**
- * @param {WeakRef} socketWeakRef
- * @param {object} opts
- * @param {number} opts.timeout
- * @param {string} opts.hostname
- * @param {number} opts.port
- * @returns {() => void}
- */
-const setupConnectTimeout = process.platform === 'win32'
- ? (socketWeakRef, opts) => {
- if (!opts.timeout) {
- return noop
- }
+ // 9. Let slicedBodyWithType be the result of safely extracting slicedBlob.
+ // Note: same reason as mentioned above as to why we use extractBody
+ const slicedBodyWithType = extractBody(slicedBlob)
- let s1 = null
- let s2 = null
- const fastTimer = timers.setFastTimeout(() => {
- // setImmediate is added to make sure that we prioritize socket error events over timeouts
- s1 = setImmediate(() => {
- // Windows needs an extra setImmediate probably due to implementation differences in the socket logic
- s2 = setImmediate(() => onConnectTimeout(socketWeakRef.deref(), opts))
- })
- }, opts.timeout)
- return () => {
- timers.clearFastTimeout(fastTimer)
- clearImmediate(s1)
- clearImmediate(s2)
+ // 10. Set response’s body to slicedBodyWithType’s body.
+ response.body = slicedBodyWithType[0]
+
+ // 11. Let serializedSlicedLength be slicedBlob’s size, serialized and isomorphic encoded.
+ const serializedSlicedLength = isomorphicEncode(`${slicedBlob.size}`)
+
+ // 12. Let contentRange be the result of invoking build a content range given rangeStart,
+ // rangeEnd, and fullLength.
+ const contentRange = buildContentRange(rangeStart, rangeEnd, fullLength)
+
+ // 13. Set response’s status to 206.
+ response.status = 206
+
+ // 14. Set response’s status message to `Partial Content`.
+ response.statusText = 'Partial Content'
+
+ // 15. Set response’s header list to « (`Content-Length`, serializedSlicedLength),
+ // (`Content-Type`, type), (`Content-Range`, contentRange) ».
+ response.headersList.set('content-length', serializedSlicedLength, true)
+ response.headersList.set('content-type', type, true)
+ response.headersList.set('content-range', contentRange, true)
}
+
+ // 10. Return response.
+ return Promise.resolve(response)
}
- : (socketWeakRef, opts) => {
- if (!opts.timeout) {
- return noop
- }
+ case 'data:': {
+ // 1. Let dataURLStruct be the result of running the
+ // data: URL processor on request’s current URL.
+ const currentURL = requestCurrentURL(request)
+ const dataURLStruct = dataURLProcessor(currentURL)
- let s1 = null
- const fastTimer = timers.setFastTimeout(() => {
- // setImmediate is added to make sure that we prioritize socket error events over timeouts
- s1 = setImmediate(() => {
- onConnectTimeout(socketWeakRef.deref(), opts)
- })
- }, opts.timeout)
- return () => {
- timers.clearFastTimeout(fastTimer)
- clearImmediate(s1)
+ // 2. If dataURLStruct is failure, then return a
+ // network error.
+ if (dataURLStruct === 'failure') {
+ return Promise.resolve(makeNetworkError('failed to fetch the data URL'))
}
+
+ // 3. Let mimeType be dataURLStruct’s MIME type, serialized.
+ const mimeType = serializeAMimeType(dataURLStruct.mimeType)
+
+ // 4. Return a response whose status message is `OK`,
+ // header list is « (`Content-Type`, mimeType) »,
+ // and body is dataURLStruct’s body as a body.
+ return Promise.resolve(makeResponse({
+ statusText: 'OK',
+ headersList: [
+ ['content-type', { name: 'Content-Type', value: mimeType }]
+ ],
+ body: safelyExtractBody(dataURLStruct.body)[0]
+ }))
+ }
+ case 'file:': {
+ // For now, unfortunate as it is, file URLs are left as an exercise for the reader.
+ // When in doubt, return a network error.
+ return Promise.resolve(makeNetworkError('not implemented... yet...'))
}
+ case 'http:':
+ case 'https:': {
+ // Return the result of running HTTP fetch given fetchParams.
-/**
- * @param {net.Socket} socket
- * @param {object} opts
- * @param {number} opts.timeout
- * @param {string} opts.hostname
- * @param {number} opts.port
- */
-function onConnectTimeout (socket, opts) {
- // The socket could be already garbage collected
- if (socket == null) {
- return
+ return httpFetch(fetchParams)
+ .catch((err) => makeNetworkError(err))
+ }
+ default: {
+ return Promise.resolve(makeNetworkError('unknown scheme'))
+ }
}
+}
- let message = 'Connect Timeout Error'
- if (Array.isArray(socket.autoSelectFamilyAttemptedAddresses)) {
- message += ` (attempted addresses: ${socket.autoSelectFamilyAttemptedAddresses.join(', ')},`
- } else {
- message += ` (attempted address: ${opts.hostname}:${opts.port},`
+// https://fetch.spec.whatwg.org/#finalize-response
+function finalizeResponse (fetchParams, response) {
+ // 1. Set fetchParams’s request’s done flag.
+ fetchParams.request.done = true
+
+ // 2, If fetchParams’s process response done is not null, then queue a fetch
+ // task to run fetchParams’s process response done given response, with
+ // fetchParams’s task destination.
+ if (fetchParams.processResponseDone != null) {
+ queueMicrotask(() => fetchParams.processResponseDone(response))
}
+}
- message += ` timeout: ${opts.timeout}ms)`
+// https://fetch.spec.whatwg.org/#fetch-finale
+function fetchFinale (fetchParams, response) {
+ // 1. Let timingInfo be fetchParams’s timing info.
+ let timingInfo = fetchParams.timingInfo
- util.destroy(socket, new ConnectTimeoutError(message))
-}
+ // 2. If response is not a network error and fetchParams’s request’s client is a secure context,
+ // then set timingInfo’s server-timing headers to the result of getting, decoding, and splitting
+ // `Server-Timing` from response’s internal response’s header list.
+ // TODO
-module.exports = buildConnector
+ // 3. Let processResponseEndOfBody be the following steps:
+ const processResponseEndOfBody = () => {
+ // 1. Let unsafeEndTime be the unsafe shared current time.
+ const unsafeEndTime = Date.now() // ?
+ // 2. If fetchParams’s request’s destination is "document", then set fetchParams’s controller’s
+ // full timing info to fetchParams’s timing info.
+ if (fetchParams.request.destination === 'document') {
+ fetchParams.controller.fullTimingInfo = timingInfo
+ }
-/***/ }),
+ // 3. Set fetchParams’s controller’s report timing steps to the following steps given a global object global:
+ fetchParams.controller.reportTimingSteps = () => {
+ // 1. If fetchParams’s request’s URL’s scheme is not an HTTP(S) scheme, then return.
+ if (fetchParams.request.url.protocol !== 'https:') {
+ return
+ }
-/***/ 1303:
-/***/ ((module) => {
+ // 2. Set timingInfo’s end time to the relative high resolution time given unsafeEndTime and global.
+ timingInfo.endTime = unsafeEndTime
+ // 3. Let cacheState be response’s cache state.
+ let cacheState = response.cacheState
+ // 4. Let bodyInfo be response’s body info.
+ const bodyInfo = response.bodyInfo
-/** @type {Record} */
-const headerNameLowerCasedRecord = {}
+ // 5. If response’s timing allow passed flag is not set, then set timingInfo to the result of creating an
+ // opaque timing info for timingInfo and set cacheState to the empty string.
+ if (!response.timingAllowPassed) {
+ timingInfo = createOpaqueTimingInfo(timingInfo)
-// https://developer.mozilla.org/docs/Web/HTTP/Headers
-const wellknownHeaderNames = [
- 'Accept',
- 'Accept-Encoding',
- 'Accept-Language',
- 'Accept-Ranges',
- 'Access-Control-Allow-Credentials',
- 'Access-Control-Allow-Headers',
- 'Access-Control-Allow-Methods',
- 'Access-Control-Allow-Origin',
- 'Access-Control-Expose-Headers',
- 'Access-Control-Max-Age',
- 'Access-Control-Request-Headers',
- 'Access-Control-Request-Method',
- 'Age',
- 'Allow',
- 'Alt-Svc',
- 'Alt-Used',
- 'Authorization',
- 'Cache-Control',
- 'Clear-Site-Data',
- 'Connection',
- 'Content-Disposition',
- 'Content-Encoding',
- 'Content-Language',
- 'Content-Length',
- 'Content-Location',
- 'Content-Range',
- 'Content-Security-Policy',
- 'Content-Security-Policy-Report-Only',
- 'Content-Type',
- 'Cookie',
- 'Cross-Origin-Embedder-Policy',
- 'Cross-Origin-Opener-Policy',
- 'Cross-Origin-Resource-Policy',
- 'Date',
- 'Device-Memory',
- 'Downlink',
- 'ECT',
- 'ETag',
- 'Expect',
- 'Expect-CT',
- 'Expires',
- 'Forwarded',
- 'From',
- 'Host',
- 'If-Match',
- 'If-Modified-Since',
- 'If-None-Match',
- 'If-Range',
- 'If-Unmodified-Since',
- 'Keep-Alive',
- 'Last-Modified',
- 'Link',
- 'Location',
- 'Max-Forwards',
- 'Origin',
- 'Permissions-Policy',
- 'Pragma',
- 'Proxy-Authenticate',
- 'Proxy-Authorization',
- 'RTT',
- 'Range',
- 'Referer',
- 'Referrer-Policy',
- 'Refresh',
- 'Retry-After',
- 'Sec-WebSocket-Accept',
- 'Sec-WebSocket-Extensions',
- 'Sec-WebSocket-Key',
- 'Sec-WebSocket-Protocol',
- 'Sec-WebSocket-Version',
- 'Server',
- 'Server-Timing',
- 'Service-Worker-Allowed',
- 'Service-Worker-Navigation-Preload',
- 'Set-Cookie',
- 'SourceMap',
- 'Strict-Transport-Security',
- 'Supports-Loading-Mode',
- 'TE',
- 'Timing-Allow-Origin',
- 'Trailer',
- 'Transfer-Encoding',
- 'Upgrade',
- 'Upgrade-Insecure-Requests',
- 'User-Agent',
- 'Vary',
- 'Via',
- 'WWW-Authenticate',
- 'X-Content-Type-Options',
- 'X-DNS-Prefetch-Control',
- 'X-Frame-Options',
- 'X-Permitted-Cross-Domain-Policies',
- 'X-Powered-By',
- 'X-Requested-With',
- 'X-XSS-Protection'
-]
+ cacheState = ''
+ }
-for (let i = 0; i < wellknownHeaderNames.length; ++i) {
- const key = wellknownHeaderNames[i]
- const lowerCasedKey = key.toLowerCase()
- headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] =
- lowerCasedKey
-}
+ // 6. Let responseStatus be 0.
+ let responseStatus = 0
-// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`.
-Object.setPrototypeOf(headerNameLowerCasedRecord, null)
+ // 7. If fetchParams’s request’s mode is not "navigate" or response’s has-cross-origin-redirects is false:
+ if (fetchParams.request.mode !== 'navigator' || !response.hasCrossOriginRedirects) {
+ // 1. Set responseStatus to response’s status.
+ responseStatus = response.status
-module.exports = {
- wellknownHeaderNames,
- headerNameLowerCasedRecord
-}
+ // 2. Let mimeType be the result of extracting a MIME type from response’s header list.
+ const mimeType = extractMimeType(response.headersList)
+ // 3. If mimeType is not failure, then set bodyInfo’s content type to the result of minimizing a supported MIME type given mimeType.
+ if (mimeType !== 'failure') {
+ bodyInfo.contentType = minimizeSupportedMimeType(mimeType)
+ }
+ }
-/***/ }),
+ // 8. If fetchParams’s request’s initiator type is non-null, then mark resource timing given timingInfo,
+ // fetchParams’s request’s URL, fetchParams’s request’s initiator type, global, cacheState, bodyInfo,
+ // and responseStatus.
+ if (fetchParams.request.initiatorType != null) {
+ // TODO: update markresourcetiming
+ markResourceTiming(timingInfo, fetchParams.request.url.href, fetchParams.request.initiatorType, globalThis, cacheState, bodyInfo, responseStatus)
+ }
+ }
-/***/ 8150:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 4. Let processResponseEndOfBodyTask be the following steps:
+ const processResponseEndOfBodyTask = () => {
+ // 1. Set fetchParams’s request’s done flag.
+ fetchParams.request.done = true
+ // 2. If fetchParams’s process response end-of-body is non-null, then run fetchParams’s process
+ // response end-of-body given response.
+ if (fetchParams.processResponseEndOfBody != null) {
+ queueMicrotask(() => fetchParams.processResponseEndOfBody(response))
+ }
-const diagnosticsChannel = __nccwpck_require__(3053)
-const util = __nccwpck_require__(7975)
+ // 3. If fetchParams’s request’s initiator type is non-null and fetchParams’s request’s client’s
+ // global object is fetchParams’s task destination, then run fetchParams’s controller’s report
+ // timing steps given fetchParams’s request’s client’s global object.
+ if (fetchParams.request.initiatorType != null) {
+ fetchParams.controller.reportTimingSteps()
+ }
+ }
-const undiciDebugLog = util.debuglog('undici')
-const fetchDebuglog = util.debuglog('fetch')
-const websocketDebuglog = util.debuglog('websocket')
-let isClientSet = false
-const channels = {
- // Client
- beforeConnect: diagnosticsChannel.channel('undici:client:beforeConnect'),
- connected: diagnosticsChannel.channel('undici:client:connected'),
- connectError: diagnosticsChannel.channel('undici:client:connectError'),
- sendHeaders: diagnosticsChannel.channel('undici:client:sendHeaders'),
- // Request
- create: diagnosticsChannel.channel('undici:request:create'),
- bodySent: diagnosticsChannel.channel('undici:request:bodySent'),
- headers: diagnosticsChannel.channel('undici:request:headers'),
- trailers: diagnosticsChannel.channel('undici:request:trailers'),
- error: diagnosticsChannel.channel('undici:request:error'),
- // WebSocket
- open: diagnosticsChannel.channel('undici:websocket:open'),
- close: diagnosticsChannel.channel('undici:websocket:close'),
- socketError: diagnosticsChannel.channel('undici:websocket:socket_error'),
- ping: diagnosticsChannel.channel('undici:websocket:ping'),
- pong: diagnosticsChannel.channel('undici:websocket:pong')
-}
-
-if (undiciDebugLog.enabled || fetchDebuglog.enabled) {
- const debuglog = fetchDebuglog.enabled ? fetchDebuglog : undiciDebugLog
-
- // Track all Client events
- diagnosticsChannel.channel('undici:client:beforeConnect').subscribe(evt => {
- const {
- connectParams: { version, protocol, port, host }
- } = evt
- debuglog(
- 'connecting to %s using %s%s',
- `${host}${port ? `:${port}` : ''}`,
- protocol,
- version
- )
- })
-
- diagnosticsChannel.channel('undici:client:connected').subscribe(evt => {
- const {
- connectParams: { version, protocol, port, host }
- } = evt
- debuglog(
- 'connected to %s using %s%s',
- `${host}${port ? `:${port}` : ''}`,
- protocol,
- version
- )
- })
-
- diagnosticsChannel.channel('undici:client:connectError').subscribe(evt => {
- const {
- connectParams: { version, protocol, port, host },
- error
- } = evt
- debuglog(
- 'connection to %s using %s%s errored - %s',
- `${host}${port ? `:${port}` : ''}`,
- protocol,
- version,
- error.message
- )
- })
-
- diagnosticsChannel.channel('undici:client:sendHeaders').subscribe(evt => {
- const {
- request: { method, path, origin }
- } = evt
- debuglog('sending request to %s %s/%s', method, origin, path)
- })
-
- // Track Request events
- diagnosticsChannel.channel('undici:request:headers').subscribe(evt => {
- const {
- request: { method, path, origin },
- response: { statusCode }
- } = evt
- debuglog(
- 'received response to %s %s/%s - HTTP %d',
- method,
- origin,
- path,
- statusCode
- )
- })
-
- diagnosticsChannel.channel('undici:request:trailers').subscribe(evt => {
- const {
- request: { method, path, origin }
- } = evt
- debuglog('trailers received from %s %s/%s', method, origin, path)
- })
-
- diagnosticsChannel.channel('undici:request:error').subscribe(evt => {
- const {
- request: { method, path, origin },
- error
- } = evt
- debuglog(
- 'request to %s %s/%s errored - %s',
- method,
- origin,
- path,
- error.message
- )
- })
-
- isClientSet = true
-}
+ // 5. Queue a fetch task to run processResponseEndOfBodyTask with fetchParams’s task destination
+ queueMicrotask(() => processResponseEndOfBodyTask())
+ }
-if (websocketDebuglog.enabled) {
- if (!isClientSet) {
- const debuglog = undiciDebugLog.enabled ? undiciDebugLog : websocketDebuglog
- diagnosticsChannel.channel('undici:client:beforeConnect').subscribe(evt => {
- const {
- connectParams: { version, protocol, port, host }
- } = evt
- debuglog(
- 'connecting to %s%s using %s%s',
- host,
- port ? `:${port}` : '',
- protocol,
- version
- )
+ // 4. If fetchParams’s process response is non-null, then queue a fetch task to run fetchParams’s
+ // process response given response, with fetchParams’s task destination.
+ if (fetchParams.processResponse != null) {
+ queueMicrotask(() => {
+ fetchParams.processResponse(response)
+ fetchParams.processResponse = null
})
+ }
- diagnosticsChannel.channel('undici:client:connected').subscribe(evt => {
- const {
- connectParams: { version, protocol, port, host }
- } = evt
- debuglog(
- 'connected to %s%s using %s%s',
- host,
- port ? `:${port}` : '',
- protocol,
- version
- )
- })
+ // 5. Let internalResponse be response, if response is a network error; otherwise response’s internal response.
+ const internalResponse = response.type === 'error' ? response : (response.internalResponse ?? response)
- diagnosticsChannel.channel('undici:client:connectError').subscribe(evt => {
- const {
- connectParams: { version, protocol, port, host },
- error
- } = evt
- debuglog(
- 'connection to %s%s using %s%s errored - %s',
- host,
- port ? `:${port}` : '',
- protocol,
- version,
- error.message
- )
- })
+ // 6. If internalResponse’s body is null, then run processResponseEndOfBody.
+ // 7. Otherwise:
+ if (internalResponse.body == null) {
+ processResponseEndOfBody()
+ } else {
+ // mcollina: all the following steps of the specs are skipped.
+ // The internal transform stream is not needed.
+ // See https://github.com/nodejs/undici/pull/3093#issuecomment-2050198541
- diagnosticsChannel.channel('undici:client:sendHeaders').subscribe(evt => {
- const {
- request: { method, path, origin }
- } = evt
- debuglog('sending request to %s %s/%s', method, origin, path)
+ // 1. Let transformStream be a new TransformStream.
+ // 2. Let identityTransformAlgorithm be an algorithm which, given chunk, enqueues chunk in transformStream.
+ // 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm and flushAlgorithm
+ // set to processResponseEndOfBody.
+ // 4. Set internalResponse’s body’s stream to the result of internalResponse’s body’s stream piped through transformStream.
+
+ finished(internalResponse.body.stream, () => {
+ processResponseEndOfBody()
})
}
+}
- // Track all WebSocket events
- diagnosticsChannel.channel('undici:websocket:open').subscribe(evt => {
- const {
- address: { address, port }
- } = evt
- websocketDebuglog('connection opened %s%s', address, port ? `:${port}` : '')
- })
-
- diagnosticsChannel.channel('undici:websocket:close').subscribe(evt => {
- const { websocket, code, reason } = evt
- websocketDebuglog(
- 'closed connection to %s - %s %s',
- websocket.url,
- code,
- reason
- )
- })
-
- diagnosticsChannel.channel('undici:websocket:socket_error').subscribe(err => {
- websocketDebuglog('connection errored - %s', err.message)
- })
+// https://fetch.spec.whatwg.org/#http-fetch
+async function httpFetch (fetchParams) {
+ // 1. Let request be fetchParams’s request.
+ const request = fetchParams.request
- diagnosticsChannel.channel('undici:websocket:ping').subscribe(evt => {
- websocketDebuglog('ping received')
- })
+ // 2. Let response be null.
+ let response = null
- diagnosticsChannel.channel('undici:websocket:pong').subscribe(evt => {
- websocketDebuglog('pong received')
- })
-}
+ // 3. Let actualResponse be null.
+ let actualResponse = null
-module.exports = {
- channels
-}
+ // 4. Let timingInfo be fetchParams’s timing info.
+ const timingInfo = fetchParams.timingInfo
+ // 5. If request’s service-workers mode is "all", then:
+ if (request.serviceWorkers === 'all') {
+ // TODO
+ }
-/***/ }),
+ // 6. If response is null, then:
+ if (response === null) {
+ // 1. If makeCORSPreflight is true and one of these conditions is true:
+ // TODO
-/***/ 8091:
-/***/ ((module) => {
+ // 2. If request’s redirect mode is "follow", then set request’s
+ // service-workers mode to "none".
+ if (request.redirect === 'follow') {
+ request.serviceWorkers = 'none'
+ }
+ // 3. Set response and actualResponse to the result of running
+ // HTTP-network-or-cache fetch given fetchParams.
+ actualResponse = response = await httpNetworkOrCacheFetch(fetchParams)
+ // 4. If request’s response tainting is "cors" and a CORS check
+ // for request and response returns failure, then return a network error.
+ if (
+ request.responseTainting === 'cors' &&
+ corsCheck(request, response) === 'failure'
+ ) {
+ return makeNetworkError('cors failure')
+ }
-const kUndiciError = Symbol.for('undici.error.UND_ERR')
-class UndiciError extends Error {
- constructor (message) {
- super(message)
- this.name = 'UndiciError'
- this.code = 'UND_ERR'
+ // 5. If the TAO check for request and response returns failure, then set
+ // request’s timing allow failed flag.
+ if (TAOCheck(request, response) === 'failure') {
+ request.timingAllowFailed = true
+ }
}
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kUndiciError] === true
+ // 7. If either request’s response tainting or response’s type
+ // is "opaque", and the cross-origin resource policy check with
+ // request’s origin, request’s client, request’s destination,
+ // and actualResponse returns blocked, then return a network error.
+ if (
+ (request.responseTainting === 'opaque' || response.type === 'opaque') &&
+ crossOriginResourcePolicyCheck(
+ request.origin,
+ request.client,
+ request.destination,
+ actualResponse
+ ) === 'blocked'
+ ) {
+ return makeNetworkError('blocked')
}
- [kUndiciError] = true
-}
+ // 8. If actualResponse’s status is a redirect status, then:
+ if (redirectStatusSet.has(actualResponse.status)) {
+ // 1. If actualResponse’s status is not 303, request’s body is not null,
+ // and the connection uses HTTP/2, then user agents may, and are even
+ // encouraged to, transmit an RST_STREAM frame.
+ // See, https://github.com/whatwg/fetch/issues/1288
+ if (request.redirect !== 'manual') {
+ fetchParams.controller.connection.destroy(undefined, false)
+ }
-const kConnectTimeoutError = Symbol.for('undici.error.UND_ERR_CONNECT_TIMEOUT')
-class ConnectTimeoutError extends UndiciError {
- constructor (message) {
- super(message)
- this.name = 'ConnectTimeoutError'
- this.message = message || 'Connect Timeout Error'
- this.code = 'UND_ERR_CONNECT_TIMEOUT'
+ // 2. Switch on request’s redirect mode:
+ if (request.redirect === 'error') {
+ // Set response to a network error.
+ response = makeNetworkError('unexpected redirect')
+ } else if (request.redirect === 'manual') {
+ // Set response to an opaque-redirect filtered response whose internal
+ // response is actualResponse.
+ // NOTE(spec): On the web this would return an `opaqueredirect` response,
+ // but that doesn't make sense server side.
+ // See https://github.com/nodejs/undici/issues/1193.
+ response = actualResponse
+ } else if (request.redirect === 'follow') {
+ // Set response to the result of running HTTP-redirect fetch given
+ // fetchParams and response.
+ response = await httpRedirectFetch(fetchParams, response)
+ } else {
+ assert(false)
+ }
}
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kConnectTimeoutError] === true
- }
+ // 9. Set response’s timing info to timingInfo.
+ response.timingInfo = timingInfo
- [kConnectTimeoutError] = true
+ // 10. Return response.
+ return response
}
-const kHeadersTimeoutError = Symbol.for('undici.error.UND_ERR_HEADERS_TIMEOUT')
-class HeadersTimeoutError extends UndiciError {
- constructor (message) {
- super(message)
- this.name = 'HeadersTimeoutError'
- this.message = message || 'Headers Timeout Error'
- this.code = 'UND_ERR_HEADERS_TIMEOUT'
- }
+// https://fetch.spec.whatwg.org/#http-redirect-fetch
+function httpRedirectFetch (fetchParams, response) {
+ // 1. Let request be fetchParams’s request.
+ const request = fetchParams.request
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kHeadersTimeoutError] === true
- }
+ // 2. Let actualResponse be response, if response is not a filtered response,
+ // and response’s internal response otherwise.
+ const actualResponse = response.internalResponse
+ ? response.internalResponse
+ : response
- [kHeadersTimeoutError] = true
-}
+ // 3. Let locationURL be actualResponse’s location URL given request’s current
+ // URL’s fragment.
+ let locationURL
-const kHeadersOverflowError = Symbol.for('undici.error.UND_ERR_HEADERS_OVERFLOW')
-class HeadersOverflowError extends UndiciError {
- constructor (message) {
- super(message)
- this.name = 'HeadersOverflowError'
- this.message = message || 'Headers Overflow Error'
- this.code = 'UND_ERR_HEADERS_OVERFLOW'
- }
+ try {
+ locationURL = responseLocationURL(
+ actualResponse,
+ requestCurrentURL(request).hash
+ )
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kHeadersOverflowError] === true
+ // 4. If locationURL is null, then return response.
+ if (locationURL == null) {
+ return response
+ }
+ } catch (err) {
+ // 5. If locationURL is failure, then return a network error.
+ return Promise.resolve(makeNetworkError(err))
}
- [kHeadersOverflowError] = true
-}
-
-const kBodyTimeoutError = Symbol.for('undici.error.UND_ERR_BODY_TIMEOUT')
-class BodyTimeoutError extends UndiciError {
- constructor (message) {
- super(message)
- this.name = 'BodyTimeoutError'
- this.message = message || 'Body Timeout Error'
- this.code = 'UND_ERR_BODY_TIMEOUT'
+ // 6. If locationURL’s scheme is not an HTTP(S) scheme, then return a network
+ // error.
+ if (!urlIsHttpHttpsScheme(locationURL)) {
+ return Promise.resolve(makeNetworkError('URL scheme must be a HTTP(S) scheme'))
}
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kBodyTimeoutError] === true
+ // 7. If request’s redirect count is 20, then return a network error.
+ if (request.redirectCount === 20) {
+ return Promise.resolve(makeNetworkError('redirect count exceeded'))
}
- [kBodyTimeoutError] = true
-}
-
-const kResponseStatusCodeError = Symbol.for('undici.error.UND_ERR_RESPONSE_STATUS_CODE')
-class ResponseStatusCodeError extends UndiciError {
- constructor (message, statusCode, headers, body) {
- super(message)
- this.name = 'ResponseStatusCodeError'
- this.message = message || 'Response Status Code Error'
- this.code = 'UND_ERR_RESPONSE_STATUS_CODE'
- this.body = body
- this.status = statusCode
- this.statusCode = statusCode
- this.headers = headers
- }
+ // 8. Increase request’s redirect count by 1.
+ request.redirectCount += 1
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kResponseStatusCodeError] === true
+ // 9. If request’s mode is "cors", locationURL includes credentials, and
+ // request’s origin is not same origin with locationURL’s origin, then return
+ // a network error.
+ if (
+ request.mode === 'cors' &&
+ (locationURL.username || locationURL.password) &&
+ !sameOrigin(request, locationURL)
+ ) {
+ return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"'))
}
- [kResponseStatusCodeError] = true
-}
-
-const kInvalidArgumentError = Symbol.for('undici.error.UND_ERR_INVALID_ARG')
-class InvalidArgumentError extends UndiciError {
- constructor (message) {
- super(message)
- this.name = 'InvalidArgumentError'
- this.message = message || 'Invalid Argument Error'
- this.code = 'UND_ERR_INVALID_ARG'
+ // 10. If request’s response tainting is "cors" and locationURL includes
+ // credentials, then return a network error.
+ if (
+ request.responseTainting === 'cors' &&
+ (locationURL.username || locationURL.password)
+ ) {
+ return Promise.resolve(makeNetworkError(
+ 'URL cannot contain credentials for request mode "cors"'
+ ))
}
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kInvalidArgumentError] === true
+ // 11. If actualResponse’s status is not 303, request’s body is non-null,
+ // and request’s body’s source is null, then return a network error.
+ if (
+ actualResponse.status !== 303 &&
+ request.body != null &&
+ request.body.source == null
+ ) {
+ return Promise.resolve(makeNetworkError())
}
- [kInvalidArgumentError] = true
-}
+ // 12. If one of the following is true
+ // - actualResponse’s status is 301 or 302 and request’s method is `POST`
+ // - actualResponse’s status is 303 and request’s method is not `GET` or `HEAD`
+ if (
+ ([301, 302].includes(actualResponse.status) && request.method === 'POST') ||
+ (actualResponse.status === 303 &&
+ !GET_OR_HEAD.includes(request.method))
+ ) {
+ // then:
+ // 1. Set request’s method to `GET` and request’s body to null.
+ request.method = 'GET'
+ request.body = null
-const kInvalidReturnValueError = Symbol.for('undici.error.UND_ERR_INVALID_RETURN_VALUE')
-class InvalidReturnValueError extends UndiciError {
- constructor (message) {
- super(message)
- this.name = 'InvalidReturnValueError'
- this.message = message || 'Invalid Return Value Error'
- this.code = 'UND_ERR_INVALID_RETURN_VALUE'
+ // 2. For each headerName of request-body-header name, delete headerName from
+ // request’s header list.
+ for (const headerName of requestBodyHeader) {
+ request.headersList.delete(headerName)
+ }
}
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kInvalidReturnValueError] === true
- }
+ // 13. If request’s current URL’s origin is not same origin with locationURL’s
+ // origin, then for each headerName of CORS non-wildcard request-header name,
+ // delete headerName from request’s header list.
+ if (!sameOrigin(requestCurrentURL(request), locationURL)) {
+ // https://fetch.spec.whatwg.org/#cors-non-wildcard-request-header-name
+ request.headersList.delete('authorization', true)
- [kInvalidReturnValueError] = true
-}
+ // https://fetch.spec.whatwg.org/#authentication-entries
+ request.headersList.delete('proxy-authorization', true)
-const kAbortError = Symbol.for('undici.error.UND_ERR_ABORT')
-class AbortError extends UndiciError {
- constructor (message) {
- super(message)
- this.name = 'AbortError'
- this.message = message || 'The operation was aborted'
- this.code = 'UND_ERR_ABORT'
+ // "Cookie" and "Host" are forbidden request-headers, which undici doesn't implement.
+ request.headersList.delete('cookie', true)
+ request.headersList.delete('host', true)
}
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kAbortError] === true
+ // 14. If request’s body is non-null, then set request’s body to the first return
+ // value of safely extracting request’s body’s source.
+ if (request.body != null) {
+ assert(request.body.source != null)
+ request.body = safelyExtractBody(request.body.source)[0]
}
- [kAbortError] = true
-}
+ // 15. Let timingInfo be fetchParams’s timing info.
+ const timingInfo = fetchParams.timingInfo
-const kRequestAbortedError = Symbol.for('undici.error.UND_ERR_ABORTED')
-class RequestAbortedError extends AbortError {
- constructor (message) {
- super(message)
- this.name = 'AbortError'
- this.message = message || 'Request aborted'
- this.code = 'UND_ERR_ABORTED'
- }
+ // 16. Set timingInfo’s redirect end time and post-redirect start time to the
+ // coarsened shared current time given fetchParams’s cross-origin isolated
+ // capability.
+ timingInfo.redirectEndTime = timingInfo.postRedirectStartTime =
+ coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability)
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kRequestAbortedError] === true
+ // 17. If timingInfo’s redirect start time is 0, then set timingInfo’s
+ // redirect start time to timingInfo’s start time.
+ if (timingInfo.redirectStartTime === 0) {
+ timingInfo.redirectStartTime = timingInfo.startTime
}
- [kRequestAbortedError] = true
-}
-
-const kInformationalError = Symbol.for('undici.error.UND_ERR_INFO')
-class InformationalError extends UndiciError {
- constructor (message) {
- super(message)
- this.name = 'InformationalError'
- this.message = message || 'Request information'
- this.code = 'UND_ERR_INFO'
- }
+ // 18. Append locationURL to request’s URL list.
+ request.urlList.push(locationURL)
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kInformationalError] === true
- }
+ // 19. Invoke set request’s referrer policy on redirect on request and
+ // actualResponse.
+ setRequestReferrerPolicyOnRedirect(request, actualResponse)
- [kInformationalError] = true
+ // 20. Return the result of running main fetch given fetchParams and true.
+ return mainFetch(fetchParams, true)
}
-const kRequestContentLengthMismatchError = Symbol.for('undici.error.UND_ERR_REQ_CONTENT_LENGTH_MISMATCH')
-class RequestContentLengthMismatchError extends UndiciError {
- constructor (message) {
- super(message)
- this.name = 'RequestContentLengthMismatchError'
- this.message = message || 'Request body length does not match content-length header'
- this.code = 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH'
- }
+// https://fetch.spec.whatwg.org/#http-network-or-cache-fetch
+async function httpNetworkOrCacheFetch (
+ fetchParams,
+ isAuthenticationFetch = false,
+ isNewConnectionFetch = false
+) {
+ // 1. Let request be fetchParams’s request.
+ const request = fetchParams.request
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kRequestContentLengthMismatchError] === true
- }
+ // 2. Let httpFetchParams be null.
+ let httpFetchParams = null
- [kRequestContentLengthMismatchError] = true
-}
+ // 3. Let httpRequest be null.
+ let httpRequest = null
-const kResponseContentLengthMismatchError = Symbol.for('undici.error.UND_ERR_RES_CONTENT_LENGTH_MISMATCH')
-class ResponseContentLengthMismatchError extends UndiciError {
- constructor (message) {
- super(message)
- this.name = 'ResponseContentLengthMismatchError'
- this.message = message || 'Response body length does not match content-length header'
- this.code = 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH'
- }
+ // 4. Let response be null.
+ let response = null
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kResponseContentLengthMismatchError] === true
- }
+ // 5. Let storedResponse be null.
+ // TODO: cache
- [kResponseContentLengthMismatchError] = true
-}
+ // 6. Let httpCache be null.
+ const httpCache = null
-const kClientDestroyedError = Symbol.for('undici.error.UND_ERR_DESTROYED')
-class ClientDestroyedError extends UndiciError {
- constructor (message) {
- super(message)
- this.name = 'ClientDestroyedError'
- this.message = message || 'The client is destroyed'
- this.code = 'UND_ERR_DESTROYED'
- }
+ // 7. Let the revalidatingFlag be unset.
+ const revalidatingFlag = false
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kClientDestroyedError] === true
- }
+ // 8. Run these steps, but abort when the ongoing fetch is terminated:
- [kClientDestroyedError] = true
-}
+ // 1. If request’s window is "no-window" and request’s redirect mode is
+ // "error", then set httpFetchParams to fetchParams and httpRequest to
+ // request.
+ if (request.window === 'no-window' && request.redirect === 'error') {
+ httpFetchParams = fetchParams
+ httpRequest = request
+ } else {
+ // Otherwise:
-const kClientClosedError = Symbol.for('undici.error.UND_ERR_CLOSED')
-class ClientClosedError extends UndiciError {
- constructor (message) {
- super(message)
- this.name = 'ClientClosedError'
- this.message = message || 'The client is closed'
- this.code = 'UND_ERR_CLOSED'
- }
+ // 1. Set httpRequest to a clone of request.
+ httpRequest = cloneRequest(request)
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kClientClosedError] === true
+ // 2. Set httpFetchParams to a copy of fetchParams.
+ httpFetchParams = { ...fetchParams }
+
+ // 3. Set httpFetchParams’s request to httpRequest.
+ httpFetchParams.request = httpRequest
}
- [kClientClosedError] = true
-}
+ // 3. Let includeCredentials be true if one of
+ const includeCredentials =
+ request.credentials === 'include' ||
+ (request.credentials === 'same-origin' &&
+ request.responseTainting === 'basic')
-const kSocketError = Symbol.for('undici.error.UND_ERR_SOCKET')
-class SocketError extends UndiciError {
- constructor (message, socket) {
- super(message)
- this.name = 'SocketError'
- this.message = message || 'Socket error'
- this.code = 'UND_ERR_SOCKET'
- this.socket = socket
- }
+ // 4. Let contentLength be httpRequest’s body’s length, if httpRequest’s
+ // body is non-null; otherwise null.
+ const contentLength = httpRequest.body ? httpRequest.body.length : null
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kSocketError] === true
- }
+ // 5. Let contentLengthHeaderValue be null.
+ let contentLengthHeaderValue = null
- [kSocketError] = true
-}
+ // 6. If httpRequest’s body is null and httpRequest’s method is `POST` or
+ // `PUT`, then set contentLengthHeaderValue to `0`.
+ if (
+ httpRequest.body == null &&
+ ['POST', 'PUT'].includes(httpRequest.method)
+ ) {
+ contentLengthHeaderValue = '0'
+ }
-const kNotSupportedError = Symbol.for('undici.error.UND_ERR_NOT_SUPPORTED')
-class NotSupportedError extends UndiciError {
- constructor (message) {
- super(message)
- this.name = 'NotSupportedError'
- this.message = message || 'Not supported error'
- this.code = 'UND_ERR_NOT_SUPPORTED'
+ // 7. If contentLength is non-null, then set contentLengthHeaderValue to
+ // contentLength, serialized and isomorphic encoded.
+ if (contentLength != null) {
+ contentLengthHeaderValue = isomorphicEncode(`${contentLength}`)
}
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kNotSupportedError] === true
+ // 8. If contentLengthHeaderValue is non-null, then append
+ // `Content-Length`/contentLengthHeaderValue to httpRequest’s header
+ // list.
+ if (contentLengthHeaderValue != null) {
+ httpRequest.headersList.append('content-length', contentLengthHeaderValue, true)
}
- [kNotSupportedError] = true
-}
+ // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`,
+ // contentLengthHeaderValue) to httpRequest’s header list.
-const kBalancedPoolMissingUpstreamError = Symbol.for('undici.error.UND_ERR_BPL_MISSING_UPSTREAM')
-class BalancedPoolMissingUpstreamError extends UndiciError {
- constructor (message) {
- super(message)
- this.name = 'MissingUpstreamError'
- this.message = message || 'No upstream has been added to the BalancedPool'
- this.code = 'UND_ERR_BPL_MISSING_UPSTREAM'
+ // 10. If contentLength is non-null and httpRequest’s keepalive is true,
+ // then:
+ if (contentLength != null && httpRequest.keepalive) {
+ // NOTE: keepalive is a noop outside of browser context.
}
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kBalancedPoolMissingUpstreamError] === true
+ // 11. If httpRequest’s referrer is a URL, then append
+ // `Referer`/httpRequest’s referrer, serialized and isomorphic encoded,
+ // to httpRequest’s header list.
+ if (httpRequest.referrer instanceof URL) {
+ httpRequest.headersList.append('referer', isomorphicEncode(httpRequest.referrer.href), true)
}
- [kBalancedPoolMissingUpstreamError] = true
-}
+ // 12. Append a request `Origin` header for httpRequest.
+ appendRequestOriginHeader(httpRequest)
-const kHTTPParserError = Symbol.for('undici.error.UND_ERR_HTTP_PARSER')
-class HTTPParserError extends Error {
- constructor (message, code, data) {
- super(message)
- this.name = 'HTTPParserError'
- this.code = code ? `HPE_${code}` : undefined
- this.data = data ? data.toString() : undefined
- }
+ // 13. Append the Fetch metadata headers for httpRequest. [FETCH-METADATA]
+ appendFetchMetadata(httpRequest)
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kHTTPParserError] === true
+ // 14. If httpRequest’s header list does not contain `User-Agent`, then
+ // user agents should append `User-Agent`/default `User-Agent` value to
+ // httpRequest’s header list.
+ if (!httpRequest.headersList.contains('user-agent', true)) {
+ httpRequest.headersList.append('user-agent', defaultUserAgent)
}
- [kHTTPParserError] = true
-}
-
-const kResponseExceededMaxSizeError = Symbol.for('undici.error.UND_ERR_RES_EXCEEDED_MAX_SIZE')
-class ResponseExceededMaxSizeError extends UndiciError {
- constructor (message) {
- super(message)
- this.name = 'ResponseExceededMaxSizeError'
- this.message = message || 'Response content exceeded max size'
- this.code = 'UND_ERR_RES_EXCEEDED_MAX_SIZE'
+ // 15. If httpRequest’s cache mode is "default" and httpRequest’s header
+ // list contains `If-Modified-Since`, `If-None-Match`,
+ // `If-Unmodified-Since`, `If-Match`, or `If-Range`, then set
+ // httpRequest’s cache mode to "no-store".
+ if (
+ httpRequest.cache === 'default' &&
+ (httpRequest.headersList.contains('if-modified-since', true) ||
+ httpRequest.headersList.contains('if-none-match', true) ||
+ httpRequest.headersList.contains('if-unmodified-since', true) ||
+ httpRequest.headersList.contains('if-match', true) ||
+ httpRequest.headersList.contains('if-range', true))
+ ) {
+ httpRequest.cache = 'no-store'
}
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kResponseExceededMaxSizeError] === true
+ // 16. If httpRequest’s cache mode is "no-cache", httpRequest’s prevent
+ // no-cache cache-control header modification flag is unset, and
+ // httpRequest’s header list does not contain `Cache-Control`, then append
+ // `Cache-Control`/`max-age=0` to httpRequest’s header list.
+ if (
+ httpRequest.cache === 'no-cache' &&
+ !httpRequest.preventNoCacheCacheControlHeaderModification &&
+ !httpRequest.headersList.contains('cache-control', true)
+ ) {
+ httpRequest.headersList.append('cache-control', 'max-age=0', true)
}
- [kResponseExceededMaxSizeError] = true
-}
+ // 17. If httpRequest’s cache mode is "no-store" or "reload", then:
+ if (httpRequest.cache === 'no-store' || httpRequest.cache === 'reload') {
+ // 1. If httpRequest’s header list does not contain `Pragma`, then append
+ // `Pragma`/`no-cache` to httpRequest’s header list.
+ if (!httpRequest.headersList.contains('pragma', true)) {
+ httpRequest.headersList.append('pragma', 'no-cache', true)
+ }
-const kRequestRetryError = Symbol.for('undici.error.UND_ERR_REQ_RETRY')
-class RequestRetryError extends UndiciError {
- constructor (message, code, { headers, data }) {
- super(message)
- this.name = 'RequestRetryError'
- this.message = message || 'Request retry error'
- this.code = 'UND_ERR_REQ_RETRY'
- this.statusCode = code
- this.data = data
- this.headers = headers
+ // 2. If httpRequest’s header list does not contain `Cache-Control`,
+ // then append `Cache-Control`/`no-cache` to httpRequest’s header list.
+ if (!httpRequest.headersList.contains('cache-control', true)) {
+ httpRequest.headersList.append('cache-control', 'no-cache', true)
+ }
}
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kRequestRetryError] === true
+ // 18. If httpRequest’s header list contains `Range`, then append
+ // `Accept-Encoding`/`identity` to httpRequest’s header list.
+ if (httpRequest.headersList.contains('range', true)) {
+ httpRequest.headersList.append('accept-encoding', 'identity', true)
}
- [kRequestRetryError] = true
-}
-
-const kResponseError = Symbol.for('undici.error.UND_ERR_RESPONSE')
-class ResponseError extends UndiciError {
- constructor (message, code, { headers, data }) {
- super(message)
- this.name = 'ResponseError'
- this.message = message || 'Response error'
- this.code = 'UND_ERR_RESPONSE'
- this.statusCode = code
- this.data = data
- this.headers = headers
+ // 19. Modify httpRequest’s header list per HTTP. Do not append a given
+ // header if httpRequest’s header list contains that header’s name.
+ // TODO: https://github.com/whatwg/fetch/issues/1285#issuecomment-896560129
+ if (!httpRequest.headersList.contains('accept-encoding', true)) {
+ if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) {
+ httpRequest.headersList.append('accept-encoding', 'br, gzip, deflate', true)
+ } else {
+ httpRequest.headersList.append('accept-encoding', 'gzip, deflate', true)
+ }
}
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kResponseError] === true
+ httpRequest.headersList.delete('host', true)
+
+ // 20. If includeCredentials is true, then:
+ if (includeCredentials) {
+ // 1. If the user agent is not configured to block cookies for httpRequest
+ // (see section 7 of [COOKIES]), then:
+ // TODO: credentials
+ // 2. If httpRequest’s header list does not contain `Authorization`, then:
+ // TODO: credentials
}
- [kResponseError] = true
-}
+ // 21. If there’s a proxy-authentication entry, use it as appropriate.
+ // TODO: proxy-authentication
-const kSecureProxyConnectionError = Symbol.for('undici.error.UND_ERR_PRX_TLS')
-class SecureProxyConnectionError extends UndiciError {
- constructor (cause, message, options) {
- super(message, { cause, ...(options ?? {}) })
- this.name = 'SecureProxyConnectionError'
- this.message = message || 'Secure Proxy Connection failed'
- this.code = 'UND_ERR_PRX_TLS'
- this.cause = cause
+ // 22. Set httpCache to the result of determining the HTTP cache
+ // partition, given httpRequest.
+ // TODO: cache
+
+ // 23. If httpCache is null, then set httpRequest’s cache mode to
+ // "no-store".
+ if (httpCache == null) {
+ httpRequest.cache = 'no-store'
}
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kSecureProxyConnectionError] === true
+ // 24. If httpRequest’s cache mode is neither "no-store" nor "reload",
+ // then:
+ if (httpRequest.cache !== 'no-store' && httpRequest.cache !== 'reload') {
+ // TODO: cache
}
- [kSecureProxyConnectionError] = true
-}
+ // 9. If aborted, then return the appropriate network error for fetchParams.
+ // TODO
-module.exports = {
- AbortError,
- HTTPParserError,
- UndiciError,
- HeadersTimeoutError,
- HeadersOverflowError,
- BodyTimeoutError,
- RequestContentLengthMismatchError,
- ConnectTimeoutError,
- ResponseStatusCodeError,
- InvalidArgumentError,
- InvalidReturnValueError,
- RequestAbortedError,
- ClientDestroyedError,
- ClientClosedError,
- InformationalError,
- SocketError,
- NotSupportedError,
- ResponseContentLengthMismatchError,
- BalancedPoolMissingUpstreamError,
- ResponseExceededMaxSizeError,
- RequestRetryError,
- ResponseError,
- SecureProxyConnectionError
-}
+ // 10. If response is null, then:
+ if (response == null) {
+ // 1. If httpRequest’s cache mode is "only-if-cached", then return a
+ // network error.
+ if (httpRequest.cache === 'only-if-cached') {
+ return makeNetworkError('only if cached')
+ }
+ // 2. Let forwardResponse be the result of running HTTP-network fetch
+ // given httpFetchParams, includeCredentials, and isNewConnectionFetch.
+ const forwardResponse = await httpNetworkFetch(
+ httpFetchParams,
+ includeCredentials,
+ isNewConnectionFetch
+ )
-/***/ }),
+ // 3. If httpRequest’s method is unsafe and forwardResponse’s status is
+ // in the range 200 to 399, inclusive, invalidate appropriate stored
+ // responses in httpCache, as per the "Invalidation" chapter of HTTP
+ // Caching, and set storedResponse to null. [HTTP-CACHING]
+ if (
+ !safeMethodsSet.has(httpRequest.method) &&
+ forwardResponse.status >= 200 &&
+ forwardResponse.status <= 399
+ ) {
+ // TODO: cache
+ }
-/***/ 8823:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 4. If the revalidatingFlag is set and forwardResponse’s status is 304,
+ // then:
+ if (revalidatingFlag && forwardResponse.status === 304) {
+ // TODO: cache
+ }
+ // 5. If response is null, then:
+ if (response == null) {
+ // 1. Set response to forwardResponse.
+ response = forwardResponse
+ // 2. Store httpRequest and forwardResponse in httpCache, as per the
+ // "Storing Responses in Caches" chapter of HTTP Caching. [HTTP-CACHING]
+ // TODO: cache
+ }
+ }
-const {
- InvalidArgumentError,
- NotSupportedError
-} = __nccwpck_require__(8091)
-const assert = __nccwpck_require__(4589)
-const {
- isValidHTTPToken,
- isValidHeaderValue,
- isStream,
- destroy,
- isBuffer,
- isFormDataLike,
- isIterable,
- isBlobLike,
- buildURL,
- validateHandler,
- getServerName,
- normalizedMethodRecords
-} = __nccwpck_require__(1544)
-const { channels } = __nccwpck_require__(8150)
-const { headerNameLowerCasedRecord } = __nccwpck_require__(1303)
+ // 11. Set response’s URL list to a clone of httpRequest’s URL list.
+ response.urlList = [...httpRequest.urlList]
-// Verifies that a given path is valid does not contain control chars \x00 to \x20
-const invalidPathRegex = /[^\u0021-\u00ff]/
+ // 12. If httpRequest’s header list contains `Range`, then set response’s
+ // range-requested flag.
+ if (httpRequest.headersList.contains('range', true)) {
+ response.rangeRequested = true
+ }
-const kHandler = Symbol('handler')
+ // 13. Set response’s request-includes-credentials to includeCredentials.
+ response.requestIncludesCredentials = includeCredentials
-class Request {
- constructor (origin, {
- path,
- method,
- body,
- headers,
- query,
- idempotent,
- blocking,
- upgrade,
- headersTimeout,
- bodyTimeout,
- reset,
- throwOnError,
- expectContinue,
- servername
- }, handler) {
- if (typeof path !== 'string') {
- throw new InvalidArgumentError('path must be a string')
- } else if (
- path[0] !== '/' &&
- !(path.startsWith('http://') || path.startsWith('https://')) &&
- method !== 'CONNECT'
- ) {
- throw new InvalidArgumentError('path must be an absolute URL or start with a slash')
- } else if (invalidPathRegex.test(path)) {
- throw new InvalidArgumentError('invalid request path')
- }
+ // 14. If response’s status is 401, httpRequest’s response tainting is not
+ // "cors", includeCredentials is true, and request’s window is an environment
+ // settings object, then:
+ // TODO
- if (typeof method !== 'string') {
- throw new InvalidArgumentError('method must be a string')
- } else if (normalizedMethodRecords[method] === undefined && !isValidHTTPToken(method)) {
- throw new InvalidArgumentError('invalid request method')
+ // 15. If response’s status is 407, then:
+ if (response.status === 407) {
+ // 1. If request’s window is "no-window", then return a network error.
+ if (request.window === 'no-window') {
+ return makeNetworkError()
}
- if (upgrade && typeof upgrade !== 'string') {
- throw new InvalidArgumentError('upgrade must be a string')
- }
+ // 2. ???
- if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) {
- throw new InvalidArgumentError('invalid headersTimeout')
+ // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams.
+ if (isCancelled(fetchParams)) {
+ return makeAppropriateNetworkError(fetchParams)
}
- if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) {
- throw new InvalidArgumentError('invalid bodyTimeout')
- }
+ // 4. Prompt the end user as appropriate in request’s window and store
+ // the result as a proxy-authentication entry. [HTTP-AUTH]
+ // TODO: Invoke some kind of callback?
- if (reset != null && typeof reset !== 'boolean') {
- throw new InvalidArgumentError('invalid reset')
- }
+ // 5. Set response to the result of running HTTP-network-or-cache fetch given
+ // fetchParams.
+ // TODO
+ return makeNetworkError('proxy authentication required')
+ }
- if (expectContinue != null && typeof expectContinue !== 'boolean') {
- throw new InvalidArgumentError('invalid expectContinue')
+ // 16. If all of the following are true
+ if (
+ // response’s status is 421
+ response.status === 421 &&
+ // isNewConnectionFetch is false
+ !isNewConnectionFetch &&
+ // request’s body is null, or request’s body is non-null and request’s body’s source is non-null
+ (request.body == null || request.body.source != null)
+ ) {
+ // then:
+
+ // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
+ if (isCancelled(fetchParams)) {
+ return makeAppropriateNetworkError(fetchParams)
}
- this.headersTimeout = headersTimeout
+ // 2. Set response to the result of running HTTP-network-or-cache
+ // fetch given fetchParams, isAuthenticationFetch, and true.
- this.bodyTimeout = bodyTimeout
+ // TODO (spec): The spec doesn't specify this but we need to cancel
+ // the active response before we can start a new one.
+ // https://github.com/whatwg/fetch/issues/1293
+ fetchParams.controller.connection.destroy()
- this.throwOnError = throwOnError === true
-
- this.method = method
+ response = await httpNetworkOrCacheFetch(
+ fetchParams,
+ isAuthenticationFetch,
+ true
+ )
+ }
- this.abort = null
+ // 17. If isAuthenticationFetch is true, then create an authentication entry
+ if (isAuthenticationFetch) {
+ // TODO
+ }
- if (body == null) {
- this.body = null
- } else if (isStream(body)) {
- this.body = body
+ // 18. Return response.
+ return response
+}
- const rState = this.body._readableState
- if (!rState || !rState.autoDestroy) {
- this.endHandler = function autoDestroy () {
- destroy(this)
- }
- this.body.on('end', this.endHandler)
- }
+// https://fetch.spec.whatwg.org/#http-network-fetch
+async function httpNetworkFetch (
+ fetchParams,
+ includeCredentials = false,
+ forceNewConnection = false
+) {
+ assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed)
- this.errorHandler = err => {
- if (this.abort) {
- this.abort(err)
- } else {
- this.error = err
+ fetchParams.controller.connection = {
+ abort: null,
+ destroyed: false,
+ destroy (err, abort = true) {
+ if (!this.destroyed) {
+ this.destroyed = true
+ if (abort) {
+ this.abort?.(err ?? new DOMException('The operation was aborted.', 'AbortError'))
}
}
- this.body.on('error', this.errorHandler)
- } else if (isBuffer(body)) {
- this.body = body.byteLength ? body : null
- } else if (ArrayBuffer.isView(body)) {
- this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null
- } else if (body instanceof ArrayBuffer) {
- this.body = body.byteLength ? Buffer.from(body) : null
- } else if (typeof body === 'string') {
- this.body = body.length ? Buffer.from(body) : null
- } else if (isFormDataLike(body) || isIterable(body) || isBlobLike(body)) {
- this.body = body
- } else {
- throw new InvalidArgumentError('body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable')
}
+ }
- this.completed = false
+ // 1. Let request be fetchParams’s request.
+ const request = fetchParams.request
- this.aborted = false
+ // 2. Let response be null.
+ let response = null
- this.upgrade = upgrade || null
+ // 3. Let timingInfo be fetchParams’s timing info.
+ const timingInfo = fetchParams.timingInfo
- this.path = query ? buildURL(path, query) : path
+ // 4. Let httpCache be the result of determining the HTTP cache partition,
+ // given request.
+ // TODO: cache
+ const httpCache = null
- this.origin = origin
+ // 5. If httpCache is null, then set request’s cache mode to "no-store".
+ if (httpCache == null) {
+ request.cache = 'no-store'
+ }
- this.idempotent = idempotent == null
- ? method === 'HEAD' || method === 'GET'
- : idempotent
+ // 6. Let networkPartitionKey be the result of determining the network
+ // partition key given request.
+ // TODO
- this.blocking = blocking == null ? false : blocking
+ // 7. Let newConnection be "yes" if forceNewConnection is true; otherwise
+ // "no".
+ const newConnection = forceNewConnection ? 'yes' : 'no' // eslint-disable-line no-unused-vars
- this.reset = reset == null ? null : reset
+ // 8. Switch on request’s mode:
+ if (request.mode === 'websocket') {
+ // Let connection be the result of obtaining a WebSocket connection,
+ // given request’s current URL.
+ // TODO
+ } else {
+ // Let connection be the result of obtaining a connection, given
+ // networkPartitionKey, request’s current URL’s origin,
+ // includeCredentials, and forceNewConnection.
+ // TODO
+ }
- this.host = null
+ // 9. Run these steps, but abort when the ongoing fetch is terminated:
- this.contentLength = null
+ // 1. If connection is failure, then return a network error.
- this.contentType = null
+ // 2. Set timingInfo’s final connection timing info to the result of
+ // calling clamp and coarsen connection timing info with connection’s
+ // timing info, timingInfo’s post-redirect start time, and fetchParams’s
+ // cross-origin isolated capability.
- this.headers = []
+ // 3. If connection is not an HTTP/2 connection, request’s body is non-null,
+ // and request’s body’s source is null, then append (`Transfer-Encoding`,
+ // `chunked`) to request’s header list.
- // Only for H2
- this.expectContinue = expectContinue != null ? expectContinue : false
+ // 4. Set timingInfo’s final network-request start time to the coarsened
+ // shared current time given fetchParams’s cross-origin isolated
+ // capability.
- if (Array.isArray(headers)) {
- if (headers.length % 2 !== 0) {
- throw new InvalidArgumentError('headers array must be even')
- }
- for (let i = 0; i < headers.length; i += 2) {
- processHeader(this, headers[i], headers[i + 1])
- }
- } else if (headers && typeof headers === 'object') {
- if (headers[Symbol.iterator]) {
- for (const header of headers) {
- if (!Array.isArray(header) || header.length !== 2) {
- throw new InvalidArgumentError('headers must be in key-value pair format')
- }
- processHeader(this, header[0], header[1])
- }
- } else {
- const keys = Object.keys(headers)
- for (let i = 0; i < keys.length; ++i) {
- processHeader(this, keys[i], headers[keys[i]])
- }
- }
- } else if (headers != null) {
- throw new InvalidArgumentError('headers must be an object or an array')
- }
+ // 5. Set response to the result of making an HTTP request over connection
+ // using request with the following caveats:
- validateHandler(handler, method, upgrade)
+ // - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS]
+ // [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH]
- this.servername = servername || getServerName(this.host)
+ // - If request’s body is non-null, and request’s body’s source is null,
+ // then the user agent may have a buffer of up to 64 kibibytes and store
+ // a part of request’s body in that buffer. If the user agent reads from
+ // request’s body beyond that buffer’s size and the user agent needs to
+ // resend request, then instead return a network error.
- this[kHandler] = handler
+ // - Set timingInfo’s final network-response start time to the coarsened
+ // shared current time given fetchParams’s cross-origin isolated capability,
+ // immediately after the user agent’s HTTP parser receives the first byte
+ // of the response (e.g., frame header bytes for HTTP/2 or response status
+ // line for HTTP/1.x).
- if (channels.create.hasSubscribers) {
- channels.create.publish({ request: this })
+ // - Wait until all the headers are transmitted.
+
+ // - Any responses whose status is in the range 100 to 199, inclusive,
+ // and is not 101, are to be ignored, except for the purposes of setting
+ // timingInfo’s final network-response start time above.
+
+ // - If request’s header list contains `Transfer-Encoding`/`chunked` and
+ // response is transferred via HTTP/1.0 or older, then return a network
+ // error.
+
+ // - If the HTTP request results in a TLS client certificate dialog, then:
+
+ // 1. If request’s window is an environment settings object, make the
+ // dialog available in request’s window.
+
+ // 2. Otherwise, return a network error.
+
+ // To transmit request’s body body, run these steps:
+ let requestBody = null
+ // 1. If body is null and fetchParams’s process request end-of-body is
+ // non-null, then queue a fetch task given fetchParams’s process request
+ // end-of-body and fetchParams’s task destination.
+ if (request.body == null && fetchParams.processRequestEndOfBody) {
+ queueMicrotask(() => fetchParams.processRequestEndOfBody())
+ } else if (request.body != null) {
+ // 2. Otherwise, if body is non-null:
+
+ // 1. Let processBodyChunk given bytes be these steps:
+ const processBodyChunk = async function * (bytes) {
+ // 1. If the ongoing fetch is terminated, then abort these steps.
+ if (isCancelled(fetchParams)) {
+ return
+ }
+
+ // 2. Run this step in parallel: transmit bytes.
+ yield bytes
+
+ // 3. If fetchParams’s process request body is non-null, then run
+ // fetchParams’s process request body given bytes’s length.
+ fetchParams.processRequestBodyChunkLength?.(bytes.byteLength)
}
- }
- onBodySent (chunk) {
- if (this[kHandler].onBodySent) {
- try {
- return this[kHandler].onBodySent(chunk)
- } catch (err) {
- this.abort(err)
+ // 2. Let processEndOfBody be these steps:
+ const processEndOfBody = () => {
+ // 1. If fetchParams is canceled, then abort these steps.
+ if (isCancelled(fetchParams)) {
+ return
+ }
+
+ // 2. If fetchParams’s process request end-of-body is non-null,
+ // then run fetchParams’s process request end-of-body.
+ if (fetchParams.processRequestEndOfBody) {
+ fetchParams.processRequestEndOfBody()
}
}
- }
- onRequestSent () {
- if (channels.bodySent.hasSubscribers) {
- channels.bodySent.publish({ request: this })
+ // 3. Let processBodyError given e be these steps:
+ const processBodyError = (e) => {
+ // 1. If fetchParams is canceled, then abort these steps.
+ if (isCancelled(fetchParams)) {
+ return
+ }
+
+ // 2. If e is an "AbortError" DOMException, then abort fetchParams’s controller.
+ if (e.name === 'AbortError') {
+ fetchParams.controller.abort()
+ } else {
+ fetchParams.controller.terminate(e)
+ }
}
- if (this[kHandler].onRequestSent) {
+ // 4. Incrementally read request’s body given processBodyChunk, processEndOfBody,
+ // processBodyError, and fetchParams’s task destination.
+ requestBody = (async function * () {
try {
- return this[kHandler].onRequestSent()
+ for await (const bytes of request.body.stream) {
+ yield * processBodyChunk(bytes)
+ }
+ processEndOfBody()
} catch (err) {
- this.abort(err)
+ processBodyError(err)
}
- }
+ })()
}
- onConnect (abort) {
- assert(!this.aborted)
- assert(!this.completed)
+ try {
+ // socket is only provided for websockets
+ const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody })
- if (this.error) {
- abort(this.error)
+ if (socket) {
+ response = makeResponse({ status, statusText, headersList, socket })
} else {
- this.abort = abort
- return this[kHandler].onConnect(abort)
- }
- }
-
- onResponseStarted () {
- return this[kHandler].onResponseStarted?.()
- }
-
- onHeaders (statusCode, headers, resume, statusText) {
- assert(!this.aborted)
- assert(!this.completed)
+ const iterator = body[Symbol.asyncIterator]()
+ fetchParams.controller.next = () => iterator.next()
- if (channels.headers.hasSubscribers) {
- channels.headers.publish({ request: this, response: { statusCode, headers, statusText } })
+ response = makeResponse({ status, statusText, headersList })
}
+ } catch (err) {
+ // 10. If aborted, then:
+ if (err.name === 'AbortError') {
+ // 1. If connection uses HTTP/2, then transmit an RST_STREAM frame.
+ fetchParams.controller.connection.destroy()
- try {
- return this[kHandler].onHeaders(statusCode, headers, resume, statusText)
- } catch (err) {
- this.abort(err)
+ // 2. Return the appropriate network error for fetchParams.
+ return makeAppropriateNetworkError(fetchParams, err)
}
- }
-
- onData (chunk) {
- assert(!this.aborted)
- assert(!this.completed)
- try {
- return this[kHandler].onData(chunk)
- } catch (err) {
- this.abort(err)
- return false
- }
+ return makeNetworkError(err)
}
- onUpgrade (statusCode, headers, socket) {
- assert(!this.aborted)
- assert(!this.completed)
-
- return this[kHandler].onUpgrade(statusCode, headers, socket)
+ // 11. Let pullAlgorithm be an action that resumes the ongoing fetch
+ // if it is suspended.
+ const pullAlgorithm = async () => {
+ await fetchParams.controller.resume()
}
- onComplete (trailers) {
- this.onFinally()
+ // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s
+ // controller with reason, given reason.
+ const cancelAlgorithm = (reason) => {
+ // If the aborted fetch was already terminated, then we do not
+ // need to do anything.
+ if (!isCancelled(fetchParams)) {
+ fetchParams.controller.abort(reason)
+ }
+ }
- assert(!this.aborted)
+ // 13. Let highWaterMark be a non-negative, non-NaN number, chosen by
+ // the user agent.
+ // TODO
- this.completed = true
- if (channels.trailers.hasSubscribers) {
- channels.trailers.publish({ request: this, trailers })
- }
+ // 14. Let sizeAlgorithm be an algorithm that accepts a chunk object
+ // and returns a non-negative, non-NaN, non-infinite number, chosen by the user agent.
+ // TODO
- try {
- return this[kHandler].onComplete(trailers)
- } catch (err) {
- // TODO (fix): This might be a bad idea?
- this.onError(err)
+ // 15. Let stream be a new ReadableStream.
+ // 16. Set up stream with byte reading support with pullAlgorithm set to pullAlgorithm,
+ // cancelAlgorithm set to cancelAlgorithm.
+ const stream = new ReadableStream(
+ {
+ async start (controller) {
+ fetchParams.controller.controller = controller
+ },
+ async pull (controller) {
+ await pullAlgorithm(controller)
+ },
+ async cancel (reason) {
+ await cancelAlgorithm(reason)
+ },
+ type: 'bytes'
}
- }
+ )
- onError (error) {
- this.onFinally()
+ // 17. Run these steps, but abort when the ongoing fetch is terminated:
- if (channels.error.hasSubscribers) {
- channels.error.publish({ request: this, error })
- }
+ // 1. Set response’s body to a new body whose stream is stream.
+ response.body = { stream, source: null, length: null }
- if (this.aborted) {
- return
- }
- this.aborted = true
+ // 2. If response is not a network error and request’s cache mode is
+ // not "no-store", then update response in httpCache for request.
+ // TODO
- return this[kHandler].onError(error)
- }
+ // 3. If includeCredentials is true and the user agent is not configured
+ // to block cookies for request (see section 7 of [COOKIES]), then run the
+ // "set-cookie-string" parsing algorithm (see section 5.2 of [COOKIES]) on
+ // the value of each header whose name is a byte-case-insensitive match for
+ // `Set-Cookie` in response’s header list, if any, and request’s current URL.
+ // TODO
- onFinally () {
- if (this.errorHandler) {
- this.body.off('error', this.errorHandler)
- this.errorHandler = null
- }
+ // 18. If aborted, then:
+ // TODO
- if (this.endHandler) {
- this.body.off('end', this.endHandler)
- this.endHandler = null
- }
- }
+ // 19. Run these steps in parallel:
- addHeader (key, value) {
- processHeader(this, key, value)
- return this
- }
-}
+ // 1. Run these steps, but abort when fetchParams is canceled:
+ fetchParams.controller.onAborted = onAborted
+ fetchParams.controller.on('terminated', onAborted)
+ fetchParams.controller.resume = async () => {
+ // 1. While true
+ while (true) {
+ // 1-3. See onData...
-function processHeader (request, key, val) {
- if (val && (typeof val === 'object' && !Array.isArray(val))) {
- throw new InvalidArgumentError(`invalid ${key} header`)
- } else if (val === undefined) {
- return
- }
+ // 4. Set bytes to the result of handling content codings given
+ // codings and bytes.
+ let bytes
+ let isFailure
+ try {
+ const { done, value } = await fetchParams.controller.next()
- let headerName = headerNameLowerCasedRecord[key]
+ if (isAborted(fetchParams)) {
+ break
+ }
- if (headerName === undefined) {
- headerName = key.toLowerCase()
- if (headerNameLowerCasedRecord[headerName] === undefined && !isValidHTTPToken(headerName)) {
- throw new InvalidArgumentError('invalid header key')
- }
- }
+ bytes = done ? undefined : value
+ } catch (err) {
+ if (fetchParams.controller.ended && !timingInfo.encodedBodySize) {
+ // zlib doesn't like empty streams.
+ bytes = undefined
+ } else {
+ bytes = err
- if (Array.isArray(val)) {
- const arr = []
- for (let i = 0; i < val.length; i++) {
- if (typeof val[i] === 'string') {
- if (!isValidHeaderValue(val[i])) {
- throw new InvalidArgumentError(`invalid ${key} header`)
+ // err may be propagated from the result of calling readablestream.cancel,
+ // which might not be an error. https://github.com/nodejs/undici/issues/2009
+ isFailure = true
}
- arr.push(val[i])
- } else if (val[i] === null) {
- arr.push('')
- } else if (typeof val[i] === 'object') {
- throw new InvalidArgumentError(`invalid ${key} header`)
- } else {
- arr.push(`${val[i]}`)
}
- }
- val = arr
- } else if (typeof val === 'string') {
- if (!isValidHeaderValue(val)) {
- throw new InvalidArgumentError(`invalid ${key} header`)
- }
- } else if (val === null) {
- val = ''
- } else {
- val = `${val}`
- }
- if (request.host === null && headerName === 'host') {
- if (typeof val !== 'string') {
- throw new InvalidArgumentError('invalid host header')
- }
- // Consumed by Client
- request.host = val
- } else if (request.contentLength === null && headerName === 'content-length') {
- request.contentLength = parseInt(val, 10)
- if (!Number.isFinite(request.contentLength)) {
- throw new InvalidArgumentError('invalid content-length header')
- }
- } else if (request.contentType === null && headerName === 'content-type') {
- request.contentType = val
- request.headers.push(key, val)
- } else if (headerName === 'transfer-encoding' || headerName === 'keep-alive' || headerName === 'upgrade') {
- throw new InvalidArgumentError(`invalid ${headerName} header`)
- } else if (headerName === 'connection') {
- const value = typeof val === 'string' ? val.toLowerCase() : null
- if (value !== 'close' && value !== 'keep-alive') {
- throw new InvalidArgumentError('invalid connection header')
- }
+ if (bytes === undefined) {
+ // 2. Otherwise, if the bytes transmission for response’s message
+ // body is done normally and stream is readable, then close
+ // stream, finalize response for fetchParams and response, and
+ // abort these in-parallel steps.
+ readableStreamClose(fetchParams.controller.controller)
- if (value === 'close') {
- request.reset = true
- }
- } else if (headerName === 'expect') {
- throw new NotSupportedError('expect header not supported')
- } else {
- request.headers.push(key, val)
- }
-}
+ finalizeResponse(fetchParams, response)
-module.exports = Request
+ return
+ }
+ // 5. Increase timingInfo’s decoded body size by bytes’s length.
+ timingInfo.decodedBodySize += bytes?.byteLength ?? 0
-/***/ }),
+ // 6. If bytes is failure, then terminate fetchParams’s controller.
+ if (isFailure) {
+ fetchParams.controller.terminate(bytes)
+ return
+ }
-/***/ 9411:
-/***/ ((module) => {
+ // 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes
+ // into stream.
+ const buffer = new Uint8Array(bytes)
+ if (buffer.byteLength) {
+ fetchParams.controller.controller.enqueue(buffer)
+ }
-module.exports = {
- kClose: Symbol('close'),
- kDestroy: Symbol('destroy'),
- kDispatch: Symbol('dispatch'),
- kUrl: Symbol('url'),
- kWriting: Symbol('writing'),
- kResuming: Symbol('resuming'),
- kQueue: Symbol('queue'),
- kConnect: Symbol('connect'),
- kConnecting: Symbol('connecting'),
- kKeepAliveDefaultTimeout: Symbol('default keep alive timeout'),
- kKeepAliveMaxTimeout: Symbol('max keep alive timeout'),
- kKeepAliveTimeoutThreshold: Symbol('keep alive timeout threshold'),
- kKeepAliveTimeoutValue: Symbol('keep alive timeout'),
- kKeepAlive: Symbol('keep alive'),
- kHeadersTimeout: Symbol('headers timeout'),
- kBodyTimeout: Symbol('body timeout'),
- kServerName: Symbol('server name'),
- kLocalAddress: Symbol('local address'),
- kHost: Symbol('host'),
- kNoRef: Symbol('no ref'),
- kBodyUsed: Symbol('used'),
- kBody: Symbol('abstracted request body'),
- kRunning: Symbol('running'),
- kBlocking: Symbol('blocking'),
- kPending: Symbol('pending'),
- kSize: Symbol('size'),
- kBusy: Symbol('busy'),
- kQueued: Symbol('queued'),
- kFree: Symbol('free'),
- kConnected: Symbol('connected'),
- kClosed: Symbol('closed'),
- kNeedDrain: Symbol('need drain'),
- kReset: Symbol('reset'),
- kDestroyed: Symbol.for('nodejs.stream.destroyed'),
- kResume: Symbol('resume'),
- kOnError: Symbol('on error'),
- kMaxHeadersSize: Symbol('max headers size'),
- kRunningIdx: Symbol('running index'),
- kPendingIdx: Symbol('pending index'),
- kError: Symbol('error'),
- kClients: Symbol('clients'),
- kClient: Symbol('client'),
- kParser: Symbol('parser'),
- kOnDestroyed: Symbol('destroy callbacks'),
- kPipelining: Symbol('pipelining'),
- kSocket: Symbol('socket'),
- kHostHeader: Symbol('host header'),
- kConnector: Symbol('connector'),
- kStrictContentLength: Symbol('strict content length'),
- kMaxRedirections: Symbol('maxRedirections'),
- kMaxRequests: Symbol('maxRequestsPerClient'),
- kProxy: Symbol('proxy agent options'),
- kCounter: Symbol('socket request counter'),
- kInterceptors: Symbol('dispatch interceptors'),
- kMaxResponseSize: Symbol('max response size'),
- kHTTP2Session: Symbol('http2Session'),
- kHTTP2SessionState: Symbol('http2Session state'),
- kRetryHandlerDefaultRetry: Symbol('retry agent default retry'),
- kConstruct: Symbol('constructable'),
- kListeners: Symbol('listeners'),
- kHTTPContext: Symbol('http context'),
- kMaxConcurrentStreams: Symbol('max concurrent streams'),
- kNoProxyAgent: Symbol('no proxy agent'),
- kHttpProxyAgent: Symbol('http proxy agent'),
- kHttpsProxyAgent: Symbol('https proxy agent')
-}
-
-
-/***/ }),
-
-/***/ 3568:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const {
- wellknownHeaderNames,
- headerNameLowerCasedRecord
-} = __nccwpck_require__(1303)
-
-class TstNode {
- /** @type {any} */
- value = null
- /** @type {null | TstNode} */
- left = null
- /** @type {null | TstNode} */
- middle = null
- /** @type {null | TstNode} */
- right = null
- /** @type {number} */
- code
- /**
- * @param {string} key
- * @param {any} value
- * @param {number} index
- */
- constructor (key, value, index) {
- if (index === undefined || index >= key.length) {
- throw new TypeError('Unreachable')
- }
- const code = this.code = key.charCodeAt(index)
- // check code is ascii string
- if (code > 0x7F) {
- throw new TypeError('key must be ascii string')
- }
- if (key.length !== ++index) {
- this.middle = new TstNode(key, value, index)
- } else {
- this.value = value
- }
- }
-
- /**
- * @param {string} key
- * @param {any} value
- */
- add (key, value) {
- const length = key.length
- if (length === 0) {
- throw new TypeError('Unreachable')
- }
- let index = 0
- let node = this
- while (true) {
- const code = key.charCodeAt(index)
- // check code is ascii string
- if (code > 0x7F) {
- throw new TypeError('key must be ascii string')
- }
- if (node.code === code) {
- if (length === ++index) {
- node.value = value
- break
- } else if (node.middle !== null) {
- node = node.middle
- } else {
- node.middle = new TstNode(key, value, index)
- break
- }
- } else if (node.code < code) {
- if (node.left !== null) {
- node = node.left
- } else {
- node.left = new TstNode(key, value, index)
- break
- }
- } else if (node.right !== null) {
- node = node.right
- } else {
- node.right = new TstNode(key, value, index)
- break
+ // 8. If stream is errored, then terminate the ongoing fetch.
+ if (isErrored(stream)) {
+ fetchParams.controller.terminate()
+ return
}
- }
- }
- /**
- * @param {Uint8Array} key
- * @return {TstNode | null}
- */
- search (key) {
- const keylength = key.length
- let index = 0
- let node = this
- while (node !== null && index < keylength) {
- let code = key[index]
- // A-Z
- // First check if it is bigger than 0x5a.
- // Lowercase letters have higher char codes than uppercase ones.
- // Also we assume that headers will mostly contain lowercase characters.
- if (code <= 0x5a && code >= 0x41) {
- // Lowercase for uppercase.
- code |= 32
- }
- while (node !== null) {
- if (code === node.code) {
- if (keylength === ++index) {
- // Returns Node since it is the last key.
- return node
- }
- node = node.middle
- break
- }
- node = node.code < code ? node.left : node.right
+ // 9. If stream doesn’t need more data ask the user agent to suspend
+ // the ongoing fetch.
+ if (fetchParams.controller.controller.desiredSize <= 0) {
+ return
}
}
- return null
}
-}
-class TernarySearchTree {
- /** @type {TstNode | null} */
- node = null
+ // 2. If aborted, then:
+ function onAborted (reason) {
+ // 2. If fetchParams is aborted, then:
+ if (isAborted(fetchParams)) {
+ // 1. Set response’s aborted flag.
+ response.aborted = true
- /**
- * @param {string} key
- * @param {any} value
- * */
- insert (key, value) {
- if (this.node === null) {
- this.node = new TstNode(key, value, 0)
+ // 2. If stream is readable, then error stream with the result of
+ // deserialize a serialized abort reason given fetchParams’s
+ // controller’s serialized abort reason and an
+ // implementation-defined realm.
+ if (isReadable(stream)) {
+ fetchParams.controller.controller.error(
+ fetchParams.controller.serializedAbortReason
+ )
+ }
} else {
- this.node.add(key, value)
+ // 3. Otherwise, if stream is readable, error stream with a TypeError.
+ if (isReadable(stream)) {
+ fetchParams.controller.controller.error(new TypeError('terminated', {
+ cause: isErrorLike(reason) ? reason : undefined
+ }))
+ }
}
- }
- /**
- * @param {Uint8Array} key
- * @return {any}
- */
- lookup (key) {
- return this.node?.search(key)?.value ?? null
+ // 4. If connection uses HTTP/2, then transmit an RST_STREAM frame.
+ // 5. Otherwise, the user agent should close connection unless it would be bad for performance to do so.
+ fetchParams.controller.connection.destroy()
}
-}
-const tree = new TernarySearchTree()
+ // 20. Return response.
+ return response
-for (let i = 0; i < wellknownHeaderNames.length; ++i) {
- const key = headerNameLowerCasedRecord[wellknownHeaderNames[i]]
- tree.insert(key, key)
-}
+ function dispatch ({ body }) {
+ const url = requestCurrentURL(request)
+ /** @type {import('../..').Agent} */
+ const agent = fetchParams.controller.dispatcher
-module.exports = {
- TernarySearchTree,
- tree
-}
+ return new Promise((resolve, reject) => agent.dispatch(
+ {
+ path: url.pathname + url.search,
+ origin: url.origin,
+ method: request.method,
+ body: agent.isMockActive ? request.body && (request.body.source || request.body.stream) : body,
+ headers: request.headersList.entries,
+ maxRedirections: 0,
+ upgrade: request.mode === 'websocket' ? 'websocket' : undefined
+ },
+ {
+ body: null,
+ abort: null,
+ onConnect (abort) {
+ // TODO (fix): Do we need connection here?
+ const { connection } = fetchParams.controller
-/***/ }),
+ // Set timingInfo’s final connection timing info to the result of calling clamp and coarsen
+ // connection timing info with connection’s timing info, timingInfo’s post-redirect start
+ // time, and fetchParams’s cross-origin isolated capability.
+ // TODO: implement connection timing
+ timingInfo.finalConnectionTimingInfo = clampAndCoarsenConnectionTimingInfo(undefined, timingInfo.postRedirectStartTime, fetchParams.crossOriginIsolatedCapability)
-/***/ 1544:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ if (connection.destroyed) {
+ abort(new DOMException('The operation was aborted.', 'AbortError'))
+ } else {
+ fetchParams.controller.on('terminated', abort)
+ this.abort = connection.abort = abort
+ }
+ // Set timingInfo’s final network-request start time to the coarsened shared current time given
+ // fetchParams’s cross-origin isolated capability.
+ timingInfo.finalNetworkRequestStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability)
+ },
+ onResponseStarted () {
+ // Set timingInfo’s final network-response start time to the coarsened shared current
+ // time given fetchParams’s cross-origin isolated capability, immediately after the
+ // user agent’s HTTP parser receives the first byte of the response (e.g., frame header
+ // bytes for HTTP/2 or response status line for HTTP/1.x).
+ timingInfo.finalNetworkResponseStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability)
+ },
-const assert = __nccwpck_require__(4589)
-const { kDestroyed, kBodyUsed, kListeners, kBody } = __nccwpck_require__(9411)
-const { IncomingMessage } = __nccwpck_require__(7067)
-const stream = __nccwpck_require__(7075)
-const net = __nccwpck_require__(7030)
-const { Blob } = __nccwpck_require__(4573)
-const nodeUtil = __nccwpck_require__(7975)
-const { stringify } = __nccwpck_require__(1792)
-const { EventEmitter: EE } = __nccwpck_require__(8474)
-const { InvalidArgumentError } = __nccwpck_require__(8091)
-const { headerNameLowerCasedRecord } = __nccwpck_require__(1303)
-const { tree } = __nccwpck_require__(3568)
+ onHeaders (status, rawHeaders, resume, statusText) {
+ if (status < 200) {
+ return
+ }
-const [nodeMajor, nodeMinor] = process.versions.node.split('.').map(v => Number(v))
+ let location = ''
-class BodyAsyncIterable {
- constructor (body) {
- this[kBody] = body
- this[kBodyUsed] = false
- }
+ const headersList = new HeadersList()
- async * [Symbol.asyncIterator] () {
- assert(!this[kBodyUsed], 'disturbed')
- this[kBodyUsed] = true
- yield * this[kBody]
- }
-}
+ for (let i = 0; i < rawHeaders.length; i += 2) {
+ headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i]), rawHeaders[i + 1].toString('latin1'), true)
+ }
+ location = headersList.get('location', true)
-function wrapRequestBody (body) {
- if (isStream(body)) {
- // TODO (fix): Provide some way for the user to cache the file to e.g. /tmp
- // so that it can be dispatched again?
- // TODO (fix): Do we need 100-expect support to provide a way to do this properly?
- if (bodyLength(body) === 0) {
- body
- .on('data', function () {
- assert(false)
- })
- }
+ this.body = new Readable({ read: resume })
- if (typeof body.readableDidRead !== 'boolean') {
- body[kBodyUsed] = false
- EE.prototype.on.call(body, 'data', function () {
- this[kBodyUsed] = true
- })
- }
+ const decoders = []
- return body
- } else if (body && typeof body.pipeTo === 'function') {
- // TODO (fix): We can't access ReadableStream internal state
- // to determine whether or not it has been disturbed. This is just
- // a workaround.
- return new BodyAsyncIterable(body)
- } else if (
- body &&
- typeof body !== 'string' &&
- !ArrayBuffer.isView(body) &&
- isIterable(body)
- ) {
- // TODO: Should we allow re-using iterable if !this.opts.idempotent
- // or through some other flag?
- return new BodyAsyncIterable(body)
- } else {
- return body
- }
-}
+ const willFollow = location && request.redirect === 'follow' &&
+ redirectStatusSet.has(status)
-function nop () {}
+ // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding
+ if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) {
+ // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1
+ const contentEncoding = headersList.get('content-encoding', true)
+ // "All content-coding values are case-insensitive..."
+ /** @type {string[]} */
+ const codings = contentEncoding ? contentEncoding.toLowerCase().split(',') : []
-function isStream (obj) {
- return obj && typeof obj === 'object' && typeof obj.pipe === 'function' && typeof obj.on === 'function'
-}
+ // Limit the number of content-encodings to prevent resource exhaustion.
+ // CVE fix similar to urllib3 (GHSA-gm62-xv2j-4w53) and curl (CVE-2022-32206).
+ const maxContentEncodings = 5
+ if (codings.length > maxContentEncodings) {
+ reject(new Error(`too many content-encodings in response: ${codings.length}, maximum allowed is ${maxContentEncodings}`))
+ return true
+ }
-// based on https://github.com/node-fetch/fetch-blob/blob/8ab587d34080de94140b54f07168451e7d0b655e/index.js#L229-L241 (MIT License)
-function isBlobLike (object) {
- if (object === null) {
- return false
- } else if (object instanceof Blob) {
- return true
- } else if (typeof object !== 'object') {
- return false
- } else {
- const sTag = object[Symbol.toStringTag]
+ for (let i = codings.length - 1; i >= 0; --i) {
+ const coding = codings[i].trim()
+ // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.2
+ if (coding === 'x-gzip' || coding === 'gzip') {
+ decoders.push(zlib.createGunzip({
+ // Be less strict when decoding compressed responses, since sometimes
+ // servers send slightly invalid responses that are still accepted
+ // by common browsers.
+ // Always using Z_SYNC_FLUSH is what cURL does.
+ flush: zlib.constants.Z_SYNC_FLUSH,
+ finishFlush: zlib.constants.Z_SYNC_FLUSH
+ }))
+ } else if (coding === 'deflate') {
+ decoders.push(createInflate({
+ flush: zlib.constants.Z_SYNC_FLUSH,
+ finishFlush: zlib.constants.Z_SYNC_FLUSH
+ }))
+ } else if (coding === 'br') {
+ decoders.push(zlib.createBrotliDecompress({
+ flush: zlib.constants.BROTLI_OPERATION_FLUSH,
+ finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH
+ }))
+ } else {
+ decoders.length = 0
+ break
+ }
+ }
+ }
- return (sTag === 'Blob' || sTag === 'File') && (
- ('stream' in object && typeof object.stream === 'function') ||
- ('arrayBuffer' in object && typeof object.arrayBuffer === 'function')
- )
- }
-}
+ const onError = this.onError.bind(this)
-function buildURL (url, queryParams) {
- if (url.includes('?') || url.includes('#')) {
- throw new Error('Query params cannot be passed when url already contains "?" or "#".')
- }
+ resolve({
+ status,
+ statusText,
+ headersList,
+ body: decoders.length
+ ? pipeline(this.body, ...decoders, (err) => {
+ if (err) {
+ this.onError(err)
+ }
+ }).on('error', onError)
+ : this.body.on('error', onError)
+ })
- const stringified = stringify(queryParams)
+ return true
+ },
- if (stringified) {
- url += '?' + stringified
- }
+ onData (chunk) {
+ if (fetchParams.controller.dump) {
+ return
+ }
- return url
-}
+ // 1. If one or more bytes have been transmitted from response’s
+ // message body, then:
-function isValidPort (port) {
- const value = parseInt(port, 10)
- return (
- value === Number(port) &&
- value >= 0 &&
- value <= 65535
- )
-}
+ // 1. Let bytes be the transmitted bytes.
+ const bytes = chunk
-function isHttpOrHttpsPrefixed (value) {
- return (
- value != null &&
- value[0] === 'h' &&
- value[1] === 't' &&
- value[2] === 't' &&
- value[3] === 'p' &&
- (
- value[4] === ':' ||
- (
- value[4] === 's' &&
- value[5] === ':'
- )
- )
- )
-}
+ // 2. Let codings be the result of extracting header list values
+ // given `Content-Encoding` and response’s header list.
+ // See pullAlgorithm.
-function parseURL (url) {
- if (typeof url === 'string') {
- url = new URL(url)
+ // 3. Increase timingInfo’s encoded body size by bytes’s length.
+ timingInfo.encodedBodySize += bytes.byteLength
- if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) {
- throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')
- }
+ // 4. See pullAlgorithm...
- return url
- }
+ return this.body.push(bytes)
+ },
- if (!url || typeof url !== 'object') {
- throw new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.')
- }
+ onComplete () {
+ if (this.abort) {
+ fetchParams.controller.off('terminated', this.abort)
+ }
- if (!(url instanceof URL)) {
- if (url.port != null && url.port !== '' && isValidPort(url.port) === false) {
- throw new InvalidArgumentError('Invalid URL: port must be a valid integer or a string representation of an integer.')
- }
+ if (fetchParams.controller.onAborted) {
+ fetchParams.controller.off('terminated', fetchParams.controller.onAborted)
+ }
- if (url.path != null && typeof url.path !== 'string') {
- throw new InvalidArgumentError('Invalid URL path: the path must be a string or null/undefined.')
- }
+ fetchParams.controller.ended = true
- if (url.pathname != null && typeof url.pathname !== 'string') {
- throw new InvalidArgumentError('Invalid URL pathname: the pathname must be a string or null/undefined.')
- }
-
- if (url.hostname != null && typeof url.hostname !== 'string') {
- throw new InvalidArgumentError('Invalid URL hostname: the hostname must be a string or null/undefined.')
- }
+ this.body.push(null)
+ },
- if (url.origin != null && typeof url.origin !== 'string') {
- throw new InvalidArgumentError('Invalid URL origin: the origin must be a string or null/undefined.')
- }
+ onError (error) {
+ if (this.abort) {
+ fetchParams.controller.off('terminated', this.abort)
+ }
- if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) {
- throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')
- }
+ this.body?.destroy(error)
- const port = url.port != null
- ? url.port
- : (url.protocol === 'https:' ? 443 : 80)
- let origin = url.origin != null
- ? url.origin
- : `${url.protocol || ''}//${url.hostname || ''}:${port}`
- let path = url.path != null
- ? url.path
- : `${url.pathname || ''}${url.search || ''}`
+ fetchParams.controller.terminate(error)
- if (origin[origin.length - 1] === '/') {
- origin = origin.slice(0, origin.length - 1)
- }
+ reject(error)
+ },
- if (path && path[0] !== '/') {
- path = `/${path}`
- }
- // new URL(path, origin) is unsafe when `path` contains an absolute URL
- // From https://developer.mozilla.org/en-US/docs/Web/API/URL/URL:
- // If first parameter is a relative URL, second param is required, and will be used as the base URL.
- // If first parameter is an absolute URL, a given second param will be ignored.
- return new URL(`${origin}${path}`)
- }
+ onUpgrade (status, rawHeaders, socket) {
+ if (status !== 101) {
+ return
+ }
- if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) {
- throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')
- }
+ const headersList = new HeadersList()
- return url
-}
+ for (let i = 0; i < rawHeaders.length; i += 2) {
+ headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i]), rawHeaders[i + 1].toString('latin1'), true)
+ }
-function parseOrigin (url) {
- url = parseURL(url)
+ resolve({
+ status,
+ statusText: STATUS_CODES[status],
+ headersList,
+ socket
+ })
- if (url.pathname !== '/' || url.search || url.hash) {
- throw new InvalidArgumentError('invalid url')
+ return true
+ }
+ }
+ ))
}
+}
- return url
+module.exports = {
+ fetch,
+ Fetch,
+ fetching,
+ finalizeAndReportTiming
}
-function getHostname (host) {
- if (host[0] === '[') {
- const idx = host.indexOf(']')
- assert(idx !== -1)
- return host.substring(1, idx)
- }
+/***/ }),
- const idx = host.indexOf(':')
- if (idx === -1) return host
+/***/ 9967:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- return host.substring(0, idx)
-}
+/* globals AbortController */
-// IP addresses are not valid server names per RFC6066
-// > Currently, the only server names supported are DNS hostnames
-function getServerName (host) {
- if (!host) {
- return null
- }
- assert(typeof host === 'string')
- const servername = getHostname(host)
- if (net.isIP(servername)) {
- return ''
- }
+const { extractBody, mixinBody, cloneBody, bodyUnusable } = __nccwpck_require__(4492)
+const { Headers, fill: fillHeaders, HeadersList, setHeadersGuard, getHeadersGuard, setHeadersList, getHeadersList } = __nccwpck_require__(660)
+const { FinalizationRegistry } = __nccwpck_require__(6653)()
+const util = __nccwpck_require__(3440)
+const nodeUtil = __nccwpck_require__(7975)
+const {
+ isValidHTTPToken,
+ sameOrigin,
+ environmentSettingsObject
+} = __nccwpck_require__(3168)
+const {
+ forbiddenMethodsSet,
+ corsSafeListedMethodsSet,
+ referrerPolicy,
+ requestRedirect,
+ requestMode,
+ requestCredentials,
+ requestCache,
+ requestDuplex
+} = __nccwpck_require__(4495)
+const { kEnumerableProperty, normalizedMethodRecordsBase, normalizedMethodRecords } = util
+const { kHeaders, kSignal, kState, kDispatcher } = __nccwpck_require__(3627)
+const { webidl } = __nccwpck_require__(5893)
+const { URLSerializer } = __nccwpck_require__(1900)
+const { kConstruct } = __nccwpck_require__(6443)
+const assert = __nccwpck_require__(4589)
+const { getMaxListeners, setMaxListeners, getEventListeners, defaultMaxListeners } = __nccwpck_require__(8474)
- return servername
-}
+const kAbortController = Symbol('abortController')
-function deepClone (obj) {
- return JSON.parse(JSON.stringify(obj))
-}
+const requestFinalizer = new FinalizationRegistry(({ signal, abort }) => {
+ signal.removeEventListener('abort', abort)
+})
-function isAsyncIterable (obj) {
- return !!(obj != null && typeof obj[Symbol.asyncIterator] === 'function')
-}
+const dependentControllerMap = new WeakMap()
-function isIterable (obj) {
- return !!(obj != null && (typeof obj[Symbol.iterator] === 'function' || typeof obj[Symbol.asyncIterator] === 'function'))
-}
+function buildAbort (acRef) {
+ return abort
-function bodyLength (body) {
- if (body == null) {
- return 0
- } else if (isStream(body)) {
- const state = body._readableState
- return state && state.objectMode === false && state.ended === true && Number.isFinite(state.length)
- ? state.length
- : null
- } else if (isBlobLike(body)) {
- return body.size != null ? body.size : null
- } else if (isBuffer(body)) {
- return body.byteLength
- }
+ function abort () {
+ const ac = acRef.deref()
+ if (ac !== undefined) {
+ // Currently, there is a problem with FinalizationRegistry.
+ // https://github.com/nodejs/node/issues/49344
+ // https://github.com/nodejs/node/issues/47748
+ // In the case of abort, the first step is to unregister from it.
+ // If the controller can refer to it, it is still registered.
+ // It will be removed in the future.
+ requestFinalizer.unregister(abort)
- return null
-}
+ // Unsubscribe a listener.
+ // FinalizationRegistry will no longer be called, so this must be done.
+ this.removeEventListener('abort', abort)
-function isDestroyed (body) {
- return body && !!(body.destroyed || body[kDestroyed] || (stream.isDestroyed?.(body)))
-}
+ ac.abort(this.reason)
-function destroy (stream, err) {
- if (stream == null || !isStream(stream) || isDestroyed(stream)) {
- return
- }
+ const controllerList = dependentControllerMap.get(ac.signal)
- if (typeof stream.destroy === 'function') {
- if (Object.getPrototypeOf(stream).constructor === IncomingMessage) {
- // See: https://github.com/nodejs/node/pull/38505/files
- stream.socket = null
+ if (controllerList !== undefined) {
+ if (controllerList.size !== 0) {
+ for (const ref of controllerList) {
+ const ctrl = ref.deref()
+ if (ctrl !== undefined) {
+ ctrl.abort(this.reason)
+ }
+ }
+ controllerList.clear()
+ }
+ dependentControllerMap.delete(ac.signal)
+ }
}
-
- stream.destroy(err)
- } else if (err) {
- queueMicrotask(() => {
- stream.emit('error', err)
- })
- }
-
- if (stream.destroyed !== true) {
- stream[kDestroyed] = true
}
}
-const KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/
-function parseKeepAliveTimeout (val) {
- const m = val.toString().match(KEEPALIVE_TIMEOUT_EXPR)
- return m ? parseInt(m[1], 10) * 1000 : null
-}
+let patchMethodWarning = false
-/**
- * Retrieves a header name and returns its lowercase value.
- * @param {string | Buffer} value Header name
- * @returns {string}
- */
-function headerNameToString (value) {
- return typeof value === 'string'
- ? headerNameLowerCasedRecord[value] ?? value.toLowerCase()
- : tree.lookup(value) ?? value.toString('latin1').toLowerCase()
-}
+// https://fetch.spec.whatwg.org/#request-class
+class Request {
+ // https://fetch.spec.whatwg.org/#dom-request
+ constructor (input, init = {}) {
+ webidl.util.markAsUncloneable(this)
+ if (input === kConstruct) {
+ return
+ }
-/**
- * Receive the buffer as a string and return its lowercase value.
- * @param {Buffer} value Header name
- * @returns {string}
- */
-function bufferToLowerCasedHeaderName (value) {
- return tree.lookup(value) ?? value.toString('latin1').toLowerCase()
-}
+ const prefix = 'Request constructor'
+ webidl.argumentLengthCheck(arguments, 1, prefix)
-/**
- * @param {Record | (Buffer | string | (Buffer | string)[])[]} headers
- * @param {Record} [obj]
- * @returns {Record}
- */
-function parseHeaders (headers, obj) {
- if (obj === undefined) obj = {}
- for (let i = 0; i < headers.length; i += 2) {
- const key = headerNameToString(headers[i])
- let val = obj[key]
+ input = webidl.converters.RequestInfo(input, prefix, 'input')
+ init = webidl.converters.RequestInit(init, prefix, 'init')
- if (val) {
- if (typeof val === 'string') {
- val = [val]
- obj[key] = val
- }
- val.push(headers[i + 1].toString('utf8'))
- } else {
- const headersValue = headers[i + 1]
- if (typeof headersValue === 'string') {
- obj[key] = headersValue
- } else {
- obj[key] = Array.isArray(headersValue) ? headersValue.map(x => x.toString('utf8')) : headersValue.toString('utf8')
- }
- }
- }
+ // 1. Let request be null.
+ let request = null
- // See https://github.com/nodejs/node/pull/46528
- if ('content-length' in obj && 'content-disposition' in obj) {
- obj['content-disposition'] = Buffer.from(obj['content-disposition']).toString('latin1')
- }
+ // 2. Let fallbackMode be null.
+ let fallbackMode = null
- return obj
-}
+ // 3. Let baseURL be this’s relevant settings object’s API base URL.
+ const baseUrl = environmentSettingsObject.settingsObject.baseUrl
-function parseRawHeaders (headers) {
- const len = headers.length
- const ret = new Array(len)
+ // 4. Let signal be null.
+ let signal = null
- let hasContentLength = false
- let contentDispositionIdx = -1
- let key
- let val
- let kLen = 0
+ // 5. If input is a string, then:
+ if (typeof input === 'string') {
+ this[kDispatcher] = init.dispatcher
- for (let n = 0; n < headers.length; n += 2) {
- key = headers[n]
- val = headers[n + 1]
+ // 1. Let parsedURL be the result of parsing input with baseURL.
+ // 2. If parsedURL is failure, then throw a TypeError.
+ let parsedURL
+ try {
+ parsedURL = new URL(input, baseUrl)
+ } catch (err) {
+ throw new TypeError('Failed to parse URL from ' + input, { cause: err })
+ }
- typeof key !== 'string' && (key = key.toString())
- typeof val !== 'string' && (val = val.toString('utf8'))
+ // 3. If parsedURL includes credentials, then throw a TypeError.
+ if (parsedURL.username || parsedURL.password) {
+ throw new TypeError(
+ 'Request cannot be constructed from a URL that includes credentials: ' +
+ input
+ )
+ }
- kLen = key.length
- if (kLen === 14 && key[7] === '-' && (key === 'content-length' || key.toLowerCase() === 'content-length')) {
- hasContentLength = true
- } else if (kLen === 19 && key[7] === '-' && (key === 'content-disposition' || key.toLowerCase() === 'content-disposition')) {
- contentDispositionIdx = n + 1
- }
- ret[n] = key
- ret[n + 1] = val
- }
+ // 4. Set request to a new request whose URL is parsedURL.
+ request = makeRequest({ urlList: [parsedURL] })
- // See https://github.com/nodejs/node/pull/46528
- if (hasContentLength && contentDispositionIdx !== -1) {
- ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString('latin1')
- }
+ // 5. Set fallbackMode to "cors".
+ fallbackMode = 'cors'
+ } else {
+ this[kDispatcher] = init.dispatcher || input[kDispatcher]
- return ret
-}
+ // 6. Otherwise:
-function isBuffer (buffer) {
- // See, https://github.com/mcollina/undici/pull/319
- return buffer instanceof Uint8Array || Buffer.isBuffer(buffer)
-}
+ // 7. Assert: input is a Request object.
+ assert(input instanceof Request)
-function validateHandler (handler, method, upgrade) {
- if (!handler || typeof handler !== 'object') {
- throw new InvalidArgumentError('handler must be an object')
- }
+ // 8. Set request to input’s request.
+ request = input[kState]
- if (typeof handler.onConnect !== 'function') {
- throw new InvalidArgumentError('invalid onConnect method')
- }
+ // 9. Set signal to input’s signal.
+ signal = input[kSignal]
+ }
- if (typeof handler.onError !== 'function') {
- throw new InvalidArgumentError('invalid onError method')
- }
+ // 7. Let origin be this’s relevant settings object’s origin.
+ const origin = environmentSettingsObject.settingsObject.origin
- if (typeof handler.onBodySent !== 'function' && handler.onBodySent !== undefined) {
- throw new InvalidArgumentError('invalid onBodySent method')
- }
+ // 8. Let window be "client".
+ let window = 'client'
- if (upgrade || method === 'CONNECT') {
- if (typeof handler.onUpgrade !== 'function') {
- throw new InvalidArgumentError('invalid onUpgrade method')
- }
- } else {
- if (typeof handler.onHeaders !== 'function') {
- throw new InvalidArgumentError('invalid onHeaders method')
+ // 9. If request’s window is an environment settings object and its origin
+ // is same origin with origin, then set window to request’s window.
+ if (
+ request.window?.constructor?.name === 'EnvironmentSettingsObject' &&
+ sameOrigin(request.window, origin)
+ ) {
+ window = request.window
}
- if (typeof handler.onData !== 'function') {
- throw new InvalidArgumentError('invalid onData method')
+ // 10. If init["window"] exists and is non-null, then throw a TypeError.
+ if (init.window != null) {
+ throw new TypeError(`'window' option '${window}' must be null`)
}
- if (typeof handler.onComplete !== 'function') {
- throw new InvalidArgumentError('invalid onComplete method')
+ // 11. If init["window"] exists, then set window to "no-window".
+ if ('window' in init) {
+ window = 'no-window'
}
- }
-}
-// A body is disturbed if it has been read from and it cannot
-// be re-used without losing state or data.
-function isDisturbed (body) {
- // TODO (fix): Why is body[kBodyUsed] needed?
- return !!(body && (stream.isDisturbed(body) || body[kBodyUsed]))
-}
+ // 12. Set request to a new request with the following properties:
+ request = makeRequest({
+ // URL request’s URL.
+ // undici implementation note: this is set as the first item in request's urlList in makeRequest
+ // method request’s method.
+ method: request.method,
+ // header list A copy of request’s header list.
+ // undici implementation note: headersList is cloned in makeRequest
+ headersList: request.headersList,
+ // unsafe-request flag Set.
+ unsafeRequest: request.unsafeRequest,
+ // client This’s relevant settings object.
+ client: environmentSettingsObject.settingsObject,
+ // window window.
+ window,
+ // priority request’s priority.
+ priority: request.priority,
+ // origin request’s origin. The propagation of the origin is only significant for navigation requests
+ // being handled by a service worker. In this scenario a request can have an origin that is different
+ // from the current client.
+ origin: request.origin,
+ // referrer request’s referrer.
+ referrer: request.referrer,
+ // referrer policy request’s referrer policy.
+ referrerPolicy: request.referrerPolicy,
+ // mode request’s mode.
+ mode: request.mode,
+ // credentials mode request’s credentials mode.
+ credentials: request.credentials,
+ // cache mode request’s cache mode.
+ cache: request.cache,
+ // redirect mode request’s redirect mode.
+ redirect: request.redirect,
+ // integrity metadata request’s integrity metadata.
+ integrity: request.integrity,
+ // keepalive request’s keepalive.
+ keepalive: request.keepalive,
+ // reload-navigation flag request’s reload-navigation flag.
+ reloadNavigation: request.reloadNavigation,
+ // history-navigation flag request’s history-navigation flag.
+ historyNavigation: request.historyNavigation,
+ // URL list A clone of request’s URL list.
+ urlList: [...request.urlList]
+ })
-function isErrored (body) {
- return !!(body && stream.isErrored(body))
-}
+ const initHasKey = Object.keys(init).length !== 0
-function isReadable (body) {
- return !!(body && stream.isReadable(body))
-}
+ // 13. If init is not empty, then:
+ if (initHasKey) {
+ // 1. If request’s mode is "navigate", then set it to "same-origin".
+ if (request.mode === 'navigate') {
+ request.mode = 'same-origin'
+ }
-function getSocketInfo (socket) {
- return {
- localAddress: socket.localAddress,
- localPort: socket.localPort,
- remoteAddress: socket.remoteAddress,
- remotePort: socket.remotePort,
- remoteFamily: socket.remoteFamily,
- timeout: socket.timeout,
- bytesWritten: socket.bytesWritten,
- bytesRead: socket.bytesRead
- }
-}
+ // 2. Unset request’s reload-navigation flag.
+ request.reloadNavigation = false
-/** @type {globalThis['ReadableStream']} */
-function ReadableStreamFrom (iterable) {
- // We cannot use ReadableStream.from here because it does not return a byte stream.
+ // 3. Unset request’s history-navigation flag.
+ request.historyNavigation = false
- let iterator
- return new ReadableStream(
- {
- async start () {
- iterator = iterable[Symbol.asyncIterator]()
- },
- async pull (controller) {
- const { done, value } = await iterator.next()
- if (done) {
- queueMicrotask(() => {
- controller.close()
- controller.byobRequest?.respond(0)
- })
- } else {
- const buf = Buffer.isBuffer(value) ? value : Buffer.from(value)
- if (buf.byteLength) {
- controller.enqueue(new Uint8Array(buf))
- }
- }
- return controller.desiredSize > 0
- },
- async cancel (reason) {
- await iterator.return()
- },
- type: 'bytes'
- }
- )
-}
+ // 4. Set request’s origin to "client".
+ request.origin = 'client'
-// The chunk should be a FormData instance and contains
-// all the required methods.
-function isFormDataLike (object) {
- return (
- object &&
- typeof object === 'object' &&
- typeof object.append === 'function' &&
- typeof object.delete === 'function' &&
- typeof object.get === 'function' &&
- typeof object.getAll === 'function' &&
- typeof object.has === 'function' &&
- typeof object.set === 'function' &&
- object[Symbol.toStringTag] === 'FormData'
- )
-}
+ // 5. Set request’s referrer to "client"
+ request.referrer = 'client'
-function addAbortListener (signal, listener) {
- if ('addEventListener' in signal) {
- signal.addEventListener('abort', listener, { once: true })
- return () => signal.removeEventListener('abort', listener)
- }
- signal.addListener('abort', listener)
- return () => signal.removeListener('abort', listener)
-}
-
-const hasToWellFormed = typeof String.prototype.toWellFormed === 'function'
-const hasIsWellFormed = typeof String.prototype.isWellFormed === 'function'
-
-/**
- * @param {string} val
- */
-function toUSVString (val) {
- return hasToWellFormed ? `${val}`.toWellFormed() : nodeUtil.toUSVString(val)
-}
-
-/**
- * @param {string} val
- */
-// TODO: move this to webidl
-function isUSVString (val) {
- return hasIsWellFormed ? `${val}`.isWellFormed() : toUSVString(val) === `${val}`
-}
+ // 6. Set request’s referrer policy to the empty string.
+ request.referrerPolicy = ''
-/**
- * @see https://tools.ietf.org/html/rfc7230#section-3.2.6
- * @param {number} c
- */
-function isTokenCharCode (c) {
- switch (c) {
- case 0x22:
- case 0x28:
- case 0x29:
- case 0x2c:
- case 0x2f:
- case 0x3a:
- case 0x3b:
- case 0x3c:
- case 0x3d:
- case 0x3e:
- case 0x3f:
- case 0x40:
- case 0x5b:
- case 0x5c:
- case 0x5d:
- case 0x7b:
- case 0x7d:
- // DQUOTE and "(),/:;<=>?@[\]{}"
- return false
- default:
- // VCHAR %x21-7E
- return c >= 0x21 && c <= 0x7e
- }
-}
+ // 7. Set request’s URL to request’s current URL.
+ request.url = request.urlList[request.urlList.length - 1]
-/**
- * @param {string} characters
- */
-function isValidHTTPToken (characters) {
- if (characters.length === 0) {
- return false
- }
- for (let i = 0; i < characters.length; ++i) {
- if (!isTokenCharCode(characters.charCodeAt(i))) {
- return false
+ // 8. Set request’s URL list to « request’s URL ».
+ request.urlList = [request.url]
}
- }
- return true
-}
-
-// headerCharRegex have been lifted from
-// https://github.com/nodejs/node/blob/main/lib/_http_common.js
-
-/**
- * Matches if val contains an invalid field-vchar
- * field-value = *( field-content / obs-fold )
- * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
- * field-vchar = VCHAR / obs-text
- */
-const headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/
-/**
- * @param {string} characters
- */
-function isValidHeaderValue (characters) {
- return !headerCharRegex.test(characters)
-}
+ // 14. If init["referrer"] exists, then:
+ if (init.referrer !== undefined) {
+ // 1. Let referrer be init["referrer"].
+ const referrer = init.referrer
-// Parsed accordingly to RFC 9110
-// https://www.rfc-editor.org/rfc/rfc9110#field.content-range
-function parseRangeHeader (range) {
- if (range == null || range === '') return { start: 0, end: null, size: null }
+ // 2. If referrer is the empty string, then set request’s referrer to "no-referrer".
+ if (referrer === '') {
+ request.referrer = 'no-referrer'
+ } else {
+ // 1. Let parsedReferrer be the result of parsing referrer with
+ // baseURL.
+ // 2. If parsedReferrer is failure, then throw a TypeError.
+ let parsedReferrer
+ try {
+ parsedReferrer = new URL(referrer, baseUrl)
+ } catch (err) {
+ throw new TypeError(`Referrer "${referrer}" is not a valid URL.`, { cause: err })
+ }
- const m = range ? range.match(/^bytes (\d+)-(\d+)\/(\d+)?$/) : null
- return m
- ? {
- start: parseInt(m[1]),
- end: m[2] ? parseInt(m[2]) : null,
- size: m[3] ? parseInt(m[3]) : null
+ // 3. If one of the following is true
+ // - parsedReferrer’s scheme is "about" and path is the string "client"
+ // - parsedReferrer’s origin is not same origin with origin
+ // then set request’s referrer to "client".
+ if (
+ (parsedReferrer.protocol === 'about:' && parsedReferrer.hostname === 'client') ||
+ (origin && !sameOrigin(parsedReferrer, environmentSettingsObject.settingsObject.baseUrl))
+ ) {
+ request.referrer = 'client'
+ } else {
+ // 4. Otherwise, set request’s referrer to parsedReferrer.
+ request.referrer = parsedReferrer
+ }
}
- : null
-}
+ }
-function addListener (obj, name, listener) {
- const listeners = (obj[kListeners] ??= [])
- listeners.push([name, listener])
- obj.on(name, listener)
- return obj
-}
+ // 15. If init["referrerPolicy"] exists, then set request’s referrer policy
+ // to it.
+ if (init.referrerPolicy !== undefined) {
+ request.referrerPolicy = init.referrerPolicy
+ }
-function removeAllListeners (obj) {
- for (const [name, listener] of obj[kListeners] ?? []) {
- obj.removeListener(name, listener)
- }
- obj[kListeners] = null
-}
+ // 16. Let mode be init["mode"] if it exists, and fallbackMode otherwise.
+ let mode
+ if (init.mode !== undefined) {
+ mode = init.mode
+ } else {
+ mode = fallbackMode
+ }
-function errorRequest (client, request, err) {
- try {
- request.onError(err)
- assert(request.aborted)
- } catch (err) {
- client.emit('error', err)
- }
-}
+ // 17. If mode is "navigate", then throw a TypeError.
+ if (mode === 'navigate') {
+ throw webidl.errors.exception({
+ header: 'Request constructor',
+ message: 'invalid request mode navigate.'
+ })
+ }
-const kEnumerableProperty = Object.create(null)
-kEnumerableProperty.enumerable = true
+ // 18. If mode is non-null, set request’s mode to mode.
+ if (mode != null) {
+ request.mode = mode
+ }
-const normalizedMethodRecordsBase = {
- delete: 'DELETE',
- DELETE: 'DELETE',
- get: 'GET',
- GET: 'GET',
- head: 'HEAD',
- HEAD: 'HEAD',
- options: 'OPTIONS',
- OPTIONS: 'OPTIONS',
- post: 'POST',
- POST: 'POST',
- put: 'PUT',
- PUT: 'PUT'
-}
+ // 19. If init["credentials"] exists, then set request’s credentials mode
+ // to it.
+ if (init.credentials !== undefined) {
+ request.credentials = init.credentials
+ }
-const normalizedMethodRecords = {
- ...normalizedMethodRecordsBase,
- patch: 'patch',
- PATCH: 'PATCH'
-}
+ // 18. If init["cache"] exists, then set request’s cache mode to it.
+ if (init.cache !== undefined) {
+ request.cache = init.cache
+ }
-// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`.
-Object.setPrototypeOf(normalizedMethodRecordsBase, null)
-Object.setPrototypeOf(normalizedMethodRecords, null)
+ // 21. If request’s cache mode is "only-if-cached" and request’s mode is
+ // not "same-origin", then throw a TypeError.
+ if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {
+ throw new TypeError(
+ "'only-if-cached' can be set only with 'same-origin' mode"
+ )
+ }
-module.exports = {
- kEnumerableProperty,
- nop,
- isDisturbed,
- isErrored,
- isReadable,
- toUSVString,
- isUSVString,
- isBlobLike,
- parseOrigin,
- parseURL,
- getServerName,
- isStream,
- isIterable,
- isAsyncIterable,
- isDestroyed,
- headerNameToString,
- bufferToLowerCasedHeaderName,
- addListener,
- removeAllListeners,
- errorRequest,
- parseRawHeaders,
- parseHeaders,
- parseKeepAliveTimeout,
- destroy,
- bodyLength,
- deepClone,
- ReadableStreamFrom,
- isBuffer,
- validateHandler,
- getSocketInfo,
- isFormDataLike,
- buildURL,
- addAbortListener,
- isValidHTTPToken,
- isValidHeaderValue,
- isTokenCharCode,
- parseRangeHeader,
- normalizedMethodRecordsBase,
- normalizedMethodRecords,
- isValidPort,
- isHttpOrHttpsPrefixed,
- nodeMajor,
- nodeMinor,
- safeHTTPMethods: ['GET', 'HEAD', 'OPTIONS', 'TRACE'],
- wrapRequestBody
-}
+ // 22. If init["redirect"] exists, then set request’s redirect mode to it.
+ if (init.redirect !== undefined) {
+ request.redirect = init.redirect
+ }
+ // 23. If init["integrity"] exists, then set request’s integrity metadata to it.
+ if (init.integrity != null) {
+ request.integrity = String(init.integrity)
+ }
-/***/ }),
+ // 24. If init["keepalive"] exists, then set request’s keepalive to it.
+ if (init.keepalive !== undefined) {
+ request.keepalive = Boolean(init.keepalive)
+ }
-/***/ 6261:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 25. If init["method"] exists, then:
+ if (init.method !== undefined) {
+ // 1. Let method be init["method"].
+ let method = init.method
+ const mayBeNormalized = normalizedMethodRecords[method]
+ if (mayBeNormalized !== undefined) {
+ // Note: Bypass validation DELETE, GET, HEAD, OPTIONS, POST, PUT, PATCH and these lowercase ones
+ request.method = mayBeNormalized
+ } else {
+ // 2. If method is not a method or method is a forbidden method, then
+ // throw a TypeError.
+ if (!isValidHTTPToken(method)) {
+ throw new TypeError(`'${method}' is not a valid HTTP method.`)
+ }
-const { InvalidArgumentError } = __nccwpck_require__(8091)
-const { kClients, kRunning, kClose, kDestroy, kDispatch, kInterceptors } = __nccwpck_require__(9411)
-const DispatcherBase = __nccwpck_require__(4745)
-const Pool = __nccwpck_require__(7404)
-const Client = __nccwpck_require__(3069)
-const util = __nccwpck_require__(1544)
-const createRedirectInterceptor = __nccwpck_require__(1676)
+ const upperCase = method.toUpperCase()
-const kOnConnect = Symbol('onConnect')
-const kOnDisconnect = Symbol('onDisconnect')
-const kOnConnectionError = Symbol('onConnectionError')
-const kMaxRedirections = Symbol('maxRedirections')
-const kOnDrain = Symbol('onDrain')
-const kFactory = Symbol('factory')
-const kOptions = Symbol('options')
+ if (forbiddenMethodsSet.has(upperCase)) {
+ throw new TypeError(`'${method}' HTTP method is unsupported.`)
+ }
-function defaultFactory (origin, opts) {
- return opts && opts.connections === 1
- ? new Client(origin, opts)
- : new Pool(origin, opts)
-}
+ // 3. Normalize method.
+ // https://fetch.spec.whatwg.org/#concept-method-normalize
+ // Note: must be in uppercase
+ method = normalizedMethodRecordsBase[upperCase] ?? method
-class Agent extends DispatcherBase {
- constructor ({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) {
- super()
+ // 4. Set request’s method to method.
+ request.method = method
+ }
- if (typeof factory !== 'function') {
- throw new InvalidArgumentError('factory must be a function.')
- }
+ if (!patchMethodWarning && request.method === 'patch') {
+ process.emitWarning('Using `patch` is highly likely to result in a `405 Method Not Allowed`. `PATCH` is much more likely to succeed.', {
+ code: 'UNDICI-FETCH-patch'
+ })
- if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {
- throw new InvalidArgumentError('connect must be a function or an object')
+ patchMethodWarning = true
+ }
}
- if (!Number.isInteger(maxRedirections) || maxRedirections < 0) {
- throw new InvalidArgumentError('maxRedirections must be a positive number')
+ // 26. If init["signal"] exists, then set signal to it.
+ if (init.signal !== undefined) {
+ signal = init.signal
}
- if (connect && typeof connect !== 'function') {
- connect = { ...connect }
- }
+ // 27. Set this’s request to request.
+ this[kState] = request
- this[kInterceptors] = options.interceptors?.Agent && Array.isArray(options.interceptors.Agent)
- ? options.interceptors.Agent
- : [createRedirectInterceptor({ maxRedirections })]
+ // 28. Set this’s signal to a new AbortSignal object with this’s relevant
+ // Realm.
+ // TODO: could this be simplified with AbortSignal.any
+ // (https://dom.spec.whatwg.org/#dom-abortsignal-any)
+ const ac = new AbortController()
+ this[kSignal] = ac.signal
- this[kOptions] = { ...util.deepClone(options), connect }
- this[kOptions].interceptors = options.interceptors
- ? { ...options.interceptors }
- : undefined
- this[kMaxRedirections] = maxRedirections
- this[kFactory] = factory
- this[kClients] = new Map()
+ // 29. If signal is not null, then make this’s signal follow signal.
+ if (signal != null) {
+ if (
+ !signal ||
+ typeof signal.aborted !== 'boolean' ||
+ typeof signal.addEventListener !== 'function'
+ ) {
+ throw new TypeError(
+ "Failed to construct 'Request': member signal is not of type AbortSignal."
+ )
+ }
- this[kOnDrain] = (origin, targets) => {
- this.emit('drain', origin, [this, ...targets])
- }
+ if (signal.aborted) {
+ ac.abort(signal.reason)
+ } else {
+ // Keep a strong ref to ac while request object
+ // is alive. This is needed to prevent AbortController
+ // from being prematurely garbage collected.
+ // See, https://github.com/nodejs/undici/issues/1926.
+ this[kAbortController] = ac
- this[kOnConnect] = (origin, targets) => {
- this.emit('connect', origin, [this, ...targets])
- }
+ const acRef = new WeakRef(ac)
+ const abort = buildAbort(acRef)
- this[kOnDisconnect] = (origin, targets, err) => {
- this.emit('disconnect', origin, [this, ...targets], err)
- }
+ // Third-party AbortControllers may not work with these.
+ // See, https://github.com/nodejs/undici/pull/1910#issuecomment-1464495619.
+ try {
+ // If the max amount of listeners is equal to the default, increase it
+ // This is only available in node >= v19.9.0
+ if (typeof getMaxListeners === 'function' && getMaxListeners(signal) === defaultMaxListeners) {
+ setMaxListeners(1500, signal)
+ } else if (getEventListeners(signal, 'abort').length >= defaultMaxListeners) {
+ setMaxListeners(1500, signal)
+ }
+ } catch {}
- this[kOnConnectionError] = (origin, targets, err) => {
- this.emit('connectionError', origin, [this, ...targets], err)
+ util.addAbortListener(signal, abort)
+ // The third argument must be a registry key to be unregistered.
+ // Without it, you cannot unregister.
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry
+ // abort is used as the unregister key. (because it is unique)
+ requestFinalizer.register(ac, { signal, abort }, abort)
+ }
}
- }
- get [kRunning] () {
- let ret = 0
- for (const client of this[kClients].values()) {
- ret += client[kRunning]
- }
- return ret
- }
+ // 30. Set this’s headers to a new Headers object with this’s relevant
+ // Realm, whose header list is request’s header list and guard is
+ // "request".
+ this[kHeaders] = new Headers(kConstruct)
+ setHeadersList(this[kHeaders], request.headersList)
+ setHeadersGuard(this[kHeaders], 'request')
- [kDispatch] (opts, handler) {
- let key
- if (opts.origin && (typeof opts.origin === 'string' || opts.origin instanceof URL)) {
- key = String(opts.origin)
- } else {
- throw new InvalidArgumentError('opts.origin must be a non-empty string or URL.')
+ // 31. If this’s request’s mode is "no-cors", then:
+ if (mode === 'no-cors') {
+ // 1. If this’s request’s method is not a CORS-safelisted method,
+ // then throw a TypeError.
+ if (!corsSafeListedMethodsSet.has(request.method)) {
+ throw new TypeError(
+ `'${request.method} is unsupported in no-cors mode.`
+ )
+ }
+
+ // 2. Set this’s headers’s guard to "request-no-cors".
+ setHeadersGuard(this[kHeaders], 'request-no-cors')
}
- let dispatcher = this[kClients].get(key)
+ // 32. If init is not empty, then:
+ if (initHasKey) {
+ /** @type {HeadersList} */
+ const headersList = getHeadersList(this[kHeaders])
+ // 1. Let headers be a copy of this’s headers and its associated header
+ // list.
+ // 2. If init["headers"] exists, then set headers to init["headers"].
+ const headers = init.headers !== undefined ? init.headers : new HeadersList(headersList)
- if (!dispatcher) {
- dispatcher = this[kFactory](opts.origin, this[kOptions])
- .on('drain', this[kOnDrain])
- .on('connect', this[kOnConnect])
- .on('disconnect', this[kOnDisconnect])
- .on('connectionError', this[kOnConnectionError])
+ // 3. Empty this’s headers’s header list.
+ headersList.clear()
- // This introduces a tiny memory leak, as dispatchers are never removed from the map.
- // TODO(mcollina): remove te timer when the client/pool do not have any more
- // active connections.
- this[kClients].set(key, dispatcher)
+ // 4. If headers is a Headers object, then for each header in its header
+ // list, append header’s name/header’s value to this’s headers.
+ if (headers instanceof HeadersList) {
+ for (const { name, value } of headers.rawValues()) {
+ headersList.append(name, value, false)
+ }
+ // Note: Copy the `set-cookie` meta-data.
+ headersList.cookies = headers.cookies
+ } else {
+ // 5. Otherwise, fill this’s headers with headers.
+ fillHeaders(this[kHeaders], headers)
+ }
}
- return dispatcher.dispatch(opts, handler)
- }
+ // 33. Let inputBody be input’s request’s body if input is a Request
+ // object; otherwise null.
+ const inputBody = input instanceof Request ? input[kState].body : null
- async [kClose] () {
- const closePromises = []
- for (const client of this[kClients].values()) {
- closePromises.push(client.close())
+ // 34. If either init["body"] exists and is non-null or inputBody is
+ // non-null, and request’s method is `GET` or `HEAD`, then throw a
+ // TypeError.
+ if (
+ (init.body != null || inputBody != null) &&
+ (request.method === 'GET' || request.method === 'HEAD')
+ ) {
+ throw new TypeError('Request with GET/HEAD method cannot have body.')
}
- this[kClients].clear()
-
- await Promise.all(closePromises)
- }
- async [kDestroy] (err) {
- const destroyPromises = []
- for (const client of this[kClients].values()) {
- destroyPromises.push(client.destroy(err))
- }
- this[kClients].clear()
+ // 35. Let initBody be null.
+ let initBody = null
- await Promise.all(destroyPromises)
- }
-}
-
-module.exports = Agent
+ // 36. If init["body"] exists and is non-null, then:
+ if (init.body != null) {
+ // 1. Let Content-Type be null.
+ // 2. Set initBody and Content-Type to the result of extracting
+ // init["body"], with keepalive set to request’s keepalive.
+ const [extractedBody, contentType] = extractBody(
+ init.body,
+ request.keepalive
+ )
+ initBody = extractedBody
+ // 3, If Content-Type is non-null and this’s headers’s header list does
+ // not contain `Content-Type`, then append `Content-Type`/Content-Type to
+ // this’s headers.
+ if (contentType && !getHeadersList(this[kHeaders]).contains('content-type', true)) {
+ this[kHeaders].append('content-type', contentType)
+ }
+ }
-/***/ }),
+ // 37. Let inputOrInitBody be initBody if it is non-null; otherwise
+ // inputBody.
+ const inputOrInitBody = initBody ?? inputBody
-/***/ 8973:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 38. If inputOrInitBody is non-null and inputOrInitBody’s source is
+ // null, then:
+ if (inputOrInitBody != null && inputOrInitBody.source == null) {
+ // 1. If initBody is non-null and init["duplex"] does not exist,
+ // then throw a TypeError.
+ if (initBody != null && init.duplex == null) {
+ throw new TypeError('RequestInit: duplex option is required when sending a body.')
+ }
+ // 2. If this’s request’s mode is neither "same-origin" nor "cors",
+ // then throw a TypeError.
+ if (request.mode !== 'same-origin' && request.mode !== 'cors') {
+ throw new TypeError(
+ 'If request is made from ReadableStream, mode should be "same-origin" or "cors"'
+ )
+ }
+ // 3. Set this’s request’s use-CORS-preflight flag.
+ request.useCORSPreflightFlag = true
+ }
-const {
- BalancedPoolMissingUpstreamError,
- InvalidArgumentError
-} = __nccwpck_require__(8091)
-const {
- PoolBase,
- kClients,
- kNeedDrain,
- kAddClient,
- kRemoveClient,
- kGetDispatcher
-} = __nccwpck_require__(3272)
-const Pool = __nccwpck_require__(7404)
-const { kUrl, kInterceptors } = __nccwpck_require__(9411)
-const { parseOrigin } = __nccwpck_require__(1544)
-const kFactory = Symbol('factory')
+ // 39. Let finalBody be inputOrInitBody.
+ let finalBody = inputOrInitBody
-const kOptions = Symbol('options')
-const kGreatestCommonDivisor = Symbol('kGreatestCommonDivisor')
-const kCurrentWeight = Symbol('kCurrentWeight')
-const kIndex = Symbol('kIndex')
-const kWeight = Symbol('kWeight')
-const kMaxWeightPerServer = Symbol('kMaxWeightPerServer')
-const kErrorPenalty = Symbol('kErrorPenalty')
+ // 40. If initBody is null and inputBody is non-null, then:
+ if (initBody == null && inputBody != null) {
+ // 1. If input is unusable, then throw a TypeError.
+ if (bodyUnusable(input)) {
+ throw new TypeError(
+ 'Cannot construct a Request with a Request object that has already been used.'
+ )
+ }
-/**
- * Calculate the greatest common divisor of two numbers by
- * using the Euclidean algorithm.
- *
- * @param {number} a
- * @param {number} b
- * @returns {number}
- */
-function getGreatestCommonDivisor (a, b) {
- if (a === 0) return b
+ // 2. Set finalBody to the result of creating a proxy for inputBody.
+ // https://streams.spec.whatwg.org/#readablestream-create-a-proxy
+ const identityTransform = new TransformStream()
+ inputBody.stream.pipeThrough(identityTransform)
+ finalBody = {
+ source: inputBody.source,
+ length: inputBody.length,
+ stream: identityTransform.readable
+ }
+ }
- while (b !== 0) {
- const t = b
- b = a % b
- a = t
+ // 41. Set this’s request’s body to finalBody.
+ this[kState].body = finalBody
}
- return a
-}
-function defaultFactory (origin, opts) {
- return new Pool(origin, opts)
-}
+ // Returns request’s HTTP method, which is "GET" by default.
+ get method () {
+ webidl.brandCheck(this, Request)
-class BalancedPool extends PoolBase {
- constructor (upstreams = [], { factory = defaultFactory, ...opts } = {}) {
- super()
+ // The method getter steps are to return this’s request’s method.
+ return this[kState].method
+ }
- this[kOptions] = opts
- this[kIndex] = -1
- this[kCurrentWeight] = 0
+ // Returns the URL of request as a string.
+ get url () {
+ webidl.brandCheck(this, Request)
- this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100
- this[kErrorPenalty] = this[kOptions].errorPenalty || 15
+ // The url getter steps are to return this’s request’s URL, serialized.
+ return URLSerializer(this[kState].url)
+ }
- if (!Array.isArray(upstreams)) {
- upstreams = [upstreams]
- }
+ // Returns a Headers object consisting of the headers associated with request.
+ // Note that headers added in the network layer by the user agent will not
+ // be accounted for in this object, e.g., the "Host" header.
+ get headers () {
+ webidl.brandCheck(this, Request)
- if (typeof factory !== 'function') {
- throw new InvalidArgumentError('factory must be a function.')
- }
+ // The headers getter steps are to return this’s headers.
+ return this[kHeaders]
+ }
- this[kInterceptors] = opts.interceptors?.BalancedPool && Array.isArray(opts.interceptors.BalancedPool)
- ? opts.interceptors.BalancedPool
- : []
- this[kFactory] = factory
+ // Returns the kind of resource requested by request, e.g., "document"
+ // or "script".
+ get destination () {
+ webidl.brandCheck(this, Request)
- for (const upstream of upstreams) {
- this.addUpstream(upstream)
- }
- this._updateBalancedPoolStats()
+ // The destination getter are to return this’s request’s destination.
+ return this[kState].destination
}
- addUpstream (upstream) {
- const upstreamOrigin = parseOrigin(upstream).origin
+ // Returns the referrer of request. Its value can be a same-origin URL if
+ // explicitly set in init, the empty string to indicate no referrer, and
+ // "about:client" when defaulting to the global’s default. This is used
+ // during fetching to determine the value of the `Referer` header of the
+ // request being made.
+ get referrer () {
+ webidl.brandCheck(this, Request)
- if (this[kClients].find((pool) => (
- pool[kUrl].origin === upstreamOrigin &&
- pool.closed !== true &&
- pool.destroyed !== true
- ))) {
- return this
+ // 1. If this’s request’s referrer is "no-referrer", then return the
+ // empty string.
+ if (this[kState].referrer === 'no-referrer') {
+ return ''
}
- const pool = this[kFactory](upstreamOrigin, Object.assign({}, this[kOptions]))
-
- this[kAddClient](pool)
- pool.on('connect', () => {
- pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty])
- })
-
- pool.on('connectionError', () => {
- pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty])
- this._updateBalancedPoolStats()
- })
-
- pool.on('disconnect', (...args) => {
- const err = args[2]
- if (err && err.code === 'UND_ERR_SOCKET') {
- // decrease the weight of the pool.
- pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty])
- this._updateBalancedPoolStats()
- }
- })
- for (const client of this[kClients]) {
- client[kWeight] = this[kMaxWeightPerServer]
+ // 2. If this’s request’s referrer is "client", then return
+ // "about:client".
+ if (this[kState].referrer === 'client') {
+ return 'about:client'
}
- this._updateBalancedPoolStats()
-
- return this
+ // Return this’s request’s referrer, serialized.
+ return this[kState].referrer.toString()
}
- _updateBalancedPoolStats () {
- let result = 0
- for (let i = 0; i < this[kClients].length; i++) {
- result = getGreatestCommonDivisor(this[kClients][i][kWeight], result)
- }
+ // Returns the referrer policy associated with request.
+ // This is used during fetching to compute the value of the request’s
+ // referrer.
+ get referrerPolicy () {
+ webidl.brandCheck(this, Request)
- this[kGreatestCommonDivisor] = result
+ // The referrerPolicy getter steps are to return this’s request’s referrer policy.
+ return this[kState].referrerPolicy
}
- removeUpstream (upstream) {
- const upstreamOrigin = parseOrigin(upstream).origin
-
- const pool = this[kClients].find((pool) => (
- pool[kUrl].origin === upstreamOrigin &&
- pool.closed !== true &&
- pool.destroyed !== true
- ))
-
- if (pool) {
- this[kRemoveClient](pool)
- }
+ // Returns the mode associated with request, which is a string indicating
+ // whether the request will use CORS, or will be restricted to same-origin
+ // URLs.
+ get mode () {
+ webidl.brandCheck(this, Request)
- return this
+ // The mode getter steps are to return this’s request’s mode.
+ return this[kState].mode
}
- get upstreams () {
- return this[kClients]
- .filter(dispatcher => dispatcher.closed !== true && dispatcher.destroyed !== true)
- .map((p) => p[kUrl].origin)
+ // Returns the credentials mode associated with request,
+ // which is a string indicating whether credentials will be sent with the
+ // request always, never, or only when sent to a same-origin URL.
+ get credentials () {
+ // The credentials getter steps are to return this’s request’s credentials mode.
+ return this[kState].credentials
}
- [kGetDispatcher] () {
- // We validate that pools is greater than 0,
- // otherwise we would have to wait until an upstream
- // is added, which might never happen.
- if (this[kClients].length === 0) {
- throw new BalancedPoolMissingUpstreamError()
- }
+ // Returns the cache mode associated with request,
+ // which is a string indicating how the request will
+ // interact with the browser’s cache when fetching.
+ get cache () {
+ webidl.brandCheck(this, Request)
- const dispatcher = this[kClients].find(dispatcher => (
- !dispatcher[kNeedDrain] &&
- dispatcher.closed !== true &&
- dispatcher.destroyed !== true
- ))
+ // The cache getter steps are to return this’s request’s cache mode.
+ return this[kState].cache
+ }
- if (!dispatcher) {
- return
- }
+ // Returns the redirect mode associated with request,
+ // which is a string indicating how redirects for the
+ // request will be handled during fetching. A request
+ // will follow redirects by default.
+ get redirect () {
+ webidl.brandCheck(this, Request)
- const allClientsBusy = this[kClients].map(pool => pool[kNeedDrain]).reduce((a, b) => a && b, true)
+ // The redirect getter steps are to return this’s request’s redirect mode.
+ return this[kState].redirect
+ }
- if (allClientsBusy) {
- return
- }
+ // Returns request’s subresource integrity metadata, which is a
+ // cryptographic hash of the resource being fetched. Its value
+ // consists of multiple hashes separated by whitespace. [SRI]
+ get integrity () {
+ webidl.brandCheck(this, Request)
- let counter = 0
+ // The integrity getter steps are to return this’s request’s integrity
+ // metadata.
+ return this[kState].integrity
+ }
- let maxWeightIndex = this[kClients].findIndex(pool => !pool[kNeedDrain])
+ // Returns a boolean indicating whether or not request can outlive the
+ // global in which it was created.
+ get keepalive () {
+ webidl.brandCheck(this, Request)
- while (counter++ < this[kClients].length) {
- this[kIndex] = (this[kIndex] + 1) % this[kClients].length
- const pool = this[kClients][this[kIndex]]
+ // The keepalive getter steps are to return this’s request’s keepalive.
+ return this[kState].keepalive
+ }
- // find pool index with the largest weight
- if (pool[kWeight] > this[kClients][maxWeightIndex][kWeight] && !pool[kNeedDrain]) {
- maxWeightIndex = this[kIndex]
- }
+ // Returns a boolean indicating whether or not request is for a reload
+ // navigation.
+ get isReloadNavigation () {
+ webidl.brandCheck(this, Request)
- // decrease the current weight every `this[kClients].length`.
- if (this[kIndex] === 0) {
- // Set the current weight to the next lower weight.
- this[kCurrentWeight] = this[kCurrentWeight] - this[kGreatestCommonDivisor]
+ // The isReloadNavigation getter steps are to return true if this’s
+ // request’s reload-navigation flag is set; otherwise false.
+ return this[kState].reloadNavigation
+ }
- if (this[kCurrentWeight] <= 0) {
- this[kCurrentWeight] = this[kMaxWeightPerServer]
- }
- }
- if (pool[kWeight] >= this[kCurrentWeight] && (!pool[kNeedDrain])) {
- return pool
- }
- }
+ // Returns a boolean indicating whether or not request is for a history
+ // navigation (a.k.a. back-forward navigation).
+ get isHistoryNavigation () {
+ webidl.brandCheck(this, Request)
- this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight]
- this[kIndex] = maxWeightIndex
- return this[kClients][maxWeightIndex]
+ // The isHistoryNavigation getter steps are to return true if this’s request’s
+ // history-navigation flag is set; otherwise false.
+ return this[kState].historyNavigation
}
-}
-module.exports = BalancedPool
+ // Returns the signal associated with request, which is an AbortSignal
+ // object indicating whether or not request has been aborted, and its
+ // abort event handler.
+ get signal () {
+ webidl.brandCheck(this, Request)
+ // The signal getter steps are to return this’s signal.
+ return this[kSignal]
+ }
-/***/ }),
+ get body () {
+ webidl.brandCheck(this, Request)
-/***/ 1557:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ return this[kState].body ? this[kState].body.stream : null
+ }
+ get bodyUsed () {
+ webidl.brandCheck(this, Request)
+ return !!this[kState].body && util.isDisturbed(this[kState].body.stream)
+ }
-/* global WebAssembly */
+ get duplex () {
+ webidl.brandCheck(this, Request)
-const assert = __nccwpck_require__(4589)
-const util = __nccwpck_require__(1544)
-const { channels } = __nccwpck_require__(8150)
-const timers = __nccwpck_require__(2563)
-const {
- RequestContentLengthMismatchError,
- ResponseContentLengthMismatchError,
- RequestAbortedError,
- HeadersTimeoutError,
- HeadersOverflowError,
- SocketError,
- InformationalError,
- BodyTimeoutError,
- HTTPParserError,
- ResponseExceededMaxSizeError
-} = __nccwpck_require__(8091)
-const {
- kUrl,
- kReset,
- kClient,
- kParser,
- kBlocking,
- kRunning,
- kPending,
- kSize,
- kWriting,
- kQueue,
- kNoRef,
- kKeepAliveDefaultTimeout,
- kHostHeader,
- kPendingIdx,
- kRunningIdx,
- kError,
- kPipelining,
- kSocket,
- kKeepAliveTimeoutValue,
- kMaxHeadersSize,
- kKeepAliveMaxTimeout,
- kKeepAliveTimeoutThreshold,
- kHeadersTimeout,
- kBodyTimeout,
- kStrictContentLength,
- kMaxRequests,
- kCounter,
- kMaxResponseSize,
- kOnError,
- kResume,
- kHTTPContext
-} = __nccwpck_require__(9411)
+ return 'half'
+ }
-const constants = __nccwpck_require__(7424)
-const EMPTY_BUF = Buffer.alloc(0)
-const FastBuffer = Buffer[Symbol.species]
-const addListener = util.addListener
-const removeAllListeners = util.removeAllListeners
+ // Returns a clone of request.
+ clone () {
+ webidl.brandCheck(this, Request)
-let extractBody
+ // 1. If this is unusable, then throw a TypeError.
+ if (bodyUnusable(this)) {
+ throw new TypeError('unusable')
+ }
-async function lazyllhttp () {
- const llhttpWasmData = process.env.JEST_WORKER_ID ? __nccwpck_require__(7846) : undefined
+ // 2. Let clonedRequest be the result of cloning this’s request.
+ const clonedRequest = cloneRequest(this[kState])
- let mod
- try {
- mod = await WebAssembly.compile(__nccwpck_require__(9474))
- } catch (e) {
- /* istanbul ignore next */
+ // 3. Let clonedRequestObject be the result of creating a Request object,
+ // given clonedRequest, this’s headers’s guard, and this’s relevant Realm.
+ // 4. Make clonedRequestObject’s signal follow this’s signal.
+ const ac = new AbortController()
+ if (this.signal.aborted) {
+ ac.abort(this.signal.reason)
+ } else {
+ let list = dependentControllerMap.get(this.signal)
+ if (list === undefined) {
+ list = new Set()
+ dependentControllerMap.set(this.signal, list)
+ }
+ const acRef = new WeakRef(ac)
+ list.add(acRef)
+ util.addAbortListener(
+ ac.signal,
+ buildAbort(acRef)
+ )
+ }
- // We could check if the error was caused by the simd option not
- // being enabled, but the occurring of this other error
- // * https://github.com/emscripten-core/emscripten/issues/11495
- // got me to remove that check to avoid breaking Node 12.
- mod = await WebAssembly.compile(llhttpWasmData || __nccwpck_require__(7846))
+ // 4. Return clonedRequestObject.
+ return fromInnerRequest(clonedRequest, ac.signal, getHeadersGuard(this[kHeaders]))
}
- return await WebAssembly.instantiate(mod, {
- env: {
- /* eslint-disable camelcase */
+ [nodeUtil.inspect.custom] (depth, options) {
+ if (options.depth === null) {
+ options.depth = 2
+ }
- wasm_on_url: (p, at, len) => {
- /* istanbul ignore next */
- return 0
- },
- wasm_on_status: (p, at, len) => {
- assert(currentParser.ptr === p)
- const start = at - currentBufferPtr + currentBufferRef.byteOffset
- return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
- },
- wasm_on_message_begin: (p) => {
- assert(currentParser.ptr === p)
- return currentParser.onMessageBegin() || 0
- },
- wasm_on_header_field: (p, at, len) => {
- assert(currentParser.ptr === p)
- const start = at - currentBufferPtr + currentBufferRef.byteOffset
- return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
- },
- wasm_on_header_value: (p, at, len) => {
- assert(currentParser.ptr === p)
- const start = at - currentBufferPtr + currentBufferRef.byteOffset
- return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
- },
- wasm_on_headers_complete: (p, statusCode, upgrade, shouldKeepAlive) => {
- assert(currentParser.ptr === p)
- return currentParser.onHeadersComplete(statusCode, Boolean(upgrade), Boolean(shouldKeepAlive)) || 0
- },
- wasm_on_body: (p, at, len) => {
- assert(currentParser.ptr === p)
- const start = at - currentBufferPtr + currentBufferRef.byteOffset
- return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
- },
- wasm_on_message_complete: (p) => {
- assert(currentParser.ptr === p)
- return currentParser.onMessageComplete() || 0
- }
+ options.colors ??= true
- /* eslint-enable camelcase */
+ const properties = {
+ method: this.method,
+ url: this.url,
+ headers: this.headers,
+ destination: this.destination,
+ referrer: this.referrer,
+ referrerPolicy: this.referrerPolicy,
+ mode: this.mode,
+ credentials: this.credentials,
+ cache: this.cache,
+ redirect: this.redirect,
+ integrity: this.integrity,
+ keepalive: this.keepalive,
+ isReloadNavigation: this.isReloadNavigation,
+ isHistoryNavigation: this.isHistoryNavigation,
+ signal: this.signal
}
- })
-}
-
-let llhttpInstance = null
-let llhttpPromise = lazyllhttp()
-llhttpPromise.catch()
-let currentParser = null
-let currentBufferRef = null
-let currentBufferSize = 0
-let currentBufferPtr = null
+ return `Request ${nodeUtil.formatWithOptions(options, properties)}`
+ }
+}
-const USE_NATIVE_TIMER = 0
-const USE_FAST_TIMER = 1
+mixinBody(Request)
-// Use fast timers for headers and body to take eventual event loop
-// latency into account.
-const TIMEOUT_HEADERS = 2 | USE_FAST_TIMER
-const TIMEOUT_BODY = 4 | USE_FAST_TIMER
-
-// Use native timers to ignore event loop latency for keep-alive
-// handling.
-const TIMEOUT_KEEP_ALIVE = 8 | USE_NATIVE_TIMER
-
-class Parser {
- constructor (client, socket, { exports }) {
- assert(Number.isFinite(client[kMaxHeadersSize]) && client[kMaxHeadersSize] > 0)
-
- this.llhttp = exports
- this.ptr = this.llhttp.llhttp_alloc(constants.TYPE.RESPONSE)
- this.client = client
- this.socket = socket
- this.timeout = null
- this.timeoutValue = null
- this.timeoutType = null
- this.statusCode = null
- this.statusText = ''
- this.upgrade = false
- this.headers = []
- this.headersSize = 0
- this.headersMaxSize = client[kMaxHeadersSize]
- this.shouldKeepAlive = false
- this.paused = false
- this.resume = this.resume.bind(this)
-
- this.bytesRead = 0
-
- this.keepAlive = ''
- this.contentLength = ''
- this.connection = ''
- this.maxResponseSize = client[kMaxResponseSize]
+// https://fetch.spec.whatwg.org/#requests
+function makeRequest (init) {
+ return {
+ method: init.method ?? 'GET',
+ localURLsOnly: init.localURLsOnly ?? false,
+ unsafeRequest: init.unsafeRequest ?? false,
+ body: init.body ?? null,
+ client: init.client ?? null,
+ reservedClient: init.reservedClient ?? null,
+ replacesClientId: init.replacesClientId ?? '',
+ window: init.window ?? 'client',
+ keepalive: init.keepalive ?? false,
+ serviceWorkers: init.serviceWorkers ?? 'all',
+ initiator: init.initiator ?? '',
+ destination: init.destination ?? '',
+ priority: init.priority ?? null,
+ origin: init.origin ?? 'client',
+ policyContainer: init.policyContainer ?? 'client',
+ referrer: init.referrer ?? 'client',
+ referrerPolicy: init.referrerPolicy ?? '',
+ mode: init.mode ?? 'no-cors',
+ useCORSPreflightFlag: init.useCORSPreflightFlag ?? false,
+ credentials: init.credentials ?? 'same-origin',
+ useCredentials: init.useCredentials ?? false,
+ cache: init.cache ?? 'default',
+ redirect: init.redirect ?? 'follow',
+ integrity: init.integrity ?? '',
+ cryptoGraphicsNonceMetadata: init.cryptoGraphicsNonceMetadata ?? '',
+ parserMetadata: init.parserMetadata ?? '',
+ reloadNavigation: init.reloadNavigation ?? false,
+ historyNavigation: init.historyNavigation ?? false,
+ userActivation: init.userActivation ?? false,
+ taintedOrigin: init.taintedOrigin ?? false,
+ redirectCount: init.redirectCount ?? 0,
+ responseTainting: init.responseTainting ?? 'basic',
+ preventNoCacheCacheControlHeaderModification: init.preventNoCacheCacheControlHeaderModification ?? false,
+ done: init.done ?? false,
+ timingAllowFailed: init.timingAllowFailed ?? false,
+ urlList: init.urlList,
+ url: init.urlList[0],
+ headersList: init.headersList
+ ? new HeadersList(init.headersList)
+ : new HeadersList()
}
+}
- setTimeout (delay, type) {
- // If the existing timer and the new timer are of different timer type
- // (fast or native) or have different delay, we need to clear the existing
- // timer and set a new one.
- if (
- delay !== this.timeoutValue ||
- (type & USE_FAST_TIMER) ^ (this.timeoutType & USE_FAST_TIMER)
- ) {
- // If a timeout is already set, clear it with clearTimeout of the fast
- // timer implementation, as it can clear fast and native timers.
- if (this.timeout) {
- timers.clearTimeout(this.timeout)
- this.timeout = null
- }
-
- if (delay) {
- if (type & USE_FAST_TIMER) {
- this.timeout = timers.setFastTimeout(onParserTimeout, delay, new WeakRef(this))
- } else {
- this.timeout = setTimeout(onParserTimeout, delay, new WeakRef(this))
- this.timeout.unref()
- }
- }
+// https://fetch.spec.whatwg.org/#concept-request-clone
+function cloneRequest (request) {
+ // To clone a request request, run these steps:
- this.timeoutValue = delay
- } else if (this.timeout) {
- // istanbul ignore else: only for jest
- if (this.timeout.refresh) {
- this.timeout.refresh()
- }
- }
+ // 1. Let newRequest be a copy of request, except for its body.
+ const newRequest = makeRequest({ ...request, body: null })
- this.timeoutType = type
+ // 2. If request’s body is non-null, set newRequest’s body to the
+ // result of cloning request’s body.
+ if (request.body != null) {
+ newRequest.body = cloneBody(newRequest, request.body)
}
- resume () {
- if (this.socket.destroyed || !this.paused) {
- return
- }
+ // 3. Return newRequest.
+ return newRequest
+}
- assert(this.ptr != null)
- assert(currentParser == null)
+/**
+ * @see https://fetch.spec.whatwg.org/#request-create
+ * @param {any} innerRequest
+ * @param {AbortSignal} signal
+ * @param {'request' | 'immutable' | 'request-no-cors' | 'response' | 'none'} guard
+ * @returns {Request}
+ */
+function fromInnerRequest (innerRequest, signal, guard) {
+ const request = new Request(kConstruct)
+ request[kState] = innerRequest
+ request[kSignal] = signal
+ request[kHeaders] = new Headers(kConstruct)
+ setHeadersList(request[kHeaders], innerRequest.headersList)
+ setHeadersGuard(request[kHeaders], guard)
+ return request
+}
- this.llhttp.llhttp_resume(this.ptr)
+Object.defineProperties(Request.prototype, {
+ method: kEnumerableProperty,
+ url: kEnumerableProperty,
+ headers: kEnumerableProperty,
+ redirect: kEnumerableProperty,
+ clone: kEnumerableProperty,
+ signal: kEnumerableProperty,
+ duplex: kEnumerableProperty,
+ destination: kEnumerableProperty,
+ body: kEnumerableProperty,
+ bodyUsed: kEnumerableProperty,
+ isHistoryNavigation: kEnumerableProperty,
+ isReloadNavigation: kEnumerableProperty,
+ keepalive: kEnumerableProperty,
+ integrity: kEnumerableProperty,
+ cache: kEnumerableProperty,
+ credentials: kEnumerableProperty,
+ attribute: kEnumerableProperty,
+ referrerPolicy: kEnumerableProperty,
+ referrer: kEnumerableProperty,
+ mode: kEnumerableProperty,
+ [Symbol.toStringTag]: {
+ value: 'Request',
+ configurable: true
+ }
+})
- assert(this.timeoutType === TIMEOUT_BODY)
- if (this.timeout) {
- // istanbul ignore else: only for jest
- if (this.timeout.refresh) {
- this.timeout.refresh()
- }
- }
+webidl.converters.Request = webidl.interfaceConverter(
+ Request
+)
- this.paused = false
- this.execute(this.socket.read() || EMPTY_BUF) // Flush parser.
- this.readMore()
+// https://fetch.spec.whatwg.org/#requestinfo
+webidl.converters.RequestInfo = function (V, prefix, argument) {
+ if (typeof V === 'string') {
+ return webidl.converters.USVString(V, prefix, argument)
}
- readMore () {
- while (!this.paused && this.ptr) {
- const chunk = this.socket.read()
- if (chunk === null) {
- break
- }
- this.execute(chunk)
- }
+ if (V instanceof Request) {
+ return webidl.converters.Request(V, prefix, argument)
}
- execute (data) {
- assert(this.ptr != null)
- assert(currentParser == null)
- assert(!this.paused)
+ return webidl.converters.USVString(V, prefix, argument)
+}
- const { socket, llhttp } = this
+webidl.converters.AbortSignal = webidl.interfaceConverter(
+ AbortSignal
+)
- if (data.length > currentBufferSize) {
- if (currentBufferPtr) {
- llhttp.free(currentBufferPtr)
- }
- currentBufferSize = Math.ceil(data.length / 4096) * 4096
- currentBufferPtr = llhttp.malloc(currentBufferSize)
- }
+// https://fetch.spec.whatwg.org/#requestinit
+webidl.converters.RequestInit = webidl.dictionaryConverter([
+ {
+ key: 'method',
+ converter: webidl.converters.ByteString
+ },
+ {
+ key: 'headers',
+ converter: webidl.converters.HeadersInit
+ },
+ {
+ key: 'body',
+ converter: webidl.nullableConverter(
+ webidl.converters.BodyInit
+ )
+ },
+ {
+ key: 'referrer',
+ converter: webidl.converters.USVString
+ },
+ {
+ key: 'referrerPolicy',
+ converter: webidl.converters.DOMString,
+ // https://w3c.github.io/webappsec-referrer-policy/#referrer-policy
+ allowedValues: referrerPolicy
+ },
+ {
+ key: 'mode',
+ converter: webidl.converters.DOMString,
+ // https://fetch.spec.whatwg.org/#concept-request-mode
+ allowedValues: requestMode
+ },
+ {
+ key: 'credentials',
+ converter: webidl.converters.DOMString,
+ // https://fetch.spec.whatwg.org/#requestcredentials
+ allowedValues: requestCredentials
+ },
+ {
+ key: 'cache',
+ converter: webidl.converters.DOMString,
+ // https://fetch.spec.whatwg.org/#requestcache
+ allowedValues: requestCache
+ },
+ {
+ key: 'redirect',
+ converter: webidl.converters.DOMString,
+ // https://fetch.spec.whatwg.org/#requestredirect
+ allowedValues: requestRedirect
+ },
+ {
+ key: 'integrity',
+ converter: webidl.converters.DOMString
+ },
+ {
+ key: 'keepalive',
+ converter: webidl.converters.boolean
+ },
+ {
+ key: 'signal',
+ converter: webidl.nullableConverter(
+ (signal) => webidl.converters.AbortSignal(
+ signal,
+ 'RequestInit',
+ 'signal',
+ { strict: false }
+ )
+ )
+ },
+ {
+ key: 'window',
+ converter: webidl.converters.any
+ },
+ {
+ key: 'duplex',
+ converter: webidl.converters.DOMString,
+ allowedValues: requestDuplex
+ },
+ {
+ key: 'dispatcher', // undici specific option
+ converter: webidl.converters.any
+ }
+])
- new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(data)
+module.exports = { Request, makeRequest, fromInnerRequest, cloneRequest }
- // Call `execute` on the wasm parser.
- // We pass the `llhttp_parser` pointer address, the pointer address of buffer view data,
- // and finally the length of bytes to parse.
- // The return value is an error code or `constants.ERROR.OK`.
- try {
- let ret
- try {
- currentBufferRef = data
- currentParser = this
- ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, data.length)
- /* eslint-disable-next-line no-useless-catch */
- } catch (err) {
- /* istanbul ignore next: difficult to make a test case for */
- throw err
- } finally {
- currentParser = null
- currentBufferRef = null
- }
+/***/ }),
- const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr
+/***/ 9051:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- if (ret === constants.ERROR.PAUSED_UPGRADE) {
- this.onUpgrade(data.slice(offset))
- } else if (ret === constants.ERROR.PAUSED) {
- this.paused = true
- socket.unshift(data.slice(offset))
- } else if (ret !== constants.ERROR.OK) {
- const ptr = llhttp.llhttp_get_error_reason(this.ptr)
- let message = ''
- /* istanbul ignore else: difficult to make a test case for */
- if (ptr) {
- const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0)
- message =
- 'Response does not match the HTTP/1.1 protocol (' +
- Buffer.from(llhttp.memory.buffer, ptr, len).toString() +
- ')'
- }
- throw new HTTPParserError(message, constants.ERROR[ret], data.slice(offset))
- }
- } catch (err) {
- util.destroy(socket, err)
- }
- }
- destroy () {
- assert(this.ptr != null)
- assert(currentParser == null)
- this.llhttp.llhttp_free(this.ptr)
- this.ptr = null
+const { Headers, HeadersList, fill, getHeadersGuard, setHeadersGuard, setHeadersList } = __nccwpck_require__(660)
+const { extractBody, cloneBody, mixinBody, hasFinalizationRegistry, streamRegistry, bodyUnusable } = __nccwpck_require__(4492)
+const util = __nccwpck_require__(3440)
+const nodeUtil = __nccwpck_require__(7975)
+const { kEnumerableProperty } = util
+const {
+ isValidReasonPhrase,
+ isCancelled,
+ isAborted,
+ isBlobLike,
+ serializeJavascriptValueToJSONString,
+ isErrorLike,
+ isomorphicEncode,
+ environmentSettingsObject: relevantRealm
+} = __nccwpck_require__(3168)
+const {
+ redirectStatusSet,
+ nullBodyStatus
+} = __nccwpck_require__(4495)
+const { kState, kHeaders } = __nccwpck_require__(3627)
+const { webidl } = __nccwpck_require__(5893)
+const { FormData } = __nccwpck_require__(5910)
+const { URLSerializer } = __nccwpck_require__(1900)
+const { kConstruct } = __nccwpck_require__(6443)
+const assert = __nccwpck_require__(4589)
+const { types } = __nccwpck_require__(7975)
- this.timeout && timers.clearTimeout(this.timeout)
- this.timeout = null
- this.timeoutValue = null
- this.timeoutType = null
+const textEncoder = new TextEncoder('utf-8')
- this.paused = false
- }
+// https://fetch.spec.whatwg.org/#response-class
+class Response {
+ // Creates network error Response.
+ static error () {
+ // The static error() method steps are to return the result of creating a
+ // Response object, given a new network error, "immutable", and this’s
+ // relevant Realm.
+ const responseObject = fromInnerResponse(makeNetworkError(), 'immutable')
- onStatus (buf) {
- this.statusText = buf.toString()
+ return responseObject
}
- onMessageBegin () {
- const { socket, client } = this
+ // https://fetch.spec.whatwg.org/#dom-response-json
+ static json (data, init = {}) {
+ webidl.argumentLengthCheck(arguments, 1, 'Response.json')
- /* istanbul ignore next: difficult to make a test case for */
- if (socket.destroyed) {
- return -1
+ if (init !== null) {
+ init = webidl.converters.ResponseInit(init)
}
- const request = client[kQueue][client[kRunningIdx]]
- if (!request) {
- return -1
- }
- request.onResponseStarted()
- }
+ // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data.
+ const bytes = textEncoder.encode(
+ serializeJavascriptValueToJSONString(data)
+ )
- onHeaderField (buf) {
- const len = this.headers.length
+ // 2. Let body be the result of extracting bytes.
+ const body = extractBody(bytes)
- if ((len & 1) === 0) {
- this.headers.push(buf)
- } else {
- this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf])
- }
+ // 3. Let responseObject be the result of creating a Response object, given a new response,
+ // "response", and this’s relevant Realm.
+ const responseObject = fromInnerResponse(makeResponse({}), 'response')
- this.trackHeader(buf.length)
+ // 4. Perform initialize a response given responseObject, init, and (body, "application/json").
+ initializeResponse(responseObject, init, { body: body[0], type: 'application/json' })
+
+ // 5. Return responseObject.
+ return responseObject
}
- onHeaderValue (buf) {
- let len = this.headers.length
+ // Creates a redirect Response that redirects to url with status status.
+ static redirect (url, status = 302) {
+ webidl.argumentLengthCheck(arguments, 1, 'Response.redirect')
- if ((len & 1) === 1) {
- this.headers.push(buf)
- len += 1
- } else {
- this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf])
- }
+ url = webidl.converters.USVString(url)
+ status = webidl.converters['unsigned short'](status)
- const key = this.headers[len - 2]
- if (key.length === 10) {
- const headerName = util.bufferToLowerCasedHeaderName(key)
- if (headerName === 'keep-alive') {
- this.keepAlive += buf.toString()
- } else if (headerName === 'connection') {
- this.connection += buf.toString()
- }
- } else if (key.length === 14 && util.bufferToLowerCasedHeaderName(key) === 'content-length') {
- this.contentLength += buf.toString()
+ // 1. Let parsedURL be the result of parsing url with current settings
+ // object’s API base URL.
+ // 2. If parsedURL is failure, then throw a TypeError.
+ // TODO: base-URL?
+ let parsedURL
+ try {
+ parsedURL = new URL(url, relevantRealm.settingsObject.baseUrl)
+ } catch (err) {
+ throw new TypeError(`Failed to parse URL from ${url}`, { cause: err })
}
- this.trackHeader(buf.length)
- }
-
- trackHeader (len) {
- this.headersSize += len
- if (this.headersSize >= this.headersMaxSize) {
- util.destroy(this.socket, new HeadersOverflowError())
+ // 3. If status is not a redirect status, then throw a RangeError.
+ if (!redirectStatusSet.has(status)) {
+ throw new RangeError(`Invalid status code ${status}`)
}
- }
- onUpgrade (head) {
- const { upgrade, client, socket, headers, statusCode } = this
+ // 4. Let responseObject be the result of creating a Response object,
+ // given a new response, "immutable", and this’s relevant Realm.
+ const responseObject = fromInnerResponse(makeResponse({}), 'immutable')
- assert(upgrade)
- assert(client[kSocket] === socket)
- assert(!socket.destroyed)
- assert(!this.paused)
- assert((headers.length & 1) === 0)
+ // 5. Set responseObject’s response’s status to status.
+ responseObject[kState].status = status
- const request = client[kQueue][client[kRunningIdx]]
- assert(request)
- assert(request.upgrade || request.method === 'CONNECT')
+ // 6. Let value be parsedURL, serialized and isomorphic encoded.
+ const value = isomorphicEncode(URLSerializer(parsedURL))
- this.statusCode = null
- this.statusText = ''
- this.shouldKeepAlive = null
+ // 7. Append `Location`/value to responseObject’s response’s header list.
+ responseObject[kState].headersList.append('location', value, true)
- this.headers = []
- this.headersSize = 0
+ // 8. Return responseObject.
+ return responseObject
+ }
- socket.unshift(head)
+ // https://fetch.spec.whatwg.org/#dom-response
+ constructor (body = null, init = {}) {
+ webidl.util.markAsUncloneable(this)
+ if (body === kConstruct) {
+ return
+ }
- socket[kParser].destroy()
- socket[kParser] = null
+ if (body !== null) {
+ body = webidl.converters.BodyInit(body)
+ }
- socket[kClient] = null
- socket[kError] = null
+ init = webidl.converters.ResponseInit(init)
- removeAllListeners(socket)
+ // 1. Set this’s response to a new response.
+ this[kState] = makeResponse({})
- client[kSocket] = null
- client[kHTTPContext] = null // TODO (fix): This is hacky...
- client[kQueue][client[kRunningIdx]++] = null
- client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade'))
+ // 2. Set this’s headers to a new Headers object with this’s relevant
+ // Realm, whose header list is this’s response’s header list and guard
+ // is "response".
+ this[kHeaders] = new Headers(kConstruct)
+ setHeadersGuard(this[kHeaders], 'response')
+ setHeadersList(this[kHeaders], this[kState].headersList)
- try {
- request.onUpgrade(statusCode, headers, socket)
- } catch (err) {
- util.destroy(socket, err)
+ // 3. Let bodyWithType be null.
+ let bodyWithType = null
+
+ // 4. If body is non-null, then set bodyWithType to the result of extracting body.
+ if (body != null) {
+ const [extractedBody, type] = extractBody(body)
+ bodyWithType = { body: extractedBody, type }
}
- client[kResume]()
+ // 5. Perform initialize a response given this, init, and bodyWithType.
+ initializeResponse(this, init, bodyWithType)
}
- onHeadersComplete (statusCode, upgrade, shouldKeepAlive) {
- const { client, socket, headers, statusText } = this
+ // Returns response’s type, e.g., "cors".
+ get type () {
+ webidl.brandCheck(this, Response)
- /* istanbul ignore next: difficult to make a test case for */
- if (socket.destroyed) {
- return -1
- }
+ // The type getter steps are to return this’s response’s type.
+ return this[kState].type
+ }
- const request = client[kQueue][client[kRunningIdx]]
+ // Returns response’s URL, if it has one; otherwise the empty string.
+ get url () {
+ webidl.brandCheck(this, Response)
- /* istanbul ignore next: difficult to make a test case for */
- if (!request) {
- return -1
- }
+ const urlList = this[kState].urlList
- assert(!this.upgrade)
- assert(this.statusCode < 200)
+ // The url getter steps are to return the empty string if this’s
+ // response’s URL is null; otherwise this’s response’s URL,
+ // serialized with exclude fragment set to true.
+ const url = urlList[urlList.length - 1] ?? null
- if (statusCode === 100) {
- util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket)))
- return -1
+ if (url === null) {
+ return ''
}
- /* this can only happen if server is misbehaving */
- if (upgrade && !request.upgrade) {
- util.destroy(socket, new SocketError('bad upgrade', util.getSocketInfo(socket)))
- return -1
- }
+ return URLSerializer(url, true)
+ }
- assert(this.timeoutType === TIMEOUT_HEADERS)
+ // Returns whether response was obtained through a redirect.
+ get redirected () {
+ webidl.brandCheck(this, Response)
- this.statusCode = statusCode
- this.shouldKeepAlive = (
- shouldKeepAlive ||
- // Override llhttp value which does not allow keepAlive for HEAD.
- (request.method === 'HEAD' && !socket[kReset] && this.connection.toLowerCase() === 'keep-alive')
- )
+ // The redirected getter steps are to return true if this’s response’s URL
+ // list has more than one item; otherwise false.
+ return this[kState].urlList.length > 1
+ }
- if (this.statusCode >= 200) {
- const bodyTimeout = request.bodyTimeout != null
- ? request.bodyTimeout
- : client[kBodyTimeout]
- this.setTimeout(bodyTimeout, TIMEOUT_BODY)
- } else if (this.timeout) {
- // istanbul ignore else: only for jest
- if (this.timeout.refresh) {
- this.timeout.refresh()
- }
- }
+ // Returns response’s status.
+ get status () {
+ webidl.brandCheck(this, Response)
- if (request.method === 'CONNECT') {
- assert(client[kRunning] === 1)
- this.upgrade = true
- return 2
- }
+ // The status getter steps are to return this’s response’s status.
+ return this[kState].status
+ }
- if (upgrade) {
- assert(client[kRunning] === 1)
- this.upgrade = true
- return 2
- }
+ // Returns whether response’s status is an ok status.
+ get ok () {
+ webidl.brandCheck(this, Response)
- assert((this.headers.length & 1) === 0)
- this.headers = []
- this.headersSize = 0
+ // The ok getter steps are to return true if this’s response’s status is an
+ // ok status; otherwise false.
+ return this[kState].status >= 200 && this[kState].status <= 299
+ }
- if (this.shouldKeepAlive && client[kPipelining]) {
- const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null
+ // Returns response’s status message.
+ get statusText () {
+ webidl.brandCheck(this, Response)
- if (keepAliveTimeout != null) {
- const timeout = Math.min(
- keepAliveTimeout - client[kKeepAliveTimeoutThreshold],
- client[kKeepAliveMaxTimeout]
- )
- if (timeout <= 0) {
- socket[kReset] = true
- } else {
- client[kKeepAliveTimeoutValue] = timeout
- }
- } else {
- client[kKeepAliveTimeoutValue] = client[kKeepAliveDefaultTimeout]
- }
- } else {
- // Stop more requests from being dispatched.
- socket[kReset] = true
- }
+ // The statusText getter steps are to return this’s response’s status
+ // message.
+ return this[kState].statusText
+ }
- const pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false
+ // Returns response’s headers as Headers.
+ get headers () {
+ webidl.brandCheck(this, Response)
- if (request.aborted) {
- return -1
- }
+ // The headers getter steps are to return this’s headers.
+ return this[kHeaders]
+ }
- if (request.method === 'HEAD') {
- return 1
- }
+ get body () {
+ webidl.brandCheck(this, Response)
- if (statusCode < 200) {
- return 1
- }
+ return this[kState].body ? this[kState].body.stream : null
+ }
- if (socket[kBlocking]) {
- socket[kBlocking] = false
- client[kResume]()
- }
+ get bodyUsed () {
+ webidl.brandCheck(this, Response)
- return pause ? constants.ERROR.PAUSED : 0
+ return !!this[kState].body && util.isDisturbed(this[kState].body.stream)
}
- onBody (buf) {
- const { client, socket, statusCode, maxResponseSize } = this
+ // Returns a clone of response.
+ clone () {
+ webidl.brandCheck(this, Response)
- if (socket.destroyed) {
- return -1
+ // 1. If this is unusable, then throw a TypeError.
+ if (bodyUnusable(this)) {
+ throw webidl.errors.exception({
+ header: 'Response.clone',
+ message: 'Body has already been consumed.'
+ })
}
- const request = client[kQueue][client[kRunningIdx]]
- assert(request)
+ // 2. Let clonedResponse be the result of cloning this’s response.
+ const clonedResponse = cloneResponse(this[kState])
- assert(this.timeoutType === TIMEOUT_BODY)
- if (this.timeout) {
- // istanbul ignore else: only for jest
- if (this.timeout.refresh) {
- this.timeout.refresh()
- }
+ // Note: To re-register because of a new stream.
+ if (hasFinalizationRegistry && this[kState].body?.stream) {
+ streamRegistry.register(this, new WeakRef(this[kState].body.stream))
}
- assert(statusCode >= 200)
+ // 3. Return the result of creating a Response object, given
+ // clonedResponse, this’s headers’s guard, and this’s relevant Realm.
+ return fromInnerResponse(clonedResponse, getHeadersGuard(this[kHeaders]))
+ }
- if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) {
- util.destroy(socket, new ResponseExceededMaxSizeError())
- return -1
+ [nodeUtil.inspect.custom] (depth, options) {
+ if (options.depth === null) {
+ options.depth = 2
}
- this.bytesRead += buf.length
+ options.colors ??= true
- if (request.onData(buf) === false) {
- return constants.ERROR.PAUSED
+ const properties = {
+ status: this.status,
+ statusText: this.statusText,
+ headers: this.headers,
+ body: this.body,
+ bodyUsed: this.bodyUsed,
+ ok: this.ok,
+ redirected: this.redirected,
+ type: this.type,
+ url: this.url
}
- }
- onMessageComplete () {
- const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this
+ return `Response ${nodeUtil.formatWithOptions(options, properties)}`
+ }
+}
- if (socket.destroyed && (!statusCode || shouldKeepAlive)) {
- return -1
- }
+mixinBody(Response)
- if (upgrade) {
- return
- }
+Object.defineProperties(Response.prototype, {
+ type: kEnumerableProperty,
+ url: kEnumerableProperty,
+ status: kEnumerableProperty,
+ ok: kEnumerableProperty,
+ redirected: kEnumerableProperty,
+ statusText: kEnumerableProperty,
+ headers: kEnumerableProperty,
+ clone: kEnumerableProperty,
+ body: kEnumerableProperty,
+ bodyUsed: kEnumerableProperty,
+ [Symbol.toStringTag]: {
+ value: 'Response',
+ configurable: true
+ }
+})
- assert(statusCode >= 100)
- assert((this.headers.length & 1) === 0)
+Object.defineProperties(Response, {
+ json: kEnumerableProperty,
+ redirect: kEnumerableProperty,
+ error: kEnumerableProperty
+})
- const request = client[kQueue][client[kRunningIdx]]
- assert(request)
+// https://fetch.spec.whatwg.org/#concept-response-clone
+function cloneResponse (response) {
+ // To clone a response response, run these steps:
- this.statusCode = null
- this.statusText = ''
- this.bytesRead = 0
- this.contentLength = ''
- this.keepAlive = ''
- this.connection = ''
+ // 1. If response is a filtered response, then return a new identical
+ // filtered response whose internal response is a clone of response’s
+ // internal response.
+ if (response.internalResponse) {
+ return filterResponse(
+ cloneResponse(response.internalResponse),
+ response.type
+ )
+ }
- this.headers = []
- this.headersSize = 0
+ // 2. Let newResponse be a copy of response, except for its body.
+ const newResponse = makeResponse({ ...response, body: null })
- if (statusCode < 200) {
- return
- }
+ // 3. If response’s body is non-null, then set newResponse’s body to the
+ // result of cloning response’s body.
+ if (response.body != null) {
+ newResponse.body = cloneBody(newResponse, response.body)
+ }
- /* istanbul ignore next: should be handled by llhttp? */
- if (request.method !== 'HEAD' && contentLength && bytesRead !== parseInt(contentLength, 10)) {
- util.destroy(socket, new ResponseContentLengthMismatchError())
- return -1
- }
+ // 4. Return newResponse.
+ return newResponse
+}
- request.onComplete(headers)
+function makeResponse (init) {
+ return {
+ aborted: false,
+ rangeRequested: false,
+ timingAllowPassed: false,
+ requestIncludesCredentials: false,
+ type: 'default',
+ status: 200,
+ timingInfo: null,
+ cacheState: '',
+ statusText: '',
+ ...init,
+ headersList: init?.headersList
+ ? new HeadersList(init?.headersList)
+ : new HeadersList(),
+ urlList: init?.urlList ? [...init.urlList] : []
+ }
+}
- client[kQueue][client[kRunningIdx]++] = null
+function makeNetworkError (reason) {
+ const isError = isErrorLike(reason)
+ return makeResponse({
+ type: 'error',
+ status: 0,
+ error: isError
+ ? reason
+ : new Error(reason ? String(reason) : reason),
+ aborted: reason && reason.name === 'AbortError'
+ })
+}
- if (socket[kWriting]) {
- assert(client[kRunning] === 0)
- // Response completed before request.
- util.destroy(socket, new InformationalError('reset'))
- return constants.ERROR.PAUSED
- } else if (!shouldKeepAlive) {
- util.destroy(socket, new InformationalError('reset'))
- return constants.ERROR.PAUSED
- } else if (socket[kReset] && client[kRunning] === 0) {
- // Destroy socket once all requests have completed.
- // The request at the tail of the pipeline is the one
- // that requested reset and no further requests should
- // have been queued since then.
- util.destroy(socket, new InformationalError('reset'))
- return constants.ERROR.PAUSED
- } else if (client[kPipelining] == null || client[kPipelining] === 1) {
- // We must wait a full event loop cycle to reuse this socket to make sure
- // that non-spec compliant servers are not closing the connection even if they
- // said they won't.
- setImmediate(() => client[kResume]())
- } else {
- client[kResume]()
- }
- }
+// @see https://fetch.spec.whatwg.org/#concept-network-error
+function isNetworkError (response) {
+ return (
+ // A network error is a response whose type is "error",
+ response.type === 'error' &&
+ // status is 0
+ response.status === 0
+ )
}
-function onParserTimeout (parser) {
- const { socket, timeoutType, client, paused } = parser.deref()
+function makeFilteredResponse (response, state) {
+ state = {
+ internalResponse: response,
+ ...state
+ }
- /* istanbul ignore else */
- if (timeoutType === TIMEOUT_HEADERS) {
- if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) {
- assert(!paused, 'cannot be paused while waiting for headers')
- util.destroy(socket, new HeadersTimeoutError())
- }
- } else if (timeoutType === TIMEOUT_BODY) {
- if (!paused) {
- util.destroy(socket, new BodyTimeoutError())
+ return new Proxy(response, {
+ get (target, p) {
+ return p in state ? state[p] : target[p]
+ },
+ set (target, p, value) {
+ assert(!(p in state))
+ target[p] = value
+ return true
}
- } else if (timeoutType === TIMEOUT_KEEP_ALIVE) {
- assert(client[kRunning] === 0 && client[kKeepAliveTimeoutValue])
- util.destroy(socket, new InformationalError('socket idle timeout'))
- }
+ })
}
-async function connectH1 (client, socket) {
- client[kSocket] = socket
+// https://fetch.spec.whatwg.org/#concept-filtered-response
+function filterResponse (response, type) {
+ // Set response to the following filtered response with response as its
+ // internal response, depending on request’s response tainting:
+ if (type === 'basic') {
+ // A basic filtered response is a filtered response whose type is "basic"
+ // and header list excludes any headers in internal response’s header list
+ // whose name is a forbidden response-header name.
- if (!llhttpInstance) {
- llhttpInstance = await llhttpPromise
- llhttpPromise = null
- }
+ // Note: undici does not implement forbidden response-header names
+ return makeFilteredResponse(response, {
+ type: 'basic',
+ headersList: response.headersList
+ })
+ } else if (type === 'cors') {
+ // A CORS filtered response is a filtered response whose type is "cors"
+ // and header list excludes any headers in internal response’s header
+ // list whose name is not a CORS-safelisted response-header name, given
+ // internal response’s CORS-exposed header-name list.
- socket[kNoRef] = false
- socket[kWriting] = false
- socket[kReset] = false
- socket[kBlocking] = false
- socket[kParser] = new Parser(client, socket, llhttpInstance)
+ // Note: undici does not implement CORS-safelisted response-header names
+ return makeFilteredResponse(response, {
+ type: 'cors',
+ headersList: response.headersList
+ })
+ } else if (type === 'opaque') {
+ // An opaque filtered response is a filtered response whose type is
+ // "opaque", URL list is the empty list, status is 0, status message
+ // is the empty byte sequence, header list is empty, and body is null.
- addListener(socket, 'error', function (err) {
- assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')
+ return makeFilteredResponse(response, {
+ type: 'opaque',
+ urlList: Object.freeze([]),
+ status: 0,
+ statusText: '',
+ body: null
+ })
+ } else if (type === 'opaqueredirect') {
+ // An opaque-redirect filtered response is a filtered response whose type
+ // is "opaqueredirect", status is 0, status message is the empty byte
+ // sequence, header list is empty, and body is null.
- const parser = this[kParser]
+ return makeFilteredResponse(response, {
+ type: 'opaqueredirect',
+ status: 0,
+ statusText: '',
+ headersList: [],
+ body: null
+ })
+ } else {
+ assert(false)
+ }
+}
- // On Mac OS, we get an ECONNRESET even if there is a full body to be forwarded
- // to the user.
- if (err.code === 'ECONNRESET' && parser.statusCode && !parser.shouldKeepAlive) {
- // We treat all incoming data so for as a valid response.
- parser.onMessageComplete()
- return
- }
+// https://fetch.spec.whatwg.org/#appropriate-network-error
+function makeAppropriateNetworkError (fetchParams, err = null) {
+ // 1. Assert: fetchParams is canceled.
+ assert(isCancelled(fetchParams))
- this[kError] = err
+ // 2. Return an aborted network error if fetchParams is aborted;
+ // otherwise return a network error.
+ return isAborted(fetchParams)
+ ? makeNetworkError(Object.assign(new DOMException('The operation was aborted.', 'AbortError'), { cause: err }))
+ : makeNetworkError(Object.assign(new DOMException('Request was cancelled.'), { cause: err }))
+}
- this[kClient][kOnError](err)
- })
- addListener(socket, 'readable', function () {
- const parser = this[kParser]
+// https://whatpr.org/fetch/1392.html#initialize-a-response
+function initializeResponse (response, init, body) {
+ // 1. If init["status"] is not in the range 200 to 599, inclusive, then
+ // throw a RangeError.
+ if (init.status !== null && (init.status < 200 || init.status > 599)) {
+ throw new RangeError('init["status"] must be in the range of 200 to 599, inclusive.')
+ }
- if (parser) {
- parser.readMore()
+ // 2. If init["statusText"] does not match the reason-phrase token production,
+ // then throw a TypeError.
+ if ('statusText' in init && init.statusText != null) {
+ // See, https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2:
+ // reason-phrase = *( HTAB / SP / VCHAR / obs-text )
+ if (!isValidReasonPhrase(String(init.statusText))) {
+ throw new TypeError('Invalid statusText')
}
- })
- addListener(socket, 'end', function () {
- const parser = this[kParser]
+ }
- if (parser.statusCode && !parser.shouldKeepAlive) {
- // We treat all incoming data so far as a valid response.
- parser.onMessageComplete()
- return
- }
+ // 3. Set response’s response’s status to init["status"].
+ if ('status' in init && init.status != null) {
+ response[kState].status = init.status
+ }
- util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this)))
- })
- addListener(socket, 'close', function () {
- const client = this[kClient]
- const parser = this[kParser]
+ // 4. Set response’s response’s status message to init["statusText"].
+ if ('statusText' in init && init.statusText != null) {
+ response[kState].statusText = init.statusText
+ }
- if (parser) {
- if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) {
- // We treat all incoming data so far as a valid response.
- parser.onMessageComplete()
- }
+ // 5. If init["headers"] exists, then fill response’s headers with init["headers"].
+ if ('headers' in init && init.headers != null) {
+ fill(response[kHeaders], init.headers)
+ }
- this[kParser].destroy()
- this[kParser] = null
+ // 6. If body was given, then:
+ if (body) {
+ // 1. If response's status is a null body status, then throw a TypeError.
+ if (nullBodyStatus.includes(response.status)) {
+ throw webidl.errors.exception({
+ header: 'Response constructor',
+ message: `Invalid response status code ${response.status}`
+ })
}
- const err = this[kError] || new SocketError('closed', util.getSocketInfo(this))
-
- client[kSocket] = null
- client[kHTTPContext] = null // TODO (fix): This is hacky...
-
- if (client.destroyed) {
- assert(client[kPending] === 0)
-
- // Fail entire queue.
- const requests = client[kQueue].splice(client[kRunningIdx])
- for (let i = 0; i < requests.length; i++) {
- const request = requests[i]
- util.errorRequest(client, request, err)
- }
- } else if (client[kRunning] > 0 && err.code !== 'UND_ERR_INFO') {
- // Fail head of pipeline.
- const request = client[kQueue][client[kRunningIdx]]
- client[kQueue][client[kRunningIdx]++] = null
+ // 2. Set response's body to body's body.
+ response[kState].body = body.body
- util.errorRequest(client, request, err)
+ // 3. If body's type is non-null and response's header list does not contain
+ // `Content-Type`, then append (`Content-Type`, body's type) to response's header list.
+ if (body.type != null && !response[kState].headersList.contains('content-type', true)) {
+ response[kState].headersList.append('content-type', body.type, true)
}
+ }
+}
- client[kPendingIdx] = client[kRunningIdx]
+/**
+ * @see https://fetch.spec.whatwg.org/#response-create
+ * @param {any} innerResponse
+ * @param {'request' | 'immutable' | 'request-no-cors' | 'response' | 'none'} guard
+ * @returns {Response}
+ */
+function fromInnerResponse (innerResponse, guard) {
+ const response = new Response(kConstruct)
+ response[kState] = innerResponse
+ response[kHeaders] = new Headers(kConstruct)
+ setHeadersList(response[kHeaders], innerResponse.headersList)
+ setHeadersGuard(response[kHeaders], guard)
- assert(client[kRunning] === 0)
+ if (hasFinalizationRegistry && innerResponse.body?.stream) {
+ // If the target (response) is reclaimed, the cleanup callback may be called at some point with
+ // the held value provided for it (innerResponse.body.stream). The held value can be any value:
+ // a primitive or an object, even undefined. If the held value is an object, the registry keeps
+ // a strong reference to it (so it can pass it to the cleanup callback later). Reworded from
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry
+ streamRegistry.register(response, new WeakRef(innerResponse.body.stream))
+ }
- client.emit('disconnect', client[kUrl], [client], err)
+ return response
+}
- client[kResume]()
- })
+webidl.converters.ReadableStream = webidl.interfaceConverter(
+ ReadableStream
+)
- let closed = false
- socket.on('close', () => {
- closed = true
- })
+webidl.converters.FormData = webidl.interfaceConverter(
+ FormData
+)
- return {
- version: 'h1',
- defaultPipelining: 1,
- write (...args) {
- return writeH1(client, ...args)
- },
- resume () {
- resumeH1(client)
- },
- destroy (err, callback) {
- if (closed) {
- queueMicrotask(callback)
- } else {
- socket.destroy(err).on('close', callback)
- }
- },
- get destroyed () {
- return socket.destroyed
- },
- busy (request) {
- if (socket[kWriting] || socket[kReset] || socket[kBlocking]) {
- return true
- }
+webidl.converters.URLSearchParams = webidl.interfaceConverter(
+ URLSearchParams
+)
- if (request) {
- if (client[kRunning] > 0 && !request.idempotent) {
- // Non-idempotent request cannot be retried.
- // Ensure that no other requests are inflight and
- // could cause failure.
- return true
- }
+// https://fetch.spec.whatwg.org/#typedefdef-xmlhttprequestbodyinit
+webidl.converters.XMLHttpRequestBodyInit = function (V, prefix, name) {
+ if (typeof V === 'string') {
+ return webidl.converters.USVString(V, prefix, name)
+ }
- if (client[kRunning] > 0 && (request.upgrade || request.method === 'CONNECT')) {
- // Don't dispatch an upgrade until all preceding requests have completed.
- // A misbehaving server might upgrade the connection before all pipelined
- // request has completed.
- return true
- }
+ if (isBlobLike(V)) {
+ return webidl.converters.Blob(V, prefix, name, { strict: false })
+ }
- if (client[kRunning] > 0 && util.bodyLength(request.body) !== 0 &&
- (util.isStream(request.body) || util.isAsyncIterable(request.body) || util.isFormDataLike(request.body))) {
- // Request with stream or iterator body can error while other requests
- // are inflight and indirectly error those as well.
- // Ensure this doesn't happen by waiting for inflight
- // to complete before dispatching.
+ if (ArrayBuffer.isView(V) || types.isArrayBuffer(V)) {
+ return webidl.converters.BufferSource(V, prefix, name)
+ }
- // Request with stream or iterator body cannot be retried.
- // Ensure that no other requests are inflight and
- // could cause failure.
- return true
- }
- }
+ if (util.isFormDataLike(V)) {
+ return webidl.converters.FormData(V, prefix, name, { strict: false })
+ }
- return false
- }
+ if (V instanceof URLSearchParams) {
+ return webidl.converters.URLSearchParams(V, prefix, name)
}
-}
-function resumeH1 (client) {
- const socket = client[kSocket]
+ return webidl.converters.DOMString(V, prefix, name)
+}
- if (socket && !socket.destroyed) {
- if (client[kSize] === 0) {
- if (!socket[kNoRef] && socket.unref) {
- socket.unref()
- socket[kNoRef] = true
- }
- } else if (socket[kNoRef] && socket.ref) {
- socket.ref()
- socket[kNoRef] = false
- }
+// https://fetch.spec.whatwg.org/#bodyinit
+webidl.converters.BodyInit = function (V, prefix, argument) {
+ if (V instanceof ReadableStream) {
+ return webidl.converters.ReadableStream(V, prefix, argument)
+ }
- if (client[kSize] === 0) {
- if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) {
- socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE)
- }
- } else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) {
- if (socket[kParser].timeoutType !== TIMEOUT_HEADERS) {
- const request = client[kQueue][client[kRunningIdx]]
- const headersTimeout = request.headersTimeout != null
- ? request.headersTimeout
- : client[kHeadersTimeout]
- socket[kParser].setTimeout(headersTimeout, TIMEOUT_HEADERS)
- }
- }
+ // Note: the spec doesn't include async iterables,
+ // this is an undici extension.
+ if (V?.[Symbol.asyncIterator]) {
+ return V
}
-}
-// https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2
-function shouldSendContentLength (method) {
- return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT'
+ return webidl.converters.XMLHttpRequestBodyInit(V, prefix, argument)
}
-function writeH1 (client, request) {
- const { method, path, host, upgrade, blocking, reset } = request
+webidl.converters.ResponseInit = webidl.dictionaryConverter([
+ {
+ key: 'status',
+ converter: webidl.converters['unsigned short'],
+ defaultValue: () => 200
+ },
+ {
+ key: 'statusText',
+ converter: webidl.converters.ByteString,
+ defaultValue: () => ''
+ },
+ {
+ key: 'headers',
+ converter: webidl.converters.HeadersInit
+ }
+])
- let { body, headers, contentLength } = request
+module.exports = {
+ isNetworkError,
+ makeNetworkError,
+ makeResponse,
+ makeAppropriateNetworkError,
+ filterResponse,
+ Response,
+ cloneResponse,
+ fromInnerResponse
+}
- // https://tools.ietf.org/html/rfc7231#section-4.3.1
- // https://tools.ietf.org/html/rfc7231#section-4.3.2
- // https://tools.ietf.org/html/rfc7231#section-4.3.5
- // Sending a payload body on a request that does not
- // expect it can cause undefined behavior on some
- // servers and corrupt connection state. Do not
- // re-use the connection for further requests.
+/***/ }),
- const expectsPayload = (
- method === 'PUT' ||
- method === 'POST' ||
- method === 'PATCH' ||
- method === 'QUERY' ||
- method === 'PROPFIND' ||
- method === 'PROPPATCH'
- )
+/***/ 3627:
+/***/ ((module) => {
- if (util.isFormDataLike(body)) {
- if (!extractBody) {
- extractBody = (__nccwpck_require__(8900).extractBody)
- }
- const [bodyStream, contentType] = extractBody(body)
- if (request.contentType == null) {
- headers.push('content-type', contentType)
- }
- body = bodyStream.stream
- contentLength = bodyStream.length
- } else if (util.isBlobLike(body) && request.contentType == null && body.type) {
- headers.push('content-type', body.type)
- }
- if (body && typeof body.read === 'function') {
- // Try to read EOF in order to get length.
- body.read(0)
- }
+module.exports = {
+ kUrl: Symbol('url'),
+ kHeaders: Symbol('headers'),
+ kSignal: Symbol('signal'),
+ kState: Symbol('state'),
+ kDispatcher: Symbol('dispatcher')
+}
- const bodyLength = util.bodyLength(body)
- contentLength = bodyLength ?? contentLength
+/***/ }),
- if (contentLength === null) {
- contentLength = request.contentLength
- }
+/***/ 3168:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- if (contentLength === 0 && !expectsPayload) {
- // https://tools.ietf.org/html/rfc7230#section-3.3.2
- // A user agent SHOULD NOT send a Content-Length header field when
- // the request message does not contain a payload body and the method
- // semantics do not anticipate such a body.
- contentLength = null
- }
- // https://github.com/nodejs/undici/issues/2046
- // A user agent may send a Content-Length header with 0 value, this should be allowed.
- if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength !== null && request.contentLength !== contentLength) {
- if (client[kStrictContentLength]) {
- util.errorRequest(client, request, new RequestContentLengthMismatchError())
- return false
- }
+const { Transform } = __nccwpck_require__(7075)
+const zlib = __nccwpck_require__(8522)
+const { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = __nccwpck_require__(4495)
+const { getGlobalOrigin } = __nccwpck_require__(1059)
+const { collectASequenceOfCodePoints, collectAnHTTPQuotedString, removeChars, parseMIMEType } = __nccwpck_require__(1900)
+const { performance } = __nccwpck_require__(643)
+const { isBlobLike, ReadableStreamFrom, isValidHTTPToken, normalizedMethodRecordsBase } = __nccwpck_require__(3440)
+const assert = __nccwpck_require__(4589)
+const { isUint8Array } = __nccwpck_require__(3429)
+const { webidl } = __nccwpck_require__(5893)
- process.emitWarning(new RequestContentLengthMismatchError())
- }
+let supportedHashes = []
- const socket = client[kSocket]
+// https://nodejs.org/api/crypto.html#determining-if-crypto-support-is-unavailable
+/** @type {import('crypto')} */
+let crypto
+try {
+ crypto = __nccwpck_require__(7598)
+ const possibleRelevantHashes = ['sha256', 'sha384', 'sha512']
+ supportedHashes = crypto.getHashes().filter((hash) => possibleRelevantHashes.includes(hash))
+/* c8 ignore next 3 */
+} catch {
- const abort = (err) => {
- if (request.aborted || request.completed) {
- return
- }
+}
- util.errorRequest(client, request, err || new RequestAbortedError())
+function responseURL (response) {
+ // https://fetch.spec.whatwg.org/#responses
+ // A response has an associated URL. It is a pointer to the last URL
+ // in response’s URL list and null if response’s URL list is empty.
+ const urlList = response.urlList
+ const length = urlList.length
+ return length === 0 ? null : urlList[length - 1].toString()
+}
- util.destroy(body)
- util.destroy(socket, new InformationalError('aborted'))
+// https://fetch.spec.whatwg.org/#concept-response-location-url
+function responseLocationURL (response, requestFragment) {
+ // 1. If response’s status is not a redirect status, then return null.
+ if (!redirectStatusSet.has(response.status)) {
+ return null
}
- try {
- request.onConnect(abort)
- } catch (err) {
- util.errorRequest(client, request, err)
- }
+ // 2. Let location be the result of extracting header list values given
+ // `Location` and response’s header list.
+ let location = response.headersList.get('location', true)
- if (request.aborted) {
- return false
+ // 3. If location is a header value, then set location to the result of
+ // parsing location with response’s URL.
+ if (location !== null && isValidHeaderValue(location)) {
+ if (!isValidEncodedURL(location)) {
+ // Some websites respond location header in UTF-8 form without encoding them as ASCII
+ // and major browsers redirect them to correctly UTF-8 encoded addresses.
+ // Here, we handle that behavior in the same way.
+ location = normalizeBinaryStringToUtf8(location)
+ }
+ location = new URL(location, responseURL(response))
}
- if (method === 'HEAD') {
- // https://github.com/mcollina/undici/issues/258
- // Close after a HEAD request to interop with misbehaving servers
- // that may send a body in the response.
-
- socket[kReset] = true
+ // 4. If location is a URL whose fragment is null, then set location’s
+ // fragment to requestFragment.
+ if (location && !location.hash) {
+ location.hash = requestFragment
}
- if (upgrade || method === 'CONNECT') {
- // On CONNECT or upgrade, block pipeline from dispatching further
- // requests on this connection.
-
- socket[kReset] = true
- }
+ // 5. Return location.
+ return location
+}
- if (reset != null) {
- socket[kReset] = reset
- }
+/**
+ * @see https://www.rfc-editor.org/rfc/rfc1738#section-2.2
+ * @param {string} url
+ * @returns {boolean}
+ */
+function isValidEncodedURL (url) {
+ for (let i = 0; i < url.length; ++i) {
+ const code = url.charCodeAt(i)
- if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) {
- socket[kReset] = true
+ if (
+ code > 0x7E || // Non-US-ASCII + DEL
+ code < 0x20 // Control characters NUL - US
+ ) {
+ return false
+ }
}
+ return true
+}
- if (blocking) {
- socket[kBlocking] = true
- }
+/**
+ * If string contains non-ASCII characters, assumes it's UTF-8 encoded and decodes it.
+ * Since UTF-8 is a superset of ASCII, this will work for ASCII strings as well.
+ * @param {string} value
+ * @returns {string}
+ */
+function normalizeBinaryStringToUtf8 (value) {
+ return Buffer.from(value, 'binary').toString('utf8')
+}
- let header = `${method} ${path} HTTP/1.1\r\n`
+/** @returns {URL} */
+function requestCurrentURL (request) {
+ return request.urlList[request.urlList.length - 1]
+}
- if (typeof host === 'string') {
- header += `host: ${host}\r\n`
- } else {
- header += client[kHostHeader]
- }
+function requestBadPort (request) {
+ // 1. Let url be request’s current URL.
+ const url = requestCurrentURL(request)
- if (upgrade) {
- header += `connection: upgrade\r\nupgrade: ${upgrade}\r\n`
- } else if (client[kPipelining] && !socket[kReset]) {
- header += 'connection: keep-alive\r\n'
- } else {
- header += 'connection: close\r\n'
+ // 2. If url’s scheme is an HTTP(S) scheme and url’s port is a bad port,
+ // then return blocked.
+ if (urlIsHttpHttpsScheme(url) && badPortsSet.has(url.port)) {
+ return 'blocked'
}
- if (Array.isArray(headers)) {
- for (let n = 0; n < headers.length; n += 2) {
- const key = headers[n + 0]
- const val = headers[n + 1]
-
- if (Array.isArray(val)) {
- for (let i = 0; i < val.length; i++) {
- header += `${key}: ${val[i]}\r\n`
- }
- } else {
- header += `${key}: ${val}\r\n`
- }
- }
- }
+ // 3. Return allowed.
+ return 'allowed'
+}
- if (channels.sendHeaders.hasSubscribers) {
- channels.sendHeaders.publish({ request, headers: header, socket })
- }
+function isErrorLike (object) {
+ return object instanceof Error || (
+ object?.constructor?.name === 'Error' ||
+ object?.constructor?.name === 'DOMException'
+ )
+}
- /* istanbul ignore else: assertion */
- if (!body || bodyLength === 0) {
- writeBuffer(abort, null, client, request, socket, contentLength, header, expectsPayload)
- } else if (util.isBuffer(body)) {
- writeBuffer(abort, body, client, request, socket, contentLength, header, expectsPayload)
- } else if (util.isBlobLike(body)) {
- if (typeof body.stream === 'function') {
- writeIterable(abort, body.stream(), client, request, socket, contentLength, header, expectsPayload)
- } else {
- writeBlob(abort, body, client, request, socket, contentLength, header, expectsPayload)
+// Check whether |statusText| is a ByteString and
+// matches the Reason-Phrase token production.
+// RFC 2616: https://tools.ietf.org/html/rfc2616
+// RFC 7230: https://tools.ietf.org/html/rfc7230
+// "reason-phrase = *( HTAB / SP / VCHAR / obs-text )"
+// https://github.com/chromium/chromium/blob/94.0.4604.1/third_party/blink/renderer/core/fetch/response.cc#L116
+function isValidReasonPhrase (statusText) {
+ for (let i = 0; i < statusText.length; ++i) {
+ const c = statusText.charCodeAt(i)
+ if (
+ !(
+ (
+ c === 0x09 || // HTAB
+ (c >= 0x20 && c <= 0x7e) || // SP / VCHAR
+ (c >= 0x80 && c <= 0xff)
+ ) // obs-text
+ )
+ ) {
+ return false
}
- } else if (util.isStream(body)) {
- writeStream(abort, body, client, request, socket, contentLength, header, expectsPayload)
- } else if (util.isIterable(body)) {
- writeIterable(abort, body, client, request, socket, contentLength, header, expectsPayload)
- } else {
- assert(false)
}
-
return true
}
-function writeStream (abort, body, client, request, socket, contentLength, header, expectsPayload) {
- assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined')
+/**
+ * @see https://fetch.spec.whatwg.org/#header-name
+ * @param {string} potentialValue
+ */
+const isValidHeaderName = isValidHTTPToken
- let finished = false
+/**
+ * @see https://fetch.spec.whatwg.org/#header-value
+ * @param {string} potentialValue
+ */
+function isValidHeaderValue (potentialValue) {
+ // - Has no leading or trailing HTTP tab or space bytes.
+ // - Contains no 0x00 (NUL) or HTTP newline bytes.
+ return (
+ potentialValue[0] === '\t' ||
+ potentialValue[0] === ' ' ||
+ potentialValue[potentialValue.length - 1] === '\t' ||
+ potentialValue[potentialValue.length - 1] === ' ' ||
+ potentialValue.includes('\n') ||
+ potentialValue.includes('\r') ||
+ potentialValue.includes('\0')
+ ) === false
+}
- const writer = new AsyncWriter({ abort, socket, request, contentLength, client, expectsPayload, header })
+// https://w3c.github.io/webappsec-referrer-policy/#set-requests-referrer-policy-on-redirect
+function setRequestReferrerPolicyOnRedirect (request, actualResponse) {
+ // Given a request request and a response actualResponse, this algorithm
+ // updates request’s referrer policy according to the Referrer-Policy
+ // header (if any) in actualResponse.
- const onData = function (chunk) {
- if (finished) {
- return
- }
+ // 1. Let policy be the result of executing § 8.1 Parse a referrer policy
+ // from a Referrer-Policy header on actualResponse.
- try {
- if (!writer.write(chunk) && this.pause) {
- this.pause()
+ // 8.1 Parse a referrer policy from a Referrer-Policy header
+ // 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy` and response’s header list.
+ const { headersList } = actualResponse
+ // 2. Let policy be the empty string.
+ // 3. For each token in policy-tokens, if token is a referrer policy and token is not the empty string, then set policy to token.
+ // 4. Return policy.
+ const policyHeader = (headersList.get('referrer-policy', true) ?? '').split(',')
+
+ // Note: As the referrer-policy can contain multiple policies
+ // separated by comma, we need to loop through all of them
+ // and pick the first valid one.
+ // Ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy#specify_a_fallback_policy
+ let policy = ''
+ if (policyHeader.length > 0) {
+ // The right-most policy takes precedence.
+ // The left-most policy is the fallback.
+ for (let i = policyHeader.length; i !== 0; i--) {
+ const token = policyHeader[i - 1].trim()
+ if (referrerPolicyTokens.has(token)) {
+ policy = token
+ break
}
- } catch (err) {
- util.destroy(this, err)
}
}
- const onDrain = function () {
- if (finished) {
- return
- }
- if (body.resume) {
- body.resume()
- }
+ // 2. If policy is not the empty string, then set request’s referrer policy to policy.
+ if (policy !== '') {
+ request.referrerPolicy = policy
}
- const onClose = function () {
- // 'close' might be emitted *before* 'error' for
- // broken streams. Wait a tick to avoid this case.
- queueMicrotask(() => {
- // It's only safe to remove 'error' listener after
- // 'close'.
- body.removeListener('error', onFinished)
- })
+}
- if (!finished) {
- const err = new RequestAbortedError()
- queueMicrotask(() => onFinished(err))
- }
- }
- const onFinished = function (err) {
- if (finished) {
- return
- }
+// https://fetch.spec.whatwg.org/#cross-origin-resource-policy-check
+function crossOriginResourcePolicyCheck () {
+ // TODO
+ return 'allowed'
+}
- finished = true
+// https://fetch.spec.whatwg.org/#concept-cors-check
+function corsCheck () {
+ // TODO
+ return 'success'
+}
- assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1))
+// https://fetch.spec.whatwg.org/#concept-tao-check
+function TAOCheck () {
+ // TODO
+ return 'success'
+}
- socket
- .off('drain', onDrain)
- .off('error', onFinished)
+function appendFetchMetadata (httpRequest) {
+ // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-dest-header
+ // TODO
- body
- .removeListener('data', onData)
- .removeListener('end', onFinished)
- .removeListener('close', onClose)
+ // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-mode-header
- if (!err) {
- try {
- writer.end()
- } catch (er) {
- err = er
- }
- }
+ // 1. Assert: r’s url is a potentially trustworthy URL.
+ // TODO
- writer.destroy(err)
+ // 2. Let header be a Structured Header whose value is a token.
+ let header = null
- if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) {
- util.destroy(body, err)
- } else {
- util.destroy(body)
- }
+ // 3. Set header’s value to r’s mode.
+ header = httpRequest.mode
+
+ // 4. Set a structured field value `Sec-Fetch-Mode`/header in r’s header list.
+ httpRequest.headersList.set('sec-fetch-mode', header, true)
+
+ // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-site-header
+ // TODO
+
+ // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-user-header
+ // TODO
+}
+
+// https://fetch.spec.whatwg.org/#append-a-request-origin-header
+function appendRequestOriginHeader (request) {
+ // 1. Let serializedOrigin be the result of byte-serializing a request origin
+ // with request.
+ // TODO: implement "byte-serializing a request origin"
+ let serializedOrigin = request.origin
+
+ // - "'client' is changed to an origin during fetching."
+ // This doesn't happen in undici (in most cases) because undici, by default,
+ // has no concept of origin.
+ // - request.origin can also be set to request.client.origin (client being
+ // an environment settings object), which is undefined without using
+ // setGlobalOrigin.
+ if (serializedOrigin === 'client' || serializedOrigin === undefined) {
+ return
}
- body
- .on('data', onData)
- .on('end', onFinished)
- .on('error', onFinished)
- .on('close', onClose)
+ // 2. If request’s response tainting is "cors" or request’s mode is "websocket",
+ // then append (`Origin`, serializedOrigin) to request’s header list.
+ // 3. Otherwise, if request’s method is neither `GET` nor `HEAD`, then:
+ if (request.responseTainting === 'cors' || request.mode === 'websocket') {
+ request.headersList.append('origin', serializedOrigin, true)
+ } else if (request.method !== 'GET' && request.method !== 'HEAD') {
+ // 1. Switch on request’s referrer policy:
+ switch (request.referrerPolicy) {
+ case 'no-referrer':
+ // Set serializedOrigin to `null`.
+ serializedOrigin = null
+ break
+ case 'no-referrer-when-downgrade':
+ case 'strict-origin':
+ case 'strict-origin-when-cross-origin':
+ // If request’s origin is a tuple origin, its scheme is "https", and
+ // request’s current URL’s scheme is not "https", then set
+ // serializedOrigin to `null`.
+ if (request.origin && urlHasHttpsScheme(request.origin) && !urlHasHttpsScheme(requestCurrentURL(request))) {
+ serializedOrigin = null
+ }
+ break
+ case 'same-origin':
+ // If request’s origin is not same origin with request’s current URL’s
+ // origin, then set serializedOrigin to `null`.
+ if (!sameOrigin(request, requestCurrentURL(request))) {
+ serializedOrigin = null
+ }
+ break
+ default:
+ // Do nothing.
+ }
- if (body.resume) {
- body.resume()
+ // 2. Append (`Origin`, serializedOrigin) to request’s header list.
+ request.headersList.append('origin', serializedOrigin, true)
}
+}
- socket
- .on('drain', onDrain)
- .on('error', onFinished)
+// https://w3c.github.io/hr-time/#dfn-coarsen-time
+function coarsenTime (timestamp, crossOriginIsolatedCapability) {
+ // TODO
+ return timestamp
+}
- if (body.errorEmitted ?? body.errored) {
- setImmediate(() => onFinished(body.errored))
- } else if (body.endEmitted ?? body.readableEnded) {
- setImmediate(() => onFinished(null))
+// https://fetch.spec.whatwg.org/#clamp-and-coarsen-connection-timing-info
+function clampAndCoarsenConnectionTimingInfo (connectionTimingInfo, defaultStartTime, crossOriginIsolatedCapability) {
+ if (!connectionTimingInfo?.startTime || connectionTimingInfo.startTime < defaultStartTime) {
+ return {
+ domainLookupStartTime: defaultStartTime,
+ domainLookupEndTime: defaultStartTime,
+ connectionStartTime: defaultStartTime,
+ connectionEndTime: defaultStartTime,
+ secureConnectionStartTime: defaultStartTime,
+ ALPNNegotiatedProtocol: connectionTimingInfo?.ALPNNegotiatedProtocol
+ }
}
- if (body.closeEmitted ?? body.closed) {
- setImmediate(onClose)
+ return {
+ domainLookupStartTime: coarsenTime(connectionTimingInfo.domainLookupStartTime, crossOriginIsolatedCapability),
+ domainLookupEndTime: coarsenTime(connectionTimingInfo.domainLookupEndTime, crossOriginIsolatedCapability),
+ connectionStartTime: coarsenTime(connectionTimingInfo.connectionStartTime, crossOriginIsolatedCapability),
+ connectionEndTime: coarsenTime(connectionTimingInfo.connectionEndTime, crossOriginIsolatedCapability),
+ secureConnectionStartTime: coarsenTime(connectionTimingInfo.secureConnectionStartTime, crossOriginIsolatedCapability),
+ ALPNNegotiatedProtocol: connectionTimingInfo.ALPNNegotiatedProtocol
}
}
-function writeBuffer (abort, body, client, request, socket, contentLength, header, expectsPayload) {
- try {
- if (!body) {
- if (contentLength === 0) {
- socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1')
- } else {
- assert(contentLength === null, 'no body must not have content length')
- socket.write(`${header}\r\n`, 'latin1')
- }
- } else if (util.isBuffer(body)) {
- assert(contentLength === body.byteLength, 'buffer body must have content length')
+// https://w3c.github.io/hr-time/#dfn-coarsened-shared-current-time
+function coarsenedSharedCurrentTime (crossOriginIsolatedCapability) {
+ return coarsenTime(performance.now(), crossOriginIsolatedCapability)
+}
- socket.cork()
- socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
- socket.write(body)
- socket.uncork()
- request.onBodySent(body)
+// https://fetch.spec.whatwg.org/#create-an-opaque-timing-info
+function createOpaqueTimingInfo (timingInfo) {
+ return {
+ startTime: timingInfo.startTime ?? 0,
+ redirectStartTime: 0,
+ redirectEndTime: 0,
+ postRedirectStartTime: timingInfo.startTime ?? 0,
+ finalServiceWorkerStartTime: 0,
+ finalNetworkResponseStartTime: 0,
+ finalNetworkRequestStartTime: 0,
+ endTime: 0,
+ encodedBodySize: 0,
+ decodedBodySize: 0,
+ finalConnectionTimingInfo: null
+ }
+}
- if (!expectsPayload && request.reset !== false) {
- socket[kReset] = true
- }
- }
- request.onRequestSent()
+// https://html.spec.whatwg.org/multipage/origin.html#policy-container
+function makePolicyContainer () {
+ // Note: the fetch spec doesn't make use of embedder policy or CSP list
+ return {
+ referrerPolicy: 'strict-origin-when-cross-origin'
+ }
+}
- client[kResume]()
- } catch (err) {
- abort(err)
+// https://html.spec.whatwg.org/multipage/origin.html#clone-a-policy-container
+function clonePolicyContainer (policyContainer) {
+ return {
+ referrerPolicy: policyContainer.referrerPolicy
}
}
-async function writeBlob (abort, body, client, request, socket, contentLength, header, expectsPayload) {
- assert(contentLength === body.size, 'blob body must have content length')
+// https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer
+function determineRequestsReferrer (request) {
+ // 1. Let policy be request's referrer policy.
+ const policy = request.referrerPolicy
- try {
- if (contentLength != null && contentLength !== body.size) {
- throw new RequestContentLengthMismatchError()
- }
+ // Note: policy cannot (shouldn't) be null or an empty string.
+ assert(policy)
- const buffer = Buffer.from(await body.arrayBuffer())
+ // 2. Let environment be request’s client.
- socket.cork()
- socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
- socket.write(buffer)
- socket.uncork()
+ let referrerSource = null
- request.onBodySent(buffer)
- request.onRequestSent()
+ // 3. Switch on request’s referrer:
+ if (request.referrer === 'client') {
+ // Note: node isn't a browser and doesn't implement document/iframes,
+ // so we bypass this step and replace it with our own.
- if (!expectsPayload && request.reset !== false) {
- socket[kReset] = true
+ const globalOrigin = getGlobalOrigin()
+
+ if (!globalOrigin || globalOrigin.origin === 'null') {
+ return 'no-referrer'
}
- client[kResume]()
- } catch (err) {
- abort(err)
+ // note: we need to clone it as it's mutated
+ referrerSource = new URL(globalOrigin)
+ } else if (request.referrer instanceof URL) {
+ // Let referrerSource be request’s referrer.
+ referrerSource = request.referrer
}
-}
-async function writeIterable (abort, body, client, request, socket, contentLength, header, expectsPayload) {
- assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined')
+ // 4. Let request’s referrerURL be the result of stripping referrerSource for
+ // use as a referrer.
+ let referrerURL = stripURLForReferrer(referrerSource)
- let callback = null
- function onDrain () {
- if (callback) {
- const cb = callback
- callback = null
- cb()
- }
- }
+ // 5. Let referrerOrigin be the result of stripping referrerSource for use as
+ // a referrer, with the origin-only flag set to true.
+ const referrerOrigin = stripURLForReferrer(referrerSource, true)
- const waitForDrain = () => new Promise((resolve, reject) => {
- assert(callback === null)
+ // 6. If the result of serializing referrerURL is a string whose length is
+ // greater than 4096, set referrerURL to referrerOrigin.
+ if (referrerURL.toString().length > 4096) {
+ referrerURL = referrerOrigin
+ }
- if (socket[kError]) {
- reject(socket[kError])
- } else {
- callback = resolve
- }
- })
+ const areSameOrigin = sameOrigin(request, referrerURL)
+ const isNonPotentiallyTrustWorthy = isURLPotentiallyTrustworthy(referrerURL) &&
+ !isURLPotentiallyTrustworthy(request.url)
- socket
- .on('close', onDrain)
- .on('drain', onDrain)
+ // 8. Execute the switch statements corresponding to the value of policy:
+ switch (policy) {
+ case 'origin': return referrerOrigin != null ? referrerOrigin : stripURLForReferrer(referrerSource, true)
+ case 'unsafe-url': return referrerURL
+ case 'same-origin':
+ return areSameOrigin ? referrerOrigin : 'no-referrer'
+ case 'origin-when-cross-origin':
+ return areSameOrigin ? referrerURL : referrerOrigin
+ case 'strict-origin-when-cross-origin': {
+ const currentURL = requestCurrentURL(request)
- const writer = new AsyncWriter({ abort, socket, request, contentLength, client, expectsPayload, header })
- try {
- // It's up to the user to somehow abort the async iterable.
- for await (const chunk of body) {
- if (socket[kError]) {
- throw socket[kError]
+ // 1. If the origin of referrerURL and the origin of request’s current
+ // URL are the same, then return referrerURL.
+ if (sameOrigin(referrerURL, currentURL)) {
+ return referrerURL
}
- if (!writer.write(chunk)) {
- await waitForDrain()
+ // 2. If referrerURL is a potentially trustworthy URL and request’s
+ // current URL is not a potentially trustworthy URL, then return no
+ // referrer.
+ if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) {
+ return 'no-referrer'
}
+
+ // 3. Return referrerOrigin.
+ return referrerOrigin
}
+ case 'strict-origin': // eslint-disable-line
+ /**
+ * 1. If referrerURL is a potentially trustworthy URL and
+ * request’s current URL is not a potentially trustworthy URL,
+ * then return no referrer.
+ * 2. Return referrerOrigin
+ */
+ case 'no-referrer-when-downgrade': // eslint-disable-line
+ /**
+ * 1. If referrerURL is a potentially trustworthy URL and
+ * request’s current URL is not a potentially trustworthy URL,
+ * then return no referrer.
+ * 2. Return referrerOrigin
+ */
- writer.end()
- } catch (err) {
- writer.destroy(err)
- } finally {
- socket
- .off('close', onDrain)
- .off('drain', onDrain)
+ default: // eslint-disable-line
+ return isNonPotentiallyTrustWorthy ? 'no-referrer' : referrerOrigin
}
}
-class AsyncWriter {
- constructor ({ abort, socket, request, contentLength, client, expectsPayload, header }) {
- this.socket = socket
- this.request = request
- this.contentLength = contentLength
- this.client = client
- this.bytesWritten = 0
- this.expectsPayload = expectsPayload
- this.header = header
- this.abort = abort
+/**
+ * @see https://w3c.github.io/webappsec-referrer-policy/#strip-url
+ * @param {URL} url
+ * @param {boolean|undefined} originOnly
+ */
+function stripURLForReferrer (url, originOnly) {
+ // 1. Assert: url is a URL.
+ assert(url instanceof URL)
- socket[kWriting] = true
- }
+ url = new URL(url)
- write (chunk) {
- const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this
+ // 2. If url’s scheme is a local scheme, then return no referrer.
+ if (url.protocol === 'file:' || url.protocol === 'about:' || url.protocol === 'blank:') {
+ return 'no-referrer'
+ }
- if (socket[kError]) {
- throw socket[kError]
- }
+ // 3. Set url’s username to the empty string.
+ url.username = ''
- if (socket.destroyed) {
- return false
- }
+ // 4. Set url’s password to the empty string.
+ url.password = ''
- const len = Buffer.byteLength(chunk)
- if (!len) {
- return true
- }
+ // 5. Set url’s fragment to null.
+ url.hash = ''
- // We should defer writing chunks.
- if (contentLength !== null && bytesWritten + len > contentLength) {
- if (client[kStrictContentLength]) {
- throw new RequestContentLengthMismatchError()
- }
+ // 6. If the origin-only flag is true, then:
+ if (originOnly) {
+ // 1. Set url’s path to « the empty string ».
+ url.pathname = ''
- process.emitWarning(new RequestContentLengthMismatchError())
- }
+ // 2. Set url’s query to null.
+ url.search = ''
+ }
- socket.cork()
+ // 7. Return url.
+ return url
+}
- if (bytesWritten === 0) {
- if (!expectsPayload && request.reset !== false) {
- socket[kReset] = true
- }
+function isURLPotentiallyTrustworthy (url) {
+ if (!(url instanceof URL)) {
+ return false
+ }
- if (contentLength === null) {
- socket.write(`${header}transfer-encoding: chunked\r\n`, 'latin1')
- } else {
- socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
- }
- }
+ // If child of about, return true
+ if (url.href === 'about:blank' || url.href === 'about:srcdoc') {
+ return true
+ }
- if (contentLength === null) {
- socket.write(`\r\n${len.toString(16)}\r\n`, 'latin1')
- }
+ // If scheme is data, return true
+ if (url.protocol === 'data:') return true
- this.bytesWritten += len
+ // If file, return true
+ if (url.protocol === 'file:') return true
- const ret = socket.write(chunk)
+ return isOriginPotentiallyTrustworthy(url.origin)
- socket.uncork()
+ function isOriginPotentiallyTrustworthy (origin) {
+ // If origin is explicitly null, return false
+ if (origin == null || origin === 'null') return false
- request.onBodySent(chunk)
+ const originAsURL = new URL(origin)
- if (!ret) {
- if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
- // istanbul ignore else: only for jest
- if (socket[kParser].timeout.refresh) {
- socket[kParser].timeout.refresh()
- }
- }
+ // If secure, return true
+ if (originAsURL.protocol === 'https:' || originAsURL.protocol === 'wss:') {
+ return true
}
- return ret
- }
-
- end () {
- const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this
- request.onRequestSent()
-
- socket[kWriting] = false
-
- if (socket[kError]) {
- throw socket[kError]
+ // If localhost or variants, return true
+ if (/^127(?:\.[0-9]+){0,2}\.[0-9]+$|^\[(?:0*:)*?:?0*1\]$/.test(originAsURL.hostname) ||
+ (originAsURL.hostname === 'localhost' || originAsURL.hostname.includes('localhost.')) ||
+ (originAsURL.hostname.endsWith('.localhost'))) {
+ return true
}
- if (socket.destroyed) {
- return
- }
+ // If any other, return false
+ return false
+ }
+}
- if (bytesWritten === 0) {
- if (expectsPayload) {
- // https://tools.ietf.org/html/rfc7230#section-3.3.2
- // A user agent SHOULD send a Content-Length in a request message when
- // no Transfer-Encoding is sent and the request method defines a meaning
- // for an enclosed payload body.
-
- socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1')
- } else {
- socket.write(`${header}\r\n`, 'latin1')
- }
- } else if (contentLength === null) {
- socket.write('\r\n0\r\n\r\n', 'latin1')
- }
-
- if (contentLength !== null && bytesWritten !== contentLength) {
- if (client[kStrictContentLength]) {
- throw new RequestContentLengthMismatchError()
- } else {
- process.emitWarning(new RequestContentLengthMismatchError())
- }
- }
-
- if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
- // istanbul ignore else: only for jest
- if (socket[kParser].timeout.refresh) {
- socket[kParser].timeout.refresh()
- }
- }
-
- client[kResume]()
+/**
+ * @see https://w3c.github.io/webappsec-subresource-integrity/#does-response-match-metadatalist
+ * @param {Uint8Array} bytes
+ * @param {string} metadataList
+ */
+function bytesMatch (bytes, metadataList) {
+ // If node is not built with OpenSSL support, we cannot check
+ // a request's integrity, so allow it by default (the spec will
+ // allow requests if an invalid hash is given, as precedence).
+ /* istanbul ignore if: only if node is built with --without-ssl */
+ if (crypto === undefined) {
+ return true
}
- destroy (err) {
- const { socket, client, abort } = this
-
- socket[kWriting] = false
+ // 1. Let parsedMetadata be the result of parsing metadataList.
+ const parsedMetadata = parseMetadata(metadataList)
- if (err) {
- assert(client[kRunning] <= 1, 'pipeline should only contain this request')
- abort(err)
- }
+ // 2. If parsedMetadata is no metadata, return true.
+ if (parsedMetadata === 'no metadata') {
+ return true
}
-}
-
-module.exports = connectH1
-
-
-/***/ }),
-
-/***/ 4092:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 3. If response is not eligible for integrity validation, return false.
+ // TODO
+ // 4. If parsedMetadata is the empty set, return true.
+ if (parsedMetadata.length === 0) {
+ return true
+ }
-const assert = __nccwpck_require__(4589)
-const { pipeline } = __nccwpck_require__(7075)
-const util = __nccwpck_require__(1544)
-const {
- RequestContentLengthMismatchError,
- RequestAbortedError,
- SocketError,
- InformationalError
-} = __nccwpck_require__(8091)
-const {
- kUrl,
- kReset,
- kClient,
- kRunning,
- kPending,
- kQueue,
- kPendingIdx,
- kRunningIdx,
- kError,
- kSocket,
- kStrictContentLength,
- kOnError,
- kMaxConcurrentStreams,
- kHTTP2Session,
- kResume,
- kSize,
- kHTTPContext
-} = __nccwpck_require__(9411)
-
-const kOpenStreams = Symbol('open streams')
-
-let extractBody
+ // 5. Let metadata be the result of getting the strongest
+ // metadata from parsedMetadata.
+ const strongest = getStrongestMetadata(parsedMetadata)
+ const metadata = filterMetadataListByAlgorithm(parsedMetadata, strongest)
-// Experimental
-let h2ExperimentalWarned = false
+ // 6. For each item in metadata:
+ for (const item of metadata) {
+ // 1. Let algorithm be the alg component of item.
+ const algorithm = item.algo
-/** @type {import('http2')} */
-let http2
-try {
- http2 = __nccwpck_require__(2467)
-} catch {
- // @ts-ignore
- http2 = { constants: {} }
-}
+ // 2. Let expectedValue be the val component of item.
+ const expectedValue = item.hash
-const {
- constants: {
- HTTP2_HEADER_AUTHORITY,
- HTTP2_HEADER_METHOD,
- HTTP2_HEADER_PATH,
- HTTP2_HEADER_SCHEME,
- HTTP2_HEADER_CONTENT_LENGTH,
- HTTP2_HEADER_EXPECT,
- HTTP2_HEADER_STATUS
- }
-} = http2
+ // See https://github.com/web-platform-tests/wpt/commit/e4c5cc7a5e48093220528dfdd1c4012dc3837a0e
+ // "be liberal with padding". This is annoying, and it's not even in the spec.
-function parseH2Headers (headers) {
- const result = []
+ // 3. Let actualValue be the result of applying algorithm to bytes.
+ let actualValue = crypto.createHash(algorithm).update(bytes).digest('base64')
- for (const [name, value] of Object.entries(headers)) {
- // h2 may concat the header value by array
- // e.g. Set-Cookie
- if (Array.isArray(value)) {
- for (const subvalue of value) {
- // we need to provide each header value of header name
- // because the headers handler expect name-value pair
- result.push(Buffer.from(name), Buffer.from(subvalue))
+ if (actualValue[actualValue.length - 1] === '=') {
+ if (actualValue[actualValue.length - 2] === '=') {
+ actualValue = actualValue.slice(0, -2)
+ } else {
+ actualValue = actualValue.slice(0, -1)
}
- } else {
- result.push(Buffer.from(name), Buffer.from(value))
}
- }
- return result
-}
-
-async function connectH2 (client, socket) {
- client[kSocket] = socket
-
- if (!h2ExperimentalWarned) {
- h2ExperimentalWarned = true
- process.emitWarning('H2 support is experimental, expect them to change at any time.', {
- code: 'UNDICI-H2'
- })
+ // 4. If actualValue is a case-sensitive match for expectedValue,
+ // return true.
+ if (compareBase64Mixed(actualValue, expectedValue)) {
+ return true
+ }
}
- const session = http2.connect(client[kUrl], {
- createConnection: () => socket,
- peerMaxConcurrentStreams: client[kMaxConcurrentStreams]
- })
+ // 7. Return false.
+ return false
+}
- session[kOpenStreams] = 0
- session[kClient] = client
- session[kSocket] = socket
+// https://w3c.github.io/webappsec-subresource-integrity/#grammardef-hash-with-options
+// https://www.w3.org/TR/CSP2/#source-list-syntax
+// https://www.rfc-editor.org/rfc/rfc5234#appendix-B.1
+const parseHashWithOptions = /(?sha256|sha384|sha512)-((?[A-Za-z0-9+/]+|[A-Za-z0-9_-]+)={0,2}(?:\s|$)( +[!-~]*)?)?/i
- util.addListener(session, 'error', onHttp2SessionError)
- util.addListener(session, 'frameError', onHttp2FrameError)
- util.addListener(session, 'end', onHttp2SessionEnd)
- util.addListener(session, 'goaway', onHTTP2GoAway)
- util.addListener(session, 'close', function () {
- const { [kClient]: client } = this
- const { [kSocket]: socket } = client
+/**
+ * @see https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata
+ * @param {string} metadata
+ */
+function parseMetadata (metadata) {
+ // 1. Let result be the empty set.
+ /** @type {{ algo: string, hash: string }[]} */
+ const result = []
- const err = this[kSocket][kError] || this[kError] || new SocketError('closed', util.getSocketInfo(socket))
+ // 2. Let empty be equal to true.
+ let empty = true
- client[kHTTP2Session] = null
+ // 3. For each token returned by splitting metadata on spaces:
+ for (const token of metadata.split(' ')) {
+ // 1. Set empty to false.
+ empty = false
- if (client.destroyed) {
- assert(client[kPending] === 0)
+ // 2. Parse token as a hash-with-options.
+ const parsedToken = parseHashWithOptions.exec(token)
- // Fail entire queue.
- const requests = client[kQueue].splice(client[kRunningIdx])
- for (let i = 0; i < requests.length; i++) {
- const request = requests[i]
- util.errorRequest(client, request, err)
- }
+ // 3. If token does not parse, continue to the next token.
+ if (
+ parsedToken === null ||
+ parsedToken.groups === undefined ||
+ parsedToken.groups.algo === undefined
+ ) {
+ // Note: Chromium blocks the request at this point, but Firefox
+ // gives a warning that an invalid integrity was given. The
+ // correct behavior is to ignore these, and subsequently not
+ // check the integrity of the resource.
+ continue
}
- })
-
- session.unref()
-
- client[kHTTP2Session] = session
- socket[kHTTP2Session] = session
-
- util.addListener(socket, 'error', function (err) {
- assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')
-
- this[kError] = err
-
- this[kClient][kOnError](err)
- })
- util.addListener(socket, 'end', function () {
- util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this)))
- })
-
- util.addListener(socket, 'close', function () {
- const err = this[kError] || new SocketError('closed', util.getSocketInfo(this))
-
- client[kSocket] = null
+ // 4. Let algorithm be the hash-algo component of token.
+ const algorithm = parsedToken.groups.algo.toLowerCase()
- if (this[kHTTP2Session] != null) {
- this[kHTTP2Session].destroy(err)
+ // 5. If algorithm is a hash function recognized by the user
+ // agent, add the parsed token to result.
+ if (supportedHashes.includes(algorithm)) {
+ result.push(parsedToken.groups)
}
+ }
- client[kPendingIdx] = client[kRunningIdx]
-
- assert(client[kRunning] === 0)
-
- client.emit('disconnect', client[kUrl], [client], err)
+ // 4. Return no metadata if empty is true, otherwise return result.
+ if (empty === true) {
+ return 'no metadata'
+ }
- client[kResume]()
- })
+ return result
+}
- let closed = false
- socket.on('close', () => {
- closed = true
- })
+/**
+ * @param {{ algo: 'sha256' | 'sha384' | 'sha512' }[]} metadataList
+ */
+function getStrongestMetadata (metadataList) {
+ // Let algorithm be the algo component of the first item in metadataList.
+ // Can be sha256
+ let algorithm = metadataList[0].algo
+ // If the algorithm is sha512, then it is the strongest
+ // and we can return immediately
+ if (algorithm[3] === '5') {
+ return algorithm
+ }
- return {
- version: 'h2',
- defaultPipelining: Infinity,
- write (...args) {
- return writeH2(client, ...args)
- },
- resume () {
- resumeH2(client)
- },
- destroy (err, callback) {
- if (closed) {
- queueMicrotask(callback)
- } else {
- // Destroying the socket will trigger the session close
- socket.destroy(err).on('close', callback)
- }
- },
- get destroyed () {
- return socket.destroyed
- },
- busy () {
- return false
+ for (let i = 1; i < metadataList.length; ++i) {
+ const metadata = metadataList[i]
+ // If the algorithm is sha512, then it is the strongest
+ // and we can break the loop immediately
+ if (metadata.algo[3] === '5') {
+ algorithm = 'sha512'
+ break
+ // If the algorithm is sha384, then a potential sha256 or sha384 is ignored
+ } else if (algorithm[3] === '3') {
+ continue
+ // algorithm is sha256, check if algorithm is sha384 and if so, set it as
+ // the strongest
+ } else if (metadata.algo[3] === '3') {
+ algorithm = 'sha384'
}
}
+ return algorithm
}
-function resumeH2 (client) {
- const socket = client[kSocket]
+function filterMetadataListByAlgorithm (metadataList, algorithm) {
+ if (metadataList.length === 1) {
+ return metadataList
+ }
- if (socket?.destroyed === false) {
- if (client[kSize] === 0 && client[kMaxConcurrentStreams] === 0) {
- socket.unref()
- client[kHTTP2Session].unref()
- } else {
- socket.ref()
- client[kHTTP2Session].ref()
+ let pos = 0
+ for (let i = 0; i < metadataList.length; ++i) {
+ if (metadataList[i].algo === algorithm) {
+ metadataList[pos++] = metadataList[i]
}
}
-}
-function onHttp2SessionError (err) {
- assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')
+ metadataList.length = pos
- this[kSocket][kError] = err
- this[kClient][kOnError](err)
+ return metadataList
}
-function onHttp2FrameError (type, code, id) {
- if (id === 0) {
- const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`)
- this[kSocket][kError] = err
- this[kClient][kOnError](err)
+/**
+ * Compares two base64 strings, allowing for base64url
+ * in the second string.
+ *
+* @param {string} actualValue always base64
+ * @param {string} expectedValue base64 or base64url
+ * @returns {boolean}
+ */
+function compareBase64Mixed (actualValue, expectedValue) {
+ if (actualValue.length !== expectedValue.length) {
+ return false
+ }
+ for (let i = 0; i < actualValue.length; ++i) {
+ if (actualValue[i] !== expectedValue[i]) {
+ if (
+ (actualValue[i] === '+' && expectedValue[i] === '-') ||
+ (actualValue[i] === '/' && expectedValue[i] === '_')
+ ) {
+ continue
+ }
+ return false
+ }
}
+
+ return true
}
-function onHttp2SessionEnd () {
- const err = new SocketError('other side closed', util.getSocketInfo(this[kSocket]))
- this.destroy(err)
- util.destroy(this[kSocket], err)
+// https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-request
+function tryUpgradeRequestToAPotentiallyTrustworthyURL (request) {
+ // TODO
}
/**
- * This is the root cause of #3011
- * We need to handle GOAWAY frames properly, and trigger the session close
- * along with the socket right away
+ * @link {https://html.spec.whatwg.org/multipage/origin.html#same-origin}
+ * @param {URL} A
+ * @param {URL} B
*/
-function onHTTP2GoAway (code) {
- // We cannot recover, so best to close the session and the socket
- const err = this[kError] || new SocketError(`HTTP/2: "GOAWAY" frame received with code ${code}`, util.getSocketInfo(this))
- const client = this[kClient]
-
- client[kSocket] = null
- client[kHTTPContext] = null
-
- if (this[kHTTP2Session] != null) {
- this[kHTTP2Session].destroy(err)
- this[kHTTP2Session] = null
+function sameOrigin (A, B) {
+ // 1. If A and B are the same opaque origin, then return true.
+ if (A.origin === B.origin && A.origin === 'null') {
+ return true
}
- util.destroy(this[kSocket], err)
-
- // Fail head of pipeline.
- if (client[kRunningIdx] < client[kQueue].length) {
- const request = client[kQueue][client[kRunningIdx]]
- client[kQueue][client[kRunningIdx]++] = null
- util.errorRequest(client, request, err)
- client[kPendingIdx] = client[kRunningIdx]
+ // 2. If A and B are both tuple origins and their schemes,
+ // hosts, and port are identical, then return true.
+ if (A.protocol === B.protocol && A.hostname === B.hostname && A.port === B.port) {
+ return true
}
- assert(client[kRunning] === 0)
+ // 3. Return false.
+ return false
+}
- client.emit('disconnect', client[kUrl], [client], err)
+function createDeferredPromise () {
+ let res
+ let rej
+ const promise = new Promise((resolve, reject) => {
+ res = resolve
+ rej = reject
+ })
- client[kResume]()
+ return { promise, resolve: res, reject: rej }
}
-// https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2
-function shouldSendContentLength (method) {
- return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT'
+function isAborted (fetchParams) {
+ return fetchParams.controller.state === 'aborted'
}
-function writeH2 (client, request) {
- const session = client[kHTTP2Session]
- const { method, path, host, upgrade, expectContinue, signal, headers: reqHeaders } = request
- let { body } = request
+function isCancelled (fetchParams) {
+ return fetchParams.controller.state === 'aborted' ||
+ fetchParams.controller.state === 'terminated'
+}
- if (upgrade) {
- util.errorRequest(client, request, new Error('Upgrade not supported for H2'))
- return false
- }
+/**
+ * @see https://fetch.spec.whatwg.org/#concept-method-normalize
+ * @param {string} method
+ */
+function normalizeMethod (method) {
+ return normalizedMethodRecordsBase[method.toLowerCase()] ?? method
+}
- const headers = {}
- for (let n = 0; n < reqHeaders.length; n += 2) {
- const key = reqHeaders[n + 0]
- const val = reqHeaders[n + 1]
+// https://infra.spec.whatwg.org/#serialize-a-javascript-value-to-a-json-string
+function serializeJavascriptValueToJSONString (value) {
+ // 1. Let result be ? Call(%JSON.stringify%, undefined, « value »).
+ const result = JSON.stringify(value)
- if (Array.isArray(val)) {
- for (let i = 0; i < val.length; i++) {
- if (headers[key]) {
- headers[key] += `,${val[i]}`
- } else {
- headers[key] = val[i]
- }
- }
- } else {
- headers[key] = val
- }
+ // 2. If result is undefined, then throw a TypeError.
+ if (result === undefined) {
+ throw new TypeError('Value is not JSON serializable')
}
- /** @type {import('node:http2').ClientHttp2Stream} */
- let stream
-
- const { hostname, port } = client[kUrl]
-
- headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ''}`
- headers[HTTP2_HEADER_METHOD] = method
+ // 3. Assert: result is a string.
+ assert(typeof result === 'string')
- const abort = (err) => {
- if (request.aborted || request.completed) {
- return
- }
+ // 4. Return result.
+ return result
+}
- err = err || new RequestAbortedError()
+// https://tc39.es/ecma262/#sec-%25iteratorprototype%25-object
+const esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))
- util.errorRequest(client, request, err)
+/**
+ * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object
+ * @param {string} name name of the instance
+ * @param {symbol} kInternalIterator
+ * @param {string | number} [keyIndex]
+ * @param {string | number} [valueIndex]
+ */
+function createIterator (name, kInternalIterator, keyIndex = 0, valueIndex = 1) {
+ class FastIterableIterator {
+ /** @type {any} */
+ #target
+ /** @type {'key' | 'value' | 'key+value'} */
+ #kind
+ /** @type {number} */
+ #index
- if (stream != null) {
- util.destroy(stream, err)
+ /**
+ * @see https://webidl.spec.whatwg.org/#dfn-default-iterator-object
+ * @param {unknown} target
+ * @param {'key' | 'value' | 'key+value'} kind
+ */
+ constructor (target, kind) {
+ this.#target = target
+ this.#kind = kind
+ this.#index = 0
}
- // We do not destroy the socket as we can continue using the session
- // the stream get's destroyed and the session remains to create new streams
- util.destroy(body, err)
- client[kQueue][client[kRunningIdx]++] = null
- client[kResume]()
- }
+ next () {
+ // 1. Let interface be the interface for which the iterator prototype object exists.
+ // 2. Let thisValue be the this value.
+ // 3. Let object be ? ToObject(thisValue).
+ // 4. If object is a platform object, then perform a security
+ // check, passing:
+ // 5. If object is not a default iterator object for interface,
+ // then throw a TypeError.
+ if (typeof this !== 'object' || this === null || !(#target in this)) {
+ throw new TypeError(
+ `'next' called on an object that does not implement interface ${name} Iterator.`
+ )
+ }
- try {
- // We are already connected, streams are pending.
- // We can call on connect, and wait for abort
- request.onConnect(abort)
- } catch (err) {
- util.errorRequest(client, request, err)
- }
+ // 6. Let index be object’s index.
+ // 7. Let kind be object’s kind.
+ // 8. Let values be object’s target's value pairs to iterate over.
+ const index = this.#index
+ const values = this.#target[kInternalIterator]
- if (request.aborted) {
- return false
- }
+ // 9. Let len be the length of values.
+ const len = values.length
- if (method === 'CONNECT') {
- session.ref()
- // We are already connected, streams are pending, first request
- // will create a new stream. We trigger a request to create the stream and wait until
- // `ready` event is triggered
- // We disabled endStream to allow the user to write to the stream
- stream = session.request(headers, { endStream: false, signal })
+ // 10. If index is greater than or equal to len, then return
+ // CreateIterResultObject(undefined, true).
+ if (index >= len) {
+ return {
+ value: undefined,
+ done: true
+ }
+ }
- if (stream.id && !stream.pending) {
- request.onUpgrade(null, null, stream)
- ++session[kOpenStreams]
- client[kQueue][client[kRunningIdx]++] = null
- } else {
- stream.once('ready', () => {
- request.onUpgrade(null, null, stream)
- ++session[kOpenStreams]
- client[kQueue][client[kRunningIdx]++] = null
- })
- }
+ // 11. Let pair be the entry in values at index index.
+ const { [keyIndex]: key, [valueIndex]: value } = values[index]
- stream.once('close', () => {
- session[kOpenStreams] -= 1
- if (session[kOpenStreams] === 0) session.unref()
- })
+ // 12. Set object’s index to index + 1.
+ this.#index = index + 1
- return true
- }
+ // 13. Return the iterator result for pair and kind.
- // https://tools.ietf.org/html/rfc7540#section-8.3
- // :path and :scheme headers must be omitted when sending CONNECT
+ // https://webidl.spec.whatwg.org/#iterator-result
- headers[HTTP2_HEADER_PATH] = path
- headers[HTTP2_HEADER_SCHEME] = 'https'
+ // 1. Let result be a value determined by the value of kind:
+ let result
+ switch (this.#kind) {
+ case 'key':
+ // 1. Let idlKey be pair’s key.
+ // 2. Let key be the result of converting idlKey to an
+ // ECMAScript value.
+ // 3. result is key.
+ result = key
+ break
+ case 'value':
+ // 1. Let idlValue be pair’s value.
+ // 2. Let value be the result of converting idlValue to
+ // an ECMAScript value.
+ // 3. result is value.
+ result = value
+ break
+ case 'key+value':
+ // 1. Let idlKey be pair’s key.
+ // 2. Let idlValue be pair’s value.
+ // 3. Let key be the result of converting idlKey to an
+ // ECMAScript value.
+ // 4. Let value be the result of converting idlValue to
+ // an ECMAScript value.
+ // 5. Let array be ! ArrayCreate(2).
+ // 6. Call ! CreateDataProperty(array, "0", key).
+ // 7. Call ! CreateDataProperty(array, "1", value).
+ // 8. result is array.
+ result = [key, value]
+ break
+ }
- // https://tools.ietf.org/html/rfc7231#section-4.3.1
- // https://tools.ietf.org/html/rfc7231#section-4.3.2
- // https://tools.ietf.org/html/rfc7231#section-4.3.5
+ // 2. Return CreateIterResultObject(result, false).
+ return {
+ value: result,
+ done: false
+ }
+ }
+ }
- // Sending a payload body on a request that does not
- // expect it can cause undefined behavior on some
- // servers and corrupt connection state. Do not
- // re-use the connection for further requests.
+ // https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object
+ // @ts-ignore
+ delete FastIterableIterator.prototype.constructor
- const expectsPayload = (
- method === 'PUT' ||
- method === 'POST' ||
- method === 'PATCH'
- )
+ Object.setPrototypeOf(FastIterableIterator.prototype, esIteratorPrototype)
- if (body && typeof body.read === 'function') {
- // Try to read EOF in order to get length.
- body.read(0)
+ Object.defineProperties(FastIterableIterator.prototype, {
+ [Symbol.toStringTag]: {
+ writable: false,
+ enumerable: false,
+ configurable: true,
+ value: `${name} Iterator`
+ },
+ next: { writable: true, enumerable: true, configurable: true }
+ })
+
+ /**
+ * @param {unknown} target
+ * @param {'key' | 'value' | 'key+value'} kind
+ * @returns {IterableIterator}
+ */
+ return function (target, kind) {
+ return new FastIterableIterator(target, kind)
}
+}
- let contentLength = util.bodyLength(body)
+/**
+ * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object
+ * @param {string} name name of the instance
+ * @param {any} object class
+ * @param {symbol} kInternalIterator
+ * @param {string | number} [keyIndex]
+ * @param {string | number} [valueIndex]
+ */
+function iteratorMixin (name, object, kInternalIterator, keyIndex = 0, valueIndex = 1) {
+ const makeIterator = createIterator(name, kInternalIterator, keyIndex, valueIndex)
- if (util.isFormDataLike(body)) {
- extractBody ??= (__nccwpck_require__(8900).extractBody)
+ const properties = {
+ keys: {
+ writable: true,
+ enumerable: true,
+ configurable: true,
+ value: function keys () {
+ webidl.brandCheck(this, object)
+ return makeIterator(this, 'key')
+ }
+ },
+ values: {
+ writable: true,
+ enumerable: true,
+ configurable: true,
+ value: function values () {
+ webidl.brandCheck(this, object)
+ return makeIterator(this, 'value')
+ }
+ },
+ entries: {
+ writable: true,
+ enumerable: true,
+ configurable: true,
+ value: function entries () {
+ webidl.brandCheck(this, object)
+ return makeIterator(this, 'key+value')
+ }
+ },
+ forEach: {
+ writable: true,
+ enumerable: true,
+ configurable: true,
+ value: function forEach (callbackfn, thisArg = globalThis) {
+ webidl.brandCheck(this, object)
+ webidl.argumentLengthCheck(arguments, 1, `${name}.forEach`)
+ if (typeof callbackfn !== 'function') {
+ throw new TypeError(
+ `Failed to execute 'forEach' on '${name}': parameter 1 is not of type 'Function'.`
+ )
+ }
+ for (const { 0: key, 1: value } of makeIterator(this, 'key+value')) {
+ callbackfn.call(thisArg, value, key, this)
+ }
+ }
+ }
+ }
- const [bodyStream, contentType] = extractBody(body)
- headers['content-type'] = contentType
+ return Object.defineProperties(object.prototype, {
+ ...properties,
+ [Symbol.iterator]: {
+ writable: true,
+ enumerable: false,
+ configurable: true,
+ value: properties.entries.value
+ }
+ })
+}
- body = bodyStream.stream
- contentLength = bodyStream.length
- }
+/**
+ * @see https://fetch.spec.whatwg.org/#body-fully-read
+ */
+async function fullyReadBody (body, processBody, processBodyError) {
+ // 1. If taskDestination is null, then set taskDestination to
+ // the result of starting a new parallel queue.
- if (contentLength == null) {
- contentLength = request.contentLength
- }
+ // 2. Let successSteps given a byte sequence bytes be to queue a
+ // fetch task to run processBody given bytes, with taskDestination.
+ const successSteps = processBody
- if (contentLength === 0 || !expectsPayload) {
- // https://tools.ietf.org/html/rfc7230#section-3.3.2
- // A user agent SHOULD NOT send a Content-Length header field when
- // the request message does not contain a payload body and the method
- // semantics do not anticipate such a body.
+ // 3. Let errorSteps be to queue a fetch task to run processBodyError,
+ // with taskDestination.
+ const errorSteps = processBodyError
- contentLength = null
- }
+ // 4. Let reader be the result of getting a reader for body’s stream.
+ // If that threw an exception, then run errorSteps with that
+ // exception and return.
+ let reader
- // https://github.com/nodejs/undici/issues/2046
- // A user agent may send a Content-Length header with 0 value, this should be allowed.
- if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength != null && request.contentLength !== contentLength) {
- if (client[kStrictContentLength]) {
- util.errorRequest(client, request, new RequestContentLengthMismatchError())
- return false
- }
+ try {
+ reader = body.stream.getReader()
+ } catch (e) {
+ errorSteps(e)
+ return
+ }
- process.emitWarning(new RequestContentLengthMismatchError())
+ // 5. Read all bytes from reader, given successSteps and errorSteps.
+ try {
+ successSteps(await readAllBytes(reader))
+ } catch (e) {
+ errorSteps(e)
}
+}
- if (contentLength != null) {
- assert(body, 'no body must not have content length')
- headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}`
+function isReadableStreamLike (stream) {
+ return stream instanceof ReadableStream || (
+ stream[Symbol.toStringTag] === 'ReadableStream' &&
+ typeof stream.tee === 'function'
+ )
+}
+
+/**
+ * @param {ReadableStreamController} controller
+ */
+function readableStreamClose (controller) {
+ try {
+ controller.close()
+ controller.byobRequest?.respond(0)
+ } catch (err) {
+ // TODO: add comment explaining why this error occurs.
+ if (!err.message.includes('Controller is already closed') && !err.message.includes('ReadableStream is already closed')) {
+ throw err
+ }
}
+}
- session.ref()
+const invalidIsomorphicEncodeValueRegex = /[^\x00-\xFF]/ // eslint-disable-line
- const shouldEndStream = method === 'GET' || method === 'HEAD' || body === null
- if (expectContinue) {
- headers[HTTP2_HEADER_EXPECT] = '100-continue'
- stream = session.request(headers, { endStream: shouldEndStream, signal })
+/**
+ * @see https://infra.spec.whatwg.org/#isomorphic-encode
+ * @param {string} input
+ */
+function isomorphicEncode (input) {
+ // 1. Assert: input contains no code points greater than U+00FF.
+ assert(!invalidIsomorphicEncodeValueRegex.test(input))
- stream.once('continue', writeBodyH2)
- } else {
- stream = session.request(headers, {
- endStream: shouldEndStream,
- signal
- })
- writeBodyH2()
- }
+ // 2. Return a byte sequence whose length is equal to input’s code
+ // point length and whose bytes have the same values as the
+ // values of input’s code points, in the same order
+ return input
+}
- // Increment counter as we have new streams open
- ++session[kOpenStreams]
+/**
+ * @see https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-all-bytes
+ * @see https://streams.spec.whatwg.org/#read-loop
+ * @param {ReadableStreamDefaultReader} reader
+ */
+async function readAllBytes (reader) {
+ const bytes = []
+ let byteLength = 0
- stream.once('response', headers => {
- const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers
- request.onResponseStarted()
+ while (true) {
+ const { done, value: chunk } = await reader.read()
- // Due to the stream nature, it is possible we face a race condition
- // where the stream has been assigned, but the request has been aborted
- // the request remains in-flight and headers hasn't been received yet
- // for those scenarios, best effort is to destroy the stream immediately
- // as there's no value to keep it open.
- if (request.aborted) {
- const err = new RequestAbortedError()
- util.errorRequest(client, request, err)
- util.destroy(stream, err)
- return
+ if (done) {
+ // 1. Call successSteps with bytes.
+ return Buffer.concat(bytes, byteLength)
}
- if (request.onHeaders(Number(statusCode), parseH2Headers(realHeaders), stream.resume.bind(stream), '') === false) {
- stream.pause()
+ // 1. If chunk is not a Uint8Array object, call failureSteps
+ // with a TypeError and abort these steps.
+ if (!isUint8Array(chunk)) {
+ throw new TypeError('Received non-Uint8Array chunk')
}
- stream.on('data', (chunk) => {
- if (request.onData(chunk) === false) {
- stream.pause()
- }
- })
- })
+ // 2. Append the bytes represented by chunk to bytes.
+ bytes.push(chunk)
+ byteLength += chunk.length
- stream.once('end', () => {
- // When state is null, it means we haven't consumed body and the stream still do not have
- // a state.
- // Present specially when using pipeline or stream
- if (stream.state?.state == null || stream.state.state < 6) {
- request.onComplete([])
- }
+ // 3. Read-loop given reader, bytes, successSteps, and failureSteps.
+ }
+}
- if (session[kOpenStreams] === 0) {
- // Stream is closed or half-closed-remote (6), decrement counter and cleanup
- // It does not have sense to continue working with the stream as we do not
- // have yet RST_STREAM support on client-side
+/**
+ * @see https://fetch.spec.whatwg.org/#is-local
+ * @param {URL} url
+ */
+function urlIsLocal (url) {
+ assert('protocol' in url) // ensure it's a url object
- session.unref()
- }
+ const protocol = url.protocol
- abort(new InformationalError('HTTP/2: stream half-closed (remote)'))
- client[kQueue][client[kRunningIdx]++] = null
- client[kPendingIdx] = client[kRunningIdx]
- client[kResume]()
- })
+ return protocol === 'about:' || protocol === 'blob:' || protocol === 'data:'
+}
- stream.once('close', () => {
- session[kOpenStreams] -= 1
- if (session[kOpenStreams] === 0) {
- session.unref()
- }
- })
+/**
+ * @param {string|URL} url
+ * @returns {boolean}
+ */
+function urlHasHttpsScheme (url) {
+ return (
+ (
+ typeof url === 'string' &&
+ url[5] === ':' &&
+ url[0] === 'h' &&
+ url[1] === 't' &&
+ url[2] === 't' &&
+ url[3] === 'p' &&
+ url[4] === 's'
+ ) ||
+ url.protocol === 'https:'
+ )
+}
- stream.once('error', function (err) {
- abort(err)
- })
+/**
+ * @see https://fetch.spec.whatwg.org/#http-scheme
+ * @param {URL} url
+ */
+function urlIsHttpHttpsScheme (url) {
+ assert('protocol' in url) // ensure it's a url object
- stream.once('frameError', (type, code) => {
- abort(new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`))
- })
+ const protocol = url.protocol
- // stream.on('aborted', () => {
- // // TODO(HTTP/2): Support aborted
- // })
+ return protocol === 'http:' || protocol === 'https:'
+}
- // stream.on('timeout', () => {
- // // TODO(HTTP/2): Support timeout
- // })
+/**
+ * @see https://fetch.spec.whatwg.org/#simple-range-header-value
+ * @param {string} value
+ * @param {boolean} allowWhitespace
+ */
+function simpleRangeHeaderValue (value, allowWhitespace) {
+ // 1. Let data be the isomorphic decoding of value.
+ // Note: isomorphic decoding takes a sequence of bytes (ie. a Uint8Array) and turns it into a string,
+ // nothing more. We obviously don't need to do that if value is a string already.
+ const data = value
- // stream.on('push', headers => {
- // // TODO(HTTP/2): Support push
- // })
+ // 2. If data does not start with "bytes", then return failure.
+ if (!data.startsWith('bytes')) {
+ return 'failure'
+ }
- // stream.on('trailers', headers => {
- // // TODO(HTTP/2): Support trailers
- // })
+ // 3. Let position be a position variable for data, initially pointing at the 5th code point of data.
+ const position = { position: 5 }
- return true
+ // 4. If allowWhitespace is true, collect a sequence of code points that are HTTP tab or space,
+ // from data given position.
+ if (allowWhitespace) {
+ collectASequenceOfCodePoints(
+ (char) => char === '\t' || char === ' ',
+ data,
+ position
+ )
+ }
- function writeBodyH2 () {
- /* istanbul ignore else: assertion */
- if (!body || contentLength === 0) {
- writeBuffer(
- abort,
- stream,
- null,
- client,
- request,
- client[kSocket],
- contentLength,
- expectsPayload
- )
- } else if (util.isBuffer(body)) {
- writeBuffer(
- abort,
- stream,
- body,
- client,
- request,
- client[kSocket],
- contentLength,
- expectsPayload
- )
- } else if (util.isBlobLike(body)) {
- if (typeof body.stream === 'function') {
- writeIterable(
- abort,
- stream,
- body.stream(),
- client,
- request,
- client[kSocket],
- contentLength,
- expectsPayload
- )
- } else {
- writeBlob(
- abort,
- stream,
- body,
- client,
- request,
- client[kSocket],
- contentLength,
- expectsPayload
- )
- }
- } else if (util.isStream(body)) {
- writeStream(
- abort,
- client[kSocket],
- expectsPayload,
- stream,
- body,
- client,
- request,
- contentLength
- )
- } else if (util.isIterable(body)) {
- writeIterable(
- abort,
- stream,
- body,
- client,
- request,
- client[kSocket],
- contentLength,
- expectsPayload
- )
- } else {
- assert(false)
- }
+ // 5. If the code point at position within data is not U+003D (=), then return failure.
+ if (data.charCodeAt(position.position) !== 0x3D) {
+ return 'failure'
}
-}
-function writeBuffer (abort, h2stream, body, client, request, socket, contentLength, expectsPayload) {
- try {
- if (body != null && util.isBuffer(body)) {
- assert(contentLength === body.byteLength, 'buffer body must have content length')
- h2stream.cork()
- h2stream.write(body)
- h2stream.uncork()
- h2stream.end()
+ // 6. Advance position by 1.
+ position.position++
- request.onBodySent(body)
- }
+ // 7. If allowWhitespace is true, collect a sequence of code points that are HTTP tab or space, from
+ // data given position.
+ if (allowWhitespace) {
+ collectASequenceOfCodePoints(
+ (char) => char === '\t' || char === ' ',
+ data,
+ position
+ )
+ }
- if (!expectsPayload) {
- socket[kReset] = true
- }
+ // 8. Let rangeStart be the result of collecting a sequence of code points that are ASCII digits,
+ // from data given position.
+ const rangeStart = collectASequenceOfCodePoints(
+ (char) => {
+ const code = char.charCodeAt(0)
- request.onRequestSent()
- client[kResume]()
- } catch (error) {
- abort(error)
+ return code >= 0x30 && code <= 0x39
+ },
+ data,
+ position
+ )
+
+ // 9. Let rangeStartValue be rangeStart, interpreted as decimal number, if rangeStart is not the
+ // empty string; otherwise null.
+ const rangeStartValue = rangeStart.length ? Number(rangeStart) : null
+
+ // 10. If allowWhitespace is true, collect a sequence of code points that are HTTP tab or space,
+ // from data given position.
+ if (allowWhitespace) {
+ collectASequenceOfCodePoints(
+ (char) => char === '\t' || char === ' ',
+ data,
+ position
+ )
}
-}
-function writeStream (abort, socket, expectsPayload, h2stream, body, client, request, contentLength) {
- assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined')
+ // 11. If the code point at position within data is not U+002D (-), then return failure.
+ if (data.charCodeAt(position.position) !== 0x2D) {
+ return 'failure'
+ }
- // For HTTP/2, is enough to pipe the stream
- const pipe = pipeline(
- body,
- h2stream,
- (err) => {
- if (err) {
- util.destroy(pipe, err)
- abort(err)
- } else {
- util.removeAllListeners(pipe)
- request.onRequestSent()
+ // 12. Advance position by 1.
+ position.position++
- if (!expectsPayload) {
- socket[kReset] = true
- }
+ // 13. If allowWhitespace is true, collect a sequence of code points that are HTTP tab
+ // or space, from data given position.
+ // Note from Khafra: its the same step as in #8 again lol
+ if (allowWhitespace) {
+ collectASequenceOfCodePoints(
+ (char) => char === '\t' || char === ' ',
+ data,
+ position
+ )
+ }
- client[kResume]()
- }
- }
+ // 14. Let rangeEnd be the result of collecting a sequence of code points that are
+ // ASCII digits, from data given position.
+ // Note from Khafra: you wouldn't guess it, but this is also the same step as #8
+ const rangeEnd = collectASequenceOfCodePoints(
+ (char) => {
+ const code = char.charCodeAt(0)
+
+ return code >= 0x30 && code <= 0x39
+ },
+ data,
+ position
)
- util.addListener(pipe, 'data', onPipeData)
+ // 15. Let rangeEndValue be rangeEnd, interpreted as decimal number, if rangeEnd
+ // is not the empty string; otherwise null.
+ // Note from Khafra: THE SAME STEP, AGAIN!!!
+ // Note: why interpret as a decimal if we only collect ascii digits?
+ const rangeEndValue = rangeEnd.length ? Number(rangeEnd) : null
- function onPipeData (chunk) {
- request.onBodySent(chunk)
+ // 16. If position is not past the end of data, then return failure.
+ if (position.position < data.length) {
+ return 'failure'
}
-}
-async function writeBlob (abort, h2stream, body, client, request, socket, contentLength, expectsPayload) {
- assert(contentLength === body.size, 'blob body must have content length')
+ // 17. If rangeEndValue and rangeStartValue are null, then return failure.
+ if (rangeEndValue === null && rangeStartValue === null) {
+ return 'failure'
+ }
- try {
- if (contentLength != null && contentLength !== body.size) {
- throw new RequestContentLengthMismatchError()
- }
+ // 18. If rangeStartValue and rangeEndValue are numbers, and rangeStartValue is
+ // greater than rangeEndValue, then return failure.
+ // Note: ... when can they not be numbers?
+ if (rangeStartValue > rangeEndValue) {
+ return 'failure'
+ }
- const buffer = Buffer.from(await body.arrayBuffer())
+ // 19. Return (rangeStartValue, rangeEndValue).
+ return { rangeStartValue, rangeEndValue }
+}
- h2stream.cork()
- h2stream.write(buffer)
- h2stream.uncork()
- h2stream.end()
+/**
+ * @see https://fetch.spec.whatwg.org/#build-a-content-range
+ * @param {number} rangeStart
+ * @param {number} rangeEnd
+ * @param {number} fullLength
+ */
+function buildContentRange (rangeStart, rangeEnd, fullLength) {
+ // 1. Let contentRange be `bytes `.
+ let contentRange = 'bytes '
- request.onBodySent(buffer)
- request.onRequestSent()
+ // 2. Append rangeStart, serialized and isomorphic encoded, to contentRange.
+ contentRange += isomorphicEncode(`${rangeStart}`)
- if (!expectsPayload) {
- socket[kReset] = true
- }
+ // 3. Append 0x2D (-) to contentRange.
+ contentRange += '-'
- client[kResume]()
- } catch (err) {
- abort(err)
- }
-}
+ // 4. Append rangeEnd, serialized and isomorphic encoded to contentRange.
+ contentRange += isomorphicEncode(`${rangeEnd}`)
-async function writeIterable (abort, h2stream, body, client, request, socket, contentLength, expectsPayload) {
- assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined')
+ // 5. Append 0x2F (/) to contentRange.
+ contentRange += '/'
- let callback = null
- function onDrain () {
- if (callback) {
- const cb = callback
- callback = null
- cb()
- }
- }
+ // 6. Append fullLength, serialized and isomorphic encoded to contentRange.
+ contentRange += isomorphicEncode(`${fullLength}`)
- const waitForDrain = () => new Promise((resolve, reject) => {
- assert(callback === null)
+ // 7. Return contentRange.
+ return contentRange
+}
- if (socket[kError]) {
- reject(socket[kError])
- } else {
- callback = resolve
- }
- })
+// A Stream, which pipes the response to zlib.createInflate() or
+// zlib.createInflateRaw() depending on the first byte of the Buffer.
+// If the lower byte of the first byte is 0x08, then the stream is
+// interpreted as a zlib stream, otherwise it's interpreted as a
+// raw deflate stream.
+class InflateStream extends Transform {
+ #zlibOptions
- h2stream
- .on('close', onDrain)
- .on('drain', onDrain)
+ /** @param {zlib.ZlibOptions} [zlibOptions] */
+ constructor (zlibOptions) {
+ super()
+ this.#zlibOptions = zlibOptions
+ }
- try {
- // It's up to the user to somehow abort the async iterable.
- for await (const chunk of body) {
- if (socket[kError]) {
- throw socket[kError]
+ _transform (chunk, encoding, callback) {
+ if (!this._inflateStream) {
+ if (chunk.length === 0) {
+ callback()
+ return
}
+ this._inflateStream = (chunk[0] & 0x0F) === 0x08
+ ? zlib.createInflate(this.#zlibOptions)
+ : zlib.createInflateRaw(this.#zlibOptions)
- const res = h2stream.write(chunk)
- request.onBodySent(chunk)
- if (!res) {
- await waitForDrain()
- }
+ this._inflateStream.on('data', this.push.bind(this))
+ this._inflateStream.on('end', () => this.push(null))
+ this._inflateStream.on('error', (err) => this.destroy(err))
}
- h2stream.end()
-
- request.onRequestSent()
+ this._inflateStream.write(chunk, encoding, callback)
+ }
- if (!expectsPayload) {
- socket[kReset] = true
+ _final (callback) {
+ if (this._inflateStream) {
+ this._inflateStream.end()
+ this._inflateStream = null
}
-
- client[kResume]()
- } catch (err) {
- abort(err)
- } finally {
- h2stream
- .off('close', onDrain)
- .off('drain', onDrain)
+ callback()
}
}
-module.exports = connectH2
+/**
+ * @param {zlib.ZlibOptions} [zlibOptions]
+ * @returns {InflateStream}
+ */
+function createInflate (zlibOptions) {
+ return new InflateStream(zlibOptions)
+}
+/**
+ * @see https://fetch.spec.whatwg.org/#concept-header-extract-mime-type
+ * @param {import('./headers').HeadersList} headers
+ */
+function extractMimeType (headers) {
+ // 1. Let charset be null.
+ let charset = null
-/***/ }),
+ // 2. Let essence be null.
+ let essence = null
-/***/ 3069:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 3. Let mimeType be null.
+ let mimeType = null
-// @ts-check
+ // 4. Let values be the result of getting, decoding, and splitting `Content-Type` from headers.
+ const values = getDecodeSplit('content-type', headers)
+ // 5. If values is null, then return failure.
+ if (values === null) {
+ return 'failure'
+ }
+ // 6. For each value of values:
+ for (const value of values) {
+ // 6.1. Let temporaryMimeType be the result of parsing value.
+ const temporaryMimeType = parseMIMEType(value)
-const assert = __nccwpck_require__(4589)
-const net = __nccwpck_require__(7030)
-const http = __nccwpck_require__(7067)
-const util = __nccwpck_require__(1544)
-const { channels } = __nccwpck_require__(8150)
-const Request = __nccwpck_require__(8823)
-const DispatcherBase = __nccwpck_require__(4745)
-const {
- InvalidArgumentError,
- InformationalError,
- ClientDestroyedError
-} = __nccwpck_require__(8091)
-const buildConnector = __nccwpck_require__(2296)
-const {
- kUrl,
- kServerName,
- kClient,
- kBusy,
- kConnect,
- kResuming,
- kRunning,
- kPending,
- kSize,
- kQueue,
- kConnected,
- kConnecting,
- kNeedDrain,
- kKeepAliveDefaultTimeout,
- kHostHeader,
- kPendingIdx,
- kRunningIdx,
- kError,
- kPipelining,
- kKeepAliveTimeoutValue,
- kMaxHeadersSize,
- kKeepAliveMaxTimeout,
- kKeepAliveTimeoutThreshold,
- kHeadersTimeout,
- kBodyTimeout,
- kStrictContentLength,
- kConnector,
- kMaxRedirections,
- kMaxRequests,
- kCounter,
- kClose,
- kDestroy,
- kDispatch,
- kInterceptors,
- kLocalAddress,
- kMaxResponseSize,
- kOnError,
- kHTTPContext,
- kMaxConcurrentStreams,
- kResume
-} = __nccwpck_require__(9411)
-const connectH1 = __nccwpck_require__(1557)
-const connectH2 = __nccwpck_require__(4092)
-let deprecatedInterceptorWarned = false
+ // 6.2. If temporaryMimeType is failure or its essence is "*/*", then continue.
+ if (temporaryMimeType === 'failure' || temporaryMimeType.essence === '*/*') {
+ continue
+ }
-const kClosedResolve = Symbol('kClosedResolve')
+ // 6.3. Set mimeType to temporaryMimeType.
+ mimeType = temporaryMimeType
-const noop = () => {}
+ // 6.4. If mimeType’s essence is not essence, then:
+ if (mimeType.essence !== essence) {
+ // 6.4.1. Set charset to null.
+ charset = null
-function getPipelining (client) {
- return client[kPipelining] ?? client[kHTTPContext]?.defaultPipelining ?? 1
+ // 6.4.2. If mimeType’s parameters["charset"] exists, then set charset to
+ // mimeType’s parameters["charset"].
+ if (mimeType.parameters.has('charset')) {
+ charset = mimeType.parameters.get('charset')
+ }
+
+ // 6.4.3. Set essence to mimeType’s essence.
+ essence = mimeType.essence
+ } else if (!mimeType.parameters.has('charset') && charset !== null) {
+ // 6.5. Otherwise, if mimeType’s parameters["charset"] does not exist, and
+ // charset is non-null, set mimeType’s parameters["charset"] to charset.
+ mimeType.parameters.set('charset', charset)
+ }
+ }
+
+ // 7. If mimeType is null, then return failure.
+ if (mimeType == null) {
+ return 'failure'
+ }
+
+ // 8. Return mimeType.
+ return mimeType
}
/**
- * @type {import('../../types/client.js').default}
+ * @see https://fetch.spec.whatwg.org/#header-value-get-decode-and-split
+ * @param {string|null} value
*/
-class Client extends DispatcherBase {
- /**
- *
- * @param {string|URL} url
- * @param {import('../../types/client.js').Client.Options} options
- */
- constructor (url, {
- interceptors,
- maxHeaderSize,
- headersTimeout,
- socketTimeout,
- requestTimeout,
- connectTimeout,
- bodyTimeout,
- idleTimeout,
- keepAlive,
- keepAliveTimeout,
- maxKeepAliveTimeout,
- keepAliveMaxTimeout,
- keepAliveTimeoutThreshold,
- socketPath,
- pipelining,
- tls,
- strictContentLength,
- maxCachedSessions,
- maxRedirections,
- connect,
- maxRequestsPerClient,
- localAddress,
- maxResponseSize,
- autoSelectFamily,
- autoSelectFamilyAttemptTimeout,
- // h2
- maxConcurrentStreams,
- allowH2
- } = {}) {
- super()
+function gettingDecodingSplitting (value) {
+ // 1. Let input be the result of isomorphic decoding value.
+ const input = value
- if (keepAlive !== undefined) {
- throw new InvalidArgumentError('unsupported keepAlive, use pipelining=0 instead')
- }
+ // 2. Let position be a position variable for input, initially pointing at the start of input.
+ const position = { position: 0 }
- if (socketTimeout !== undefined) {
- throw new InvalidArgumentError('unsupported socketTimeout, use headersTimeout & bodyTimeout instead')
- }
+ // 3. Let values be a list of strings, initially empty.
+ const values = []
- if (requestTimeout !== undefined) {
- throw new InvalidArgumentError('unsupported requestTimeout, use headersTimeout & bodyTimeout instead')
- }
+ // 4. Let temporaryValue be the empty string.
+ let temporaryValue = ''
- if (idleTimeout !== undefined) {
- throw new InvalidArgumentError('unsupported idleTimeout, use keepAliveTimeout instead')
- }
+ // 5. While position is not past the end of input:
+ while (position.position < input.length) {
+ // 5.1. Append the result of collecting a sequence of code points that are not U+0022 (")
+ // or U+002C (,) from input, given position, to temporaryValue.
+ temporaryValue += collectASequenceOfCodePoints(
+ (char) => char !== '"' && char !== ',',
+ input,
+ position
+ )
- if (maxKeepAliveTimeout !== undefined) {
- throw new InvalidArgumentError('unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead')
- }
+ // 5.2. If position is not past the end of input, then:
+ if (position.position < input.length) {
+ // 5.2.1. If the code point at position within input is U+0022 ("), then:
+ if (input.charCodeAt(position.position) === 0x22) {
+ // 5.2.1.1. Append the result of collecting an HTTP quoted string from input, given position, to temporaryValue.
+ temporaryValue += collectAnHTTPQuotedString(
+ input,
+ position
+ )
- if (maxHeaderSize != null && !Number.isFinite(maxHeaderSize)) {
- throw new InvalidArgumentError('invalid maxHeaderSize')
- }
+ // 5.2.1.2. If position is not past the end of input, then continue.
+ if (position.position < input.length) {
+ continue
+ }
+ } else {
+ // 5.2.2. Otherwise:
- if (socketPath != null && typeof socketPath !== 'string') {
- throw new InvalidArgumentError('invalid socketPath')
- }
+ // 5.2.2.1. Assert: the code point at position within input is U+002C (,).
+ assert(input.charCodeAt(position.position) === 0x2C)
- if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) {
- throw new InvalidArgumentError('invalid connectTimeout')
+ // 5.2.2.2. Advance position by 1.
+ position.position++
+ }
}
- if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) {
- throw new InvalidArgumentError('invalid keepAliveTimeout')
- }
+ // 5.3. Remove all HTTP tab or space from the start and end of temporaryValue.
+ temporaryValue = removeChars(temporaryValue, true, true, (char) => char === 0x9 || char === 0x20)
- if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) {
- throw new InvalidArgumentError('invalid keepAliveMaxTimeout')
- }
+ // 5.4. Append temporaryValue to values.
+ values.push(temporaryValue)
- if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) {
- throw new InvalidArgumentError('invalid keepAliveTimeoutThreshold')
- }
+ // 5.6. Set temporaryValue to the empty string.
+ temporaryValue = ''
+ }
- if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) {
- throw new InvalidArgumentError('headersTimeout must be a positive integer or zero')
- }
+ // 6. Return values.
+ return values
+}
- if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) {
- throw new InvalidArgumentError('bodyTimeout must be a positive integer or zero')
- }
+/**
+ * @see https://fetch.spec.whatwg.org/#concept-header-list-get-decode-split
+ * @param {string} name lowercase header name
+ * @param {import('./headers').HeadersList} list
+ */
+function getDecodeSplit (name, list) {
+ // 1. Let value be the result of getting name from list.
+ const value = list.get(name, true)
- if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {
- throw new InvalidArgumentError('connect must be a function or an object')
- }
+ // 2. If value is null, then return null.
+ if (value === null) {
+ return null
+ }
- if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {
- throw new InvalidArgumentError('maxRedirections must be a positive number')
- }
+ // 3. Return the result of getting, decoding, and splitting value.
+ return gettingDecodingSplitting(value)
+}
- if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) {
- throw new InvalidArgumentError('maxRequestsPerClient must be a positive number')
- }
+const textDecoder = new TextDecoder()
- if (localAddress != null && (typeof localAddress !== 'string' || net.isIP(localAddress) === 0)) {
- throw new InvalidArgumentError('localAddress must be valid string IP address')
- }
+/**
+ * @see https://encoding.spec.whatwg.org/#utf-8-decode
+ * @param {Buffer} buffer
+ */
+function utf8DecodeBytes (buffer) {
+ if (buffer.length === 0) {
+ return ''
+ }
- if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) {
- throw new InvalidArgumentError('maxResponseSize must be a positive number')
- }
+ // 1. Let buffer be the result of peeking three bytes from
+ // ioQueue, converted to a byte sequence.
- if (
- autoSelectFamilyAttemptTimeout != null &&
- (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1)
- ) {
- throw new InvalidArgumentError('autoSelectFamilyAttemptTimeout must be a positive number')
- }
+ // 2. If buffer is 0xEF 0xBB 0xBF, then read three
+ // bytes from ioQueue. (Do nothing with those bytes.)
+ if (buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) {
+ buffer = buffer.subarray(3)
+ }
- // h2
- if (allowH2 != null && typeof allowH2 !== 'boolean') {
- throw new InvalidArgumentError('allowH2 must be a valid boolean value')
- }
+ // 3. Process a queue with an instance of UTF-8’s
+ // decoder, ioQueue, output, and "replacement".
+ const output = textDecoder.decode(buffer)
- if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== 'number' || maxConcurrentStreams < 1)) {
- throw new InvalidArgumentError('maxConcurrentStreams must be a positive integer, greater than 0')
- }
+ // 4. Return output.
+ return output
+}
- if (typeof connect !== 'function') {
- connect = buildConnector({
- ...tls,
- maxCachedSessions,
- allowH2,
- socketPath,
- timeout: connectTimeout,
- ...(autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined),
- ...connect
- })
- }
+class EnvironmentSettingsObjectBase {
+ get baseUrl () {
+ return getGlobalOrigin()
+ }
- if (interceptors?.Client && Array.isArray(interceptors.Client)) {
- this[kInterceptors] = interceptors.Client
- if (!deprecatedInterceptorWarned) {
- deprecatedInterceptorWarned = true
- process.emitWarning('Client.Options#interceptor is deprecated. Use Dispatcher#compose instead.', {
- code: 'UNDICI-CLIENT-INTERCEPTOR-DEPRECATED'
- })
- }
- } else {
- this[kInterceptors] = [createRedirectInterceptor({ maxRedirections })]
- }
+ get origin () {
+ return this.baseUrl?.origin
+ }
- this[kUrl] = util.parseOrigin(url)
- this[kConnector] = connect
- this[kPipelining] = pipelining != null ? pipelining : 1
- this[kMaxHeadersSize] = maxHeaderSize || http.maxHeaderSize
- this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout
- this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 600e3 : keepAliveMaxTimeout
- this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 2e3 : keepAliveTimeoutThreshold
- this[kKeepAliveTimeoutValue] = this[kKeepAliveDefaultTimeout]
- this[kServerName] = null
- this[kLocalAddress] = localAddress != null ? localAddress : null
- this[kResuming] = 0 // 0, idle, 1, scheduled, 2 resuming
- this[kNeedDrain] = 0 // 0, idle, 1, scheduled, 2 resuming
- this[kHostHeader] = `host: ${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}\r\n`
- this[kBodyTimeout] = bodyTimeout != null ? bodyTimeout : 300e3
- this[kHeadersTimeout] = headersTimeout != null ? headersTimeout : 300e3
- this[kStrictContentLength] = strictContentLength == null ? true : strictContentLength
- this[kMaxRedirections] = maxRedirections
- this[kMaxRequests] = maxRequestsPerClient
- this[kClosedResolve] = null
- this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1
- this[kMaxConcurrentStreams] = maxConcurrentStreams != null ? maxConcurrentStreams : 100 // Max peerConcurrentStreams for a Node h2 server
- this[kHTTPContext] = null
+ policyContainer = makePolicyContainer()
+}
- // kQueue is built up of 3 sections separated by
- // the kRunningIdx and kPendingIdx indices.
- // | complete | running | pending |
- // ^ kRunningIdx ^ kPendingIdx ^ kQueue.length
- // kRunningIdx points to the first running element.
- // kPendingIdx points to the first pending element.
- // This implements a fast queue with an amortized
- // time of O(1).
+class EnvironmentSettingsObject {
+ settingsObject = new EnvironmentSettingsObjectBase()
+}
- this[kQueue] = []
- this[kRunningIdx] = 0
- this[kPendingIdx] = 0
+const environmentSettingsObject = new EnvironmentSettingsObject()
- this[kResume] = (sync) => resume(this, sync)
- this[kOnError] = (err) => onError(this, err)
- }
+module.exports = {
+ isAborted,
+ isCancelled,
+ isValidEncodedURL,
+ createDeferredPromise,
+ ReadableStreamFrom,
+ tryUpgradeRequestToAPotentiallyTrustworthyURL,
+ clampAndCoarsenConnectionTimingInfo,
+ coarsenedSharedCurrentTime,
+ determineRequestsReferrer,
+ makePolicyContainer,
+ clonePolicyContainer,
+ appendFetchMetadata,
+ appendRequestOriginHeader,
+ TAOCheck,
+ corsCheck,
+ crossOriginResourcePolicyCheck,
+ createOpaqueTimingInfo,
+ setRequestReferrerPolicyOnRedirect,
+ isValidHTTPToken,
+ requestBadPort,
+ requestCurrentURL,
+ responseURL,
+ responseLocationURL,
+ isBlobLike,
+ isURLPotentiallyTrustworthy,
+ isValidReasonPhrase,
+ sameOrigin,
+ normalizeMethod,
+ serializeJavascriptValueToJSONString,
+ iteratorMixin,
+ createIterator,
+ isValidHeaderName,
+ isValidHeaderValue,
+ isErrorLike,
+ fullyReadBody,
+ bytesMatch,
+ isReadableStreamLike,
+ readableStreamClose,
+ isomorphicEncode,
+ urlIsLocal,
+ urlHasHttpsScheme,
+ urlIsHttpHttpsScheme,
+ readAllBytes,
+ simpleRangeHeaderValue,
+ buildContentRange,
+ parseMetadata,
+ createInflate,
+ extractMimeType,
+ getDecodeSplit,
+ utf8DecodeBytes,
+ environmentSettingsObject
+}
- get pipelining () {
- return this[kPipelining]
- }
- set pipelining (value) {
- this[kPipelining] = value
- this[kResume](true)
- }
+/***/ }),
- get [kPending] () {
- return this[kQueue].length - this[kPendingIdx]
- }
+/***/ 5893:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- get [kRunning] () {
- return this[kPendingIdx] - this[kRunningIdx]
- }
- get [kSize] () {
- return this[kQueue].length - this[kRunningIdx]
- }
- get [kConnected] () {
- return !!this[kHTTPContext] && !this[kConnecting] && !this[kHTTPContext].destroyed
- }
+const { types, inspect } = __nccwpck_require__(7975)
+const { markAsUncloneable } = __nccwpck_require__(5919)
+const { toUSVString } = __nccwpck_require__(3440)
- get [kBusy] () {
- return Boolean(
- this[kHTTPContext]?.busy(null) ||
- (this[kSize] >= (getPipelining(this) || 1)) ||
- this[kPending] > 0
- )
- }
+/** @type {import('../../../types/webidl').Webidl} */
+const webidl = {}
+webidl.converters = {}
+webidl.util = {}
+webidl.errors = {}
- /* istanbul ignore: only used for test */
- [kConnect] (cb) {
- connect(this)
- this.once('connect', cb)
- }
+webidl.errors.exception = function (message) {
+ return new TypeError(`${message.header}: ${message.message}`)
+}
- [kDispatch] (opts, handler) {
- const origin = opts.origin || this[kUrl].origin
- const request = new Request(origin, opts, handler)
+webidl.errors.conversionFailed = function (context) {
+ const plural = context.types.length === 1 ? '' : ' one of'
+ const message =
+ `${context.argument} could not be converted to` +
+ `${plural}: ${context.types.join(', ')}.`
- this[kQueue].push(request)
- if (this[kResuming]) {
- // Do nothing.
- } else if (util.bodyLength(request.body) == null && util.isIterable(request.body)) {
- // Wait a tick in case stream/iterator is ended in the same tick.
- this[kResuming] = 1
- queueMicrotask(() => resume(this))
- } else {
- this[kResume](true)
- }
+ return webidl.errors.exception({
+ header: context.prefix,
+ message
+ })
+}
- if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) {
- this[kNeedDrain] = 2
- }
+webidl.errors.invalidArgument = function (context) {
+ return webidl.errors.exception({
+ header: context.prefix,
+ message: `"${context.value}" is an invalid ${context.type}.`
+ })
+}
- return this[kNeedDrain] < 2
+// https://webidl.spec.whatwg.org/#implements
+webidl.brandCheck = function (V, I, opts) {
+ if (opts?.strict !== false) {
+ if (!(V instanceof I)) {
+ const err = new TypeError('Illegal invocation')
+ err.code = 'ERR_INVALID_THIS' // node compat.
+ throw err
+ }
+ } else {
+ if (V?.[Symbol.toStringTag] !== I.prototype[Symbol.toStringTag]) {
+ const err = new TypeError('Illegal invocation')
+ err.code = 'ERR_INVALID_THIS' // node compat.
+ throw err
+ }
}
+}
- async [kClose] () {
- // TODO: for H2 we need to gracefully flush the remaining enqueued
- // request and close each stream.
- return new Promise((resolve) => {
- if (this[kSize]) {
- this[kClosedResolve] = resolve
- } else {
- resolve(null)
- }
+webidl.argumentLengthCheck = function ({ length }, min, ctx) {
+ if (length < min) {
+ throw webidl.errors.exception({
+ message: `${min} argument${min !== 1 ? 's' : ''} required, ` +
+ `but${length ? ' only' : ''} ${length} found.`,
+ header: ctx
})
}
+}
- async [kDestroy] (err) {
- return new Promise((resolve) => {
- const requests = this[kQueue].splice(this[kPendingIdx])
- for (let i = 0; i < requests.length; i++) {
- const request = requests[i]
- util.errorRequest(this, request, err)
- }
-
- const callback = () => {
- if (this[kClosedResolve]) {
- // TODO (fix): Should we error here with ClientDestroyedError?
- this[kClosedResolve]()
- this[kClosedResolve] = null
- }
- resolve(null)
- }
+webidl.illegalConstructor = function () {
+ throw webidl.errors.exception({
+ header: 'TypeError',
+ message: 'Illegal constructor'
+ })
+}
- if (this[kHTTPContext]) {
- this[kHTTPContext].destroy(err, callback)
- this[kHTTPContext] = null
- } else {
- queueMicrotask(callback)
+// https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values
+webidl.util.Type = function (V) {
+ switch (typeof V) {
+ case 'undefined': return 'Undefined'
+ case 'boolean': return 'Boolean'
+ case 'string': return 'String'
+ case 'symbol': return 'Symbol'
+ case 'number': return 'Number'
+ case 'bigint': return 'BigInt'
+ case 'function':
+ case 'object': {
+ if (V === null) {
+ return 'Null'
}
- this[kResume]()
- })
+ return 'Object'
+ }
}
}
-const createRedirectInterceptor = __nccwpck_require__(1676)
-
-function onError (client, err) {
- if (
- client[kRunning] === 0 &&
- err.code !== 'UND_ERR_INFO' &&
- err.code !== 'UND_ERR_SOCKET'
- ) {
- // Error is not caused by running request and not a recoverable
- // socket error.
-
- assert(client[kPendingIdx] === client[kRunningIdx])
+webidl.util.markAsUncloneable = markAsUncloneable || (() => {})
+// https://webidl.spec.whatwg.org/#abstract-opdef-converttoint
+webidl.util.ConvertToInt = function (V, bitLength, signedness, opts) {
+ let upperBound
+ let lowerBound
- const requests = client[kQueue].splice(client[kRunningIdx])
+ // 1. If bitLength is 64, then:
+ if (bitLength === 64) {
+ // 1. Let upperBound be 2^53 − 1.
+ upperBound = Math.pow(2, 53) - 1
- for (let i = 0; i < requests.length; i++) {
- const request = requests[i]
- util.errorRequest(client, request, err)
+ // 2. If signedness is "unsigned", then let lowerBound be 0.
+ if (signedness === 'unsigned') {
+ lowerBound = 0
+ } else {
+ // 3. Otherwise let lowerBound be −2^53 + 1.
+ lowerBound = Math.pow(-2, 53) + 1
}
- assert(client[kSize] === 0)
- }
-}
-
-/**
- * @param {Client} client
- * @returns
- */
-async function connect (client) {
- assert(!client[kConnecting])
- assert(!client[kHTTPContext])
+ } else if (signedness === 'unsigned') {
+ // 2. Otherwise, if signedness is "unsigned", then:
- let { host, hostname, protocol, port } = client[kUrl]
+ // 1. Let lowerBound be 0.
+ lowerBound = 0
- // Resolve ipv6
- if (hostname[0] === '[') {
- const idx = hostname.indexOf(']')
+ // 2. Let upperBound be 2^bitLength − 1.
+ upperBound = Math.pow(2, bitLength) - 1
+ } else {
+ // 3. Otherwise:
- assert(idx !== -1)
- const ip = hostname.substring(1, idx)
+ // 1. Let lowerBound be -2^bitLength − 1.
+ lowerBound = Math.pow(-2, bitLength) - 1
- assert(net.isIP(ip))
- hostname = ip
+ // 2. Let upperBound be 2^bitLength − 1 − 1.
+ upperBound = Math.pow(2, bitLength - 1) - 1
}
- client[kConnecting] = true
+ // 4. Let x be ? ToNumber(V).
+ let x = Number(V)
- if (channels.beforeConnect.hasSubscribers) {
- channels.beforeConnect.publish({
- connectParams: {
- host,
- hostname,
- protocol,
- port,
- version: client[kHTTPContext]?.version,
- servername: client[kServerName],
- localAddress: client[kLocalAddress]
- },
- connector: client[kConnector]
- })
+ // 5. If x is −0, then set x to +0.
+ if (x === 0) {
+ x = 0
}
- try {
- const socket = await new Promise((resolve, reject) => {
- client[kConnector]({
- host,
- hostname,
- protocol,
- port,
- servername: client[kServerName],
- localAddress: client[kLocalAddress]
- }, (err, socket) => {
- if (err) {
- reject(err)
- } else {
- resolve(socket)
- }
+ // 6. If the conversion is to an IDL type associated
+ // with the [EnforceRange] extended attribute, then:
+ if (opts?.enforceRange === true) {
+ // 1. If x is NaN, +∞, or −∞, then throw a TypeError.
+ if (
+ Number.isNaN(x) ||
+ x === Number.POSITIVE_INFINITY ||
+ x === Number.NEGATIVE_INFINITY
+ ) {
+ throw webidl.errors.exception({
+ header: 'Integer conversion',
+ message: `Could not convert ${webidl.util.Stringify(V)} to an integer.`
})
- })
-
- if (client.destroyed) {
- util.destroy(socket.on('error', noop), new ClientDestroyedError())
- return
}
- assert(socket)
+ // 2. Set x to IntegerPart(x).
+ x = webidl.util.IntegerPart(x)
- try {
- client[kHTTPContext] = socket.alpnProtocol === 'h2'
- ? await connectH2(client, socket)
- : await connectH1(client, socket)
- } catch (err) {
- socket.destroy().on('error', noop)
- throw err
+ // 3. If x < lowerBound or x > upperBound, then
+ // throw a TypeError.
+ if (x < lowerBound || x > upperBound) {
+ throw webidl.errors.exception({
+ header: 'Integer conversion',
+ message: `Value must be between ${lowerBound}-${upperBound}, got ${x}.`
+ })
}
- client[kConnecting] = false
+ // 4. Return x.
+ return x
+ }
- socket[kCounter] = 0
- socket[kMaxRequests] = client[kMaxRequests]
- socket[kClient] = client
- socket[kError] = null
+ // 7. If x is not NaN and the conversion is to an IDL
+ // type associated with the [Clamp] extended
+ // attribute, then:
+ if (!Number.isNaN(x) && opts?.clamp === true) {
+ // 1. Set x to min(max(x, lowerBound), upperBound).
+ x = Math.min(Math.max(x, lowerBound), upperBound)
- if (channels.connected.hasSubscribers) {
- channels.connected.publish({
- connectParams: {
- host,
- hostname,
- protocol,
- port,
- version: client[kHTTPContext]?.version,
- servername: client[kServerName],
- localAddress: client[kLocalAddress]
- },
- connector: client[kConnector],
- socket
- })
- }
- client.emit('connect', client[kUrl], [client])
- } catch (err) {
- if (client.destroyed) {
- return
- }
-
- client[kConnecting] = false
-
- if (channels.connectError.hasSubscribers) {
- channels.connectError.publish({
- connectParams: {
- host,
- hostname,
- protocol,
- port,
- version: client[kHTTPContext]?.version,
- servername: client[kServerName],
- localAddress: client[kLocalAddress]
- },
- connector: client[kConnector],
- error: err
- })
- }
-
- if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') {
- assert(client[kRunning] === 0)
- while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) {
- const request = client[kQueue][client[kPendingIdx]++]
- util.errorRequest(client, request, err)
- }
+ // 2. Round x to the nearest integer, choosing the
+ // even integer if it lies halfway between two,
+ // and choosing +0 rather than −0.
+ if (Math.floor(x) % 2 === 0) {
+ x = Math.floor(x)
} else {
- onError(client, err)
+ x = Math.ceil(x)
}
- client.emit('connectionError', client[kUrl], [client], err)
+ // 3. Return x.
+ return x
}
- client[kResume]()
-}
-
-function emitDrain (client) {
- client[kNeedDrain] = 0
- client.emit('drain', client[kUrl], [client])
-}
-
-function resume (client, sync) {
- if (client[kResuming] === 2) {
- return
+ // 8. If x is NaN, +0, +∞, or −∞, then return +0.
+ if (
+ Number.isNaN(x) ||
+ (x === 0 && Object.is(0, x)) ||
+ x === Number.POSITIVE_INFINITY ||
+ x === Number.NEGATIVE_INFINITY
+ ) {
+ return 0
}
- client[kResuming] = 2
+ // 9. Set x to IntegerPart(x).
+ x = webidl.util.IntegerPart(x)
- _resume(client, sync)
- client[kResuming] = 0
+ // 10. Set x to x modulo 2^bitLength.
+ x = x % Math.pow(2, bitLength)
- if (client[kRunningIdx] > 256) {
- client[kQueue].splice(0, client[kRunningIdx])
- client[kPendingIdx] -= client[kRunningIdx]
- client[kRunningIdx] = 0
+ // 11. If signedness is "signed" and x ≥ 2^bitLength − 1,
+ // then return x − 2^bitLength.
+ if (signedness === 'signed' && x >= Math.pow(2, bitLength) - 1) {
+ return x - Math.pow(2, bitLength)
}
+
+ // 12. Otherwise, return x.
+ return x
}
-function _resume (client, sync) {
- while (true) {
- if (client.destroyed) {
- assert(client[kPending] === 0)
- return
- }
+// https://webidl.spec.whatwg.org/#abstract-opdef-integerpart
+webidl.util.IntegerPart = function (n) {
+ // 1. Let r be floor(abs(n)).
+ const r = Math.floor(Math.abs(n))
- if (client[kClosedResolve] && !client[kSize]) {
- client[kClosedResolve]()
- client[kClosedResolve] = null
- return
- }
+ // 2. If n < 0, then return -1 × r.
+ if (n < 0) {
+ return -1 * r
+ }
- if (client[kHTTPContext]) {
- client[kHTTPContext].resume()
- }
+ // 3. Otherwise, return r.
+ return r
+}
- if (client[kBusy]) {
- client[kNeedDrain] = 2
- } else if (client[kNeedDrain] === 2) {
- if (sync) {
- client[kNeedDrain] = 1
- queueMicrotask(() => emitDrain(client))
- } else {
- emitDrain(client)
- }
- continue
- }
+webidl.util.Stringify = function (V) {
+ const type = webidl.util.Type(V)
- if (client[kPending] === 0) {
- return
- }
+ switch (type) {
+ case 'Symbol':
+ return `Symbol(${V.description})`
+ case 'Object':
+ return inspect(V)
+ case 'String':
+ return `"${V}"`
+ default:
+ return `${V}`
+ }
+}
- if (client[kRunning] >= (getPipelining(client) || 1)) {
- return
+// https://webidl.spec.whatwg.org/#es-sequence
+webidl.sequenceConverter = function (converter) {
+ return (V, prefix, argument, Iterable) => {
+ // 1. If Type(V) is not Object, throw a TypeError.
+ if (webidl.util.Type(V) !== 'Object') {
+ throw webidl.errors.exception({
+ header: prefix,
+ message: `${argument} (${webidl.util.Stringify(V)}) is not iterable.`
+ })
}
- const request = client[kQueue][client[kPendingIdx]]
-
- if (client[kUrl].protocol === 'https:' && client[kServerName] !== request.servername) {
- if (client[kRunning] > 0) {
- return
- }
+ // 2. Let method be ? GetMethod(V, @@iterator).
+ /** @type {Generator} */
+ const method = typeof Iterable === 'function' ? Iterable() : V?.[Symbol.iterator]?.()
+ const seq = []
+ let index = 0
- client[kServerName] = request.servername
- client[kHTTPContext]?.destroy(new InformationalError('servername changed'), () => {
- client[kHTTPContext] = null
- resume(client)
+ // 3. If method is undefined, throw a TypeError.
+ if (
+ method === undefined ||
+ typeof method.next !== 'function'
+ ) {
+ throw webidl.errors.exception({
+ header: prefix,
+ message: `${argument} is not iterable.`
})
}
- if (client[kConnecting]) {
- return
- }
-
- if (!client[kHTTPContext]) {
- connect(client)
- return
- }
+ // https://webidl.spec.whatwg.org/#create-sequence-from-iterable
+ while (true) {
+ const { done, value } = method.next()
- if (client[kHTTPContext].destroyed) {
- return
- }
+ if (done) {
+ break
+ }
- if (client[kHTTPContext].busy(request)) {
- return
+ seq.push(converter(value, prefix, `${argument}[${index++}]`))
}
- if (!request.aborted && client[kHTTPContext].write(request)) {
- client[kPendingIdx]++
- } else {
- client[kQueue].splice(client[kPendingIdx], 1)
- }
+ return seq
}
}
-module.exports = Client
-
-
-/***/ }),
+// https://webidl.spec.whatwg.org/#es-to-record
+webidl.recordConverter = function (keyConverter, valueConverter) {
+ return (O, prefix, argument) => {
+ // 1. If Type(O) is not Object, throw a TypeError.
+ if (webidl.util.Type(O) !== 'Object') {
+ throw webidl.errors.exception({
+ header: prefix,
+ message: `${argument} ("${webidl.util.Type(O)}") is not an Object.`
+ })
+ }
-/***/ 4745:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 2. Let result be a new empty instance of record.
+ const result = {}
+ if (!types.isProxy(O)) {
+ // 1. Let desc be ? O.[[GetOwnProperty]](key).
+ const keys = [...Object.getOwnPropertyNames(O), ...Object.getOwnPropertySymbols(O)]
+ for (const key of keys) {
+ // 1. Let typedKey be key converted to an IDL value of type K.
+ const typedKey = keyConverter(key, prefix, argument)
-const Dispatcher = __nccwpck_require__(2091)
-const {
- ClientDestroyedError,
- ClientClosedError,
- InvalidArgumentError
-} = __nccwpck_require__(8091)
-const { kDestroy, kClose, kClosed, kDestroyed, kDispatch, kInterceptors } = __nccwpck_require__(9411)
+ // 2. Let value be ? Get(O, key).
+ // 3. Let typedValue be value converted to an IDL value of type V.
+ const typedValue = valueConverter(O[key], prefix, argument)
-const kOnDestroyed = Symbol('onDestroyed')
-const kOnClosed = Symbol('onClosed')
-const kInterceptedDispatch = Symbol('Intercepted Dispatch')
+ // 4. Set result[typedKey] to typedValue.
+ result[typedKey] = typedValue
+ }
-class DispatcherBase extends Dispatcher {
- constructor () {
- super()
+ // 5. Return result.
+ return result
+ }
- this[kDestroyed] = false
- this[kOnDestroyed] = null
- this[kClosed] = false
- this[kOnClosed] = []
- }
+ // 3. Let keys be ? O.[[OwnPropertyKeys]]().
+ const keys = Reflect.ownKeys(O)
- get destroyed () {
- return this[kDestroyed]
- }
+ // 4. For each key of keys.
+ for (const key of keys) {
+ // 1. Let desc be ? O.[[GetOwnProperty]](key).
+ const desc = Reflect.getOwnPropertyDescriptor(O, key)
- get closed () {
- return this[kClosed]
- }
+ // 2. If desc is not undefined and desc.[[Enumerable]] is true:
+ if (desc?.enumerable) {
+ // 1. Let typedKey be key converted to an IDL value of type K.
+ const typedKey = keyConverter(key, prefix, argument)
- get interceptors () {
- return this[kInterceptors]
- }
+ // 2. Let value be ? Get(O, key).
+ // 3. Let typedValue be value converted to an IDL value of type V.
+ const typedValue = valueConverter(O[key], prefix, argument)
- set interceptors (newInterceptors) {
- if (newInterceptors) {
- for (let i = newInterceptors.length - 1; i >= 0; i--) {
- const interceptor = this[kInterceptors][i]
- if (typeof interceptor !== 'function') {
- throw new InvalidArgumentError('interceptor must be an function')
- }
+ // 4. Set result[typedKey] to typedValue.
+ result[typedKey] = typedValue
}
}
- this[kInterceptors] = newInterceptors
+ // 5. Return result.
+ return result
}
+}
- close (callback) {
- if (callback === undefined) {
- return new Promise((resolve, reject) => {
- this.close((err, data) => {
- return err ? reject(err) : resolve(data)
- })
+webidl.interfaceConverter = function (i) {
+ return (V, prefix, argument, opts) => {
+ if (opts?.strict !== false && !(V instanceof i)) {
+ throw webidl.errors.exception({
+ header: prefix,
+ message: `Expected ${argument} ("${webidl.util.Stringify(V)}") to be an instance of ${i.name}.`
})
}
- if (typeof callback !== 'function') {
- throw new InvalidArgumentError('invalid callback')
- }
+ return V
+ }
+}
- if (this[kDestroyed]) {
- queueMicrotask(() => callback(new ClientDestroyedError(), null))
- return
- }
+webidl.dictionaryConverter = function (converters) {
+ return (dictionary, prefix, argument) => {
+ const type = webidl.util.Type(dictionary)
+ const dict = {}
- if (this[kClosed]) {
- if (this[kOnClosed]) {
- this[kOnClosed].push(callback)
- } else {
- queueMicrotask(() => callback(null, null))
- }
- return
+ if (type === 'Null' || type === 'Undefined') {
+ return dict
+ } else if (type !== 'Object') {
+ throw webidl.errors.exception({
+ header: prefix,
+ message: `Expected ${dictionary} to be one of: Null, Undefined, Object.`
+ })
}
- this[kClosed] = true
- this[kOnClosed].push(callback)
+ for (const options of converters) {
+ const { key, defaultValue, required, converter } = options
- const onClosed = () => {
- const callbacks = this[kOnClosed]
- this[kOnClosed] = null
- for (let i = 0; i < callbacks.length; i++) {
- callbacks[i](null, null)
+ if (required === true) {
+ if (!Object.hasOwn(dictionary, key)) {
+ throw webidl.errors.exception({
+ header: prefix,
+ message: `Missing required key "${key}".`
+ })
+ }
}
- }
-
- // Should not error.
- this[kClose]()
- .then(() => this.destroy())
- .then(() => {
- queueMicrotask(onClosed)
- })
- }
-
- destroy (err, callback) {
- if (typeof err === 'function') {
- callback = err
- err = null
- }
-
- if (callback === undefined) {
- return new Promise((resolve, reject) => {
- this.destroy(err, (err, data) => {
- return err ? /* istanbul ignore next: should never error */ reject(err) : resolve(data)
- })
- })
- }
- if (typeof callback !== 'function') {
- throw new InvalidArgumentError('invalid callback')
- }
+ let value = dictionary[key]
+ const hasDefault = Object.hasOwn(options, 'defaultValue')
- if (this[kDestroyed]) {
- if (this[kOnDestroyed]) {
- this[kOnDestroyed].push(callback)
- } else {
- queueMicrotask(() => callback(null, null))
+ // Only use defaultValue if value is undefined and
+ // a defaultValue options was provided.
+ if (hasDefault && value !== null) {
+ value ??= defaultValue()
}
- return
- }
- if (!err) {
- err = new ClientDestroyedError()
- }
+ // A key can be optional and have no default value.
+ // When this happens, do not perform a conversion,
+ // and do not assign the key a value.
+ if (required || hasDefault || value !== undefined) {
+ value = converter(value, prefix, `${argument}.${key}`)
- this[kDestroyed] = true
- this[kOnDestroyed] = this[kOnDestroyed] || []
- this[kOnDestroyed].push(callback)
+ if (
+ options.allowedValues &&
+ !options.allowedValues.includes(value)
+ ) {
+ throw webidl.errors.exception({
+ header: prefix,
+ message: `${value} is not an accepted type. Expected one of ${options.allowedValues.join(', ')}.`
+ })
+ }
- const onDestroyed = () => {
- const callbacks = this[kOnDestroyed]
- this[kOnDestroyed] = null
- for (let i = 0; i < callbacks.length; i++) {
- callbacks[i](null, null)
+ dict[key] = value
}
}
- // Should not error.
- this[kDestroy](err).then(() => {
- queueMicrotask(onDestroyed)
- })
+ return dict
}
+}
- [kInterceptedDispatch] (opts, handler) {
- if (!this[kInterceptors] || this[kInterceptors].length === 0) {
- this[kInterceptedDispatch] = this[kDispatch]
- return this[kDispatch](opts, handler)
+webidl.nullableConverter = function (converter) {
+ return (V, prefix, argument) => {
+ if (V === null) {
+ return V
}
- let dispatch = this[kDispatch].bind(this)
- for (let i = this[kInterceptors].length - 1; i >= 0; i--) {
- dispatch = this[kInterceptors][i](dispatch)
- }
- this[kInterceptedDispatch] = dispatch
- return dispatch(opts, handler)
+ return converter(V, prefix, argument)
}
+}
- dispatch (opts, handler) {
- if (!handler || typeof handler !== 'object') {
- throw new InvalidArgumentError('handler must be an object')
- }
-
- try {
- if (!opts || typeof opts !== 'object') {
- throw new InvalidArgumentError('opts must be an object.')
- }
-
- if (this[kDestroyed] || this[kOnDestroyed]) {
- throw new ClientDestroyedError()
- }
+// https://webidl.spec.whatwg.org/#es-DOMString
+webidl.converters.DOMString = function (V, prefix, argument, opts) {
+ // 1. If V is null and the conversion is to an IDL type
+ // associated with the [LegacyNullToEmptyString]
+ // extended attribute, then return the DOMString value
+ // that represents the empty string.
+ if (V === null && opts?.legacyNullToEmptyString) {
+ return ''
+ }
- if (this[kClosed]) {
- throw new ClientClosedError()
- }
+ // 2. Let x be ? ToString(V).
+ if (typeof V === 'symbol') {
+ throw webidl.errors.exception({
+ header: prefix,
+ message: `${argument} is a symbol, which cannot be converted to a DOMString.`
+ })
+ }
- return this[kInterceptedDispatch](opts, handler)
- } catch (err) {
- if (typeof handler.onError !== 'function') {
- throw new InvalidArgumentError('invalid onError method')
- }
+ // 3. Return the IDL DOMString value that represents the
+ // same sequence of code units as the one the
+ // ECMAScript String value x represents.
+ return String(V)
+}
- handler.onError(err)
+// https://webidl.spec.whatwg.org/#es-ByteString
+webidl.converters.ByteString = function (V, prefix, argument) {
+ // 1. Let x be ? ToString(V).
+ // Note: DOMString converter perform ? ToString(V)
+ const x = webidl.converters.DOMString(V, prefix, argument)
- return false
+ // 2. If the value of any element of x is greater than
+ // 255, then throw a TypeError.
+ for (let index = 0; index < x.length; index++) {
+ if (x.charCodeAt(index) > 255) {
+ throw new TypeError(
+ 'Cannot convert argument to a ByteString because the character at ' +
+ `index ${index} has a value of ${x.charCodeAt(index)} which is greater than 255.`
+ )
}
}
-}
-module.exports = DispatcherBase
+ // 3. Return an IDL ByteString value whose length is the
+ // length of x, and where the value of each element is
+ // the value of the corresponding element of x.
+ return x
+}
+// https://webidl.spec.whatwg.org/#es-USVString
+// TODO: rewrite this so we can control the errors thrown
+webidl.converters.USVString = toUSVString
-/***/ }),
+// https://webidl.spec.whatwg.org/#es-boolean
+webidl.converters.boolean = function (V) {
+ // 1. Let x be the result of computing ToBoolean(V).
+ const x = Boolean(V)
-/***/ 2091:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 2. Return the IDL boolean value that is the one that represents
+ // the same truth value as the ECMAScript Boolean value x.
+ return x
+}
+// https://webidl.spec.whatwg.org/#es-any
+webidl.converters.any = function (V) {
+ return V
+}
-const EventEmitter = __nccwpck_require__(8474)
+// https://webidl.spec.whatwg.org/#es-long-long
+webidl.converters['long long'] = function (V, prefix, argument) {
+ // 1. Let x be ? ConvertToInt(V, 64, "signed").
+ const x = webidl.util.ConvertToInt(V, 64, 'signed', undefined, prefix, argument)
-class Dispatcher extends EventEmitter {
- dispatch () {
- throw new Error('not implemented')
- }
+ // 2. Return the IDL long long value that represents
+ // the same numeric value as x.
+ return x
+}
- close () {
- throw new Error('not implemented')
- }
-
- destroy () {
- throw new Error('not implemented')
- }
-
- compose (...args) {
- // So we handle [interceptor1, interceptor2] or interceptor1, interceptor2, ...
- const interceptors = Array.isArray(args[0]) ? args[0] : args
- let dispatch = this.dispatch.bind(this)
-
- for (const interceptor of interceptors) {
- if (interceptor == null) {
- continue
- }
-
- if (typeof interceptor !== 'function') {
- throw new TypeError(`invalid interceptor, expected function received ${typeof interceptor}`)
- }
-
- dispatch = interceptor(dispatch)
-
- if (dispatch == null || typeof dispatch !== 'function' || dispatch.length !== 2) {
- throw new TypeError('invalid interceptor')
- }
- }
+// https://webidl.spec.whatwg.org/#es-unsigned-long-long
+webidl.converters['unsigned long long'] = function (V, prefix, argument) {
+ // 1. Let x be ? ConvertToInt(V, 64, "unsigned").
+ const x = webidl.util.ConvertToInt(V, 64, 'unsigned', undefined, prefix, argument)
- return new ComposedDispatcher(this, dispatch)
- }
+ // 2. Return the IDL unsigned long long value that
+ // represents the same numeric value as x.
+ return x
}
-class ComposedDispatcher extends Dispatcher {
- #dispatcher = null
- #dispatch = null
-
- constructor (dispatcher, dispatch) {
- super()
- this.#dispatcher = dispatcher
- this.#dispatch = dispatch
- }
-
- dispatch (...args) {
- this.#dispatch(...args)
- }
-
- close (...args) {
- return this.#dispatcher.close(...args)
- }
+// https://webidl.spec.whatwg.org/#es-unsigned-long
+webidl.converters['unsigned long'] = function (V, prefix, argument) {
+ // 1. Let x be ? ConvertToInt(V, 32, "unsigned").
+ const x = webidl.util.ConvertToInt(V, 32, 'unsigned', undefined, prefix, argument)
- destroy (...args) {
- return this.#dispatcher.destroy(...args)
- }
+ // 2. Return the IDL unsigned long value that
+ // represents the same numeric value as x.
+ return x
}
-module.exports = Dispatcher
-
-
-/***/ }),
-
-/***/ 7897:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const DispatcherBase = __nccwpck_require__(4745)
-const { kClose, kDestroy, kClosed, kDestroyed, kDispatch, kNoProxyAgent, kHttpProxyAgent, kHttpsProxyAgent } = __nccwpck_require__(9411)
-const ProxyAgent = __nccwpck_require__(9848)
-const Agent = __nccwpck_require__(6261)
+// https://webidl.spec.whatwg.org/#es-unsigned-short
+webidl.converters['unsigned short'] = function (V, prefix, argument, opts) {
+ // 1. Let x be ? ConvertToInt(V, 16, "unsigned").
+ const x = webidl.util.ConvertToInt(V, 16, 'unsigned', opts, prefix, argument)
-const DEFAULT_PORTS = {
- 'http:': 80,
- 'https:': 443
+ // 2. Return the IDL unsigned short value that represents
+ // the same numeric value as x.
+ return x
}
-let experimentalWarned = false
-
-class EnvHttpProxyAgent extends DispatcherBase {
- #noProxyValue = null
- #noProxyEntries = null
- #opts = null
-
- constructor (opts = {}) {
- super()
- this.#opts = opts
-
- if (!experimentalWarned) {
- experimentalWarned = true
- process.emitWarning('EnvHttpProxyAgent is experimental, expect them to change at any time.', {
- code: 'UNDICI-EHPA'
- })
- }
-
- const { httpProxy, httpsProxy, noProxy, ...agentOpts } = opts
-
- this[kNoProxyAgent] = new Agent(agentOpts)
-
- const HTTP_PROXY = httpProxy ?? process.env.http_proxy ?? process.env.HTTP_PROXY
- if (HTTP_PROXY) {
- this[kHttpProxyAgent] = new ProxyAgent({ ...agentOpts, uri: HTTP_PROXY })
- } else {
- this[kHttpProxyAgent] = this[kNoProxyAgent]
- }
-
- const HTTPS_PROXY = httpsProxy ?? process.env.https_proxy ?? process.env.HTTPS_PROXY
- if (HTTPS_PROXY) {
- this[kHttpsProxyAgent] = new ProxyAgent({ ...agentOpts, uri: HTTPS_PROXY })
- } else {
- this[kHttpsProxyAgent] = this[kHttpProxyAgent]
- }
-
- this.#parseNoProxy()
- }
-
- [kDispatch] (opts, handler) {
- const url = new URL(opts.origin)
- const agent = this.#getProxyAgentForUrl(url)
- return agent.dispatch(opts, handler)
- }
-
- async [kClose] () {
- await this[kNoProxyAgent].close()
- if (!this[kHttpProxyAgent][kClosed]) {
- await this[kHttpProxyAgent].close()
- }
- if (!this[kHttpsProxyAgent][kClosed]) {
- await this[kHttpsProxyAgent].close()
- }
+// https://webidl.spec.whatwg.org/#idl-ArrayBuffer
+webidl.converters.ArrayBuffer = function (V, prefix, argument, opts) {
+ // 1. If Type(V) is not Object, or V does not have an
+ // [[ArrayBufferData]] internal slot, then throw a
+ // TypeError.
+ // see: https://tc39.es/ecma262/#sec-properties-of-the-arraybuffer-instances
+ // see: https://tc39.es/ecma262/#sec-properties-of-the-sharedarraybuffer-instances
+ if (
+ webidl.util.Type(V) !== 'Object' ||
+ !types.isAnyArrayBuffer(V)
+ ) {
+ throw webidl.errors.conversionFailed({
+ prefix,
+ argument: `${argument} ("${webidl.util.Stringify(V)}")`,
+ types: ['ArrayBuffer']
+ })
}
- async [kDestroy] (err) {
- await this[kNoProxyAgent].destroy(err)
- if (!this[kHttpProxyAgent][kDestroyed]) {
- await this[kHttpProxyAgent].destroy(err)
- }
- if (!this[kHttpsProxyAgent][kDestroyed]) {
- await this[kHttpsProxyAgent].destroy(err)
- }
+ // 2. If the conversion is not to an IDL type associated
+ // with the [AllowShared] extended attribute, and
+ // IsSharedArrayBuffer(V) is true, then throw a
+ // TypeError.
+ if (opts?.allowShared === false && types.isSharedArrayBuffer(V)) {
+ throw webidl.errors.exception({
+ header: 'ArrayBuffer',
+ message: 'SharedArrayBuffer is not allowed.'
+ })
}
- #getProxyAgentForUrl (url) {
- let { protocol, host: hostname, port } = url
-
- // Stripping ports in this way instead of using parsedUrl.hostname to make
- // sure that the brackets around IPv6 addresses are kept.
- hostname = hostname.replace(/:\d*$/, '').toLowerCase()
- port = Number.parseInt(port, 10) || DEFAULT_PORTS[protocol] || 0
- if (!this.#shouldProxy(hostname, port)) {
- return this[kNoProxyAgent]
- }
- if (protocol === 'https:') {
- return this[kHttpsProxyAgent]
- }
- return this[kHttpProxyAgent]
+ // 3. If the conversion is not to an IDL type associated
+ // with the [AllowResizable] extended attribute, and
+ // IsResizableArrayBuffer(V) is true, then throw a
+ // TypeError.
+ if (V.resizable || V.growable) {
+ throw webidl.errors.exception({
+ header: 'ArrayBuffer',
+ message: 'Received a resizable ArrayBuffer.'
+ })
}
- #shouldProxy (hostname, port) {
- if (this.#noProxyChanged) {
- this.#parseNoProxy()
- }
-
- if (this.#noProxyEntries.length === 0) {
- return true // Always proxy if NO_PROXY is not set or empty.
- }
- if (this.#noProxyValue === '*') {
- return false // Never proxy if wildcard is set.
- }
+ // 4. Return the IDL ArrayBuffer value that is a
+ // reference to the same object as V.
+ return V
+}
- for (let i = 0; i < this.#noProxyEntries.length; i++) {
- const entry = this.#noProxyEntries[i]
- if (entry.port && entry.port !== port) {
- continue // Skip if ports don't match.
- }
- if (!/^[.*]/.test(entry.hostname)) {
- // No wildcards, so don't proxy only if there is not an exact match.
- if (hostname === entry.hostname) {
- return false
- }
- } else {
- // Don't proxy if the hostname ends with the no_proxy host.
- if (hostname.endsWith(entry.hostname.replace(/^\*/, ''))) {
- return false
- }
- }
- }
+webidl.converters.TypedArray = function (V, T, prefix, name, opts) {
+ // 1. Let T be the IDL type V is being converted to.
- return true
+ // 2. If Type(V) is not Object, or V does not have a
+ // [[TypedArrayName]] internal slot with a value
+ // equal to T’s name, then throw a TypeError.
+ if (
+ webidl.util.Type(V) !== 'Object' ||
+ !types.isTypedArray(V) ||
+ V.constructor.name !== T.name
+ ) {
+ throw webidl.errors.conversionFailed({
+ prefix,
+ argument: `${name} ("${webidl.util.Stringify(V)}")`,
+ types: [T.name]
+ })
}
- #parseNoProxy () {
- const noProxyValue = this.#opts.noProxy ?? this.#noProxyEnv
- const noProxySplit = noProxyValue.split(/[,\s]/)
- const noProxyEntries = []
-
- for (let i = 0; i < noProxySplit.length; i++) {
- const entry = noProxySplit[i]
- if (!entry) {
- continue
- }
- const parsed = entry.match(/^(.+):(\d+)$/)
- noProxyEntries.push({
- hostname: (parsed ? parsed[1] : entry).toLowerCase(),
- port: parsed ? Number.parseInt(parsed[2], 10) : 0
- })
- }
-
- this.#noProxyValue = noProxyValue
- this.#noProxyEntries = noProxyEntries
+ // 3. If the conversion is not to an IDL type associated
+ // with the [AllowShared] extended attribute, and
+ // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is
+ // true, then throw a TypeError.
+ if (opts?.allowShared === false && types.isSharedArrayBuffer(V.buffer)) {
+ throw webidl.errors.exception({
+ header: 'ArrayBuffer',
+ message: 'SharedArrayBuffer is not allowed.'
+ })
}
- get #noProxyChanged () {
- if (this.#opts.noProxy !== undefined) {
- return false
- }
- return this.#noProxyValue !== this.#noProxyEnv
+ // 4. If the conversion is not to an IDL type associated
+ // with the [AllowResizable] extended attribute, and
+ // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is
+ // true, then throw a TypeError.
+ if (V.buffer.resizable || V.buffer.growable) {
+ throw webidl.errors.exception({
+ header: 'ArrayBuffer',
+ message: 'Received a resizable ArrayBuffer.'
+ })
}
- get #noProxyEnv () {
- return process.env.no_proxy ?? process.env.NO_PROXY ?? ''
- }
+ // 5. Return the IDL value of type T that is a reference
+ // to the same object as V.
+ return V
}
-module.exports = EnvHttpProxyAgent
-
-
-/***/ }),
-
-/***/ 6524:
-/***/ ((module) => {
-
-/* eslint-disable */
-
-
-
-// Extracted from node/lib/internal/fixed_queue.js
-
-// Currently optimal queue size, tested on V8 6.0 - 6.6. Must be power of two.
-const kSize = 2048;
-const kMask = kSize - 1;
-
-// The FixedQueue is implemented as a singly-linked list of fixed-size
-// circular buffers. It looks something like this:
-//
-// head tail
-// | |
-// v v
-// +-----------+ <-----\ +-----------+ <------\ +-----------+
-// | [null] | \----- | next | \------- | next |
-// +-----------+ +-----------+ +-----------+
-// | item | <-- bottom | item | <-- bottom | [empty] |
-// | item | | item | | [empty] |
-// | item | | item | | [empty] |
-// | item | | item | | [empty] |
-// | item | | item | bottom --> | item |
-// | item | | item | | item |
-// | ... | | ... | | ... |
-// | item | | item | | item |
-// | item | | item | | item |
-// | [empty] | <-- top | item | | item |
-// | [empty] | | item | | item |
-// | [empty] | | [empty] | <-- top top --> | [empty] |
-// +-----------+ +-----------+ +-----------+
-//
-// Or, if there is only one circular buffer, it looks something
-// like either of these:
-//
-// head tail head tail
-// | | | |
-// v v v v
-// +-----------+ +-----------+
-// | [null] | | [null] |
-// +-----------+ +-----------+
-// | [empty] | | item |
-// | [empty] | | item |
-// | item | <-- bottom top --> | [empty] |
-// | item | | [empty] |
-// | [empty] | <-- top bottom --> | item |
-// | [empty] | | item |
-// +-----------+ +-----------+
-//
-// Adding a value means moving `top` forward by one, removing means
-// moving `bottom` forward by one. After reaching the end, the queue
-// wraps around.
-//
-// When `top === bottom` the current queue is empty and when
-// `top + 1 === bottom` it's full. This wastes a single space of storage
-// but allows much quicker checks.
-
-class FixedCircularBuffer {
- constructor() {
- this.bottom = 0;
- this.top = 0;
- this.list = new Array(kSize);
- this.next = null;
- }
-
- isEmpty() {
- return this.top === this.bottom;
+webidl.converters.DataView = function (V, prefix, name, opts) {
+ // 1. If Type(V) is not Object, or V does not have a
+ // [[DataView]] internal slot, then throw a TypeError.
+ if (webidl.util.Type(V) !== 'Object' || !types.isDataView(V)) {
+ throw webidl.errors.exception({
+ header: prefix,
+ message: `${name} is not a DataView.`
+ })
}
- isFull() {
- return ((this.top + 1) & kMask) === this.bottom;
+ // 2. If the conversion is not to an IDL type associated
+ // with the [AllowShared] extended attribute, and
+ // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true,
+ // then throw a TypeError.
+ if (opts?.allowShared === false && types.isSharedArrayBuffer(V.buffer)) {
+ throw webidl.errors.exception({
+ header: 'ArrayBuffer',
+ message: 'SharedArrayBuffer is not allowed.'
+ })
}
- push(data) {
- this.list[this.top] = data;
- this.top = (this.top + 1) & kMask;
+ // 3. If the conversion is not to an IDL type associated
+ // with the [AllowResizable] extended attribute, and
+ // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is
+ // true, then throw a TypeError.
+ if (V.buffer.resizable || V.buffer.growable) {
+ throw webidl.errors.exception({
+ header: 'ArrayBuffer',
+ message: 'Received a resizable ArrayBuffer.'
+ })
}
- shift() {
- const nextItem = this.list[this.bottom];
- if (nextItem === undefined)
- return null;
- this.list[this.bottom] = undefined;
- this.bottom = (this.bottom + 1) & kMask;
- return nextItem;
- }
+ // 4. Return the IDL DataView value that is a reference
+ // to the same object as V.
+ return V
}
-module.exports = class FixedQueue {
- constructor() {
- this.head = this.tail = new FixedCircularBuffer();
- }
-
- isEmpty() {
- return this.head.isEmpty();
+// https://webidl.spec.whatwg.org/#BufferSource
+webidl.converters.BufferSource = function (V, prefix, name, opts) {
+ if (types.isAnyArrayBuffer(V)) {
+ return webidl.converters.ArrayBuffer(V, prefix, name, { ...opts, allowShared: false })
}
- push(data) {
- if (this.head.isFull()) {
- // Head is full: Creates a new queue, sets the old queue's `.next` to it,
- // and sets it as the new main queue.
- this.head = this.head.next = new FixedCircularBuffer();
- }
- this.head.push(data);
+ if (types.isTypedArray(V)) {
+ return webidl.converters.TypedArray(V, V.constructor, prefix, name, { ...opts, allowShared: false })
}
- shift() {
- const tail = this.tail;
- const next = tail.shift();
- if (tail.isEmpty() && tail.next !== null) {
- // If there is another queue, it forms the new tail.
- this.tail = tail.next;
- }
- return next;
+ if (types.isDataView(V)) {
+ return webidl.converters.DataView(V, prefix, name, { ...opts, allowShared: false })
}
-};
-
-
-/***/ }),
-
-/***/ 3272:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
+ throw webidl.errors.conversionFailed({
+ prefix,
+ argument: `${name} ("${webidl.util.Stringify(V)}")`,
+ types: ['BufferSource']
+ })
+}
-const DispatcherBase = __nccwpck_require__(4745)
-const FixedQueue = __nccwpck_require__(6524)
-const { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = __nccwpck_require__(9411)
-const PoolStats = __nccwpck_require__(9686)
+webidl.converters['sequence'] = webidl.sequenceConverter(
+ webidl.converters.ByteString
+)
-const kClients = Symbol('clients')
-const kNeedDrain = Symbol('needDrain')
-const kQueue = Symbol('queue')
-const kClosedResolve = Symbol('closed resolve')
-const kOnDrain = Symbol('onDrain')
-const kOnConnect = Symbol('onConnect')
-const kOnDisconnect = Symbol('onDisconnect')
-const kOnConnectionError = Symbol('onConnectionError')
-const kGetDispatcher = Symbol('get dispatcher')
-const kAddClient = Symbol('add client')
-const kRemoveClient = Symbol('remove client')
-const kStats = Symbol('stats')
+webidl.converters['sequence>'] = webidl.sequenceConverter(
+ webidl.converters['sequence']
+)
-class PoolBase extends DispatcherBase {
- constructor () {
- super()
+webidl.converters['record'] = webidl.recordConverter(
+ webidl.converters.ByteString,
+ webidl.converters.ByteString
+)
- this[kQueue] = new FixedQueue()
- this[kClients] = []
- this[kQueued] = 0
+module.exports = {
+ webidl
+}
- const pool = this
- this[kOnDrain] = function onDrain (origin, targets) {
- const queue = pool[kQueue]
+/***/ }),
- let needDrain = false
+/***/ 2607:
+/***/ ((module) => {
- while (!needDrain) {
- const item = queue.shift()
- if (!item) {
- break
- }
- pool[kQueued]--
- needDrain = !this.dispatch(item.opts, item.handler)
- }
- this[kNeedDrain] = needDrain
- if (!this[kNeedDrain] && pool[kNeedDrain]) {
- pool[kNeedDrain] = false
- pool.emit('drain', origin, [pool, ...targets])
- }
+/**
+ * @see https://encoding.spec.whatwg.org/#concept-encoding-get
+ * @param {string|undefined} label
+ */
+function getEncoding (label) {
+ if (!label) {
+ return 'failure'
+ }
- if (pool[kClosedResolve] && queue.isEmpty()) {
- Promise
- .all(pool[kClients].map(c => c.close()))
- .then(pool[kClosedResolve])
- }
- }
-
- this[kOnConnect] = (origin, targets) => {
- pool.emit('connect', origin, [pool, ...targets])
- }
+ // 1. Remove any leading and trailing ASCII whitespace from label.
+ // 2. If label is an ASCII case-insensitive match for any of the
+ // labels listed in the table below, then return the
+ // corresponding encoding; otherwise return failure.
+ switch (label.trim().toLowerCase()) {
+ case 'unicode-1-1-utf-8':
+ case 'unicode11utf8':
+ case 'unicode20utf8':
+ case 'utf-8':
+ case 'utf8':
+ case 'x-unicode20utf8':
+ return 'UTF-8'
+ case '866':
+ case 'cp866':
+ case 'csibm866':
+ case 'ibm866':
+ return 'IBM866'
+ case 'csisolatin2':
+ case 'iso-8859-2':
+ case 'iso-ir-101':
+ case 'iso8859-2':
+ case 'iso88592':
+ case 'iso_8859-2':
+ case 'iso_8859-2:1987':
+ case 'l2':
+ case 'latin2':
+ return 'ISO-8859-2'
+ case 'csisolatin3':
+ case 'iso-8859-3':
+ case 'iso-ir-109':
+ case 'iso8859-3':
+ case 'iso88593':
+ case 'iso_8859-3':
+ case 'iso_8859-3:1988':
+ case 'l3':
+ case 'latin3':
+ return 'ISO-8859-3'
+ case 'csisolatin4':
+ case 'iso-8859-4':
+ case 'iso-ir-110':
+ case 'iso8859-4':
+ case 'iso88594':
+ case 'iso_8859-4':
+ case 'iso_8859-4:1988':
+ case 'l4':
+ case 'latin4':
+ return 'ISO-8859-4'
+ case 'csisolatincyrillic':
+ case 'cyrillic':
+ case 'iso-8859-5':
+ case 'iso-ir-144':
+ case 'iso8859-5':
+ case 'iso88595':
+ case 'iso_8859-5':
+ case 'iso_8859-5:1988':
+ return 'ISO-8859-5'
+ case 'arabic':
+ case 'asmo-708':
+ case 'csiso88596e':
+ case 'csiso88596i':
+ case 'csisolatinarabic':
+ case 'ecma-114':
+ case 'iso-8859-6':
+ case 'iso-8859-6-e':
+ case 'iso-8859-6-i':
+ case 'iso-ir-127':
+ case 'iso8859-6':
+ case 'iso88596':
+ case 'iso_8859-6':
+ case 'iso_8859-6:1987':
+ return 'ISO-8859-6'
+ case 'csisolatingreek':
+ case 'ecma-118':
+ case 'elot_928':
+ case 'greek':
+ case 'greek8':
+ case 'iso-8859-7':
+ case 'iso-ir-126':
+ case 'iso8859-7':
+ case 'iso88597':
+ case 'iso_8859-7':
+ case 'iso_8859-7:1987':
+ case 'sun_eu_greek':
+ return 'ISO-8859-7'
+ case 'csiso88598e':
+ case 'csisolatinhebrew':
+ case 'hebrew':
+ case 'iso-8859-8':
+ case 'iso-8859-8-e':
+ case 'iso-ir-138':
+ case 'iso8859-8':
+ case 'iso88598':
+ case 'iso_8859-8':
+ case 'iso_8859-8:1988':
+ case 'visual':
+ return 'ISO-8859-8'
+ case 'csiso88598i':
+ case 'iso-8859-8-i':
+ case 'logical':
+ return 'ISO-8859-8-I'
+ case 'csisolatin6':
+ case 'iso-8859-10':
+ case 'iso-ir-157':
+ case 'iso8859-10':
+ case 'iso885910':
+ case 'l6':
+ case 'latin6':
+ return 'ISO-8859-10'
+ case 'iso-8859-13':
+ case 'iso8859-13':
+ case 'iso885913':
+ return 'ISO-8859-13'
+ case 'iso-8859-14':
+ case 'iso8859-14':
+ case 'iso885914':
+ return 'ISO-8859-14'
+ case 'csisolatin9':
+ case 'iso-8859-15':
+ case 'iso8859-15':
+ case 'iso885915':
+ case 'iso_8859-15':
+ case 'l9':
+ return 'ISO-8859-15'
+ case 'iso-8859-16':
+ return 'ISO-8859-16'
+ case 'cskoi8r':
+ case 'koi':
+ case 'koi8':
+ case 'koi8-r':
+ case 'koi8_r':
+ return 'KOI8-R'
+ case 'koi8-ru':
+ case 'koi8-u':
+ return 'KOI8-U'
+ case 'csmacintosh':
+ case 'mac':
+ case 'macintosh':
+ case 'x-mac-roman':
+ return 'macintosh'
+ case 'iso-8859-11':
+ case 'iso8859-11':
+ case 'iso885911':
+ case 'tis-620':
+ case 'windows-874':
+ return 'windows-874'
+ case 'cp1250':
+ case 'windows-1250':
+ case 'x-cp1250':
+ return 'windows-1250'
+ case 'cp1251':
+ case 'windows-1251':
+ case 'x-cp1251':
+ return 'windows-1251'
+ case 'ansi_x3.4-1968':
+ case 'ascii':
+ case 'cp1252':
+ case 'cp819':
+ case 'csisolatin1':
+ case 'ibm819':
+ case 'iso-8859-1':
+ case 'iso-ir-100':
+ case 'iso8859-1':
+ case 'iso88591':
+ case 'iso_8859-1':
+ case 'iso_8859-1:1987':
+ case 'l1':
+ case 'latin1':
+ case 'us-ascii':
+ case 'windows-1252':
+ case 'x-cp1252':
+ return 'windows-1252'
+ case 'cp1253':
+ case 'windows-1253':
+ case 'x-cp1253':
+ return 'windows-1253'
+ case 'cp1254':
+ case 'csisolatin5':
+ case 'iso-8859-9':
+ case 'iso-ir-148':
+ case 'iso8859-9':
+ case 'iso88599':
+ case 'iso_8859-9':
+ case 'iso_8859-9:1989':
+ case 'l5':
+ case 'latin5':
+ case 'windows-1254':
+ case 'x-cp1254':
+ return 'windows-1254'
+ case 'cp1255':
+ case 'windows-1255':
+ case 'x-cp1255':
+ return 'windows-1255'
+ case 'cp1256':
+ case 'windows-1256':
+ case 'x-cp1256':
+ return 'windows-1256'
+ case 'cp1257':
+ case 'windows-1257':
+ case 'x-cp1257':
+ return 'windows-1257'
+ case 'cp1258':
+ case 'windows-1258':
+ case 'x-cp1258':
+ return 'windows-1258'
+ case 'x-mac-cyrillic':
+ case 'x-mac-ukrainian':
+ return 'x-mac-cyrillic'
+ case 'chinese':
+ case 'csgb2312':
+ case 'csiso58gb231280':
+ case 'gb2312':
+ case 'gb_2312':
+ case 'gb_2312-80':
+ case 'gbk':
+ case 'iso-ir-58':
+ case 'x-gbk':
+ return 'GBK'
+ case 'gb18030':
+ return 'gb18030'
+ case 'big5':
+ case 'big5-hkscs':
+ case 'cn-big5':
+ case 'csbig5':
+ case 'x-x-big5':
+ return 'Big5'
+ case 'cseucpkdfmtjapanese':
+ case 'euc-jp':
+ case 'x-euc-jp':
+ return 'EUC-JP'
+ case 'csiso2022jp':
+ case 'iso-2022-jp':
+ return 'ISO-2022-JP'
+ case 'csshiftjis':
+ case 'ms932':
+ case 'ms_kanji':
+ case 'shift-jis':
+ case 'shift_jis':
+ case 'sjis':
+ case 'windows-31j':
+ case 'x-sjis':
+ return 'Shift_JIS'
+ case 'cseuckr':
+ case 'csksc56011987':
+ case 'euc-kr':
+ case 'iso-ir-149':
+ case 'korean':
+ case 'ks_c_5601-1987':
+ case 'ks_c_5601-1989':
+ case 'ksc5601':
+ case 'ksc_5601':
+ case 'windows-949':
+ return 'EUC-KR'
+ case 'csiso2022kr':
+ case 'hz-gb-2312':
+ case 'iso-2022-cn':
+ case 'iso-2022-cn-ext':
+ case 'iso-2022-kr':
+ case 'replacement':
+ return 'replacement'
+ case 'unicodefffe':
+ case 'utf-16be':
+ return 'UTF-16BE'
+ case 'csunicode':
+ case 'iso-10646-ucs-2':
+ case 'ucs-2':
+ case 'unicode':
+ case 'unicodefeff':
+ case 'utf-16':
+ case 'utf-16le':
+ return 'UTF-16LE'
+ case 'x-user-defined':
+ return 'x-user-defined'
+ default: return 'failure'
+ }
+}
- this[kOnDisconnect] = (origin, targets, err) => {
- pool.emit('disconnect', origin, [pool, ...targets], err)
- }
+module.exports = {
+ getEncoding
+}
- this[kOnConnectionError] = (origin, targets, err) => {
- pool.emit('connectionError', origin, [pool, ...targets], err)
- }
- this[kStats] = new PoolStats(this)
- }
+/***/ }),
- get [kBusy] () {
- return this[kNeedDrain]
- }
+/***/ 8355:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- get [kConnected] () {
- return this[kClients].filter(client => client[kConnected]).length
- }
- get [kFree] () {
- return this[kClients].filter(client => client[kConnected] && !client[kNeedDrain]).length
- }
- get [kPending] () {
- let ret = this[kQueued]
- for (const { [kPending]: pending } of this[kClients]) {
- ret += pending
- }
- return ret
- }
+const {
+ staticPropertyDescriptors,
+ readOperation,
+ fireAProgressEvent
+} = __nccwpck_require__(3610)
+const {
+ kState,
+ kError,
+ kResult,
+ kEvents,
+ kAborted
+} = __nccwpck_require__(961)
+const { webidl } = __nccwpck_require__(5893)
+const { kEnumerableProperty } = __nccwpck_require__(3440)
- get [kRunning] () {
- let ret = 0
- for (const { [kRunning]: running } of this[kClients]) {
- ret += running
- }
- return ret
- }
+class FileReader extends EventTarget {
+ constructor () {
+ super()
- get [kSize] () {
- let ret = this[kQueued]
- for (const { [kSize]: size } of this[kClients]) {
- ret += size
+ this[kState] = 'empty'
+ this[kResult] = null
+ this[kError] = null
+ this[kEvents] = {
+ loadend: null,
+ error: null,
+ abort: null,
+ load: null,
+ progress: null,
+ loadstart: null
}
- return ret
}
- get stats () {
- return this[kStats]
- }
+ /**
+ * @see https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer
+ * @param {import('buffer').Blob} blob
+ */
+ readAsArrayBuffer (blob) {
+ webidl.brandCheck(this, FileReader)
- async [kClose] () {
- if (this[kQueue].isEmpty()) {
- await Promise.all(this[kClients].map(c => c.close()))
- } else {
- await new Promise((resolve) => {
- this[kClosedResolve] = resolve
- })
- }
- }
+ webidl.argumentLengthCheck(arguments, 1, 'FileReader.readAsArrayBuffer')
- async [kDestroy] (err) {
- while (true) {
- const item = this[kQueue].shift()
- if (!item) {
- break
- }
- item.handler.onError(err)
- }
+ blob = webidl.converters.Blob(blob, { strict: false })
- await Promise.all(this[kClients].map(c => c.destroy(err)))
+ // The readAsArrayBuffer(blob) method, when invoked,
+ // must initiate a read operation for blob with ArrayBuffer.
+ readOperation(this, blob, 'ArrayBuffer')
}
- [kDispatch] (opts, handler) {
- const dispatcher = this[kGetDispatcher]()
+ /**
+ * @see https://w3c.github.io/FileAPI/#readAsBinaryString
+ * @param {import('buffer').Blob} blob
+ */
+ readAsBinaryString (blob) {
+ webidl.brandCheck(this, FileReader)
- if (!dispatcher) {
- this[kNeedDrain] = true
- this[kQueue].push({ opts, handler })
- this[kQueued]++
- } else if (!dispatcher.dispatch(opts, handler)) {
- dispatcher[kNeedDrain] = true
- this[kNeedDrain] = !this[kGetDispatcher]()
- }
+ webidl.argumentLengthCheck(arguments, 1, 'FileReader.readAsBinaryString')
- return !this[kNeedDrain]
+ blob = webidl.converters.Blob(blob, { strict: false })
+
+ // The readAsBinaryString(blob) method, when invoked,
+ // must initiate a read operation for blob with BinaryString.
+ readOperation(this, blob, 'BinaryString')
}
- [kAddClient] (client) {
- client
- .on('drain', this[kOnDrain])
- .on('connect', this[kOnConnect])
- .on('disconnect', this[kOnDisconnect])
- .on('connectionError', this[kOnConnectionError])
+ /**
+ * @see https://w3c.github.io/FileAPI/#readAsDataText
+ * @param {import('buffer').Blob} blob
+ * @param {string?} encoding
+ */
+ readAsText (blob, encoding = undefined) {
+ webidl.brandCheck(this, FileReader)
- this[kClients].push(client)
+ webidl.argumentLengthCheck(arguments, 1, 'FileReader.readAsText')
- if (this[kNeedDrain]) {
- queueMicrotask(() => {
- if (this[kNeedDrain]) {
- this[kOnDrain](client[kUrl], [this, client])
- }
- })
+ blob = webidl.converters.Blob(blob, { strict: false })
+
+ if (encoding !== undefined) {
+ encoding = webidl.converters.DOMString(encoding, 'FileReader.readAsText', 'encoding')
}
- return this
+ // The readAsText(blob, encoding) method, when invoked,
+ // must initiate a read operation for blob with Text and encoding.
+ readOperation(this, blob, 'Text', encoding)
}
- [kRemoveClient] (client) {
- client.close(() => {
- const idx = this[kClients].indexOf(client)
- if (idx !== -1) {
- this[kClients].splice(idx, 1)
- }
- })
+ /**
+ * @see https://w3c.github.io/FileAPI/#dfn-readAsDataURL
+ * @param {import('buffer').Blob} blob
+ */
+ readAsDataURL (blob) {
+ webidl.brandCheck(this, FileReader)
- this[kNeedDrain] = this[kClients].some(dispatcher => (
- !dispatcher[kNeedDrain] &&
- dispatcher.closed !== true &&
- dispatcher.destroyed !== true
- ))
+ webidl.argumentLengthCheck(arguments, 1, 'FileReader.readAsDataURL')
+
+ blob = webidl.converters.Blob(blob, { strict: false })
+
+ // The readAsDataURL(blob) method, when invoked, must
+ // initiate a read operation for blob with DataURL.
+ readOperation(this, blob, 'DataURL')
}
-}
-module.exports = {
- PoolBase,
- kClients,
- kNeedDrain,
- kAddClient,
- kRemoveClient,
- kGetDispatcher
-}
+ /**
+ * @see https://w3c.github.io/FileAPI/#dfn-abort
+ */
+ abort () {
+ // 1. If this's state is "empty" or if this's state is
+ // "done" set this's result to null and terminate
+ // this algorithm.
+ if (this[kState] === 'empty' || this[kState] === 'done') {
+ this[kResult] = null
+ return
+ }
+ // 2. If this's state is "loading" set this's state to
+ // "done" and set this's result to null.
+ if (this[kState] === 'loading') {
+ this[kState] = 'done'
+ this[kResult] = null
+ }
-/***/ }),
+ // 3. If there are any tasks from this on the file reading
+ // task source in an affiliated task queue, then remove
+ // those tasks from that task queue.
+ this[kAborted] = true
-/***/ 9686:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 4. Terminate the algorithm for the read method being processed.
+ // TODO
-const { kFree, kConnected, kPending, kQueued, kRunning, kSize } = __nccwpck_require__(9411)
-const kPool = Symbol('pool')
+ // 5. Fire a progress event called abort at this.
+ fireAProgressEvent('abort', this)
-class PoolStats {
- constructor (pool) {
- this[kPool] = pool
+ // 6. If this's state is not "loading", fire a progress
+ // event called loadend at this.
+ if (this[kState] !== 'loading') {
+ fireAProgressEvent('loadend', this)
+ }
}
- get connected () {
- return this[kPool][kConnected]
- }
+ /**
+ * @see https://w3c.github.io/FileAPI/#dom-filereader-readystate
+ */
+ get readyState () {
+ webidl.brandCheck(this, FileReader)
- get free () {
- return this[kPool][kFree]
+ switch (this[kState]) {
+ case 'empty': return this.EMPTY
+ case 'loading': return this.LOADING
+ case 'done': return this.DONE
+ }
}
- get pending () {
- return this[kPool][kPending]
- }
+ /**
+ * @see https://w3c.github.io/FileAPI/#dom-filereader-result
+ */
+ get result () {
+ webidl.brandCheck(this, FileReader)
- get queued () {
- return this[kPool][kQueued]
+ // The result attribute’s getter, when invoked, must return
+ // this's result.
+ return this[kResult]
}
- get running () {
- return this[kPool][kRunning]
- }
+ /**
+ * @see https://w3c.github.io/FileAPI/#dom-filereader-error
+ */
+ get error () {
+ webidl.brandCheck(this, FileReader)
- get size () {
- return this[kPool][kSize]
+ // The error attribute’s getter, when invoked, must return
+ // this's error.
+ return this[kError]
}
-}
-
-module.exports = PoolStats
-
-
-/***/ }),
-/***/ 7404:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const {
- PoolBase,
- kClients,
- kNeedDrain,
- kAddClient,
- kGetDispatcher
-} = __nccwpck_require__(3272)
-const Client = __nccwpck_require__(3069)
-const {
- InvalidArgumentError
-} = __nccwpck_require__(8091)
-const util = __nccwpck_require__(1544)
-const { kUrl, kInterceptors } = __nccwpck_require__(9411)
-const buildConnector = __nccwpck_require__(2296)
-
-const kOptions = Symbol('options')
-const kConnections = Symbol('connections')
-const kFactory = Symbol('factory')
-
-function defaultFactory (origin, opts) {
- return new Client(origin, opts)
-}
-
-class Pool extends PoolBase {
- constructor (origin, {
- connections,
- factory = defaultFactory,
- connect,
- connectTimeout,
- tls,
- maxCachedSessions,
- socketPath,
- autoSelectFamily,
- autoSelectFamilyAttemptTimeout,
- allowH2,
- ...options
- } = {}) {
- super()
+ get onloadend () {
+ webidl.brandCheck(this, FileReader)
- if (connections != null && (!Number.isFinite(connections) || connections < 0)) {
- throw new InvalidArgumentError('invalid connections')
- }
+ return this[kEvents].loadend
+ }
- if (typeof factory !== 'function') {
- throw new InvalidArgumentError('factory must be a function.')
- }
+ set onloadend (fn) {
+ webidl.brandCheck(this, FileReader)
- if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {
- throw new InvalidArgumentError('connect must be a function or an object')
+ if (this[kEvents].loadend) {
+ this.removeEventListener('loadend', this[kEvents].loadend)
}
- if (typeof connect !== 'function') {
- connect = buildConnector({
- ...tls,
- maxCachedSessions,
- allowH2,
- socketPath,
- timeout: connectTimeout,
- ...(autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined),
- ...connect
- })
+ if (typeof fn === 'function') {
+ this[kEvents].loadend = fn
+ this.addEventListener('loadend', fn)
+ } else {
+ this[kEvents].loadend = null
}
+ }
- this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool)
- ? options.interceptors.Pool
- : []
- this[kConnections] = connections || null
- this[kUrl] = util.parseOrigin(origin)
- this[kOptions] = { ...util.deepClone(options), connect, allowH2 }
- this[kOptions].interceptors = options.interceptors
- ? { ...options.interceptors }
- : undefined
- this[kFactory] = factory
+ get onerror () {
+ webidl.brandCheck(this, FileReader)
- this.on('connectionError', (origin, targets, error) => {
- // If a connection error occurs, we remove the client from the pool,
- // and emit a connectionError event. They will not be re-used.
- // Fixes https://github.com/nodejs/undici/issues/3895
- for (const target of targets) {
- // Do not use kRemoveClient here, as it will close the client,
- // but the client cannot be closed in this state.
- const idx = this[kClients].indexOf(target)
- if (idx !== -1) {
- this[kClients].splice(idx, 1)
- }
- }
- })
+ return this[kEvents].error
}
- [kGetDispatcher] () {
- for (const client of this[kClients]) {
- if (!client[kNeedDrain]) {
- return client
- }
+ set onerror (fn) {
+ webidl.brandCheck(this, FileReader)
+
+ if (this[kEvents].error) {
+ this.removeEventListener('error', this[kEvents].error)
}
- if (!this[kConnections] || this[kClients].length < this[kConnections]) {
- const dispatcher = this[kFactory](this[kUrl], this[kOptions])
- this[kAddClient](dispatcher)
- return dispatcher
+ if (typeof fn === 'function') {
+ this[kEvents].error = fn
+ this.addEventListener('error', fn)
+ } else {
+ this[kEvents].error = null
}
}
-}
-
-module.exports = Pool
-
-
-/***/ }),
-
-/***/ 9848:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const { kProxy, kClose, kDestroy, kDispatch, kInterceptors } = __nccwpck_require__(9411)
-const { URL } = __nccwpck_require__(3136)
-const Agent = __nccwpck_require__(6261)
-const Pool = __nccwpck_require__(7404)
-const DispatcherBase = __nccwpck_require__(4745)
-const { InvalidArgumentError, RequestAbortedError, SecureProxyConnectionError } = __nccwpck_require__(8091)
-const buildConnector = __nccwpck_require__(2296)
-const Client = __nccwpck_require__(3069)
-
-const kAgent = Symbol('proxy agent')
-const kClient = Symbol('proxy client')
-const kProxyHeaders = Symbol('proxy headers')
-const kRequestTls = Symbol('request tls settings')
-const kProxyTls = Symbol('proxy tls settings')
-const kConnectEndpoint = Symbol('connect endpoint function')
-const kTunnelProxy = Symbol('tunnel proxy')
-
-function defaultProtocolPort (protocol) {
- return protocol === 'https:' ? 443 : 80
-}
-
-function defaultFactory (origin, opts) {
- return new Pool(origin, opts)
-}
-const noop = () => {}
+ get onloadstart () {
+ webidl.brandCheck(this, FileReader)
-function defaultAgentFactory (origin, opts) {
- if (opts.connections === 1) {
- return new Client(origin, opts)
+ return this[kEvents].loadstart
}
- return new Pool(origin, opts)
-}
-class Http1ProxyWrapper extends DispatcherBase {
- #client
+ set onloadstart (fn) {
+ webidl.brandCheck(this, FileReader)
- constructor (proxyUrl, { headers = {}, connect, factory }) {
- super()
- if (!proxyUrl) {
- throw new InvalidArgumentError('Proxy URL is mandatory')
+ if (this[kEvents].loadstart) {
+ this.removeEventListener('loadstart', this[kEvents].loadstart)
}
- this[kProxyHeaders] = headers
- if (factory) {
- this.#client = factory(proxyUrl, { connect })
+ if (typeof fn === 'function') {
+ this[kEvents].loadstart = fn
+ this.addEventListener('loadstart', fn)
} else {
- this.#client = new Client(proxyUrl, { connect })
+ this[kEvents].loadstart = null
}
}
- [kDispatch] (opts, handler) {
- const onHeaders = handler.onHeaders
- handler.onHeaders = function (statusCode, data, resume) {
- if (statusCode === 407) {
- if (typeof handler.onError === 'function') {
- handler.onError(new InvalidArgumentError('Proxy Authentication Required (407)'))
- }
- return
- }
- if (onHeaders) onHeaders.call(this, statusCode, data, resume)
- }
+ get onprogress () {
+ webidl.brandCheck(this, FileReader)
- // Rewrite request as an HTTP1 Proxy request, without tunneling.
- const {
- origin,
- path = '/',
- headers = {}
- } = opts
+ return this[kEvents].progress
+ }
- opts.path = origin + path
+ set onprogress (fn) {
+ webidl.brandCheck(this, FileReader)
- if (!('host' in headers) && !('Host' in headers)) {
- const { host } = new URL(origin)
- headers.host = host
+ if (this[kEvents].progress) {
+ this.removeEventListener('progress', this[kEvents].progress)
}
- opts.headers = { ...this[kProxyHeaders], ...headers }
- return this.#client[kDispatch](opts, handler)
+ if (typeof fn === 'function') {
+ this[kEvents].progress = fn
+ this.addEventListener('progress', fn)
+ } else {
+ this[kEvents].progress = null
+ }
}
- async [kClose] () {
- return this.#client.close()
- }
+ get onload () {
+ webidl.brandCheck(this, FileReader)
- async [kDestroy] (err) {
- return this.#client.destroy(err)
+ return this[kEvents].load
}
-}
-
-class ProxyAgent extends DispatcherBase {
- constructor (opts) {
- super()
- if (!opts || (typeof opts === 'object' && !(opts instanceof URL) && !opts.uri)) {
- throw new InvalidArgumentError('Proxy uri is mandatory')
- }
+ set onload (fn) {
+ webidl.brandCheck(this, FileReader)
- const { clientFactory = defaultFactory } = opts
- if (typeof clientFactory !== 'function') {
- throw new InvalidArgumentError('Proxy opts.clientFactory must be a function.')
+ if (this[kEvents].load) {
+ this.removeEventListener('load', this[kEvents].load)
}
- const { proxyTunnel = true } = opts
-
- const url = this.#getUrl(opts)
- const { href, origin, port, protocol, username, password, hostname: proxyHostname } = url
-
- this[kProxy] = { uri: href, protocol }
- this[kInterceptors] = opts.interceptors?.ProxyAgent && Array.isArray(opts.interceptors.ProxyAgent)
- ? opts.interceptors.ProxyAgent
- : []
- this[kRequestTls] = opts.requestTls
- this[kProxyTls] = opts.proxyTls
- this[kProxyHeaders] = opts.headers || {}
- this[kTunnelProxy] = proxyTunnel
-
- if (opts.auth && opts.token) {
- throw new InvalidArgumentError('opts.auth cannot be used in combination with opts.token')
- } else if (opts.auth) {
- /* @deprecated in favour of opts.token */
- this[kProxyHeaders]['proxy-authorization'] = `Basic ${opts.auth}`
- } else if (opts.token) {
- this[kProxyHeaders]['proxy-authorization'] = opts.token
- } else if (username && password) {
- this[kProxyHeaders]['proxy-authorization'] = `Basic ${Buffer.from(`${decodeURIComponent(username)}:${decodeURIComponent(password)}`).toString('base64')}`
+ if (typeof fn === 'function') {
+ this[kEvents].load = fn
+ this.addEventListener('load', fn)
+ } else {
+ this[kEvents].load = null
}
+ }
- const connect = buildConnector({ ...opts.proxyTls })
- this[kConnectEndpoint] = buildConnector({ ...opts.requestTls })
+ get onabort () {
+ webidl.brandCheck(this, FileReader)
- const agentFactory = opts.factory || defaultAgentFactory
- const factory = (origin, options) => {
- const { protocol } = new URL(origin)
- if (!this[kTunnelProxy] && protocol === 'http:' && this[kProxy].protocol === 'http:') {
- return new Http1ProxyWrapper(this[kProxy].uri, {
- headers: this[kProxyHeaders],
- connect,
- factory: agentFactory
- })
- }
- return agentFactory(origin, options)
- }
- this[kClient] = clientFactory(url, { connect })
- this[kAgent] = new Agent({
- ...opts,
- factory,
- connect: async (opts, callback) => {
- let requestedPath = opts.host
- if (!opts.port) {
- requestedPath += `:${defaultProtocolPort(opts.protocol)}`
- }
- try {
- const { socket, statusCode } = await this[kClient].connect({
- origin,
- port,
- path: requestedPath,
- signal: opts.signal,
- headers: {
- ...this[kProxyHeaders],
- host: opts.host
- },
- servername: this[kProxyTls]?.servername || proxyHostname
- })
- if (statusCode !== 200) {
- socket.on('error', noop).destroy()
- callback(new RequestAbortedError(`Proxy response (${statusCode}) !== 200 when HTTP Tunneling`))
- }
- if (opts.protocol !== 'https:') {
- callback(null, socket)
- return
- }
- let servername
- if (this[kRequestTls]) {
- servername = this[kRequestTls].servername
- } else {
- servername = opts.servername
- }
- this[kConnectEndpoint]({ ...opts, servername, httpSocket: socket }, callback)
- } catch (err) {
- if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') {
- // Throw a custom error to avoid loop in client.js#connect
- callback(new SecureProxyConnectionError(err))
- } else {
- callback(err)
- }
- }
- }
- })
+ return this[kEvents].abort
}
- dispatch (opts, handler) {
- const headers = buildHeaders(opts.headers)
- throwIfProxyAuthIsSent(headers)
+ set onabort (fn) {
+ webidl.brandCheck(this, FileReader)
- if (headers && !('host' in headers) && !('Host' in headers)) {
- const { host } = new URL(opts.origin)
- headers.host = host
+ if (this[kEvents].abort) {
+ this.removeEventListener('abort', this[kEvents].abort)
}
- return this[kAgent].dispatch(
- {
- ...opts,
- headers
- },
- handler
- )
- }
-
- /**
- * @param {import('../types/proxy-agent').ProxyAgent.Options | string | URL} opts
- * @returns {URL}
- */
- #getUrl (opts) {
- if (typeof opts === 'string') {
- return new URL(opts)
- } else if (opts instanceof URL) {
- return opts
+ if (typeof fn === 'function') {
+ this[kEvents].abort = fn
+ this.addEventListener('abort', fn)
} else {
- return new URL(opts.uri)
+ this[kEvents].abort = null
}
}
-
- async [kClose] () {
- await this[kAgent].close()
- await this[kClient].close()
- }
-
- async [kDestroy] () {
- await this[kAgent].destroy()
- await this[kClient].destroy()
- }
}
-/**
- * @param {string[] | Record} headers
- * @returns {Record}
- */
-function buildHeaders (headers) {
- // When using undici.fetch, the headers list is stored
- // as an array.
- if (Array.isArray(headers)) {
- /** @type {Record} */
- const headersPair = {}
-
- for (let i = 0; i < headers.length; i += 2) {
- headersPair[headers[i]] = headers[i + 1]
- }
+// https://w3c.github.io/FileAPI/#dom-filereader-empty
+FileReader.EMPTY = FileReader.prototype.EMPTY = 0
+// https://w3c.github.io/FileAPI/#dom-filereader-loading
+FileReader.LOADING = FileReader.prototype.LOADING = 1
+// https://w3c.github.io/FileAPI/#dom-filereader-done
+FileReader.DONE = FileReader.prototype.DONE = 2
- return headersPair
+Object.defineProperties(FileReader.prototype, {
+ EMPTY: staticPropertyDescriptors,
+ LOADING: staticPropertyDescriptors,
+ DONE: staticPropertyDescriptors,
+ readAsArrayBuffer: kEnumerableProperty,
+ readAsBinaryString: kEnumerableProperty,
+ readAsText: kEnumerableProperty,
+ readAsDataURL: kEnumerableProperty,
+ abort: kEnumerableProperty,
+ readyState: kEnumerableProperty,
+ result: kEnumerableProperty,
+ error: kEnumerableProperty,
+ onloadstart: kEnumerableProperty,
+ onprogress: kEnumerableProperty,
+ onload: kEnumerableProperty,
+ onabort: kEnumerableProperty,
+ onerror: kEnumerableProperty,
+ onloadend: kEnumerableProperty,
+ [Symbol.toStringTag]: {
+ value: 'FileReader',
+ writable: false,
+ enumerable: false,
+ configurable: true
}
+})
- return headers
-}
+Object.defineProperties(FileReader, {
+ EMPTY: staticPropertyDescriptors,
+ LOADING: staticPropertyDescriptors,
+ DONE: staticPropertyDescriptors
+})
-/**
- * @param {Record} headers
- *
- * Previous versions of ProxyAgent suggests the Proxy-Authorization in request headers
- * Nevertheless, it was changed and to avoid a security vulnerability by end users
- * this check was created.
- * It should be removed in the next major version for performance reasons
- */
-function throwIfProxyAuthIsSent (headers) {
- const existProxyAuth = headers && Object.keys(headers)
- .find((key) => key.toLowerCase() === 'proxy-authorization')
- if (existProxyAuth) {
- throw new InvalidArgumentError('Proxy-Authorization should be sent in ProxyAgent constructor')
- }
+module.exports = {
+ FileReader
}
-module.exports = ProxyAgent
-
/***/ }),
-/***/ 1882:
+/***/ 8573:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const Dispatcher = __nccwpck_require__(2091)
-const RetryHandler = __nccwpck_require__(112)
+const { webidl } = __nccwpck_require__(5893)
-class RetryAgent extends Dispatcher {
- #agent = null
- #options = null
- constructor (agent, options = {}) {
- super(options)
- this.#agent = agent
- this.#options = options
- }
+const kState = Symbol('ProgressEvent state')
- dispatch (opts, handler) {
- const retry = new RetryHandler({
- ...opts,
- retryOptions: this.#options
- }, {
- dispatch: this.#agent.dispatch.bind(this.#agent),
- handler
- })
- return this.#agent.dispatch(opts, retry)
- }
+/**
+ * @see https://xhr.spec.whatwg.org/#progressevent
+ */
+class ProgressEvent extends Event {
+ constructor (type, eventInitDict = {}) {
+ type = webidl.converters.DOMString(type, 'ProgressEvent constructor', 'type')
+ eventInitDict = webidl.converters.ProgressEventInit(eventInitDict ?? {})
- close () {
- return this.#agent.close()
- }
+ super(type, eventInitDict)
- destroy () {
- return this.#agent.destroy()
+ this[kState] = {
+ lengthComputable: eventInitDict.lengthComputable,
+ loaded: eventInitDict.loaded,
+ total: eventInitDict.total
+ }
}
-}
-module.exports = RetryAgent
+ get lengthComputable () {
+ webidl.brandCheck(this, ProgressEvent)
+ return this[kState].lengthComputable
+ }
-/***/ }),
-
-/***/ 5837:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
+ get loaded () {
+ webidl.brandCheck(this, ProgressEvent)
+ return this[kState].loaded
+ }
-// We include a version number for the Dispatcher API. In case of breaking changes,
-// this version number must be increased to avoid conflicts.
-const globalDispatcher = Symbol.for('undici.globalDispatcher.1')
-const { InvalidArgumentError } = __nccwpck_require__(8091)
-const Agent = __nccwpck_require__(6261)
+ get total () {
+ webidl.brandCheck(this, ProgressEvent)
-if (getGlobalDispatcher() === undefined) {
- setGlobalDispatcher(new Agent())
+ return this[kState].total
+ }
}
-function setGlobalDispatcher (agent) {
- if (!agent || typeof agent.dispatch !== 'function') {
- throw new InvalidArgumentError('Argument agent must implement Agent')
+webidl.converters.ProgressEventInit = webidl.dictionaryConverter([
+ {
+ key: 'lengthComputable',
+ converter: webidl.converters.boolean,
+ defaultValue: () => false
+ },
+ {
+ key: 'loaded',
+ converter: webidl.converters['unsigned long long'],
+ defaultValue: () => 0
+ },
+ {
+ key: 'total',
+ converter: webidl.converters['unsigned long long'],
+ defaultValue: () => 0
+ },
+ {
+ key: 'bubbles',
+ converter: webidl.converters.boolean,
+ defaultValue: () => false
+ },
+ {
+ key: 'cancelable',
+ converter: webidl.converters.boolean,
+ defaultValue: () => false
+ },
+ {
+ key: 'composed',
+ converter: webidl.converters.boolean,
+ defaultValue: () => false
}
- Object.defineProperty(globalThis, globalDispatcher, {
- value: agent,
- writable: true,
- enumerable: false,
- configurable: false
- })
-}
+])
-function getGlobalDispatcher () {
- return globalThis[globalDispatcher]
+module.exports = {
+ ProgressEvent
}
+
+/***/ }),
+
+/***/ 961:
+/***/ ((module) => {
+
+
+
module.exports = {
- setGlobalDispatcher,
- getGlobalDispatcher
+ kState: Symbol('FileReader state'),
+ kResult: Symbol('FileReader result'),
+ kError: Symbol('FileReader error'),
+ kLastProgressEventFired: Symbol('FileReader last progress event fired timestamp'),
+ kEvents: Symbol('FileReader events'),
+ kAborted: Symbol('FileReader aborted')
}
/***/ }),
-/***/ 7011:
-/***/ ((module) => {
+/***/ 3610:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-module.exports = class DecoratorHandler {
- #handler
+const {
+ kState,
+ kError,
+ kResult,
+ kAborted,
+ kLastProgressEventFired
+} = __nccwpck_require__(961)
+const { ProgressEvent } = __nccwpck_require__(8573)
+const { getEncoding } = __nccwpck_require__(2607)
+const { serializeAMimeType, parseMIMEType } = __nccwpck_require__(1900)
+const { types } = __nccwpck_require__(7975)
+const { StringDecoder } = __nccwpck_require__(3193)
+const { btoa } = __nccwpck_require__(4573)
- constructor (handler) {
- if (typeof handler !== 'object' || handler === null) {
- throw new TypeError('handler must be an object')
- }
- this.#handler = handler
- }
+/** @type {PropertyDescriptor} */
+const staticPropertyDescriptors = {
+ enumerable: true,
+ writable: false,
+ configurable: false
+}
- onConnect (...args) {
- return this.#handler.onConnect?.(...args)
+/**
+ * @see https://w3c.github.io/FileAPI/#readOperation
+ * @param {import('./filereader').FileReader} fr
+ * @param {import('buffer').Blob} blob
+ * @param {string} type
+ * @param {string?} encodingName
+ */
+function readOperation (fr, blob, type, encodingName) {
+ // 1. If fr’s state is "loading", throw an InvalidStateError
+ // DOMException.
+ if (fr[kState] === 'loading') {
+ throw new DOMException('Invalid state', 'InvalidStateError')
}
- onError (...args) {
- return this.#handler.onError?.(...args)
- }
+ // 2. Set fr’s state to "loading".
+ fr[kState] = 'loading'
- onUpgrade (...args) {
- return this.#handler.onUpgrade?.(...args)
- }
+ // 3. Set fr’s result to null.
+ fr[kResult] = null
- onResponseStarted (...args) {
- return this.#handler.onResponseStarted?.(...args)
- }
+ // 4. Set fr’s error to null.
+ fr[kError] = null
- onHeaders (...args) {
- return this.#handler.onHeaders?.(...args)
- }
+ // 5. Let stream be the result of calling get stream on blob.
+ /** @type {import('stream/web').ReadableStream} */
+ const stream = blob.stream()
- onData (...args) {
- return this.#handler.onData?.(...args)
- }
+ // 6. Let reader be the result of getting a reader from stream.
+ const reader = stream.getReader()
- onComplete (...args) {
- return this.#handler.onComplete?.(...args)
- }
+ // 7. Let bytes be an empty byte sequence.
+ /** @type {Uint8Array[]} */
+ const bytes = []
- onBodySent (...args) {
- return this.#handler.onBodySent?.(...args)
- }
-}
+ // 8. Let chunkPromise be the result of reading a chunk from
+ // stream with reader.
+ let chunkPromise = reader.read()
+ // 9. Let isFirstChunk be true.
+ let isFirstChunk = true
-/***/ }),
+ // 10. In parallel, while true:
+ // Note: "In parallel" just means non-blocking
+ // Note 2: readOperation itself cannot be async as double
+ // reading the body would then reject the promise, instead
+ // of throwing an error.
+ ;(async () => {
+ while (!fr[kAborted]) {
+ // 1. Wait for chunkPromise to be fulfilled or rejected.
+ try {
+ const { done, value } = await chunkPromise
-/***/ 5050:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 2. If chunkPromise is fulfilled, and isFirstChunk is
+ // true, queue a task to fire a progress event called
+ // loadstart at fr.
+ if (isFirstChunk && !fr[kAborted]) {
+ queueMicrotask(() => {
+ fireAProgressEvent('loadstart', fr)
+ })
+ }
+ // 3. Set isFirstChunk to false.
+ isFirstChunk = false
+ // 4. If chunkPromise is fulfilled with an object whose
+ // done property is false and whose value property is
+ // a Uint8Array object, run these steps:
+ if (!done && types.isUint8Array(value)) {
+ // 1. Let bs be the byte sequence represented by the
+ // Uint8Array object.
-const util = __nccwpck_require__(1544)
-const { kBodyUsed } = __nccwpck_require__(9411)
-const assert = __nccwpck_require__(4589)
-const { InvalidArgumentError } = __nccwpck_require__(8091)
-const EE = __nccwpck_require__(8474)
+ // 2. Append bs to bytes.
+ bytes.push(value)
-const redirectableStatusCodes = [300, 301, 302, 303, 307, 308]
+ // 3. If roughly 50ms have passed since these steps
+ // were last invoked, queue a task to fire a
+ // progress event called progress at fr.
+ if (
+ (
+ fr[kLastProgressEventFired] === undefined ||
+ Date.now() - fr[kLastProgressEventFired] >= 50
+ ) &&
+ !fr[kAborted]
+ ) {
+ fr[kLastProgressEventFired] = Date.now()
+ queueMicrotask(() => {
+ fireAProgressEvent('progress', fr)
+ })
+ }
-const kBody = Symbol('body')
+ // 4. Set chunkPromise to the result of reading a
+ // chunk from stream with reader.
+ chunkPromise = reader.read()
+ } else if (done) {
+ // 5. Otherwise, if chunkPromise is fulfilled with an
+ // object whose done property is true, queue a task
+ // to run the following steps and abort this algorithm:
+ queueMicrotask(() => {
+ // 1. Set fr’s state to "done".
+ fr[kState] = 'done'
-class BodyAsyncIterable {
- constructor (body) {
- this[kBody] = body
- this[kBodyUsed] = false
- }
+ // 2. Let result be the result of package data given
+ // bytes, type, blob’s type, and encodingName.
+ try {
+ const result = packageData(bytes, type, blob.type, encodingName)
- async * [Symbol.asyncIterator] () {
- assert(!this[kBodyUsed], 'disturbed')
- this[kBodyUsed] = true
- yield * this[kBody]
- }
-}
+ // 4. Else:
-class RedirectHandler {
- constructor (dispatch, maxRedirections, opts, handler) {
- if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {
- throw new InvalidArgumentError('maxRedirections must be a positive number')
- }
+ if (fr[kAborted]) {
+ return
+ }
- util.validateHandler(handler, opts.method, opts.upgrade)
+ // 1. Set fr’s result to result.
+ fr[kResult] = result
- this.dispatch = dispatch
- this.location = null
- this.abort = null
- this.opts = { ...opts, maxRedirections: 0 } // opts must be a copy
- this.maxRedirections = maxRedirections
- this.handler = handler
- this.history = []
- this.redirectionLimitReached = false
+ // 2. Fire a progress event called load at the fr.
+ fireAProgressEvent('load', fr)
+ } catch (error) {
+ // 3. If package data threw an exception error:
- if (util.isStream(this.opts.body)) {
- // TODO (fix): Provide some way for the user to cache the file to e.g. /tmp
- // so that it can be dispatched again?
- // TODO (fix): Do we need 100-expect support to provide a way to do this properly?
- if (util.bodyLength(this.opts.body) === 0) {
- this.opts.body
- .on('data', function () {
- assert(false)
+ // 1. Set fr’s error to error.
+ fr[kError] = error
+
+ // 2. Fire a progress event called error at fr.
+ fireAProgressEvent('error', fr)
+ }
+
+ // 5. If fr’s state is not "loading", fire a progress
+ // event called loadend at the fr.
+ if (fr[kState] !== 'loading') {
+ fireAProgressEvent('loadend', fr)
+ }
})
- }
- if (typeof this.opts.body.readableDidRead !== 'boolean') {
- this.opts.body[kBodyUsed] = false
- EE.prototype.on.call(this.opts.body, 'data', function () {
- this[kBodyUsed] = true
- })
- }
- } else if (this.opts.body && typeof this.opts.body.pipeTo === 'function') {
- // TODO (fix): We can't access ReadableStream internal state
- // to determine whether or not it has been disturbed. This is just
- // a workaround.
- this.opts.body = new BodyAsyncIterable(this.opts.body)
- } else if (
- this.opts.body &&
- typeof this.opts.body !== 'string' &&
- !ArrayBuffer.isView(this.opts.body) &&
- util.isIterable(this.opts.body)
- ) {
- // TODO: Should we allow re-using iterable if !this.opts.idempotent
- // or through some other flag?
- this.opts.body = new BodyAsyncIterable(this.opts.body)
- }
- }
+ break
+ }
+ } catch (error) {
+ if (fr[kAborted]) {
+ return
+ }
- onConnect (abort) {
- this.abort = abort
- this.handler.onConnect(abort, { history: this.history })
- }
+ // 6. Otherwise, if chunkPromise is rejected with an
+ // error error, queue a task to run the following
+ // steps and abort this algorithm:
+ queueMicrotask(() => {
+ // 1. Set fr’s state to "done".
+ fr[kState] = 'done'
- onUpgrade (statusCode, headers, socket) {
- this.handler.onUpgrade(statusCode, headers, socket)
- }
+ // 2. Set fr’s error to error.
+ fr[kError] = error
- onError (error) {
- this.handler.onError(error)
- }
+ // 3. Fire a progress event called error at fr.
+ fireAProgressEvent('error', fr)
- onHeaders (statusCode, headers, resume, statusText) {
- this.location = this.history.length >= this.maxRedirections || util.isDisturbed(this.opts.body)
- ? null
- : parseLocation(statusCode, headers)
+ // 4. If fr’s state is not "loading", fire a progress
+ // event called loadend at fr.
+ if (fr[kState] !== 'loading') {
+ fireAProgressEvent('loadend', fr)
+ }
+ })
- if (this.opts.throwOnMaxRedirect && this.history.length >= this.maxRedirections) {
- if (this.request) {
- this.request.abort(new Error('max redirects'))
+ break
}
-
- this.redirectionLimitReached = true
- this.abort(new Error('max redirects'))
- return
}
+ })()
+}
- if (this.opts.origin) {
- this.history.push(new URL(this.opts.path, this.opts.origin))
- }
+/**
+ * @see https://w3c.github.io/FileAPI/#fire-a-progress-event
+ * @see https://dom.spec.whatwg.org/#concept-event-fire
+ * @param {string} e The name of the event
+ * @param {import('./filereader').FileReader} reader
+ */
+function fireAProgressEvent (e, reader) {
+ // The progress event e does not bubble. e.bubbles must be false
+ // The progress event e is NOT cancelable. e.cancelable must be false
+ const event = new ProgressEvent(e, {
+ bubbles: false,
+ cancelable: false
+ })
- if (!this.location) {
- return this.handler.onHeaders(statusCode, headers, resume, statusText)
- }
+ reader.dispatchEvent(event)
+}
- const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin)))
- const path = search ? `${pathname}${search}` : pathname
+/**
+ * @see https://w3c.github.io/FileAPI/#blob-package-data
+ * @param {Uint8Array[]} bytes
+ * @param {string} type
+ * @param {string?} mimeType
+ * @param {string?} encodingName
+ */
+function packageData (bytes, type, mimeType, encodingName) {
+ // 1. A Blob has an associated package data algorithm, given
+ // bytes, a type, a optional mimeType, and a optional
+ // encodingName, which switches on type and runs the
+ // associated steps:
- // Remove headers referring to the original URL.
- // By default it is Host only, unless it's a 303 (see below), which removes also all Content-* headers.
- // https://tools.ietf.org/html/rfc7231#section-6.4
- this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin)
- this.opts.path = path
- this.opts.origin = origin
- this.opts.maxRedirections = 0
- this.opts.query = null
+ switch (type) {
+ case 'DataURL': {
+ // 1. Return bytes as a DataURL [RFC2397] subject to
+ // the considerations below:
+ // * Use mimeType as part of the Data URL if it is
+ // available in keeping with the Data URL
+ // specification [RFC2397].
+ // * If mimeType is not available return a Data URL
+ // without a media-type. [RFC2397].
- // https://tools.ietf.org/html/rfc7231#section-6.4.4
- // In case of HTTP 303, always replace method to be either HEAD or GET
- if (statusCode === 303 && this.opts.method !== 'HEAD') {
- this.opts.method = 'GET'
- this.opts.body = null
- }
- }
+ // https://datatracker.ietf.org/doc/html/rfc2397#section-3
+ // dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
+ // mediatype := [ type "/" subtype ] *( ";" parameter )
+ // data := *urlchar
+ // parameter := attribute "=" value
+ let dataURL = 'data:'
- onData (chunk) {
- if (this.location) {
- /*
- https://tools.ietf.org/html/rfc7231#section-6.4
+ const parsed = parseMIMEType(mimeType || 'application/octet-stream')
- TLDR: undici always ignores 3xx response bodies.
+ if (parsed !== 'failure') {
+ dataURL += serializeAMimeType(parsed)
+ }
- Redirection is used to serve the requested resource from another URL, so it is assumes that
- no body is generated (and thus can be ignored). Even though generating a body is not prohibited.
+ dataURL += ';base64,'
- For status 301, 302, 303, 307 and 308 (the latter from RFC 7238), the specs mention that the body usually
- (which means it's optional and not mandated) contain just an hyperlink to the value of
- the Location response header, so the body can be ignored safely.
+ const decoder = new StringDecoder('latin1')
- For status 300, which is "Multiple Choices", the spec mentions both generating a Location
- response header AND a response body with the other possible location to follow.
- Since the spec explicitly chooses not to specify a format for such body and leave it to
- servers and browsers implementors, we ignore the body as there is no specified way to eventually parse it.
- */
- } else {
- return this.handler.onData(chunk)
+ for (const chunk of bytes) {
+ dataURL += btoa(decoder.write(chunk))
+ }
+
+ dataURL += btoa(decoder.end())
+
+ return dataURL
}
- }
+ case 'Text': {
+ // 1. Let encoding be failure
+ let encoding = 'failure'
- onComplete (trailers) {
- if (this.location) {
- /*
- https://tools.ietf.org/html/rfc7231#section-6.4
+ // 2. If the encodingName is present, set encoding to the
+ // result of getting an encoding from encodingName.
+ if (encodingName) {
+ encoding = getEncoding(encodingName)
+ }
- TLDR: undici always ignores 3xx response trailers as they are not expected in case of redirections
- and neither are useful if present.
+ // 3. If encoding is failure, and mimeType is present:
+ if (encoding === 'failure' && mimeType) {
+ // 1. Let type be the result of parse a MIME type
+ // given mimeType.
+ const type = parseMIMEType(mimeType)
- See comment on onData method above for more detailed information.
- */
+ // 2. If type is not failure, set encoding to the result
+ // of getting an encoding from type’s parameters["charset"].
+ if (type !== 'failure') {
+ encoding = getEncoding(type.parameters.get('charset'))
+ }
+ }
- this.location = null
- this.abort = null
+ // 4. If encoding is failure, then set encoding to UTF-8.
+ if (encoding === 'failure') {
+ encoding = 'UTF-8'
+ }
- this.dispatch(this.opts, this)
- } else {
- this.handler.onComplete(trailers)
+ // 5. Decode bytes using fallback encoding encoding, and
+ // return the result.
+ return decode(bytes, encoding)
}
- }
+ case 'ArrayBuffer': {
+ // Return a new ArrayBuffer whose contents are bytes.
+ const sequence = combineByteSequences(bytes)
- onBodySent (chunk) {
- if (this.handler.onBodySent) {
- this.handler.onBodySent(chunk)
+ return sequence.buffer
}
- }
-}
+ case 'BinaryString': {
+ // Return bytes as a binary string, in which every byte
+ // is represented by a code unit of equal value [0..255].
+ let binaryString = ''
-function parseLocation (statusCode, headers) {
- if (redirectableStatusCodes.indexOf(statusCode) === -1) {
- return null
- }
+ const decoder = new StringDecoder('latin1')
- for (let i = 0; i < headers.length; i += 2) {
- if (headers[i].length === 8 && util.headerNameToString(headers[i]) === 'location') {
- return headers[i + 1]
+ for (const chunk of bytes) {
+ binaryString += decoder.write(chunk)
+ }
+
+ binaryString += decoder.end()
+
+ return binaryString
}
}
}
-// https://tools.ietf.org/html/rfc7231#section-6.4.4
-function shouldRemoveHeader (header, removeContent, unknownOrigin) {
- if (header.length === 4) {
- return util.headerNameToString(header) === 'host'
- }
- if (removeContent && util.headerNameToString(header).startsWith('content-')) {
- return true
- }
- if (unknownOrigin && (header.length === 13 || header.length === 6 || header.length === 19)) {
- const name = util.headerNameToString(header)
- return name === 'authorization' || name === 'cookie' || name === 'proxy-authorization'
+/**
+ * @see https://encoding.spec.whatwg.org/#decode
+ * @param {Uint8Array[]} ioQueue
+ * @param {string} encoding
+ */
+function decode (ioQueue, encoding) {
+ const bytes = combineByteSequences(ioQueue)
+
+ // 1. Let BOMEncoding be the result of BOM sniffing ioQueue.
+ const BOMEncoding = BOMSniffing(bytes)
+
+ let slice = 0
+
+ // 2. If BOMEncoding is non-null:
+ if (BOMEncoding !== null) {
+ // 1. Set encoding to BOMEncoding.
+ encoding = BOMEncoding
+
+ // 2. Read three bytes from ioQueue, if BOMEncoding is
+ // UTF-8; otherwise read two bytes.
+ // (Do nothing with those bytes.)
+ slice = BOMEncoding === 'UTF-8' ? 3 : 2
}
- return false
+
+ // 3. Process a queue with an instance of encoding’s
+ // decoder, ioQueue, output, and "replacement".
+
+ // 4. Return output.
+
+ const sliced = bytes.slice(slice)
+ return new TextDecoder(encoding).decode(sliced)
}
-// https://tools.ietf.org/html/rfc7231#section-6.4
-function cleanRequestHeaders (headers, removeContent, unknownOrigin) {
- const ret = []
- if (Array.isArray(headers)) {
- for (let i = 0; i < headers.length; i += 2) {
- if (!shouldRemoveHeader(headers[i], removeContent, unknownOrigin)) {
- ret.push(headers[i], headers[i + 1])
- }
- }
- } else if (headers && typeof headers === 'object') {
- for (const key of Object.keys(headers)) {
- if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) {
- ret.push(key, headers[key])
- }
- }
- } else {
- assert(headers == null, 'headers must be an object or an array')
+/**
+ * @see https://encoding.spec.whatwg.org/#bom-sniff
+ * @param {Uint8Array} ioQueue
+ */
+function BOMSniffing (ioQueue) {
+ // 1. Let BOM be the result of peeking 3 bytes from ioQueue,
+ // converted to a byte sequence.
+ const [a, b, c] = ioQueue
+
+ // 2. For each of the rows in the table below, starting with
+ // the first one and going down, if BOM starts with the
+ // bytes given in the first column, then return the
+ // encoding given in the cell in the second column of that
+ // row. Otherwise, return null.
+ if (a === 0xEF && b === 0xBB && c === 0xBF) {
+ return 'UTF-8'
+ } else if (a === 0xFE && b === 0xFF) {
+ return 'UTF-16BE'
+ } else if (a === 0xFF && b === 0xFE) {
+ return 'UTF-16LE'
}
- return ret
+
+ return null
}
-module.exports = RedirectHandler
+/**
+ * @param {Uint8Array[]} sequences
+ */
+function combineByteSequences (sequences) {
+ const size = sequences.reduce((a, b) => {
+ return a + b.byteLength
+ }, 0)
+
+ let offset = 0
+
+ return sequences.reduce((a, b) => {
+ a.set(b, offset)
+ offset += b.byteLength
+ return a
+ }, new Uint8Array(size))
+}
+
+module.exports = {
+ staticPropertyDescriptors,
+ readOperation,
+ fireAProgressEvent
+}
/***/ }),
-/***/ 112:
+/***/ 6897:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const assert = __nccwpck_require__(4589)
-const { kRetryHandlerDefaultRetry } = __nccwpck_require__(9411)
-const { RequestRetryError } = __nccwpck_require__(8091)
+const { uid, states, sentCloseFrameState, emptyBuffer, opcodes } = __nccwpck_require__(736)
const {
- isDisturbed,
- parseHeaders,
- parseRangeHeader,
- wrapRequestBody
-} = __nccwpck_require__(1544)
-
-function calculateRetryAfterHeader (retryAfter) {
- const current = Date.now()
- return new Date(retryAfter).getTime() - current
-}
-
-class RetryHandler {
- constructor (opts, handlers) {
- const { retryOptions, ...dispatchOpts } = opts
- const {
- // Retry scoped
- retry: retryFn,
- maxRetries,
- maxTimeout,
- minTimeout,
- timeoutFactor,
- // Response scoped
- methods,
- errorCodes,
- retryAfter,
- statusCodes
- } = retryOptions ?? {}
+ kReadyState,
+ kSentClose,
+ kByteParser,
+ kReceivedClose,
+ kResponse
+} = __nccwpck_require__(1216)
+const { fireEvent, failWebsocketConnection, isClosing, isClosed, isEstablished, parseExtensions } = __nccwpck_require__(8625)
+const { channels } = __nccwpck_require__(2414)
+const { CloseEvent } = __nccwpck_require__(5188)
+const { makeRequest } = __nccwpck_require__(9967)
+const { fetching } = __nccwpck_require__(4398)
+const { Headers, getHeadersList } = __nccwpck_require__(660)
+const { getDecodeSplit } = __nccwpck_require__(3168)
+const { WebsocketFrameSend } = __nccwpck_require__(3264)
- this.dispatch = handlers.dispatch
- this.handler = handlers.handler
- this.opts = { ...dispatchOpts, body: wrapRequestBody(opts.body) }
- this.abort = null
- this.aborted = false
- this.retryOpts = {
- retry: retryFn ?? RetryHandler[kRetryHandlerDefaultRetry],
- retryAfter: retryAfter ?? true,
- maxTimeout: maxTimeout ?? 30 * 1000, // 30s,
- minTimeout: minTimeout ?? 500, // .5s
- timeoutFactor: timeoutFactor ?? 2,
- maxRetries: maxRetries ?? 5,
- // What errors we should retry
- methods: methods ?? ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE'],
- // Indicates which errors to retry
- statusCodes: statusCodes ?? [500, 502, 503, 504, 429],
- // List of errors to retry
- errorCodes: errorCodes ?? [
- 'ECONNRESET',
- 'ECONNREFUSED',
- 'ENOTFOUND',
- 'ENETDOWN',
- 'ENETUNREACH',
- 'EHOSTDOWN',
- 'EHOSTUNREACH',
- 'EPIPE',
- 'UND_ERR_SOCKET'
- ]
- }
+/** @type {import('crypto')} */
+let crypto
+try {
+ crypto = __nccwpck_require__(7598)
+/* c8 ignore next 3 */
+} catch {
- this.retryCount = 0
- this.retryCountCheckpoint = 0
- this.start = 0
- this.end = null
- this.etag = null
- this.resume = null
+}
- // Handle possible onConnect duplication
- this.handler.onConnect(reason => {
- this.aborted = true
- if (this.abort) {
- this.abort(reason)
- } else {
- this.reason = reason
- }
- })
- }
+/**
+ * @see https://websockets.spec.whatwg.org/#concept-websocket-establish
+ * @param {URL} url
+ * @param {string|string[]} protocols
+ * @param {import('./websocket').WebSocket} ws
+ * @param {(response: any, extensions: string[] | undefined) => void} onEstablish
+ * @param {Partial} options
+ */
+function establishWebSocketConnection (url, protocols, client, ws, onEstablish, options) {
+ // 1. Let requestURL be a copy of url, with its scheme set to "http", if url’s
+ // scheme is "ws", and to "https" otherwise.
+ const requestURL = url
- onRequestSent () {
- if (this.handler.onRequestSent) {
- this.handler.onRequestSent()
- }
- }
+ requestURL.protocol = url.protocol === 'ws:' ? 'http:' : 'https:'
- onUpgrade (statusCode, headers, socket) {
- if (this.handler.onUpgrade) {
- this.handler.onUpgrade(statusCode, headers, socket)
- }
- }
+ // 2. Let request be a new request, whose URL is requestURL, client is client,
+ // service-workers mode is "none", referrer is "no-referrer", mode is
+ // "websocket", credentials mode is "include", cache mode is "no-store" ,
+ // and redirect mode is "error".
+ const request = makeRequest({
+ urlList: [requestURL],
+ client,
+ serviceWorkers: 'none',
+ referrer: 'no-referrer',
+ mode: 'websocket',
+ credentials: 'include',
+ cache: 'no-store',
+ redirect: 'error'
+ })
- onConnect (abort) {
- if (this.aborted) {
- abort(this.reason)
- } else {
- this.abort = abort
- }
- }
+ // Note: undici extension, allow setting custom headers.
+ if (options.headers) {
+ const headersList = getHeadersList(new Headers(options.headers))
- onBodySent (chunk) {
- if (this.handler.onBodySent) return this.handler.onBodySent(chunk)
+ request.headersList = headersList
}
- static [kRetryHandlerDefaultRetry] (err, { state, opts }, cb) {
- const { statusCode, code, headers } = err
- const { method, retryOptions } = opts
- const {
- maxRetries,
- minTimeout,
- maxTimeout,
- timeoutFactor,
- statusCodes,
- errorCodes,
- methods
- } = retryOptions
- const { counter } = state
-
- // Any code that is not a Undici's originated and allowed to retry
- if (code && code !== 'UND_ERR_REQ_RETRY' && !errorCodes.includes(code)) {
- cb(err)
- return
- }
-
- // If a set of method are provided and the current method is not in the list
- if (Array.isArray(methods) && !methods.includes(method)) {
- cb(err)
- return
- }
-
- // If a set of status code are provided and the current status code is not in the list
- if (
- statusCode != null &&
- Array.isArray(statusCodes) &&
- !statusCodes.includes(statusCode)
- ) {
- cb(err)
- return
- }
+ // 3. Append (`Upgrade`, `websocket`) to request’s header list.
+ // 4. Append (`Connection`, `Upgrade`) to request’s header list.
+ // Note: both of these are handled by undici currently.
+ // https://github.com/nodejs/undici/blob/68c269c4144c446f3f1220951338daef4a6b5ec4/lib/client.js#L1397
- // If we reached the max number of retries
- if (counter > maxRetries) {
- cb(err)
- return
- }
+ // 5. Let keyValue be a nonce consisting of a randomly selected
+ // 16-byte value that has been forgiving-base64-encoded and
+ // isomorphic encoded.
+ const keyValue = crypto.randomBytes(16).toString('base64')
- let retryAfterHeader = headers?.['retry-after']
- if (retryAfterHeader) {
- retryAfterHeader = Number(retryAfterHeader)
- retryAfterHeader = Number.isNaN(retryAfterHeader)
- ? calculateRetryAfterHeader(retryAfterHeader)
- : retryAfterHeader * 1e3 // Retry-After is in seconds
- }
+ // 6. Append (`Sec-WebSocket-Key`, keyValue) to request’s
+ // header list.
+ request.headersList.append('sec-websocket-key', keyValue)
- const retryTimeout =
- retryAfterHeader > 0
- ? Math.min(retryAfterHeader, maxTimeout)
- : Math.min(minTimeout * timeoutFactor ** (counter - 1), maxTimeout)
+ // 7. Append (`Sec-WebSocket-Version`, `13`) to request’s
+ // header list.
+ request.headersList.append('sec-websocket-version', '13')
- setTimeout(() => cb(null), retryTimeout)
+ // 8. For each protocol in protocols, combine
+ // (`Sec-WebSocket-Protocol`, protocol) in request’s header
+ // list.
+ for (const protocol of protocols) {
+ request.headersList.append('sec-websocket-protocol', protocol)
}
- onHeaders (statusCode, rawHeaders, resume, statusMessage) {
- const headers = parseHeaders(rawHeaders)
+ // 9. Let permessageDeflate be a user-agent defined
+ // "permessage-deflate" extension header value.
+ // https://github.com/mozilla/gecko-dev/blob/ce78234f5e653a5d3916813ff990f053510227bc/netwerk/protocol/websocket/WebSocketChannel.cpp#L2673
+ const permessageDeflate = 'permessage-deflate; client_max_window_bits'
- this.retryCount += 1
+ // 10. Append (`Sec-WebSocket-Extensions`, permessageDeflate) to
+ // request’s header list.
+ request.headersList.append('sec-websocket-extensions', permessageDeflate)
- if (statusCode >= 300) {
- if (this.retryOpts.statusCodes.includes(statusCode) === false) {
- return this.handler.onHeaders(
- statusCode,
- rawHeaders,
- resume,
- statusMessage
- )
- } else {
- this.abort(
- new RequestRetryError('Request failed', statusCode, {
- headers,
- data: {
- count: this.retryCount
- }
- })
- )
- return false
+ // 11. Fetch request with useParallelQueue set to true, and
+ // processResponse given response being these steps:
+ const controller = fetching({
+ request,
+ useParallelQueue: true,
+ dispatcher: options.dispatcher,
+ processResponse (response) {
+ // 1. If response is a network error or its status is not 101,
+ // fail the WebSocket connection.
+ if (response.type === 'error' || response.status !== 101) {
+ failWebsocketConnection(ws, 'Received network error or non-101 status code.')
+ return
}
- }
- // Checkpoint for resume from where we left it
- if (this.resume != null) {
- this.resume = null
-
- // Only Partial Content 206 supposed to provide Content-Range,
- // any other status code that partially consumed the payload
- // should not be retry because it would result in downstream
- // wrongly concatanete multiple responses.
- if (statusCode !== 206 && (this.start > 0 || statusCode !== 200)) {
- this.abort(
- new RequestRetryError('server does not support the range header and the payload was partially consumed', statusCode, {
- headers,
- data: { count: this.retryCount }
- })
- )
- return false
+ // 2. If protocols is not the empty list and extracting header
+ // list values given `Sec-WebSocket-Protocol` and response’s
+ // header list results in null, failure, or the empty byte
+ // sequence, then fail the WebSocket connection.
+ if (protocols.length !== 0 && !response.headersList.get('Sec-WebSocket-Protocol')) {
+ failWebsocketConnection(ws, 'Server did not respond with sent protocols.')
+ return
}
- const contentRange = parseRangeHeader(headers['content-range'])
- // If no content range
- if (!contentRange) {
- this.abort(
- new RequestRetryError('Content-Range mismatch', statusCode, {
- headers,
- data: { count: this.retryCount }
- })
- )
- return false
- }
+ // 3. Follow the requirements stated step 2 to step 6, inclusive,
+ // of the last set of steps in section 4.1 of The WebSocket
+ // Protocol to validate response. This either results in fail
+ // the WebSocket connection or the WebSocket connection is
+ // established.
- // Let's start with a weak etag check
- if (this.etag != null && this.etag !== headers.etag) {
- this.abort(
- new RequestRetryError('ETag mismatch', statusCode, {
- headers,
- data: { count: this.retryCount }
- })
- )
- return false
+ // 2. If the response lacks an |Upgrade| header field or the |Upgrade|
+ // header field contains a value that is not an ASCII case-
+ // insensitive match for the value "websocket", the client MUST
+ // _Fail the WebSocket Connection_.
+ if (response.headersList.get('Upgrade')?.toLowerCase() !== 'websocket') {
+ failWebsocketConnection(ws, 'Server did not set Upgrade header to "websocket".')
+ return
}
- const { start, size, end = size - 1 } = contentRange
+ // 3. If the response lacks a |Connection| header field or the
+ // |Connection| header field doesn't contain a token that is an
+ // ASCII case-insensitive match for the value "Upgrade", the client
+ // MUST _Fail the WebSocket Connection_.
+ if (response.headersList.get('Connection')?.toLowerCase() !== 'upgrade') {
+ failWebsocketConnection(ws, 'Server did not set Connection header to "upgrade".')
+ return
+ }
- assert(this.start === start, 'content-range mismatch')
- assert(this.end == null || this.end === end, 'content-range mismatch')
+ // 4. If the response lacks a |Sec-WebSocket-Accept| header field or
+ // the |Sec-WebSocket-Accept| contains a value other than the
+ // base64-encoded SHA-1 of the concatenation of the |Sec-WebSocket-
+ // Key| (as a string, not base64-decoded) with the string "258EAFA5-
+ // E914-47DA-95CA-C5AB0DC85B11" but ignoring any leading and
+ // trailing whitespace, the client MUST _Fail the WebSocket
+ // Connection_.
+ const secWSAccept = response.headersList.get('Sec-WebSocket-Accept')
+ const digest = crypto.createHash('sha1').update(keyValue + uid).digest('base64')
+ if (secWSAccept !== digest) {
+ failWebsocketConnection(ws, 'Incorrect hash received in Sec-WebSocket-Accept header.')
+ return
+ }
- this.resume = resume
- return true
- }
+ // 5. If the response includes a |Sec-WebSocket-Extensions| header
+ // field and this header field indicates the use of an extension
+ // that was not present in the client's handshake (the server has
+ // indicated an extension not requested by the client), the client
+ // MUST _Fail the WebSocket Connection_. (The parsing of this
+ // header field to determine which extensions are requested is
+ // discussed in Section 9.1.)
+ const secExtension = response.headersList.get('Sec-WebSocket-Extensions')
+ let extensions
- if (this.end == null) {
- if (statusCode === 206) {
- // First time we receive 206
- const range = parseRangeHeader(headers['content-range'])
+ if (secExtension !== null) {
+ extensions = parseExtensions(secExtension)
- if (range == null) {
- return this.handler.onHeaders(
- statusCode,
- rawHeaders,
- resume,
- statusMessage
- )
+ if (!extensions.has('permessage-deflate')) {
+ failWebsocketConnection(ws, 'Sec-WebSocket-Extensions header does not match.')
+ return
}
+ }
- const { start, size, end = size - 1 } = range
- assert(
- start != null && Number.isFinite(start),
- 'content-range mismatch'
- )
- assert(end != null && Number.isFinite(end), 'invalid content-length')
+ // 6. If the response includes a |Sec-WebSocket-Protocol| header field
+ // and this header field indicates the use of a subprotocol that was
+ // not present in the client's handshake (the server has indicated a
+ // subprotocol not requested by the client), the client MUST _Fail
+ // the WebSocket Connection_.
+ const secProtocol = response.headersList.get('Sec-WebSocket-Protocol')
- this.start = start
- this.end = end
- }
+ if (secProtocol !== null) {
+ const requestProtocols = getDecodeSplit('sec-websocket-protocol', request.headersList)
- // We make our best to checkpoint the body for further range headers
- if (this.end == null) {
- const contentLength = headers['content-length']
- this.end = contentLength != null ? Number(contentLength) - 1 : null
+ // The client can request that the server use a specific subprotocol by
+ // including the |Sec-WebSocket-Protocol| field in its handshake. If it
+ // is specified, the server needs to include the same field and one of
+ // the selected subprotocol values in its response for the connection to
+ // be established.
+ if (!requestProtocols.includes(secProtocol)) {
+ failWebsocketConnection(ws, 'Protocol was not set in the opening handshake.')
+ return
+ }
}
- assert(Number.isFinite(this.start))
- assert(
- this.end == null || Number.isFinite(this.end),
- 'invalid content-length'
- )
-
- this.resume = resume
- this.etag = headers.etag != null ? headers.etag : null
+ response.socket.on('data', onSocketData)
+ response.socket.on('close', onSocketClose)
+ response.socket.on('error', onSocketError)
- // Weak etags are not useful for comparison nor cache
- // for instance not safe to assume if the response is byte-per-byte
- // equal
- if (this.etag != null && this.etag.startsWith('W/')) {
- this.etag = null
+ if (channels.open.hasSubscribers) {
+ channels.open.publish({
+ address: response.socket.address(),
+ protocol: secProtocol,
+ extensions: secExtension
+ })
}
- return this.handler.onHeaders(
- statusCode,
- rawHeaders,
- resume,
- statusMessage
- )
+ onEstablish(response, extensions)
}
+ })
- const err = new RequestRetryError('Request failed', statusCode, {
- headers,
- data: { count: this.retryCount }
- })
-
- this.abort(err)
-
- return false
- }
+ return controller
+}
- onData (chunk) {
- this.start += chunk.length
+function closeWebSocketConnection (ws, code, reason, reasonByteLength) {
+ if (isClosing(ws) || isClosed(ws)) {
+ // If this's ready state is CLOSING (2) or CLOSED (3)
+ // Do nothing.
+ } else if (!isEstablished(ws)) {
+ // If the WebSocket connection is not yet established
+ // Fail the WebSocket connection and set this's ready state
+ // to CLOSING (2).
+ failWebsocketConnection(ws, 'Connection was closed before it was established.')
+ ws[kReadyState] = states.CLOSING
+ } else if (ws[kSentClose] === sentCloseFrameState.NOT_SENT) {
+ // If the WebSocket closing handshake has not yet been started
+ // Start the WebSocket closing handshake and set this's ready
+ // state to CLOSING (2).
+ // - If neither code nor reason is present, the WebSocket Close
+ // message must not have a body.
+ // - If code is present, then the status code to use in the
+ // WebSocket Close message must be the integer given by code.
+ // - If reason is also present, then reasonBytes must be
+ // provided in the Close message after the status code.
- return this.handler.onData(chunk)
- }
+ ws[kSentClose] = sentCloseFrameState.PROCESSING
- onComplete (rawTrailers) {
- this.retryCount = 0
- return this.handler.onComplete(rawTrailers)
- }
+ const frame = new WebsocketFrameSend()
- onError (err) {
- if (this.aborted || isDisturbed(this.opts.body)) {
- return this.handler.onError(err)
- }
+ // If neither code nor reason is present, the WebSocket Close
+ // message must not have a body.
- // We reconcile in case of a mix between network errors
- // and server error response
- if (this.retryCount - this.retryCountCheckpoint > 0) {
- // We count the difference between the last checkpoint and the current retry count
- this.retryCount =
- this.retryCountCheckpoint +
- (this.retryCount - this.retryCountCheckpoint)
+ // If code is present, then the status code to use in the
+ // WebSocket Close message must be the integer given by code.
+ if (code !== undefined && reason === undefined) {
+ frame.frameData = Buffer.allocUnsafe(2)
+ frame.frameData.writeUInt16BE(code, 0)
+ } else if (code !== undefined && reason !== undefined) {
+ // If reason is also present, then reasonBytes must be
+ // provided in the Close message after the status code.
+ frame.frameData = Buffer.allocUnsafe(2 + reasonByteLength)
+ frame.frameData.writeUInt16BE(code, 0)
+ // the body MAY contain UTF-8-encoded data with value /reason/
+ frame.frameData.write(reason, 2, 'utf-8')
} else {
- this.retryCount += 1
+ frame.frameData = emptyBuffer
}
- this.retryOpts.retry(
- err,
- {
- state: { counter: this.retryCount },
- opts: { retryOptions: this.retryOpts, ...this.opts }
- },
- onRetry.bind(this)
- )
-
- function onRetry (err) {
- if (err != null || this.aborted || isDisturbed(this.opts.body)) {
- return this.handler.onError(err)
- }
+ /** @type {import('stream').Duplex} */
+ const socket = ws[kResponse].socket
- if (this.start !== 0) {
- const headers = { range: `bytes=${this.start}-${this.end ?? ''}` }
+ socket.write(frame.createFrame(opcodes.CLOSE))
- // Weak etag check - weak etags will make comparison algorithms never match
- if (this.etag != null) {
- headers['if-match'] = this.etag
- }
+ ws[kSentClose] = sentCloseFrameState.SENT
- this.opts = {
- ...this.opts,
- headers: {
- ...this.opts.headers,
- ...headers
- }
- }
- }
+ // Upon either sending or receiving a Close control frame, it is said
+ // that _The WebSocket Closing Handshake is Started_ and that the
+ // WebSocket connection is in the CLOSING state.
+ ws[kReadyState] = states.CLOSING
+ } else {
+ // Otherwise
+ // Set this's ready state to CLOSING (2).
+ ws[kReadyState] = states.CLOSING
+ }
+}
- try {
- this.retryCountCheckpoint = this.retryCount
- this.dispatch(this.opts, this)
- } catch (err) {
- this.handler.onError(err)
- }
- }
+/**
+ * @param {Buffer} chunk
+ */
+function onSocketData (chunk) {
+ if (!this.ws[kByteParser].write(chunk)) {
+ this.pause()
}
}
-module.exports = RetryHandler
+/**
+ * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
+ * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4
+ */
+function onSocketClose () {
+ const { ws } = this
+ const { [kResponse]: response } = ws
+ response.socket.off('data', onSocketData)
+ response.socket.off('close', onSocketClose)
+ response.socket.off('error', onSocketError)
-/***/ }),
+ // If the TCP connection was closed after the
+ // WebSocket closing handshake was completed, the WebSocket connection
+ // is said to have been closed _cleanly_.
+ const wasClean = ws[kSentClose] === sentCloseFrameState.SENT && ws[kReceivedClose]
-/***/ 7251:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ let code = 1005
+ let reason = ''
+ const result = ws[kByteParser].closingInfo
-const { isIP } = __nccwpck_require__(7030)
-const { lookup } = __nccwpck_require__(610)
-const DecoratorHandler = __nccwpck_require__(7011)
-const { InvalidArgumentError, InformationalError } = __nccwpck_require__(8091)
-const maxInt = Math.pow(2, 31) - 1
+ if (result && !result.error) {
+ code = result.code ?? 1005
+ reason = result.reason
+ } else if (!ws[kReceivedClose]) {
+ // If _The WebSocket
+ // Connection is Closed_ and no Close control frame was received by the
+ // endpoint (such as could occur if the underlying transport connection
+ // is lost), _The WebSocket Connection Close Code_ is considered to be
+ // 1006.
+ code = 1006
+ }
-class DNSInstance {
- #maxTTL = 0
- #maxItems = 0
- #records = new Map()
- dualStack = true
- affinity = null
- lookup = null
- pick = null
+ // 1. Change the ready state to CLOSED (3).
+ ws[kReadyState] = states.CLOSED
- constructor (opts) {
- this.#maxTTL = opts.maxTTL
- this.#maxItems = opts.maxItems
- this.dualStack = opts.dualStack
- this.affinity = opts.affinity
- this.lookup = opts.lookup ?? this.#defaultLookup
- this.pick = opts.pick ?? this.#defaultPick
- }
+ // 2. If the user agent was required to fail the WebSocket
+ // connection, or if the WebSocket connection was closed
+ // after being flagged as full, fire an event named error
+ // at the WebSocket object.
+ // TODO
- get full () {
- return this.#records.size === this.#maxItems
+ // 3. Fire an event named close at the WebSocket object,
+ // using CloseEvent, with the wasClean attribute
+ // initialized to true if the connection closed cleanly
+ // and false otherwise, the code attribute initialized to
+ // the WebSocket connection close code, and the reason
+ // attribute initialized to the result of applying UTF-8
+ // decode without BOM to the WebSocket connection close
+ // reason.
+ // TODO: process.nextTick
+ fireEvent('close', ws, (type, init) => new CloseEvent(type, init), {
+ wasClean, code, reason
+ })
+
+ if (channels.close.hasSubscribers) {
+ channels.close.publish({
+ websocket: ws,
+ code,
+ reason
+ })
}
+}
- runLookup (origin, opts, cb) {
- const ips = this.#records.get(origin.hostname)
+function onSocketError (error) {
+ const { ws } = this
- // If full, we just return the origin
- if (ips == null && this.full) {
- cb(null, origin.origin)
- return
- }
+ ws[kReadyState] = states.CLOSING
- const newOpts = {
- affinity: this.affinity,
- dualStack: this.dualStack,
- lookup: this.lookup,
- pick: this.pick,
- ...opts.dns,
- maxTTL: this.#maxTTL,
- maxItems: this.#maxItems
- }
+ if (channels.socketError.hasSubscribers) {
+ channels.socketError.publish(error)
+ }
- // If no IPs we lookup
- if (ips == null) {
- this.lookup(origin, newOpts, (err, addresses) => {
- if (err || addresses == null || addresses.length === 0) {
- cb(err ?? new InformationalError('No DNS entries found'))
- return
- }
+ this.destroy()
+}
- this.setRecords(origin, addresses)
- const records = this.#records.get(origin.hostname)
+module.exports = {
+ establishWebSocketConnection,
+ closeWebSocketConnection
+}
- const ip = this.pick(
- origin,
- records,
- newOpts.affinity
- )
- let port
- if (typeof ip.port === 'number') {
- port = `:${ip.port}`
- } else if (origin.port !== '') {
- port = `:${origin.port}`
- } else {
- port = ''
- }
+/***/ }),
- cb(
- null,
- `${origin.protocol}//${
- ip.family === 6 ? `[${ip.address}]` : ip.address
- }${port}`
- )
- })
- } else {
- // If there's IPs we pick
- const ip = this.pick(
- origin,
- ips,
- newOpts.affinity
- )
+/***/ 736:
+/***/ ((module) => {
- // If no IPs we lookup - deleting old records
- if (ip == null) {
- this.#records.delete(origin.hostname)
- this.runLookup(origin, opts, cb)
- return
- }
- let port
- if (typeof ip.port === 'number') {
- port = `:${ip.port}`
- } else if (origin.port !== '') {
- port = `:${origin.port}`
- } else {
- port = ''
- }
- cb(
- null,
- `${origin.protocol}//${
- ip.family === 6 ? `[${ip.address}]` : ip.address
- }${port}`
- )
- }
- }
+// This is a Globally Unique Identifier unique used
+// to validate that the endpoint accepts websocket
+// connections.
+// See https://www.rfc-editor.org/rfc/rfc6455.html#section-1.3
+const uid = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
- #defaultLookup (origin, opts, cb) {
- lookup(
- origin.hostname,
- {
- all: true,
- family: this.dualStack === false ? this.affinity : 0,
- order: 'ipv4first'
- },
- (err, addresses) => {
- if (err) {
- return cb(err)
- }
+/** @type {PropertyDescriptor} */
+const staticPropertyDescriptors = {
+ enumerable: true,
+ writable: false,
+ configurable: false
+}
- const results = new Map()
+const states = {
+ CONNECTING: 0,
+ OPEN: 1,
+ CLOSING: 2,
+ CLOSED: 3
+}
- for (const addr of addresses) {
- // On linux we found duplicates, we attempt to remove them with
- // the latest record
- results.set(`${addr.address}:${addr.family}`, addr)
- }
+const sentCloseFrameState = {
+ NOT_SENT: 0,
+ PROCESSING: 1,
+ SENT: 2
+}
- cb(null, results.values())
- }
- )
- }
+const opcodes = {
+ CONTINUATION: 0x0,
+ TEXT: 0x1,
+ BINARY: 0x2,
+ CLOSE: 0x8,
+ PING: 0x9,
+ PONG: 0xA
+}
- #defaultPick (origin, hostnameRecords, affinity) {
- let ip = null
- const { records, offset } = hostnameRecords
+const maxUnsigned16Bit = 2 ** 16 - 1 // 65535
- let family
- if (this.dualStack) {
- if (affinity == null) {
- // Balance between ip families
- if (offset == null || offset === maxInt) {
- hostnameRecords.offset = 0
- affinity = 4
- } else {
- hostnameRecords.offset++
- affinity = (hostnameRecords.offset & 1) === 1 ? 6 : 4
- }
- }
+const parserStates = {
+ INFO: 0,
+ PAYLOADLENGTH_16: 2,
+ PAYLOADLENGTH_64: 3,
+ READ_DATA: 4
+}
- if (records[affinity] != null && records[affinity].ips.length > 0) {
- family = records[affinity]
- } else {
- family = records[affinity === 4 ? 6 : 4]
- }
- } else {
- family = records[affinity]
- }
+const emptyBuffer = Buffer.allocUnsafe(0)
- // If no IPs we return null
- if (family == null || family.ips.length === 0) {
- return ip
- }
+const sendHints = {
+ string: 1,
+ typedArray: 2,
+ arrayBuffer: 3,
+ blob: 4
+}
- if (family.offset == null || family.offset === maxInt) {
- family.offset = 0
- } else {
- family.offset++
- }
+module.exports = {
+ uid,
+ sentCloseFrameState,
+ staticPropertyDescriptors,
+ states,
+ opcodes,
+ maxUnsigned16Bit,
+ parserStates,
+ emptyBuffer,
+ sendHints
+}
- const position = family.offset % family.ips.length
- ip = family.ips[position] ?? null
- if (ip == null) {
- return ip
- }
+/***/ }),
- if (Date.now() - ip.timestamp > ip.ttl) { // record TTL is already in ms
- // We delete expired records
- // It is possible that they have different TTL, so we manage them individually
- family.ips.splice(position, 1)
- return this.pick(origin, hostnameRecords, affinity)
- }
+/***/ 5188:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- return ip
- }
- setRecords (origin, addresses) {
- const timestamp = Date.now()
- const records = { records: { 4: null, 6: null } }
- for (const record of addresses) {
- record.timestamp = timestamp
- if (typeof record.ttl === 'number') {
- // The record TTL is expected to be in ms
- record.ttl = Math.min(record.ttl, this.#maxTTL)
- } else {
- record.ttl = this.#maxTTL
- }
- const familyRecords = records.records[record.family] ?? { ips: [] }
+const { webidl } = __nccwpck_require__(5893)
+const { kEnumerableProperty } = __nccwpck_require__(3440)
+const { kConstruct } = __nccwpck_require__(6443)
+const { MessagePort } = __nccwpck_require__(5919)
- familyRecords.ips.push(record)
- records.records[record.family] = familyRecords
+/**
+ * @see https://html.spec.whatwg.org/multipage/comms.html#messageevent
+ */
+class MessageEvent extends Event {
+ #eventInit
+
+ constructor (type, eventInitDict = {}) {
+ if (type === kConstruct) {
+ super(arguments[1], arguments[2])
+ webidl.util.markAsUncloneable(this)
+ return
}
- this.#records.set(origin.hostname, records)
- }
+ const prefix = 'MessageEvent constructor'
+ webidl.argumentLengthCheck(arguments, 1, prefix)
- getHandler (meta, opts) {
- return new DNSDispatchHandler(this, meta, opts)
+ type = webidl.converters.DOMString(type, prefix, 'type')
+ eventInitDict = webidl.converters.MessageEventInit(eventInitDict, prefix, 'eventInitDict')
+
+ super(type, eventInitDict)
+
+ this.#eventInit = eventInitDict
+ webidl.util.markAsUncloneable(this)
}
-}
-class DNSDispatchHandler extends DecoratorHandler {
- #state = null
- #opts = null
- #dispatch = null
- #handler = null
- #origin = null
+ get data () {
+ webidl.brandCheck(this, MessageEvent)
- constructor (state, { origin, handler, dispatch }, opts) {
- super(handler)
- this.#origin = origin
- this.#handler = handler
- this.#opts = { ...opts }
- this.#state = state
- this.#dispatch = dispatch
+ return this.#eventInit.data
}
- onError (err) {
- switch (err.code) {
- case 'ETIMEDOUT':
- case 'ECONNREFUSED': {
- if (this.#state.dualStack) {
- // We delete the record and retry
- this.#state.runLookup(this.#origin, this.#opts, (err, newOrigin) => {
- if (err) {
- return this.#handler.onError(err)
- }
+ get origin () {
+ webidl.brandCheck(this, MessageEvent)
- const dispatchOpts = {
- ...this.#opts,
- origin: newOrigin
- }
+ return this.#eventInit.origin
+ }
- this.#dispatch(dispatchOpts, this)
- })
+ get lastEventId () {
+ webidl.brandCheck(this, MessageEvent)
- // if dual-stack disabled, we error out
- return
- }
+ return this.#eventInit.lastEventId
+ }
- this.#handler.onError(err)
- return
- }
- case 'ENOTFOUND':
- this.#state.deleteRecord(this.#origin)
- // eslint-disable-next-line no-fallthrough
- default:
- this.#handler.onError(err)
- break
- }
+ get source () {
+ webidl.brandCheck(this, MessageEvent)
+
+ return this.#eventInit.source
}
-}
-module.exports = interceptorOpts => {
- if (
- interceptorOpts?.maxTTL != null &&
- (typeof interceptorOpts?.maxTTL !== 'number' || interceptorOpts?.maxTTL < 0)
- ) {
- throw new InvalidArgumentError('Invalid maxTTL. Must be a positive number')
- }
+ get ports () {
+ webidl.brandCheck(this, MessageEvent)
- if (
- interceptorOpts?.maxItems != null &&
- (typeof interceptorOpts?.maxItems !== 'number' ||
- interceptorOpts?.maxItems < 1)
- ) {
- throw new InvalidArgumentError(
- 'Invalid maxItems. Must be a positive number and greater than zero'
- )
- }
+ if (!Object.isFrozen(this.#eventInit.ports)) {
+ Object.freeze(this.#eventInit.ports)
+ }
- if (
- interceptorOpts?.affinity != null &&
- interceptorOpts?.affinity !== 4 &&
- interceptorOpts?.affinity !== 6
- ) {
- throw new InvalidArgumentError('Invalid affinity. Must be either 4 or 6')
+ return this.#eventInit.ports
}
- if (
- interceptorOpts?.dualStack != null &&
- typeof interceptorOpts?.dualStack !== 'boolean'
+ initMessageEvent (
+ type,
+ bubbles = false,
+ cancelable = false,
+ data = null,
+ origin = '',
+ lastEventId = '',
+ source = null,
+ ports = []
) {
- throw new InvalidArgumentError('Invalid dualStack. Must be a boolean')
- }
+ webidl.brandCheck(this, MessageEvent)
- if (
- interceptorOpts?.lookup != null &&
- typeof interceptorOpts?.lookup !== 'function'
- ) {
- throw new InvalidArgumentError('Invalid lookup. Must be a function')
- }
+ webidl.argumentLengthCheck(arguments, 1, 'MessageEvent.initMessageEvent')
- if (
- interceptorOpts?.pick != null &&
- typeof interceptorOpts?.pick !== 'function'
- ) {
- throw new InvalidArgumentError('Invalid pick. Must be a function')
+ return new MessageEvent(type, {
+ bubbles, cancelable, data, origin, lastEventId, source, ports
+ })
}
- const dualStack = interceptorOpts?.dualStack ?? true
- let affinity
- if (dualStack) {
- affinity = interceptorOpts?.affinity ?? null
- } else {
- affinity = interceptorOpts?.affinity ?? 4
+ static createFastMessageEvent (type, init) {
+ const messageEvent = new MessageEvent(kConstruct, type, init)
+ messageEvent.#eventInit = init
+ messageEvent.#eventInit.data ??= null
+ messageEvent.#eventInit.origin ??= ''
+ messageEvent.#eventInit.lastEventId ??= ''
+ messageEvent.#eventInit.source ??= null
+ messageEvent.#eventInit.ports ??= []
+ return messageEvent
}
+}
- const opts = {
- maxTTL: interceptorOpts?.maxTTL ?? 10e3, // Expressed in ms
- lookup: interceptorOpts?.lookup ?? null,
- pick: interceptorOpts?.pick ?? null,
- dualStack,
- affinity,
- maxItems: interceptorOpts?.maxItems ?? Infinity
- }
+const { createFastMessageEvent } = MessageEvent
+delete MessageEvent.createFastMessageEvent
- const instance = new DNSInstance(opts)
+/**
+ * @see https://websockets.spec.whatwg.org/#the-closeevent-interface
+ */
+class CloseEvent extends Event {
+ #eventInit
- return dispatch => {
- return function dnsInterceptor (origDispatchOpts, handler) {
- const origin =
- origDispatchOpts.origin.constructor === URL
- ? origDispatchOpts.origin
- : new URL(origDispatchOpts.origin)
+ constructor (type, eventInitDict = {}) {
+ const prefix = 'CloseEvent constructor'
+ webidl.argumentLengthCheck(arguments, 1, prefix)
- if (isIP(origin.hostname) !== 0) {
- return dispatch(origDispatchOpts, handler)
- }
+ type = webidl.converters.DOMString(type, prefix, 'type')
+ eventInitDict = webidl.converters.CloseEventInit(eventInitDict)
- instance.runLookup(origin, origDispatchOpts, (err, newOrigin) => {
- if (err) {
- return handler.onError(err)
- }
+ super(type, eventInitDict)
- let dispatchOpts = null
- dispatchOpts = {
- ...origDispatchOpts,
- servername: origin.hostname, // For SNI on TLS
- origin: newOrigin,
- headers: {
- host: origin.hostname,
- ...origDispatchOpts.headers
- }
- }
+ this.#eventInit = eventInitDict
+ webidl.util.markAsUncloneable(this)
+ }
- dispatch(
- dispatchOpts,
- instance.getHandler({ origin, dispatch, handler }, origDispatchOpts)
- )
- })
+ get wasClean () {
+ webidl.brandCheck(this, CloseEvent)
- return true
- }
+ return this.#eventInit.wasClean
}
-}
+ get code () {
+ webidl.brandCheck(this, CloseEvent)
-/***/ }),
-
-/***/ 2375:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ return this.#eventInit.code
+ }
+ get reason () {
+ webidl.brandCheck(this, CloseEvent)
+ return this.#eventInit.reason
+ }
+}
-const util = __nccwpck_require__(1544)
-const { InvalidArgumentError, RequestAbortedError } = __nccwpck_require__(8091)
-const DecoratorHandler = __nccwpck_require__(7011)
+// https://html.spec.whatwg.org/multipage/webappapis.html#the-errorevent-interface
+class ErrorEvent extends Event {
+ #eventInit
-class DumpHandler extends DecoratorHandler {
- #maxSize = 1024 * 1024
- #abort = null
- #dumped = false
- #aborted = false
- #size = 0
- #reason = null
- #handler = null
+ constructor (type, eventInitDict) {
+ const prefix = 'ErrorEvent constructor'
+ webidl.argumentLengthCheck(arguments, 1, prefix)
- constructor ({ maxSize }, handler) {
- super(handler)
+ super(type, eventInitDict)
+ webidl.util.markAsUncloneable(this)
- if (maxSize != null && (!Number.isFinite(maxSize) || maxSize < 1)) {
- throw new InvalidArgumentError('maxSize must be a number greater than 0')
- }
+ type = webidl.converters.DOMString(type, prefix, 'type')
+ eventInitDict = webidl.converters.ErrorEventInit(eventInitDict ?? {})
- this.#maxSize = maxSize ?? this.#maxSize
- this.#handler = handler
+ this.#eventInit = eventInitDict
}
- onConnect (abort) {
- this.#abort = abort
+ get message () {
+ webidl.brandCheck(this, ErrorEvent)
- this.#handler.onConnect(this.#customAbort.bind(this))
+ return this.#eventInit.message
}
- #customAbort (reason) {
- this.#aborted = true
- this.#reason = reason
+ get filename () {
+ webidl.brandCheck(this, ErrorEvent)
+
+ return this.#eventInit.filename
}
- // TODO: will require adjustment after new hooks are out
- onHeaders (statusCode, rawHeaders, resume, statusMessage) {
- const headers = util.parseHeaders(rawHeaders)
- const contentLength = headers['content-length']
+ get lineno () {
+ webidl.brandCheck(this, ErrorEvent)
- if (contentLength != null && contentLength > this.#maxSize) {
- throw new RequestAbortedError(
- `Response size (${contentLength}) larger than maxSize (${
- this.#maxSize
- })`
- )
- }
+ return this.#eventInit.lineno
+ }
- if (this.#aborted) {
- return true
- }
+ get colno () {
+ webidl.brandCheck(this, ErrorEvent)
- return this.#handler.onHeaders(
- statusCode,
- rawHeaders,
- resume,
- statusMessage
- )
+ return this.#eventInit.colno
}
- onError (err) {
- if (this.#dumped) {
- return
- }
-
- err = this.#reason ?? err
+ get error () {
+ webidl.brandCheck(this, ErrorEvent)
- this.#handler.onError(err)
+ return this.#eventInit.error
}
+}
- onData (chunk) {
- this.#size = this.#size + chunk.length
-
- if (this.#size >= this.#maxSize) {
- this.#dumped = true
+Object.defineProperties(MessageEvent.prototype, {
+ [Symbol.toStringTag]: {
+ value: 'MessageEvent',
+ configurable: true
+ },
+ data: kEnumerableProperty,
+ origin: kEnumerableProperty,
+ lastEventId: kEnumerableProperty,
+ source: kEnumerableProperty,
+ ports: kEnumerableProperty,
+ initMessageEvent: kEnumerableProperty
+})
- if (this.#aborted) {
- this.#handler.onError(this.#reason)
- } else {
- this.#handler.onComplete([])
- }
- }
+Object.defineProperties(CloseEvent.prototype, {
+ [Symbol.toStringTag]: {
+ value: 'CloseEvent',
+ configurable: true
+ },
+ reason: kEnumerableProperty,
+ code: kEnumerableProperty,
+ wasClean: kEnumerableProperty
+})
- return true
- }
+Object.defineProperties(ErrorEvent.prototype, {
+ [Symbol.toStringTag]: {
+ value: 'ErrorEvent',
+ configurable: true
+ },
+ message: kEnumerableProperty,
+ filename: kEnumerableProperty,
+ lineno: kEnumerableProperty,
+ colno: kEnumerableProperty,
+ error: kEnumerableProperty
+})
- onComplete (trailers) {
- if (this.#dumped) {
- return
- }
+webidl.converters.MessagePort = webidl.interfaceConverter(MessagePort)
- if (this.#aborted) {
- this.#handler.onError(this.reason)
- return
- }
+webidl.converters['sequence'] = webidl.sequenceConverter(
+ webidl.converters.MessagePort
+)
- this.#handler.onComplete(trailers)
+const eventInit = [
+ {
+ key: 'bubbles',
+ converter: webidl.converters.boolean,
+ defaultValue: () => false
+ },
+ {
+ key: 'cancelable',
+ converter: webidl.converters.boolean,
+ defaultValue: () => false
+ },
+ {
+ key: 'composed',
+ converter: webidl.converters.boolean,
+ defaultValue: () => false
}
-}
+]
-function createDumpInterceptor (
- { maxSize: defaultMaxSize } = {
- maxSize: 1024 * 1024
+webidl.converters.MessageEventInit = webidl.dictionaryConverter([
+ ...eventInit,
+ {
+ key: 'data',
+ converter: webidl.converters.any,
+ defaultValue: () => null
+ },
+ {
+ key: 'origin',
+ converter: webidl.converters.USVString,
+ defaultValue: () => ''
+ },
+ {
+ key: 'lastEventId',
+ converter: webidl.converters.DOMString,
+ defaultValue: () => ''
+ },
+ {
+ key: 'source',
+ // Node doesn't implement WindowProxy or ServiceWorker, so the only
+ // valid value for source is a MessagePort.
+ converter: webidl.nullableConverter(webidl.converters.MessagePort),
+ defaultValue: () => null
+ },
+ {
+ key: 'ports',
+ converter: webidl.converters['sequence'],
+ defaultValue: () => new Array(0)
}
-) {
- return dispatch => {
- return function Intercept (opts, handler) {
- const { dumpMaxSize = defaultMaxSize } =
- opts
+])
- const dumpHandler = new DumpHandler(
- { maxSize: dumpMaxSize },
- handler
- )
+webidl.converters.CloseEventInit = webidl.dictionaryConverter([
+ ...eventInit,
+ {
+ key: 'wasClean',
+ converter: webidl.converters.boolean,
+ defaultValue: () => false
+ },
+ {
+ key: 'code',
+ converter: webidl.converters['unsigned short'],
+ defaultValue: () => 0
+ },
+ {
+ key: 'reason',
+ converter: webidl.converters.USVString,
+ defaultValue: () => ''
+ }
+])
- return dispatch(opts, dumpHandler)
- }
+webidl.converters.ErrorEventInit = webidl.dictionaryConverter([
+ ...eventInit,
+ {
+ key: 'message',
+ converter: webidl.converters.DOMString,
+ defaultValue: () => ''
+ },
+ {
+ key: 'filename',
+ converter: webidl.converters.USVString,
+ defaultValue: () => ''
+ },
+ {
+ key: 'lineno',
+ converter: webidl.converters['unsigned long'],
+ defaultValue: () => 0
+ },
+ {
+ key: 'colno',
+ converter: webidl.converters['unsigned long'],
+ defaultValue: () => 0
+ },
+ {
+ key: 'error',
+ converter: webidl.converters.any
}
-}
+])
-module.exports = createDumpInterceptor
+module.exports = {
+ MessageEvent,
+ CloseEvent,
+ ErrorEvent,
+ createFastMessageEvent
+}
/***/ }),
-/***/ 1676:
+/***/ 3264:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const RedirectHandler = __nccwpck_require__(5050)
+const { maxUnsigned16Bit } = __nccwpck_require__(736)
-function createRedirectInterceptor ({ maxRedirections: defaultMaxRedirections }) {
- return (dispatch) => {
- return function Intercept (opts, handler) {
- const { maxRedirections = defaultMaxRedirections } = opts
+const BUFFER_SIZE = 16386
- if (!maxRedirections) {
- return dispatch(opts, handler)
- }
+/** @type {import('crypto')} */
+let crypto
+let buffer = null
+let bufIdx = BUFFER_SIZE
- const redirectHandler = new RedirectHandler(dispatch, maxRedirections, opts, handler)
- opts = { ...opts, maxRedirections: 0 } // Stop sub dispatcher from also redirecting.
- return dispatch(opts, redirectHandler)
+try {
+ crypto = __nccwpck_require__(7598)
+/* c8 ignore next 3 */
+} catch {
+ crypto = {
+ // not full compatibility, but minimum.
+ randomFillSync: function randomFillSync (buffer, _offset, _size) {
+ for (let i = 0; i < buffer.length; ++i) {
+ buffer[i] = Math.random() * 255 | 0
+ }
+ return buffer
}
}
}
-module.exports = createRedirectInterceptor
+function generateMask () {
+ if (bufIdx === BUFFER_SIZE) {
+ bufIdx = 0
+ crypto.randomFillSync((buffer ??= Buffer.allocUnsafe(BUFFER_SIZE)), 0, BUFFER_SIZE)
+ }
+ return [buffer[bufIdx++], buffer[bufIdx++], buffer[bufIdx++], buffer[bufIdx++]]
+}
+
+class WebsocketFrameSend {
+ /**
+ * @param {Buffer|undefined} data
+ */
+ constructor (data) {
+ this.frameData = data
+ }
+ createFrame (opcode) {
+ const frameData = this.frameData
+ const maskKey = generateMask()
+ const bodyLength = frameData?.byteLength ?? 0
-/***/ }),
+ /** @type {number} */
+ let payloadLength = bodyLength // 0-125
+ let offset = 6
-/***/ 3650:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ if (bodyLength > maxUnsigned16Bit) {
+ offset += 8 // payload length is next 8 bytes
+ payloadLength = 127
+ } else if (bodyLength > 125) {
+ offset += 2 // payload length is next 2 bytes
+ payloadLength = 126
+ }
+ const buffer = Buffer.allocUnsafe(bodyLength + offset)
-const RedirectHandler = __nccwpck_require__(5050)
+ // Clear first 2 bytes, everything else is overwritten
+ buffer[0] = buffer[1] = 0
+ buffer[0] |= 0x80 // FIN
+ buffer[0] = (buffer[0] & 0xF0) + opcode // opcode
-module.exports = opts => {
- const globalMaxRedirections = opts?.maxRedirections
- return dispatch => {
- return function redirectInterceptor (opts, handler) {
- const { maxRedirections = globalMaxRedirections, ...baseOpts } = opts
+ /*! ws. MIT License. Einar Otto Stangvik */
+ buffer[offset - 4] = maskKey[0]
+ buffer[offset - 3] = maskKey[1]
+ buffer[offset - 2] = maskKey[2]
+ buffer[offset - 1] = maskKey[3]
- if (!maxRedirections) {
- return dispatch(opts, handler)
- }
+ buffer[1] = payloadLength
- const redirectHandler = new RedirectHandler(
- dispatch,
- maxRedirections,
- opts,
- handler
- )
+ if (payloadLength === 126) {
+ buffer.writeUInt16BE(bodyLength, 2)
+ } else if (payloadLength === 127) {
+ // Clear extended payload length
+ buffer[2] = buffer[3] = 0
+ buffer.writeUIntBE(bodyLength, 4, 6)
+ }
- return dispatch(baseOpts, redirectHandler)
+ buffer[1] |= 0x80 // MASK
+
+ // mask body
+ for (let i = 0; i < bodyLength; ++i) {
+ buffer[offset + i] = frameData[i] ^ maskKey[i & 3]
}
+
+ return buffer
}
}
+module.exports = {
+ WebsocketFrameSend
+}
+
/***/ }),
-/***/ 3874:
+/***/ 9469:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const RetryHandler = __nccwpck_require__(112)
-
-module.exports = globalOpts => {
- return dispatch => {
- return function retryInterceptor (opts, handler) {
- return dispatch(
- opts,
- new RetryHandler(
- { ...opts, retryOptions: { ...globalOpts, ...opts.retryOptions } },
- {
- handler,
- dispatch
- }
- )
- )
- }
- }
-}
+const { createInflateRaw, Z_DEFAULT_WINDOWBITS } = __nccwpck_require__(8522)
+const { isValidClientWindowBits } = __nccwpck_require__(8625)
+const { MessageSizeExceededError } = __nccwpck_require__(8707)
-/***/ }),
+const tail = Buffer.from([0x00, 0x00, 0xff, 0xff])
+const kBuffer = Symbol('kBuffer')
+const kLength = Symbol('kLength')
-/***/ 7424:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+// Default maximum decompressed message size: 4 MB
+const kDefaultMaxDecompressedSize = 4 * 1024 * 1024
+class PerMessageDeflate {
+ /** @type {import('node:zlib').InflateRaw} */
+ #inflate
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.SPECIAL_HEADERS = exports.HEADER_STATE = exports.MINOR = exports.MAJOR = exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS = exports.TOKEN = exports.STRICT_TOKEN = exports.HEX = exports.URL_CHAR = exports.STRICT_URL_CHAR = exports.USERINFO_CHARS = exports.MARK = exports.ALPHANUM = exports.NUM = exports.HEX_MAP = exports.NUM_MAP = exports.ALPHA = exports.FINISH = exports.H_METHOD_MAP = exports.METHOD_MAP = exports.METHODS_RTSP = exports.METHODS_ICE = exports.METHODS_HTTP = exports.METHODS = exports.LENIENT_FLAGS = exports.FLAGS = exports.TYPE = exports.ERROR = void 0;
-const utils_1 = __nccwpck_require__(8916);
-// C headers
-var ERROR;
-(function (ERROR) {
- ERROR[ERROR["OK"] = 0] = "OK";
- ERROR[ERROR["INTERNAL"] = 1] = "INTERNAL";
- ERROR[ERROR["STRICT"] = 2] = "STRICT";
- ERROR[ERROR["LF_EXPECTED"] = 3] = "LF_EXPECTED";
- ERROR[ERROR["UNEXPECTED_CONTENT_LENGTH"] = 4] = "UNEXPECTED_CONTENT_LENGTH";
- ERROR[ERROR["CLOSED_CONNECTION"] = 5] = "CLOSED_CONNECTION";
- ERROR[ERROR["INVALID_METHOD"] = 6] = "INVALID_METHOD";
- ERROR[ERROR["INVALID_URL"] = 7] = "INVALID_URL";
- ERROR[ERROR["INVALID_CONSTANT"] = 8] = "INVALID_CONSTANT";
- ERROR[ERROR["INVALID_VERSION"] = 9] = "INVALID_VERSION";
- ERROR[ERROR["INVALID_HEADER_TOKEN"] = 10] = "INVALID_HEADER_TOKEN";
- ERROR[ERROR["INVALID_CONTENT_LENGTH"] = 11] = "INVALID_CONTENT_LENGTH";
- ERROR[ERROR["INVALID_CHUNK_SIZE"] = 12] = "INVALID_CHUNK_SIZE";
- ERROR[ERROR["INVALID_STATUS"] = 13] = "INVALID_STATUS";
- ERROR[ERROR["INVALID_EOF_STATE"] = 14] = "INVALID_EOF_STATE";
- ERROR[ERROR["INVALID_TRANSFER_ENCODING"] = 15] = "INVALID_TRANSFER_ENCODING";
- ERROR[ERROR["CB_MESSAGE_BEGIN"] = 16] = "CB_MESSAGE_BEGIN";
- ERROR[ERROR["CB_HEADERS_COMPLETE"] = 17] = "CB_HEADERS_COMPLETE";
- ERROR[ERROR["CB_MESSAGE_COMPLETE"] = 18] = "CB_MESSAGE_COMPLETE";
- ERROR[ERROR["CB_CHUNK_HEADER"] = 19] = "CB_CHUNK_HEADER";
- ERROR[ERROR["CB_CHUNK_COMPLETE"] = 20] = "CB_CHUNK_COMPLETE";
- ERROR[ERROR["PAUSED"] = 21] = "PAUSED";
- ERROR[ERROR["PAUSED_UPGRADE"] = 22] = "PAUSED_UPGRADE";
- ERROR[ERROR["PAUSED_H2_UPGRADE"] = 23] = "PAUSED_H2_UPGRADE";
- ERROR[ERROR["USER"] = 24] = "USER";
-})(ERROR = exports.ERROR || (exports.ERROR = {}));
-var TYPE;
-(function (TYPE) {
- TYPE[TYPE["BOTH"] = 0] = "BOTH";
- TYPE[TYPE["REQUEST"] = 1] = "REQUEST";
- TYPE[TYPE["RESPONSE"] = 2] = "RESPONSE";
-})(TYPE = exports.TYPE || (exports.TYPE = {}));
-var FLAGS;
-(function (FLAGS) {
- FLAGS[FLAGS["CONNECTION_KEEP_ALIVE"] = 1] = "CONNECTION_KEEP_ALIVE";
- FLAGS[FLAGS["CONNECTION_CLOSE"] = 2] = "CONNECTION_CLOSE";
- FLAGS[FLAGS["CONNECTION_UPGRADE"] = 4] = "CONNECTION_UPGRADE";
- FLAGS[FLAGS["CHUNKED"] = 8] = "CHUNKED";
- FLAGS[FLAGS["UPGRADE"] = 16] = "UPGRADE";
- FLAGS[FLAGS["CONTENT_LENGTH"] = 32] = "CONTENT_LENGTH";
- FLAGS[FLAGS["SKIPBODY"] = 64] = "SKIPBODY";
- FLAGS[FLAGS["TRAILING"] = 128] = "TRAILING";
- // 1 << 8 is unused
- FLAGS[FLAGS["TRANSFER_ENCODING"] = 512] = "TRANSFER_ENCODING";
-})(FLAGS = exports.FLAGS || (exports.FLAGS = {}));
-var LENIENT_FLAGS;
-(function (LENIENT_FLAGS) {
- LENIENT_FLAGS[LENIENT_FLAGS["HEADERS"] = 1] = "HEADERS";
- LENIENT_FLAGS[LENIENT_FLAGS["CHUNKED_LENGTH"] = 2] = "CHUNKED_LENGTH";
- LENIENT_FLAGS[LENIENT_FLAGS["KEEP_ALIVE"] = 4] = "KEEP_ALIVE";
-})(LENIENT_FLAGS = exports.LENIENT_FLAGS || (exports.LENIENT_FLAGS = {}));
-var METHODS;
-(function (METHODS) {
- METHODS[METHODS["DELETE"] = 0] = "DELETE";
- METHODS[METHODS["GET"] = 1] = "GET";
- METHODS[METHODS["HEAD"] = 2] = "HEAD";
- METHODS[METHODS["POST"] = 3] = "POST";
- METHODS[METHODS["PUT"] = 4] = "PUT";
- /* pathological */
- METHODS[METHODS["CONNECT"] = 5] = "CONNECT";
- METHODS[METHODS["OPTIONS"] = 6] = "OPTIONS";
- METHODS[METHODS["TRACE"] = 7] = "TRACE";
- /* WebDAV */
- METHODS[METHODS["COPY"] = 8] = "COPY";
- METHODS[METHODS["LOCK"] = 9] = "LOCK";
- METHODS[METHODS["MKCOL"] = 10] = "MKCOL";
- METHODS[METHODS["MOVE"] = 11] = "MOVE";
- METHODS[METHODS["PROPFIND"] = 12] = "PROPFIND";
- METHODS[METHODS["PROPPATCH"] = 13] = "PROPPATCH";
- METHODS[METHODS["SEARCH"] = 14] = "SEARCH";
- METHODS[METHODS["UNLOCK"] = 15] = "UNLOCK";
- METHODS[METHODS["BIND"] = 16] = "BIND";
- METHODS[METHODS["REBIND"] = 17] = "REBIND";
- METHODS[METHODS["UNBIND"] = 18] = "UNBIND";
- METHODS[METHODS["ACL"] = 19] = "ACL";
- /* subversion */
- METHODS[METHODS["REPORT"] = 20] = "REPORT";
- METHODS[METHODS["MKACTIVITY"] = 21] = "MKACTIVITY";
- METHODS[METHODS["CHECKOUT"] = 22] = "CHECKOUT";
- METHODS[METHODS["MERGE"] = 23] = "MERGE";
- /* upnp */
- METHODS[METHODS["M-SEARCH"] = 24] = "M-SEARCH";
- METHODS[METHODS["NOTIFY"] = 25] = "NOTIFY";
- METHODS[METHODS["SUBSCRIBE"] = 26] = "SUBSCRIBE";
- METHODS[METHODS["UNSUBSCRIBE"] = 27] = "UNSUBSCRIBE";
- /* RFC-5789 */
- METHODS[METHODS["PATCH"] = 28] = "PATCH";
- METHODS[METHODS["PURGE"] = 29] = "PURGE";
- /* CalDAV */
- METHODS[METHODS["MKCALENDAR"] = 30] = "MKCALENDAR";
- /* RFC-2068, section 19.6.1.2 */
- METHODS[METHODS["LINK"] = 31] = "LINK";
- METHODS[METHODS["UNLINK"] = 32] = "UNLINK";
- /* icecast */
- METHODS[METHODS["SOURCE"] = 33] = "SOURCE";
- /* RFC-7540, section 11.6 */
- METHODS[METHODS["PRI"] = 34] = "PRI";
- /* RFC-2326 RTSP */
- METHODS[METHODS["DESCRIBE"] = 35] = "DESCRIBE";
- METHODS[METHODS["ANNOUNCE"] = 36] = "ANNOUNCE";
- METHODS[METHODS["SETUP"] = 37] = "SETUP";
- METHODS[METHODS["PLAY"] = 38] = "PLAY";
- METHODS[METHODS["PAUSE"] = 39] = "PAUSE";
- METHODS[METHODS["TEARDOWN"] = 40] = "TEARDOWN";
- METHODS[METHODS["GET_PARAMETER"] = 41] = "GET_PARAMETER";
- METHODS[METHODS["SET_PARAMETER"] = 42] = "SET_PARAMETER";
- METHODS[METHODS["REDIRECT"] = 43] = "REDIRECT";
- METHODS[METHODS["RECORD"] = 44] = "RECORD";
- /* RAOP */
- METHODS[METHODS["FLUSH"] = 45] = "FLUSH";
-})(METHODS = exports.METHODS || (exports.METHODS = {}));
-exports.METHODS_HTTP = [
- METHODS.DELETE,
- METHODS.GET,
- METHODS.HEAD,
- METHODS.POST,
- METHODS.PUT,
- METHODS.CONNECT,
- METHODS.OPTIONS,
- METHODS.TRACE,
- METHODS.COPY,
- METHODS.LOCK,
- METHODS.MKCOL,
- METHODS.MOVE,
- METHODS.PROPFIND,
- METHODS.PROPPATCH,
- METHODS.SEARCH,
- METHODS.UNLOCK,
- METHODS.BIND,
- METHODS.REBIND,
- METHODS.UNBIND,
- METHODS.ACL,
- METHODS.REPORT,
- METHODS.MKACTIVITY,
- METHODS.CHECKOUT,
- METHODS.MERGE,
- METHODS['M-SEARCH'],
- METHODS.NOTIFY,
- METHODS.SUBSCRIBE,
- METHODS.UNSUBSCRIBE,
- METHODS.PATCH,
- METHODS.PURGE,
- METHODS.MKCALENDAR,
- METHODS.LINK,
- METHODS.UNLINK,
- METHODS.PRI,
- // TODO(indutny): should we allow it with HTTP?
- METHODS.SOURCE,
-];
-exports.METHODS_ICE = [
- METHODS.SOURCE,
-];
-exports.METHODS_RTSP = [
- METHODS.OPTIONS,
- METHODS.DESCRIBE,
- METHODS.ANNOUNCE,
- METHODS.SETUP,
- METHODS.PLAY,
- METHODS.PAUSE,
- METHODS.TEARDOWN,
- METHODS.GET_PARAMETER,
- METHODS.SET_PARAMETER,
- METHODS.REDIRECT,
- METHODS.RECORD,
- METHODS.FLUSH,
- // For AirPlay
- METHODS.GET,
- METHODS.POST,
-];
-exports.METHOD_MAP = utils_1.enumToMap(METHODS);
-exports.H_METHOD_MAP = {};
-Object.keys(exports.METHOD_MAP).forEach((key) => {
- if (/^H/.test(key)) {
- exports.H_METHOD_MAP[key] = exports.METHOD_MAP[key];
- }
-});
-var FINISH;
-(function (FINISH) {
- FINISH[FINISH["SAFE"] = 0] = "SAFE";
- FINISH[FINISH["SAFE_WITH_CB"] = 1] = "SAFE_WITH_CB";
- FINISH[FINISH["UNSAFE"] = 2] = "UNSAFE";
-})(FINISH = exports.FINISH || (exports.FINISH = {}));
-exports.ALPHA = [];
-for (let i = 'A'.charCodeAt(0); i <= 'Z'.charCodeAt(0); i++) {
- // Upper case
- exports.ALPHA.push(String.fromCharCode(i));
- // Lower case
- exports.ALPHA.push(String.fromCharCode(i + 0x20));
-}
-exports.NUM_MAP = {
- 0: 0, 1: 1, 2: 2, 3: 3, 4: 4,
- 5: 5, 6: 6, 7: 7, 8: 8, 9: 9,
-};
-exports.HEX_MAP = {
- 0: 0, 1: 1, 2: 2, 3: 3, 4: 4,
- 5: 5, 6: 6, 7: 7, 8: 8, 9: 9,
- A: 0XA, B: 0XB, C: 0XC, D: 0XD, E: 0XE, F: 0XF,
- a: 0xa, b: 0xb, c: 0xc, d: 0xd, e: 0xe, f: 0xf,
-};
-exports.NUM = [
- '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
-];
-exports.ALPHANUM = exports.ALPHA.concat(exports.NUM);
-exports.MARK = ['-', '_', '.', '!', '~', '*', '\'', '(', ')'];
-exports.USERINFO_CHARS = exports.ALPHANUM
- .concat(exports.MARK)
- .concat(['%', ';', ':', '&', '=', '+', '$', ',']);
-// TODO(indutny): use RFC
-exports.STRICT_URL_CHAR = [
- '!', '"', '$', '%', '&', '\'',
- '(', ')', '*', '+', ',', '-', '.', '/',
- ':', ';', '<', '=', '>',
- '@', '[', '\\', ']', '^', '_',
- '`',
- '{', '|', '}', '~',
-].concat(exports.ALPHANUM);
-exports.URL_CHAR = exports.STRICT_URL_CHAR
- .concat(['\t', '\f']);
-// All characters with 0x80 bit set to 1
-for (let i = 0x80; i <= 0xff; i++) {
- exports.URL_CHAR.push(i);
-}
-exports.HEX = exports.NUM.concat(['a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F']);
-/* Tokens as defined by rfc 2616. Also lowercases them.
- * token = 1*
- * separators = "(" | ")" | "<" | ">" | "@"
- * | "," | ";" | ":" | "\" | <">
- * | "/" | "[" | "]" | "?" | "="
- * | "{" | "}" | SP | HT
- */
-exports.STRICT_TOKEN = [
- '!', '#', '$', '%', '&', '\'',
- '*', '+', '-', '.',
- '^', '_', '`',
- '|', '~',
-].concat(exports.ALPHANUM);
-exports.TOKEN = exports.STRICT_TOKEN.concat([' ']);
-/*
- * Verify that a char is a valid visible (printable) US-ASCII
- * character or %x80-FF
- */
-exports.HEADER_CHARS = ['\t'];
-for (let i = 32; i <= 255; i++) {
- if (i !== 127) {
- exports.HEADER_CHARS.push(i);
- }
-}
-// ',' = \x44
-exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS.filter((c) => c !== 44);
-exports.MAJOR = exports.NUM_MAP;
-exports.MINOR = exports.MAJOR;
-var HEADER_STATE;
-(function (HEADER_STATE) {
- HEADER_STATE[HEADER_STATE["GENERAL"] = 0] = "GENERAL";
- HEADER_STATE[HEADER_STATE["CONNECTION"] = 1] = "CONNECTION";
- HEADER_STATE[HEADER_STATE["CONTENT_LENGTH"] = 2] = "CONTENT_LENGTH";
- HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING"] = 3] = "TRANSFER_ENCODING";
- HEADER_STATE[HEADER_STATE["UPGRADE"] = 4] = "UPGRADE";
- HEADER_STATE[HEADER_STATE["CONNECTION_KEEP_ALIVE"] = 5] = "CONNECTION_KEEP_ALIVE";
- HEADER_STATE[HEADER_STATE["CONNECTION_CLOSE"] = 6] = "CONNECTION_CLOSE";
- HEADER_STATE[HEADER_STATE["CONNECTION_UPGRADE"] = 7] = "CONNECTION_UPGRADE";
- HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING_CHUNKED"] = 8] = "TRANSFER_ENCODING_CHUNKED";
-})(HEADER_STATE = exports.HEADER_STATE || (exports.HEADER_STATE = {}));
-exports.SPECIAL_HEADERS = {
- 'connection': HEADER_STATE.CONNECTION,
- 'content-length': HEADER_STATE.CONTENT_LENGTH,
- 'proxy-connection': HEADER_STATE.CONNECTION,
- 'transfer-encoding': HEADER_STATE.TRANSFER_ENCODING,
- 'upgrade': HEADER_STATE.UPGRADE,
-};
-//# sourceMappingURL=constants.js.map
+ #options = {}
-/***/ }),
+ /** @type {boolean} */
+ #aborted = false
-/***/ 7846:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ /** @type {Function|null} */
+ #currentCallback = null
+ /**
+ * @param {Map} extensions
+ */
+ constructor (extensions) {
+ this.#options.serverNoContextTakeover = extensions.has('server_no_context_takeover')
+ this.#options.serverMaxWindowBits = extensions.get('server_max_window_bits')
+ }
+ decompress (chunk, fin, callback) {
+ // An endpoint uses the following algorithm to decompress a message.
+ // 1. Append 4 octets of 0x00 0x00 0xff 0xff to the tail end of the
+ // payload of the message.
+ // 2. Decompress the resulting data using DEFLATE.
-const { Buffer } = __nccwpck_require__(4573)
+ if (this.#aborted) {
+ callback(new MessageSizeExceededError())
+ return
+ }
-module.exports = Buffer.from('AGFzbQEAAAABJwdgAX8Bf2ADf39/AX9gAX8AYAJ/fwBgBH9/f38Bf2AAAGADf39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQAEA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAAy0sBQYAAAIAAAAAAAACAQIAAgICAAADAAAAAAMDAwMBAQEBAQEBAQEAAAIAAAAEBQFwARISBQMBAAIGCAF/AUGA1AQLB9EFIgZtZW1vcnkCAAtfaW5pdGlhbGl6ZQAIGV9faW5kaXJlY3RfZnVuY3Rpb25fdGFibGUBAAtsbGh0dHBfaW5pdAAJGGxsaHR0cF9zaG91bGRfa2VlcF9hbGl2ZQAvDGxsaHR0cF9hbGxvYwALBm1hbGxvYwAxC2xsaHR0cF9mcmVlAAwEZnJlZQAMD2xsaHR0cF9nZXRfdHlwZQANFWxsaHR0cF9nZXRfaHR0cF9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iEAIAQgAUEBaiIBRw0ACyACIAU2AgAMogILQYsBIQMgASAERg2hAiACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEGOzwBqLQAARw1kIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyiAgsgAkEANgIAIAZBAWohAUECDGULQYwBIQMgASAERg2gAiACKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHwzwBqLQAARw1jIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyhAgsgAkEANgIAIAZBAWohAUEfDGQLQY0BIQMgASAERg2fAiACKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHyzwBqLQAARw1iIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAygAgsgAkEANgIAIAZBAWohAUEJDGMLIAEgBEYEQEGOASEDDJ8CCwJAAkAgAS0AAEHJAGsOBwBiYmJiYgFiCyABQQFqIQFB+AAhAwyGAgsgAUEBaiEBQfkAIQMMhQILQY8BIQMgASAERg2dAiACKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEGRzwBqLQAARw1gIABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyeAgsgAkEANgIAIAZBAWohAUEYDGELQZABIQMgASAERg2cAiACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEGXzwBqLQAARw1fIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAydAgsgAkEANgIAIAZBAWohAUEXDGALQZEBIQMgASAERg2bAiACKAIAIgAgBCABa2ohBSABIABrQQZqIQYCQANAIAEtAAAgAEGazwBqLQAARw1eIABBBkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAycAgsgAkEANgIAIAZBAWohAUEVDF8LQZIBIQMgASAERg2aAiACKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAA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HcCDYCECACQQc2AgxBACEDDKsBCyACKAIEIQAgAkEANgIEIAIgACABECUiAEUNByACQeUANgIcIAIgATYCFCACIAA2AgxBACEDDKoBCyACKAIEIQAgAkEANgIEIAIgACABECUiAEUNFiACQdMANgIcIAIgATYCFCACIAA2AgxBACEDDKkBCyACKAIEIQAgAkEANgIEIAIgACABECUiAEUNGCACQdIANgIcIAIgATYCFCACIAA2AgxBACEDDKgBCyACQQA2AhwgAiABNgIUIAJBxgo2AhAgAkEHNgIMQQAhAwynAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDQMgAkHlADYCHCACIAE2AhQgAiAANgIMQQAhAwymAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDRIgAkHTADYCHCACIAE2AhQgAiAANgIMQQAhAwylAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDRQgAkHSADYCHCACIAE2AhQgAiAANgIMQQAhAwykAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDQAgAkHlADYCHCACIAE2AhQgAiAANgIMQQAhAwyjAQtB1QAhAwyJAQsgAEEVRwRAIAJBADYCHCACIAE2AhQgAkG5DTYCECACQRo2AgxBACEDDKIBCyACQeQANgIcIAIgATYCFCACQeMXNgIQIAJBFTYCDEEAIQMMoQELIAJBADYCACAGQQFqIQEgAi0AKSIAQSNrQQtJDQQCQCAAQQZLDQBBASAAdEHKAHFFDQAMBQtBACEDIAJBADYCHCACIAE2AhQgAkH3CTYCECACQQg2AgwMoAELIAJBADYCACAGQQFqIQEgAi0AKUEhRg0DIAJBADYCHCACIAE2AhQgAkGbCjYCECACQQg2AgxBACEDDJ8BCyACQQA2AgALQQAhAyACQQA2AhwgAiABNgIUIAJBkDM2AhAgAkEINgIMDJ0BCyACQQA2AgAgBkEBaiEBIAItAClBI0kNACACQQA2AhwgAiABNgIUIAJB0wk2AhAgAkEINgIMQQAhAwycAQtB0QAhAwyCAQsgAS0AAEEwayIAQf8BcUEKSQRAIAIgADoAKiABQQFqIQFBzw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AAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAEH6zAALBAEAAAEAQZDNAAsBAQBBms0ACwYCAAAAAAIAQbHNAAs6AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwBB8M4AC5YBTk9VTkNFRUNLT1VUTkVDVEVURUNSSUJFTFVTSEVURUFEU0VBUkNIUkdFQ1RJVklUWUxFTkRBUlZFT1RJRllQVElPTlNDSFNFQVlTVEFUQ0hHRU9SRElSRUNUT1JUUkNIUEFSQU1FVEVSVVJDRUJTQ1JJQkVBUkRPV05BQ0VJTkROS0NLVUJTQ1JJQkVIVFRQL0FEVFAv', 'base64')
+ if (!this.#inflate) {
+ let windowBits = Z_DEFAULT_WINDOWBITS
+ if (this.#options.serverMaxWindowBits) { // empty values default to Z_DEFAULT_WINDOWBITS
+ if (!isValidClientWindowBits(this.#options.serverMaxWindowBits)) {
+ callback(new Error('Invalid server_max_window_bits'))
+ return
+ }
-/***/ }),
+ windowBits = Number.parseInt(this.#options.serverMaxWindowBits)
+ }
-/***/ 9474:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ try {
+ this.#inflate = createInflateRaw({ windowBits })
+ } catch (err) {
+ callback(err)
+ return
+ }
+ this.#inflate[kBuffer] = []
+ this.#inflate[kLength] = 0
+ this.#inflate.on('data', (data) => {
+ if (this.#aborted) {
+ return
+ }
+ this.#inflate[kLength] += data.length
-const { Buffer } = __nccwpck_require__(4573)
+ if (this.#inflate[kLength] > kDefaultMaxDecompressedSize) {
+ this.#aborted = true
+ this.#inflate.removeAllListeners()
+ this.#inflate.destroy()
+ this.#inflate = null
-module.exports = Buffer.from('AGFzbQEAAAABJwdgAX8Bf2ADf39/AX9gAX8AYAJ/fwBgBH9/f38Bf2AAAGADf39/AALLAQgDZW52GHdhc21fb25faGVhZGV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gIAIAEgADYCGCABIAE2AgggASABNgIMDAELIARBGSACQQF2a0EAIAJBH0cbdCECIAAoAgAhAAJAA0AgACIDKAIEQXhxIARGDQEgAkEddiEAIAJBAXQhAiADIABBBHFqQRBqIgcoAgAiAA0ACyAHIAE2AgAgASADNgIYIAEgATYCDCABIAE2AggMAQsgAygCCCIAIAE2AgwgAyABNgIIIAFBADYCGCABIAM2AgwgASAANgIIC0Gs0ABBrNAAKAIAQQFrIgBBfyAAGzYCAAsLBwAgAC0AKAsHACAALQAqCwcAIAAtACsLBwAgAC0AKQsHACAALwEyCwcAIAAtAC4LQAEEfyAAKAIYIQEgAC0ALSECIAAtACghAyAAKAI4IQQgABAwIAAgBDYCOCAAIAM6ACggACACOgAtIAAgATYCGAu74gECB38DfiABIAJqIQQCQCAAIgIoAgwiAA0AIAIoAgQEQCACIAE2AgQLIwBBEGsiCCQAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAIoAhwiA0EBaw7dAdoBAdkBAgMEBQYHCAkKCwwNDtgBDx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QAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJ/AkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAgJ/AkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAn8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCADDsYBAAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHyAhIyUmKCorLC8wMTIzNDU2Nzk6Ozw9lANAQkRFRklLTk9QUVJTVFVWWFpbXF1eX2BhYmNkZWZnaGpsb3Bxc3V2eHl6e3x/gAGBAYIBgwGEAYUBhgGHAYgBiQGKAYsBjAGNAY4BjwGQAZEBkgGTAZ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BSABIABrQQJqIQYCQANAIAEtAAAgAEHtzwBqLQAARw1IIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyGAgsgAkEANgIAIAZBAWohAUERDEkLQagBIQMgASAERg2EAiACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHCzwBqLQAARw1HIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyFAgsgAkEANgIAIAZBAWohAUEsDEgLQakBIQMgASAERg2DAiACKAIAIgAgBCABa2ohBSABIABrQQRqIQYCQANAIAEtAAAgAEHFzwBqLQAARw1GIABBBEYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyEAgsgAkEANgIAIAZBAWohAUErDEcLQaoBIQMgASAERg2CAiACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHKzwBqLQAARw1FIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyDAgsgAkEANgIAIAZBAWohAUEUDEYLIAEgBEYEQEGrASEDDIICCwJAAkACQAJAIAEtAABBwgBrDg8AAQJHR0dHR0dHR0dHRwNHCyABQQFqIQFBkwEhAwzrAQsgAUEBaiEBQZQBIQMM6gELIAFBAWohAUGVASEDDOkBCyABQQFqIQFBlgEhAwzoAQsgASAERgRAQawBIQMMgQILIAEtAABBxQBHDUIgAUEBaiEBDD0LQa0BIQMgASAERg3/ASACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHNzwBqLQAARw1CIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyAAgsgAkEANgIAIAZBAWohAUEODEMLIAEgBEYEQEGuASEDDP8BCyABLQAAQdAARw1AIAFBAWohAUElDEILQa8BIQMgASAERg39ASACKAIAIgAgBCABa2ohBSABIABrQQhqIQYCQANAIAEtAAAgAEHQzwBqLQAARw1AIABBCEYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAz+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IcIAIgATYCFCACQcMPNgIQIAJBBzYCDEEAIQMMtQELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0RIAJB5QA2AhwgAiABNgIUIAIgADYCDEEAIQMMtAELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0gIAJB0wA2AhwgAiABNgIUIAIgADYCDEEAIQMMswELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0iIAJB0gA2AhwgAiABNgIUIAIgADYCDEEAIQMMsgELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0OIAJB5QA2AhwgAiABNgIUIAIgADYCDEEAIQMMsQELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0dIAJB0wA2AhwgAiABNgIUIAIgADYCDEEAIQMMsAELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0fIAJB0gA2AhwgAiABNgIUIAIgADYCDEEAIQMMrwELIABBP0cNASABQQFqCyEBQQUhAwyUAQtBACEDIAJBADYCHCACIAE2AhQgAkH9EjYCECACQQc2AgwMrAELIAJBADYCHCACIAE2AhQgAkHcCDYCECACQQc2AgxBACEDDKsBCyACKAIEIQAgAkEANgIEIAIgACABECUiAEUNByACQeUANgIcIAIgATYCFCACIAA2AgxBACEDDKoBCyACKAIEIQAgAkEANgIEIAIgACABECUiAEUNFiACQdMANgIcIAIgATYCFCACIAA2AgxBACEDDKkBCyACKAIEIQAgAkEANgIEIAIgACABECUiAEUNGCACQdIANgIcIAIgATYCFCACIAA2AgxBACEDDKgBCyACQQA2AhwgAiABNgIUIAJBxgo2AhAgAkEHNgIMQQAhAwynAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDQMgAkHlADYCHCACIAE2AhQgAiAANgIMQQAhAwymAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDRIgAkHTADYCHCACIAE2AhQgAiAANgIMQQAhAwylAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDRQgAkHSADYCHCACIAE2AhQgAiAANgIMQQAhAwyk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dOQUNFSU5ETktDS1VCU0NSSUJFSFRUUC9BRFRQLw==', 'base64')
+ if (this.#currentCallback) {
+ const cb = this.#currentCallback
+ this.#currentCallback = null
+ cb(new MessageSizeExceededError())
+ }
+ return
+ }
+ this.#inflate[kBuffer].push(data)
+ })
-/***/ }),
+ this.#inflate.on('error', (err) => {
+ this.#inflate = null
+ callback(err)
+ })
+ }
-/***/ 8916:
-/***/ ((__unused_webpack_module, exports) => {
+ this.#currentCallback = callback
+ this.#inflate.write(chunk)
+ if (fin) {
+ this.#inflate.write(tail)
+ }
+ this.#inflate.flush(() => {
+ if (this.#aborted || !this.#inflate) {
+ return
+ }
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.enumToMap = void 0;
-function enumToMap(obj) {
- const res = {};
- Object.keys(obj).forEach((key) => {
- const value = obj[key];
- if (typeof value === 'number') {
- res[key] = value;
- }
- });
- return res;
+ const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength])
+
+ this.#inflate[kBuffer].length = 0
+ this.#inflate[kLength] = 0
+ this.#currentCallback = null
+
+ callback(null, full)
+ })
+ }
}
-exports.enumToMap = enumToMap;
-//# sourceMappingURL=utils.js.map
+
+module.exports = { PerMessageDeflate }
+
/***/ }),
-/***/ 5973:
+/***/ 1652:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const { kClients } = __nccwpck_require__(9411)
-const Agent = __nccwpck_require__(6261)
+const { Writable } = __nccwpck_require__(7075)
+const assert = __nccwpck_require__(4589)
+const { parserStates, opcodes, states, emptyBuffer, sentCloseFrameState } = __nccwpck_require__(736)
+const { kReadyState, kSentClose, kResponse, kReceivedClose } = __nccwpck_require__(1216)
+const { channels } = __nccwpck_require__(2414)
const {
- kAgent,
- kMockAgentSet,
- kMockAgentGet,
- kDispatches,
- kIsMockActive,
- kNetConnect,
- kGetNetConnect,
- kOptions,
- kFactory
-} = __nccwpck_require__(8149)
-const MockClient = __nccwpck_require__(8957)
-const MockPool = __nccwpck_require__(8780)
-const { matchValue, buildMockOptions } = __nccwpck_require__(1725)
-const { InvalidArgumentError, UndiciError } = __nccwpck_require__(8091)
-const Dispatcher = __nccwpck_require__(2091)
-const Pluralizer = __nccwpck_require__(8353)
-const PendingInterceptorsFormatter = __nccwpck_require__(1030)
+ isValidStatusCode,
+ isValidOpcode,
+ failWebsocketConnection,
+ websocketMessageReceived,
+ utf8Decode,
+ isControlFrame,
+ isTextBinaryFrame,
+ isContinuationFrame
+} = __nccwpck_require__(8625)
+const { WebsocketFrameSend } = __nccwpck_require__(3264)
+const { closeWebSocketConnection } = __nccwpck_require__(6897)
+const { PerMessageDeflate } = __nccwpck_require__(9469)
-class MockAgent extends Dispatcher {
- constructor (opts) {
- super(opts)
+// This code was influenced by ws released under the MIT license.
+// Copyright (c) 2011 Einar Otto Stangvik
+// Copyright (c) 2013 Arnout Kazemier and contributors
+// Copyright (c) 2016 Luigi Pinca and contributors
- this[kNetConnect] = true
- this[kIsMockActive] = true
+class ByteParser extends Writable {
+ #buffers = []
+ #byteOffset = 0
+ #loop = false
- // Instantiate Agent and encapsulate
- if ((opts?.agent && typeof opts.agent.dispatch !== 'function')) {
- throw new InvalidArgumentError('Argument opts.agent must implement Agent')
- }
- const agent = opts?.agent ? opts.agent : new Agent(opts)
- this[kAgent] = agent
+ #state = parserStates.INFO
- this[kClients] = agent[kClients]
- this[kOptions] = buildMockOptions(opts)
- }
+ #info = {}
+ #fragments = []
- get (origin) {
- let dispatcher = this[kMockAgentGet](origin)
+ /** @type {Map} */
+ #extensions
- if (!dispatcher) {
- dispatcher = this[kFactory](origin)
- this[kMockAgentSet](origin, dispatcher)
- }
- return dispatcher
- }
+ /**
+ * @param {import('./websocket').WebSocket} ws
+ * @param {Map|null} extensions
+ */
+ constructor (ws, extensions) {
+ super()
- dispatch (opts, handler) {
- // Call MockAgent.get to perform additional setup before dispatching as normal
- this.get(opts.origin)
- return this[kAgent].dispatch(opts, handler)
- }
+ this.ws = ws
+ this.#extensions = extensions == null ? new Map() : extensions
- async close () {
- await this[kAgent].close()
- this[kClients].clear()
+ if (this.#extensions.has('permessage-deflate')) {
+ this.#extensions.set('permessage-deflate', new PerMessageDeflate(extensions))
+ }
}
- deactivate () {
- this[kIsMockActive] = false
- }
+ /**
+ * @param {Buffer} chunk
+ * @param {() => void} callback
+ */
+ _write (chunk, _, callback) {
+ this.#buffers.push(chunk)
+ this.#byteOffset += chunk.length
+ this.#loop = true
- activate () {
- this[kIsMockActive] = true
+ this.run(callback)
}
- enableNetConnect (matcher) {
- if (typeof matcher === 'string' || typeof matcher === 'function' || matcher instanceof RegExp) {
- if (Array.isArray(this[kNetConnect])) {
- this[kNetConnect].push(matcher)
- } else {
- this[kNetConnect] = [matcher]
- }
- } else if (typeof matcher === 'undefined') {
- this[kNetConnect] = true
- } else {
- throw new InvalidArgumentError('Unsupported matcher. Must be one of String|Function|RegExp.')
- }
- }
+ /**
+ * Runs whenever a new chunk is received.
+ * Callback is called whenever there are no more chunks buffering,
+ * or not enough bytes are buffered to parse.
+ */
+ run (callback) {
+ while (this.#loop) {
+ if (this.#state === parserStates.INFO) {
+ // If there aren't enough bytes to parse the payload length, etc.
+ if (this.#byteOffset < 2) {
+ return callback()
+ }
- disableNetConnect () {
- this[kNetConnect] = false
- }
+ const buffer = this.consume(2)
+ const fin = (buffer[0] & 0x80) !== 0
+ const opcode = buffer[0] & 0x0F
+ const masked = (buffer[1] & 0x80) === 0x80
- // This is required to bypass issues caused by using global symbols - see:
- // https://github.com/nodejs/undici/issues/1447
- get isMockActive () {
- return this[kIsMockActive]
- }
+ const fragmented = !fin && opcode !== opcodes.CONTINUATION
+ const payloadLength = buffer[1] & 0x7F
- [kMockAgentSet] (origin, dispatcher) {
- this[kClients].set(origin, dispatcher)
- }
+ const rsv1 = buffer[0] & 0x40
+ const rsv2 = buffer[0] & 0x20
+ const rsv3 = buffer[0] & 0x10
- [kFactory] (origin) {
- const mockOptions = Object.assign({ agent: this }, this[kOptions])
- return this[kOptions] && this[kOptions].connections === 1
- ? new MockClient(origin, mockOptions)
- : new MockPool(origin, mockOptions)
- }
+ if (!isValidOpcode(opcode)) {
+ failWebsocketConnection(this.ws, 'Invalid opcode received')
+ return callback()
+ }
- [kMockAgentGet] (origin) {
- // First check if we can immediately find it
- const client = this[kClients].get(origin)
- if (client) {
- return client
- }
+ if (masked) {
+ failWebsocketConnection(this.ws, 'Frame cannot be masked')
+ return callback()
+ }
- // If the origin is not a string create a dummy parent pool and return to user
- if (typeof origin !== 'string') {
- const dispatcher = this[kFactory]('http://localhost:9999')
- this[kMockAgentSet](origin, dispatcher)
- return dispatcher
- }
+ // MUST be 0 unless an extension is negotiated that defines meanings
+ // for non-zero values. If a nonzero value is received and none of
+ // the negotiated extensions defines the meaning of such a nonzero
+ // value, the receiving endpoint MUST _Fail the WebSocket
+ // Connection_.
+ // This document allocates the RSV1 bit of the WebSocket header for
+ // PMCEs and calls the bit the "Per-Message Compressed" bit. On a
+ // WebSocket connection where a PMCE is in use, this bit indicates
+ // whether a message is compressed or not.
+ if (rsv1 !== 0 && !this.#extensions.has('permessage-deflate')) {
+ failWebsocketConnection(this.ws, 'Expected RSV1 to be clear.')
+ return
+ }
- // If we match, create a pool and assign the same dispatches
- for (const [keyMatcher, nonExplicitDispatcher] of Array.from(this[kClients])) {
- if (nonExplicitDispatcher && typeof keyMatcher !== 'string' && matchValue(keyMatcher, origin)) {
- const dispatcher = this[kFactory](origin)
- this[kMockAgentSet](origin, dispatcher)
- dispatcher[kDispatches] = nonExplicitDispatcher[kDispatches]
- return dispatcher
- }
- }
- }
+ if (rsv2 !== 0 || rsv3 !== 0) {
+ failWebsocketConnection(this.ws, 'RSV1, RSV2, RSV3 must be clear')
+ return
+ }
- [kGetNetConnect] () {
- return this[kNetConnect]
- }
+ if (fragmented && !isTextBinaryFrame(opcode)) {
+ // Only text and binary frames can be fragmented
+ failWebsocketConnection(this.ws, 'Invalid frame type was fragmented.')
+ return
+ }
- pendingInterceptors () {
- const mockAgentClients = this[kClients]
+ // If we are already parsing a text/binary frame and do not receive either
+ // a continuation frame or close frame, fail the connection.
+ if (isTextBinaryFrame(opcode) && this.#fragments.length > 0) {
+ failWebsocketConnection(this.ws, 'Expected continuation frame')
+ return
+ }
- return Array.from(mockAgentClients.entries())
- .flatMap(([origin, scope]) => scope[kDispatches].map(dispatch => ({ ...dispatch, origin })))
- .filter(({ pending }) => pending)
- }
+ if (this.#info.fragmented && fragmented) {
+ // A fragmented frame can't be fragmented itself
+ failWebsocketConnection(this.ws, 'Fragmented frame exceeded 125 bytes.')
+ return
+ }
- assertNoPendingInterceptors ({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) {
- const pending = this.pendingInterceptors()
+ // "All control frames MUST have a payload length of 125 bytes or less
+ // and MUST NOT be fragmented."
+ if ((payloadLength > 125 || fragmented) && isControlFrame(opcode)) {
+ failWebsocketConnection(this.ws, 'Control frame either too large or fragmented')
+ return
+ }
- if (pending.length === 0) {
- return
- }
+ if (isContinuationFrame(opcode) && this.#fragments.length === 0 && !this.#info.compressed) {
+ failWebsocketConnection(this.ws, 'Unexpected continuation frame')
+ return
+ }
- const pluralizer = new Pluralizer('interceptor', 'interceptors').pluralize(pending.length)
+ if (payloadLength <= 125) {
+ this.#info.payloadLength = payloadLength
+ this.#state = parserStates.READ_DATA
+ } else if (payloadLength === 126) {
+ this.#state = parserStates.PAYLOADLENGTH_16
+ } else if (payloadLength === 127) {
+ this.#state = parserStates.PAYLOADLENGTH_64
+ }
- throw new UndiciError(`
-${pluralizer.count} ${pluralizer.noun} ${pluralizer.is} pending:
+ if (isTextBinaryFrame(opcode)) {
+ this.#info.binaryType = opcode
+ this.#info.compressed = rsv1 !== 0
+ }
-${pendingInterceptorsFormatter.format(pending)}
-`.trim())
- }
-}
+ this.#info.opcode = opcode
+ this.#info.masked = masked
+ this.#info.fin = fin
+ this.#info.fragmented = fragmented
+ } else if (this.#state === parserStates.PAYLOADLENGTH_16) {
+ if (this.#byteOffset < 2) {
+ return callback()
+ }
-module.exports = MockAgent
+ const buffer = this.consume(2)
+ this.#info.payloadLength = buffer.readUInt16BE(0)
+ this.#state = parserStates.READ_DATA
+ } else if (this.#state === parserStates.PAYLOADLENGTH_64) {
+ if (this.#byteOffset < 8) {
+ return callback()
+ }
-/***/ }),
+ const buffer = this.consume(8)
+ const upper = buffer.readUInt32BE(0)
+ const lower = buffer.readUInt32BE(4)
-/***/ 8957:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 2^31 is the maximum bytes an arraybuffer can contain
+ // on 32-bit systems. Although, on 64-bit systems, this is
+ // 2^53-1 bytes.
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_array_length
+ // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/common/globals.h;drc=1946212ac0100668f14eb9e2843bdd846e510a1e;bpv=1;bpt=1;l=1275
+ // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/js-array-buffer.h;l=34;drc=1946212ac0100668f14eb9e2843bdd846e510a1e
+ if (upper !== 0 || lower > 2 ** 31 - 1) {
+ failWebsocketConnection(this.ws, 'Received payload length > 2^31 bytes.')
+ return
+ }
+ this.#info.payloadLength = lower
+ this.#state = parserStates.READ_DATA
+ } else if (this.#state === parserStates.READ_DATA) {
+ if (this.#byteOffset < this.#info.payloadLength) {
+ return callback()
+ }
+ const body = this.consume(this.#info.payloadLength)
-const { promisify } = __nccwpck_require__(7975)
-const Client = __nccwpck_require__(3069)
-const { buildMockDispatch } = __nccwpck_require__(1725)
-const {
- kDispatches,
- kMockAgent,
- kClose,
- kOriginalClose,
- kOrigin,
- kOriginalDispatch,
- kConnected
-} = __nccwpck_require__(8149)
-const { MockInterceptor } = __nccwpck_require__(1599)
-const Symbols = __nccwpck_require__(9411)
-const { InvalidArgumentError } = __nccwpck_require__(8091)
+ if (isControlFrame(this.#info.opcode)) {
+ this.#loop = this.parseControlFrame(body)
+ this.#state = parserStates.INFO
+ } else {
+ if (!this.#info.compressed) {
+ this.#fragments.push(body)
-/**
- * MockClient provides an API that extends the Client to influence the mockDispatches.
- */
-class MockClient extends Client {
- constructor (origin, opts) {
- super(origin, opts)
+ // If the frame is not fragmented, a message has been received.
+ // If the frame is fragmented, it will terminate with a fin bit set
+ // and an opcode of 0 (continuation), therefore we handle that when
+ // parsing continuation frames, not here.
+ if (!this.#info.fragmented && this.#info.fin) {
+ const fullMessage = Buffer.concat(this.#fragments)
+ websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage)
+ this.#fragments.length = 0
+ }
- if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') {
- throw new InvalidArgumentError('Argument opts.agent must implement Agent')
- }
+ this.#state = parserStates.INFO
+ } else {
+ this.#extensions.get('permessage-deflate').decompress(body, this.#info.fin, (error, data) => {
+ if (error) {
+ failWebsocketConnection(this.ws, error.message)
+ return
+ }
- this[kMockAgent] = opts.agent
- this[kOrigin] = origin
- this[kDispatches] = []
- this[kConnected] = 1
- this[kOriginalDispatch] = this.dispatch
- this[kOriginalClose] = this.close.bind(this)
+ this.#fragments.push(data)
- this.dispatch = buildMockDispatch.call(this)
- this.close = this[kClose]
- }
+ if (!this.#info.fin) {
+ this.#state = parserStates.INFO
+ this.#loop = true
+ this.run(callback)
+ return
+ }
- get [Symbols.kConnected] () {
- return this[kConnected]
+ websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments))
+
+ this.#loop = true
+ this.#state = parserStates.INFO
+ this.#fragments.length = 0
+ this.run(callback)
+ })
+
+ this.#loop = false
+ break
+ }
+ }
+ }
+ }
}
/**
- * Sets up the base interceptor for mocking replies from undici.
+ * Take n bytes from the buffered Buffers
+ * @param {number} n
+ * @returns {Buffer}
*/
- intercept (opts) {
- return new MockInterceptor(opts, this[kDispatches])
+ consume (n) {
+ if (n > this.#byteOffset) {
+ throw new Error('Called consume() before buffers satiated.')
+ } else if (n === 0) {
+ return emptyBuffer
+ }
+
+ if (this.#buffers[0].length === n) {
+ this.#byteOffset -= this.#buffers[0].length
+ return this.#buffers.shift()
+ }
+
+ const buffer = Buffer.allocUnsafe(n)
+ let offset = 0
+
+ while (offset !== n) {
+ const next = this.#buffers[0]
+ const { length } = next
+
+ if (length + offset === n) {
+ buffer.set(this.#buffers.shift(), offset)
+ break
+ } else if (length + offset > n) {
+ buffer.set(next.subarray(0, n - offset), offset)
+ this.#buffers[0] = next.subarray(n - offset)
+ break
+ } else {
+ buffer.set(this.#buffers.shift(), offset)
+ offset += next.length
+ }
+ }
+
+ this.#byteOffset -= n
+
+ return buffer
}
- async [kClose] () {
- await promisify(this[kOriginalClose])()
- this[kConnected] = 0
- this[kMockAgent][Symbols.kClients].delete(this[kOrigin])
+ parseCloseBody (data) {
+ assert(data.length !== 1)
+
+ // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5
+ /** @type {number|undefined} */
+ let code
+
+ if (data.length >= 2) {
+ // _The WebSocket Connection Close Code_ is
+ // defined as the status code (Section 7.4) contained in the first Close
+ // control frame received by the application
+ code = data.readUInt16BE(0)
+ }
+
+ if (code !== undefined && !isValidStatusCode(code)) {
+ return { code: 1002, reason: 'Invalid status code', error: true }
+ }
+
+ // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6
+ /** @type {Buffer} */
+ let reason = data.subarray(2)
+
+ // Remove BOM
+ if (reason[0] === 0xEF && reason[1] === 0xBB && reason[2] === 0xBF) {
+ reason = reason.subarray(3)
+ }
+
+ try {
+ reason = utf8Decode(reason)
+ } catch {
+ return { code: 1007, reason: 'Invalid UTF-8', error: true }
+ }
+
+ return { code, reason, error: false }
}
-}
-module.exports = MockClient
+ /**
+ * Parses control frames.
+ * @param {Buffer} body
+ */
+ parseControlFrame (body) {
+ const { opcode, payloadLength } = this.#info
+ if (opcode === opcodes.CLOSE) {
+ if (payloadLength === 1) {
+ failWebsocketConnection(this.ws, 'Received close frame with a 1-byte body.')
+ return false
+ }
-/***/ }),
+ this.#info.closeInfo = this.parseCloseBody(body)
-/***/ 5445:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ if (this.#info.closeInfo.error) {
+ const { code, reason } = this.#info.closeInfo
+
+ closeWebSocketConnection(this.ws, code, reason, reason.length)
+ failWebsocketConnection(this.ws, reason)
+ return false
+ }
+
+ if (this.ws[kSentClose] !== sentCloseFrameState.SENT) {
+ // If an endpoint receives a Close frame and did not previously send a
+ // Close frame, the endpoint MUST send a Close frame in response. (When
+ // sending a Close frame in response, the endpoint typically echos the
+ // status code it received.)
+ let body = emptyBuffer
+ if (this.#info.closeInfo.code) {
+ body = Buffer.allocUnsafe(2)
+ body.writeUInt16BE(this.#info.closeInfo.code, 0)
+ }
+ const closeFrame = new WebsocketFrameSend(body)
+ this.ws[kResponse].socket.write(
+ closeFrame.createFrame(opcodes.CLOSE),
+ (err) => {
+ if (!err) {
+ this.ws[kSentClose] = sentCloseFrameState.SENT
+ }
+ }
+ )
+ }
+ // Upon either sending or receiving a Close control frame, it is said
+ // that _The WebSocket Closing Handshake is Started_ and that the
+ // WebSocket connection is in the CLOSING state.
+ this.ws[kReadyState] = states.CLOSING
+ this.ws[kReceivedClose] = true
-const { UndiciError } = __nccwpck_require__(8091)
+ return false
+ } else if (opcode === opcodes.PING) {
+ // Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in
+ // response, unless it already received a Close frame.
+ // A Pong frame sent in response to a Ping frame must have identical
+ // "Application data"
-const kMockNotMatchedError = Symbol.for('undici.error.UND_MOCK_ERR_MOCK_NOT_MATCHED')
+ if (!this.ws[kReceivedClose]) {
+ const frame = new WebsocketFrameSend(body)
-/**
- * The request does not match any registered mock dispatches.
- */
-class MockNotMatchedError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, MockNotMatchedError)
- this.name = 'MockNotMatchedError'
- this.message = message || 'The request does not match any registered mock dispatches'
- this.code = 'UND_MOCK_ERR_MOCK_NOT_MATCHED'
- }
+ this.ws[kResponse].socket.write(frame.createFrame(opcodes.PONG))
- static [Symbol.hasInstance] (instance) {
- return instance && instance[kMockNotMatchedError] === true
+ if (channels.ping.hasSubscribers) {
+ channels.ping.publish({
+ payload: body
+ })
+ }
+ }
+ } else if (opcode === opcodes.PONG) {
+ // A Pong frame MAY be sent unsolicited. This serves as a
+ // unidirectional heartbeat. A response to an unsolicited Pong frame is
+ // not expected.
+
+ if (channels.pong.hasSubscribers) {
+ channels.pong.publish({
+ payload: body
+ })
+ }
+ }
+
+ return true
}
- [kMockNotMatchedError] = true
+ get closingInfo () {
+ return this.#info.closeInfo
+ }
}
module.exports = {
- MockNotMatchedError
+ ByteParser
}
/***/ }),
-/***/ 1599:
+/***/ 3900:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const { getResponseData, buildKey, addMockDispatch } = __nccwpck_require__(1725)
-const {
- kDispatches,
- kDispatchKey,
- kDefaultHeaders,
- kDefaultTrailers,
- kContentLength,
- kMockDispatch
-} = __nccwpck_require__(8149)
-const { InvalidArgumentError } = __nccwpck_require__(8091)
-const { buildURL } = __nccwpck_require__(1544)
+const { WebsocketFrameSend } = __nccwpck_require__(3264)
+const { opcodes, sendHints } = __nccwpck_require__(736)
+const FixedQueue = __nccwpck_require__(4660)
+
+/** @type {typeof Uint8Array} */
+const FastBuffer = Buffer[Symbol.species]
/**
- * Defines the scope API for an interceptor reply
+ * @typedef {object} SendQueueNode
+ * @property {Promise | null} promise
+ * @property {((...args: any[]) => any)} callback
+ * @property {Buffer | null} frame
*/
-class MockScope {
- constructor (mockDispatch) {
- this[kMockDispatch] = mockDispatch
- }
+class SendQueue {
/**
- * Delay a reply by a set amount in ms.
+ * @type {FixedQueue}
*/
- delay (waitInMs) {
- if (typeof waitInMs !== 'number' || !Number.isInteger(waitInMs) || waitInMs <= 0) {
- throw new InvalidArgumentError('waitInMs must be a valid integer > 0')
- }
-
- this[kMockDispatch].delay = waitInMs
- return this
- }
+ #queue = new FixedQueue()
/**
- * For a defined reply, never mark as consumed.
+ * @type {boolean}
*/
- persist () {
- this[kMockDispatch].persist = true
- return this
- }
+ #running = false
- /**
- * Allow one to define a reply for a set amount of matching requests.
- */
- times (repeatTimes) {
- if (typeof repeatTimes !== 'number' || !Number.isInteger(repeatTimes) || repeatTimes <= 0) {
- throw new InvalidArgumentError('repeatTimes must be a valid integer > 0')
- }
+ /** @type {import('node:net').Socket} */
+ #socket
- this[kMockDispatch].times = repeatTimes
- return this
+ constructor (socket) {
+ this.#socket = socket
}
-}
-/**
- * Defines an interceptor for a Mock
- */
-class MockInterceptor {
- constructor (opts, mockDispatches) {
- if (typeof opts !== 'object') {
- throw new InvalidArgumentError('opts must be an object')
- }
- if (typeof opts.path === 'undefined') {
- throw new InvalidArgumentError('opts.path must be defined')
- }
- if (typeof opts.method === 'undefined') {
- opts.method = 'GET'
- }
- // See https://github.com/nodejs/undici/issues/1245
- // As per RFC 3986, clients are not supposed to send URI
- // fragments to servers when they retrieve a document,
- if (typeof opts.path === 'string') {
- if (opts.query) {
- opts.path = buildURL(opts.path, opts.query)
+ add (item, cb, hint) {
+ if (hint !== sendHints.blob) {
+ const frame = createFrame(item, hint)
+ if (!this.#running) {
+ // fast-path
+ this.#socket.write(frame, cb)
} else {
- // Matches https://github.com/nodejs/undici/blob/main/lib/web/fetch/index.js#L1811
- const parsedURL = new URL(opts.path, 'data://')
- opts.path = parsedURL.pathname + parsedURL.search
+ /** @type {SendQueueNode} */
+ const node = {
+ promise: null,
+ callback: cb,
+ frame
+ }
+ this.#queue.push(node)
}
+ return
}
- if (typeof opts.method === 'string') {
- opts.method = opts.method.toUpperCase()
- }
-
- this[kDispatchKey] = buildKey(opts)
- this[kDispatches] = mockDispatches
- this[kDefaultHeaders] = {}
- this[kDefaultTrailers] = {}
- this[kContentLength] = false
- }
- createMockScopeDispatchData ({ statusCode, data, responseOptions }) {
- const responseData = getResponseData(data)
- const contentLength = this[kContentLength] ? { 'content-length': responseData.length } : {}
- const headers = { ...this[kDefaultHeaders], ...contentLength, ...responseOptions.headers }
- const trailers = { ...this[kDefaultTrailers], ...responseOptions.trailers }
+ /** @type {SendQueueNode} */
+ const node = {
+ promise: item.arrayBuffer().then((ab) => {
+ node.promise = null
+ node.frame = createFrame(ab, hint)
+ }),
+ callback: cb,
+ frame: null
+ }
- return { statusCode, data, headers, trailers }
- }
+ this.#queue.push(node)
- validateReplyParameters (replyParameters) {
- if (typeof replyParameters.statusCode === 'undefined') {
- throw new InvalidArgumentError('statusCode must be defined')
- }
- if (typeof replyParameters.responseOptions !== 'object' || replyParameters.responseOptions === null) {
- throw new InvalidArgumentError('responseOptions must be an object')
+ if (!this.#running) {
+ this.#run()
}
}
- /**
- * Mock an undici request with a defined reply.
- */
- reply (replyOptionsCallbackOrStatusCode) {
- // Values of reply aren't available right now as they
- // can only be available when the reply callback is invoked.
- if (typeof replyOptionsCallbackOrStatusCode === 'function') {
- // We'll first wrap the provided callback in another function,
- // this function will properly resolve the data from the callback
- // when invoked.
- const wrappedDefaultsCallback = (opts) => {
- // Our reply options callback contains the parameter for statusCode, data and options.
- const resolvedData = replyOptionsCallbackOrStatusCode(opts)
-
- // Check if it is in the right format
- if (typeof resolvedData !== 'object' || resolvedData === null) {
- throw new InvalidArgumentError('reply options callback must return an object')
- }
-
- const replyParameters = { data: '', responseOptions: {}, ...resolvedData }
- this.validateReplyParameters(replyParameters)
- // Since the values can be obtained immediately we return them
- // from this higher order function that will be resolved later.
- return {
- ...this.createMockScopeDispatchData(replyParameters)
- }
+ async #run () {
+ this.#running = true
+ const queue = this.#queue
+ while (!queue.isEmpty()) {
+ const node = queue.shift()
+ // wait pending promise
+ if (node.promise !== null) {
+ await node.promise
}
-
- // Add usual dispatch data, but this time set the data parameter to function that will eventually provide data.
- const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], wrappedDefaultsCallback)
- return new MockScope(newMockDispatch)
+ // write
+ this.#socket.write(node.frame, node.callback)
+ // cleanup
+ node.callback = node.frame = null
}
+ this.#running = false
+ }
+}
- // We can have either one or three parameters, if we get here,
- // we should have 1-3 parameters. So we spread the arguments of
- // this function to obtain the parameters, since replyData will always
- // just be the statusCode.
- const replyParameters = {
- statusCode: replyOptionsCallbackOrStatusCode,
- data: arguments[1] === undefined ? '' : arguments[1],
- responseOptions: arguments[2] === undefined ? {} : arguments[2]
- }
- this.validateReplyParameters(replyParameters)
+function createFrame (data, hint) {
+ return new WebsocketFrameSend(toBuffer(data, hint)).createFrame(hint === sendHints.string ? opcodes.TEXT : opcodes.BINARY)
+}
- // Send in-already provided data like usual
- const dispatchData = this.createMockScopeDispatchData(replyParameters)
- const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], dispatchData)
- return new MockScope(newMockDispatch)
+function toBuffer (data, hint) {
+ switch (hint) {
+ case sendHints.string:
+ return Buffer.from(data)
+ case sendHints.arrayBuffer:
+ case sendHints.blob:
+ return new FastBuffer(data)
+ case sendHints.typedArray:
+ return new FastBuffer(data.buffer, data.byteOffset, data.byteLength)
}
+}
- /**
- * Mock an undici request with a defined error.
- */
- replyWithError (error) {
- if (typeof error === 'undefined') {
- throw new InvalidArgumentError('error must be defined')
- }
+module.exports = { SendQueue }
- const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error })
- return new MockScope(newMockDispatch)
- }
- /**
- * Set default reply headers on the interceptor for subsequent replies
- */
- defaultReplyHeaders (headers) {
- if (typeof headers === 'undefined') {
- throw new InvalidArgumentError('headers must be defined')
- }
+/***/ }),
- this[kDefaultHeaders] = headers
- return this
- }
+/***/ 1216:
+/***/ ((module) => {
- /**
- * Set default reply trailers on the interceptor for subsequent replies
- */
- defaultReplyTrailers (trailers) {
- if (typeof trailers === 'undefined') {
- throw new InvalidArgumentError('trailers must be defined')
- }
- this[kDefaultTrailers] = trailers
- return this
- }
- /**
- * Set reply content length header for replies on the interceptor
- */
- replyContentLength () {
- this[kContentLength] = true
- return this
- }
+module.exports = {
+ kWebSocketURL: Symbol('url'),
+ kReadyState: Symbol('ready state'),
+ kController: Symbol('controller'),
+ kResponse: Symbol('response'),
+ kBinaryType: Symbol('binary type'),
+ kSentClose: Symbol('sent close'),
+ kReceivedClose: Symbol('received close'),
+ kByteParser: Symbol('byte parser')
}
-module.exports.MockInterceptor = MockInterceptor
-module.exports.MockScope = MockScope
-
/***/ }),
-/***/ 8780:
+/***/ 8625:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const { promisify } = __nccwpck_require__(7975)
-const Pool = __nccwpck_require__(7404)
-const { buildMockDispatch } = __nccwpck_require__(1725)
-const {
- kDispatches,
- kMockAgent,
- kClose,
- kOriginalClose,
- kOrigin,
- kOriginalDispatch,
- kConnected
-} = __nccwpck_require__(8149)
-const { MockInterceptor } = __nccwpck_require__(1599)
-const Symbols = __nccwpck_require__(9411)
-const { InvalidArgumentError } = __nccwpck_require__(8091)
+const { kReadyState, kController, kResponse, kBinaryType, kWebSocketURL } = __nccwpck_require__(1216)
+const { states, opcodes } = __nccwpck_require__(736)
+const { ErrorEvent, createFastMessageEvent } = __nccwpck_require__(5188)
+const { isUtf8 } = __nccwpck_require__(4573)
+const { collectASequenceOfCodePointsFast, removeHTTPWhitespace } = __nccwpck_require__(1900)
+
+/* globals Blob */
/**
- * MockPool provides an API that extends the Pool to influence the mockDispatches.
+ * @param {import('./websocket').WebSocket} ws
+ * @returns {boolean}
*/
-class MockPool extends Pool {
- constructor (origin, opts) {
- super(origin, opts)
+function isConnecting (ws) {
+ // If the WebSocket connection is not yet established, and the connection
+ // is not yet closed, then the WebSocket connection is in the CONNECTING state.
+ return ws[kReadyState] === states.CONNECTING
+}
- if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') {
- throw new InvalidArgumentError('Argument opts.agent must implement Agent')
- }
+/**
+ * @param {import('./websocket').WebSocket} ws
+ * @returns {boolean}
+ */
+function isEstablished (ws) {
+ // If the server's response is validated as provided for above, it is
+ // said that _The WebSocket Connection is Established_ and that the
+ // WebSocket Connection is in the OPEN state.
+ return ws[kReadyState] === states.OPEN
+}
- this[kMockAgent] = opts.agent
- this[kOrigin] = origin
- this[kDispatches] = []
- this[kConnected] = 1
- this[kOriginalDispatch] = this.dispatch
- this[kOriginalClose] = this.close.bind(this)
+/**
+ * @param {import('./websocket').WebSocket} ws
+ * @returns {boolean}
+ */
+function isClosing (ws) {
+ // Upon either sending or receiving a Close control frame, it is said
+ // that _The WebSocket Closing Handshake is Started_ and that the
+ // WebSocket connection is in the CLOSING state.
+ return ws[kReadyState] === states.CLOSING
+}
- this.dispatch = buildMockDispatch.call(this)
- this.close = this[kClose]
- }
+/**
+ * @param {import('./websocket').WebSocket} ws
+ * @returns {boolean}
+ */
+function isClosed (ws) {
+ return ws[kReadyState] === states.CLOSED
+}
- get [Symbols.kConnected] () {
- return this[kConnected]
- }
+/**
+ * @see https://dom.spec.whatwg.org/#concept-event-fire
+ * @param {string} e
+ * @param {EventTarget} target
+ * @param {(...args: ConstructorParameters) => Event} eventFactory
+ * @param {EventInit | undefined} eventInitDict
+ */
+function fireEvent (e, target, eventFactory = (type, init) => new Event(type, init), eventInitDict = {}) {
+ // 1. If eventConstructor is not given, then let eventConstructor be Event.
- /**
- * Sets up the base interceptor for mocking replies from undici.
- */
- intercept (opts) {
- return new MockInterceptor(opts, this[kDispatches])
- }
+ // 2. Let event be the result of creating an event given eventConstructor,
+ // in the relevant realm of target.
+ // 3. Initialize event’s type attribute to e.
+ const event = eventFactory(e, eventInitDict)
- async [kClose] () {
- await promisify(this[kOriginalClose])()
- this[kConnected] = 0
- this[kMockAgent][Symbols.kClients].delete(this[kOrigin])
- }
+ // 4. Initialize any other IDL attributes of event as described in the
+ // invocation of this algorithm.
+
+ // 5. Return the result of dispatching event at target, with legacy target
+ // override flag set if set.
+ target.dispatchEvent(event)
}
-module.exports = MockPool
+/**
+ * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
+ * @param {import('./websocket').WebSocket} ws
+ * @param {number} type Opcode
+ * @param {Buffer} data application data
+ */
+function websocketMessageReceived (ws, type, data) {
+ // 1. If ready state is not OPEN (1), then return.
+ if (ws[kReadyState] !== states.OPEN) {
+ return
+ }
+ // 2. Let dataForEvent be determined by switching on type and binary type:
+ let dataForEvent
-/***/ }),
+ if (type === opcodes.TEXT) {
+ // -> type indicates that the data is Text
+ // a new DOMString containing data
+ try {
+ dataForEvent = utf8Decode(data)
+ } catch {
+ failWebsocketConnection(ws, 'Received invalid UTF-8 in text frame.')
+ return
+ }
+ } else if (type === opcodes.BINARY) {
+ if (ws[kBinaryType] === 'blob') {
+ // -> type indicates that the data is Binary and binary type is "blob"
+ // a new Blob object, created in the relevant Realm of the WebSocket
+ // object, that represents data as its raw data
+ dataForEvent = new Blob([data])
+ } else {
+ // -> type indicates that the data is Binary and binary type is "arraybuffer"
+ // a new ArrayBuffer object, created in the relevant Realm of the
+ // WebSocket object, whose contents are data
+ dataForEvent = toArrayBuffer(data)
+ }
+ }
-/***/ 8149:
-/***/ ((module) => {
+ // 3. Fire an event named message at the WebSocket object, using MessageEvent,
+ // with the origin attribute initialized to the serialization of the WebSocket
+ // object’s url's origin, and the data attribute initialized to dataForEvent.
+ fireEvent('message', ws, createFastMessageEvent, {
+ origin: ws[kWebSocketURL].origin,
+ data: dataForEvent
+ })
+}
+function toArrayBuffer (buffer) {
+ if (buffer.byteLength === buffer.buffer.byteLength) {
+ return buffer.buffer
+ }
+ return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength)
+}
+/**
+ * @see https://datatracker.ietf.org/doc/html/rfc6455
+ * @see https://datatracker.ietf.org/doc/html/rfc2616
+ * @see https://bugs.chromium.org/p/chromium/issues/detail?id=398407
+ * @param {string} protocol
+ */
+function isValidSubprotocol (protocol) {
+ // If present, this value indicates one
+ // or more comma-separated subprotocol the client wishes to speak,
+ // ordered by preference. The elements that comprise this value
+ // MUST be non-empty strings with characters in the range U+0021 to
+ // U+007E not including separator characters as defined in
+ // [RFC2616] and MUST all be unique strings.
+ if (protocol.length === 0) {
+ return false
+ }
-module.exports = {
- kAgent: Symbol('agent'),
- kOptions: Symbol('options'),
- kFactory: Symbol('factory'),
- kDispatches: Symbol('dispatches'),
- kDispatchKey: Symbol('dispatch key'),
- kDefaultHeaders: Symbol('default headers'),
- kDefaultTrailers: Symbol('default trailers'),
- kContentLength: Symbol('content length'),
- kMockAgent: Symbol('mock agent'),
- kMockAgentSet: Symbol('mock agent set'),
- kMockAgentGet: Symbol('mock agent get'),
- kMockDispatch: Symbol('mock dispatch'),
- kClose: Symbol('close'),
- kOriginalClose: Symbol('original agent close'),
- kOrigin: Symbol('origin'),
- kIsMockActive: Symbol('is mock active'),
- kNetConnect: Symbol('net connect'),
- kGetNetConnect: Symbol('get net connect'),
- kConnected: Symbol('connected')
-}
+ for (let i = 0; i < protocol.length; ++i) {
+ const code = protocol.charCodeAt(i)
+
+ if (
+ code < 0x21 || // CTL, contains SP (0x20) and HT (0x09)
+ code > 0x7E ||
+ code === 0x22 || // "
+ code === 0x28 || // (
+ code === 0x29 || // )
+ code === 0x2C || // ,
+ code === 0x2F || // /
+ code === 0x3A || // :
+ code === 0x3B || // ;
+ code === 0x3C || // <
+ code === 0x3D || // =
+ code === 0x3E || // >
+ code === 0x3F || // ?
+ code === 0x40 || // @
+ code === 0x5B || // [
+ code === 0x5C || // \
+ code === 0x5D || // ]
+ code === 0x7B || // {
+ code === 0x7D // }
+ ) {
+ return false
+ }
+ }
+ return true
+}
-/***/ }),
+/**
+ * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7-4
+ * @param {number} code
+ */
+function isValidStatusCode (code) {
+ if (code >= 1000 && code < 1015) {
+ return (
+ code !== 1004 && // reserved
+ code !== 1005 && // "MUST NOT be set as a status code"
+ code !== 1006 // "MUST NOT be set as a status code"
+ )
+ }
-/***/ 1725:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ return code >= 3000 && code <= 4999
+}
+/**
+ * @param {import('./websocket').WebSocket} ws
+ * @param {string|undefined} reason
+ */
+function failWebsocketConnection (ws, reason) {
+ const { [kController]: controller, [kResponse]: response } = ws
+ controller.abort()
-const { MockNotMatchedError } = __nccwpck_require__(5445)
-const {
- kDispatches,
- kMockAgent,
- kOriginalDispatch,
- kOrigin,
- kGetNetConnect
-} = __nccwpck_require__(8149)
-const { buildURL } = __nccwpck_require__(1544)
-const { STATUS_CODES } = __nccwpck_require__(7067)
-const {
- types: {
- isPromise
+ if (response?.socket && !response.socket.destroyed) {
+ response.socket.destroy()
}
-} = __nccwpck_require__(7975)
-function matchValue (match, value) {
- if (typeof match === 'string') {
- return match === value
- }
- if (match instanceof RegExp) {
- return match.test(value)
- }
- if (typeof match === 'function') {
- return match(value) === true
+ if (reason) {
+ // TODO: process.nextTick
+ fireEvent('error', ws, (type, init) => new ErrorEvent(type, init), {
+ error: new Error(reason),
+ message: reason
+ })
}
- return false
}
-function lowerCaseEntries (headers) {
- return Object.fromEntries(
- Object.entries(headers).map(([headerName, headerValue]) => {
- return [headerName.toLocaleLowerCase(), headerValue]
- })
+/**
+ * @see https://datatracker.ietf.org/doc/html/rfc6455#section-5.5
+ * @param {number} opcode
+ */
+function isControlFrame (opcode) {
+ return (
+ opcode === opcodes.CLOSE ||
+ opcode === opcodes.PING ||
+ opcode === opcodes.PONG
)
}
+function isContinuationFrame (opcode) {
+ return opcode === opcodes.CONTINUATION
+}
+
+function isTextBinaryFrame (opcode) {
+ return opcode === opcodes.TEXT || opcode === opcodes.BINARY
+}
+
+function isValidOpcode (opcode) {
+ return isTextBinaryFrame(opcode) || isContinuationFrame(opcode) || isControlFrame(opcode)
+}
+
/**
- * @param {import('../../index').Headers|string[]|Record} headers
- * @param {string} key
+ * Parses a Sec-WebSocket-Extensions header value.
+ * @param {string} extensions
+ * @returns {Map}
*/
-function getHeaderByName (headers, key) {
- if (Array.isArray(headers)) {
- for (let i = 0; i < headers.length; i += 2) {
- if (headers[i].toLocaleLowerCase() === key.toLocaleLowerCase()) {
- return headers[i + 1]
- }
- }
+// TODO(@Uzlopak, @KhafraDev): make compliant https://datatracker.ietf.org/doc/html/rfc6455#section-9.1
+function parseExtensions (extensions) {
+ const position = { position: 0 }
+ const extensionList = new Map()
- return undefined
- } else if (typeof headers.get === 'function') {
- return headers.get(key)
- } else {
- return lowerCaseEntries(headers)[key.toLocaleLowerCase()]
- }
-}
+ while (position.position < extensions.length) {
+ const pair = collectASequenceOfCodePointsFast(';', extensions, position)
+ const [name, value = ''] = pair.split('=')
-/** @param {string[]} headers */
-function buildHeadersFromArray (headers) { // fetch HeadersList
- const clone = headers.slice()
- const entries = []
- for (let index = 0; index < clone.length; index += 2) {
- entries.push([clone[index], clone[index + 1]])
+ extensionList.set(
+ removeHTTPWhitespace(name, true, false),
+ removeHTTPWhitespace(value, false, true)
+ )
+
+ position.position++
}
- return Object.fromEntries(entries)
+
+ return extensionList
}
-function matchHeaders (mockDispatch, headers) {
- if (typeof mockDispatch.headers === 'function') {
- if (Array.isArray(headers)) { // fetch HeadersList
- headers = buildHeadersFromArray(headers)
- }
- return mockDispatch.headers(headers ? lowerCaseEntries(headers) : {})
- }
- if (typeof mockDispatch.headers === 'undefined') {
- return true
- }
- if (typeof headers !== 'object' || typeof mockDispatch.headers !== 'object') {
+/**
+ * @see https://www.rfc-editor.org/rfc/rfc7692#section-7.1.2.2
+ * @description "client-max-window-bits = 1*DIGIT"
+ * @param {string} value
+ */
+function isValidClientWindowBits (value) {
+ // Must have at least one character
+ if (value.length === 0) {
return false
}
- for (const [matchHeaderName, matchHeaderValue] of Object.entries(mockDispatch.headers)) {
- const headerValue = getHeaderByName(headers, matchHeaderName)
+ // Check all characters are ASCII digits
+ for (let i = 0; i < value.length; i++) {
+ const byte = value.charCodeAt(i)
- if (!matchValue(matchHeaderValue, headerValue)) {
+ if (byte < 0x30 || byte > 0x39) {
return false
}
}
- return true
-}
-function safeUrl (path) {
- if (typeof path !== 'string') {
- return path
- }
+ // Check numeric range: zlib requires windowBits in range 8-15
+ const num = Number.parseInt(value, 10)
+ return num >= 8 && num <= 15
+}
- const pathSegments = path.split('?')
+// https://nodejs.org/api/intl.html#detecting-internationalization-support
+const hasIntl = typeof process.versions.icu === 'string'
+const fatalDecoder = hasIntl ? new TextDecoder('utf-8', { fatal: true }) : undefined
- if (pathSegments.length !== 2) {
- return path
+/**
+ * Converts a Buffer to utf-8, even on platforms without icu.
+ * @param {Buffer} buffer
+ */
+const utf8Decode = hasIntl
+ ? fatalDecoder.decode.bind(fatalDecoder)
+ : function (buffer) {
+ if (isUtf8(buffer)) {
+ return buffer.toString('utf-8')
+ }
+ throw new TypeError('Invalid utf-8 received.')
}
- const qp = new URLSearchParams(pathSegments.pop())
- qp.sort()
- return [...pathSegments, qp.toString()].join('?')
-}
-
-function matchKey (mockDispatch, { path, method, body, headers }) {
- const pathMatch = matchValue(mockDispatch.path, path)
- const methodMatch = matchValue(mockDispatch.method, method)
- const bodyMatch = typeof mockDispatch.body !== 'undefined' ? matchValue(mockDispatch.body, body) : true
- const headersMatch = matchHeaders(mockDispatch, headers)
- return pathMatch && methodMatch && bodyMatch && headersMatch
-}
-
-function getResponseData (data) {
- if (Buffer.isBuffer(data)) {
- return data
- } else if (data instanceof Uint8Array) {
- return data
- } else if (data instanceof ArrayBuffer) {
- return data
- } else if (typeof data === 'object') {
- return JSON.stringify(data)
- } else {
- return data.toString()
- }
+module.exports = {
+ isConnecting,
+ isEstablished,
+ isClosing,
+ isClosed,
+ fireEvent,
+ isValidSubprotocol,
+ isValidStatusCode,
+ failWebsocketConnection,
+ websocketMessageReceived,
+ utf8Decode,
+ isControlFrame,
+ isContinuationFrame,
+ isTextBinaryFrame,
+ isValidOpcode,
+ parseExtensions,
+ isValidClientWindowBits
}
-function getMockDispatch (mockDispatches, key) {
- const basePath = key.query ? buildURL(key.path, key.query) : key.path
- const resolvedPath = typeof basePath === 'string' ? safeUrl(basePath) : basePath
-
- // Match path
- let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path }) => matchValue(safeUrl(path), resolvedPath))
- if (matchedMockDispatches.length === 0) {
- throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`)
- }
-
- // Match method
- matchedMockDispatches = matchedMockDispatches.filter(({ method }) => matchValue(method, key.method))
- if (matchedMockDispatches.length === 0) {
- throw new MockNotMatchedError(`Mock dispatch not matched for method '${key.method}' on path '${resolvedPath}'`)
- }
-
- // Match body
- matchedMockDispatches = matchedMockDispatches.filter(({ body }) => typeof body !== 'undefined' ? matchValue(body, key.body) : true)
- if (matchedMockDispatches.length === 0) {
- throw new MockNotMatchedError(`Mock dispatch not matched for body '${key.body}' on path '${resolvedPath}'`)
- }
- // Match headers
- matchedMockDispatches = matchedMockDispatches.filter((mockDispatch) => matchHeaders(mockDispatch, key.headers))
- if (matchedMockDispatches.length === 0) {
- const headers = typeof key.headers === 'object' ? JSON.stringify(key.headers) : key.headers
- throw new MockNotMatchedError(`Mock dispatch not matched for headers '${headers}' on path '${resolvedPath}'`)
- }
+/***/ }),
- return matchedMockDispatches[0]
-}
+/***/ 3726:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-function addMockDispatch (mockDispatches, key, data) {
- const baseData = { timesInvoked: 0, times: 1, persist: false, consumed: false }
- const replyData = typeof data === 'function' ? { callback: data } : { ...data }
- const newMockDispatch = { ...baseData, ...key, pending: true, data: { error: null, ...replyData } }
- mockDispatches.push(newMockDispatch)
- return newMockDispatch
-}
-function deleteMockDispatch (mockDispatches, key) {
- const index = mockDispatches.findIndex(dispatch => {
- if (!dispatch.consumed) {
- return false
- }
- return matchKey(dispatch, key)
- })
- if (index !== -1) {
- mockDispatches.splice(index, 1)
- }
-}
-function buildKey (opts) {
- const { path, method, body, headers, query } = opts
- return {
- path,
- method,
- body,
- headers,
- query
- }
-}
+const { webidl } = __nccwpck_require__(5893)
+const { URLSerializer } = __nccwpck_require__(1900)
+const { environmentSettingsObject } = __nccwpck_require__(3168)
+const { staticPropertyDescriptors, states, sentCloseFrameState, sendHints } = __nccwpck_require__(736)
+const {
+ kWebSocketURL,
+ kReadyState,
+ kController,
+ kBinaryType,
+ kResponse,
+ kSentClose,
+ kByteParser
+} = __nccwpck_require__(1216)
+const {
+ isConnecting,
+ isEstablished,
+ isClosing,
+ isValidSubprotocol,
+ fireEvent
+} = __nccwpck_require__(8625)
+const { establishWebSocketConnection, closeWebSocketConnection } = __nccwpck_require__(6897)
+const { ByteParser } = __nccwpck_require__(1652)
+const { kEnumerableProperty, isBlobLike } = __nccwpck_require__(3440)
+const { getGlobalDispatcher } = __nccwpck_require__(2581)
+const { types } = __nccwpck_require__(7975)
+const { ErrorEvent, CloseEvent } = __nccwpck_require__(5188)
+const { SendQueue } = __nccwpck_require__(3900)
-function generateKeyValues (data) {
- const keys = Object.keys(data)
- const result = []
- for (let i = 0; i < keys.length; ++i) {
- const key = keys[i]
- const value = data[key]
- const name = Buffer.from(`${key}`)
- if (Array.isArray(value)) {
- for (let j = 0; j < value.length; ++j) {
- result.push(name, Buffer.from(`${value[j]}`))
- }
- } else {
- result.push(name, Buffer.from(`${value}`))
- }
+// https://websockets.spec.whatwg.org/#interface-definition
+class WebSocket extends EventTarget {
+ #events = {
+ open: null,
+ error: null,
+ close: null,
+ message: null
}
- return result
-}
-
-/**
- * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
- * @param {number} statusCode
- */
-function getStatusText (statusCode) {
- return STATUS_CODES[statusCode] || 'unknown'
-}
-async function getResponse (body) {
- const buffers = []
- for await (const data of body) {
- buffers.push(data)
- }
- return Buffer.concat(buffers).toString('utf8')
-}
+ #bufferedAmount = 0
+ #protocol = ''
+ #extensions = ''
-/**
- * Mock dispatch function used to simulate undici dispatches
- */
-function mockDispatch (opts, handler) {
- // Get mock dispatch from built key
- const key = buildKey(opts)
- const mockDispatch = getMockDispatch(this[kDispatches], key)
+ /** @type {SendQueue} */
+ #sendQueue
- mockDispatch.timesInvoked++
+ /**
+ * @param {string} url
+ * @param {string|string[]} protocols
+ */
+ constructor (url, protocols = []) {
+ super()
- // Here's where we resolve a callback if a callback is present for the dispatch data.
- if (mockDispatch.data.callback) {
- mockDispatch.data = { ...mockDispatch.data, ...mockDispatch.data.callback(opts) }
- }
+ webidl.util.markAsUncloneable(this)
- // Parse mockDispatch data
- const { data: { statusCode, data, headers, trailers, error }, delay, persist } = mockDispatch
- const { timesInvoked, times } = mockDispatch
+ const prefix = 'WebSocket constructor'
+ webidl.argumentLengthCheck(arguments, 1, prefix)
- // If it's used up and not persistent, mark as consumed
- mockDispatch.consumed = !persist && timesInvoked >= times
- mockDispatch.pending = timesInvoked < times
+ const options = webidl.converters['DOMString or sequence or WebSocketInit'](protocols, prefix, 'options')
- // If specified, trigger dispatch error
- if (error !== null) {
- deleteMockDispatch(this[kDispatches], key)
- handler.onError(error)
- return true
- }
+ url = webidl.converters.USVString(url, prefix, 'url')
+ protocols = options.protocols
- // Handle the request with a delay if necessary
- if (typeof delay === 'number' && delay > 0) {
- setTimeout(() => {
- handleReply(this[kDispatches])
- }, delay)
- } else {
- handleReply(this[kDispatches])
- }
+ // 1. Let baseURL be this's relevant settings object's API base URL.
+ const baseURL = environmentSettingsObject.settingsObject.baseUrl
- function handleReply (mockDispatches, _data = data) {
- // fetch's HeadersList is a 1D string array
- const optsHeaders = Array.isArray(opts.headers)
- ? buildHeadersFromArray(opts.headers)
- : opts.headers
- const body = typeof _data === 'function'
- ? _data({ ...opts, headers: optsHeaders })
- : _data
+ // 1. Let urlRecord be the result of applying the URL parser to url with baseURL.
+ let urlRecord
- // util.types.isPromise is likely needed for jest.
- if (isPromise(body)) {
- // If handleReply is asynchronous, throwing an error
- // in the callback will reject the promise, rather than
- // synchronously throw the error, which breaks some tests.
- // Rather, we wait for the callback to resolve if it is a
- // promise, and then re-run handleReply with the new body.
- body.then((newData) => handleReply(mockDispatches, newData))
- return
+ try {
+ urlRecord = new URL(url, baseURL)
+ } catch (e) {
+ // 3. If urlRecord is failure, then throw a "SyntaxError" DOMException.
+ throw new DOMException(e, 'SyntaxError')
}
- const responseData = getResponseData(body)
- const responseHeaders = generateKeyValues(headers)
- const responseTrailers = generateKeyValues(trailers)
-
- handler.onConnect?.(err => handler.onError(err), null)
- handler.onHeaders?.(statusCode, responseHeaders, resume, getStatusText(statusCode))
- handler.onData?.(Buffer.from(responseData))
- handler.onComplete?.(responseTrailers)
- deleteMockDispatch(mockDispatches, key)
- }
-
- function resume () {}
-
- return true
-}
-
-function buildMockDispatch () {
- const agent = this[kMockAgent]
- const origin = this[kOrigin]
- const originalDispatch = this[kOriginalDispatch]
-
- return function dispatch (opts, handler) {
- if (agent.isMockActive) {
- try {
- mockDispatch.call(this, opts, handler)
- } catch (error) {
- if (error instanceof MockNotMatchedError) {
- const netConnect = agent[kGetNetConnect]()
- if (netConnect === false) {
- throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)`)
- }
- if (checkNetConnect(netConnect, origin)) {
- originalDispatch.call(this, opts, handler)
- } else {
- throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)`)
- }
- } else {
- throw error
- }
- }
- } else {
- originalDispatch.call(this, opts, handler)
+ // 4. If urlRecord’s scheme is "http", then set urlRecord’s scheme to "ws".
+ if (urlRecord.protocol === 'http:') {
+ urlRecord.protocol = 'ws:'
+ } else if (urlRecord.protocol === 'https:') {
+ // 5. Otherwise, if urlRecord’s scheme is "https", set urlRecord’s scheme to "wss".
+ urlRecord.protocol = 'wss:'
}
- }
-}
-function checkNetConnect (netConnect, origin) {
- const url = new URL(origin)
- if (netConnect === true) {
- return true
- } else if (Array.isArray(netConnect) && netConnect.some((matcher) => matchValue(matcher, url.host))) {
- return true
- }
- return false
-}
+ // 6. If urlRecord’s scheme is not "ws" or "wss", then throw a "SyntaxError" DOMException.
+ if (urlRecord.protocol !== 'ws:' && urlRecord.protocol !== 'wss:') {
+ throw new DOMException(
+ `Expected a ws: or wss: protocol, got ${urlRecord.protocol}`,
+ 'SyntaxError'
+ )
+ }
-function buildMockOptions (opts) {
- if (opts) {
- const { agent, ...mockOptions } = opts
- return mockOptions
- }
-}
+ // 7. If urlRecord’s fragment is non-null, then throw a "SyntaxError"
+ // DOMException.
+ if (urlRecord.hash || urlRecord.href.endsWith('#')) {
+ throw new DOMException('Got fragment', 'SyntaxError')
+ }
-module.exports = {
- getResponseData,
- getMockDispatch,
- addMockDispatch,
- deleteMockDispatch,
- buildKey,
- generateKeyValues,
- matchValue,
- getResponse,
- getStatusText,
- mockDispatch,
- buildMockDispatch,
- checkNetConnect,
- buildMockOptions,
- getHeaderByName,
- buildHeadersFromArray
-}
+ // 8. If protocols is a string, set protocols to a sequence consisting
+ // of just that string.
+ if (typeof protocols === 'string') {
+ protocols = [protocols]
+ }
+ // 9. If any of the values in protocols occur more than once or otherwise
+ // fail to match the requirements for elements that comprise the value
+ // of `Sec-WebSocket-Protocol` fields as defined by The WebSocket
+ // protocol, then throw a "SyntaxError" DOMException.
+ if (protocols.length !== new Set(protocols.map(p => p.toLowerCase())).size) {
+ throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError')
+ }
-/***/ }),
+ if (protocols.length > 0 && !protocols.every(p => isValidSubprotocol(p))) {
+ throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError')
+ }
-/***/ 1030:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 10. Set this's url to urlRecord.
+ this[kWebSocketURL] = new URL(urlRecord.href)
+ // 11. Let client be this's relevant settings object.
+ const client = environmentSettingsObject.settingsObject
+ // 12. Run this step in parallel:
-const { Transform } = __nccwpck_require__(7075)
-const { Console } = __nccwpck_require__(7540)
+ // 1. Establish a WebSocket connection given urlRecord, protocols,
+ // and client.
+ this[kController] = establishWebSocketConnection(
+ urlRecord,
+ protocols,
+ client,
+ this,
+ (response, extensions) => this.#onConnectionEstablished(response, extensions),
+ options
+ )
-const PERSISTENT = process.versions.icu ? '✅' : 'Y '
-const NOT_PERSISTENT = process.versions.icu ? '❌' : 'N '
+ // Each WebSocket object has an associated ready state, which is a
+ // number representing the state of the connection. Initially it must
+ // be CONNECTING (0).
+ this[kReadyState] = WebSocket.CONNECTING
-/**
- * Gets the output of `console.table(…)` as a string.
- */
-module.exports = class PendingInterceptorsFormatter {
- constructor ({ disableColors } = {}) {
- this.transform = new Transform({
- transform (chunk, _enc, cb) {
- cb(null, chunk)
- }
- })
+ this[kSentClose] = sentCloseFrameState.NOT_SENT
- this.logger = new Console({
- stdout: this.transform,
- inspectOptions: {
- colors: !disableColors && !process.env.CI
- }
- })
- }
+ // The extensions attribute must initially return the empty string.
- format (pendingInterceptors) {
- const withPrettyHeaders = pendingInterceptors.map(
- ({ method, path, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
- Method: method,
- Origin: origin,
- Path: path,
- 'Status code': statusCode,
- Persistent: persist ? PERSISTENT : NOT_PERSISTENT,
- Invocations: timesInvoked,
- Remaining: persist ? Infinity : times - timesInvoked
- }))
+ // The protocol attribute must initially return the empty string.
- this.logger.table(withPrettyHeaders)
- return this.transform.read().toString()
+ // Each WebSocket object has an associated binary type, which is a
+ // BinaryType. Initially it must be "blob".
+ this[kBinaryType] = 'blob'
}
-}
+ /**
+ * @see https://websockets.spec.whatwg.org/#dom-websocket-close
+ * @param {number|undefined} code
+ * @param {string|undefined} reason
+ */
+ close (code = undefined, reason = undefined) {
+ webidl.brandCheck(this, WebSocket)
-/***/ }),
+ const prefix = 'WebSocket.close'
-/***/ 8353:
-/***/ ((module) => {
+ if (code !== undefined) {
+ code = webidl.converters['unsigned short'](code, prefix, 'code', { clamp: true })
+ }
+ if (reason !== undefined) {
+ reason = webidl.converters.USVString(reason, prefix, 'reason')
+ }
+ // 1. If code is present, but is neither an integer equal to 1000 nor an
+ // integer in the range 3000 to 4999, inclusive, throw an
+ // "InvalidAccessError" DOMException.
+ if (code !== undefined) {
+ if (code !== 1000 && (code < 3000 || code > 4999)) {
+ throw new DOMException('invalid code', 'InvalidAccessError')
+ }
+ }
-const singulars = {
- pronoun: 'it',
- is: 'is',
- was: 'was',
- this: 'this'
-}
+ let reasonByteLength = 0
-const plurals = {
- pronoun: 'they',
- is: 'are',
- was: 'were',
- this: 'these'
-}
+ // 2. If reason is present, then run these substeps:
+ if (reason !== undefined) {
+ // 1. Let reasonBytes be the result of encoding reason.
+ // 2. If reasonBytes is longer than 123 bytes, then throw a
+ // "SyntaxError" DOMException.
+ reasonByteLength = Buffer.byteLength(reason)
-module.exports = class Pluralizer {
- constructor (singular, plural) {
- this.singular = singular
- this.plural = plural
- }
+ if (reasonByteLength > 123) {
+ throw new DOMException(
+ `Reason must be less than 123 bytes; received ${reasonByteLength}`,
+ 'SyntaxError'
+ )
+ }
+ }
- pluralize (count) {
- const one = count === 1
- const keys = one ? singulars : plurals
- const noun = one ? this.singular : this.plural
- return { ...keys, count, noun }
+ // 3. Run the first matching steps from the following list:
+ closeWebSocketConnection(this, code, reason, reasonByteLength)
}
-}
+ /**
+ * @see https://websockets.spec.whatwg.org/#dom-websocket-send
+ * @param {NodeJS.TypedArray|ArrayBuffer|Blob|string} data
+ */
+ send (data) {
+ webidl.brandCheck(this, WebSocket)
-/***/ }),
+ const prefix = 'WebSocket.send'
+ webidl.argumentLengthCheck(arguments, 1, prefix)
-/***/ 2563:
-/***/ ((module) => {
+ data = webidl.converters.WebSocketSendData(data, prefix, 'data')
+ // 1. If this's ready state is CONNECTING, then throw an
+ // "InvalidStateError" DOMException.
+ if (isConnecting(this)) {
+ throw new DOMException('Sent before connected.', 'InvalidStateError')
+ }
+ // 2. Run the appropriate set of steps from the following list:
+ // https://datatracker.ietf.org/doc/html/rfc6455#section-6.1
+ // https://datatracker.ietf.org/doc/html/rfc6455#section-5.2
-/**
- * This module offers an optimized timer implementation designed for scenarios
- * where high precision is not critical.
- *
- * The timer achieves faster performance by using a low-resolution approach,
- * with an accuracy target of within 500ms. This makes it particularly useful
- * for timers with delays of 1 second or more, where exact timing is less
- * crucial.
- *
- * It's important to note that Node.js timers are inherently imprecise, as
- * delays can occur due to the event loop being blocked by other operations.
- * Consequently, timers may trigger later than their scheduled time.
- */
+ if (!isEstablished(this) || isClosing(this)) {
+ return
+ }
-/**
- * The fastNow variable contains the internal fast timer clock value.
- *
- * @type {number}
- */
-let fastNow = 0
+ // If data is a string
+ if (typeof data === 'string') {
+ // If the WebSocket connection is established and the WebSocket
+ // closing handshake has not yet started, then the user agent
+ // must send a WebSocket Message comprised of the data argument
+ // using a text frame opcode; if the data cannot be sent, e.g.
+ // because it would need to be buffered but the buffer is full,
+ // the user agent must flag the WebSocket as full and then close
+ // the WebSocket connection. Any invocation of this method with a
+ // string argument that does not throw an exception must increase
+ // the bufferedAmount attribute by the number of bytes needed to
+ // express the argument as UTF-8.
-/**
- * RESOLUTION_MS represents the target resolution time in milliseconds.
- *
- * @type {number}
- * @default 1000
- */
-const RESOLUTION_MS = 1e3
+ const length = Buffer.byteLength(data)
-/**
- * TICK_MS defines the desired interval in milliseconds between each tick.
- * The target value is set to half the resolution time, minus 1 ms, to account
- * for potential event loop overhead.
- *
- * @type {number}
- * @default 499
- */
-const TICK_MS = (RESOLUTION_MS >> 1) - 1
+ this.#bufferedAmount += length
+ this.#sendQueue.add(data, () => {
+ this.#bufferedAmount -= length
+ }, sendHints.string)
+ } else if (types.isArrayBuffer(data)) {
+ // If the WebSocket connection is established, and the WebSocket
+ // closing handshake has not yet started, then the user agent must
+ // send a WebSocket Message comprised of data using a binary frame
+ // opcode; if the data cannot be sent, e.g. because it would need
+ // to be buffered but the buffer is full, the user agent must flag
+ // the WebSocket as full and then close the WebSocket connection.
+ // The data to be sent is the data stored in the buffer described
+ // by the ArrayBuffer object. Any invocation of this method with an
+ // ArrayBuffer argument that does not throw an exception must
+ // increase the bufferedAmount attribute by the length of the
+ // ArrayBuffer in bytes.
-/**
- * fastNowTimeout is a Node.js timer used to manage and process
- * the FastTimers stored in the `fastTimers` array.
- *
- * @type {NodeJS.Timeout}
- */
-let fastNowTimeout
+ this.#bufferedAmount += data.byteLength
+ this.#sendQueue.add(data, () => {
+ this.#bufferedAmount -= data.byteLength
+ }, sendHints.arrayBuffer)
+ } else if (ArrayBuffer.isView(data)) {
+ // If the WebSocket connection is established, and the WebSocket
+ // closing handshake has not yet started, then the user agent must
+ // send a WebSocket Message comprised of data using a binary frame
+ // opcode; if the data cannot be sent, e.g. because it would need to
+ // be buffered but the buffer is full, the user agent must flag the
+ // WebSocket as full and then close the WebSocket connection. The
+ // data to be sent is the data stored in the section of the buffer
+ // described by the ArrayBuffer object that data references. Any
+ // invocation of this method with this kind of argument that does
+ // not throw an exception must increase the bufferedAmount attribute
+ // by the length of data’s buffer in bytes.
-/**
- * The kFastTimer symbol is used to identify FastTimer instances.
- *
- * @type {Symbol}
- */
-const kFastTimer = Symbol('kFastTimer')
+ this.#bufferedAmount += data.byteLength
+ this.#sendQueue.add(data, () => {
+ this.#bufferedAmount -= data.byteLength
+ }, sendHints.typedArray)
+ } else if (isBlobLike(data)) {
+ // If the WebSocket connection is established, and the WebSocket
+ // closing handshake has not yet started, then the user agent must
+ // send a WebSocket Message comprised of data using a binary frame
+ // opcode; if the data cannot be sent, e.g. because it would need to
+ // be buffered but the buffer is full, the user agent must flag the
+ // WebSocket as full and then close the WebSocket connection. The data
+ // to be sent is the raw data represented by the Blob object. Any
+ // invocation of this method with a Blob argument that does not throw
+ // an exception must increase the bufferedAmount attribute by the size
+ // of the Blob object’s raw data, in bytes.
-/**
- * The fastTimers array contains all active FastTimers.
- *
- * @type {FastTimer[]}
- */
-const fastTimers = []
+ this.#bufferedAmount += data.size
+ this.#sendQueue.add(data, () => {
+ this.#bufferedAmount -= data.size
+ }, sendHints.blob)
+ }
+ }
-/**
- * These constants represent the various states of a FastTimer.
- */
+ get readyState () {
+ webidl.brandCheck(this, WebSocket)
-/**
- * The `NOT_IN_LIST` constant indicates that the FastTimer is not included
- * in the `fastTimers` array. Timers with this status will not be processed
- * during the next tick by the `onTick` function.
- *
- * A FastTimer can be re-added to the `fastTimers` array by invoking the
- * `refresh` method on the FastTimer instance.
- *
- * @type {-2}
- */
-const NOT_IN_LIST = -2
+ // The readyState getter steps are to return this's ready state.
+ return this[kReadyState]
+ }
-/**
- * The `TO_BE_CLEARED` constant indicates that the FastTimer is scheduled
- * for removal from the `fastTimers` array. A FastTimer in this state will
- * be removed in the next tick by the `onTick` function and will no longer
- * be processed.
- *
- * This status is also set when the `clear` method is called on the FastTimer instance.
- *
- * @type {-1}
- */
-const TO_BE_CLEARED = -1
+ get bufferedAmount () {
+ webidl.brandCheck(this, WebSocket)
-/**
- * The `PENDING` constant signifies that the FastTimer is awaiting processing
- * in the next tick by the `onTick` function. Timers with this status will have
- * their `_idleStart` value set and their status updated to `ACTIVE` in the next tick.
- *
- * @type {0}
- */
-const PENDING = 0
+ return this.#bufferedAmount
+ }
-/**
- * The `ACTIVE` constant indicates that the FastTimer is active and waiting
- * for its timer to expire. During the next tick, the `onTick` function will
- * check if the timer has expired, and if so, it will execute the associated callback.
- *
- * @type {1}
- */
-const ACTIVE = 1
+ get url () {
+ webidl.brandCheck(this, WebSocket)
-/**
- * The onTick function processes the fastTimers array.
- *
- * @returns {void}
- */
-function onTick () {
- /**
- * Increment the fastNow value by the TICK_MS value, despite the actual time
- * that has passed since the last tick. This approach ensures independence
- * from the system clock and delays caused by a blocked event loop.
- *
- * @type {number}
- */
- fastNow += TICK_MS
+ // The url getter steps are to return this's url, serialized.
+ return URLSerializer(this[kWebSocketURL])
+ }
- /**
- * The `idx` variable is used to iterate over the `fastTimers` array.
- * Expired timers are removed by replacing them with the last element in the array.
- * Consequently, `idx` is only incremented when the current element is not removed.
- *
- * @type {number}
- */
- let idx = 0
+ get extensions () {
+ webidl.brandCheck(this, WebSocket)
- /**
- * The len variable will contain the length of the fastTimers array
- * and will be decremented when a FastTimer should be removed from the
- * fastTimers array.
- *
- * @type {number}
- */
- let len = fastTimers.length
+ return this.#extensions
+ }
- while (idx < len) {
- /**
- * @type {FastTimer}
- */
- const timer = fastTimers[idx]
+ get protocol () {
+ webidl.brandCheck(this, WebSocket)
- // If the timer is in the ACTIVE state and the timer has expired, it will
- // be processed in the next tick.
- if (timer._state === PENDING) {
- // Set the _idleStart value to the fastNow value minus the TICK_MS value
- // to account for the time the timer was in the PENDING state.
- timer._idleStart = fastNow - TICK_MS
- timer._state = ACTIVE
- } else if (
- timer._state === ACTIVE &&
- fastNow >= timer._idleStart + timer._idleTimeout
- ) {
- timer._state = TO_BE_CLEARED
- timer._idleStart = -1
- timer._onTimeout(timer._timerArg)
- }
+ return this.#protocol
+ }
- if (timer._state === TO_BE_CLEARED) {
- timer._state = NOT_IN_LIST
+ get onopen () {
+ webidl.brandCheck(this, WebSocket)
- // Move the last element to the current index and decrement len if it is
- // not the only element in the array.
- if (--len !== 0) {
- fastTimers[idx] = fastTimers[len]
- }
+ return this.#events.open
+ }
+
+ set onopen (fn) {
+ webidl.brandCheck(this, WebSocket)
+
+ if (this.#events.open) {
+ this.removeEventListener('open', this.#events.open)
+ }
+
+ if (typeof fn === 'function') {
+ this.#events.open = fn
+ this.addEventListener('open', fn)
} else {
- ++idx
+ this.#events.open = null
}
}
- // Set the length of the fastTimers array to the new length and thus
- // removing the excess FastTimers elements from the array.
- fastTimers.length = len
+ get onerror () {
+ webidl.brandCheck(this, WebSocket)
- // If there are still active FastTimers in the array, refresh the Timer.
- // If there are no active FastTimers, the timer will be refreshed again
- // when a new FastTimer is instantiated.
- if (fastTimers.length !== 0) {
- refreshTimeout()
+ return this.#events.error
}
-}
-function refreshTimeout () {
- // If the fastNowTimeout is already set, refresh it.
- if (fastNowTimeout) {
- fastNowTimeout.refresh()
- // fastNowTimeout is not instantiated yet, create a new Timer.
- } else {
- clearTimeout(fastNowTimeout)
- fastNowTimeout = setTimeout(onTick, TICK_MS)
+ set onerror (fn) {
+ webidl.brandCheck(this, WebSocket)
- // If the Timer has an unref method, call it to allow the process to exit if
- // there are no other active handles.
- if (fastNowTimeout.unref) {
- fastNowTimeout.unref()
+ if (this.#events.error) {
+ this.removeEventListener('error', this.#events.error)
}
- }
-}
-/**
- * The `FastTimer` class is a data structure designed to store and manage
- * timer information.
- */
-class FastTimer {
- [kFastTimer] = true
+ if (typeof fn === 'function') {
+ this.#events.error = fn
+ this.addEventListener('error', fn)
+ } else {
+ this.#events.error = null
+ }
+ }
- /**
- * The state of the timer, which can be one of the following:
- * - NOT_IN_LIST (-2)
- * - TO_BE_CLEARED (-1)
- * - PENDING (0)
- * - ACTIVE (1)
- *
- * @type {-2|-1|0|1}
- * @private
- */
- _state = NOT_IN_LIST
+ get onclose () {
+ webidl.brandCheck(this, WebSocket)
- /**
- * The number of milliseconds to wait before calling the callback.
- *
- * @type {number}
- * @private
- */
- _idleTimeout = -1
+ return this.#events.close
+ }
- /**
- * The time in milliseconds when the timer was started. This value is used to
- * calculate when the timer should expire.
- *
- * @type {number}
- * @default -1
- * @private
- */
- _idleStart = -1
+ set onclose (fn) {
+ webidl.brandCheck(this, WebSocket)
- /**
- * The function to be executed when the timer expires.
- * @type {Function}
- * @private
- */
- _onTimeout
+ if (this.#events.close) {
+ this.removeEventListener('close', this.#events.close)
+ }
- /**
- * The argument to be passed to the callback when the timer expires.
- *
- * @type {*}
- * @private
- */
- _timerArg
+ if (typeof fn === 'function') {
+ this.#events.close = fn
+ this.addEventListener('close', fn)
+ } else {
+ this.#events.close = null
+ }
+ }
- /**
- * @constructor
- * @param {Function} callback A function to be executed after the timer
- * expires.
- * @param {number} delay The time, in milliseconds that the timer should wait
- * before the specified function or code is executed.
- * @param {*} arg
- */
- constructor (callback, delay, arg) {
- this._onTimeout = callback
- this._idleTimeout = delay
- this._timerArg = arg
+ get onmessage () {
+ webidl.brandCheck(this, WebSocket)
- this.refresh()
+ return this.#events.message
}
- /**
- * Sets the timer's start time to the current time, and reschedules the timer
- * to call its callback at the previously specified duration adjusted to the
- * current time.
- * Using this on a timer that has already called its callback will reactivate
- * the timer.
- *
- * @returns {void}
- */
- refresh () {
- // In the special case that the timer is not in the list of active timers,
- // add it back to the array to be processed in the next tick by the onTick
- // function.
- if (this._state === NOT_IN_LIST) {
- fastTimers.push(this)
- }
+ set onmessage (fn) {
+ webidl.brandCheck(this, WebSocket)
- // If the timer is the only active timer, refresh the fastNowTimeout for
- // better resolution.
- if (!fastNowTimeout || fastTimers.length === 1) {
- refreshTimeout()
+ if (this.#events.message) {
+ this.removeEventListener('message', this.#events.message)
}
- // Setting the state to PENDING will cause the timer to be reset in the
- // next tick by the onTick function.
- this._state = PENDING
+ if (typeof fn === 'function') {
+ this.#events.message = fn
+ this.addEventListener('message', fn)
+ } else {
+ this.#events.message = null
+ }
}
- /**
- * The `clear` method cancels the timer, preventing it from executing.
- *
- * @returns {void}
- * @private
- */
- clear () {
- // Set the state to TO_BE_CLEARED to mark the timer for removal in the next
- // tick by the onTick function.
- this._state = TO_BE_CLEARED
+ get binaryType () {
+ webidl.brandCheck(this, WebSocket)
- // Reset the _idleStart value to -1 to indicate that the timer is no longer
- // active.
- this._idleStart = -1
+ return this[kBinaryType]
}
-}
-/**
- * This module exports a setTimeout and clearTimeout function that can be
- * used as a drop-in replacement for the native functions.
- */
-module.exports = {
- /**
- * The setTimeout() method sets a timer which executes a function once the
- * timer expires.
- * @param {Function} callback A function to be executed after the timer
- * expires.
- * @param {number} delay The time, in milliseconds that the timer should
- * wait before the specified function or code is executed.
- * @param {*} [arg] An optional argument to be passed to the callback function
- * when the timer expires.
- * @returns {NodeJS.Timeout|FastTimer}
- */
- setTimeout (callback, delay, arg) {
- // If the delay is less than or equal to the RESOLUTION_MS value return a
- // native Node.js Timer instance.
- return delay <= RESOLUTION_MS
- ? setTimeout(callback, delay, arg)
- : new FastTimer(callback, delay, arg)
- },
- /**
- * The clearTimeout method cancels an instantiated Timer previously created
- * by calling setTimeout.
- *
- * @param {NodeJS.Timeout|FastTimer} timeout
- */
- clearTimeout (timeout) {
- // If the timeout is a FastTimer, call its own clear method.
- if (timeout[kFastTimer]) {
- /**
- * @type {FastTimer}
- */
- timeout.clear()
- // Otherwise it is an instance of a native NodeJS.Timeout, so call the
- // Node.js native clearTimeout function.
+ set binaryType (type) {
+ webidl.brandCheck(this, WebSocket)
+
+ if (type !== 'blob' && type !== 'arraybuffer') {
+ this[kBinaryType] = 'blob'
} else {
- clearTimeout(timeout)
+ this[kBinaryType] = type
}
- },
- /**
- * The setFastTimeout() method sets a fastTimer which executes a function once
- * the timer expires.
- * @param {Function} callback A function to be executed after the timer
- * expires.
- * @param {number} delay The time, in milliseconds that the timer should
- * wait before the specified function or code is executed.
- * @param {*} [arg] An optional argument to be passed to the callback function
- * when the timer expires.
- * @returns {FastTimer}
- */
- setFastTimeout (callback, delay, arg) {
- return new FastTimer(callback, delay, arg)
- },
- /**
- * The clearTimeout method cancels an instantiated FastTimer previously
- * created by calling setFastTimeout.
- *
- * @param {FastTimer} timeout
- */
- clearFastTimeout (timeout) {
- timeout.clear()
- },
- /**
- * The now method returns the value of the internal fast timer clock.
- *
- * @returns {number}
- */
- now () {
- return fastNow
- },
- /**
- * Trigger the onTick function to process the fastTimers array.
- * Exported for testing purposes only.
- * Marking as deprecated to discourage any use outside of testing.
- * @deprecated
- * @param {number} [delay=0] The delay in milliseconds to add to the now value.
- */
- tick (delay = 0) {
- fastNow += delay - RESOLUTION_MS + 1
- onTick()
- onTick()
- },
- /**
- * Reset FastTimers.
- * Exported for testing purposes only.
- * Marking as deprecated to discourage any use outside of testing.
- * @deprecated
- */
- reset () {
- fastNow = 0
- fastTimers.length = 0
- clearTimeout(fastNowTimeout)
- fastNowTimeout = null
- },
+ }
+
/**
- * Exporting for testing purposes only.
- * Marking as deprecated to discourage any use outside of testing.
- * @deprecated
+ * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
*/
- kFastTimer
-}
+ #onConnectionEstablished (response, parsedExtensions) {
+ // processResponse is called when the "response's header list has been received and initialized."
+ // once this happens, the connection is open
+ this[kResponse] = response
+ const parser = new ByteParser(this, parsedExtensions)
+ parser.on('drain', onParserDrain)
+ parser.on('error', onParserError.bind(this))
-/***/ }),
+ response.socket.ws = this
+ this[kByteParser] = parser
-/***/ 4330:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ this.#sendQueue = new SendQueue(response.socket)
+ // 1. Change the ready state to OPEN (1).
+ this[kReadyState] = states.OPEN
+ // 2. Change the extensions attribute’s value to the extensions in use, if
+ // it is not the null value.
+ // https://datatracker.ietf.org/doc/html/rfc6455#section-9.1
+ const extensions = response.headersList.get('sec-websocket-extensions')
-const { kConstruct } = __nccwpck_require__(7589)
-const { urlEquals, getFieldValues } = __nccwpck_require__(102)
-const { kEnumerableProperty, isDisturbed } = __nccwpck_require__(1544)
-const { webidl } = __nccwpck_require__(253)
-const { Response, cloneResponse, fromInnerResponse } = __nccwpck_require__(9107)
-const { Request, fromInnerRequest } = __nccwpck_require__(6055)
-const { kState } = __nccwpck_require__(4883)
-const { fetching } = __nccwpck_require__(7302)
-const { urlIsHttpHttpsScheme, createDeferredPromise, readAllBytes } = __nccwpck_require__(4296)
-const assert = __nccwpck_require__(4589)
+ if (extensions !== null) {
+ this.#extensions = extensions
+ }
-/**
- * @see https://w3c.github.io/ServiceWorker/#dfn-cache-batch-operation
- * @typedef {Object} CacheBatchOperation
- * @property {'delete' | 'put'} type
- * @property {any} request
- * @property {any} response
- * @property {import('../../types/cache').CacheQueryOptions} options
- */
+ // 3. Change the protocol attribute’s value to the subprotocol in use, if
+ // it is not the null value.
+ // https://datatracker.ietf.org/doc/html/rfc6455#section-1.9
+ const protocol = response.headersList.get('sec-websocket-protocol')
-/**
- * @see https://w3c.github.io/ServiceWorker/#dfn-request-response-list
- * @typedef {[any, any][]} requestResponseList
- */
+ if (protocol !== null) {
+ this.#protocol = protocol
+ }
-class Cache {
- /**
- * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list
- * @type {requestResponseList}
- */
- #relevantRequestResponseList
+ // 4. Fire an event named open at the WebSocket object.
+ fireEvent('open', this)
+ }
+}
- constructor () {
- if (arguments[0] !== kConstruct) {
- webidl.illegalConstructor()
- }
+// https://websockets.spec.whatwg.org/#dom-websocket-connecting
+WebSocket.CONNECTING = WebSocket.prototype.CONNECTING = states.CONNECTING
+// https://websockets.spec.whatwg.org/#dom-websocket-open
+WebSocket.OPEN = WebSocket.prototype.OPEN = states.OPEN
+// https://websockets.spec.whatwg.org/#dom-websocket-closing
+WebSocket.CLOSING = WebSocket.prototype.CLOSING = states.CLOSING
+// https://websockets.spec.whatwg.org/#dom-websocket-closed
+WebSocket.CLOSED = WebSocket.prototype.CLOSED = states.CLOSED
- webidl.util.markAsUncloneable(this)
- this.#relevantRequestResponseList = arguments[1]
+Object.defineProperties(WebSocket.prototype, {
+ CONNECTING: staticPropertyDescriptors,
+ OPEN: staticPropertyDescriptors,
+ CLOSING: staticPropertyDescriptors,
+ CLOSED: staticPropertyDescriptors,
+ url: kEnumerableProperty,
+ readyState: kEnumerableProperty,
+ bufferedAmount: kEnumerableProperty,
+ onopen: kEnumerableProperty,
+ onerror: kEnumerableProperty,
+ onclose: kEnumerableProperty,
+ close: kEnumerableProperty,
+ onmessage: kEnumerableProperty,
+ binaryType: kEnumerableProperty,
+ send: kEnumerableProperty,
+ extensions: kEnumerableProperty,
+ protocol: kEnumerableProperty,
+ [Symbol.toStringTag]: {
+ value: 'WebSocket',
+ writable: false,
+ enumerable: false,
+ configurable: true
}
+})
- async match (request, options = {}) {
- webidl.brandCheck(this, Cache)
+Object.defineProperties(WebSocket, {
+ CONNECTING: staticPropertyDescriptors,
+ OPEN: staticPropertyDescriptors,
+ CLOSING: staticPropertyDescriptors,
+ CLOSED: staticPropertyDescriptors
+})
- const prefix = 'Cache.match'
- webidl.argumentLengthCheck(arguments, 1, prefix)
+webidl.converters['sequence'] = webidl.sequenceConverter(
+ webidl.converters.DOMString
+)
- request = webidl.converters.RequestInfo(request, prefix, 'request')
- options = webidl.converters.CacheQueryOptions(options, prefix, 'options')
+webidl.converters['DOMString or sequence'] = function (V, prefix, argument) {
+ if (webidl.util.Type(V) === 'Object' && Symbol.iterator in V) {
+ return webidl.converters['sequence'](V)
+ }
- const p = this.#internalMatchAll(request, options, 1)
+ return webidl.converters.DOMString(V, prefix, argument)
+}
- if (p.length === 0) {
- return
- }
+// This implements the proposal made in https://github.com/whatwg/websockets/issues/42
+webidl.converters.WebSocketInit = webidl.dictionaryConverter([
+ {
+ key: 'protocols',
+ converter: webidl.converters['DOMString or sequence'],
+ defaultValue: () => new Array(0)
+ },
+ {
+ key: 'dispatcher',
+ converter: webidl.converters.any,
+ defaultValue: () => getGlobalDispatcher()
+ },
+ {
+ key: 'headers',
+ converter: webidl.nullableConverter(webidl.converters.HeadersInit)
+ }
+])
- return p[0]
+webidl.converters['DOMString or sequence or WebSocketInit'] = function (V) {
+ if (webidl.util.Type(V) === 'Object' && !(Symbol.iterator in V)) {
+ return webidl.converters.WebSocketInit(V)
}
- async matchAll (request = undefined, options = {}) {
- webidl.brandCheck(this, Cache)
+ return { protocols: webidl.converters['DOMString or sequence'](V) }
+}
- const prefix = 'Cache.matchAll'
- if (request !== undefined) request = webidl.converters.RequestInfo(request, prefix, 'request')
- options = webidl.converters.CacheQueryOptions(options, prefix, 'options')
+webidl.converters.WebSocketSendData = function (V) {
+ if (webidl.util.Type(V) === 'Object') {
+ if (isBlobLike(V)) {
+ return webidl.converters.Blob(V, { strict: false })
+ }
- return this.#internalMatchAll(request, options)
+ if (ArrayBuffer.isView(V) || types.isArrayBuffer(V)) {
+ return webidl.converters.BufferSource(V)
+ }
}
- async add (request) {
- webidl.brandCheck(this, Cache)
+ return webidl.converters.USVString(V)
+}
- const prefix = 'Cache.add'
- webidl.argumentLengthCheck(arguments, 1, prefix)
+function onParserDrain () {
+ this.ws[kResponse].socket.resume()
+}
- request = webidl.converters.RequestInfo(request, prefix, 'request')
+function onParserError (err) {
+ let message
+ let code
- // 1.
- const requests = [request]
+ if (err instanceof CloseEvent) {
+ message = err.reason
+ code = err.code
+ } else {
+ message = err.message
+ }
- // 2.
- const responseArrayPromise = this.addAll(requests)
+ fireEvent('error', this, () => new ErrorEvent('error', { error: err, message }))
- // 3.
- return await responseArrayPromise
- }
+ closeWebSocketConnection(this, code)
+}
- async addAll (requests) {
- webidl.brandCheck(this, Cache)
+module.exports = {
+ WebSocket
+}
- const prefix = 'Cache.addAll'
- webidl.argumentLengthCheck(arguments, 1, prefix)
- // 1.
- const responsePromises = []
+/***/ }),
- // 2.
- const requestList = []
+/***/ 75:
+/***/ ((module) => {
- // 3.
- for (let request of requests) {
- if (request === undefined) {
- throw webidl.errors.conversionFailed({
- prefix,
- argument: 'Argument 1',
- types: ['undefined is not allowed']
- })
- }
+module.exports = eval("require")("supports-color");
- request = webidl.converters.RequestInfo(request)
- if (typeof request === 'string') {
- continue
- }
+/***/ }),
- // 3.1
- const r = request[kState]
+/***/ 2613:
+/***/ ((module) => {
- // 3.2
- if (!urlIsHttpHttpsScheme(r.url) || r.method !== 'GET') {
- throw webidl.errors.exception({
- header: prefix,
- message: 'Expected http/s scheme when method is not GET.'
- })
- }
- }
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("assert");
- // 4.
- /** @type {ReturnType[]} */
- const fetchControllers = []
+/***/ }),
- // 5.
- for (const request of requests) {
- // 5.1
- const r = new Request(request)[kState]
+/***/ 181:
+/***/ ((module) => {
- // 5.2
- if (!urlIsHttpHttpsScheme(r.url)) {
- throw webidl.errors.exception({
- header: prefix,
- message: 'Expected http/s scheme.'
- })
- }
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("buffer");
- // 5.4
- r.initiator = 'fetch'
- r.destination = 'subresource'
+/***/ }),
- // 5.5
- requestList.push(r)
+/***/ 4434:
+/***/ ((module) => {
- // 5.6
- const responsePromise = createDeferredPromise()
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("events");
- // 5.7
- fetchControllers.push(fetching({
- request: r,
- processResponse (response) {
- // 1.
- if (response.type === 'error' || response.status === 206 || response.status < 200 || response.status > 299) {
- responsePromise.reject(webidl.errors.exception({
- header: 'Cache.addAll',
- message: 'Received an invalid status code or the request failed.'
- }))
- } else if (response.headersList.contains('vary')) { // 2.
- // 2.1
- const fieldValues = getFieldValues(response.headersList.get('vary'))
+/***/ }),
- // 2.2
- for (const fieldValue of fieldValues) {
- // 2.2.1
- if (fieldValue === '*') {
- responsePromise.reject(webidl.errors.exception({
- header: 'Cache.addAll',
- message: 'invalid vary field value'
- }))
+/***/ 8611:
+/***/ ((module) => {
- for (const controller of fetchControllers) {
- controller.abort()
- }
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("http");
- return
- }
- }
- }
- },
- processResponseEndOfBody (response) {
- // 1.
- if (response.aborted) {
- responsePromise.reject(new DOMException('aborted', 'AbortError'))
- return
- }
+/***/ }),
- // 2.
- responsePromise.resolve(response)
- }
- }))
+/***/ 5692:
+/***/ ((module) => {
- // 5.8
- responsePromises.push(responsePromise.promise)
- }
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("https");
- // 6.
- const p = Promise.all(responsePromises)
+/***/ }),
- // 7.
- const responses = await p
+/***/ 9278:
+/***/ ((module) => {
- // 7.1
- const operations = []
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("net");
- // 7.2
- let index = 0
+/***/ }),
- // 7.3
- for (const response of responses) {
- // 7.3.1
- /** @type {CacheBatchOperation} */
- const operation = {
- type: 'put', // 7.3.2
- request: requestList[index], // 7.3.3
- response // 7.3.4
- }
+/***/ 4589:
+/***/ ((module) => {
- operations.push(operation) // 7.3.5
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:assert");
- index++ // 7.3.6
- }
+/***/ }),
- // 7.5
- const cacheJobPromise = createDeferredPromise()
+/***/ 6698:
+/***/ ((module) => {
- // 7.6.1
- let errorData = null
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:async_hooks");
- // 7.6.2
- try {
- this.#batchCacheOperations(operations)
- } catch (e) {
- errorData = e
- }
+/***/ }),
- // 7.6.3
- queueMicrotask(() => {
- // 7.6.3.1
- if (errorData === null) {
- cacheJobPromise.resolve(undefined)
- } else {
- // 7.6.3.2
- cacheJobPromise.reject(errorData)
- }
- })
+/***/ 4573:
+/***/ ((module) => {
- // 7.7
- return cacheJobPromise.promise
- }
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:buffer");
- async put (request, response) {
- webidl.brandCheck(this, Cache)
+/***/ }),
- const prefix = 'Cache.put'
- webidl.argumentLengthCheck(arguments, 2, prefix)
+/***/ 7540:
+/***/ ((module) => {
- request = webidl.converters.RequestInfo(request, prefix, 'request')
- response = webidl.converters.Response(response, prefix, 'response')
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:console");
- // 1.
- let innerRequest = null
+/***/ }),
- // 2.
- if (request instanceof Request) {
- innerRequest = request[kState]
- } else { // 3.
- innerRequest = new Request(request)[kState]
- }
+/***/ 7598:
+/***/ ((module) => {
- // 4.
- if (!urlIsHttpHttpsScheme(innerRequest.url) || innerRequest.method !== 'GET') {
- throw webidl.errors.exception({
- header: prefix,
- message: 'Expected an http/s scheme when method is not GET'
- })
- }
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:crypto");
- // 5.
- const innerResponse = response[kState]
+/***/ }),
- // 6.
- if (innerResponse.status === 206) {
- throw webidl.errors.exception({
- header: prefix,
- message: 'Got 206 status'
- })
- }
+/***/ 3053:
+/***/ ((module) => {
- // 7.
- if (innerResponse.headersList.contains('vary')) {
- // 7.1.
- const fieldValues = getFieldValues(innerResponse.headersList.get('vary'))
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:diagnostics_channel");
- // 7.2.
- for (const fieldValue of fieldValues) {
- // 7.2.1
- if (fieldValue === '*') {
- throw webidl.errors.exception({
- header: prefix,
- message: 'Got * vary field value'
- })
- }
- }
- }
+/***/ }),
- // 8.
- if (innerResponse.body && (isDisturbed(innerResponse.body.stream) || innerResponse.body.stream.locked)) {
- throw webidl.errors.exception({
- header: prefix,
- message: 'Response body is locked or disturbed'
- })
- }
+/***/ 610:
+/***/ ((module) => {
- // 9.
- const clonedResponse = cloneResponse(innerResponse)
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:dns");
- // 10.
- const bodyReadPromise = createDeferredPromise()
+/***/ }),
- // 11.
- if (innerResponse.body != null) {
- // 11.1
- const stream = innerResponse.body.stream
+/***/ 8474:
+/***/ ((module) => {
- // 11.2
- const reader = stream.getReader()
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:events");
- // 11.3
- readAllBytes(reader).then(bodyReadPromise.resolve, bodyReadPromise.reject)
- } else {
- bodyReadPromise.resolve(undefined)
- }
+/***/ }),
- // 12.
- /** @type {CacheBatchOperation[]} */
- const operations = []
+/***/ 7067:
+/***/ ((module) => {
- // 13.
- /** @type {CacheBatchOperation} */
- const operation = {
- type: 'put', // 14.
- request: innerRequest, // 15.
- response: clonedResponse // 16.
- }
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:http");
- // 17.
- operations.push(operation)
+/***/ }),
- // 19.
- const bytes = await bodyReadPromise.promise
+/***/ 2467:
+/***/ ((module) => {
- if (clonedResponse.body != null) {
- clonedResponse.body.source = bytes
- }
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:http2");
- // 19.1
- const cacheJobPromise = createDeferredPromise()
+/***/ }),
- // 19.2.1
- let errorData = null
+/***/ 7030:
+/***/ ((module) => {
- // 19.2.2
- try {
- this.#batchCacheOperations(operations)
- } catch (e) {
- errorData = e
- }
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:net");
- // 19.2.3
- queueMicrotask(() => {
- // 19.2.3.1
- if (errorData === null) {
- cacheJobPromise.resolve()
- } else { // 19.2.3.2
- cacheJobPromise.reject(errorData)
- }
- })
+/***/ }),
- return cacheJobPromise.promise
- }
+/***/ 8161:
+/***/ ((module) => {
- async delete (request, options = {}) {
- webidl.brandCheck(this, Cache)
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:os");
- const prefix = 'Cache.delete'
- webidl.argumentLengthCheck(arguments, 1, prefix)
+/***/ }),
- request = webidl.converters.RequestInfo(request, prefix, 'request')
- options = webidl.converters.CacheQueryOptions(options, prefix, 'options')
+/***/ 643:
+/***/ ((module) => {
- /**
- * @type {Request}
- */
- let r = null
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:perf_hooks");
- if (request instanceof Request) {
- r = request[kState]
+/***/ }),
- if (r.method !== 'GET' && !options.ignoreMethod) {
- return false
- }
- } else {
- assert(typeof request === 'string')
+/***/ 1708:
+/***/ ((module) => {
- r = new Request(request)[kState]
- }
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:process");
- /** @type {CacheBatchOperation[]} */
- const operations = []
+/***/ }),
- /** @type {CacheBatchOperation} */
- const operation = {
- type: 'delete',
- request: r,
- options
- }
+/***/ 1792:
+/***/ ((module) => {
- operations.push(operation)
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:querystring");
- const cacheJobPromise = createDeferredPromise()
+/***/ }),
- let errorData = null
- let requestResponses
+/***/ 7075:
+/***/ ((module) => {
- try {
- requestResponses = this.#batchCacheOperations(operations)
- } catch (e) {
- errorData = e
- }
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:stream");
- queueMicrotask(() => {
- if (errorData === null) {
- cacheJobPromise.resolve(!!requestResponses?.length)
- } else {
- cacheJobPromise.reject(errorData)
- }
- })
+/***/ }),
- return cacheJobPromise.promise
- }
+/***/ 1692:
+/***/ ((module) => {
- /**
- * @see https://w3c.github.io/ServiceWorker/#dom-cache-keys
- * @param {any} request
- * @param {import('../../types/cache').CacheQueryOptions} options
- * @returns {Promise}
- */
- async keys (request = undefined, options = {}) {
- webidl.brandCheck(this, Cache)
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:tls");
- const prefix = 'Cache.keys'
+/***/ }),
- if (request !== undefined) request = webidl.converters.RequestInfo(request, prefix, 'request')
- options = webidl.converters.CacheQueryOptions(options, prefix, 'options')
+/***/ 3136:
+/***/ ((module) => {
- // 1.
- let r = null
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:url");
- // 2.
- if (request !== undefined) {
- // 2.1
- if (request instanceof Request) {
- // 2.1.1
- r = request[kState]
+/***/ }),
- // 2.1.2
- if (r.method !== 'GET' && !options.ignoreMethod) {
- return []
- }
- } else if (typeof request === 'string') { // 2.2
- r = new Request(request)[kState]
- }
- }
+/***/ 7975:
+/***/ ((module) => {
- // 4.
- const promise = createDeferredPromise()
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:util");
- // 5.
- // 5.1
- const requests = []
+/***/ }),
- // 5.2
- if (request === undefined) {
- // 5.2.1
- for (const requestResponse of this.#relevantRequestResponseList) {
- // 5.2.1.1
- requests.push(requestResponse[0])
- }
- } else { // 5.3
- // 5.3.1
- const requestResponses = this.#queryCache(r, options)
+/***/ 3429:
+/***/ ((module) => {
- // 5.3.2
- for (const requestResponse of requestResponses) {
- // 5.3.2.1
- requests.push(requestResponse[0])
- }
- }
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:util/types");
- // 5.4
- queueMicrotask(() => {
- // 5.4.1
- const requestList = []
+/***/ }),
- // 5.4.2
- for (const request of requests) {
- const requestObject = fromInnerRequest(
- request,
- new AbortController().signal,
- 'immutable'
- )
- // 5.4.2.1
- requestList.push(requestObject)
- }
+/***/ 5919:
+/***/ ((module) => {
- // 5.4.3
- promise.resolve(Object.freeze(requestList))
- })
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:worker_threads");
- return promise.promise
- }
+/***/ }),
- /**
- * @see https://w3c.github.io/ServiceWorker/#batch-cache-operations-algorithm
- * @param {CacheBatchOperation[]} operations
- * @returns {requestResponseList}
- */
- #batchCacheOperations (operations) {
- // 1.
- const cache = this.#relevantRequestResponseList
+/***/ 8522:
+/***/ ((module) => {
- // 2.
- const backupCache = [...cache]
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:zlib");
- // 3.
- const addedItems = []
+/***/ }),
- // 4.1
- const resultList = []
+/***/ 6928:
+/***/ ((module) => {
- try {
- // 4.2
- for (const operation of operations) {
- // 4.2.1
- if (operation.type !== 'delete' && operation.type !== 'put') {
- throw webidl.errors.exception({
- header: 'Cache.#batchCacheOperations',
- message: 'operation type does not match "delete" or "put"'
- })
- }
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("path");
- // 4.2.2
- if (operation.type === 'delete' && operation.response != null) {
- throw webidl.errors.exception({
- header: 'Cache.#batchCacheOperations',
- message: 'delete operation should not have an associated response'
- })
- }
+/***/ }),
- // 4.2.3
- if (this.#queryCache(operation.request, operation.options, addedItems).length) {
- throw new DOMException('???', 'InvalidStateError')
- }
+/***/ 932:
+/***/ ((module) => {
- // 4.2.4
- let requestResponses
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("process");
- // 4.2.5
- if (operation.type === 'delete') {
- // 4.2.5.1
- requestResponses = this.#queryCache(operation.request, operation.options)
+/***/ }),
- // TODO: the spec is wrong, this is needed to pass WPTs
- if (requestResponses.length === 0) {
- return []
- }
+/***/ 3193:
+/***/ ((module) => {
- // 4.2.5.2
- for (const requestResponse of requestResponses) {
- const idx = cache.indexOf(requestResponse)
- assert(idx !== -1)
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("string_decoder");
- // 4.2.5.2.1
- cache.splice(idx, 1)
- }
- } else if (operation.type === 'put') { // 4.2.6
- // 4.2.6.1
- if (operation.response == null) {
- throw webidl.errors.exception({
- header: 'Cache.#batchCacheOperations',
- message: 'put operation should have an associated response'
- })
- }
+/***/ }),
- // 4.2.6.2
- const r = operation.request
+/***/ 4756:
+/***/ ((module) => {
- // 4.2.6.3
- if (!urlIsHttpHttpsScheme(r.url)) {
- throw webidl.errors.exception({
- header: 'Cache.#batchCacheOperations',
- message: 'expected http or https scheme'
- })
- }
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("tls");
- // 4.2.6.4
- if (r.method !== 'GET') {
- throw webidl.errors.exception({
- header: 'Cache.#batchCacheOperations',
- message: 'not get method'
- })
- }
+/***/ }),
- // 4.2.6.5
- if (operation.options != null) {
- throw webidl.errors.exception({
- header: 'Cache.#batchCacheOperations',
- message: 'options must not be defined'
- })
- }
+/***/ 2018:
+/***/ ((module) => {
- // 4.2.6.6
- requestResponses = this.#queryCache(operation.request)
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("tty");
- // 4.2.6.7
- for (const requestResponse of requestResponses) {
- const idx = cache.indexOf(requestResponse)
- assert(idx !== -1)
+/***/ }),
- // 4.2.6.7.1
- cache.splice(idx, 1)
- }
+/***/ 7016:
+/***/ ((module) => {
- // 4.2.6.8
- cache.push([operation.request, operation.response])
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("url");
- // 4.2.6.10
- addedItems.push([operation.request, operation.response])
- }
+/***/ }),
- // 4.2.7
- resultList.push([operation.request, operation.response])
- }
+/***/ 9023:
+/***/ ((module) => {
- // 4.3
- return resultList
- } catch (e) { // 5.
- // 5.1
- this.#relevantRequestResponseList.length = 0
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("util");
- // 5.2
- this.#relevantRequestResponseList = backupCache
+/***/ }),
- // 5.3
- throw e
- }
- }
+/***/ 3345:
+/***/ ((__unused_webpack_module, exports) => {
- /**
- * @see https://w3c.github.io/ServiceWorker/#query-cache
- * @param {any} requestQuery
- * @param {import('../../types/cache').CacheQueryOptions} options
- * @param {requestResponseList} targetStorage
- * @returns {requestResponseList}
- */
- #queryCache (requestQuery, options, targetStorage) {
- /** @type {requestResponseList} */
- const resultList = []
+var __webpack_unused_export__;
- const storage = targetStorage ?? this.#relevantRequestResponseList
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+__webpack_unused_export__ = ({ value: true });
+exports.w = void 0;
+/**
+ * Holds the singleton operationRequestMap, to be shared across CJS and ESM imports.
+ */
+exports.w = {
+ operationRequestMap: new WeakMap(),
+};
+//# sourceMappingURL=state-cjs.cjs.map
- for (const requestResponse of storage) {
- const [cachedRequest, cachedResponse] = requestResponse
- if (this.#requestMatchesCachedItem(requestQuery, cachedRequest, cachedResponse, options)) {
- resultList.push(requestResponse)
- }
- }
+/***/ }),
- return resultList
- }
+/***/ 8914:
+/***/ ((__unused_webpack_module, exports) => {
- /**
- * @see https://w3c.github.io/ServiceWorker/#request-matches-cached-item-algorithm
- * @param {any} requestQuery
- * @param {any} request
- * @param {any | null} response
- * @param {import('../../types/cache').CacheQueryOptions | undefined} options
- * @returns {boolean}
- */
- #requestMatchesCachedItem (requestQuery, request, response = null, options) {
- // if (options?.ignoreMethod === false && request.method === 'GET') {
- // return false
- // }
+var __webpack_unused_export__;
- const queryURL = new URL(requestQuery.url)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+__webpack_unused_export__ = ({ value: true });
+exports.w = void 0;
+/**
+ * @internal
+ *
+ * Holds the singleton instrumenter, to be shared across CJS and ESM imports.
+ */
+exports.w = {
+ instrumenterImplementation: undefined,
+};
+//# sourceMappingURL=state-cjs.cjs.map
- const cachedURL = new URL(request.url)
+/***/ }),
- if (options?.ignoreSearch) {
- cachedURL.search = ''
+/***/ 5209:
+/***/ ((__unused_webpack_module, exports) => {
- queryURL.search = ''
- }
- if (!urlEquals(queryURL, cachedURL, true)) {
- return false
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.cancelablePromiseRace = cancelablePromiseRace;
+/**
+ * promise.race() wrapper that aborts rest of promises as soon as the first promise settles.
+ */
+async function cancelablePromiseRace(abortablePromiseBuilders, options) {
+ const aborter = new AbortController();
+ function abortHandler() {
+ aborter.abort();
}
-
- if (
- response == null ||
- options?.ignoreVary ||
- !response.headersList.contains('vary')
- ) {
- return true
+ options?.abortSignal?.addEventListener("abort", abortHandler);
+ try {
+ return await Promise.race(abortablePromiseBuilders.map((p) => p({ abortSignal: aborter.signal })));
}
-
- const fieldValues = getFieldValues(response.headersList.get('vary'))
-
- for (const fieldValue of fieldValues) {
- if (fieldValue === '*') {
- return false
- }
-
- const requestValue = request.headersList.get(fieldValue)
- const queryValue = requestQuery.headersList.get(fieldValue)
-
- // If one has the header and the other doesn't, or one has
- // a different value than the other, return false
- if (requestValue !== queryValue) {
- return false
- }
+ finally {
+ aborter.abort();
+ options?.abortSignal?.removeEventListener("abort", abortHandler);
}
+}
+//# sourceMappingURL=aborterUtils.js.map
- return true
- }
+/***/ }),
- #internalMatchAll (request, options, maxResponses = Infinity) {
- // 1.
- let r = null
+/***/ 3128:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 2.
- if (request !== undefined) {
- if (request instanceof Request) {
- // 2.1.1
- r = request[kState]
- // 2.1.2
- if (r.method !== 'GET' && !options.ignoreMethod) {
- return []
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createAbortablePromise = createAbortablePromise;
+const abort_controller_1 = __nccwpck_require__(6492);
+/**
+ * Creates an abortable promise.
+ * @param buildPromise - A function that takes the resolve and reject functions as parameters.
+ * @param options - The options for the abortable promise.
+ * @returns A promise that can be aborted.
+ */
+function createAbortablePromise(buildPromise, options) {
+ const { cleanupBeforeAbort, abortSignal, abortErrorMsg } = options ?? {};
+ return new Promise((resolve, reject) => {
+ function rejectOnAbort() {
+ reject(new abort_controller_1.AbortError(abortErrorMsg ?? "The operation was aborted."));
}
- } else if (typeof request === 'string') {
- // 2.2.1
- r = new Request(request)[kState]
- }
- }
+ function removeListeners() {
+ abortSignal?.removeEventListener("abort", onAbort);
+ }
+ function onAbort() {
+ cleanupBeforeAbort?.();
+ removeListeners();
+ rejectOnAbort();
+ }
+ if (abortSignal?.aborted) {
+ return rejectOnAbort();
+ }
+ try {
+ buildPromise((x) => {
+ removeListeners();
+ resolve(x);
+ }, (x) => {
+ removeListeners();
+ reject(x);
+ });
+ }
+ catch (err) {
+ reject(err);
+ }
+ abortSignal?.addEventListener("abort", onAbort);
+ });
+}
+//# sourceMappingURL=createAbortablePromise.js.map
- // 5.
- // 5.1
- const responses = []
+/***/ }),
- // 5.2
- if (request === undefined) {
- // 5.2.1
- for (const requestResponse of this.#relevantRequestResponseList) {
- responses.push(requestResponse[1])
- }
- } else { // 5.3
- // 5.3.1
- const requestResponses = this.#queryCache(r, options)
+/***/ 636:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 5.3.2
- for (const requestResponse of requestResponses) {
- responses.push(requestResponse[1])
- }
- }
- // 5.4
- // We don't implement CORs so we don't need to loop over the responses, yay!
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.delay = delay;
+exports.calculateRetryDelay = calculateRetryDelay;
+const createAbortablePromise_js_1 = __nccwpck_require__(3128);
+const util_1 = __nccwpck_require__(5750);
+const StandardAbortMessage = "The delay was aborted.";
+/**
+ * A wrapper for setTimeout that resolves a promise after timeInMs milliseconds.
+ * @param timeInMs - The number of milliseconds to be delayed.
+ * @param options - The options for delay - currently abort options
+ * @returns Promise that is resolved after timeInMs
+ */
+function delay(timeInMs, options) {
+ let token;
+ const { abortSignal, abortErrorMsg } = options ?? {};
+ return (0, createAbortablePromise_js_1.createAbortablePromise)((resolve) => {
+ token = setTimeout(resolve, timeInMs);
+ }, {
+ cleanupBeforeAbort: () => clearTimeout(token),
+ abortSignal,
+ abortErrorMsg: abortErrorMsg ?? StandardAbortMessage,
+ });
+}
+/**
+ * Calculates the delay interval for retry attempts using exponential delay with jitter.
+ * @param retryAttempt - The current retry attempt number.
+ * @param config - The exponential retry configuration.
+ * @returns An object containing the calculated retry delay.
+ */
+function calculateRetryDelay(retryAttempt, config) {
+ // Exponentially increase the delay each time
+ const exponentialDelay = config.retryDelayInMs * Math.pow(2, retryAttempt);
+ // Don't let the delay exceed the maximum
+ const clampedDelay = Math.min(config.maxRetryDelayInMs, exponentialDelay);
+ // Allow the final value to have some "jitter" (within 50% of the delay size) so
+ // that retries across multiple clients don't occur simultaneously.
+ const retryAfterInMs = clampedDelay / 2 + (0, util_1.getRandomIntegerInclusive)(0, clampedDelay / 2);
+ return { retryAfterInMs };
+}
+//# sourceMappingURL=delay.js.map
- // 5.5.1
- const responseList = []
+/***/ }),
- // 5.5.2
- for (const response of responses) {
- // 5.5.2.1
- const responseObject = fromInnerResponse(response, 'immutable')
+/***/ 9945:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- responseList.push(responseObject.clone())
- if (responseList.length >= maxResponses) {
- break
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.getErrorMessage = getErrorMessage;
+const util_1 = __nccwpck_require__(5750);
+/**
+ * Given what is thought to be an error object, return the message if possible.
+ * If the message is missing, returns a stringified version of the input.
+ * @param e - Something thrown from a try block
+ * @returns The error message or a string of the input
+ */
+function getErrorMessage(e) {
+ if ((0, util_1.isError)(e)) {
+ return e.message;
+ }
+ else {
+ let stringified;
+ try {
+ if (typeof e === "object" && e) {
+ stringified = JSON.stringify(e);
+ }
+ else {
+ stringified = String(e);
+ }
+ }
+ catch (err) {
+ stringified = "[unable to stringify input]";
+ }
+ return `Unknown error ${stringified}`;
}
-
- // 6.
- return Object.freeze(responseList)
- }
}
+//# sourceMappingURL=error.js.map
-Object.defineProperties(Cache.prototype, {
- [Symbol.toStringTag]: {
- value: 'Cache',
- configurable: true
- },
- match: kEnumerableProperty,
- matchAll: kEnumerableProperty,
- add: kEnumerableProperty,
- addAll: kEnumerableProperty,
- put: kEnumerableProperty,
- delete: kEnumerableProperty,
- keys: kEnumerableProperty
-})
+/***/ }),
-const cacheQueryOptionConverters = [
- {
- key: 'ignoreSearch',
- converter: webidl.converters.boolean,
- defaultValue: () => false
- },
- {
- key: 'ignoreMethod',
- converter: webidl.converters.boolean,
- defaultValue: () => false
- },
- {
- key: 'ignoreVary',
- converter: webidl.converters.boolean,
- defaultValue: () => false
- }
-]
+/***/ 7779:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-webidl.converters.CacheQueryOptions = webidl.dictionaryConverter(cacheQueryOptionConverters)
-webidl.converters.MultiCacheQueryOptions = webidl.dictionaryConverter([
- ...cacheQueryOptionConverters,
- {
- key: 'cacheName',
- converter: webidl.converters.DOMString
- }
-])
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.isWebWorker = exports.isReactNative = exports.isNodeRuntime = exports.isNodeLike = exports.isNode = exports.isDeno = exports.isBun = exports.isBrowser = exports.objectHasProperty = exports.isObjectWithProperties = exports.isDefined = exports.getErrorMessage = exports.delay = exports.createAbortablePromise = exports.cancelablePromiseRace = void 0;
+exports.calculateRetryDelay = calculateRetryDelay;
+exports.computeSha256Hash = computeSha256Hash;
+exports.computeSha256Hmac = computeSha256Hmac;
+exports.getRandomIntegerInclusive = getRandomIntegerInclusive;
+exports.isError = isError;
+exports.isObject = isObject;
+exports.randomUUID = randomUUID;
+exports.uint8ArrayToString = uint8ArrayToString;
+exports.stringToUint8Array = stringToUint8Array;
+const tslib_1 = __nccwpck_require__(1860);
+const tspRuntime = tslib_1.__importStar(__nccwpck_require__(5750));
+var aborterUtils_js_1 = __nccwpck_require__(5209);
+Object.defineProperty(exports, "cancelablePromiseRace", ({ enumerable: true, get: function () { return aborterUtils_js_1.cancelablePromiseRace; } }));
+var createAbortablePromise_js_1 = __nccwpck_require__(3128);
+Object.defineProperty(exports, "createAbortablePromise", ({ enumerable: true, get: function () { return createAbortablePromise_js_1.createAbortablePromise; } }));
+var delay_js_1 = __nccwpck_require__(636);
+Object.defineProperty(exports, "delay", ({ enumerable: true, get: function () { return delay_js_1.delay; } }));
+var error_js_1 = __nccwpck_require__(9945);
+Object.defineProperty(exports, "getErrorMessage", ({ enumerable: true, get: function () { return error_js_1.getErrorMessage; } }));
+var typeGuards_js_1 = __nccwpck_require__(6277);
+Object.defineProperty(exports, "isDefined", ({ enumerable: true, get: function () { return typeGuards_js_1.isDefined; } }));
+Object.defineProperty(exports, "isObjectWithProperties", ({ enumerable: true, get: function () { return typeGuards_js_1.isObjectWithProperties; } }));
+Object.defineProperty(exports, "objectHasProperty", ({ enumerable: true, get: function () { return typeGuards_js_1.objectHasProperty; } }));
+/**
+ * Calculates the delay interval for retry attempts using exponential delay with jitter.
+ *
+ * @param retryAttempt - The current retry attempt number.
+ *
+ * @param config - The exponential retry configuration.
+ *
+ * @returns An object containing the calculated retry delay.
+ */
+function calculateRetryDelay(retryAttempt, config) {
+ return tspRuntime.calculateRetryDelay(retryAttempt, config);
+}
+/**
+ * Generates a SHA-256 hash.
+ *
+ * @param content - The data to be included in the hash.
+ *
+ * @param encoding - The textual encoding to use for the returned hash.
+ */
+function computeSha256Hash(content, encoding) {
+ return tspRuntime.computeSha256Hash(content, encoding);
+}
+/**
+ * Generates a SHA-256 HMAC signature.
+ *
+ * @param key - The HMAC key represented as a base64 string, used to generate the cryptographic HMAC hash.
+ *
+ * @param stringToSign - The data to be signed.
+ *
+ * @param encoding - The textual encoding to use for the returned HMAC digest.
+ */
+function computeSha256Hmac(key, stringToSign, encoding) {
+ return tspRuntime.computeSha256Hmac(key, stringToSign, encoding);
+}
+/**
+ * Returns a random integer value between a lower and upper bound, inclusive of both bounds. Note that this uses Math.random and isn't secure. If you need to use this for any kind of security purpose, find a better source of random.
+ *
+ * @param min - The smallest integer value allowed.
+ *
+ * @param max - The largest integer value allowed.
+ */
+function getRandomIntegerInclusive(min, max) {
+ return tspRuntime.getRandomIntegerInclusive(min, max);
+}
+/**
+ * Typeguard for an error object shape (has name and message)
+ *
+ * @param e - Something caught by a catch clause.
+ */
+function isError(e) {
+ return tspRuntime.isError(e);
+}
+/**
+ * Helper to determine when an input is a generic JS object.
+ *
+ * @returns true when input is an object type that is not null, Array, RegExp, or Date.
+ */
+function isObject(input) {
+ return tspRuntime.isObject(input);
+}
+/**
+ * Generated Universally Unique Identifier
+ *
+ * @returns RFC4122 v4 UUID.
+ */
+function randomUUID() {
+ return tspRuntime.randomUUID();
+}
+/**
+ * A constant that indicates whether the environment the code is running is a Web Browser.
+ */
+exports.isBrowser = tspRuntime.isBrowser;
+/**
+ * A constant that indicates whether the environment the code is running is Bun.sh.
+ */
+exports.isBun = tspRuntime.isBun;
+/**
+ * A constant that indicates whether the environment the code is running is Deno.
+ */
+exports.isDeno = tspRuntime.isDeno;
+/**
+ * A constant that indicates whether the environment the code is running is a Node.js compatible environment.
+ *
+ * @deprecated
+ *
+ * Use `isNodeLike` instead.
+ */
+exports.isNode = tspRuntime.isNodeLike;
+/**
+ * A constant that indicates whether the environment the code is running is a Node.js compatible environment.
+ */
+exports.isNodeLike = tspRuntime.isNodeLike;
+/**
+ * A constant that indicates whether the environment the code is running is Node.JS.
+ */
+exports.isNodeRuntime = tspRuntime.isNodeRuntime;
+/**
+ * A constant that indicates whether the environment the code is running is in React-Native.
+ */
+exports.isReactNative = tspRuntime.isReactNative;
+/**
+ * A constant that indicates whether the environment the code is running is a Web Worker.
+ */
+exports.isWebWorker = tspRuntime.isWebWorker;
+/**
+ * The helper that transforms bytes with specific character encoding into string
+ * @param bytes - the uint8array bytes
+ * @param format - the format we use to encode the byte
+ * @returns a string of the encoded string
+ */
+function uint8ArrayToString(bytes, format) {
+ return tspRuntime.uint8ArrayToString(bytes, format);
+}
+/**
+ * The helper that transforms string to specific character encoded bytes array.
+ * @param value - the string to be converted
+ * @param format - the format we use to decode the value
+ * @returns a uint8array
+ */
+function stringToUint8Array(value, format) {
+ return tspRuntime.stringToUint8Array(value, format);
+}
+//# sourceMappingURL=index.js.map
-webidl.converters.Response = webidl.interfaceConverter(Response)
+/***/ }),
-webidl.converters['sequence'] = webidl.sequenceConverter(
- webidl.converters.RequestInfo
-)
+/***/ 6277:
+/***/ ((__unused_webpack_module, exports) => {
-module.exports = {
- Cache
-}
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.isDefined = isDefined;
+exports.isObjectWithProperties = isObjectWithProperties;
+exports.objectHasProperty = objectHasProperty;
+/**
+ * Helper TypeGuard that checks if something is defined or not.
+ * @param thing - Anything
+ */
+function isDefined(thing) {
+ return typeof thing !== "undefined" && thing !== null;
+}
+/**
+ * Helper TypeGuard that checks if the input is an object with the specified properties.
+ * @param thing - Anything.
+ * @param properties - The name of the properties that should appear in the object.
+ */
+function isObjectWithProperties(thing, properties) {
+ if (!isDefined(thing) || typeof thing !== "object") {
+ return false;
+ }
+ for (const property of properties) {
+ if (!objectHasProperty(thing, property)) {
+ return false;
+ }
+ }
+ return true;
+}
+/**
+ * Helper TypeGuard that checks if the input is an object with the specified property.
+ * @param thing - Any object.
+ * @param property - The name of the property that should appear in the object.
+ */
+function objectHasProperty(thing, property) {
+ return (isDefined(thing) && typeof thing === "object" && property in thing);
+}
+//# sourceMappingURL=typeGuards.js.map
/***/ }),
-/***/ 6949:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 1658:
+/***/ ((__unused_webpack_module, exports) => {
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.AbortError = void 0;
+/**
+ * This error is thrown when an asynchronous operation has been aborted.
+ * Check for this error by testing the `name` that the name property of the
+ * error matches `"AbortError"`.
+ *
+ * @example
+ * ```ts
+ * const controller = new AbortController();
+ * controller.abort();
+ * try {
+ * doAsyncWork(controller.signal)
+ * } catch (e) {
+ * if (e.name === 'AbortError') {
+ * // handle abort error here.
+ * }
+ * }
+ * ```
+ */
+class AbortError extends Error {
+ constructor(message) {
+ super(message);
+ this.name = "AbortError";
+ }
+}
+exports.AbortError = AbortError;
+//# sourceMappingURL=AbortError.js.map
-const { kConstruct } = __nccwpck_require__(7589)
-const { Cache } = __nccwpck_require__(4330)
-const { webidl } = __nccwpck_require__(253)
-const { kEnumerableProperty } = __nccwpck_require__(1544)
+/***/ }),
-class CacheStorage {
- /**
- * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-name-to-cache-map
- * @type {Map {
- constructor () {
- if (arguments[0] !== kConstruct) {
- webidl.illegalConstructor()
- }
- webidl.util.markAsUncloneable(this)
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.AbortError = void 0;
+var AbortError_js_1 = __nccwpck_require__(1658);
+Object.defineProperty(exports, "AbortError", ({ enumerable: true, get: function () { return AbortError_js_1.AbortError; } }));
+//# sourceMappingURL=index.js.map
- async match (request, options = {}) {
- webidl.brandCheck(this, CacheStorage)
- webidl.argumentLengthCheck(arguments, 1, 'CacheStorage.match')
+/***/ }),
- request = webidl.converters.RequestInfo(request)
- options = webidl.converters.MultiCacheQueryOptions(options)
+/***/ 6515:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 1.
- if (options.cacheName != null) {
- // 1.1.1.1
- if (this.#caches.has(options.cacheName)) {
- // 1.1.1.1.1
- const cacheList = this.#caches.get(options.cacheName)
- const cache = new Cache(kConstruct, cacheList)
- return await cache.match(request, options)
- }
- } else { // 2.
- // 2.2
- for (const cacheList of this.#caches.values()) {
- const cache = new Cache(kConstruct, cacheList)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.AzureLogger = void 0;
+exports.setLogLevel = setLogLevel;
+exports.getLogLevel = getLogLevel;
+exports.createClientLogger = createClientLogger;
+const logger_1 = __nccwpck_require__(2490);
+const context = (0, logger_1.createLoggerContext)({
+ logLevelEnvVarName: "AZURE_LOG_LEVEL",
+ namespace: "azure",
+});
+/**
+ * The AzureLogger provides a mechanism for overriding where logs are output to.
+ * By default, logs are sent to stderr.
+ * Override the `log` method to redirect logs to another location.
+ */
+exports.AzureLogger = context.logger;
+/**
+ * Immediately enables logging at the specified log level. If no level is specified, logging is disabled.
+ * @param level - The log level to enable for logging.
+ * Options from most verbose to least verbose are:
+ * - verbose
+ * - info
+ * - warning
+ * - error
+ */
+function setLogLevel(level) {
+ context.setLogLevel(level);
+}
+/**
+ * Retrieves the currently specified log level.
+ */
+function getLogLevel() {
+ return context.getLogLevel();
+}
+/**
+ * Creates a logger for use by the Azure SDKs that inherits from `AzureLogger`.
+ * @param namespace - The name of the SDK package.
+ * @hidden
+ */
+function createClientLogger(namespace) {
+ return context.createClientLogger(namespace);
+}
+//# sourceMappingURL=index.js.map
- // 2.2.1.2
- const response = await cache.match(request, options)
+/***/ }),
- if (response !== undefined) {
- return response
+/***/ 6836:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+var __defProp = Object.defineProperty;
+var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
+var __getOwnPropNames = Object.getOwnPropertyNames;
+var __hasOwnProp = Object.prototype.hasOwnProperty;
+var __export = (target, all) => {
+ for (var name in all)
+ __defProp(target, name, { get: all[name], enumerable: true });
+};
+var __copyProps = (to, from, except, desc) => {
+ if (from && typeof from === "object" || typeof from === "function") {
+ for (let key of __getOwnPropNames(from))
+ if (!__hasOwnProp.call(to, key) && key !== except)
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
+ }
+ return to;
+};
+var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
+var debug_exports = {};
+__export(debug_exports, {
+ default: () => debug_default
+});
+module.exports = __toCommonJS(debug_exports);
+var import_log = __nccwpck_require__(8029);
+const debugEnvVariable = typeof process !== "undefined" && process.env && process.env.DEBUG || void 0;
+let enabledString;
+let enabledNamespaces = [];
+let skippedNamespaces = [];
+const debuggers = [];
+if (debugEnvVariable) {
+ enable(debugEnvVariable);
+}
+const debugObj = Object.assign(
+ (namespace) => {
+ return createDebugger(namespace);
+ },
+ {
+ enable,
+ enabled,
+ disable,
+ log: import_log.log
+ }
+);
+function enable(namespaces) {
+ enabledString = namespaces;
+ enabledNamespaces = [];
+ skippedNamespaces = [];
+ const namespaceList = namespaces.split(",").map((ns) => ns.trim());
+ for (const ns of namespaceList) {
+ if (ns.startsWith("-")) {
+ skippedNamespaces.push(ns.substring(1));
+ } else {
+ enabledNamespaces.push(ns);
+ }
+ }
+ for (const instance of debuggers) {
+ instance.enabled = enabled(instance.namespace);
+ }
+}
+function enabled(namespace) {
+ if (namespace.endsWith("*")) {
+ return true;
+ }
+ for (const skipped of skippedNamespaces) {
+ if (namespaceMatches(namespace, skipped)) {
+ return false;
+ }
+ }
+ for (const enabledNamespace of enabledNamespaces) {
+ if (namespaceMatches(namespace, enabledNamespace)) {
+ return true;
+ }
+ }
+ return false;
+}
+function namespaceMatches(namespace, patternToMatch) {
+ if (patternToMatch.indexOf("*") === -1) {
+ return namespace === patternToMatch;
+ }
+ let pattern = patternToMatch;
+ if (patternToMatch.indexOf("**") !== -1) {
+ const patternParts = [];
+ let lastCharacter = "";
+ for (const character of patternToMatch) {
+ if (character === "*" && lastCharacter === "*") {
+ continue;
+ } else {
+ lastCharacter = character;
+ patternParts.push(character);
+ }
+ }
+ pattern = patternParts.join("");
+ }
+ let namespaceIndex = 0;
+ let patternIndex = 0;
+ const patternLength = pattern.length;
+ const namespaceLength = namespace.length;
+ let lastWildcard = -1;
+ let lastWildcardNamespace = -1;
+ while (namespaceIndex < namespaceLength && patternIndex < patternLength) {
+ if (pattern[patternIndex] === "*") {
+ lastWildcard = patternIndex;
+ patternIndex++;
+ if (patternIndex === patternLength) {
+ return true;
+ }
+ while (namespace[namespaceIndex] !== pattern[patternIndex]) {
+ namespaceIndex++;
+ if (namespaceIndex === namespaceLength) {
+ return false;
}
}
+ lastWildcardNamespace = namespaceIndex;
+ namespaceIndex++;
+ patternIndex++;
+ continue;
+ } else if (pattern[patternIndex] === namespace[namespaceIndex]) {
+ patternIndex++;
+ namespaceIndex++;
+ } else if (lastWildcard >= 0) {
+ patternIndex = lastWildcard + 1;
+ namespaceIndex = lastWildcardNamespace + 1;
+ if (namespaceIndex === namespaceLength) {
+ return false;
+ }
+ while (namespace[namespaceIndex] !== pattern[patternIndex]) {
+ namespaceIndex++;
+ if (namespaceIndex === namespaceLength) {
+ return false;
+ }
+ }
+ lastWildcardNamespace = namespaceIndex;
+ namespaceIndex++;
+ patternIndex++;
+ continue;
+ } else {
+ return false;
}
}
+ const namespaceDone = namespaceIndex === namespace.length;
+ const patternDone = patternIndex === pattern.length;
+ const trailingWildCard = patternIndex === pattern.length - 1 && pattern[patternIndex] === "*";
+ return namespaceDone && (patternDone || trailingWildCard);
+}
+function disable() {
+ const result = enabledString || "";
+ enable("");
+ return result;
+}
+function createDebugger(namespace) {
+ const newDebugger = Object.assign(debug, {
+ enabled: enabled(namespace),
+ destroy,
+ log: debugObj.log,
+ namespace,
+ extend
+ });
+ function debug(...args) {
+ if (!newDebugger.enabled) {
+ return;
+ }
+ if (args.length > 0) {
+ args[0] = `${namespace} ${args[0]}`;
+ }
+ newDebugger.log(...args);
+ }
+ debuggers.push(newDebugger);
+ return newDebugger;
+}
+function destroy() {
+ const index = debuggers.indexOf(this);
+ if (index >= 0) {
+ debuggers.splice(index, 1);
+ return true;
+ }
+ return false;
+}
+function extend(namespace) {
+ const newDebugger = createDebugger(`${this.namespace}:${namespace}`);
+ newDebugger.log = this.log;
+ return newDebugger;
+}
+var debug_default = debugObj;
+//# sourceMappingURL=debug.js.map
- /**
- * @see https://w3c.github.io/ServiceWorker/#cache-storage-has
- * @param {string} cacheName
- * @returns {Promise}
- */
- async has (cacheName) {
- webidl.brandCheck(this, CacheStorage)
- const prefix = 'CacheStorage.has'
- webidl.argumentLengthCheck(arguments, 1, prefix)
+/***/ }),
- cacheName = webidl.converters.DOMString(cacheName, prefix, 'cacheName')
+/***/ 2490:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 2.1.1
- // 2.2
- return this.#caches.has(cacheName)
- }
+var __defProp = Object.defineProperty;
+var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
+var __getOwnPropNames = Object.getOwnPropertyNames;
+var __hasOwnProp = Object.prototype.hasOwnProperty;
+var __export = (target, all) => {
+ for (var name in all)
+ __defProp(target, name, { get: all[name], enumerable: true });
+};
+var __copyProps = (to, from, except, desc) => {
+ if (from && typeof from === "object" || typeof from === "function") {
+ for (let key of __getOwnPropNames(from))
+ if (!__hasOwnProp.call(to, key) && key !== except)
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
+ }
+ return to;
+};
+var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
+var internal_exports = {};
+__export(internal_exports, {
+ createLoggerContext: () => import_logger.createLoggerContext
+});
+module.exports = __toCommonJS(internal_exports);
+var import_logger = __nccwpck_require__(8459);
+// Annotate the CommonJS export names for ESM import in node:
+0 && (0);
+//# sourceMappingURL=internal.js.map
- /**
- * @see https://w3c.github.io/ServiceWorker/#dom-cachestorage-open
- * @param {string} cacheName
- * @returns {Promise}
- */
- async open (cacheName) {
- webidl.brandCheck(this, CacheStorage)
- const prefix = 'CacheStorage.open'
- webidl.argumentLengthCheck(arguments, 1, prefix)
+/***/ }),
- cacheName = webidl.converters.DOMString(cacheName, prefix, 'cacheName')
+/***/ 8029:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 2.1
- if (this.#caches.has(cacheName)) {
- // await caches.open('v1') !== await caches.open('v1')
+var __create = Object.create;
+var __defProp = Object.defineProperty;
+var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
+var __getOwnPropNames = Object.getOwnPropertyNames;
+var __getProtoOf = Object.getPrototypeOf;
+var __hasOwnProp = Object.prototype.hasOwnProperty;
+var __export = (target, all) => {
+ for (var name in all)
+ __defProp(target, name, { get: all[name], enumerable: true });
+};
+var __copyProps = (to, from, except, desc) => {
+ if (from && typeof from === "object" || typeof from === "function") {
+ for (let key of __getOwnPropNames(from))
+ if (!__hasOwnProp.call(to, key) && key !== except)
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
+ }
+ return to;
+};
+var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
+ // If the importer is in node compatibility mode or this is not an ESM
+ // file that has been converted to a CommonJS file using a Babel-
+ // compatible transform (i.e. "__esModule" has not been set), then set
+ // "default" to the CommonJS "module.exports" for node compatibility.
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
+ mod
+));
+var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
+var log_exports = {};
+__export(log_exports, {
+ log: () => log
+});
+module.exports = __toCommonJS(log_exports);
+var import_node_os = __nccwpck_require__(8161);
+var import_node_util = __toESM(__nccwpck_require__(7975));
+var import_node_process = __toESM(__nccwpck_require__(1708));
+function log(message, ...args) {
+ import_node_process.default.stderr.write(`${import_node_util.default.format(message, ...args)}${import_node_os.EOL}`);
+}
+// Annotate the CommonJS export names for ESM import in node:
+0 && (0);
+//# sourceMappingURL=log.js.map
- // 2.1.1
- const cache = this.#caches.get(cacheName)
- // 2.1.1.1
- return new Cache(kConstruct, cache)
- }
+/***/ }),
- // 2.2
- const cache = []
-
- // 2.3
- this.#caches.set(cacheName, cache)
+/***/ 8459:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 2.4
- return new Cache(kConstruct, cache)
+var __create = Object.create;
+var __defProp = Object.defineProperty;
+var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
+var __getOwnPropNames = Object.getOwnPropertyNames;
+var __getProtoOf = Object.getPrototypeOf;
+var __hasOwnProp = Object.prototype.hasOwnProperty;
+var __export = (target, all) => {
+ for (var name in all)
+ __defProp(target, name, { get: all[name], enumerable: true });
+};
+var __copyProps = (to, from, except, desc) => {
+ if (from && typeof from === "object" || typeof from === "function") {
+ for (let key of __getOwnPropNames(from))
+ if (!__hasOwnProp.call(to, key) && key !== except)
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
+ }
+ return to;
+};
+var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
+ // If the importer is in node compatibility mode or this is not an ESM
+ // file that has been converted to a CommonJS file using a Babel-
+ // compatible transform (i.e. "__esModule" has not been set), then set
+ // "default" to the CommonJS "module.exports" for node compatibility.
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
+ mod
+));
+var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
+var logger_exports = {};
+__export(logger_exports, {
+ TypeSpecRuntimeLogger: () => TypeSpecRuntimeLogger,
+ createClientLogger: () => createClientLogger,
+ createLoggerContext: () => createLoggerContext,
+ getLogLevel: () => getLogLevel,
+ setLogLevel: () => setLogLevel
+});
+module.exports = __toCommonJS(logger_exports);
+var import_debug = __toESM(__nccwpck_require__(6836));
+const TYPESPEC_RUNTIME_LOG_LEVELS = ["verbose", "info", "warning", "error"];
+const levelMap = {
+ verbose: 400,
+ info: 300,
+ warning: 200,
+ error: 100
+};
+function patchLogMethod(parent, child) {
+ child.log = (...args) => {
+ parent.log(...args);
+ };
+}
+function isTypeSpecRuntimeLogLevel(level) {
+ return TYPESPEC_RUNTIME_LOG_LEVELS.includes(level);
+}
+function createLoggerContext(options) {
+ const registeredLoggers = /* @__PURE__ */ new Set();
+ const logLevelFromEnv = typeof process !== "undefined" && process.env && process.env[options.logLevelEnvVarName] || void 0;
+ let logLevel;
+ const clientLogger = (0, import_debug.default)(options.namespace);
+ clientLogger.log = (...args) => {
+ import_debug.default.log(...args);
+ };
+ function contextSetLogLevel(level) {
+ if (level && !isTypeSpecRuntimeLogLevel(level)) {
+ throw new Error(
+ `Unknown log level '${level}'. Acceptable values: ${TYPESPEC_RUNTIME_LOG_LEVELS.join(",")}`
+ );
+ }
+ logLevel = level;
+ const enabledNamespaces = [];
+ for (const logger of registeredLoggers) {
+ if (shouldEnable(logger)) {
+ enabledNamespaces.push(logger.namespace);
+ }
+ }
+ import_debug.default.enable(enabledNamespaces.join(","));
}
+ if (logLevelFromEnv) {
+ if (isTypeSpecRuntimeLogLevel(logLevelFromEnv)) {
+ contextSetLogLevel(logLevelFromEnv);
+ } else {
+ console.error(
+ `${options.logLevelEnvVarName} set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${TYPESPEC_RUNTIME_LOG_LEVELS.join(
+ ", "
+ )}.`
+ );
+ }
+ }
+ function shouldEnable(logger) {
+ return Boolean(logLevel && levelMap[logger.level] <= levelMap[logLevel]);
+ }
+ function createLogger(parent, level) {
+ const logger = Object.assign(parent.extend(level), {
+ level
+ });
+ patchLogMethod(parent, logger);
+ if (shouldEnable(logger)) {
+ const enabledNamespaces = import_debug.default.disable();
+ import_debug.default.enable(enabledNamespaces + "," + logger.namespace);
+ }
+ registeredLoggers.add(logger);
+ return logger;
+ }
+ function contextGetLogLevel() {
+ return logLevel;
+ }
+ function contextCreateClientLogger(namespace) {
+ const clientRootLogger = clientLogger.extend(namespace);
+ patchLogMethod(clientLogger, clientRootLogger);
+ return {
+ error: createLogger(clientRootLogger, "error"),
+ warning: createLogger(clientRootLogger, "warning"),
+ info: createLogger(clientRootLogger, "info"),
+ verbose: createLogger(clientRootLogger, "verbose")
+ };
+ }
+ return {
+ setLogLevel: contextSetLogLevel,
+ getLogLevel: contextGetLogLevel,
+ createClientLogger: contextCreateClientLogger,
+ logger: clientLogger
+ };
+}
+const context = createLoggerContext({
+ logLevelEnvVarName: "TYPESPEC_RUNTIME_LOG_LEVEL",
+ namespace: "typeSpecRuntime"
+});
+const TypeSpecRuntimeLogger = context.logger;
+function setLogLevel(logLevel) {
+ context.setLogLevel(logLevel);
+}
+function getLogLevel() {
+ return context.getLogLevel();
+}
+function createClientLogger(namespace) {
+ return context.createClientLogger(namespace);
+}
+// Annotate the CommonJS export names for ESM import in node:
+0 && (0);
+//# sourceMappingURL=logger.js.map
- /**
- * @see https://w3c.github.io/ServiceWorker/#cache-storage-delete
- * @param {string} cacheName
- * @returns {Promise}
- */
- async delete (cacheName) {
- webidl.brandCheck(this, CacheStorage)
-
- const prefix = 'CacheStorage.delete'
- webidl.argumentLengthCheck(arguments, 1, prefix)
- cacheName = webidl.converters.DOMString(cacheName, prefix, 'cacheName')
+/***/ }),
- return this.#caches.delete(cacheName)
- }
+/***/ 2921:
+/***/ ((module) => {
- /**
- * @see https://w3c.github.io/ServiceWorker/#cache-storage-keys
- * @returns {Promise}
- */
- async keys () {
- webidl.brandCheck(this, CacheStorage)
+var __defProp = Object.defineProperty;
+var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
+var __getOwnPropNames = Object.getOwnPropertyNames;
+var __hasOwnProp = Object.prototype.hasOwnProperty;
+var __export = (target, all) => {
+ for (var name in all)
+ __defProp(target, name, { get: all[name], enumerable: true });
+};
+var __copyProps = (to, from, except, desc) => {
+ if (from && typeof from === "object" || typeof from === "function") {
+ for (let key of __getOwnPropNames(from))
+ if (!__hasOwnProp.call(to, key) && key !== except)
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
+ }
+ return to;
+};
+var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
+var bytesEncoding_exports = {};
+__export(bytesEncoding_exports, {
+ stringToUint8Array: () => stringToUint8Array,
+ uint8ArrayToString: () => uint8ArrayToString
+});
+module.exports = __toCommonJS(bytesEncoding_exports);
+function uint8ArrayToString(bytes, format) {
+ return Buffer.from(bytes).toString(format);
+}
+function stringToUint8Array(value, format) {
+ return Buffer.from(value, format);
+}
+// Annotate the CommonJS export names for ESM import in node:
+0 && (0);
+//# sourceMappingURL=bytesEncoding.js.map
- // 2.1
- const keys = this.#caches.keys()
- // 2.2
- return [...keys]
- }
-}
+/***/ }),
-Object.defineProperties(CacheStorage.prototype, {
- [Symbol.toStringTag]: {
- value: 'CacheStorage',
- configurable: true
- },
- match: kEnumerableProperty,
- has: kEnumerableProperty,
- open: kEnumerableProperty,
- delete: kEnumerableProperty,
- keys: kEnumerableProperty
-})
+/***/ 5086:
+/***/ ((module) => {
-module.exports = {
- CacheStorage
-}
+var __defProp = Object.defineProperty;
+var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
+var __getOwnPropNames = Object.getOwnPropertyNames;
+var __hasOwnProp = Object.prototype.hasOwnProperty;
+var __export = (target, all) => {
+ for (var name in all)
+ __defProp(target, name, { get: all[name], enumerable: true });
+};
+var __copyProps = (to, from, except, desc) => {
+ if (from && typeof from === "object" || typeof from === "function") {
+ for (let key of __getOwnPropNames(from))
+ if (!__hasOwnProp.call(to, key) && key !== except)
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
+ }
+ return to;
+};
+var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
+var checkEnvironment_exports = {};
+__export(checkEnvironment_exports, {
+ isBrowser: () => isBrowser,
+ isBun: () => isBun,
+ isDeno: () => isDeno,
+ isNodeLike: () => isNodeLike,
+ isNodeRuntime: () => isNodeRuntime,
+ isReactNative: () => isReactNative,
+ isWebWorker: () => isWebWorker
+});
+module.exports = __toCommonJS(checkEnvironment_exports);
+const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined";
+const isWebWorker = typeof self === "object" && typeof self?.importScripts === "function" && (self.constructor?.name === "DedicatedWorkerGlobalScope" || self.constructor?.name === "ServiceWorkerGlobalScope" || self.constructor?.name === "SharedWorkerGlobalScope");
+const isDeno = typeof Deno !== "undefined" && typeof Deno.version !== "undefined" && typeof Deno.version.deno !== "undefined";
+const isBun = typeof Bun !== "undefined" && typeof Bun.version !== "undefined";
+const isNodeLike = typeof globalThis.process !== "undefined" && Boolean(globalThis.process.version) && Boolean(globalThis.process.versions?.node);
+const isNodeRuntime = isNodeLike && !isBun && !isDeno;
+const isReactNative = typeof navigator !== "undefined" && navigator?.product === "ReactNative";
+// Annotate the CommonJS export names for ESM import in node:
+0 && (0);
+//# sourceMappingURL=checkEnvironment.js.map
/***/ }),
-/***/ 7589:
+/***/ 6776:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+var __defProp = Object.defineProperty;
+var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
+var __getOwnPropNames = Object.getOwnPropertyNames;
+var __hasOwnProp = Object.prototype.hasOwnProperty;
+var __export = (target, all) => {
+ for (var name in all)
+ __defProp(target, name, { get: all[name], enumerable: true });
+};
+var __copyProps = (to, from, except, desc) => {
+ if (from && typeof from === "object" || typeof from === "function") {
+ for (let key of __getOwnPropNames(from))
+ if (!__hasOwnProp.call(to, key) && key !== except)
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
+ }
+ return to;
+};
+var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
+var delay_exports = {};
+__export(delay_exports, {
+ calculateRetryDelay: () => calculateRetryDelay
+});
+module.exports = __toCommonJS(delay_exports);
+var import_random = __nccwpck_require__(8640);
+function calculateRetryDelay(retryAttempt, config) {
+ const exponentialDelay = config.retryDelayInMs * Math.pow(2, retryAttempt);
+ const clampedDelay = Math.min(config.maxRetryDelayInMs, exponentialDelay);
+ const retryAfterInMs = clampedDelay / 2 + (0, import_random.getRandomIntegerInclusive)(0, clampedDelay / 2);
+ return { retryAfterInMs };
+}
+// Annotate the CommonJS export names for ESM import in node:
+0 && (0);
+//# sourceMappingURL=delay.js.map
-module.exports = {
- kConstruct: (__nccwpck_require__(9411).kConstruct)
+/***/ }),
+
+/***/ 2573:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+var __defProp = Object.defineProperty;
+var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
+var __getOwnPropNames = Object.getOwnPropertyNames;
+var __hasOwnProp = Object.prototype.hasOwnProperty;
+var __export = (target, all) => {
+ for (var name in all)
+ __defProp(target, name, { get: all[name], enumerable: true });
+};
+var __copyProps = (to, from, except, desc) => {
+ if (from && typeof from === "object" || typeof from === "function") {
+ for (let key of __getOwnPropNames(from))
+ if (!__hasOwnProp.call(to, key) && key !== except)
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
+ }
+ return to;
+};
+var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
+var error_exports = {};
+__export(error_exports, {
+ isError: () => isError
+});
+module.exports = __toCommonJS(error_exports);
+var import_object = __nccwpck_require__(3632);
+function isError(e) {
+ if ((0, import_object.isObject)(e)) {
+ const hasName = typeof e.name === "string";
+ const hasMessage = typeof e.message === "string";
+ return hasName && hasMessage;
+ }
+ return false;
}
+// Annotate the CommonJS export names for ESM import in node:
+0 && (0);
+//# sourceMappingURL=error.js.map
/***/ }),
-/***/ 102:
+/***/ 5750:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+var __defProp = Object.defineProperty;
+var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
+var __getOwnPropNames = Object.getOwnPropertyNames;
+var __hasOwnProp = Object.prototype.hasOwnProperty;
+var __export = (target, all) => {
+ for (var name in all)
+ __defProp(target, name, { get: all[name], enumerable: true });
+};
+var __copyProps = (to, from, except, desc) => {
+ if (from && typeof from === "object" || typeof from === "function") {
+ for (let key of __getOwnPropNames(from))
+ if (!__hasOwnProp.call(to, key) && key !== except)
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
+ }
+ return to;
+};
+var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
+var internal_exports = {};
+__export(internal_exports, {
+ Sanitizer: () => import_sanitizer.Sanitizer,
+ calculateRetryDelay: () => import_delay.calculateRetryDelay,
+ computeSha256Hash: () => import_sha256.computeSha256Hash,
+ computeSha256Hmac: () => import_sha256.computeSha256Hmac,
+ getRandomIntegerInclusive: () => import_random.getRandomIntegerInclusive,
+ isBrowser: () => import_checkEnvironment.isBrowser,
+ isBun: () => import_checkEnvironment.isBun,
+ isDeno: () => import_checkEnvironment.isDeno,
+ isError: () => import_error.isError,
+ isNodeLike: () => import_checkEnvironment.isNodeLike,
+ isNodeRuntime: () => import_checkEnvironment.isNodeRuntime,
+ isObject: () => import_object.isObject,
+ isReactNative: () => import_checkEnvironment.isReactNative,
+ isWebWorker: () => import_checkEnvironment.isWebWorker,
+ randomUUID: () => import_uuidUtils.randomUUID,
+ stringToUint8Array: () => import_bytesEncoding.stringToUint8Array,
+ uint8ArrayToString: () => import_bytesEncoding.uint8ArrayToString
+});
+module.exports = __toCommonJS(internal_exports);
+var import_delay = __nccwpck_require__(6776);
+var import_random = __nccwpck_require__(8640);
+var import_object = __nccwpck_require__(3632);
+var import_error = __nccwpck_require__(2573);
+var import_sha256 = __nccwpck_require__(2016);
+var import_uuidUtils = __nccwpck_require__(5023);
+var import_checkEnvironment = __nccwpck_require__(5086);
+var import_bytesEncoding = __nccwpck_require__(2921);
+var import_sanitizer = __nccwpck_require__(7784);
+// Annotate the CommonJS export names for ESM import in node:
+0 && (0);
+//# sourceMappingURL=internal.js.map
-const assert = __nccwpck_require__(4589)
-const { URLSerializer } = __nccwpck_require__(980)
-const { isValidHeaderName } = __nccwpck_require__(4296)
+/***/ }),
-/**
- * @see https://url.spec.whatwg.org/#concept-url-equals
- * @param {URL} A
- * @param {URL} B
- * @param {boolean | undefined} excludeFragment
- * @returns {boolean}
- */
-function urlEquals (A, B, excludeFragment = false) {
- const serializedA = URLSerializer(A, excludeFragment)
+/***/ 3632:
+/***/ ((module) => {
- const serializedB = URLSerializer(B, excludeFragment)
+var __defProp = Object.defineProperty;
+var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
+var __getOwnPropNames = Object.getOwnPropertyNames;
+var __hasOwnProp = Object.prototype.hasOwnProperty;
+var __export = (target, all) => {
+ for (var name in all)
+ __defProp(target, name, { get: all[name], enumerable: true });
+};
+var __copyProps = (to, from, except, desc) => {
+ if (from && typeof from === "object" || typeof from === "function") {
+ for (let key of __getOwnPropNames(from))
+ if (!__hasOwnProp.call(to, key) && key !== except)
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
+ }
+ return to;
+};
+var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
+var object_exports = {};
+__export(object_exports, {
+ isObject: () => isObject
+});
+module.exports = __toCommonJS(object_exports);
+function isObject(input) {
+ return typeof input === "object" && input !== null && !Array.isArray(input) && !(input instanceof RegExp) && !(input instanceof Date);
+}
+// Annotate the CommonJS export names for ESM import in node:
+0 && (0);
+//# sourceMappingURL=object.js.map
- return serializedA === serializedB
+
+/***/ }),
+
+/***/ 8640:
+/***/ ((module) => {
+
+var __defProp = Object.defineProperty;
+var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
+var __getOwnPropNames = Object.getOwnPropertyNames;
+var __hasOwnProp = Object.prototype.hasOwnProperty;
+var __export = (target, all) => {
+ for (var name in all)
+ __defProp(target, name, { get: all[name], enumerable: true });
+};
+var __copyProps = (to, from, except, desc) => {
+ if (from && typeof from === "object" || typeof from === "function") {
+ for (let key of __getOwnPropNames(from))
+ if (!__hasOwnProp.call(to, key) && key !== except)
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
+ }
+ return to;
+};
+var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
+var random_exports = {};
+__export(random_exports, {
+ getRandomIntegerInclusive: () => getRandomIntegerInclusive
+});
+module.exports = __toCommonJS(random_exports);
+function getRandomIntegerInclusive(min, max) {
+ min = Math.ceil(min);
+ max = Math.floor(max);
+ const offset = Math.floor(Math.random() * (max - min + 1));
+ return offset + min;
}
+// Annotate the CommonJS export names for ESM import in node:
+0 && (0);
+//# sourceMappingURL=random.js.map
-/**
- * @see https://github.com/chromium/chromium/blob/694d20d134cb553d8d89e5500b9148012b1ba299/content/browser/cache_storage/cache_storage_cache.cc#L260-L262
- * @param {string} header
- */
-function getFieldValues (header) {
- assert(header !== null)
- const values = []
+/***/ }),
- for (let value of header.split(',')) {
- value = value.trim()
+/***/ 7784:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- if (isValidHeaderName(value)) {
- values.push(value)
+var __defProp = Object.defineProperty;
+var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
+var __getOwnPropNames = Object.getOwnPropertyNames;
+var __hasOwnProp = Object.prototype.hasOwnProperty;
+var __export = (target, all) => {
+ for (var name in all)
+ __defProp(target, name, { get: all[name], enumerable: true });
+};
+var __copyProps = (to, from, except, desc) => {
+ if (from && typeof from === "object" || typeof from === "function") {
+ for (let key of __getOwnPropNames(from))
+ if (!__hasOwnProp.call(to, key) && key !== except)
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
+ }
+ return to;
+};
+var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
+var sanitizer_exports = {};
+__export(sanitizer_exports, {
+ Sanitizer: () => Sanitizer
+});
+module.exports = __toCommonJS(sanitizer_exports);
+var import_object = __nccwpck_require__(3632);
+const RedactedString = "REDACTED";
+const defaultAllowedHeaderNames = [
+ "x-ms-client-request-id",
+ "x-ms-return-client-request-id",
+ "x-ms-useragent",
+ "x-ms-correlation-request-id",
+ "x-ms-request-id",
+ "client-request-id",
+ "ms-cv",
+ "return-client-request-id",
+ "traceparent",
+ "Access-Control-Allow-Credentials",
+ "Access-Control-Allow-Headers",
+ "Access-Control-Allow-Methods",
+ "Access-Control-Allow-Origin",
+ "Access-Control-Expose-Headers",
+ "Access-Control-Max-Age",
+ "Access-Control-Request-Headers",
+ "Access-Control-Request-Method",
+ "Origin",
+ "Accept",
+ "Accept-Encoding",
+ "Cache-Control",
+ "Connection",
+ "Content-Length",
+ "Content-Type",
+ "Date",
+ "ETag",
+ "Expires",
+ "If-Match",
+ "If-Modified-Since",
+ "If-None-Match",
+ "If-Unmodified-Since",
+ "Last-Modified",
+ "Pragma",
+ "Request-Id",
+ "Retry-After",
+ "Server",
+ "Transfer-Encoding",
+ "User-Agent",
+ "WWW-Authenticate"
+];
+const defaultAllowedQueryParameters = ["api-version"];
+class Sanitizer {
+ allowedHeaderNames;
+ allowedQueryParameters;
+ constructor({
+ additionalAllowedHeaderNames: allowedHeaderNames = [],
+ additionalAllowedQueryParameters: allowedQueryParameters = []
+ } = {}) {
+ allowedHeaderNames = defaultAllowedHeaderNames.concat(allowedHeaderNames);
+ allowedQueryParameters = defaultAllowedQueryParameters.concat(allowedQueryParameters);
+ this.allowedHeaderNames = new Set(allowedHeaderNames.map((n) => n.toLowerCase()));
+ this.allowedQueryParameters = new Set(allowedQueryParameters.map((p) => p.toLowerCase()));
+ }
+ /**
+ * Sanitizes an object for logging.
+ * @param obj - The object to sanitize
+ * @returns - The sanitized object as a string
+ */
+ sanitize(obj) {
+ const seen = /* @__PURE__ */ new Set();
+ return JSON.stringify(
+ obj,
+ (key, value) => {
+ if (value instanceof Error) {
+ return {
+ ...value,
+ name: value.name,
+ message: value.message
+ };
+ }
+ if (key === "headers" && (0, import_object.isObject)(value)) {
+ return this.sanitizeHeaders(value);
+ } else if (key === "url" && typeof value === "string") {
+ return this.sanitizeUrl(value);
+ } else if (key === "query" && (0, import_object.isObject)(value)) {
+ return this.sanitizeQuery(value);
+ } else if (key === "body") {
+ return void 0;
+ } else if (key === "response") {
+ return void 0;
+ } else if (key === "operationSpec") {
+ return void 0;
+ } else if (Array.isArray(value) || (0, import_object.isObject)(value)) {
+ if (seen.has(value)) {
+ return "[Circular]";
+ }
+ seen.add(value);
+ }
+ return value;
+ },
+ 2
+ );
+ }
+ /**
+ * Sanitizes a URL for logging.
+ * @param value - The URL to sanitize
+ * @returns - The sanitized URL as a string
+ */
+ sanitizeUrl(value) {
+ if (typeof value !== "string" || value === null || value === "") {
+ return value;
+ }
+ const url = new URL(value);
+ if (!url.search) {
+ return value;
}
+ for (const [key] of url.searchParams) {
+ if (!this.allowedQueryParameters.has(key.toLowerCase())) {
+ url.searchParams.set(key, RedactedString);
+ }
+ }
+ return url.toString();
+ }
+ sanitizeHeaders(obj) {
+ const sanitized = {};
+ for (const key of Object.keys(obj)) {
+ if (this.allowedHeaderNames.has(key.toLowerCase())) {
+ sanitized[key] = obj[key];
+ } else {
+ sanitized[key] = RedactedString;
+ }
+ }
+ return sanitized;
+ }
+ sanitizeQuery(value) {
+ if (typeof value !== "object" || value === null) {
+ return value;
+ }
+ const sanitized = {};
+ for (const k of Object.keys(value)) {
+ if (this.allowedQueryParameters.has(k.toLowerCase())) {
+ sanitized[k] = value[k];
+ } else {
+ sanitized[k] = RedactedString;
+ }
+ }
+ return sanitized;
}
-
- return values
-}
-
-module.exports = {
- urlEquals,
- getFieldValues
}
+// Annotate the CommonJS export names for ESM import in node:
+0 && (0);
+//# sourceMappingURL=sanitizer.js.map
/***/ }),
-/***/ 6820:
-/***/ ((module) => {
+/***/ 2016:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+var __defProp = Object.defineProperty;
+var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
+var __getOwnPropNames = Object.getOwnPropertyNames;
+var __hasOwnProp = Object.prototype.hasOwnProperty;
+var __export = (target, all) => {
+ for (var name in all)
+ __defProp(target, name, { get: all[name], enumerable: true });
+};
+var __copyProps = (to, from, except, desc) => {
+ if (from && typeof from === "object" || typeof from === "function") {
+ for (let key of __getOwnPropNames(from))
+ if (!__hasOwnProp.call(to, key) && key !== except)
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
+ }
+ return to;
+};
+var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
+var sha256_exports = {};
+__export(sha256_exports, {
+ computeSha256Hash: () => computeSha256Hash,
+ computeSha256Hmac: () => computeSha256Hmac
+});
+module.exports = __toCommonJS(sha256_exports);
+var import_node_crypto = __nccwpck_require__(7598);
+async function computeSha256Hmac(key, stringToSign, encoding) {
+ const decodedKey = Buffer.from(key, "base64");
+ return (0, import_node_crypto.createHmac)("sha256", decodedKey).update(stringToSign).digest(encoding);
+}
+async function computeSha256Hash(content, encoding) {
+ return (0, import_node_crypto.createHash)("sha256").update(content).digest(encoding);
+}
+// Annotate the CommonJS export names for ESM import in node:
+0 && (0);
+//# sourceMappingURL=sha256.js.map
-// https://wicg.github.io/cookie-store/#cookie-maximum-attribute-value-size
-const maxAttributeValueSize = 1024
+/***/ }),
-// https://wicg.github.io/cookie-store/#cookie-maximum-name-value-pair-size
-const maxNameValuePairSize = 4096
+/***/ 5023:
+/***/ ((module) => {
-module.exports = {
- maxAttributeValueSize,
- maxNameValuePairSize
+var __defProp = Object.defineProperty;
+var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
+var __getOwnPropNames = Object.getOwnPropertyNames;
+var __hasOwnProp = Object.prototype.hasOwnProperty;
+var __export = (target, all) => {
+ for (var name in all)
+ __defProp(target, name, { get: all[name], enumerable: true });
+};
+var __copyProps = (to, from, except, desc) => {
+ if (from && typeof from === "object" || typeof from === "function") {
+ for (let key of __getOwnPropNames(from))
+ if (!__hasOwnProp.call(to, key) && key !== except)
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
+ }
+ return to;
+};
+var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
+var uuidUtils_exports = {};
+__export(uuidUtils_exports, {
+ randomUUID: () => randomUUID
+});
+module.exports = __toCommonJS(uuidUtils_exports);
+function randomUUID() {
+ return crypto.randomUUID();
}
+// Annotate the CommonJS export names for ESM import in node:
+0 && (0);
+//# sourceMappingURL=uuidUtils.js.map
/***/ }),
-/***/ 5437:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 1120:
+/***/ ((module) => {
+var __webpack_unused_export__;
-const { parseSetCookie } = __nccwpck_require__(2802)
-const { stringify } = __nccwpck_require__(5613)
-const { webidl } = __nccwpck_require__(253)
-const { Headers } = __nccwpck_require__(3676)
+const NullObject = function NullObject () { }
+NullObject.prototype = Object.create(null)
/**
- * @typedef {Object} Cookie
- * @property {string} name
- * @property {string} value
- * @property {Date|number|undefined} expires
- * @property {number|undefined} maxAge
- * @property {string|undefined} domain
- * @property {string|undefined} path
- * @property {boolean|undefined} secure
- * @property {boolean|undefined} httpOnly
- * @property {'Strict'|'Lax'|'None'} sameSite
- * @property {string[]} unparsed
+ * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1
+ *
+ * parameter = token "=" ( token / quoted-string )
+ * token = 1*tchar
+ * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
+ * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
+ * / DIGIT / ALPHA
+ * ; any VCHAR, except delimiters
+ * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE
+ * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text
+ * obs-text = %x80-FF
+ * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text )
*/
+const paramRE = /; *([!#$%&'*+.^\w`|~-]+)=("(?:[\v\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\v\u0020-\u00ff])*"|[!#$%&'*+.^\w`|~-]+) */gu
/**
- * @param {Headers} headers
- * @returns {Record}
+ * RegExp to match quoted-pair in RFC 7230 sec 3.2.6
+ *
+ * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text )
+ * obs-text = %x80-FF
*/
-function getCookies (headers) {
- webidl.argumentLengthCheck(arguments, 1, 'getCookies')
+const quotedPairRE = /\\([\v\u0020-\u00ff])/gu
- webidl.brandCheck(headers, Headers, { strict: false })
+/**
+ * RegExp to match type in RFC 7231 sec 3.1.1.1
+ *
+ * media-type = type "/" subtype
+ * type = token
+ * subtype = token
+ */
+const mediaTypeRE = /^[!#$%&'*+.^\w|~-]+\/[!#$%&'*+.^\w|~-]+$/u
- const cookie = headers.get('cookie')
- const out = {}
+// default ContentType to prevent repeated object creation
+const defaultContentType = { type: '', parameters: new NullObject() }
+Object.freeze(defaultContentType.parameters)
+Object.freeze(defaultContentType)
- if (!cookie) {
- return out
+/**
+ * Parse media type to object.
+ *
+ * @param {string|object} header
+ * @return {Object}
+ * @public
+ */
+
+function parse (header) {
+ if (typeof header !== 'string') {
+ throw new TypeError('argument header is required and must be a string')
}
- for (const piece of cookie.split(';')) {
- const [name, ...value] = piece.split('=')
+ let index = header.indexOf(';')
+ const type = index !== -1
+ ? header.slice(0, index).trim()
+ : header.trim()
- out[name.trim()] = value.join('=')
+ if (mediaTypeRE.test(type) === false) {
+ throw new TypeError('invalid media type')
}
- return out
-}
+ const result = {
+ type: type.toLowerCase(),
+ parameters: new NullObject()
+ }
-/**
- * @param {Headers} headers
- * @param {string} name
- * @param {{ path?: string, domain?: string }|undefined} attributes
- * @returns {void}
- */
-function deleteCookie (headers, name, attributes) {
- webidl.brandCheck(headers, Headers, { strict: false })
+ // parse parameters
+ if (index === -1) {
+ return result
+ }
- const prefix = 'deleteCookie'
- webidl.argumentLengthCheck(arguments, 2, prefix)
+ let key
+ let match
+ let value
- name = webidl.converters.DOMString(name, prefix, 'name')
- attributes = webidl.converters.DeleteCookieAttributes(attributes)
+ paramRE.lastIndex = index
- // Matches behavior of
- // https://github.com/denoland/deno_std/blob/63827b16330b82489a04614027c33b7904e08be5/http/cookie.ts#L278
- setCookie(headers, {
- name,
- value: '',
- expires: new Date(0),
- ...attributes
- })
-}
+ while ((match = paramRE.exec(header))) {
+ if (match.index !== index) {
+ throw new TypeError('invalid parameter format')
+ }
-/**
- * @param {Headers} headers
- * @returns {Cookie[]}
- */
-function getSetCookies (headers) {
- webidl.argumentLengthCheck(arguments, 1, 'getSetCookies')
+ index += match[0].length
+ key = match[1].toLowerCase()
+ value = match[2]
- webidl.brandCheck(headers, Headers, { strict: false })
+ if (value[0] === '"') {
+ // remove quotes and escapes
+ value = value
+ .slice(1, value.length - 1)
- const cookies = headers.getSetCookie()
+ quotedPairRE.test(value) && (value = value.replace(quotedPairRE, '$1'))
+ }
- if (!cookies) {
- return []
+ result.parameters[key] = value
}
- return cookies.map((pair) => parseSetCookie(pair))
-}
+ if (index !== header.length) {
+ throw new TypeError('invalid parameter format')
+ }
-/**
- * @param {Headers} headers
- * @param {Cookie} cookie
- * @returns {void}
- */
-function setCookie (headers, cookie) {
- webidl.argumentLengthCheck(arguments, 2, 'setCookie')
+ return result
+}
- webidl.brandCheck(headers, Headers, { strict: false })
+function safeParse (header) {
+ if (typeof header !== 'string') {
+ return defaultContentType
+ }
- cookie = webidl.converters.Cookie(cookie)
+ let index = header.indexOf(';')
+ const type = index !== -1
+ ? header.slice(0, index).trim()
+ : header.trim()
- const str = stringify(cookie)
+ if (mediaTypeRE.test(type) === false) {
+ return defaultContentType
+ }
- if (str) {
- headers.append('Set-Cookie', str)
+ const result = {
+ type: type.toLowerCase(),
+ parameters: new NullObject()
}
-}
-webidl.converters.DeleteCookieAttributes = webidl.dictionaryConverter([
- {
- converter: webidl.nullableConverter(webidl.converters.DOMString),
- key: 'path',
- defaultValue: () => null
- },
- {
- converter: webidl.nullableConverter(webidl.converters.DOMString),
- key: 'domain',
- defaultValue: () => null
+ // parse parameters
+ if (index === -1) {
+ return result
}
-])
-webidl.converters.Cookie = webidl.dictionaryConverter([
- {
- converter: webidl.converters.DOMString,
- key: 'name'
- },
- {
- converter: webidl.converters.DOMString,
- key: 'value'
- },
- {
- converter: webidl.nullableConverter((value) => {
- if (typeof value === 'number') {
- return webidl.converters['unsigned long long'](value)
- }
+ let key
+ let match
+ let value
- return new Date(value)
- }),
- key: 'expires',
- defaultValue: () => null
- },
- {
- converter: webidl.nullableConverter(webidl.converters['long long']),
- key: 'maxAge',
- defaultValue: () => null
- },
- {
- converter: webidl.nullableConverter(webidl.converters.DOMString),
- key: 'domain',
- defaultValue: () => null
- },
- {
- converter: webidl.nullableConverter(webidl.converters.DOMString),
- key: 'path',
- defaultValue: () => null
- },
- {
- converter: webidl.nullableConverter(webidl.converters.boolean),
- key: 'secure',
- defaultValue: () => null
- },
- {
- converter: webidl.nullableConverter(webidl.converters.boolean),
- key: 'httpOnly',
- defaultValue: () => null
- },
- {
- converter: webidl.converters.USVString,
- key: 'sameSite',
- allowedValues: ['Strict', 'Lax', 'None']
- },
- {
- converter: webidl.sequenceConverter(webidl.converters.DOMString),
- key: 'unparsed',
- defaultValue: () => new Array(0)
+ paramRE.lastIndex = index
+
+ while ((match = paramRE.exec(header))) {
+ if (match.index !== index) {
+ return defaultContentType
+ }
+
+ index += match[0].length
+ key = match[1].toLowerCase()
+ value = match[2]
+
+ if (value[0] === '"') {
+ // remove quotes and escapes
+ value = value
+ .slice(1, value.length - 1)
+
+ quotedPairRE.test(value) && (value = value.replace(quotedPairRE, '$1'))
+ }
+
+ result.parameters[key] = value
}
-])
-module.exports = {
- getCookies,
- deleteCookie,
- getSetCookies,
- setCookie
+ if (index !== header.length) {
+ return defaultContentType
+ }
+
+ return result
}
+__webpack_unused_export__ = { parse, safeParse }
+__webpack_unused_export__ = parse
+module.exports.xL = safeParse
+__webpack_unused_export__ = defaultContentType
-/***/ }),
-/***/ 2802:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ }),
+/***/ 7349:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-const { maxNameValuePairSize, maxAttributeValueSize } = __nccwpck_require__(6820)
-const { isCTLExcludingHtab } = __nccwpck_require__(5613)
-const { collectASequenceOfCodePointsFast } = __nccwpck_require__(980)
-const assert = __nccwpck_require__(4589)
-/**
- * @description Parses the field-value attributes of a set-cookie header string.
- * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4
- * @param {string} header
- * @returns if the header is invalid, null will be returned
- */
-function parseSetCookie (header) {
- // 1. If the set-cookie-string contains a %x00-08 / %x0A-1F / %x7F
- // character (CTL characters excluding HTAB): Abort these steps and
- // ignore the set-cookie-string entirely.
- if (isCTLExcludingHtab(header)) {
- return null
- }
-
- let nameValuePair = ''
- let unparsedAttributes = ''
- let name = ''
- let value = ''
+var identity = __nccwpck_require__(1127);
+var Scalar = __nccwpck_require__(3301);
+var YAMLMap = __nccwpck_require__(4454);
+var YAMLSeq = __nccwpck_require__(2223);
+var resolveBlockMap = __nccwpck_require__(7103);
+var resolveBlockSeq = __nccwpck_require__(334);
+var resolveFlowCollection = __nccwpck_require__(3142);
- // 2. If the set-cookie-string contains a %x3B (";") character:
- if (header.includes(';')) {
- // 1. The name-value-pair string consists of the characters up to,
- // but not including, the first %x3B (";"), and the unparsed-
- // attributes consist of the remainder of the set-cookie-string
- // (including the %x3B (";") in question).
- const position = { position: 0 }
+function resolveCollection(CN, ctx, token, onError, tagName, tag) {
+ const coll = token.type === 'block-map'
+ ? resolveBlockMap.resolveBlockMap(CN, ctx, token, onError, tag)
+ : token.type === 'block-seq'
+ ? resolveBlockSeq.resolveBlockSeq(CN, ctx, token, onError, tag)
+ : resolveFlowCollection.resolveFlowCollection(CN, ctx, token, onError, tag);
+ const Coll = coll.constructor;
+ // If we got a tagName matching the class, or the tag name is '!',
+ // then use the tagName from the node class used to create it.
+ if (tagName === '!' || tagName === Coll.tagName) {
+ coll.tag = Coll.tagName;
+ return coll;
+ }
+ if (tagName)
+ coll.tag = tagName;
+ return coll;
+}
+function composeCollection(CN, ctx, token, props, onError) {
+ const tagToken = props.tag;
+ const tagName = !tagToken
+ ? null
+ : ctx.directives.tagName(tagToken.source, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg));
+ if (token.type === 'block-seq') {
+ const { anchor, newlineAfterProp: nl } = props;
+ const lastProp = anchor && tagToken
+ ? anchor.offset > tagToken.offset
+ ? anchor
+ : tagToken
+ : (anchor ?? tagToken);
+ if (lastProp && (!nl || nl.offset < lastProp.offset)) {
+ const message = 'Missing newline after block sequence props';
+ onError(lastProp, 'MISSING_CHAR', message);
+ }
+ }
+ const expType = token.type === 'block-map'
+ ? 'map'
+ : token.type === 'block-seq'
+ ? 'seq'
+ : token.start.source === '{'
+ ? 'map'
+ : 'seq';
+ // shortcut: check if it's a generic YAMLMap or YAMLSeq
+ // before jumping into the custom tag logic.
+ if (!tagToken ||
+ !tagName ||
+ tagName === '!' ||
+ (tagName === YAMLMap.YAMLMap.tagName && expType === 'map') ||
+ (tagName === YAMLSeq.YAMLSeq.tagName && expType === 'seq')) {
+ return resolveCollection(CN, ctx, token, onError, tagName);
+ }
+ let tag = ctx.schema.tags.find(t => t.tag === tagName && t.collection === expType);
+ if (!tag) {
+ const kt = ctx.schema.knownTags[tagName];
+ if (kt?.collection === expType) {
+ ctx.schema.tags.push(Object.assign({}, kt, { default: false }));
+ tag = kt;
+ }
+ else {
+ if (kt) {
+ onError(tagToken, 'BAD_COLLECTION_TYPE', `${kt.tag} used for ${expType} collection, but expects ${kt.collection ?? 'scalar'}`, true);
+ }
+ else {
+ onError(tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, true);
+ }
+ return resolveCollection(CN, ctx, token, onError, tagName);
+ }
+ }
+ const coll = resolveCollection(CN, ctx, token, onError, tagName, tag);
+ const res = tag.resolve?.(coll, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg), ctx.options) ?? coll;
+ const node = identity.isNode(res)
+ ? res
+ : new Scalar.Scalar(res);
+ node.range = coll.range;
+ node.tag = tagName;
+ if (tag?.format)
+ node.format = tag.format;
+ return node;
+}
- nameValuePair = collectASequenceOfCodePointsFast(';', header, position)
- unparsedAttributes = header.slice(position.position)
- } else {
- // Otherwise:
+exports.composeCollection = composeCollection;
- // 1. The name-value-pair string consists of all the characters
- // contained in the set-cookie-string, and the unparsed-
- // attributes is the empty string.
- nameValuePair = header
- }
- // 3. If the name-value-pair string lacks a %x3D ("=") character, then
- // the name string is empty, and the value string is the value of
- // name-value-pair.
- if (!nameValuePair.includes('=')) {
- value = nameValuePair
- } else {
- // Otherwise, the name string consists of the characters up to, but
- // not including, the first %x3D ("=") character, and the (possibly
- // empty) value string consists of the characters after the first
- // %x3D ("=") character.
- const position = { position: 0 }
- name = collectASequenceOfCodePointsFast(
- '=',
- nameValuePair,
- position
- )
- value = nameValuePair.slice(position.position + 1)
- }
+/***/ }),
- // 4. Remove any leading or trailing WSP characters from the name
- // string and the value string.
- name = name.trim()
- value = value.trim()
+/***/ 3683:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 5. If the sum of the lengths of the name string and the value string
- // is more than 4096 octets, abort these steps and ignore the set-
- // cookie-string entirely.
- if (name.length + value.length > maxNameValuePairSize) {
- return null
- }
- // 6. The cookie-name is the name string, and the cookie-value is the
- // value string.
- return {
- name, value, ...parseUnparsedAttributes(unparsedAttributes)
- }
-}
-/**
- * Parses the remaining attributes of a set-cookie header
- * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4
- * @param {string} unparsedAttributes
- * @param {[Object.]={}} cookieAttributeList
- */
-function parseUnparsedAttributes (unparsedAttributes, cookieAttributeList = {}) {
- // 1. If the unparsed-attributes string is empty, skip the rest of
- // these steps.
- if (unparsedAttributes.length === 0) {
- return cookieAttributeList
- }
+var Document = __nccwpck_require__(3021);
+var composeNode = __nccwpck_require__(5937);
+var resolveEnd = __nccwpck_require__(7788);
+var resolveProps = __nccwpck_require__(4631);
- // 2. Discard the first character of the unparsed-attributes (which
- // will be a %x3B (";") character).
- assert(unparsedAttributes[0] === ';')
- unparsedAttributes = unparsedAttributes.slice(1)
+function composeDoc(options, directives, { offset, start, value, end }, onError) {
+ const opts = Object.assign({ _directives: directives }, options);
+ const doc = new Document.Document(undefined, opts);
+ const ctx = {
+ atKey: false,
+ atRoot: true,
+ directives: doc.directives,
+ options: doc.options,
+ schema: doc.schema
+ };
+ const props = resolveProps.resolveProps(start, {
+ indicator: 'doc-start',
+ next: value ?? end?.[0],
+ offset,
+ onError,
+ parentIndent: 0,
+ startOnNewline: true
+ });
+ if (props.found) {
+ doc.directives.docStart = true;
+ if (value &&
+ (value.type === 'block-map' || value.type === 'block-seq') &&
+ !props.hasNewline)
+ onError(props.end, 'MISSING_CHAR', 'Block collection cannot start on same line with directives-end marker');
+ }
+ // @ts-expect-error If Contents is set, let's trust the user
+ doc.contents = value
+ ? composeNode.composeNode(ctx, value, props, onError)
+ : composeNode.composeEmptyNode(ctx, props.end, start, null, props, onError);
+ const contentEnd = doc.contents.range[2];
+ const re = resolveEnd.resolveEnd(end, contentEnd, false, onError);
+ if (re.comment)
+ doc.comment = re.comment;
+ doc.range = [offset, contentEnd, re.offset];
+ return doc;
+}
- let cookieAv = ''
+exports.composeDoc = composeDoc;
- // 3. If the remaining unparsed-attributes contains a %x3B (";")
- // character:
- if (unparsedAttributes.includes(';')) {
- // 1. Consume the characters of the unparsed-attributes up to, but
- // not including, the first %x3B (";") character.
- cookieAv = collectASequenceOfCodePointsFast(
- ';',
- unparsedAttributes,
- { position: 0 }
- )
- unparsedAttributes = unparsedAttributes.slice(cookieAv.length)
- } else {
- // Otherwise:
- // 1. Consume the remainder of the unparsed-attributes.
- cookieAv = unparsedAttributes
- unparsedAttributes = ''
- }
+/***/ }),
- // Let the cookie-av string be the characters consumed in this step.
+/***/ 5937:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- let attributeName = ''
- let attributeValue = ''
- // 4. If the cookie-av string contains a %x3D ("=") character:
- if (cookieAv.includes('=')) {
- // 1. The (possibly empty) attribute-name string consists of the
- // characters up to, but not including, the first %x3D ("=")
- // character, and the (possibly empty) attribute-value string
- // consists of the characters after the first %x3D ("=")
- // character.
- const position = { position: 0 }
- attributeName = collectASequenceOfCodePointsFast(
- '=',
- cookieAv,
- position
- )
- attributeValue = cookieAv.slice(position.position + 1)
- } else {
- // Otherwise:
+var Alias = __nccwpck_require__(4065);
+var identity = __nccwpck_require__(1127);
+var composeCollection = __nccwpck_require__(7349);
+var composeScalar = __nccwpck_require__(5413);
+var resolveEnd = __nccwpck_require__(7788);
+var utilEmptyScalarPosition = __nccwpck_require__(2599);
- // 1. The attribute-name string consists of the entire cookie-av
- // string, and the attribute-value string is empty.
- attributeName = cookieAv
- }
+const CN = { composeNode, composeEmptyNode };
+function composeNode(ctx, token, props, onError) {
+ const atKey = ctx.atKey;
+ const { spaceBefore, comment, anchor, tag } = props;
+ let node;
+ let isSrcToken = true;
+ switch (token.type) {
+ case 'alias':
+ node = composeAlias(ctx, token, onError);
+ if (anchor || tag)
+ onError(token, 'ALIAS_PROPS', 'An alias node must not specify any properties');
+ break;
+ case 'scalar':
+ case 'single-quoted-scalar':
+ case 'double-quoted-scalar':
+ case 'block-scalar':
+ node = composeScalar.composeScalar(ctx, token, tag, onError);
+ if (anchor)
+ node.anchor = anchor.source.substring(1);
+ break;
+ case 'block-map':
+ case 'block-seq':
+ case 'flow-collection':
+ try {
+ node = composeCollection.composeCollection(CN, ctx, token, props, onError);
+ if (anchor)
+ node.anchor = anchor.source.substring(1);
+ }
+ catch (error) {
+ // Almost certainly here due to a stack overflow
+ const message = error instanceof Error ? error.message : String(error);
+ onError(token, 'RESOURCE_EXHAUSTION', message);
+ }
+ break;
+ default: {
+ const message = token.type === 'error'
+ ? token.message
+ : `Unsupported token (type: ${token.type})`;
+ onError(token, 'UNEXPECTED_TOKEN', message);
+ isSrcToken = false;
+ }
+ }
+ node ?? (node = composeEmptyNode(ctx, token.offset, undefined, null, props, onError));
+ if (anchor && node.anchor === '')
+ onError(anchor, 'BAD_ALIAS', 'Anchor cannot be an empty string');
+ if (atKey &&
+ ctx.options.stringKeys &&
+ (!identity.isScalar(node) ||
+ typeof node.value !== 'string' ||
+ (node.tag && node.tag !== 'tag:yaml.org,2002:str'))) {
+ const msg = 'With stringKeys, all keys must be strings';
+ onError(tag ?? token, 'NON_STRING_KEY', msg);
+ }
+ if (spaceBefore)
+ node.spaceBefore = true;
+ if (comment) {
+ if (token.type === 'scalar' && token.source === '')
+ node.comment = comment;
+ else
+ node.commentBefore = comment;
+ }
+ // @ts-expect-error Type checking misses meaning of isSrcToken
+ if (ctx.options.keepSourceTokens && isSrcToken)
+ node.srcToken = token;
+ return node;
+}
+function composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError) {
+ const token = {
+ type: 'scalar',
+ offset: utilEmptyScalarPosition.emptyScalarPosition(offset, before, pos),
+ indent: -1,
+ source: ''
+ };
+ const node = composeScalar.composeScalar(ctx, token, tag, onError);
+ if (anchor) {
+ node.anchor = anchor.source.substring(1);
+ if (node.anchor === '')
+ onError(anchor, 'BAD_ALIAS', 'Anchor cannot be an empty string');
+ }
+ if (spaceBefore)
+ node.spaceBefore = true;
+ if (comment) {
+ node.comment = comment;
+ node.range[2] = end;
+ }
+ return node;
+}
+function composeAlias({ options }, { offset, source, end }, onError) {
+ const alias = new Alias.Alias(source.substring(1));
+ if (alias.source === '')
+ onError(offset, 'BAD_ALIAS', 'Alias cannot be an empty string');
+ if (alias.source.endsWith(':'))
+ onError(offset + source.length - 1, 'BAD_ALIAS', 'Alias ending in : is ambiguous', true);
+ const valueEnd = offset + source.length;
+ const re = resolveEnd.resolveEnd(end, valueEnd, options.strict, onError);
+ alias.range = [offset, valueEnd, re.offset];
+ if (re.comment)
+ alias.comment = re.comment;
+ return alias;
+}
- // 5. Remove any leading or trailing WSP characters from the attribute-
- // name string and the attribute-value string.
- attributeName = attributeName.trim()
- attributeValue = attributeValue.trim()
+exports.composeEmptyNode = composeEmptyNode;
+exports.composeNode = composeNode;
- // 6. If the attribute-value is longer than 1024 octets, ignore the
- // cookie-av string and return to Step 1 of this algorithm.
- if (attributeValue.length > maxAttributeValueSize) {
- return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
- }
- // 7. Process the attribute-name and attribute-value according to the
- // requirements in the following subsections. (Notice that
- // attributes with unrecognized attribute-names are ignored.)
- const attributeNameLowercase = attributeName.toLowerCase()
+/***/ }),
- // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.1
- // If the attribute-name case-insensitively matches the string
- // "Expires", the user agent MUST process the cookie-av as follows.
- if (attributeNameLowercase === 'expires') {
- // 1. Let the expiry-time be the result of parsing the attribute-value
- // as cookie-date (see Section 5.1.1).
- const expiryTime = new Date(attributeValue)
+/***/ 5413:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 2. If the attribute-value failed to parse as a cookie date, ignore
- // the cookie-av.
- cookieAttributeList.expires = expiryTime
- } else if (attributeNameLowercase === 'max-age') {
- // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.2
- // If the attribute-name case-insensitively matches the string "Max-
- // Age", the user agent MUST process the cookie-av as follows.
- // 1. If the first character of the attribute-value is not a DIGIT or a
- // "-" character, ignore the cookie-av.
- const charCode = attributeValue.charCodeAt(0)
+var identity = __nccwpck_require__(1127);
+var Scalar = __nccwpck_require__(3301);
+var resolveBlockScalar = __nccwpck_require__(8913);
+var resolveFlowScalar = __nccwpck_require__(6842);
- if ((charCode < 48 || charCode > 57) && attributeValue[0] !== '-') {
- return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
+function composeScalar(ctx, token, tagToken, onError) {
+ const { value, type, comment, range } = token.type === 'block-scalar'
+ ? resolveBlockScalar.resolveBlockScalar(ctx, token, onError)
+ : resolveFlowScalar.resolveFlowScalar(token, ctx.options.strict, onError);
+ const tagName = tagToken
+ ? ctx.directives.tagName(tagToken.source, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg))
+ : null;
+ let tag;
+ if (ctx.options.stringKeys && ctx.atKey) {
+ tag = ctx.schema[identity.SCALAR];
}
-
- // 2. If the remainder of attribute-value contains a non-DIGIT
- // character, ignore the cookie-av.
- if (!/^\d+$/.test(attributeValue)) {
- return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
+ else if (tagName)
+ tag = findScalarTagByName(ctx.schema, value, tagName, tagToken, onError);
+ else if (token.type === 'scalar')
+ tag = findScalarTagByTest(ctx, value, token, onError);
+ else
+ tag = ctx.schema[identity.SCALAR];
+ let scalar;
+ try {
+ const res = tag.resolve(value, msg => onError(tagToken ?? token, 'TAG_RESOLVE_FAILED', msg), ctx.options);
+ scalar = identity.isScalar(res) ? res : new Scalar.Scalar(res);
+ }
+ catch (error) {
+ const msg = error instanceof Error ? error.message : String(error);
+ onError(tagToken ?? token, 'TAG_RESOLVE_FAILED', msg);
+ scalar = new Scalar.Scalar(value);
+ }
+ scalar.range = range;
+ scalar.source = value;
+ if (type)
+ scalar.type = type;
+ if (tagName)
+ scalar.tag = tagName;
+ if (tag.format)
+ scalar.format = tag.format;
+ if (comment)
+ scalar.comment = comment;
+ return scalar;
+}
+function findScalarTagByName(schema, value, tagName, tagToken, onError) {
+ if (tagName === '!')
+ return schema[identity.SCALAR]; // non-specific tag
+ const matchWithTest = [];
+ for (const tag of schema.tags) {
+ if (!tag.collection && tag.tag === tagName) {
+ if (tag.default && tag.test)
+ matchWithTest.push(tag);
+ else
+ return tag;
+ }
+ }
+ for (const tag of matchWithTest)
+ if (tag.test?.test(value))
+ return tag;
+ const kt = schema.knownTags[tagName];
+ if (kt && !kt.collection) {
+ // Ensure that the known tag is available for stringifying,
+ // but does not get used by default.
+ schema.tags.push(Object.assign({}, kt, { default: false, test: undefined }));
+ return kt;
+ }
+ onError(tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, tagName !== 'tag:yaml.org,2002:str');
+ return schema[identity.SCALAR];
+}
+function findScalarTagByTest({ atKey, directives, schema }, value, token, onError) {
+ const tag = schema.tags.find(tag => (tag.default === true || (atKey && tag.default === 'key')) &&
+ tag.test?.test(value)) || schema[identity.SCALAR];
+ if (schema.compat) {
+ const compat = schema.compat.find(tag => tag.default && tag.test?.test(value)) ??
+ schema[identity.SCALAR];
+ if (tag.tag !== compat.tag) {
+ const ts = directives.tagString(tag.tag);
+ const cs = directives.tagString(compat.tag);
+ const msg = `Value may be parsed as either ${ts} or ${cs}`;
+ onError(token, 'TAG_RESOLVE_FAILED', msg, true);
+ }
}
+ return tag;
+}
- // 3. Let delta-seconds be the attribute-value converted to an integer.
- const deltaSeconds = Number(attributeValue)
+exports.composeScalar = composeScalar;
- // 4. Let cookie-age-limit be the maximum age of the cookie (which
- // SHOULD be 400 days or less, see Section 4.1.2.2).
- // 5. Set delta-seconds to the smaller of its present value and cookie-
- // age-limit.
- // deltaSeconds = Math.min(deltaSeconds * 1000, maxExpiresMs)
+/***/ }),
- // 6. If delta-seconds is less than or equal to zero (0), let expiry-
- // time be the earliest representable date and time. Otherwise, let
- // the expiry-time be the current date and time plus delta-seconds
- // seconds.
- // const expiryTime = deltaSeconds <= 0 ? Date.now() : Date.now() + deltaSeconds
+/***/ 9984:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 7. Append an attribute to the cookie-attribute-list with an
- // attribute-name of Max-Age and an attribute-value of expiry-time.
- cookieAttributeList.maxAge = deltaSeconds
- } else if (attributeNameLowercase === 'domain') {
- // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.3
- // If the attribute-name case-insensitively matches the string "Domain",
- // the user agent MUST process the cookie-av as follows.
- // 1. Let cookie-domain be the attribute-value.
- let cookieDomain = attributeValue
- // 2. If cookie-domain starts with %x2E ("."), let cookie-domain be
- // cookie-domain without its leading %x2E (".").
- if (cookieDomain[0] === '.') {
- cookieDomain = cookieDomain.slice(1)
- }
-
- // 3. Convert the cookie-domain to lower case.
- cookieDomain = cookieDomain.toLowerCase()
-
- // 4. Append an attribute to the cookie-attribute-list with an
- // attribute-name of Domain and an attribute-value of cookie-domain.
- cookieAttributeList.domain = cookieDomain
- } else if (attributeNameLowercase === 'path') {
- // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.4
- // If the attribute-name case-insensitively matches the string "Path",
- // the user agent MUST process the cookie-av as follows.
-
- // 1. If the attribute-value is empty or if the first character of the
- // attribute-value is not %x2F ("/"):
- let cookiePath = ''
- if (attributeValue.length === 0 || attributeValue[0] !== '/') {
- // 1. Let cookie-path be the default-path.
- cookiePath = '/'
- } else {
- // Otherwise:
+var node_process = __nccwpck_require__(932);
+var directives = __nccwpck_require__(1342);
+var Document = __nccwpck_require__(3021);
+var errors = __nccwpck_require__(1464);
+var identity = __nccwpck_require__(1127);
+var composeDoc = __nccwpck_require__(3683);
+var resolveEnd = __nccwpck_require__(7788);
- // 1. Let cookie-path be the attribute-value.
- cookiePath = attributeValue
+function getErrorPos(src) {
+ if (typeof src === 'number')
+ return [src, src + 1];
+ if (Array.isArray(src))
+ return src.length === 2 ? src : [src[0], src[1]];
+ const { offset, source } = src;
+ return [offset, offset + (typeof source === 'string' ? source.length : 1)];
+}
+function parsePrelude(prelude) {
+ let comment = '';
+ let atComment = false;
+ let afterEmptyLine = false;
+ for (let i = 0; i < prelude.length; ++i) {
+ const source = prelude[i];
+ switch (source[0]) {
+ case '#':
+ comment +=
+ (comment === '' ? '' : afterEmptyLine ? '\n\n' : '\n') +
+ (source.substring(1) || ' ');
+ atComment = true;
+ afterEmptyLine = false;
+ break;
+ case '%':
+ if (prelude[i + 1]?.[0] !== '#')
+ i += 1;
+ atComment = false;
+ break;
+ default:
+ // This may be wrong after doc-end, but in that case it doesn't matter
+ if (!atComment)
+ afterEmptyLine = true;
+ atComment = false;
+ }
}
-
- // 2. Append an attribute to the cookie-attribute-list with an
- // attribute-name of Path and an attribute-value of cookie-path.
- cookieAttributeList.path = cookiePath
- } else if (attributeNameLowercase === 'secure') {
- // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.5
- // If the attribute-name case-insensitively matches the string "Secure",
- // the user agent MUST append an attribute to the cookie-attribute-list
- // with an attribute-name of Secure and an empty attribute-value.
-
- cookieAttributeList.secure = true
- } else if (attributeNameLowercase === 'httponly') {
- // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.6
- // If the attribute-name case-insensitively matches the string
- // "HttpOnly", the user agent MUST append an attribute to the cookie-
- // attribute-list with an attribute-name of HttpOnly and an empty
- // attribute-value.
-
- cookieAttributeList.httpOnly = true
- } else if (attributeNameLowercase === 'samesite') {
- // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.7
- // If the attribute-name case-insensitively matches the string
- // "SameSite", the user agent MUST process the cookie-av as follows:
-
- // 1. Let enforcement be "Default".
- let enforcement = 'Default'
-
- const attributeValueLowercase = attributeValue.toLowerCase()
- // 2. If cookie-av's attribute-value is a case-insensitive match for
- // "None", set enforcement to "None".
- if (attributeValueLowercase.includes('none')) {
- enforcement = 'None'
+ return { comment, afterEmptyLine };
+}
+/**
+ * Compose a stream of CST nodes into a stream of YAML Documents.
+ *
+ * ```ts
+ * import { Composer, Parser } from 'yaml'
+ *
+ * const src: string = ...
+ * const tokens = new Parser().parse(src)
+ * const docs = new Composer().compose(tokens)
+ * ```
+ */
+class Composer {
+ constructor(options = {}) {
+ this.doc = null;
+ this.atDirectives = false;
+ this.prelude = [];
+ this.errors = [];
+ this.warnings = [];
+ this.onError = (source, code, message, warning) => {
+ const pos = getErrorPos(source);
+ if (warning)
+ this.warnings.push(new errors.YAMLWarning(pos, code, message));
+ else
+ this.errors.push(new errors.YAMLParseError(pos, code, message));
+ };
+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
+ this.directives = new directives.Directives({ version: options.version || '1.2' });
+ this.options = options;
}
-
- // 3. If cookie-av's attribute-value is a case-insensitive match for
- // "Strict", set enforcement to "Strict".
- if (attributeValueLowercase.includes('strict')) {
- enforcement = 'Strict'
+ decorate(doc, afterDoc) {
+ const { comment, afterEmptyLine } = parsePrelude(this.prelude);
+ //console.log({ dc: doc.comment, prelude, comment })
+ if (comment) {
+ const dc = doc.contents;
+ if (afterDoc) {
+ doc.comment = doc.comment ? `${doc.comment}\n${comment}` : comment;
+ }
+ else if (afterEmptyLine || doc.directives.docStart || !dc) {
+ doc.commentBefore = comment;
+ }
+ else if (identity.isCollection(dc) && !dc.flow && dc.items.length > 0) {
+ let it = dc.items[0];
+ if (identity.isPair(it))
+ it = it.key;
+ const cb = it.commentBefore;
+ it.commentBefore = cb ? `${comment}\n${cb}` : comment;
+ }
+ else {
+ const cb = dc.commentBefore;
+ dc.commentBefore = cb ? `${comment}\n${cb}` : comment;
+ }
+ }
+ if (afterDoc) {
+ for (let i = 0; i < this.errors.length; ++i)
+ doc.errors.push(this.errors[i]);
+ for (let i = 0; i < this.warnings.length; ++i)
+ doc.warnings.push(this.warnings[i]);
+ }
+ else {
+ doc.errors = this.errors;
+ doc.warnings = this.warnings;
+ }
+ this.prelude = [];
+ this.errors = [];
+ this.warnings = [];
}
-
- // 4. If cookie-av's attribute-value is a case-insensitive match for
- // "Lax", set enforcement to "Lax".
- if (attributeValueLowercase.includes('lax')) {
- enforcement = 'Lax'
+ /**
+ * Current stream status information.
+ *
+ * Mostly useful at the end of input for an empty stream.
+ */
+ streamInfo() {
+ return {
+ comment: parsePrelude(this.prelude).comment,
+ directives: this.directives,
+ errors: this.errors,
+ warnings: this.warnings
+ };
+ }
+ /**
+ * Compose tokens into documents.
+ *
+ * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.
+ * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.
+ */
+ *compose(tokens, forceDoc = false, endOffset = -1) {
+ for (const token of tokens)
+ yield* this.next(token);
+ yield* this.end(forceDoc, endOffset);
+ }
+ /** Advance the composer by one CST token. */
+ *next(token) {
+ if (node_process.env.LOG_STREAM)
+ console.dir(token, { depth: null });
+ switch (token.type) {
+ case 'directive':
+ this.directives.add(token.source, (offset, message, warning) => {
+ const pos = getErrorPos(token);
+ pos[0] += offset;
+ this.onError(pos, 'BAD_DIRECTIVE', message, warning);
+ });
+ this.prelude.push(token.source);
+ this.atDirectives = true;
+ break;
+ case 'document': {
+ const doc = composeDoc.composeDoc(this.options, this.directives, token, this.onError);
+ if (this.atDirectives && !doc.directives.docStart)
+ this.onError(token, 'MISSING_CHAR', 'Missing directives-end/doc-start indicator line');
+ this.decorate(doc, false);
+ if (this.doc)
+ yield this.doc;
+ this.doc = doc;
+ this.atDirectives = false;
+ break;
+ }
+ case 'byte-order-mark':
+ case 'space':
+ break;
+ case 'comment':
+ case 'newline':
+ this.prelude.push(token.source);
+ break;
+ case 'error': {
+ const msg = token.source
+ ? `${token.message}: ${JSON.stringify(token.source)}`
+ : token.message;
+ const error = new errors.YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', msg);
+ if (this.atDirectives || !this.doc)
+ this.errors.push(error);
+ else
+ this.doc.errors.push(error);
+ break;
+ }
+ case 'doc-end': {
+ if (!this.doc) {
+ const msg = 'Unexpected doc-end without preceding document';
+ this.errors.push(new errors.YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', msg));
+ break;
+ }
+ this.doc.directives.docEnd = true;
+ const end = resolveEnd.resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError);
+ this.decorate(this.doc, true);
+ if (end.comment) {
+ const dc = this.doc.comment;
+ this.doc.comment = dc ? `${dc}\n${end.comment}` : end.comment;
+ }
+ this.doc.range[2] = end.offset;
+ break;
+ }
+ default:
+ this.errors.push(new errors.YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', `Unsupported token ${token.type}`));
+ }
+ }
+ /**
+ * Call at end of input to yield any remaining document.
+ *
+ * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.
+ * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.
+ */
+ *end(forceDoc = false, endOffset = -1) {
+ if (this.doc) {
+ this.decorate(this.doc, true);
+ yield this.doc;
+ this.doc = null;
+ }
+ else if (forceDoc) {
+ const opts = Object.assign({ _directives: this.directives }, this.options);
+ const doc = new Document.Document(undefined, opts);
+ if (this.atDirectives)
+ this.onError(endOffset, 'MISSING_CHAR', 'Missing directives-end indicator line');
+ doc.range = [0, endOffset, endOffset];
+ this.decorate(doc, false);
+ yield doc;
+ }
}
-
- // 5. Append an attribute to the cookie-attribute-list with an
- // attribute-name of "SameSite" and an attribute-value of
- // enforcement.
- cookieAttributeList.sameSite = enforcement
- } else {
- cookieAttributeList.unparsed ??= []
-
- cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`)
- }
-
- // 8. Return to Step 1 of this algorithm.
- return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
}
-module.exports = {
- parseSetCookie,
- parseUnparsedAttributes
-}
+exports.Composer = Composer;
/***/ }),
-/***/ 5613:
-/***/ ((module) => {
+/***/ 7103:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-/**
- * @param {string} value
- * @returns {boolean}
- */
-function isCTLExcludingHtab (value) {
- for (let i = 0; i < value.length; ++i) {
- const code = value.charCodeAt(i)
+var Pair = __nccwpck_require__(7165);
+var YAMLMap = __nccwpck_require__(4454);
+var resolveProps = __nccwpck_require__(4631);
+var utilContainsNewline = __nccwpck_require__(9499);
+var utilFlowIndentCheck = __nccwpck_require__(4051);
+var utilMapIncludes = __nccwpck_require__(1187);
- if (
- (code >= 0x00 && code <= 0x08) ||
- (code >= 0x0A && code <= 0x1F) ||
- code === 0x7F
- ) {
- return true
+const startColMsg = 'All mapping items must start at the same column';
+function resolveBlockMap({ composeNode, composeEmptyNode }, ctx, bm, onError, tag) {
+ const NodeClass = tag?.nodeClass ?? YAMLMap.YAMLMap;
+ const map = new NodeClass(ctx.schema);
+ if (ctx.atRoot)
+ ctx.atRoot = false;
+ let offset = bm.offset;
+ let commentEnd = null;
+ for (const collItem of bm.items) {
+ const { start, key, sep, value } = collItem;
+ // key properties
+ const keyProps = resolveProps.resolveProps(start, {
+ indicator: 'explicit-key-ind',
+ next: key ?? sep?.[0],
+ offset,
+ onError,
+ parentIndent: bm.indent,
+ startOnNewline: true
+ });
+ const implicitKey = !keyProps.found;
+ if (implicitKey) {
+ if (key) {
+ if (key.type === 'block-seq')
+ onError(offset, 'BLOCK_AS_IMPLICIT_KEY', 'A block sequence may not be used as an implicit map key');
+ else if ('indent' in key && key.indent !== bm.indent)
+ onError(offset, 'BAD_INDENT', startColMsg);
+ }
+ if (!keyProps.anchor && !keyProps.tag && !sep) {
+ commentEnd = keyProps.end;
+ if (keyProps.comment) {
+ if (map.comment)
+ map.comment += '\n' + keyProps.comment;
+ else
+ map.comment = keyProps.comment;
+ }
+ continue;
+ }
+ if (keyProps.newlineAfterProp || utilContainsNewline.containsNewline(key)) {
+ onError(key ?? start[start.length - 1], 'MULTILINE_IMPLICIT_KEY', 'Implicit keys need to be on a single line');
+ }
+ }
+ else if (keyProps.found?.indent !== bm.indent) {
+ onError(offset, 'BAD_INDENT', startColMsg);
+ }
+ // key value
+ ctx.atKey = true;
+ const keyStart = keyProps.end;
+ const keyNode = key
+ ? composeNode(ctx, key, keyProps, onError)
+ : composeEmptyNode(ctx, keyStart, start, null, keyProps, onError);
+ if (ctx.schema.compat)
+ utilFlowIndentCheck.flowIndentCheck(bm.indent, key, onError);
+ ctx.atKey = false;
+ if (utilMapIncludes.mapIncludes(ctx, map.items, keyNode))
+ onError(keyStart, 'DUPLICATE_KEY', 'Map keys must be unique');
+ // value properties
+ const valueProps = resolveProps.resolveProps(sep ?? [], {
+ indicator: 'map-value-ind',
+ next: value,
+ offset: keyNode.range[2],
+ onError,
+ parentIndent: bm.indent,
+ startOnNewline: !key || key.type === 'block-scalar'
+ });
+ offset = valueProps.end;
+ if (valueProps.found) {
+ if (implicitKey) {
+ if (value?.type === 'block-map' && !valueProps.hasNewline)
+ onError(offset, 'BLOCK_AS_IMPLICIT_KEY', 'Nested mappings are not allowed in compact mappings');
+ if (ctx.options.strict &&
+ keyProps.start < valueProps.found.offset - 1024)
+ onError(keyNode.range, 'KEY_OVER_1024_CHARS', 'The : indicator must be at most 1024 chars after the start of an implicit block mapping key');
+ }
+ // value value
+ const valueNode = value
+ ? composeNode(ctx, value, valueProps, onError)
+ : composeEmptyNode(ctx, offset, sep, null, valueProps, onError);
+ if (ctx.schema.compat)
+ utilFlowIndentCheck.flowIndentCheck(bm.indent, value, onError);
+ offset = valueNode.range[2];
+ const pair = new Pair.Pair(keyNode, valueNode);
+ if (ctx.options.keepSourceTokens)
+ pair.srcToken = collItem;
+ map.items.push(pair);
+ }
+ else {
+ // key with no value
+ if (implicitKey)
+ onError(keyNode.range, 'MISSING_CHAR', 'Implicit map keys need to be followed by map values');
+ if (valueProps.comment) {
+ if (keyNode.comment)
+ keyNode.comment += '\n' + valueProps.comment;
+ else
+ keyNode.comment = valueProps.comment;
+ }
+ const pair = new Pair.Pair(keyNode);
+ if (ctx.options.keepSourceTokens)
+ pair.srcToken = collItem;
+ map.items.push(pair);
+ }
}
- }
- return false
+ if (commentEnd && commentEnd < offset)
+ onError(commentEnd, 'IMPOSSIBLE', 'Map comment with trailing content');
+ map.range = [bm.offset, offset, commentEnd ?? offset];
+ return map;
}
-/**
- CHAR =
- token = 1*
- separators = "(" | ")" | "<" | ">" | "@"
- | "," | ";" | ":" | "\" | <">
- | "/" | "[" | "]" | "?" | "="
- | "{" | "}" | SP | HT
- * @param {string} name
- */
-function validateCookieName (name) {
- for (let i = 0; i < name.length; ++i) {
- const code = name.charCodeAt(i)
+exports.resolveBlockMap = resolveBlockMap;
- if (
- code < 0x21 || // exclude CTLs (0-31), SP and HT
- code > 0x7E || // exclude non-ascii and DEL
- code === 0x22 || // "
- code === 0x28 || // (
- code === 0x29 || // )
- code === 0x3C || // <
- code === 0x3E || // >
- code === 0x40 || // @
- code === 0x2C || // ,
- code === 0x3B || // ;
- code === 0x3A || // :
- code === 0x5C || // \
- code === 0x2F || // /
- code === 0x5B || // [
- code === 0x5D || // ]
- code === 0x3F || // ?
- code === 0x3D || // =
- code === 0x7B || // {
- code === 0x7D // }
- ) {
- throw new Error('Invalid cookie name')
- }
- }
-}
-/**
- cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )
- cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E
- ; US-ASCII characters excluding CTLs,
- ; whitespace DQUOTE, comma, semicolon,
- ; and backslash
- * @param {string} value
- */
-function validateCookieValue (value) {
- let len = value.length
- let i = 0
+/***/ }),
- // if the value is wrapped in DQUOTE
- if (value[0] === '"') {
- if (len === 1 || value[len - 1] !== '"') {
- throw new Error('Invalid cookie value')
- }
- --len
- ++i
- }
+/***/ 8913:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- while (i < len) {
- const code = value.charCodeAt(i++)
- if (
- code < 0x21 || // exclude CTLs (0-31)
- code > 0x7E || // non-ascii and DEL (127)
- code === 0x22 || // "
- code === 0x2C || // ,
- code === 0x3B || // ;
- code === 0x5C // \
- ) {
- throw new Error('Invalid cookie value')
- }
- }
-}
-/**
- * path-value =
- * @param {string} path
- */
-function validateCookiePath (path) {
- for (let i = 0; i < path.length; ++i) {
- const code = path.charCodeAt(i)
+var Scalar = __nccwpck_require__(3301);
- if (
- code < 0x20 || // exclude CTLs (0-31)
- code === 0x7F || // DEL
- code === 0x3B // ;
- ) {
- throw new Error('Invalid cookie path')
- }
- }
-}
-
-/**
- * I have no idea why these values aren't allowed to be honest,
- * but Deno tests these. - Khafra
- * @param {string} domain
- */
-function validateCookieDomain (domain) {
- if (
- domain.startsWith('-') ||
- domain.endsWith('.') ||
- domain.endsWith('-')
- ) {
- throw new Error('Invalid cookie domain')
- }
+function resolveBlockScalar(ctx, scalar, onError) {
+ const start = scalar.offset;
+ const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError);
+ if (!header)
+ return { value: '', type: null, comment: '', range: [start, start, start] };
+ const type = header.mode === '>' ? Scalar.Scalar.BLOCK_FOLDED : Scalar.Scalar.BLOCK_LITERAL;
+ const lines = scalar.source ? splitLines(scalar.source) : [];
+ // determine the end of content & start of chomping
+ let chompStart = lines.length;
+ for (let i = lines.length - 1; i >= 0; --i) {
+ const content = lines[i][1];
+ if (content === '' || content === '\r')
+ chompStart = i;
+ else
+ break;
+ }
+ // shortcut for empty contents
+ if (chompStart === 0) {
+ const value = header.chomp === '+' && lines.length > 0
+ ? '\n'.repeat(Math.max(1, lines.length - 1))
+ : '';
+ let end = start + header.length;
+ if (scalar.source)
+ end += scalar.source.length;
+ return { value, type, comment: header.comment, range: [start, end, end] };
+ }
+ // find the indentation level to trim from start
+ let trimIndent = scalar.indent + header.indent;
+ let offset = scalar.offset + header.length;
+ let contentStart = 0;
+ for (let i = 0; i < chompStart; ++i) {
+ const [indent, content] = lines[i];
+ if (content === '' || content === '\r') {
+ if (header.indent === 0 && indent.length > trimIndent)
+ trimIndent = indent.length;
+ }
+ else {
+ if (indent.length < trimIndent) {
+ const message = 'Block scalars with more-indented leading empty lines must use an explicit indentation indicator';
+ onError(offset + indent.length, 'MISSING_CHAR', message);
+ }
+ if (header.indent === 0)
+ trimIndent = indent.length;
+ contentStart = i;
+ if (trimIndent === 0 && !ctx.atRoot) {
+ const message = 'Block scalar values in collections must be indented';
+ onError(offset, 'BAD_INDENT', message);
+ }
+ break;
+ }
+ offset += indent.length + content.length + 1;
+ }
+ // include trailing more-indented empty lines in content
+ for (let i = lines.length - 1; i >= chompStart; --i) {
+ if (lines[i][0].length > trimIndent)
+ chompStart = i + 1;
+ }
+ let value = '';
+ let sep = '';
+ let prevMoreIndented = false;
+ // leading whitespace is kept intact
+ for (let i = 0; i < contentStart; ++i)
+ value += lines[i][0].slice(trimIndent) + '\n';
+ for (let i = contentStart; i < chompStart; ++i) {
+ let [indent, content] = lines[i];
+ offset += indent.length + content.length + 1;
+ const crlf = content[content.length - 1] === '\r';
+ if (crlf)
+ content = content.slice(0, -1);
+ /* istanbul ignore if already caught in lexer */
+ if (content && indent.length < trimIndent) {
+ const src = header.indent
+ ? 'explicit indentation indicator'
+ : 'first line';
+ const message = `Block scalar lines must not be less indented than their ${src}`;
+ onError(offset - content.length - (crlf ? 2 : 1), 'BAD_INDENT', message);
+ indent = '';
+ }
+ if (type === Scalar.Scalar.BLOCK_LITERAL) {
+ value += sep + indent.slice(trimIndent) + content;
+ sep = '\n';
+ }
+ else if (indent.length > trimIndent || content[0] === '\t') {
+ // more-indented content within a folded block
+ if (sep === ' ')
+ sep = '\n';
+ else if (!prevMoreIndented && sep === '\n')
+ sep = '\n\n';
+ value += sep + indent.slice(trimIndent) + content;
+ sep = '\n';
+ prevMoreIndented = true;
+ }
+ else if (content === '') {
+ // empty line
+ if (sep === '\n')
+ value += '\n';
+ else
+ sep = '\n';
+ }
+ else {
+ value += sep + content;
+ sep = ' ';
+ prevMoreIndented = false;
+ }
+ }
+ switch (header.chomp) {
+ case '-':
+ break;
+ case '+':
+ for (let i = chompStart; i < lines.length; ++i)
+ value += '\n' + lines[i][0].slice(trimIndent);
+ if (value[value.length - 1] !== '\n')
+ value += '\n';
+ break;
+ default:
+ value += '\n';
+ }
+ const end = start + header.length + scalar.source.length;
+ return { value, type, comment: header.comment, range: [start, end, end] };
}
-
-const IMFDays = [
- 'Sun', 'Mon', 'Tue', 'Wed',
- 'Thu', 'Fri', 'Sat'
-]
-
-const IMFMonths = [
- 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
- 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
-]
-
-const IMFPaddedNumbers = Array(61).fill(0).map((_, i) => i.toString().padStart(2, '0'))
-
-/**
- * @see https://www.rfc-editor.org/rfc/rfc7231#section-7.1.1.1
- * @param {number|Date} date
- IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
- ; fixed length/zone/capitalization subset of the format
- ; see Section 3.3 of [RFC5322]
-
- day-name = %x4D.6F.6E ; "Mon", case-sensitive
- / %x54.75.65 ; "Tue", case-sensitive
- / %x57.65.64 ; "Wed", case-sensitive
- / %x54.68.75 ; "Thu", case-sensitive
- / %x46.72.69 ; "Fri", case-sensitive
- / %x53.61.74 ; "Sat", case-sensitive
- / %x53.75.6E ; "Sun", case-sensitive
- date1 = day SP month SP year
- ; e.g., 02 Jun 1982
-
- day = 2DIGIT
- month = %x4A.61.6E ; "Jan", case-sensitive
- / %x46.65.62 ; "Feb", case-sensitive
- / %x4D.61.72 ; "Mar", case-sensitive
- / %x41.70.72 ; "Apr", case-sensitive
- / %x4D.61.79 ; "May", case-sensitive
- / %x4A.75.6E ; "Jun", case-sensitive
- / %x4A.75.6C ; "Jul", case-sensitive
- / %x41.75.67 ; "Aug", case-sensitive
- / %x53.65.70 ; "Sep", case-sensitive
- / %x4F.63.74 ; "Oct", case-sensitive
- / %x4E.6F.76 ; "Nov", case-sensitive
- / %x44.65.63 ; "Dec", case-sensitive
- year = 4DIGIT
-
- GMT = %x47.4D.54 ; "GMT", case-sensitive
-
- time-of-day = hour ":" minute ":" second
- ; 00:00:00 - 23:59:60 (leap second)
-
- hour = 2DIGIT
- minute = 2DIGIT
- second = 2DIGIT
- */
-function toIMFDate (date) {
- if (typeof date === 'number') {
- date = new Date(date)
- }
-
- return `${IMFDays[date.getUTCDay()]}, ${IMFPaddedNumbers[date.getUTCDate()]} ${IMFMonths[date.getUTCMonth()]} ${date.getUTCFullYear()} ${IMFPaddedNumbers[date.getUTCHours()]}:${IMFPaddedNumbers[date.getUTCMinutes()]}:${IMFPaddedNumbers[date.getUTCSeconds()]} GMT`
+function parseBlockScalarHeader({ offset, props }, strict, onError) {
+ /* istanbul ignore if should not happen */
+ if (props[0].type !== 'block-scalar-header') {
+ onError(props[0], 'IMPOSSIBLE', 'Block scalar header not found');
+ return null;
+ }
+ const { source } = props[0];
+ const mode = source[0];
+ let indent = 0;
+ let chomp = '';
+ let error = -1;
+ for (let i = 1; i < source.length; ++i) {
+ const ch = source[i];
+ if (!chomp && (ch === '-' || ch === '+'))
+ chomp = ch;
+ else {
+ const n = Number(ch);
+ if (!indent && n)
+ indent = n;
+ else if (error === -1)
+ error = offset + i;
+ }
+ }
+ if (error !== -1)
+ onError(error, 'UNEXPECTED_TOKEN', `Block scalar header includes extra characters: ${source}`);
+ let hasSpace = false;
+ let comment = '';
+ let length = source.length;
+ for (let i = 1; i < props.length; ++i) {
+ const token = props[i];
+ switch (token.type) {
+ case 'space':
+ hasSpace = true;
+ // fallthrough
+ case 'newline':
+ length += token.source.length;
+ break;
+ case 'comment':
+ if (strict && !hasSpace) {
+ const message = 'Comments must be separated from other tokens by white space characters';
+ onError(token, 'MISSING_CHAR', message);
+ }
+ length += token.source.length;
+ comment = token.source.substring(1);
+ break;
+ case 'error':
+ onError(token, 'UNEXPECTED_TOKEN', token.message);
+ length += token.source.length;
+ break;
+ /* istanbul ignore next should not happen */
+ default: {
+ const message = `Unexpected token in block scalar header: ${token.type}`;
+ onError(token, 'UNEXPECTED_TOKEN', message);
+ const ts = token.source;
+ if (ts && typeof ts === 'string')
+ length += ts.length;
+ }
+ }
+ }
+ return { mode, indent, chomp, comment, length };
}
-
-/**
- max-age-av = "Max-Age=" non-zero-digit *DIGIT
- ; In practice, both expires-av and max-age-av
- ; are limited to dates representable by the
- ; user agent.
- * @param {number} maxAge
- */
-function validateCookieMaxAge (maxAge) {
- if (maxAge < 0) {
- throw new Error('Invalid cookie max-age')
- }
+/** @returns Array of lines split up as `[indent, content]` */
+function splitLines(source) {
+ const split = source.split(/\n( *)/);
+ const first = split[0];
+ const m = first.match(/^( *)/);
+ const line0 = m?.[1]
+ ? [m[1], first.slice(m[1].length)]
+ : ['', first];
+ const lines = [line0];
+ for (let i = 1; i < split.length; i += 2)
+ lines.push([split[i], split[i + 1]]);
+ return lines;
}
-/**
- * @see https://www.rfc-editor.org/rfc/rfc6265#section-4.1.1
- * @param {import('./index').Cookie} cookie
- */
-function stringify (cookie) {
- if (cookie.name.length === 0) {
- return null
- }
-
- validateCookieName(cookie.name)
- validateCookieValue(cookie.value)
-
- const out = [`${cookie.name}=${cookie.value}`]
-
- // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.1
- // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.2
- if (cookie.name.startsWith('__Secure-')) {
- cookie.secure = true
- }
-
- if (cookie.name.startsWith('__Host-')) {
- cookie.secure = true
- cookie.domain = null
- cookie.path = '/'
- }
-
- if (cookie.secure) {
- out.push('Secure')
- }
+exports.resolveBlockScalar = resolveBlockScalar;
- if (cookie.httpOnly) {
- out.push('HttpOnly')
- }
- if (typeof cookie.maxAge === 'number') {
- validateCookieMaxAge(cookie.maxAge)
- out.push(`Max-Age=${cookie.maxAge}`)
- }
+/***/ }),
- if (cookie.domain) {
- validateCookieDomain(cookie.domain)
- out.push(`Domain=${cookie.domain}`)
- }
+/***/ 334:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- if (cookie.path) {
- validateCookiePath(cookie.path)
- out.push(`Path=${cookie.path}`)
- }
- if (cookie.expires && cookie.expires.toString() !== 'Invalid Date') {
- out.push(`Expires=${toIMFDate(cookie.expires)}`)
- }
- if (cookie.sameSite) {
- out.push(`SameSite=${cookie.sameSite}`)
- }
+var YAMLSeq = __nccwpck_require__(2223);
+var resolveProps = __nccwpck_require__(4631);
+var utilFlowIndentCheck = __nccwpck_require__(4051);
- for (const part of cookie.unparsed) {
- if (!part.includes('=')) {
- throw new Error('Invalid unparsed')
+function resolveBlockSeq({ composeNode, composeEmptyNode }, ctx, bs, onError, tag) {
+ const NodeClass = tag?.nodeClass ?? YAMLSeq.YAMLSeq;
+ const seq = new NodeClass(ctx.schema);
+ if (ctx.atRoot)
+ ctx.atRoot = false;
+ if (ctx.atKey)
+ ctx.atKey = false;
+ let offset = bs.offset;
+ let commentEnd = null;
+ for (const { start, value } of bs.items) {
+ const props = resolveProps.resolveProps(start, {
+ indicator: 'seq-item-ind',
+ next: value,
+ offset,
+ onError,
+ parentIndent: bs.indent,
+ startOnNewline: true
+ });
+ if (!props.found) {
+ if (props.anchor || props.tag || value) {
+ if (value?.type === 'block-seq')
+ onError(props.end, 'BAD_INDENT', 'All sequence items must start at the same column');
+ else
+ onError(offset, 'MISSING_CHAR', 'Sequence item without - indicator');
+ }
+ else {
+ commentEnd = props.end;
+ if (props.comment)
+ seq.comment = props.comment;
+ continue;
+ }
+ }
+ const node = value
+ ? composeNode(ctx, value, props, onError)
+ : composeEmptyNode(ctx, props.end, start, null, props, onError);
+ if (ctx.schema.compat)
+ utilFlowIndentCheck.flowIndentCheck(bs.indent, value, onError);
+ offset = node.range[2];
+ seq.items.push(node);
}
-
- const [key, ...value] = part.split('=')
-
- out.push(`${key.trim()}=${value.join('=')}`)
- }
-
- return out.join('; ')
+ seq.range = [bs.offset, offset, commentEnd ?? offset];
+ return seq;
}
-module.exports = {
- isCTLExcludingHtab,
- validateCookieName,
- validateCookiePath,
- validateCookieValue,
- toIMFDate,
- stringify
-}
+exports.resolveBlockSeq = resolveBlockSeq;
/***/ }),
-/***/ 2455:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-const { Transform } = __nccwpck_require__(7075)
-const { isASCIINumber, isValidLastEventId } = __nccwpck_require__(6627)
+/***/ 7788:
+/***/ ((__unused_webpack_module, exports) => {
-/**
- * @type {number[]} BOM
- */
-const BOM = [0xEF, 0xBB, 0xBF]
-/**
- * @type {10} LF
- */
-const LF = 0x0A
-/**
- * @type {13} CR
- */
-const CR = 0x0D
-/**
- * @type {58} COLON
- */
-const COLON = 0x3A
-/**
- * @type {32} SPACE
- */
-const SPACE = 0x20
-/**
- * @typedef {object} EventSourceStreamEvent
- * @type {object}
- * @property {string} [event] The event type.
- * @property {string} [data] The data of the message.
- * @property {string} [id] A unique ID for the event.
- * @property {string} [retry] The reconnection time, in milliseconds.
- */
-/**
- * @typedef eventSourceSettings
- * @type {object}
- * @property {string} lastEventId The last event ID received from the server.
- * @property {string} origin The origin of the event source.
- * @property {number} reconnectionTime The reconnection time, in milliseconds.
- */
+function resolveEnd(end, offset, reqSpace, onError) {
+ let comment = '';
+ if (end) {
+ let hasSpace = false;
+ let sep = '';
+ for (const token of end) {
+ const { source, type } = token;
+ switch (type) {
+ case 'space':
+ hasSpace = true;
+ break;
+ case 'comment': {
+ if (reqSpace && !hasSpace)
+ onError(token, 'MISSING_CHAR', 'Comments must be separated from other tokens by white space characters');
+ const cb = source.substring(1) || ' ';
+ if (!comment)
+ comment = cb;
+ else
+ comment += sep + cb;
+ sep = '';
+ break;
+ }
+ case 'newline':
+ if (comment)
+ sep += source;
+ hasSpace = true;
+ break;
+ default:
+ onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${type} at node end`);
+ }
+ offset += source.length;
+ }
+ }
+ return { comment, offset };
+}
-class EventSourceStream extends Transform {
- /**
- * @type {eventSourceSettings}
- */
- state = null
+exports.resolveEnd = resolveEnd;
- /**
- * Leading byte-order-mark check.
- * @type {boolean}
- */
- checkBOM = true
- /**
- * @type {boolean}
- */
- crlfCheck = false
+/***/ }),
- /**
- * @type {boolean}
- */
- eventEndCheck = false
+/***/ 3142:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- /**
- * @type {Buffer}
- */
- buffer = null
- pos = 0
- event = {
- data: undefined,
- event: undefined,
- id: undefined,
- retry: undefined
- }
+var identity = __nccwpck_require__(1127);
+var Pair = __nccwpck_require__(7165);
+var YAMLMap = __nccwpck_require__(4454);
+var YAMLSeq = __nccwpck_require__(2223);
+var resolveEnd = __nccwpck_require__(7788);
+var resolveProps = __nccwpck_require__(4631);
+var utilContainsNewline = __nccwpck_require__(9499);
+var utilMapIncludes = __nccwpck_require__(1187);
- /**
- * @param {object} options
- * @param {eventSourceSettings} options.eventSourceSettings
- * @param {Function} [options.push]
- */
- constructor (options = {}) {
- // Enable object mode as EventSourceStream emits objects of shape
- // EventSourceStreamEvent
- options.readableObjectMode = true
-
- super(options)
-
- this.state = options.eventSourceSettings || {}
- if (options.push) {
- this.push = options.push
- }
- }
-
- /**
- * @param {Buffer} chunk
- * @param {string} _encoding
- * @param {Function} callback
- * @returns {void}
- */
- _transform (chunk, _encoding, callback) {
- if (chunk.length === 0) {
- callback()
- return
- }
-
- // Cache the chunk in the buffer, as the data might not be complete while
- // processing it
- // TODO: Investigate if there is a more performant way to handle
- // incoming chunks
- // see: https://github.com/nodejs/undici/issues/2630
- if (this.buffer) {
- this.buffer = Buffer.concat([this.buffer, chunk])
- } else {
- this.buffer = chunk
- }
-
- // Strip leading byte-order-mark if we opened the stream and started
- // the processing of the incoming data
- if (this.checkBOM) {
- switch (this.buffer.length) {
- case 1:
- // Check if the first byte is the same as the first byte of the BOM
- if (this.buffer[0] === BOM[0]) {
- // If it is, we need to wait for more data
- callback()
- return
- }
- // Set the checkBOM flag to false as we don't need to check for the
- // BOM anymore
- this.checkBOM = false
-
- // The buffer only contains one byte so we need to wait for more data
- callback()
- return
- case 2:
- // Check if the first two bytes are the same as the first two bytes
- // of the BOM
- if (
- this.buffer[0] === BOM[0] &&
- this.buffer[1] === BOM[1]
- ) {
- // If it is, we need to wait for more data, because the third byte
- // is needed to determine if it is the BOM or not
- callback()
- return
- }
-
- // Set the checkBOM flag to false as we don't need to check for the
- // BOM anymore
- this.checkBOM = false
- break
- case 3:
- // Check if the first three bytes are the same as the first three
- // bytes of the BOM
- if (
- this.buffer[0] === BOM[0] &&
- this.buffer[1] === BOM[1] &&
- this.buffer[2] === BOM[2]
- ) {
- // If it is, we can drop the buffered data, as it is only the BOM
- this.buffer = Buffer.alloc(0)
- // Set the checkBOM flag to false as we don't need to check for the
- // BOM anymore
- this.checkBOM = false
-
- // Await more data
- callback()
- return
- }
- // If it is not the BOM, we can start processing the data
- this.checkBOM = false
- break
- default:
- // The buffer is longer than 3 bytes, so we can drop the BOM if it is
- // present
- if (
- this.buffer[0] === BOM[0] &&
- this.buffer[1] === BOM[1] &&
- this.buffer[2] === BOM[2]
- ) {
- // Remove the BOM from the buffer
- this.buffer = this.buffer.subarray(3)
- }
-
- // Set the checkBOM flag to false as we don't need to check for the
- this.checkBOM = false
- break
- }
- }
-
- while (this.pos < this.buffer.length) {
- // If the previous line ended with an end-of-line, we need to check
- // if the next character is also an end-of-line.
- if (this.eventEndCheck) {
- // If the the current character is an end-of-line, then the event
- // is finished and we can process it
-
- // If the previous line ended with a carriage return, we need to
- // check if the current character is a line feed and remove it
- // from the buffer.
- if (this.crlfCheck) {
- // If the current character is a line feed, we can remove it
- // from the buffer and reset the crlfCheck flag
- if (this.buffer[this.pos] === LF) {
- this.buffer = this.buffer.subarray(this.pos + 1)
- this.pos = 0
- this.crlfCheck = false
-
- // It is possible that the line feed is not the end of the
- // event. We need to check if the next character is an
- // end-of-line character to determine if the event is
- // finished. We simply continue the loop to check the next
- // character.
-
- // As we removed the line feed from the buffer and set the
- // crlfCheck flag to false, we basically don't make any
- // distinction between a line feed and a carriage return.
- continue
- }
- this.crlfCheck = false
- }
-
- if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) {
- // If the current character is a carriage return, we need to
- // set the crlfCheck flag to true, as we need to check if the
- // next character is a line feed so we can remove it from the
- // buffer
- if (this.buffer[this.pos] === CR) {
- this.crlfCheck = true
- }
-
- this.buffer = this.buffer.subarray(this.pos + 1)
- this.pos = 0
- if (
- this.event.data !== undefined || this.event.event || this.event.id || this.event.retry) {
- this.processEvent(this.event)
- }
- this.clearEvent()
- continue
- }
- // If the current character is not an end-of-line, then the event
- // is not finished and we have to reset the eventEndCheck flag
- this.eventEndCheck = false
- continue
- }
-
- // If the current character is an end-of-line, we can process the
- // line
- if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) {
- // If the current character is a carriage return, we need to
- // set the crlfCheck flag to true, as we need to check if the
- // next character is a line feed
- if (this.buffer[this.pos] === CR) {
- this.crlfCheck = true
+const blockMsg = 'Block collections are not allowed within flow collections';
+const isBlock = (token) => token && (token.type === 'block-map' || token.type === 'block-seq');
+function resolveFlowCollection({ composeNode, composeEmptyNode }, ctx, fc, onError, tag) {
+ const isMap = fc.start.source === '{';
+ const fcName = isMap ? 'flow map' : 'flow sequence';
+ const NodeClass = (tag?.nodeClass ?? (isMap ? YAMLMap.YAMLMap : YAMLSeq.YAMLSeq));
+ const coll = new NodeClass(ctx.schema);
+ coll.flow = true;
+ const atRoot = ctx.atRoot;
+ if (atRoot)
+ ctx.atRoot = false;
+ if (ctx.atKey)
+ ctx.atKey = false;
+ let offset = fc.offset + fc.start.source.length;
+ for (let i = 0; i < fc.items.length; ++i) {
+ const collItem = fc.items[i];
+ const { start, key, sep, value } = collItem;
+ const props = resolveProps.resolveProps(start, {
+ flow: fcName,
+ indicator: 'explicit-key-ind',
+ next: key ?? sep?.[0],
+ offset,
+ onError,
+ parentIndent: fc.indent,
+ startOnNewline: false
+ });
+ if (!props.found) {
+ if (!props.anchor && !props.tag && !sep && !value) {
+ if (i === 0 && props.comma)
+ onError(props.comma, 'UNEXPECTED_TOKEN', `Unexpected , in ${fcName}`);
+ else if (i < fc.items.length - 1)
+ onError(props.start, 'UNEXPECTED_TOKEN', `Unexpected empty item in ${fcName}`);
+ if (props.comment) {
+ if (coll.comment)
+ coll.comment += '\n' + props.comment;
+ else
+ coll.comment = props.comment;
+ }
+ offset = props.end;
+ continue;
+ }
+ if (!isMap && ctx.options.strict && utilContainsNewline.containsNewline(key))
+ onError(key, // checked by containsNewline()
+ 'MULTILINE_IMPLICIT_KEY', 'Implicit keys of flow sequence pairs need to be on a single line');
}
-
- // In any case, we can process the line as we reached an
- // end-of-line character
- this.parseLine(this.buffer.subarray(0, this.pos), this.event)
-
- // Remove the processed line from the buffer
- this.buffer = this.buffer.subarray(this.pos + 1)
- // Reset the position as we removed the processed line from the buffer
- this.pos = 0
- // A line was processed and this could be the end of the event. We need
- // to check if the next line is empty to determine if the event is
- // finished.
- this.eventEndCheck = true
- continue
- }
-
- this.pos++
- }
-
- callback()
- }
-
- /**
- * @param {Buffer} line
- * @param {EventStreamEvent} event
- */
- parseLine (line, event) {
- // If the line is empty (a blank line)
- // Dispatch the event, as defined below.
- // This will be handled in the _transform method
- if (line.length === 0) {
- return
- }
-
- // If the line starts with a U+003A COLON character (:)
- // Ignore the line.
- const colonPosition = line.indexOf(COLON)
- if (colonPosition === 0) {
- return
- }
-
- let field = ''
- let value = ''
-
- // If the line contains a U+003A COLON character (:)
- if (colonPosition !== -1) {
- // Collect the characters on the line before the first U+003A COLON
- // character (:), and let field be that string.
- // TODO: Investigate if there is a more performant way to extract the
- // field
- // see: https://github.com/nodejs/undici/issues/2630
- field = line.subarray(0, colonPosition).toString('utf8')
-
- // Collect the characters on the line after the first U+003A COLON
- // character (:), and let value be that string.
- // If value starts with a U+0020 SPACE character, remove it from value.
- let valueStart = colonPosition + 1
- if (line[valueStart] === SPACE) {
- ++valueStart
- }
- // TODO: Investigate if there is a more performant way to extract the
- // value
- // see: https://github.com/nodejs/undici/issues/2630
- value = line.subarray(valueStart).toString('utf8')
-
- // Otherwise, the string is not empty but does not contain a U+003A COLON
- // character (:)
- } else {
- // Process the field using the steps described below, using the whole
- // line as the field name, and the empty string as the field value.
- field = line.toString('utf8')
- value = ''
- }
-
- // Modify the event with the field name and value. The value is also
- // decoded as UTF-8
- switch (field) {
- case 'data':
- if (event[field] === undefined) {
- event[field] = value
- } else {
- event[field] += `\n${value}`
+ if (i === 0) {
+ if (props.comma)
+ onError(props.comma, 'UNEXPECTED_TOKEN', `Unexpected , in ${fcName}`);
}
- break
- case 'retry':
- if (isASCIINumber(value)) {
- event[field] = value
+ else {
+ if (!props.comma)
+ onError(props.start, 'MISSING_CHAR', `Missing , between ${fcName} items`);
+ if (props.comment) {
+ let prevItemComment = '';
+ loop: for (const st of start) {
+ switch (st.type) {
+ case 'comma':
+ case 'space':
+ break;
+ case 'comment':
+ prevItemComment = st.source.substring(1);
+ break loop;
+ default:
+ break loop;
+ }
+ }
+ if (prevItemComment) {
+ let prev = coll.items[coll.items.length - 1];
+ if (identity.isPair(prev))
+ prev = prev.value ?? prev.key;
+ if (prev.comment)
+ prev.comment += '\n' + prevItemComment;
+ else
+ prev.comment = prevItemComment;
+ props.comment = props.comment.substring(prevItemComment.length + 1);
+ }
+ }
}
- break
- case 'id':
- if (isValidLastEventId(value)) {
- event[field] = value
+ if (!isMap && !sep && !props.found) {
+ // item is a value in a seq
+ // → key & sep are empty, start does not include ? or :
+ const valueNode = value
+ ? composeNode(ctx, value, props, onError)
+ : composeEmptyNode(ctx, props.end, sep, null, props, onError);
+ coll.items.push(valueNode);
+ offset = valueNode.range[2];
+ if (isBlock(value))
+ onError(valueNode.range, 'BLOCK_IN_FLOW', blockMsg);
}
- break
- case 'event':
- if (value.length > 0) {
- event[field] = value
+ else {
+ // item is a key+value pair
+ // key value
+ ctx.atKey = true;
+ const keyStart = props.end;
+ const keyNode = key
+ ? composeNode(ctx, key, props, onError)
+ : composeEmptyNode(ctx, keyStart, start, null, props, onError);
+ if (isBlock(key))
+ onError(keyNode.range, 'BLOCK_IN_FLOW', blockMsg);
+ ctx.atKey = false;
+ // value properties
+ const valueProps = resolveProps.resolveProps(sep ?? [], {
+ flow: fcName,
+ indicator: 'map-value-ind',
+ next: value,
+ offset: keyNode.range[2],
+ onError,
+ parentIndent: fc.indent,
+ startOnNewline: false
+ });
+ if (valueProps.found) {
+ if (!isMap && !props.found && ctx.options.strict) {
+ if (sep)
+ for (const st of sep) {
+ if (st === valueProps.found)
+ break;
+ if (st.type === 'newline') {
+ onError(st, 'MULTILINE_IMPLICIT_KEY', 'Implicit keys of flow sequence pairs need to be on a single line');
+ break;
+ }
+ }
+ if (props.start < valueProps.found.offset - 1024)
+ onError(valueProps.found, 'KEY_OVER_1024_CHARS', 'The : indicator must be at most 1024 chars after the start of an implicit flow sequence key');
+ }
+ }
+ else if (value) {
+ if ('source' in value && value.source?.[0] === ':')
+ onError(value, 'MISSING_CHAR', `Missing space after : in ${fcName}`);
+ else
+ onError(valueProps.start, 'MISSING_CHAR', `Missing , or : between ${fcName} items`);
+ }
+ // value value
+ const valueNode = value
+ ? composeNode(ctx, value, valueProps, onError)
+ : valueProps.found
+ ? composeEmptyNode(ctx, valueProps.end, sep, null, valueProps, onError)
+ : null;
+ if (valueNode) {
+ if (isBlock(value))
+ onError(valueNode.range, 'BLOCK_IN_FLOW', blockMsg);
+ }
+ else if (valueProps.comment) {
+ if (keyNode.comment)
+ keyNode.comment += '\n' + valueProps.comment;
+ else
+ keyNode.comment = valueProps.comment;
+ }
+ const pair = new Pair.Pair(keyNode, valueNode);
+ if (ctx.options.keepSourceTokens)
+ pair.srcToken = collItem;
+ if (isMap) {
+ const map = coll;
+ if (utilMapIncludes.mapIncludes(ctx, map.items, keyNode))
+ onError(keyStart, 'DUPLICATE_KEY', 'Map keys must be unique');
+ map.items.push(pair);
+ }
+ else {
+ const map = new YAMLMap.YAMLMap(ctx.schema);
+ map.flow = true;
+ map.items.push(pair);
+ const endRange = (valueNode ?? keyNode).range;
+ map.range = [keyNode.range[0], endRange[1], endRange[2]];
+ coll.items.push(map);
+ }
+ offset = valueNode ? valueNode.range[2] : valueProps.end;
}
- break
- }
- }
-
- /**
- * @param {EventSourceStreamEvent} event
- */
- processEvent (event) {
- if (event.retry && isASCIINumber(event.retry)) {
- this.state.reconnectionTime = parseInt(event.retry, 10)
}
-
- if (event.id && isValidLastEventId(event.id)) {
- this.state.lastEventId = event.id
+ const expectedEnd = isMap ? '}' : ']';
+ const [ce, ...ee] = fc.end;
+ let cePos = offset;
+ if (ce?.source === expectedEnd)
+ cePos = ce.offset + ce.source.length;
+ else {
+ const name = fcName[0].toUpperCase() + fcName.substring(1);
+ const msg = atRoot
+ ? `${name} must end with a ${expectedEnd}`
+ : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`;
+ onError(offset, atRoot ? 'MISSING_CHAR' : 'BAD_INDENT', msg);
+ if (ce && ce.source.length !== 1)
+ ee.unshift(ce);
}
-
- // only dispatch event, when data is provided
- if (event.data !== undefined) {
- this.push({
- type: event.event || 'message',
- options: {
- data: event.data,
- lastEventId: this.state.lastEventId,
- origin: this.state.origin
+ if (ee.length > 0) {
+ const end = resolveEnd.resolveEnd(ee, cePos, ctx.options.strict, onError);
+ if (end.comment) {
+ if (coll.comment)
+ coll.comment += '\n' + end.comment;
+ else
+ coll.comment = end.comment;
}
- })
+ coll.range = [fc.offset, cePos, end.offset];
}
- }
-
- clearEvent () {
- this.event = {
- data: undefined,
- event: undefined,
- id: undefined,
- retry: undefined
+ else {
+ coll.range = [fc.offset, cePos, cePos];
}
- }
+ return coll;
}
-module.exports = {
- EventSourceStream
-}
+exports.resolveFlowCollection = resolveFlowCollection;
/***/ }),
-/***/ 6942:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
+/***/ 6842:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-const { pipeline } = __nccwpck_require__(7075)
-const { fetching } = __nccwpck_require__(7302)
-const { makeRequest } = __nccwpck_require__(6055)
-const { webidl } = __nccwpck_require__(253)
-const { EventSourceStream } = __nccwpck_require__(2455)
-const { parseMIMEType } = __nccwpck_require__(980)
-const { createFastMessageEvent } = __nccwpck_require__(44)
-const { isNetworkError } = __nccwpck_require__(9107)
-const { delay } = __nccwpck_require__(6627)
-const { kEnumerableProperty } = __nccwpck_require__(1544)
-const { environmentSettingsObject } = __nccwpck_require__(4296)
-let experimentalWarned = false
-
-/**
- * A reconnection time, in milliseconds. This must initially be an implementation-defined value,
- * probably in the region of a few seconds.
- *
- * In Comparison:
- * - Chrome uses 3000ms.
- * - Deno uses 5000ms.
- *
- * @type {3000}
- */
-const defaultReconnectionTime = 3000
-
-/**
- * The readyState attribute represents the state of the connection.
- * @enum
- * @readonly
- * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#dom-eventsource-readystate-dev
- */
-
-/**
- * The connection has not yet been established, or it was closed and the user
- * agent is reconnecting.
- * @type {0}
- */
-const CONNECTING = 0
-
-/**
- * The user agent has an open connection and is dispatching events as it
- * receives them.
- * @type {1}
- */
-const OPEN = 1
+var Scalar = __nccwpck_require__(3301);
+var resolveEnd = __nccwpck_require__(7788);
+function resolveFlowScalar(scalar, strict, onError) {
+ const { offset, type, source, end } = scalar;
+ let _type;
+ let value;
+ const _onError = (rel, code, msg) => onError(offset + rel, code, msg);
+ switch (type) {
+ case 'scalar':
+ _type = Scalar.Scalar.PLAIN;
+ value = plainValue(source, _onError);
+ break;
+ case 'single-quoted-scalar':
+ _type = Scalar.Scalar.QUOTE_SINGLE;
+ value = singleQuotedValue(source, _onError);
+ break;
+ case 'double-quoted-scalar':
+ _type = Scalar.Scalar.QUOTE_DOUBLE;
+ value = doubleQuotedValue(source, _onError);
+ break;
+ /* istanbul ignore next should not happen */
+ default:
+ onError(scalar, 'UNEXPECTED_TOKEN', `Expected a flow scalar value, but found: ${type}`);
+ return {
+ value: '',
+ type: null,
+ comment: '',
+ range: [offset, offset + source.length, offset + source.length]
+ };
+ }
+ const valueEnd = offset + source.length;
+ const re = resolveEnd.resolveEnd(end, valueEnd, strict, onError);
+ return {
+ value,
+ type: _type,
+ comment: re.comment,
+ range: [offset, valueEnd, re.offset]
+ };
+}
+function plainValue(source, onError) {
+ let badChar = '';
+ switch (source[0]) {
+ /* istanbul ignore next should not happen */
+ case '\t':
+ badChar = 'a tab character';
+ break;
+ case ',':
+ badChar = 'flow indicator character ,';
+ break;
+ case '%':
+ badChar = 'directive indicator character %';
+ break;
+ case '|':
+ case '>': {
+ badChar = `block scalar indicator ${source[0]}`;
+ break;
+ }
+ case '@':
+ case '`': {
+ badChar = `reserved character ${source[0]}`;
+ break;
+ }
+ }
+ if (badChar)
+ onError(0, 'BAD_SCALAR_START', `Plain value cannot start with ${badChar}`);
+ return foldLines(source);
+}
+function singleQuotedValue(source, onError) {
+ if (source[source.length - 1] !== "'" || source.length === 1)
+ onError(source.length, 'MISSING_CHAR', "Missing closing 'quote");
+ return foldLines(source.slice(1, -1)).replace(/''/g, "'");
+}
+function foldLines(source) {
+ /**
+ * The negative lookbehind here and in the `re` RegExp is to
+ * prevent causing a polynomial search time in certain cases.
+ *
+ * The try-catch is for Safari, which doesn't support this yet:
+ * https://caniuse.com/js-regexp-lookbehind
+ */
+ let first, line;
+ try {
+ first = new RegExp('(.*?)(? wsStart ? source.slice(wsStart, i + 1) : ch;
+ }
+ else {
+ res += ch;
+ }
+ }
+ if (source[source.length - 1] !== '"' || source.length === 1)
+ onError(source.length, 'MISSING_CHAR', 'Missing closing "quote');
+ return res;
+}
/**
- * The connection is not open, and the user agent is not trying to reconnect.
- * @type {2}
+ * Fold a single newline into a space, multiple newlines to N - 1 newlines.
+ * Presumes `source[offset] === '\n'`
*/
-const CLOSED = 2
+function foldNewline(source, offset) {
+ let fold = '';
+ let ch = source[offset + 1];
+ while (ch === ' ' || ch === '\t' || ch === '\n' || ch === '\r') {
+ if (ch === '\r' && source[offset + 2] !== '\n')
+ break;
+ if (ch === '\n')
+ fold += '\n';
+ offset += 1;
+ ch = source[offset + 1];
+ }
+ if (!fold)
+ fold = ' ';
+ return { fold, offset };
+}
+const escapeCodes = {
+ '0': '\0', // null character
+ a: '\x07', // bell character
+ b: '\b', // backspace
+ e: '\x1b', // escape character
+ f: '\f', // form feed
+ n: '\n', // line feed
+ r: '\r', // carriage return
+ t: '\t', // horizontal tab
+ v: '\v', // vertical tab
+ N: '\u0085', // Unicode next line
+ _: '\u00a0', // Unicode non-breaking space
+ L: '\u2028', // Unicode line separator
+ P: '\u2029', // Unicode paragraph separator
+ ' ': ' ',
+ '"': '"',
+ '/': '/',
+ '\\': '\\',
+ '\t': '\t'
+};
+function parseCharCode(source, offset, length, onError) {
+ const cc = source.substr(offset, length);
+ const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc);
+ const code = ok ? parseInt(cc, 16) : NaN;
+ try {
+ return String.fromCodePoint(code);
+ }
+ catch {
+ const raw = source.substr(offset - 2, length + 2);
+ onError(offset - 2, 'BAD_DQ_ESCAPE', `Invalid escape sequence ${raw}`);
+ return raw;
+ }
+}
-/**
- * Requests for the element will have their mode set to "cors" and their credentials mode set to "same-origin".
- * @type {'anonymous'}
- */
-const ANONYMOUS = 'anonymous'
+exports.resolveFlowScalar = resolveFlowScalar;
-/**
- * Requests for the element will have their mode set to "cors" and their credentials mode set to "include".
- * @type {'use-credentials'}
- */
-const USE_CREDENTIALS = 'use-credentials'
-/**
- * The EventSource interface is used to receive server-sent events. It
- * connects to a server over HTTP and receives events in text/event-stream
- * format without closing the connection.
- * @extends {EventTarget}
- * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#server-sent-events
- * @api public
- */
-class EventSource extends EventTarget {
- #events = {
- open: null,
- error: null,
- message: null
- }
+/***/ }),
- #url = null
- #withCredentials = false
+/***/ 4631:
+/***/ ((__unused_webpack_module, exports) => {
- #readyState = CONNECTING
- #request = null
- #controller = null
- #dispatcher
+function resolveProps(tokens, { flow, indicator, next, offset, onError, parentIndent, startOnNewline }) {
+ let spaceBefore = false;
+ let atNewline = startOnNewline;
+ let hasSpace = startOnNewline;
+ let comment = '';
+ let commentSep = '';
+ let hasNewline = false;
+ let reqSpace = false;
+ let tab = null;
+ let anchor = null;
+ let tag = null;
+ let newlineAfterProp = null;
+ let comma = null;
+ let found = null;
+ let start = null;
+ for (const token of tokens) {
+ if (reqSpace) {
+ if (token.type !== 'space' &&
+ token.type !== 'newline' &&
+ token.type !== 'comma')
+ onError(token.offset, 'MISSING_CHAR', 'Tags and anchors must be separated from the next token by white space');
+ reqSpace = false;
+ }
+ if (tab) {
+ if (atNewline && token.type !== 'comment' && token.type !== 'newline') {
+ onError(tab, 'TAB_AS_INDENT', 'Tabs are not allowed as indentation');
+ }
+ tab = null;
+ }
+ switch (token.type) {
+ case 'space':
+ // At the doc level, tabs at line start may be parsed
+ // as leading white space rather than indentation.
+ // In a flow collection, only the parser handles indent.
+ if (!flow &&
+ (indicator !== 'doc-start' || next?.type !== 'flow-collection') &&
+ token.source.includes('\t')) {
+ tab = token;
+ }
+ hasSpace = true;
+ break;
+ case 'comment': {
+ if (!hasSpace)
+ onError(token, 'MISSING_CHAR', 'Comments must be separated from other tokens by white space characters');
+ const cb = token.source.substring(1) || ' ';
+ if (!comment)
+ comment = cb;
+ else
+ comment += commentSep + cb;
+ commentSep = '';
+ atNewline = false;
+ break;
+ }
+ case 'newline':
+ if (atNewline) {
+ if (comment)
+ comment += token.source;
+ else if (!found || indicator !== 'seq-item-ind')
+ spaceBefore = true;
+ }
+ else
+ commentSep += token.source;
+ atNewline = true;
+ hasNewline = true;
+ if (anchor || tag)
+ newlineAfterProp = token;
+ hasSpace = true;
+ break;
+ case 'anchor':
+ if (anchor)
+ onError(token, 'MULTIPLE_ANCHORS', 'A node can have at most one anchor');
+ if (token.source.endsWith(':'))
+ onError(token.offset + token.source.length - 1, 'BAD_ALIAS', 'Anchor ending in : is ambiguous', true);
+ anchor = token;
+ start ?? (start = token.offset);
+ atNewline = false;
+ hasSpace = false;
+ reqSpace = true;
+ break;
+ case 'tag': {
+ if (tag)
+ onError(token, 'MULTIPLE_TAGS', 'A node can have at most one tag');
+ tag = token;
+ start ?? (start = token.offset);
+ atNewline = false;
+ hasSpace = false;
+ reqSpace = true;
+ break;
+ }
+ case indicator:
+ // Could here handle preceding comments differently
+ if (anchor || tag)
+ onError(token, 'BAD_PROP_ORDER', `Anchors and tags must be after the ${token.source} indicator`);
+ if (found)
+ onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${token.source} in ${flow ?? 'collection'}`);
+ found = token;
+ atNewline =
+ indicator === 'seq-item-ind' || indicator === 'explicit-key-ind';
+ hasSpace = false;
+ break;
+ case 'comma':
+ if (flow) {
+ if (comma)
+ onError(token, 'UNEXPECTED_TOKEN', `Unexpected , in ${flow}`);
+ comma = token;
+ atNewline = false;
+ hasSpace = false;
+ break;
+ }
+ // else fallthrough
+ default:
+ onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${token.type} token`);
+ atNewline = false;
+ hasSpace = false;
+ }
+ }
+ const last = tokens[tokens.length - 1];
+ const end = last ? last.offset + last.source.length : offset;
+ if (reqSpace &&
+ next &&
+ next.type !== 'space' &&
+ next.type !== 'newline' &&
+ next.type !== 'comma' &&
+ (next.type !== 'scalar' || next.source !== '')) {
+ onError(next.offset, 'MISSING_CHAR', 'Tags and anchors must be separated from the next token by white space');
+ }
+ if (tab &&
+ ((atNewline && tab.indent <= parentIndent) ||
+ next?.type === 'block-map' ||
+ next?.type === 'block-seq'))
+ onError(tab, 'TAB_AS_INDENT', 'Tabs are not allowed as indentation');
+ return {
+ comma,
+ found,
+ spaceBefore,
+ comment,
+ hasNewline,
+ anchor,
+ tag,
+ newlineAfterProp,
+ end,
+ start: start ?? end
+ };
+}
- /**
- * @type {import('./eventsource-stream').eventSourceSettings}
- */
- #state
+exports.resolveProps = resolveProps;
- /**
- * Creates a new EventSource object.
- * @param {string} url
- * @param {EventSourceInit} [eventSourceInitDict]
- * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#the-eventsource-interface
- */
- constructor (url, eventSourceInitDict = {}) {
- // 1. Let ev be a new EventSource object.
- super()
- webidl.util.markAsUncloneable(this)
+/***/ }),
- const prefix = 'EventSource constructor'
- webidl.argumentLengthCheck(arguments, 1, prefix)
+/***/ 9499:
+/***/ ((__unused_webpack_module, exports) => {
- if (!experimentalWarned) {
- experimentalWarned = true
- process.emitWarning('EventSource is experimental, expect them to change at any time.', {
- code: 'UNDICI-ES'
- })
- }
- url = webidl.converters.USVString(url, prefix, 'url')
- eventSourceInitDict = webidl.converters.EventSourceInitDict(eventSourceInitDict, prefix, 'eventSourceInitDict')
- this.#dispatcher = eventSourceInitDict.dispatcher
- this.#state = {
- lastEventId: '',
- reconnectionTime: defaultReconnectionTime
+function containsNewline(key) {
+ if (!key)
+ return null;
+ switch (key.type) {
+ case 'alias':
+ case 'scalar':
+ case 'double-quoted-scalar':
+ case 'single-quoted-scalar':
+ if (key.source.includes('\n'))
+ return true;
+ if (key.end)
+ for (const st of key.end)
+ if (st.type === 'newline')
+ return true;
+ return false;
+ case 'flow-collection':
+ for (const it of key.items) {
+ for (const st of it.start)
+ if (st.type === 'newline')
+ return true;
+ if (it.sep)
+ for (const st of it.sep)
+ if (st.type === 'newline')
+ return true;
+ if (containsNewline(it.key) || containsNewline(it.value))
+ return true;
+ }
+ return false;
+ default:
+ return true;
}
+}
- // 2. Let settings be ev's relevant settings object.
- // https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object
- const settings = environmentSettingsObject
+exports.containsNewline = containsNewline;
- let urlRecord
- try {
- // 3. Let urlRecord be the result of encoding-parsing a URL given url, relative to settings.
- urlRecord = new URL(url, settings.settingsObject.baseUrl)
- this.#state.origin = urlRecord.origin
- } catch (e) {
- // 4. If urlRecord is failure, then throw a "SyntaxError" DOMException.
- throw new DOMException(e, 'SyntaxError')
- }
+/***/ }),
- // 5. Set ev's url to urlRecord.
- this.#url = urlRecord.href
+/***/ 2599:
+/***/ ((__unused_webpack_module, exports) => {
- // 6. Let corsAttributeState be Anonymous.
- let corsAttributeState = ANONYMOUS
- // 7. If the value of eventSourceInitDict's withCredentials member is true,
- // then set corsAttributeState to Use Credentials and set ev's
- // withCredentials attribute to true.
- if (eventSourceInitDict.withCredentials) {
- corsAttributeState = USE_CREDENTIALS
- this.#withCredentials = true
- }
- // 8. Let request be the result of creating a potential-CORS request given
- // urlRecord, the empty string, and corsAttributeState.
- const initRequest = {
- redirect: 'follow',
- keepalive: true,
- // @see https://html.spec.whatwg.org/multipage/urls-and-fetching.html#cors-settings-attributes
- mode: 'cors',
- credentials: corsAttributeState === 'anonymous'
- ? 'same-origin'
- : 'omit',
- referrer: 'no-referrer'
+function emptyScalarPosition(offset, before, pos) {
+ if (before) {
+ pos ?? (pos = before.length);
+ for (let i = pos - 1; i >= 0; --i) {
+ let st = before[i];
+ switch (st.type) {
+ case 'space':
+ case 'comment':
+ case 'newline':
+ offset -= st.source.length;
+ continue;
+ }
+ // Technically, an empty scalar is immediately after the last non-empty
+ // node, but it's more useful to place it after any whitespace.
+ st = before[++i];
+ while (st?.type === 'space') {
+ offset += st.source.length;
+ st = before[++i];
+ }
+ break;
+ }
}
+ return offset;
+}
- // 9. Set request's client to settings.
- initRequest.client = environmentSettingsObject.settingsObject
-
- // 10. User agents may set (`Accept`, `text/event-stream`) in request's header list.
- initRequest.headersList = [['accept', { name: 'accept', value: 'text/event-stream' }]]
-
- // 11. Set request's cache mode to "no-store".
- initRequest.cache = 'no-store'
-
- // 12. Set request's initiator type to "other".
- initRequest.initiator = 'other'
-
- initRequest.urlList = [new URL(this.#url)]
-
- // 13. Set ev's request to request.
- this.#request = makeRequest(initRequest)
-
- this.#connect()
- }
-
- /**
- * Returns the state of this EventSource object's connection. It can have the
- * values described below.
- * @returns {0|1|2}
- * @readonly
- */
- get readyState () {
- return this.#readyState
- }
-
- /**
- * Returns the URL providing the event stream.
- * @readonly
- * @returns {string}
- */
- get url () {
- return this.#url
- }
-
- /**
- * Returns a boolean indicating whether the EventSource object was
- * instantiated with CORS credentials set (true), or not (false, the default).
- */
- get withCredentials () {
- return this.#withCredentials
- }
-
- #connect () {
- if (this.#readyState === CLOSED) return
+exports.emptyScalarPosition = emptyScalarPosition;
- this.#readyState = CONNECTING
- const fetchParams = {
- request: this.#request,
- dispatcher: this.#dispatcher
- }
+/***/ }),
- // 14. Let processEventSourceEndOfBody given response res be the following step: if res is not a network error, then reestablish the connection.
- const processEventSourceEndOfBody = (response) => {
- if (isNetworkError(response)) {
- this.dispatchEvent(new Event('error'))
- this.close()
- }
+/***/ 4051:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- this.#reconnect()
- }
- // 15. Fetch request, with processResponseEndOfBody set to processEventSourceEndOfBody...
- fetchParams.processResponseEndOfBody = processEventSourceEndOfBody
- // and processResponse set to the following steps given response res:
- fetchParams.processResponse = (response) => {
- // 1. If res is an aborted network error, then fail the connection.
+var utilContainsNewline = __nccwpck_require__(9499);
- if (isNetworkError(response)) {
- // 1. When a user agent is to fail the connection, the user agent
- // must queue a task which, if the readyState attribute is set to a
- // value other than CLOSED, sets the readyState attribute to CLOSED
- // and fires an event named error at the EventSource object. Once the
- // user agent has failed the connection, it does not attempt to
- // reconnect.
- if (response.aborted) {
- this.close()
- this.dispatchEvent(new Event('error'))
- return
- // 2. Otherwise, if res is a network error, then reestablish the
- // connection, unless the user agent knows that to be futile, in
- // which case the user agent may fail the connection.
- } else {
- this.#reconnect()
- return
+function flowIndentCheck(indent, fc, onError) {
+ if (fc?.type === 'flow-collection') {
+ const end = fc.end[0];
+ if (end.indent === indent &&
+ (end.source === ']' || end.source === '}') &&
+ utilContainsNewline.containsNewline(fc)) {
+ const msg = 'Flow end indicator should be more indented than parent';
+ onError(end, 'BAD_INDENT', msg, true);
}
- }
+ }
+}
- // 3. Otherwise, if res's status is not 200, or if res's `Content-Type`
- // is not `text/event-stream`, then fail the connection.
- const contentType = response.headersList.get('content-type', true)
- const mimeType = contentType !== null ? parseMIMEType(contentType) : 'failure'
- const contentTypeValid = mimeType !== 'failure' && mimeType.essence === 'text/event-stream'
- if (
- response.status !== 200 ||
- contentTypeValid === false
- ) {
- this.close()
- this.dispatchEvent(new Event('error'))
- return
- }
+exports.flowIndentCheck = flowIndentCheck;
- // 4. Otherwise, announce the connection and interpret res's body
- // line by line.
- // When a user agent is to announce the connection, the user agent
- // must queue a task which, if the readyState attribute is set to a
- // value other than CLOSED, sets the readyState attribute to OPEN
- // and fires an event named open at the EventSource object.
- // @see https://html.spec.whatwg.org/multipage/server-sent-events.html#sse-processing-model
- this.#readyState = OPEN
- this.dispatchEvent(new Event('open'))
+/***/ }),
- // If redirected to a different origin, set the origin to the new origin.
- this.#state.origin = response.urlList[response.urlList.length - 1].origin
+/***/ 1187:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- const eventSourceStream = new EventSourceStream({
- eventSourceSettings: this.#state,
- push: (event) => {
- this.dispatchEvent(createFastMessageEvent(
- event.type,
- event.options
- ))
- }
- })
- pipeline(response.body.stream,
- eventSourceStream,
- (error) => {
- if (
- error?.aborted === false
- ) {
- this.close()
- this.dispatchEvent(new Event('error'))
- }
- })
- }
- this.#controller = fetching(fetchParams)
- }
+var identity = __nccwpck_require__(1127);
- /**
- * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#sse-processing-model
- * @returns {Promise}
- */
- async #reconnect () {
- // When a user agent is to reestablish the connection, the user agent must
- // run the following steps. These steps are run in parallel, not as part of
- // a task. (The tasks that it queues, of course, are run like normal tasks
- // and not themselves in parallel.)
+function mapIncludes(ctx, items, search) {
+ const { uniqueKeys } = ctx.options;
+ if (uniqueKeys === false)
+ return false;
+ const isEqual = typeof uniqueKeys === 'function'
+ ? uniqueKeys
+ : (a, b) => a === b || (identity.isScalar(a) && identity.isScalar(b) && a.value === b.value);
+ return items.some(pair => isEqual(pair.key, search));
+}
- // 1. Queue a task to run the following steps:
+exports.mapIncludes = mapIncludes;
- // 1. If the readyState attribute is set to CLOSED, abort the task.
- if (this.#readyState === CLOSED) return
- // 2. Set the readyState attribute to CONNECTING.
- this.#readyState = CONNECTING
+/***/ }),
- // 3. Fire an event named error at the EventSource object.
- this.dispatchEvent(new Event('error'))
+/***/ 3021:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 2. Wait a delay equal to the reconnection time of the event source.
- await delay(this.#state.reconnectionTime)
- // 5. Queue a task to run the following steps:
- // 1. If the EventSource object's readyState attribute is not set to
- // CONNECTING, then return.
- if (this.#readyState !== CONNECTING) return
+var Alias = __nccwpck_require__(4065);
+var Collection = __nccwpck_require__(101);
+var identity = __nccwpck_require__(1127);
+var Pair = __nccwpck_require__(7165);
+var toJS = __nccwpck_require__(6424);
+var Schema = __nccwpck_require__(5840);
+var stringifyDocument = __nccwpck_require__(6829);
+var anchors = __nccwpck_require__(1596);
+var applyReviver = __nccwpck_require__(3661);
+var createNode = __nccwpck_require__(2404);
+var directives = __nccwpck_require__(1342);
- // 2. Let request be the EventSource object's request.
- // 3. If the EventSource object's last event ID string is not the empty
- // string, then:
- // 1. Let lastEventIDValue be the EventSource object's last event ID
- // string, encoded as UTF-8.
- // 2. Set (`Last-Event-ID`, lastEventIDValue) in request's header
- // list.
- if (this.#state.lastEventId.length) {
- this.#request.headersList.set('last-event-id', this.#state.lastEventId, true)
+class Document {
+ constructor(value, replacer, options) {
+ /** A comment before this Document */
+ this.commentBefore = null;
+ /** A comment immediately after this Document */
+ this.comment = null;
+ /** Errors encountered during parsing. */
+ this.errors = [];
+ /** Warnings encountered during parsing. */
+ this.warnings = [];
+ Object.defineProperty(this, identity.NODE_TYPE, { value: identity.DOC });
+ let _replacer = null;
+ if (typeof replacer === 'function' || Array.isArray(replacer)) {
+ _replacer = replacer;
+ }
+ else if (options === undefined && replacer) {
+ options = replacer;
+ replacer = undefined;
+ }
+ const opt = Object.assign({
+ intAsBigInt: false,
+ keepSourceTokens: false,
+ logLevel: 'warn',
+ prettyErrors: true,
+ strict: true,
+ stringKeys: false,
+ uniqueKeys: true,
+ version: '1.2'
+ }, options);
+ this.options = opt;
+ let { version } = opt;
+ if (options?._directives) {
+ this.directives = options._directives.atDocument();
+ if (this.directives.yaml.explicit)
+ version = this.directives.yaml.version;
+ }
+ else
+ this.directives = new directives.Directives({ version });
+ this.setSchema(version, options);
+ // @ts-expect-error We can't really know that this matches Contents.
+ this.contents =
+ value === undefined ? null : this.createNode(value, _replacer, options);
}
-
- // 4. Fetch request and process the response obtained in this fashion, if any, as described earlier in this section.
- this.#connect()
- }
-
- /**
- * Closes the connection, if any, and sets the readyState attribute to
- * CLOSED.
- */
- close () {
- webidl.brandCheck(this, EventSource)
-
- if (this.#readyState === CLOSED) return
- this.#readyState = CLOSED
- this.#controller.abort()
- this.#request = null
- }
-
- get onopen () {
- return this.#events.open
- }
-
- set onopen (fn) {
- if (this.#events.open) {
- this.removeEventListener('open', this.#events.open)
+ /**
+ * Create a deep copy of this Document and its contents.
+ *
+ * Custom Node values that inherit from `Object` still refer to their original instances.
+ */
+ clone() {
+ const copy = Object.create(Document.prototype, {
+ [identity.NODE_TYPE]: { value: identity.DOC }
+ });
+ copy.commentBefore = this.commentBefore;
+ copy.comment = this.comment;
+ copy.errors = this.errors.slice();
+ copy.warnings = this.warnings.slice();
+ copy.options = Object.assign({}, this.options);
+ if (this.directives)
+ copy.directives = this.directives.clone();
+ copy.schema = this.schema.clone();
+ // @ts-expect-error We can't really know that this matches Contents.
+ copy.contents = identity.isNode(this.contents)
+ ? this.contents.clone(copy.schema)
+ : this.contents;
+ if (this.range)
+ copy.range = this.range.slice();
+ return copy;
}
-
- if (typeof fn === 'function') {
- this.#events.open = fn
- this.addEventListener('open', fn)
- } else {
- this.#events.open = null
+ /** Adds a value to the document. */
+ add(value) {
+ if (assertCollection(this.contents))
+ this.contents.add(value);
}
- }
-
- get onmessage () {
- return this.#events.message
- }
-
- set onmessage (fn) {
- if (this.#events.message) {
- this.removeEventListener('message', this.#events.message)
+ /** Adds a value to the document. */
+ addIn(path, value) {
+ if (assertCollection(this.contents))
+ this.contents.addIn(path, value);
}
-
- if (typeof fn === 'function') {
- this.#events.message = fn
- this.addEventListener('message', fn)
- } else {
- this.#events.message = null
+ /**
+ * Create a new `Alias` node, ensuring that the target `node` has the required anchor.
+ *
+ * If `node` already has an anchor, `name` is ignored.
+ * Otherwise, the `node.anchor` value will be set to `name`,
+ * or if an anchor with that name is already present in the document,
+ * `name` will be used as a prefix for a new unique anchor.
+ * If `name` is undefined, the generated anchor will use 'a' as a prefix.
+ */
+ createAlias(node, name) {
+ if (!node.anchor) {
+ const prev = anchors.anchorNames(this);
+ node.anchor =
+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
+ !name || prev.has(name) ? anchors.findNewAnchor(name || 'a', prev) : name;
+ }
+ return new Alias.Alias(node.anchor);
}
- }
-
- get onerror () {
- return this.#events.error
- }
-
- set onerror (fn) {
- if (this.#events.error) {
- this.removeEventListener('error', this.#events.error)
+ createNode(value, replacer, options) {
+ let _replacer = undefined;
+ if (typeof replacer === 'function') {
+ value = replacer.call({ '': value }, '', value);
+ _replacer = replacer;
+ }
+ else if (Array.isArray(replacer)) {
+ const keyToStr = (v) => typeof v === 'number' || v instanceof String || v instanceof Number;
+ const asStr = replacer.filter(keyToStr).map(String);
+ if (asStr.length > 0)
+ replacer = replacer.concat(asStr);
+ _replacer = replacer;
+ }
+ else if (options === undefined && replacer) {
+ options = replacer;
+ replacer = undefined;
+ }
+ const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {};
+ const { onAnchor, setAnchors, sourceObjects } = anchors.createNodeAnchors(this,
+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
+ anchorPrefix || 'a');
+ const ctx = {
+ aliasDuplicateObjects: aliasDuplicateObjects ?? true,
+ keepUndefined: keepUndefined ?? false,
+ onAnchor,
+ onTagObj,
+ replacer: _replacer,
+ schema: this.schema,
+ sourceObjects
+ };
+ const node = createNode.createNode(value, tag, ctx);
+ if (flow && identity.isCollection(node))
+ node.flow = true;
+ setAnchors();
+ return node;
}
-
- if (typeof fn === 'function') {
- this.#events.error = fn
- this.addEventListener('error', fn)
- } else {
- this.#events.error = null
+ /**
+ * Convert a key and a value into a `Pair` using the current schema,
+ * recursively wrapping all values as `Scalar` or `Collection` nodes.
+ */
+ createPair(key, value, options = {}) {
+ const k = this.createNode(key, null, options);
+ const v = this.createNode(value, null, options);
+ return new Pair.Pair(k, v);
+ }
+ /**
+ * Removes a value from the document.
+ * @returns `true` if the item was found and removed.
+ */
+ delete(key) {
+ return assertCollection(this.contents) ? this.contents.delete(key) : false;
+ }
+ /**
+ * Removes a value from the document.
+ * @returns `true` if the item was found and removed.
+ */
+ deleteIn(path) {
+ if (Collection.isEmptyPath(path)) {
+ if (this.contents == null)
+ return false;
+ // @ts-expect-error Presumed impossible if Strict extends false
+ this.contents = null;
+ return true;
+ }
+ return assertCollection(this.contents)
+ ? this.contents.deleteIn(path)
+ : false;
+ }
+ /**
+ * Returns item at `key`, or `undefined` if not found. By default unwraps
+ * scalar values from their surrounding node; to disable set `keepScalar` to
+ * `true` (collections are always returned intact).
+ */
+ get(key, keepScalar) {
+ return identity.isCollection(this.contents)
+ ? this.contents.get(key, keepScalar)
+ : undefined;
+ }
+ /**
+ * Returns item at `path`, or `undefined` if not found. By default unwraps
+ * scalar values from their surrounding node; to disable set `keepScalar` to
+ * `true` (collections are always returned intact).
+ */
+ getIn(path, keepScalar) {
+ if (Collection.isEmptyPath(path))
+ return !keepScalar && identity.isScalar(this.contents)
+ ? this.contents.value
+ : this.contents;
+ return identity.isCollection(this.contents)
+ ? this.contents.getIn(path, keepScalar)
+ : undefined;
+ }
+ /**
+ * Checks if the document includes a value with the key `key`.
+ */
+ has(key) {
+ return identity.isCollection(this.contents) ? this.contents.has(key) : false;
+ }
+ /**
+ * Checks if the document includes a value at `path`.
+ */
+ hasIn(path) {
+ if (Collection.isEmptyPath(path))
+ return this.contents !== undefined;
+ return identity.isCollection(this.contents) ? this.contents.hasIn(path) : false;
+ }
+ /**
+ * Sets a value in this document. For `!!set`, `value` needs to be a
+ * boolean to add/remove the item from the set.
+ */
+ set(key, value) {
+ if (this.contents == null) {
+ // @ts-expect-error We can't really know that this matches Contents.
+ this.contents = Collection.collectionFromPath(this.schema, [key], value);
+ }
+ else if (assertCollection(this.contents)) {
+ this.contents.set(key, value);
+ }
+ }
+ /**
+ * Sets a value in this document. For `!!set`, `value` needs to be a
+ * boolean to add/remove the item from the set.
+ */
+ setIn(path, value) {
+ if (Collection.isEmptyPath(path)) {
+ // @ts-expect-error We can't really know that this matches Contents.
+ this.contents = value;
+ }
+ else if (this.contents == null) {
+ // @ts-expect-error We can't really know that this matches Contents.
+ this.contents = Collection.collectionFromPath(this.schema, Array.from(path), value);
+ }
+ else if (assertCollection(this.contents)) {
+ this.contents.setIn(path, value);
+ }
+ }
+ /**
+ * Change the YAML version and schema used by the document.
+ * A `null` version disables support for directives, explicit tags, anchors, and aliases.
+ * It also requires the `schema` option to be given as a `Schema` instance value.
+ *
+ * Overrides all previously set schema options.
+ */
+ setSchema(version, options = {}) {
+ if (typeof version === 'number')
+ version = String(version);
+ let opt;
+ switch (version) {
+ case '1.1':
+ if (this.directives)
+ this.directives.yaml.version = '1.1';
+ else
+ this.directives = new directives.Directives({ version: '1.1' });
+ opt = { resolveKnownTags: false, schema: 'yaml-1.1' };
+ break;
+ case '1.2':
+ case 'next':
+ if (this.directives)
+ this.directives.yaml.version = version;
+ else
+ this.directives = new directives.Directives({ version });
+ opt = { resolveKnownTags: true, schema: 'core' };
+ break;
+ case null:
+ if (this.directives)
+ delete this.directives;
+ opt = null;
+ break;
+ default: {
+ const sv = JSON.stringify(version);
+ throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`);
+ }
+ }
+ // Not using `instanceof Schema` to allow for duck typing
+ if (options.schema instanceof Object)
+ this.schema = options.schema;
+ else if (opt)
+ this.schema = new Schema.Schema(Object.assign(opt, options));
+ else
+ throw new Error(`With a null YAML version, the { schema: Schema } option is required`);
+ }
+ // json & jsonArg are only used from toJSON()
+ toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
+ const ctx = {
+ anchors: new Map(),
+ doc: this,
+ keep: !json,
+ mapAsMap: mapAsMap === true,
+ mapKeyWarned: false,
+ maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100
+ };
+ const res = toJS.toJS(this.contents, jsonArg ?? '', ctx);
+ if (typeof onAnchor === 'function')
+ for (const { count, res } of ctx.anchors.values())
+ onAnchor(res, count);
+ return typeof reviver === 'function'
+ ? applyReviver.applyReviver(reviver, { '': res }, '', res)
+ : res;
+ }
+ /**
+ * A JSON representation of the document `contents`.
+ *
+ * @param jsonArg Used by `JSON.stringify` to indicate the array index or
+ * property name.
+ */
+ toJSON(jsonArg, onAnchor) {
+ return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor });
+ }
+ /** A YAML representation of the document. */
+ toString(options = {}) {
+ if (this.errors.length > 0)
+ throw new Error('Document with errors cannot be stringified');
+ if ('indent' in options &&
+ (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) {
+ const s = JSON.stringify(options.indent);
+ throw new Error(`"indent" option must be a positive integer, not ${s}`);
+ }
+ return stringifyDocument.stringifyDocument(this, options);
}
- }
-}
-
-const constantsPropertyDescriptors = {
- CONNECTING: {
- __proto__: null,
- configurable: false,
- enumerable: true,
- value: CONNECTING,
- writable: false
- },
- OPEN: {
- __proto__: null,
- configurable: false,
- enumerable: true,
- value: OPEN,
- writable: false
- },
- CLOSED: {
- __proto__: null,
- configurable: false,
- enumerable: true,
- value: CLOSED,
- writable: false
- }
-}
-
-Object.defineProperties(EventSource, constantsPropertyDescriptors)
-Object.defineProperties(EventSource.prototype, constantsPropertyDescriptors)
-
-Object.defineProperties(EventSource.prototype, {
- close: kEnumerableProperty,
- onerror: kEnumerableProperty,
- onmessage: kEnumerableProperty,
- onopen: kEnumerableProperty,
- readyState: kEnumerableProperty,
- url: kEnumerableProperty,
- withCredentials: kEnumerableProperty
-})
-
-webidl.converters.EventSourceInitDict = webidl.dictionaryConverter([
- {
- key: 'withCredentials',
- converter: webidl.converters.boolean,
- defaultValue: () => false
- },
- {
- key: 'dispatcher', // undici only
- converter: webidl.converters.any
- }
-])
-
-module.exports = {
- EventSource,
- defaultReconnectionTime
-}
-
-
-/***/ }),
-
-/***/ 6627:
-/***/ ((module) => {
-
-
-
-/**
- * Checks if the given value is a valid LastEventId.
- * @param {string} value
- * @returns {boolean}
- */
-function isValidLastEventId (value) {
- // LastEventId should not contain U+0000 NULL
- return value.indexOf('\u0000') === -1
-}
-
-/**
- * Checks if the given value is a base 10 digit.
- * @param {string} value
- * @returns {boolean}
- */
-function isASCIINumber (value) {
- if (value.length === 0) return false
- for (let i = 0; i < value.length; i++) {
- if (value.charCodeAt(i) < 0x30 || value.charCodeAt(i) > 0x39) return false
- }
- return true
}
-
-// https://github.com/nodejs/undici/issues/2664
-function delay (ms) {
- return new Promise((resolve) => {
- setTimeout(resolve, ms).unref()
- })
+function assertCollection(contents) {
+ if (identity.isCollection(contents))
+ return true;
+ throw new Error('Expected a YAML collection as document contents');
}
-module.exports = {
- isValidLastEventId,
- isASCIINumber,
- delay
-}
+exports.Document = Document;
/***/ }),
-/***/ 8900:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 1596:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-const util = __nccwpck_require__(1544)
-const {
- ReadableStreamFrom,
- isBlobLike,
- isReadableStreamLike,
- readableStreamClose,
- createDeferredPromise,
- fullyReadBody,
- extractMimeType,
- utf8DecodeBytes
-} = __nccwpck_require__(4296)
-const { FormData } = __nccwpck_require__(9662)
-const { kState } = __nccwpck_require__(4883)
-const { webidl } = __nccwpck_require__(253)
-const { Blob } = __nccwpck_require__(4573)
-const assert = __nccwpck_require__(4589)
-const { isErrored, isDisturbed } = __nccwpck_require__(7075)
-const { isArrayBuffer } = __nccwpck_require__(3429)
-const { serializeAMimeType } = __nccwpck_require__(980)
-const { multipartFormDataParser } = __nccwpck_require__(3100)
-let random
+var identity = __nccwpck_require__(1127);
+var visit = __nccwpck_require__(204);
-try {
- const crypto = __nccwpck_require__(7598)
- random = (max) => crypto.randomInt(0, max)
-} catch {
- random = (max) => Math.floor(Math.random(max))
+/**
+ * Verify that the input string is a valid anchor.
+ *
+ * Will throw on errors.
+ */
+function anchorIsValid(anchor) {
+ if (/[\x00-\x19\s,[\]{}]/.test(anchor)) {
+ const sa = JSON.stringify(anchor);
+ const msg = `Anchor must not contain whitespace or control characters: ${sa}`;
+ throw new Error(msg);
+ }
+ return true;
+}
+function anchorNames(root) {
+ const anchors = new Set();
+ visit.visit(root, {
+ Value(_key, node) {
+ if (node.anchor)
+ anchors.add(node.anchor);
+ }
+ });
+ return anchors;
+}
+/** Find a new anchor name with the given `prefix` and a one-indexed suffix. */
+function findNewAnchor(prefix, exclude) {
+ for (let i = 1; true; ++i) {
+ const name = `${prefix}${i}`;
+ if (!exclude.has(name))
+ return name;
+ }
+}
+function createNodeAnchors(doc, prefix) {
+ const aliasObjects = [];
+ const sourceObjects = new Map();
+ let prevAnchors = null;
+ return {
+ onAnchor: (source) => {
+ aliasObjects.push(source);
+ prevAnchors ?? (prevAnchors = anchorNames(doc));
+ const anchor = findNewAnchor(prefix, prevAnchors);
+ prevAnchors.add(anchor);
+ return anchor;
+ },
+ /**
+ * With circular references, the source node is only resolved after all
+ * of its child nodes are. This is why anchors are set only after all of
+ * the nodes have been created.
+ */
+ setAnchors: () => {
+ for (const source of aliasObjects) {
+ const ref = sourceObjects.get(source);
+ if (typeof ref === 'object' &&
+ ref.anchor &&
+ (identity.isScalar(ref.node) || identity.isCollection(ref.node))) {
+ ref.node.anchor = ref.anchor;
+ }
+ else {
+ const error = new Error('Failed to resolve repeated object (this should not happen)');
+ error.source = source;
+ throw error;
+ }
+ }
+ },
+ sourceObjects
+ };
}
-const textEncoder = new TextEncoder()
-function noop () {}
+exports.anchorIsValid = anchorIsValid;
+exports.anchorNames = anchorNames;
+exports.createNodeAnchors = createNodeAnchors;
+exports.findNewAnchor = findNewAnchor;
-const hasFinalizationRegistry = globalThis.FinalizationRegistry && process.version.indexOf('v18') !== 0
-let streamRegistry
-if (hasFinalizationRegistry) {
- streamRegistry = new FinalizationRegistry((weakRef) => {
- const stream = weakRef.deref()
- if (stream && !stream.locked && !isDisturbed(stream) && !isErrored(stream)) {
- stream.cancel('Response object has been garbage collected').catch(noop)
- }
- })
-}
+/***/ }),
-// https://fetch.spec.whatwg.org/#concept-bodyinit-extract
-function extractBody (object, keepalive = false) {
- // 1. Let stream be null.
- let stream = null
+/***/ 3661:
+/***/ ((__unused_webpack_module, exports) => {
- // 2. If object is a ReadableStream object, then set stream to object.
- if (object instanceof ReadableStream) {
- stream = object
- } else if (isBlobLike(object)) {
- // 3. Otherwise, if object is a Blob object, set stream to the
- // result of running object’s get stream.
- stream = object.stream()
- } else {
- // 4. Otherwise, set stream to a new ReadableStream object, and set
- // up stream with byte reading support.
- stream = new ReadableStream({
- async pull (controller) {
- const buffer = typeof source === 'string' ? textEncoder.encode(source) : source
- if (buffer.byteLength) {
- controller.enqueue(buffer)
+
+/**
+ * Applies the JSON.parse reviver algorithm as defined in the ECMA-262 spec,
+ * in section 24.5.1.1 "Runtime Semantics: InternalizeJSONProperty" of the
+ * 2021 edition: https://tc39.es/ecma262/#sec-json.parse
+ *
+ * Includes extensions for handling Map and Set objects.
+ */
+function applyReviver(reviver, obj, key, val) {
+ if (val && typeof val === 'object') {
+ if (Array.isArray(val)) {
+ for (let i = 0, len = val.length; i < len; ++i) {
+ const v0 = val[i];
+ const v1 = applyReviver(reviver, val, String(i), v0);
+ // eslint-disable-next-line @typescript-eslint/no-array-delete
+ if (v1 === undefined)
+ delete val[i];
+ else if (v1 !== v0)
+ val[i] = v1;
+ }
+ }
+ else if (val instanceof Map) {
+ for (const k of Array.from(val.keys())) {
+ const v0 = val.get(k);
+ const v1 = applyReviver(reviver, val, k, v0);
+ if (v1 === undefined)
+ val.delete(k);
+ else if (v1 !== v0)
+ val.set(k, v1);
+ }
+ }
+ else if (val instanceof Set) {
+ for (const v0 of Array.from(val)) {
+ const v1 = applyReviver(reviver, val, v0, v0);
+ if (v1 === undefined)
+ val.delete(v0);
+ else if (v1 !== v0) {
+ val.delete(v0);
+ val.add(v1);
+ }
+ }
+ }
+ else {
+ for (const [k, v0] of Object.entries(val)) {
+ const v1 = applyReviver(reviver, val, k, v0);
+ if (v1 === undefined)
+ delete val[k];
+ else if (v1 !== v0)
+ val[k] = v1;
+ }
}
+ }
+ return reviver.call(obj, key, val);
+}
- queueMicrotask(() => readableStreamClose(controller))
- },
- start () {},
- type: 'bytes'
- })
- }
+exports.applyReviver = applyReviver;
- // 5. Assert: stream is a ReadableStream object.
- assert(isReadableStreamLike(stream))
- // 6. Let action be null.
- let action = null
+/***/ }),
- // 7. Let source be null.
- let source = null
+/***/ 2404:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 8. Let length be null.
- let length = null
- // 9. Let type be null.
- let type = null
- // 10. Switch on object:
- if (typeof object === 'string') {
- // Set source to the UTF-8 encoding of object.
- // Note: setting source to a Uint8Array here breaks some mocking assumptions.
- source = object
+var Alias = __nccwpck_require__(4065);
+var identity = __nccwpck_require__(1127);
+var Scalar = __nccwpck_require__(3301);
- // Set type to `text/plain;charset=UTF-8`.
- type = 'text/plain;charset=UTF-8'
- } else if (object instanceof URLSearchParams) {
- // URLSearchParams
+const defaultTagPrefix = 'tag:yaml.org,2002:';
+function findTagObject(value, tagName, tags) {
+ if (tagName) {
+ const match = tags.filter(t => t.tag === tagName);
+ const tagObj = match.find(t => !t.format) ?? match[0];
+ if (!tagObj)
+ throw new Error(`Tag ${tagName} not found`);
+ return tagObj;
+ }
+ return tags.find(t => t.identify?.(value) && !t.format);
+}
+function createNode(value, tagName, ctx) {
+ if (identity.isDocument(value))
+ value = value.contents;
+ if (identity.isNode(value))
+ return value;
+ if (identity.isPair(value)) {
+ const map = ctx.schema[identity.MAP].createNode?.(ctx.schema, null, ctx);
+ map.items.push(value);
+ return map;
+ }
+ if (value instanceof String ||
+ value instanceof Number ||
+ value instanceof Boolean ||
+ (typeof BigInt !== 'undefined' && value instanceof BigInt) // not supported everywhere
+ ) {
+ // https://tc39.es/ecma262/#sec-serializejsonproperty
+ value = value.valueOf();
+ }
+ const { aliasDuplicateObjects, onAnchor, onTagObj, schema, sourceObjects } = ctx;
+ // Detect duplicate references to the same object & use Alias nodes for all
+ // after first. The `ref` wrapper allows for circular references to resolve.
+ let ref = undefined;
+ if (aliasDuplicateObjects && value && typeof value === 'object') {
+ ref = sourceObjects.get(value);
+ if (ref) {
+ ref.anchor ?? (ref.anchor = onAnchor(value));
+ return new Alias.Alias(ref.anchor);
+ }
+ else {
+ ref = { anchor: null, node: null };
+ sourceObjects.set(value, ref);
+ }
+ }
+ if (tagName?.startsWith('!!'))
+ tagName = defaultTagPrefix + tagName.slice(2);
+ let tagObj = findTagObject(value, tagName, schema.tags);
+ if (!tagObj) {
+ if (value && typeof value.toJSON === 'function') {
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-call
+ value = value.toJSON();
+ }
+ if (!value || typeof value !== 'object') {
+ const node = new Scalar.Scalar(value);
+ if (ref)
+ ref.node = node;
+ return node;
+ }
+ tagObj =
+ value instanceof Map
+ ? schema[identity.MAP]
+ : Symbol.iterator in Object(value)
+ ? schema[identity.SEQ]
+ : schema[identity.MAP];
+ }
+ if (onTagObj) {
+ onTagObj(tagObj);
+ delete ctx.onTagObj;
+ }
+ const node = tagObj?.createNode
+ ? tagObj.createNode(ctx.schema, value, ctx)
+ : typeof tagObj?.nodeClass?.from === 'function'
+ ? tagObj.nodeClass.from(ctx.schema, value, ctx)
+ : new Scalar.Scalar(value);
+ if (tagName)
+ node.tag = tagName;
+ else if (!tagObj.default)
+ node.tag = tagObj.tag;
+ if (ref)
+ ref.node = node;
+ return node;
+}
- // spec says to run application/x-www-form-urlencoded on body.list
- // this is implemented in Node.js as apart of an URLSearchParams instance toString method
- // See: https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L490
- // and https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L1100
+exports.createNode = createNode;
- // Set source to the result of running the application/x-www-form-urlencoded serializer with object’s list.
- source = object.toString()
- // Set type to `application/x-www-form-urlencoded;charset=UTF-8`.
- type = 'application/x-www-form-urlencoded;charset=UTF-8'
- } else if (isArrayBuffer(object)) {
- // BufferSource/ArrayBuffer
+/***/ }),
- // Set source to a copy of the bytes held by object.
- source = new Uint8Array(object.slice())
- } else if (ArrayBuffer.isView(object)) {
- // BufferSource/ArrayBufferView
+/***/ 1342:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // Set source to a copy of the bytes held by object.
- source = new Uint8Array(object.buffer.slice(object.byteOffset, object.byteOffset + object.byteLength))
- } else if (util.isFormDataLike(object)) {
- const boundary = `----formdata-undici-0${`${random(1e11)}`.padStart(11, '0')}`
- const prefix = `--${boundary}\r\nContent-Disposition: form-data`
- /*! formdata-polyfill. MIT License. Jimmy Wärting */
- const escape = (str) =>
- str.replace(/\n/g, '%0A').replace(/\r/g, '%0D').replace(/"/g, '%22')
- const normalizeLinefeeds = (value) => value.replace(/\r?\n|\r/g, '\r\n')
-
- // Set action to this step: run the multipart/form-data
- // encoding algorithm, with object’s entry list and UTF-8.
- // - This ensures that the body is immutable and can't be changed afterwords
- // - That the content-length is calculated in advance.
- // - And that all parts are pre-encoded and ready to be sent.
- const blobParts = []
- const rn = new Uint8Array([13, 10]) // '\r\n'
- length = 0
- let hasUnknownSizeValue = false
+var identity = __nccwpck_require__(1127);
+var visit = __nccwpck_require__(204);
- for (const [name, value] of object) {
- if (typeof value === 'string') {
- const chunk = textEncoder.encode(prefix +
- `; name="${escape(normalizeLinefeeds(name))}"` +
- `\r\n\r\n${normalizeLinefeeds(value)}\r\n`)
- blobParts.push(chunk)
- length += chunk.byteLength
- } else {
- const chunk = textEncoder.encode(`${prefix}; name="${escape(normalizeLinefeeds(name))}"` +
- (value.name ? `; filename="${escape(value.name)}"` : '') + '\r\n' +
- `Content-Type: ${
- value.type || 'application/octet-stream'
- }\r\n\r\n`)
- blobParts.push(chunk, value, rn)
- if (typeof value.size === 'number') {
- length += chunk.byteLength + value.size + rn.byteLength
- } else {
- hasUnknownSizeValue = true
+const escapeChars = {
+ '!': '%21',
+ ',': '%2C',
+ '[': '%5B',
+ ']': '%5D',
+ '{': '%7B',
+ '}': '%7D'
+};
+const escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, ch => escapeChars[ch]);
+class Directives {
+ constructor(yaml, tags) {
+ /**
+ * The directives-end/doc-start marker `---`. If `null`, a marker may still be
+ * included in the document's stringified representation.
+ */
+ this.docStart = null;
+ /** The doc-end marker `...`. */
+ this.docEnd = false;
+ this.yaml = Object.assign({}, Directives.defaultYaml, yaml);
+ this.tags = Object.assign({}, Directives.defaultTags, tags);
+ }
+ clone() {
+ const copy = new Directives(this.yaml, this.tags);
+ copy.docStart = this.docStart;
+ return copy;
+ }
+ /**
+ * During parsing, get a Directives instance for the current document and
+ * update the stream state according to the current version's spec.
+ */
+ atDocument() {
+ const res = new Directives(this.yaml, this.tags);
+ switch (this.yaml.version) {
+ case '1.1':
+ this.atNextDocument = true;
+ break;
+ case '1.2':
+ this.atNextDocument = false;
+ this.yaml = {
+ explicit: Directives.defaultYaml.explicit,
+ version: '1.2'
+ };
+ this.tags = Object.assign({}, Directives.defaultTags);
+ break;
}
- }
+ return res;
}
-
- // CRLF is appended to the body to function with legacy servers and match other implementations.
- // https://github.com/curl/curl/blob/3434c6b46e682452973972e8313613dfa58cd690/lib/mime.c#L1029-L1030
- // https://github.com/form-data/form-data/issues/63
- const chunk = textEncoder.encode(`--${boundary}--\r\n`)
- blobParts.push(chunk)
- length += chunk.byteLength
- if (hasUnknownSizeValue) {
- length = null
+ /**
+ * @param onError - May be called even if the action was successful
+ * @returns `true` on success
+ */
+ add(line, onError) {
+ if (this.atNextDocument) {
+ this.yaml = { explicit: Directives.defaultYaml.explicit, version: '1.1' };
+ this.tags = Object.assign({}, Directives.defaultTags);
+ this.atNextDocument = false;
+ }
+ const parts = line.trim().split(/[ \t]+/);
+ const name = parts.shift();
+ switch (name) {
+ case '%TAG': {
+ if (parts.length !== 2) {
+ onError(0, '%TAG directive should contain exactly two parts');
+ if (parts.length < 2)
+ return false;
+ }
+ const [handle, prefix] = parts;
+ this.tags[handle] = prefix;
+ return true;
+ }
+ case '%YAML': {
+ this.yaml.explicit = true;
+ if (parts.length !== 1) {
+ onError(0, '%YAML directive should contain exactly one part');
+ return false;
+ }
+ const [version] = parts;
+ if (version === '1.1' || version === '1.2') {
+ this.yaml.version = version;
+ return true;
+ }
+ else {
+ const isValid = /^\d+\.\d+$/.test(version);
+ onError(6, `Unsupported YAML version ${version}`, isValid);
+ return false;
+ }
+ }
+ default:
+ onError(0, `Unknown directive ${name}`, true);
+ return false;
+ }
}
-
- // Set source to object.
- source = object
-
- action = async function * () {
- for (const part of blobParts) {
- if (part.stream) {
- yield * part.stream()
- } else {
- yield part
+ /**
+ * Resolves a tag, matching handles to those defined in %TAG directives.
+ *
+ * @returns Resolved tag, which may also be the non-specific tag `'!'` or a
+ * `'!local'` tag, or `null` if unresolvable.
+ */
+ tagName(source, onError) {
+ if (source === '!')
+ return '!'; // non-specific tag
+ if (source[0] !== '!') {
+ onError(`Not a valid tag: ${source}`);
+ return null;
}
- }
+ if (source[1] === '<') {
+ const verbatim = source.slice(2, -1);
+ if (verbatim === '!' || verbatim === '!!') {
+ onError(`Verbatim tags aren't resolved, so ${source} is invalid.`);
+ return null;
+ }
+ if (source[source.length - 1] !== '>')
+ onError('Verbatim tags must end with a >');
+ return verbatim;
+ }
+ const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s);
+ if (!suffix)
+ onError(`The ${source} tag has no suffix`);
+ const prefix = this.tags[handle];
+ if (prefix) {
+ try {
+ return prefix + decodeURIComponent(suffix);
+ }
+ catch (error) {
+ onError(String(error));
+ return null;
+ }
+ }
+ if (handle === '!')
+ return source; // local tag
+ onError(`Could not resolve tag: ${source}`);
+ return null;
+ }
+ /**
+ * Given a fully resolved tag, returns its printable string form,
+ * taking into account current tag prefixes and defaults.
+ */
+ tagString(tag) {
+ for (const [handle, prefix] of Object.entries(this.tags)) {
+ if (tag.startsWith(prefix))
+ return handle + escapeTagName(tag.substring(prefix.length));
+ }
+ return tag[0] === '!' ? tag : `!<${tag}>`;
+ }
+ toString(doc) {
+ const lines = this.yaml.explicit
+ ? [`%YAML ${this.yaml.version || '1.2'}`]
+ : [];
+ const tagEntries = Object.entries(this.tags);
+ let tagNames;
+ if (doc && tagEntries.length > 0 && identity.isNode(doc.contents)) {
+ const tags = {};
+ visit.visit(doc.contents, (_key, node) => {
+ if (identity.isNode(node) && node.tag)
+ tags[node.tag] = true;
+ });
+ tagNames = Object.keys(tags);
+ }
+ else
+ tagNames = [];
+ for (const [handle, prefix] of tagEntries) {
+ if (handle === '!!' && prefix === 'tag:yaml.org,2002:')
+ continue;
+ if (!doc || tagNames.some(tn => tn.startsWith(prefix)))
+ lines.push(`%TAG ${handle} ${prefix}`);
+ }
+ return lines.join('\n');
}
+}
+Directives.defaultYaml = { explicit: false, version: '1.2' };
+Directives.defaultTags = { '!!': 'tag:yaml.org,2002:' };
- // Set type to `multipart/form-data; boundary=`,
- // followed by the multipart/form-data boundary string generated
- // by the multipart/form-data encoding algorithm.
- type = `multipart/form-data; boundary=${boundary}`
- } else if (isBlobLike(object)) {
- // Blob
+exports.Directives = Directives;
- // Set source to object.
- source = object
- // Set length to object’s size.
- length = object.size
+/***/ }),
- // If object’s type attribute is not the empty byte sequence, set
- // type to its value.
- if (object.type) {
- type = object.type
+/***/ 1464:
+/***/ ((__unused_webpack_module, exports) => {
+
+
+
+class YAMLError extends Error {
+ constructor(name, pos, code, message) {
+ super();
+ this.name = name;
+ this.code = code;
+ this.message = message;
+ this.pos = pos;
}
- } else if (typeof object[Symbol.asyncIterator] === 'function') {
- // If keepalive is true, then throw a TypeError.
- if (keepalive) {
- throw new TypeError('keepalive')
+}
+class YAMLParseError extends YAMLError {
+ constructor(pos, code, message) {
+ super('YAMLParseError', pos, code, message);
}
-
- // If object is disturbed or locked, then throw a TypeError.
- if (util.isDisturbed(object) || object.locked) {
- throw new TypeError(
- 'Response body object should not be disturbed or locked'
- )
+}
+class YAMLWarning extends YAMLError {
+ constructor(pos, code, message) {
+ super('YAMLWarning', pos, code, message);
+ }
+}
+const prettifyError = (src, lc) => (error) => {
+ if (error.pos[0] === -1)
+ return;
+ error.linePos = error.pos.map(pos => lc.linePos(pos));
+ const { line, col } = error.linePos[0];
+ error.message += ` at line ${line}, column ${col}`;
+ let ci = col - 1;
+ let lineStr = src
+ .substring(lc.lineStarts[line - 1], lc.lineStarts[line])
+ .replace(/[\n\r]+$/, '');
+ // Trim to max 80 chars, keeping col position near the middle
+ if (ci >= 60 && lineStr.length > 80) {
+ const trimStart = Math.min(ci - 39, lineStr.length - 79);
+ lineStr = '…' + lineStr.substring(trimStart);
+ ci -= trimStart - 1;
+ }
+ if (lineStr.length > 80)
+ lineStr = lineStr.substring(0, 79) + '…';
+ // Include previous line in context if pointing at line start
+ if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) {
+ // Regexp won't match if start is trimmed
+ let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]);
+ if (prev.length > 80)
+ prev = prev.substring(0, 79) + '…\n';
+ lineStr = prev + lineStr;
+ }
+ if (/[^ ]/.test(lineStr)) {
+ let count = 1;
+ const end = error.linePos[1];
+ if (end?.line === line && end.col > col) {
+ count = Math.max(1, Math.min(end.col - col, 80 - ci));
+ }
+ const pointer = ' '.repeat(ci) + '^'.repeat(count);
+ error.message += `:\n\n${lineStr}\n${pointer}\n`;
}
+};
- stream =
- object instanceof ReadableStream ? object : ReadableStreamFrom(object)
- }
+exports.YAMLError = YAMLError;
+exports.YAMLParseError = YAMLParseError;
+exports.YAMLWarning = YAMLWarning;
+exports.prettifyError = prettifyError;
- // 11. If source is a byte sequence, then set action to a
- // step that returns source and length to source’s length.
- if (typeof source === 'string' || util.isBuffer(source)) {
- length = Buffer.byteLength(source)
- }
- // 12. If action is non-null, then run these steps in in parallel:
- if (action != null) {
- // Run action.
- let iterator
- stream = new ReadableStream({
- async start () {
- iterator = action(object)[Symbol.asyncIterator]()
- },
- async pull (controller) {
- const { value, done } = await iterator.next()
- if (done) {
- // When running action is done, close stream.
- queueMicrotask(() => {
- controller.close()
- controller.byobRequest?.respond(0)
- })
- } else {
- // Whenever one or more bytes are available and stream is not errored,
- // enqueue a Uint8Array wrapping an ArrayBuffer containing the available
- // bytes into stream.
- if (!isErrored(stream)) {
- const buffer = new Uint8Array(value)
- if (buffer.byteLength) {
- controller.enqueue(buffer)
- }
- }
- }
- return controller.desiredSize > 0
- },
- async cancel (reason) {
- await iterator.return()
- },
- type: 'bytes'
- })
- }
+/***/ }),
- // 13. Let body be a body whose stream is stream, source is source,
- // and length is length.
- const body = { stream, source, length }
+/***/ 8815:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 14. Return (body, type).
- return [body, type]
-}
-// https://fetch.spec.whatwg.org/#bodyinit-safely-extract
-function safelyExtractBody (object, keepalive = false) {
- // To safely extract a body and a `Content-Type` value from
- // a byte sequence or BodyInit object object, run these steps:
- // 1. If object is a ReadableStream object, then:
- if (object instanceof ReadableStream) {
- // Assert: object is neither disturbed nor locked.
- // istanbul ignore next
- assert(!util.isDisturbed(object), 'The body has already been consumed.')
- // istanbul ignore next
- assert(!object.locked, 'The stream is locked.')
- }
+var composer = __nccwpck_require__(9984);
+var Document = __nccwpck_require__(3021);
+var Schema = __nccwpck_require__(5840);
+var errors = __nccwpck_require__(1464);
+var Alias = __nccwpck_require__(4065);
+var identity = __nccwpck_require__(1127);
+var Pair = __nccwpck_require__(7165);
+var Scalar = __nccwpck_require__(3301);
+var YAMLMap = __nccwpck_require__(4454);
+var YAMLSeq = __nccwpck_require__(2223);
+var cst = __nccwpck_require__(3461);
+var lexer = __nccwpck_require__(361);
+var lineCounter = __nccwpck_require__(6628);
+var parser = __nccwpck_require__(3456);
+var publicApi = __nccwpck_require__(4047);
+var visit = __nccwpck_require__(204);
- // 2. Return the results of extracting object.
- return extractBody(object, keepalive)
-}
-function cloneBody (instance, body) {
- // To clone a body body, run these steps:
- // https://fetch.spec.whatwg.org/#concept-body-clone
+exports.Composer = composer.Composer;
+exports.Document = Document.Document;
+exports.Schema = Schema.Schema;
+exports.YAMLError = errors.YAMLError;
+exports.YAMLParseError = errors.YAMLParseError;
+exports.YAMLWarning = errors.YAMLWarning;
+exports.Alias = Alias.Alias;
+exports.isAlias = identity.isAlias;
+exports.isCollection = identity.isCollection;
+exports.isDocument = identity.isDocument;
+exports.isMap = identity.isMap;
+exports.isNode = identity.isNode;
+exports.isPair = identity.isPair;
+exports.isScalar = identity.isScalar;
+exports.isSeq = identity.isSeq;
+exports.Pair = Pair.Pair;
+exports.Scalar = Scalar.Scalar;
+exports.YAMLMap = YAMLMap.YAMLMap;
+exports.YAMLSeq = YAMLSeq.YAMLSeq;
+exports.CST = cst;
+exports.Lexer = lexer.Lexer;
+exports.LineCounter = lineCounter.LineCounter;
+exports.Parser = parser.Parser;
+exports.parse = publicApi.parse;
+exports.parseAllDocuments = publicApi.parseAllDocuments;
+exports.parseDocument = publicApi.parseDocument;
+exports.stringify = publicApi.stringify;
+exports.visit = visit.visit;
+exports.visitAsync = visit.visitAsync;
- // 1. Let « out1, out2 » be the result of teeing body’s stream.
- const [out1, out2] = body.stream.tee()
- // 2. Set body’s stream to out1.
- body.stream = out1
+/***/ }),
- // 3. Return a body whose stream is out2 and other members are copied from body.
- return {
- stream: out2,
- length: body.length,
- source: body.source
- }
-}
+/***/ 7249:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-function throwIfAborted (state) {
- if (state.aborted) {
- throw new DOMException('The operation was aborted.', 'AbortError')
- }
-}
-function bodyMixinMethods (instance) {
- const methods = {
- blob () {
- // The blob() method steps are to return the result of
- // running consume body with this and the following step
- // given a byte sequence bytes: return a Blob whose
- // contents are bytes and whose type attribute is this’s
- // MIME type.
- return consumeBody(this, (bytes) => {
- let mimeType = bodyMimeType(this)
- if (mimeType === null) {
- mimeType = ''
- } else if (mimeType) {
- mimeType = serializeAMimeType(mimeType)
- }
+var node_process = __nccwpck_require__(932);
- // Return a Blob whose contents are bytes and type attribute
- // is mimeType.
- return new Blob([bytes], { type: mimeType })
- }, instance)
- },
+function debug(logLevel, ...messages) {
+ if (logLevel === 'debug')
+ console.log(...messages);
+}
+function warn(logLevel, warning) {
+ if (logLevel === 'debug' || logLevel === 'warn') {
+ if (typeof node_process.emitWarning === 'function')
+ node_process.emitWarning(warning);
+ else
+ console.warn(warning);
+ }
+}
- arrayBuffer () {
- // The arrayBuffer() method steps are to return the result
- // of running consume body with this and the following step
- // given a byte sequence bytes: return a new ArrayBuffer
- // whose contents are bytes.
- return consumeBody(this, (bytes) => {
- return new Uint8Array(bytes).buffer
- }, instance)
- },
+exports.debug = debug;
+exports.warn = warn;
- text () {
- // The text() method steps are to return the result of running
- // consume body with this and UTF-8 decode.
- return consumeBody(this, utf8DecodeBytes, instance)
- },
- json () {
- // The json() method steps are to return the result of running
- // consume body with this and parse JSON from bytes.
- return consumeBody(this, parseJSONFromBytes, instance)
- },
+/***/ }),
- formData () {
- // The formData() method steps are to return the result of running
- // consume body with this and the following step given a byte sequence bytes:
- return consumeBody(this, (value) => {
- // 1. Let mimeType be the result of get the MIME type with this.
- const mimeType = bodyMimeType(this)
+/***/ 4065:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 2. If mimeType is non-null, then switch on mimeType’s essence and run
- // the corresponding steps:
- if (mimeType !== null) {
- switch (mimeType.essence) {
- case 'multipart/form-data': {
- // 1. ... [long step]
- const parsed = multipartFormDataParser(value, mimeType)
- // 2. If that fails for some reason, then throw a TypeError.
- if (parsed === 'failure') {
- throw new TypeError('Failed to parse body as FormData.')
- }
- // 3. Return a new FormData object, appending each entry,
- // resulting from the parsing operation, to its entry list.
- const fd = new FormData()
- fd[kState] = parsed
+var anchors = __nccwpck_require__(1596);
+var visit = __nccwpck_require__(204);
+var identity = __nccwpck_require__(1127);
+var Node = __nccwpck_require__(6673);
+var toJS = __nccwpck_require__(6424);
- return fd
+class Alias extends Node.NodeBase {
+ constructor(source) {
+ super(identity.ALIAS);
+ this.source = source;
+ Object.defineProperty(this, 'tag', {
+ set() {
+ throw new Error('Alias nodes cannot have tags');
}
- case 'application/x-www-form-urlencoded': {
- // 1. Let entries be the result of parsing bytes.
- const entries = new URLSearchParams(value.toString())
-
- // 2. If entries is failure, then throw a TypeError.
-
- // 3. Return a new FormData object whose entry list is entries.
- const fd = new FormData()
-
- for (const [name, value] of entries) {
- fd.append(name, value)
- }
-
- return fd
+ });
+ }
+ /**
+ * Resolve the value of this alias within `doc`, finding the last
+ * instance of the `source` anchor before this node.
+ */
+ resolve(doc, ctx) {
+ if (ctx?.maxAliasCount === 0)
+ throw new ReferenceError('Alias resolution is disabled');
+ let nodes;
+ if (ctx?.aliasResolveCache) {
+ nodes = ctx.aliasResolveCache;
+ }
+ else {
+ nodes = [];
+ visit.visit(doc, {
+ Node: (_key, node) => {
+ if (identity.isAlias(node) || identity.hasAnchor(node))
+ nodes.push(node);
+ }
+ });
+ if (ctx)
+ ctx.aliasResolveCache = nodes;
+ }
+ let found = undefined;
+ for (const node of nodes) {
+ if (node === this)
+ break;
+ if (node.anchor === this.source)
+ found = node;
+ }
+ return found;
+ }
+ toJSON(_arg, ctx) {
+ if (!ctx)
+ return { source: this.source };
+ const { anchors, doc, maxAliasCount } = ctx;
+ const source = this.resolve(doc, ctx);
+ if (!source) {
+ const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
+ throw new ReferenceError(msg);
+ }
+ let data = anchors.get(source);
+ if (!data) {
+ // Resolve anchors for Node.prototype.toJS()
+ toJS.toJS(source, null, ctx);
+ data = anchors.get(source);
+ }
+ /* istanbul ignore if */
+ if (data?.res === undefined) {
+ const msg = 'This should not happen: Alias anchor was not resolved?';
+ throw new ReferenceError(msg);
+ }
+ if (maxAliasCount >= 0) {
+ data.count += 1;
+ if (data.aliasCount === 0)
+ data.aliasCount = getAliasCount(doc, source, anchors);
+ if (data.count * data.aliasCount > maxAliasCount) {
+ const msg = 'Excessive alias count indicates a resource exhaustion attack';
+ throw new ReferenceError(msg);
}
- }
}
-
- // 3. Throw a TypeError.
- throw new TypeError(
- 'Content-Type was not one of "multipart/form-data" or "application/x-www-form-urlencoded".'
- )
- }, instance)
- },
-
- bytes () {
- // The bytes() method steps are to return the result of running consume body
- // with this and the following step given a byte sequence bytes: return the
- // result of creating a Uint8Array from bytes in this’s relevant realm.
- return consumeBody(this, (bytes) => {
- return new Uint8Array(bytes)
- }, instance)
+ return data.res;
+ }
+ toString(ctx, _onComment, _onChompKeep) {
+ const src = `*${this.source}`;
+ if (ctx) {
+ anchors.anchorIsValid(this.source);
+ if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) {
+ const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
+ throw new Error(msg);
+ }
+ if (ctx.implicitKey)
+ return `${src} `;
+ }
+ return src;
}
- }
-
- return methods
}
-
-function mixinBody (prototype) {
- Object.assign(prototype.prototype, bodyMixinMethods(prototype))
+function getAliasCount(doc, node, anchors) {
+ if (identity.isAlias(node)) {
+ const source = node.resolve(doc);
+ const anchor = anchors && source && anchors.get(source);
+ return anchor ? anchor.count * anchor.aliasCount : 0;
+ }
+ else if (identity.isCollection(node)) {
+ let count = 0;
+ for (const item of node.items) {
+ const c = getAliasCount(doc, item, anchors);
+ if (c > count)
+ count = c;
+ }
+ return count;
+ }
+ else if (identity.isPair(node)) {
+ const kc = getAliasCount(doc, node.key, anchors);
+ const vc = getAliasCount(doc, node.value, anchors);
+ return Math.max(kc, vc);
+ }
+ return 1;
}
-/**
- * @see https://fetch.spec.whatwg.org/#concept-body-consume-body
- * @param {Response|Request} object
- * @param {(value: unknown) => unknown} convertBytesToJSValue
- * @param {Response|Request} instance
- */
-async function consumeBody (object, convertBytesToJSValue, instance) {
- webidl.brandCheck(object, instance)
-
- // 1. If object is unusable, then return a promise rejected
- // with a TypeError.
- if (bodyUnusable(object)) {
- throw new TypeError('Body is unusable: Body has already been read')
- }
+exports.Alias = Alias;
- throwIfAborted(object[kState])
- // 2. Let promise be a new promise.
- const promise = createDeferredPromise()
+/***/ }),
- // 3. Let errorSteps given error be to reject promise with error.
- const errorSteps = (error) => promise.reject(error)
+/***/ 101:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 4. Let successSteps given a byte sequence data be to resolve
- // promise with the result of running convertBytesToJSValue
- // with data. If that threw an exception, then run errorSteps
- // with that exception.
- const successSteps = (data) => {
- try {
- promise.resolve(convertBytesToJSValue(data))
- } catch (e) {
- errorSteps(e)
- }
- }
- // 5. If object’s body is null, then run successSteps with an
- // empty byte sequence.
- if (object[kState].body == null) {
- successSteps(Buffer.allocUnsafe(0))
- return promise.promise
- }
- // 6. Otherwise, fully read object’s body given successSteps,
- // errorSteps, and object’s relevant global object.
- await fullyReadBody(object[kState].body, successSteps, errorSteps)
+var createNode = __nccwpck_require__(2404);
+var identity = __nccwpck_require__(1127);
+var Node = __nccwpck_require__(6673);
- // 7. Return promise.
- return promise.promise
+function collectionFromPath(schema, path, value) {
+ let v = value;
+ for (let i = path.length - 1; i >= 0; --i) {
+ const k = path[i];
+ if (typeof k === 'number' && Number.isInteger(k) && k >= 0) {
+ const a = [];
+ a[k] = v;
+ v = a;
+ }
+ else {
+ v = new Map([[k, v]]);
+ }
+ }
+ return createNode.createNode(v, undefined, {
+ aliasDuplicateObjects: false,
+ keepUndefined: false,
+ onAnchor: () => {
+ throw new Error('This should not happen, please report a bug.');
+ },
+ schema,
+ sourceObjects: new Map()
+ });
+}
+// Type guard is intentionally a little wrong so as to be more useful,
+// as it does not cover untypable empty non-string iterables (e.g. []).
+const isEmptyPath = (path) => path == null ||
+ (typeof path === 'object' && !!path[Symbol.iterator]().next().done);
+class Collection extends Node.NodeBase {
+ constructor(type, schema) {
+ super(type);
+ Object.defineProperty(this, 'schema', {
+ value: schema,
+ configurable: true,
+ enumerable: false,
+ writable: true
+ });
+ }
+ /**
+ * Create a copy of this collection.
+ *
+ * @param schema - If defined, overwrites the original's schema
+ */
+ clone(schema) {
+ const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
+ if (schema)
+ copy.schema = schema;
+ copy.items = copy.items.map(it => identity.isNode(it) || identity.isPair(it) ? it.clone(schema) : it);
+ if (this.range)
+ copy.range = this.range.slice();
+ return copy;
+ }
+ /**
+ * Adds a value to the collection. For `!!map` and `!!omap` the value must
+ * be a Pair instance or a `{ key, value }` object, which may not have a key
+ * that already exists in the map.
+ */
+ addIn(path, value) {
+ if (isEmptyPath(path))
+ this.add(value);
+ else {
+ const [key, ...rest] = path;
+ const node = this.get(key, true);
+ if (identity.isCollection(node))
+ node.addIn(rest, value);
+ else if (node === undefined && this.schema)
+ this.set(key, collectionFromPath(this.schema, rest, value));
+ else
+ throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
+ }
+ }
+ /**
+ * Removes a value from the collection.
+ * @returns `true` if the item was found and removed.
+ */
+ deleteIn(path) {
+ const [key, ...rest] = path;
+ if (rest.length === 0)
+ return this.delete(key);
+ const node = this.get(key, true);
+ if (identity.isCollection(node))
+ return node.deleteIn(rest);
+ else
+ throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
+ }
+ /**
+ * Returns item at `key`, or `undefined` if not found. By default unwraps
+ * scalar values from their surrounding node; to disable set `keepScalar` to
+ * `true` (collections are always returned intact).
+ */
+ getIn(path, keepScalar) {
+ const [key, ...rest] = path;
+ const node = this.get(key, true);
+ if (rest.length === 0)
+ return !keepScalar && identity.isScalar(node) ? node.value : node;
+ else
+ return identity.isCollection(node) ? node.getIn(rest, keepScalar) : undefined;
+ }
+ hasAllNullValues(allowScalar) {
+ return this.items.every(node => {
+ if (!identity.isPair(node))
+ return false;
+ const n = node.value;
+ return (n == null ||
+ (allowScalar &&
+ identity.isScalar(n) &&
+ n.value == null &&
+ !n.commentBefore &&
+ !n.comment &&
+ !n.tag));
+ });
+ }
+ /**
+ * Checks if the collection includes a value with the key `key`.
+ */
+ hasIn(path) {
+ const [key, ...rest] = path;
+ if (rest.length === 0)
+ return this.has(key);
+ const node = this.get(key, true);
+ return identity.isCollection(node) ? node.hasIn(rest) : false;
+ }
+ /**
+ * Sets a value in this collection. For `!!set`, `value` needs to be a
+ * boolean to add/remove the item from the set.
+ */
+ setIn(path, value) {
+ const [key, ...rest] = path;
+ if (rest.length === 0) {
+ this.set(key, value);
+ }
+ else {
+ const node = this.get(key, true);
+ if (identity.isCollection(node))
+ node.setIn(rest, value);
+ else if (node === undefined && this.schema)
+ this.set(key, collectionFromPath(this.schema, rest, value));
+ else
+ throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
+ }
+ }
}
-// https://fetch.spec.whatwg.org/#body-unusable
-function bodyUnusable (object) {
- const body = object[kState].body
+exports.Collection = Collection;
+exports.collectionFromPath = collectionFromPath;
+exports.isEmptyPath = isEmptyPath;
- // An object including the Body interface mixin is
- // said to be unusable if its body is non-null and
- // its body’s stream is disturbed or locked.
- return body != null && (body.stream.locked || util.isDisturbed(body.stream))
-}
-/**
- * @see https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value
- * @param {Uint8Array} bytes
- */
-function parseJSONFromBytes (bytes) {
- return JSON.parse(utf8DecodeBytes(bytes))
-}
+/***/ }),
-/**
- * @see https://fetch.spec.whatwg.org/#concept-body-mime-type
- * @param {import('./response').Response|import('./request').Request} requestOrResponse
- */
-function bodyMimeType (requestOrResponse) {
- // 1. Let headers be null.
- // 2. If requestOrResponse is a Request object, then set headers to requestOrResponse’s request’s header list.
- // 3. Otherwise, set headers to requestOrResponse’s response’s header list.
- /** @type {import('./headers').HeadersList} */
- const headers = requestOrResponse[kState].headersList
+/***/ 6673:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 4. Let mimeType be the result of extracting a MIME type from headers.
- const mimeType = extractMimeType(headers)
- // 5. If mimeType is failure, then return null.
- if (mimeType === 'failure') {
- return null
- }
- // 6. Return mimeType.
- return mimeType
-}
+var applyReviver = __nccwpck_require__(3661);
+var identity = __nccwpck_require__(1127);
+var toJS = __nccwpck_require__(6424);
-module.exports = {
- extractBody,
- safelyExtractBody,
- cloneBody,
- mixinBody,
- streamRegistry,
- hasFinalizationRegistry,
- bodyUnusable
+class NodeBase {
+ constructor(type) {
+ Object.defineProperty(this, identity.NODE_TYPE, { value: type });
+ }
+ /** Create a copy of this node. */
+ clone() {
+ const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
+ if (this.range)
+ copy.range = this.range.slice();
+ return copy;
+ }
+ /** A plain JavaScript representation of this node. */
+ toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
+ if (!identity.isDocument(doc))
+ throw new TypeError('A document argument is required');
+ const ctx = {
+ anchors: new Map(),
+ doc,
+ keep: true,
+ mapAsMap: mapAsMap === true,
+ mapKeyWarned: false,
+ maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100
+ };
+ const res = toJS.toJS(this, '', ctx);
+ if (typeof onAnchor === 'function')
+ for (const { count, res } of ctx.anchors.values())
+ onAnchor(res, count);
+ return typeof reviver === 'function'
+ ? applyReviver.applyReviver(reviver, { '': res }, '', res)
+ : res;
+ }
}
+exports.NodeBase = NodeBase;
-/***/ }),
-/***/ 1207:
-/***/ ((module) => {
+/***/ }),
+/***/ 7165:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-const corsSafeListedMethods = /** @type {const} */ (['GET', 'HEAD', 'POST'])
-const corsSafeListedMethodsSet = new Set(corsSafeListedMethods)
-const nullBodyStatus = /** @type {const} */ ([101, 204, 205, 304])
+var createNode = __nccwpck_require__(2404);
+var stringifyPair = __nccwpck_require__(9748);
+var addPairToJSMap = __nccwpck_require__(7104);
+var identity = __nccwpck_require__(1127);
-const redirectStatus = /** @type {const} */ ([301, 302, 303, 307, 308])
-const redirectStatusSet = new Set(redirectStatus)
+function createPair(key, value, ctx) {
+ const k = createNode.createNode(key, undefined, ctx);
+ const v = createNode.createNode(value, undefined, ctx);
+ return new Pair(k, v);
+}
+class Pair {
+ constructor(key, value = null) {
+ Object.defineProperty(this, identity.NODE_TYPE, { value: identity.PAIR });
+ this.key = key;
+ this.value = value;
+ }
+ clone(schema) {
+ let { key, value } = this;
+ if (identity.isNode(key))
+ key = key.clone(schema);
+ if (identity.isNode(value))
+ value = value.clone(schema);
+ return new Pair(key, value);
+ }
+ toJSON(_, ctx) {
+ const pair = ctx?.mapAsMap ? new Map() : {};
+ return addPairToJSMap.addPairToJSMap(ctx, pair, this);
+ }
+ toString(ctx, onComment, onChompKeep) {
+ return ctx?.doc
+ ? stringifyPair.stringifyPair(this, ctx, onComment, onChompKeep)
+ : JSON.stringify(this);
+ }
+}
-/**
- * @see https://fetch.spec.whatwg.org/#block-bad-port
- */
-const badPorts = /** @type {const} */ ([
- '1', '7', '9', '11', '13', '15', '17', '19', '20', '21', '22', '23', '25', '37', '42', '43', '53', '69', '77', '79',
- '87', '95', '101', '102', '103', '104', '109', '110', '111', '113', '115', '117', '119', '123', '135', '137',
- '139', '143', '161', '179', '389', '427', '465', '512', '513', '514', '515', '526', '530', '531', '532',
- '540', '548', '554', '556', '563', '587', '601', '636', '989', '990', '993', '995', '1719', '1720', '1723',
- '2049', '3659', '4045', '4190', '5060', '5061', '6000', '6566', '6665', '6666', '6667', '6668', '6669', '6679',
- '6697', '10080'
-])
-const badPortsSet = new Set(badPorts)
+exports.Pair = Pair;
+exports.createPair = createPair;
-/**
- * @see https://w3c.github.io/webappsec-referrer-policy/#referrer-policies
- */
-const referrerPolicy = /** @type {const} */ ([
- '',
- 'no-referrer',
- 'no-referrer-when-downgrade',
- 'same-origin',
- 'origin',
- 'strict-origin',
- 'origin-when-cross-origin',
- 'strict-origin-when-cross-origin',
- 'unsafe-url'
-])
-const referrerPolicySet = new Set(referrerPolicy)
-const requestRedirect = /** @type {const} */ (['follow', 'manual', 'error'])
+/***/ }),
-const safeMethods = /** @type {const} */ (['GET', 'HEAD', 'OPTIONS', 'TRACE'])
-const safeMethodsSet = new Set(safeMethods)
+/***/ 3301:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-const requestMode = /** @type {const} */ (['navigate', 'same-origin', 'no-cors', 'cors'])
-const requestCredentials = /** @type {const} */ (['omit', 'same-origin', 'include'])
-const requestCache = /** @type {const} */ ([
- 'default',
- 'no-store',
- 'reload',
- 'no-cache',
- 'force-cache',
- 'only-if-cached'
-])
+var identity = __nccwpck_require__(1127);
+var Node = __nccwpck_require__(6673);
+var toJS = __nccwpck_require__(6424);
-/**
- * @see https://fetch.spec.whatwg.org/#request-body-header-name
- */
-const requestBodyHeader = /** @type {const} */ ([
- 'content-encoding',
- 'content-language',
- 'content-location',
- 'content-type',
- // See https://github.com/nodejs/undici/issues/2021
- // 'Content-Length' is a forbidden header name, which is typically
- // removed in the Headers implementation. However, undici doesn't
- // filter out headers, so we add it here.
- 'content-length'
-])
-
-/**
- * @see https://fetch.spec.whatwg.org/#enumdef-requestduplex
- */
-const requestDuplex = /** @type {const} */ ([
- 'half'
-])
-
-/**
- * @see http://fetch.spec.whatwg.org/#forbidden-method
- */
-const forbiddenMethods = /** @type {const} */ (['CONNECT', 'TRACE', 'TRACK'])
-const forbiddenMethodsSet = new Set(forbiddenMethods)
-
-const subresource = /** @type {const} */ ([
- 'audio',
- 'audioworklet',
- 'font',
- 'image',
- 'manifest',
- 'paintworklet',
- 'script',
- 'style',
- 'track',
- 'video',
- 'xslt',
- ''
-])
-const subresourceSet = new Set(subresource)
-
-module.exports = {
- subresource,
- forbiddenMethods,
- requestBodyHeader,
- referrerPolicy,
- requestRedirect,
- requestMode,
- requestCredentials,
- requestCache,
- redirectStatus,
- corsSafeListedMethods,
- nullBodyStatus,
- safeMethods,
- badPorts,
- requestDuplex,
- subresourceSet,
- badPortsSet,
- redirectStatusSet,
- corsSafeListedMethodsSet,
- safeMethodsSet,
- forbiddenMethodsSet,
- referrerPolicySet
+const isScalarValue = (value) => !value || (typeof value !== 'function' && typeof value !== 'object');
+class Scalar extends Node.NodeBase {
+ constructor(value) {
+ super(identity.SCALAR);
+ this.value = value;
+ }
+ toJSON(arg, ctx) {
+ return ctx?.keep ? this.value : toJS.toJS(this.value, arg, ctx);
+ }
+ toString() {
+ return String(this.value);
+ }
}
+Scalar.BLOCK_FOLDED = 'BLOCK_FOLDED';
+Scalar.BLOCK_LITERAL = 'BLOCK_LITERAL';
+Scalar.PLAIN = 'PLAIN';
+Scalar.QUOTE_DOUBLE = 'QUOTE_DOUBLE';
+Scalar.QUOTE_SINGLE = 'QUOTE_SINGLE';
+exports.Scalar = Scalar;
+exports.isScalarValue = isScalarValue;
-/***/ }),
-
-/***/ 980:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ }),
+/***/ 4454:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-const assert = __nccwpck_require__(4589)
-const encoder = new TextEncoder()
-/**
- * @see https://mimesniff.spec.whatwg.org/#http-token-code-point
- */
-const HTTP_TOKEN_CODEPOINTS = /^[!#$%&'*+\-.^_|~A-Za-z0-9]+$/
-const HTTP_WHITESPACE_REGEX = /[\u000A\u000D\u0009\u0020]/ // eslint-disable-line
-const ASCII_WHITESPACE_REPLACE_REGEX = /[\u0009\u000A\u000C\u000D\u0020]/g // eslint-disable-line
-/**
- * @see https://mimesniff.spec.whatwg.org/#http-quoted-string-token-code-point
- */
-const HTTP_QUOTED_STRING_TOKENS = /^[\u0009\u0020-\u007E\u0080-\u00FF]+$/ // eslint-disable-line
+var stringifyCollection = __nccwpck_require__(1212);
+var addPairToJSMap = __nccwpck_require__(7104);
+var Collection = __nccwpck_require__(101);
+var identity = __nccwpck_require__(1127);
+var Pair = __nccwpck_require__(7165);
+var Scalar = __nccwpck_require__(3301);
-// https://fetch.spec.whatwg.org/#data-url-processor
-/** @param {URL} dataURL */
-function dataURLProcessor (dataURL) {
- // 1. Assert: dataURL’s scheme is "data".
- assert(dataURL.protocol === 'data:')
+function findPair(items, key) {
+ const k = identity.isScalar(key) ? key.value : key;
+ for (const it of items) {
+ if (identity.isPair(it)) {
+ if (it.key === key || it.key === k)
+ return it;
+ if (identity.isScalar(it.key) && it.key.value === k)
+ return it;
+ }
+ }
+ return undefined;
+}
+class YAMLMap extends Collection.Collection {
+ static get tagName() {
+ return 'tag:yaml.org,2002:map';
+ }
+ constructor(schema) {
+ super(identity.MAP, schema);
+ this.items = [];
+ }
+ /**
+ * A generic collection parsing method that can be extended
+ * to other node classes that inherit from YAMLMap
+ */
+ static from(schema, obj, ctx) {
+ const { keepUndefined, replacer } = ctx;
+ const map = new this(schema);
+ const add = (key, value) => {
+ if (typeof replacer === 'function')
+ value = replacer.call(obj, key, value);
+ else if (Array.isArray(replacer) && !replacer.includes(key))
+ return;
+ if (value !== undefined || keepUndefined)
+ map.items.push(Pair.createPair(key, value, ctx));
+ };
+ if (obj instanceof Map) {
+ for (const [key, value] of obj)
+ add(key, value);
+ }
+ else if (obj && typeof obj === 'object') {
+ for (const key of Object.keys(obj))
+ add(key, obj[key]);
+ }
+ if (typeof schema.sortMapEntries === 'function') {
+ map.items.sort(schema.sortMapEntries);
+ }
+ return map;
+ }
+ /**
+ * Adds a value to the collection.
+ *
+ * @param overwrite - If not set `true`, using a key that is already in the
+ * collection will throw. Otherwise, overwrites the previous value.
+ */
+ add(pair, overwrite) {
+ let _pair;
+ if (identity.isPair(pair))
+ _pair = pair;
+ else if (!pair || typeof pair !== 'object' || !('key' in pair)) {
+ // In TypeScript, this never happens.
+ _pair = new Pair.Pair(pair, pair?.value);
+ }
+ else
+ _pair = new Pair.Pair(pair.key, pair.value);
+ const prev = findPair(this.items, _pair.key);
+ const sortEntries = this.schema?.sortMapEntries;
+ if (prev) {
+ if (!overwrite)
+ throw new Error(`Key ${_pair.key} already set`);
+ // For scalars, keep the old node & its comments and anchors
+ if (identity.isScalar(prev.value) && Scalar.isScalarValue(_pair.value))
+ prev.value.value = _pair.value;
+ else
+ prev.value = _pair.value;
+ }
+ else if (sortEntries) {
+ const i = this.items.findIndex(item => sortEntries(_pair, item) < 0);
+ if (i === -1)
+ this.items.push(_pair);
+ else
+ this.items.splice(i, 0, _pair);
+ }
+ else {
+ this.items.push(_pair);
+ }
+ }
+ delete(key) {
+ const it = findPair(this.items, key);
+ if (!it)
+ return false;
+ const del = this.items.splice(this.items.indexOf(it), 1);
+ return del.length > 0;
+ }
+ get(key, keepScalar) {
+ const it = findPair(this.items, key);
+ const node = it?.value;
+ return (!keepScalar && identity.isScalar(node) ? node.value : node) ?? undefined;
+ }
+ has(key) {
+ return !!findPair(this.items, key);
+ }
+ set(key, value) {
+ this.add(new Pair.Pair(key, value), true);
+ }
+ /**
+ * @param ctx - Conversion context, originally set in Document#toJS()
+ * @param {Class} Type - If set, forces the returned collection type
+ * @returns Instance of Type, Map, or Object
+ */
+ toJSON(_, ctx, Type) {
+ const map = Type ? new Type() : ctx?.mapAsMap ? new Map() : {};
+ if (ctx?.onCreate)
+ ctx.onCreate(map);
+ for (const item of this.items)
+ addPairToJSMap.addPairToJSMap(ctx, map, item);
+ return map;
+ }
+ toString(ctx, onComment, onChompKeep) {
+ if (!ctx)
+ return JSON.stringify(this);
+ for (const item of this.items) {
+ if (!identity.isPair(item))
+ throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`);
+ }
+ if (!ctx.allNullValues && this.hasAllNullValues(false))
+ ctx = Object.assign({}, ctx, { allNullValues: true });
+ return stringifyCollection.stringifyCollection(this, ctx, {
+ blockItemPrefix: '',
+ flowChars: { start: '{', end: '}' },
+ itemIndent: ctx.indent || '',
+ onChompKeep,
+ onComment
+ });
+ }
+}
- // 2. Let input be the result of running the URL
- // serializer on dataURL with exclude fragment
- // set to true.
- let input = URLSerializer(dataURL, true)
+exports.YAMLMap = YAMLMap;
+exports.findPair = findPair;
- // 3. Remove the leading "data:" string from input.
- input = input.slice(5)
- // 4. Let position point at the start of input.
- const position = { position: 0 }
+/***/ }),
- // 5. Let mimeType be the result of collecting a
- // sequence of code points that are not equal
- // to U+002C (,), given position.
- let mimeType = collectASequenceOfCodePointsFast(
- ',',
- input,
- position
- )
+/***/ 2223:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 6. Strip leading and trailing ASCII whitespace
- // from mimeType.
- // Undici implementation note: we need to store the
- // length because if the mimetype has spaces removed,
- // the wrong amount will be sliced from the input in
- // step #9
- const mimeTypeLength = mimeType.length
- mimeType = removeASCIIWhitespace(mimeType, true, true)
- // 7. If position is past the end of input, then
- // return failure
- if (position.position >= input.length) {
- return 'failure'
- }
- // 8. Advance position by 1.
- position.position++
+var createNode = __nccwpck_require__(2404);
+var stringifyCollection = __nccwpck_require__(1212);
+var Collection = __nccwpck_require__(101);
+var identity = __nccwpck_require__(1127);
+var Scalar = __nccwpck_require__(3301);
+var toJS = __nccwpck_require__(6424);
- // 9. Let encodedBody be the remainder of input.
- const encodedBody = input.slice(mimeTypeLength + 1)
+class YAMLSeq extends Collection.Collection {
+ static get tagName() {
+ return 'tag:yaml.org,2002:seq';
+ }
+ constructor(schema) {
+ super(identity.SEQ, schema);
+ this.items = [];
+ }
+ add(value) {
+ this.items.push(value);
+ }
+ /**
+ * Removes a value from the collection.
+ *
+ * `key` must contain a representation of an integer for this to succeed.
+ * It may be wrapped in a `Scalar`.
+ *
+ * @returns `true` if the item was found and removed.
+ */
+ delete(key) {
+ const idx = asItemIndex(key);
+ if (typeof idx !== 'number')
+ return false;
+ const del = this.items.splice(idx, 1);
+ return del.length > 0;
+ }
+ get(key, keepScalar) {
+ const idx = asItemIndex(key);
+ if (typeof idx !== 'number')
+ return undefined;
+ const it = this.items[idx];
+ return !keepScalar && identity.isScalar(it) ? it.value : it;
+ }
+ /**
+ * Checks if the collection includes a value with the key `key`.
+ *
+ * `key` must contain a representation of an integer for this to succeed.
+ * It may be wrapped in a `Scalar`.
+ */
+ has(key) {
+ const idx = asItemIndex(key);
+ return typeof idx === 'number' && idx < this.items.length;
+ }
+ /**
+ * Sets a value in this collection. For `!!set`, `value` needs to be a
+ * boolean to add/remove the item from the set.
+ *
+ * If `key` does not contain a representation of an integer, this will throw.
+ * It may be wrapped in a `Scalar`.
+ */
+ set(key, value) {
+ const idx = asItemIndex(key);
+ if (typeof idx !== 'number')
+ throw new Error(`Expected a valid index, not ${key}.`);
+ const prev = this.items[idx];
+ if (identity.isScalar(prev) && Scalar.isScalarValue(value))
+ prev.value = value;
+ else
+ this.items[idx] = value;
+ }
+ toJSON(_, ctx) {
+ const seq = [];
+ if (ctx?.onCreate)
+ ctx.onCreate(seq);
+ let i = 0;
+ for (const item of this.items)
+ seq.push(toJS.toJS(item, String(i++), ctx));
+ return seq;
+ }
+ toString(ctx, onComment, onChompKeep) {
+ if (!ctx)
+ return JSON.stringify(this);
+ return stringifyCollection.stringifyCollection(this, ctx, {
+ blockItemPrefix: '- ',
+ flowChars: { start: '[', end: ']' },
+ itemIndent: (ctx.indent || '') + ' ',
+ onChompKeep,
+ onComment
+ });
+ }
+ static from(schema, obj, ctx) {
+ const { replacer } = ctx;
+ const seq = new this(schema);
+ if (obj && Symbol.iterator in Object(obj)) {
+ let i = 0;
+ for (let it of obj) {
+ if (typeof replacer === 'function') {
+ const key = obj instanceof Set ? it : String(i++);
+ it = replacer.call(obj, key, it);
+ }
+ seq.items.push(createNode.createNode(it, undefined, ctx));
+ }
+ }
+ return seq;
+ }
+}
+function asItemIndex(key) {
+ let idx = identity.isScalar(key) ? key.value : key;
+ if (idx && typeof idx === 'string')
+ idx = Number(idx);
+ return typeof idx === 'number' && Number.isInteger(idx) && idx >= 0
+ ? idx
+ : null;
+}
- // 10. Let body be the percent-decoding of encodedBody.
- let body = stringPercentDecode(encodedBody)
+exports.YAMLSeq = YAMLSeq;
- // 11. If mimeType ends with U+003B (;), followed by
- // zero or more U+0020 SPACE, followed by an ASCII
- // case-insensitive match for "base64", then:
- if (/;(\u0020){0,}base64$/i.test(mimeType)) {
- // 1. Let stringBody be the isomorphic decode of body.
- const stringBody = isomorphicDecode(body)
- // 2. Set body to the forgiving-base64 decode of
- // stringBody.
- body = forgivingBase64(stringBody)
+/***/ }),
- // 3. If body is failure, then return failure.
- if (body === 'failure') {
- return 'failure'
- }
+/***/ 7104:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 4. Remove the last 6 code points from mimeType.
- mimeType = mimeType.slice(0, -6)
- // 5. Remove trailing U+0020 SPACE code points from mimeType,
- // if any.
- mimeType = mimeType.replace(/(\u0020)+$/, '')
- // 6. Remove the last U+003B (;) code point from mimeType.
- mimeType = mimeType.slice(0, -1)
- }
+var log = __nccwpck_require__(7249);
+var merge = __nccwpck_require__(452);
+var stringify = __nccwpck_require__(2148);
+var identity = __nccwpck_require__(1127);
+var toJS = __nccwpck_require__(6424);
- // 12. If mimeType starts with U+003B (;), then prepend
- // "text/plain" to mimeType.
- if (mimeType.startsWith(';')) {
- mimeType = 'text/plain' + mimeType
- }
+function addPairToJSMap(ctx, map, { key, value }) {
+ if (identity.isNode(key) && key.addToJSMap)
+ key.addToJSMap(ctx, map, value);
+ // TODO: Should drop this special case for bare << handling
+ else if (merge.isMergeKey(ctx, key))
+ merge.addMergeToJSMap(ctx, map, value);
+ else {
+ const jsKey = toJS.toJS(key, '', ctx);
+ if (map instanceof Map) {
+ map.set(jsKey, toJS.toJS(value, jsKey, ctx));
+ }
+ else if (map instanceof Set) {
+ map.add(jsKey);
+ }
+ else {
+ const stringKey = stringifyKey(key, jsKey, ctx);
+ const jsValue = toJS.toJS(value, stringKey, ctx);
+ if (stringKey in map)
+ Object.defineProperty(map, stringKey, {
+ value: jsValue,
+ writable: true,
+ enumerable: true,
+ configurable: true
+ });
+ else
+ map[stringKey] = jsValue;
+ }
+ }
+ return map;
+}
+function stringifyKey(key, jsKey, ctx) {
+ if (jsKey === null)
+ return '';
+ // eslint-disable-next-line @typescript-eslint/no-base-to-string
+ if (typeof jsKey !== 'object')
+ return String(jsKey);
+ if (identity.isNode(key) && ctx?.doc) {
+ const strCtx = stringify.createStringifyContext(ctx.doc, {});
+ strCtx.anchors = new Set();
+ for (const node of ctx.anchors.keys())
+ strCtx.anchors.add(node.anchor);
+ strCtx.inFlow = true;
+ strCtx.inStringifyKey = true;
+ const strKey = key.toString(strCtx);
+ if (!ctx.mapKeyWarned) {
+ let jsonStr = JSON.stringify(strKey);
+ if (jsonStr.length > 40)
+ jsonStr = jsonStr.substring(0, 36) + '..."';
+ log.warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`);
+ ctx.mapKeyWarned = true;
+ }
+ return strKey;
+ }
+ return JSON.stringify(jsKey);
+}
- // 13. Let mimeTypeRecord be the result of parsing
- // mimeType.
- let mimeTypeRecord = parseMIMEType(mimeType)
+exports.addPairToJSMap = addPairToJSMap;
- // 14. If mimeTypeRecord is failure, then set
- // mimeTypeRecord to text/plain;charset=US-ASCII.
- if (mimeTypeRecord === 'failure') {
- mimeTypeRecord = parseMIMEType('text/plain;charset=US-ASCII')
- }
- // 15. Return a new data: URL struct whose MIME
- // type is mimeTypeRecord and body is body.
- // https://fetch.spec.whatwg.org/#data-url-struct
- return { mimeType: mimeTypeRecord, body }
-}
+/***/ }),
-// https://url.spec.whatwg.org/#concept-url-serializer
-/**
- * @param {URL} url
- * @param {boolean} excludeFragment
- */
-function URLSerializer (url, excludeFragment = false) {
- if (!excludeFragment) {
- return url.href
- }
+/***/ 1127:
+/***/ ((__unused_webpack_module, exports) => {
- const href = url.href
- const hashLength = url.hash.length
- const serialized = hashLength === 0 ? href : href.substring(0, href.length - hashLength)
- if (!hashLength && href.endsWith('#')) {
- return serialized.slice(0, -1)
- }
-
- return serialized
+const ALIAS = Symbol.for('yaml.alias');
+const DOC = Symbol.for('yaml.document');
+const MAP = Symbol.for('yaml.map');
+const PAIR = Symbol.for('yaml.pair');
+const SCALAR = Symbol.for('yaml.scalar');
+const SEQ = Symbol.for('yaml.seq');
+const NODE_TYPE = Symbol.for('yaml.node.type');
+const isAlias = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === ALIAS;
+const isDocument = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === DOC;
+const isMap = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === MAP;
+const isPair = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === PAIR;
+const isScalar = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SCALAR;
+const isSeq = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SEQ;
+function isCollection(node) {
+ if (node && typeof node === 'object')
+ switch (node[NODE_TYPE]) {
+ case MAP:
+ case SEQ:
+ return true;
+ }
+ return false;
+}
+function isNode(node) {
+ if (node && typeof node === 'object')
+ switch (node[NODE_TYPE]) {
+ case ALIAS:
+ case MAP:
+ case SCALAR:
+ case SEQ:
+ return true;
+ }
+ return false;
}
+const hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor;
-// https://infra.spec.whatwg.org/#collect-a-sequence-of-code-points
-/**
- * @param {(char: string) => boolean} condition
- * @param {string} input
- * @param {{ position: number }} position
- */
-function collectASequenceOfCodePoints (condition, input, position) {
- // 1. Let result be the empty string.
- let result = ''
+exports.ALIAS = ALIAS;
+exports.DOC = DOC;
+exports.MAP = MAP;
+exports.NODE_TYPE = NODE_TYPE;
+exports.PAIR = PAIR;
+exports.SCALAR = SCALAR;
+exports.SEQ = SEQ;
+exports.hasAnchor = hasAnchor;
+exports.isAlias = isAlias;
+exports.isCollection = isCollection;
+exports.isDocument = isDocument;
+exports.isMap = isMap;
+exports.isNode = isNode;
+exports.isPair = isPair;
+exports.isScalar = isScalar;
+exports.isSeq = isSeq;
- // 2. While position doesn’t point past the end of input and the
- // code point at position within input meets the condition condition:
- while (position.position < input.length && condition(input[position.position])) {
- // 1. Append that code point to the end of result.
- result += input[position.position]
- // 2. Advance position by 1.
- position.position++
- }
+/***/ }),
+
+/***/ 6424:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 3. Return result.
- return result
-}
+
+
+var identity = __nccwpck_require__(1127);
/**
- * A faster collectASequenceOfCodePoints that only works when comparing a single character.
- * @param {string} char
- * @param {string} input
- * @param {{ position: number }} position
+ * Recursively convert any node or its contents to native JavaScript
+ *
+ * @param value - The input value
+ * @param arg - If `value` defines a `toJSON()` method, use this
+ * as its first argument
+ * @param ctx - Conversion context, originally set in Document#toJS(). If
+ * `{ keep: true }` is not set, output should be suitable for JSON
+ * stringification.
*/
-function collectASequenceOfCodePointsFast (char, input, position) {
- const idx = input.indexOf(char, position.position)
- const start = position.position
+function toJS(value, arg, ctx) {
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-return
+ if (Array.isArray(value))
+ return value.map((v, i) => toJS(v, String(i), ctx));
+ if (value && typeof value.toJSON === 'function') {
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-call
+ if (!ctx || !identity.hasAnchor(value))
+ return value.toJSON(arg, ctx);
+ const data = { aliasCount: 0, count: 1, res: undefined };
+ ctx.anchors.set(value, data);
+ ctx.onCreate = res => {
+ data.res = res;
+ delete ctx.onCreate;
+ };
+ const res = value.toJSON(arg, ctx);
+ if (ctx.onCreate)
+ ctx.onCreate(res);
+ return res;
+ }
+ if (typeof value === 'bigint' && !ctx?.keep)
+ return Number(value);
+ return value;
+}
- if (idx === -1) {
- position.position = input.length
- return input.slice(start)
- }
+exports.toJS = toJS;
- position.position = idx
- return input.slice(start, position.position)
-}
-// https://url.spec.whatwg.org/#string-percent-decode
-/** @param {string} input */
-function stringPercentDecode (input) {
- // 1. Let bytes be the UTF-8 encoding of input.
- const bytes = encoder.encode(input)
+/***/ }),
- // 2. Return the percent-decoding of bytes.
- return percentDecode(bytes)
-}
+/***/ 110:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+
+var resolveBlockScalar = __nccwpck_require__(8913);
+var resolveFlowScalar = __nccwpck_require__(6842);
+var errors = __nccwpck_require__(1464);
+var stringifyString = __nccwpck_require__(3069);
+
+function resolveAsScalar(token, strict = true, onError) {
+ if (token) {
+ const _onError = (pos, code, message) => {
+ const offset = typeof pos === 'number' ? pos : Array.isArray(pos) ? pos[0] : pos.offset;
+ if (onError)
+ onError(offset, code, message);
+ else
+ throw new errors.YAMLParseError([offset, offset + 1], code, message);
+ };
+ switch (token.type) {
+ case 'scalar':
+ case 'single-quoted-scalar':
+ case 'double-quoted-scalar':
+ return resolveFlowScalar.resolveFlowScalar(token, strict, _onError);
+ case 'block-scalar':
+ return resolveBlockScalar.resolveBlockScalar({ options: { strict } }, token, _onError);
+ }
+ }
+ return null;
+}
/**
- * @param {number} byte
+ * Create a new scalar token with `value`
+ *
+ * Values that represent an actual string but may be parsed as a different type should use a `type` other than `'PLAIN'`,
+ * as this function does not support any schema operations and won't check for such conflicts.
+ *
+ * @param value The string representation of the value, which will have its content properly indented.
+ * @param context.end Comments and whitespace after the end of the value, or after the block scalar header. If undefined, a newline will be added.
+ * @param context.implicitKey Being within an implicit key may affect the resolved type of the token's value.
+ * @param context.indent The indent level of the token.
+ * @param context.inFlow Is this scalar within a flow collection? This may affect the resolved type of the token's value.
+ * @param context.offset The offset position of the token.
+ * @param context.type The preferred type of the scalar token. If undefined, the previous type of the `token` will be used, defaulting to `'PLAIN'`.
*/
-function isHexCharByte (byte) {
- // 0-9 A-F a-f
- return (byte >= 0x30 && byte <= 0x39) || (byte >= 0x41 && byte <= 0x46) || (byte >= 0x61 && byte <= 0x66)
+function createScalarToken(value, context) {
+ const { implicitKey = false, indent, inFlow = false, offset = -1, type = 'PLAIN' } = context;
+ const source = stringifyString.stringifyString({ type, value }, {
+ implicitKey,
+ indent: indent > 0 ? ' '.repeat(indent) : '',
+ inFlow,
+ options: { blockQuote: true, lineWidth: -1 }
+ });
+ const end = context.end ?? [
+ { type: 'newline', offset: -1, indent, source: '\n' }
+ ];
+ switch (source[0]) {
+ case '|':
+ case '>': {
+ const he = source.indexOf('\n');
+ const head = source.substring(0, he);
+ const body = source.substring(he + 1) + '\n';
+ const props = [
+ { type: 'block-scalar-header', offset, indent, source: head }
+ ];
+ if (!addEndtoBlockProps(props, end))
+ props.push({ type: 'newline', offset: -1, indent, source: '\n' });
+ return { type: 'block-scalar', offset, indent, props, source: body };
+ }
+ case '"':
+ return { type: 'double-quoted-scalar', offset, indent, source, end };
+ case "'":
+ return { type: 'single-quoted-scalar', offset, indent, source, end };
+ default:
+ return { type: 'scalar', offset, indent, source, end };
+ }
}
-
/**
- * @param {number} byte
+ * Set the value of `token` to the given string `value`, overwriting any previous contents and type that it may have.
+ *
+ * Best efforts are made to retain any comments previously associated with the `token`,
+ * though all contents within a collection's `items` will be overwritten.
+ *
+ * Values that represent an actual string but may be parsed as a different type should use a `type` other than `'PLAIN'`,
+ * as this function does not support any schema operations and won't check for such conflicts.
+ *
+ * @param token Any token. If it does not include an `indent` value, the value will be stringified as if it were an implicit key.
+ * @param value The string representation of the value, which will have its content properly indented.
+ * @param context.afterKey In most cases, values after a key should have an additional level of indentation.
+ * @param context.implicitKey Being within an implicit key may affect the resolved type of the token's value.
+ * @param context.inFlow Being within a flow collection may affect the resolved type of the token's value.
+ * @param context.type The preferred type of the scalar token. If undefined, the previous type of the `token` will be used, defaulting to `'PLAIN'`.
*/
-function hexByteToNumber (byte) {
- return (
- // 0-9
- byte >= 0x30 && byte <= 0x39
- ? (byte - 48)
- // Convert to uppercase
- // ((byte & 0xDF) - 65) + 10
- : ((byte & 0xDF) - 55)
- )
+function setScalarValue(token, value, context = {}) {
+ let { afterKey = false, implicitKey = false, inFlow = false, type } = context;
+ let indent = 'indent' in token ? token.indent : null;
+ if (afterKey && typeof indent === 'number')
+ indent += 2;
+ if (!type)
+ switch (token.type) {
+ case 'single-quoted-scalar':
+ type = 'QUOTE_SINGLE';
+ break;
+ case 'double-quoted-scalar':
+ type = 'QUOTE_DOUBLE';
+ break;
+ case 'block-scalar': {
+ const header = token.props[0];
+ if (header.type !== 'block-scalar-header')
+ throw new Error('Invalid block scalar header');
+ type = header.source[0] === '>' ? 'BLOCK_FOLDED' : 'BLOCK_LITERAL';
+ break;
+ }
+ default:
+ type = 'PLAIN';
+ }
+ const source = stringifyString.stringifyString({ type, value }, {
+ implicitKey: implicitKey || indent === null,
+ indent: indent !== null && indent > 0 ? ' '.repeat(indent) : '',
+ inFlow,
+ options: { blockQuote: true, lineWidth: -1 }
+ });
+ switch (source[0]) {
+ case '|':
+ case '>':
+ setBlockScalarValue(token, source);
+ break;
+ case '"':
+ setFlowScalarValue(token, source, 'double-quoted-scalar');
+ break;
+ case "'":
+ setFlowScalarValue(token, source, 'single-quoted-scalar');
+ break;
+ default:
+ setFlowScalarValue(token, source, 'scalar');
+ }
+}
+function setBlockScalarValue(token, source) {
+ const he = source.indexOf('\n');
+ const head = source.substring(0, he);
+ const body = source.substring(he + 1) + '\n';
+ if (token.type === 'block-scalar') {
+ const header = token.props[0];
+ if (header.type !== 'block-scalar-header')
+ throw new Error('Invalid block scalar header');
+ header.source = head;
+ token.source = body;
+ }
+ else {
+ const { offset } = token;
+ const indent = 'indent' in token ? token.indent : -1;
+ const props = [
+ { type: 'block-scalar-header', offset, indent, source: head }
+ ];
+ if (!addEndtoBlockProps(props, 'end' in token ? token.end : undefined))
+ props.push({ type: 'newline', offset: -1, indent, source: '\n' });
+ for (const key of Object.keys(token))
+ if (key !== 'type' && key !== 'offset')
+ delete token[key];
+ Object.assign(token, { type: 'block-scalar', indent, props, source: body });
+ }
+}
+/** @returns `true` if last token is a newline */
+function addEndtoBlockProps(props, end) {
+ if (end)
+ for (const st of end)
+ switch (st.type) {
+ case 'space':
+ case 'comment':
+ props.push(st);
+ break;
+ case 'newline':
+ props.push(st);
+ return true;
+ }
+ return false;
+}
+function setFlowScalarValue(token, source, type) {
+ switch (token.type) {
+ case 'scalar':
+ case 'double-quoted-scalar':
+ case 'single-quoted-scalar':
+ token.type = type;
+ token.source = source;
+ break;
+ case 'block-scalar': {
+ const end = token.props.slice(1);
+ let oa = source.length;
+ if (token.props[0].type === 'block-scalar-header')
+ oa -= token.props[0].source.length;
+ for (const tok of end)
+ tok.offset += oa;
+ delete token.props;
+ Object.assign(token, { type, source, end });
+ break;
+ }
+ case 'block-map':
+ case 'block-seq': {
+ const offset = token.offset + source.length;
+ const nl = { type: 'newline', offset, indent: token.indent, source: '\n' };
+ delete token.items;
+ Object.assign(token, { type, source, end: [nl] });
+ break;
+ }
+ default: {
+ const indent = 'indent' in token ? token.indent : -1;
+ const end = 'end' in token && Array.isArray(token.end)
+ ? token.end.filter(st => st.type === 'space' ||
+ st.type === 'comment' ||
+ st.type === 'newline')
+ : [];
+ for (const key of Object.keys(token))
+ if (key !== 'type' && key !== 'offset')
+ delete token[key];
+ Object.assign(token, { type, indent, source, end });
+ }
+ }
}
-// https://url.spec.whatwg.org/#percent-decode
-/** @param {Uint8Array} input */
-function percentDecode (input) {
- const length = input.length
- // 1. Let output be an empty byte sequence.
- /** @type {Uint8Array} */
- const output = new Uint8Array(length)
- let j = 0
- // 2. For each byte byte in input:
- for (let i = 0; i < length; ++i) {
- const byte = input[i]
-
- // 1. If byte is not 0x25 (%), then append byte to output.
- if (byte !== 0x25) {
- output[j++] = byte
-
- // 2. Otherwise, if byte is 0x25 (%) and the next two bytes
- // after byte in input are not in the ranges
- // 0x30 (0) to 0x39 (9), 0x41 (A) to 0x46 (F),
- // and 0x61 (a) to 0x66 (f), all inclusive, append byte
- // to output.
- } else if (
- byte === 0x25 &&
- !(isHexCharByte(input[i + 1]) && isHexCharByte(input[i + 2]))
- ) {
- output[j++] = 0x25
+exports.createScalarToken = createScalarToken;
+exports.resolveAsScalar = resolveAsScalar;
+exports.setScalarValue = setScalarValue;
- // 3. Otherwise:
- } else {
- // 1. Let bytePoint be the two bytes after byte in input,
- // decoded, and then interpreted as hexadecimal number.
- // 2. Append a byte whose value is bytePoint to output.
- output[j++] = (hexByteToNumber(input[i + 1]) << 4) | hexByteToNumber(input[i + 2])
- // 3. Skip the next two bytes in input.
- i += 2
- }
- }
+/***/ }),
- // 3. Return output.
- return length === j ? output : output.subarray(0, j)
-}
+/***/ 1733:
+/***/ ((__unused_webpack_module, exports) => {
-// https://mimesniff.spec.whatwg.org/#parse-a-mime-type
-/** @param {string} input */
-function parseMIMEType (input) {
- // 1. Remove any leading and trailing HTTP whitespace
- // from input.
- input = removeHTTPWhitespace(input, true, true)
- // 2. Let position be a position variable for input,
- // initially pointing at the start of input.
- const position = { position: 0 }
- // 3. Let type be the result of collecting a sequence
- // of code points that are not U+002F (/) from
- // input, given position.
- const type = collectASequenceOfCodePointsFast(
- '/',
- input,
- position
- )
+/**
+ * Stringify a CST document, token, or collection item
+ *
+ * Fair warning: This applies no validation whatsoever, and
+ * simply concatenates the sources in their logical order.
+ */
+const stringify = (cst) => 'type' in cst ? stringifyToken(cst) : stringifyItem(cst);
+function stringifyToken(token) {
+ switch (token.type) {
+ case 'block-scalar': {
+ let res = '';
+ for (const tok of token.props)
+ res += stringifyToken(tok);
+ return res + token.source;
+ }
+ case 'block-map':
+ case 'block-seq': {
+ let res = '';
+ for (const item of token.items)
+ res += stringifyItem(item);
+ return res;
+ }
+ case 'flow-collection': {
+ let res = token.start.source;
+ for (const item of token.items)
+ res += stringifyItem(item);
+ for (const st of token.end)
+ res += st.source;
+ return res;
+ }
+ case 'document': {
+ let res = stringifyItem(token);
+ if (token.end)
+ for (const st of token.end)
+ res += st.source;
+ return res;
+ }
+ default: {
+ let res = token.source;
+ if ('end' in token && token.end)
+ for (const st of token.end)
+ res += st.source;
+ return res;
+ }
+ }
+}
+function stringifyItem({ start, key, sep, value }) {
+ let res = '';
+ for (const st of start)
+ res += st.source;
+ if (key)
+ res += stringifyToken(key);
+ if (sep)
+ for (const st of sep)
+ res += st.source;
+ if (value)
+ res += stringifyToken(value);
+ return res;
+}
- // 4. If type is the empty string or does not solely
- // contain HTTP token code points, then return failure.
- // https://mimesniff.spec.whatwg.org/#http-token-code-point
- if (type.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(type)) {
- return 'failure'
- }
+exports.stringify = stringify;
- // 5. If position is past the end of input, then return
- // failure
- if (position.position > input.length) {
- return 'failure'
- }
- // 6. Advance position by 1. (This skips past U+002F (/).)
- position.position++
+/***/ }),
- // 7. Let subtype be the result of collecting a sequence of
- // code points that are not U+003B (;) from input, given
- // position.
- let subtype = collectASequenceOfCodePointsFast(
- ';',
- input,
- position
- )
+/***/ 7715:
+/***/ ((__unused_webpack_module, exports) => {
- // 8. Remove any trailing HTTP whitespace from subtype.
- subtype = removeHTTPWhitespace(subtype, false, true)
- // 9. If subtype is the empty string or does not solely
- // contain HTTP token code points, then return failure.
- if (subtype.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(subtype)) {
- return 'failure'
- }
- const typeLowercase = type.toLowerCase()
- const subtypeLowercase = subtype.toLowerCase()
+const BREAK = Symbol('break visit');
+const SKIP = Symbol('skip children');
+const REMOVE = Symbol('remove item');
+/**
+ * Apply a visitor to a CST document or item.
+ *
+ * Walks through the tree (depth-first) starting from the root, calling a
+ * `visitor` function with two arguments when entering each item:
+ * - `item`: The current item, which included the following members:
+ * - `start: SourceToken[]` – Source tokens before the key or value,
+ * possibly including its anchor or tag.
+ * - `key?: Token | null` – Set for pair values. May then be `null`, if
+ * the key before the `:` separator is empty.
+ * - `sep?: SourceToken[]` – Source tokens between the key and the value,
+ * which should include the `:` map value indicator if `value` is set.
+ * - `value?: Token` – The value of a sequence item, or of a map pair.
+ * - `path`: The steps from the root to the current node, as an array of
+ * `['key' | 'value', number]` tuples.
+ *
+ * The return value of the visitor may be used to control the traversal:
+ * - `undefined` (default): Do nothing and continue
+ * - `visit.SKIP`: Do not visit the children of this token, continue with
+ * next sibling
+ * - `visit.BREAK`: Terminate traversal completely
+ * - `visit.REMOVE`: Remove the current item, then continue with the next one
+ * - `number`: Set the index of the next step. This is useful especially if
+ * the index of the current token has changed.
+ * - `function`: Define the next visitor for this item. After the original
+ * visitor is called on item entry, next visitors are called after handling
+ * a non-empty `key` and when exiting the item.
+ */
+function visit(cst, visitor) {
+ if ('type' in cst && cst.type === 'document')
+ cst = { start: cst.start, value: cst.value };
+ _visit(Object.freeze([]), cst, visitor);
+}
+// Without the `as symbol` casts, TS declares these in the `visit`
+// namespace using `var`, but then complains about that because
+// `unique symbol` must be `const`.
+/** Terminate visit traversal completely */
+visit.BREAK = BREAK;
+/** Do not visit the children of the current item */
+visit.SKIP = SKIP;
+/** Remove the current item */
+visit.REMOVE = REMOVE;
+/** Find the item at `path` from `cst` as the root */
+visit.itemAtPath = (cst, path) => {
+ let item = cst;
+ for (const [field, index] of path) {
+ const tok = item?.[field];
+ if (tok && 'items' in tok) {
+ item = tok.items[index];
+ }
+ else
+ return undefined;
+ }
+ return item;
+};
+/**
+ * Get the immediate parent collection of the item at `path` from `cst` as the root.
+ *
+ * Throws an error if the collection is not found, which should never happen if the item itself exists.
+ */
+visit.parentCollection = (cst, path) => {
+ const parent = visit.itemAtPath(cst, path.slice(0, -1));
+ const field = path[path.length - 1][0];
+ const coll = parent?.[field];
+ if (coll && 'items' in coll)
+ return coll;
+ throw new Error('Parent collection not found');
+};
+function _visit(path, item, visitor) {
+ let ctrl = visitor(item, path);
+ if (typeof ctrl === 'symbol')
+ return ctrl;
+ for (const field of ['key', 'value']) {
+ const token = item[field];
+ if (token && 'items' in token) {
+ for (let i = 0; i < token.items.length; ++i) {
+ const ci = _visit(Object.freeze(path.concat([[field, i]])), token.items[i], visitor);
+ if (typeof ci === 'number')
+ i = ci - 1;
+ else if (ci === BREAK)
+ return BREAK;
+ else if (ci === REMOVE) {
+ token.items.splice(i, 1);
+ i -= 1;
+ }
+ }
+ if (typeof ctrl === 'function' && field === 'key')
+ ctrl = ctrl(item, path);
+ }
+ }
+ return typeof ctrl === 'function' ? ctrl(item, path) : ctrl;
+}
- // 10. Let mimeType be a new MIME type record whose type
- // is type, in ASCII lowercase, and subtype is subtype,
- // in ASCII lowercase.
- // https://mimesniff.spec.whatwg.org/#mime-type
- const mimeType = {
- type: typeLowercase,
- subtype: subtypeLowercase,
- /** @type {Map} */
- parameters: new Map(),
- // https://mimesniff.spec.whatwg.org/#mime-type-essence
- essence: `${typeLowercase}/${subtypeLowercase}`
- }
+exports.visit = visit;
- // 11. While position is not past the end of input:
- while (position.position < input.length) {
- // 1. Advance position by 1. (This skips past U+003B (;).)
- position.position++
- // 2. Collect a sequence of code points that are HTTP
- // whitespace from input given position.
- collectASequenceOfCodePoints(
- // https://fetch.spec.whatwg.org/#http-whitespace
- char => HTTP_WHITESPACE_REGEX.test(char),
- input,
- position
- )
+/***/ }),
- // 3. Let parameterName be the result of collecting a
- // sequence of code points that are not U+003B (;)
- // or U+003D (=) from input, given position.
- let parameterName = collectASequenceOfCodePoints(
- (char) => char !== ';' && char !== '=',
- input,
- position
- )
+/***/ 3461:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 4. Set parameterName to parameterName, in ASCII
- // lowercase.
- parameterName = parameterName.toLowerCase()
- // 5. If position is not past the end of input, then:
- if (position.position < input.length) {
- // 1. If the code point at position within input is
- // U+003B (;), then continue.
- if (input[position.position] === ';') {
- continue
- }
- // 2. Advance position by 1. (This skips past U+003D (=).)
- position.position++
- }
+var cstScalar = __nccwpck_require__(110);
+var cstStringify = __nccwpck_require__(1733);
+var cstVisit = __nccwpck_require__(7715);
- // 6. If position is past the end of input, then break.
- if (position.position > input.length) {
- break
+/** The byte order mark */
+const BOM = '\u{FEFF}';
+/** Start of doc-mode */
+const DOCUMENT = '\x02'; // C0: Start of Text
+/** Unexpected end of flow-mode */
+const FLOW_END = '\x18'; // C0: Cancel
+/** Next token is a scalar value */
+const SCALAR = '\x1f'; // C0: Unit Separator
+/** @returns `true` if `token` is a flow or block collection */
+const isCollection = (token) => !!token && 'items' in token;
+/** @returns `true` if `token` is a flow or block scalar; not an alias */
+const isScalar = (token) => !!token &&
+ (token.type === 'scalar' ||
+ token.type === 'single-quoted-scalar' ||
+ token.type === 'double-quoted-scalar' ||
+ token.type === 'block-scalar');
+/* istanbul ignore next */
+/** Get a printable representation of a lexer token */
+function prettyToken(token) {
+ switch (token) {
+ case BOM:
+ return '';
+ case DOCUMENT:
+ return '';
+ case FLOW_END:
+ return '';
+ case SCALAR:
+ return '';
+ default:
+ return JSON.stringify(token);
}
-
- // 7. Let parameterValue be null.
- let parameterValue = null
-
- // 8. If the code point at position within input is
- // U+0022 ("), then:
- if (input[position.position] === '"') {
- // 1. Set parameterValue to the result of collecting
- // an HTTP quoted string from input, given position
- // and the extract-value flag.
- parameterValue = collectAnHTTPQuotedString(input, position, true)
-
- // 2. Collect a sequence of code points that are not
- // U+003B (;) from input, given position.
- collectASequenceOfCodePointsFast(
- ';',
- input,
- position
- )
-
- // 9. Otherwise:
- } else {
- // 1. Set parameterValue to the result of collecting
- // a sequence of code points that are not U+003B (;)
- // from input, given position.
- parameterValue = collectASequenceOfCodePointsFast(
- ';',
- input,
- position
- )
-
- // 2. Remove any trailing HTTP whitespace from parameterValue.
- parameterValue = removeHTTPWhitespace(parameterValue, false, true)
-
- // 3. If parameterValue is the empty string, then continue.
- if (parameterValue.length === 0) {
- continue
- }
+}
+/** Identify the type of a lexer token. May return `null` for unknown tokens. */
+function tokenType(source) {
+ switch (source) {
+ case BOM:
+ return 'byte-order-mark';
+ case DOCUMENT:
+ return 'doc-mode';
+ case FLOW_END:
+ return 'flow-error-end';
+ case SCALAR:
+ return 'scalar';
+ case '---':
+ return 'doc-start';
+ case '...':
+ return 'doc-end';
+ case '':
+ case '\n':
+ case '\r\n':
+ return 'newline';
+ case '-':
+ return 'seq-item-ind';
+ case '?':
+ return 'explicit-key-ind';
+ case ':':
+ return 'map-value-ind';
+ case '{':
+ return 'flow-map-start';
+ case '}':
+ return 'flow-map-end';
+ case '[':
+ return 'flow-seq-start';
+ case ']':
+ return 'flow-seq-end';
+ case ',':
+ return 'comma';
}
-
- // 10. If all of the following are true
- // - parameterName is not the empty string
- // - parameterName solely contains HTTP token code points
- // - parameterValue solely contains HTTP quoted-string token code points
- // - mimeType’s parameters[parameterName] does not exist
- // then set mimeType’s parameters[parameterName] to parameterValue.
- if (
- parameterName.length !== 0 &&
- HTTP_TOKEN_CODEPOINTS.test(parameterName) &&
- (parameterValue.length === 0 || HTTP_QUOTED_STRING_TOKENS.test(parameterValue)) &&
- !mimeType.parameters.has(parameterName)
- ) {
- mimeType.parameters.set(parameterName, parameterValue)
+ switch (source[0]) {
+ case ' ':
+ case '\t':
+ return 'space';
+ case '#':
+ return 'comment';
+ case '%':
+ return 'directive-line';
+ case '*':
+ return 'alias';
+ case '&':
+ return 'anchor';
+ case '!':
+ return 'tag';
+ case "'":
+ return 'single-quoted-scalar';
+ case '"':
+ return 'double-quoted-scalar';
+ case '|':
+ case '>':
+ return 'block-scalar-header';
}
- }
-
- // 12. Return mimeType.
- return mimeType
+ return null;
}
-// https://infra.spec.whatwg.org/#forgiving-base64-decode
-/** @param {string} data */
-function forgivingBase64 (data) {
- // 1. Remove all ASCII whitespace from data.
- data = data.replace(ASCII_WHITESPACE_REPLACE_REGEX, '') // eslint-disable-line
-
- let dataLength = data.length
- // 2. If data’s code point length divides by 4 leaving
- // no remainder, then:
- if (dataLength % 4 === 0) {
- // 1. If data ends with one or two U+003D (=) code points,
- // then remove them from data.
- if (data.charCodeAt(dataLength - 1) === 0x003D) {
- --dataLength
- if (data.charCodeAt(dataLength - 1) === 0x003D) {
- --dataLength
- }
- }
- }
+exports.createScalarToken = cstScalar.createScalarToken;
+exports.resolveAsScalar = cstScalar.resolveAsScalar;
+exports.setScalarValue = cstScalar.setScalarValue;
+exports.stringify = cstStringify.stringify;
+exports.visit = cstVisit.visit;
+exports.BOM = BOM;
+exports.DOCUMENT = DOCUMENT;
+exports.FLOW_END = FLOW_END;
+exports.SCALAR = SCALAR;
+exports.isCollection = isCollection;
+exports.isScalar = isScalar;
+exports.prettyToken = prettyToken;
+exports.tokenType = tokenType;
- // 3. If data’s code point length divides by 4 leaving
- // a remainder of 1, then return failure.
- if (dataLength % 4 === 1) {
- return 'failure'
- }
- // 4. If data contains a code point that is not one of
- // U+002B (+)
- // U+002F (/)
- // ASCII alphanumeric
- // then return failure.
- if (/[^+/0-9A-Za-z]/.test(data.length === dataLength ? data : data.substring(0, dataLength))) {
- return 'failure'
- }
+/***/ }),
- const buffer = Buffer.from(data, 'base64')
- return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength)
-}
+/***/ 361:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-// https://fetch.spec.whatwg.org/#collect-an-http-quoted-string
-// tests: https://fetch.spec.whatwg.org/#example-http-quoted-string
-/**
- * @param {string} input
- * @param {{ position: number }} position
- * @param {boolean?} extractValue
- */
-function collectAnHTTPQuotedString (input, position, extractValue) {
- // 1. Let positionStart be position.
- const positionStart = position.position
- // 2. Let value be the empty string.
- let value = ''
- // 3. Assert: the code point at position within input
- // is U+0022 (").
- assert(input[position.position] === '"')
+var cst = __nccwpck_require__(3461);
- // 4. Advance position by 1.
- position.position++
+/*
+START -> stream
- // 5. While true:
- while (true) {
- // 1. Append the result of collecting a sequence of code points
- // that are not U+0022 (") or U+005C (\) from input, given
- // position, to value.
- value += collectASequenceOfCodePoints(
- (char) => char !== '"' && char !== '\\',
- input,
- position
- )
+stream
+ directive -> line-end -> stream
+ indent + line-end -> stream
+ [else] -> line-start
- // 2. If position is past the end of input, then break.
- if (position.position >= input.length) {
- break
- }
+line-end
+ comment -> line-end
+ newline -> .
+ input-end -> END
- // 3. Let quoteOrBackslash be the code point at position within
- // input.
- const quoteOrBackslash = input[position.position]
+line-start
+ doc-start -> doc
+ doc-end -> stream
+ [else] -> indent -> block-start
- // 4. Advance position by 1.
- position.position++
+block-start
+ seq-item-start -> block-start
+ explicit-key-start -> block-start
+ map-value-start -> block-start
+ [else] -> doc
- // 5. If quoteOrBackslash is U+005C (\), then:
- if (quoteOrBackslash === '\\') {
- // 1. If position is past the end of input, then append
- // U+005C (\) to value and break.
- if (position.position >= input.length) {
- value += '\\'
- break
- }
+doc
+ line-end -> line-start
+ spaces -> doc
+ anchor -> doc
+ tag -> doc
+ flow-start -> flow -> doc
+ flow-end -> error -> doc
+ seq-item-start -> error -> doc
+ explicit-key-start -> error -> doc
+ map-value-start -> doc
+ alias -> doc
+ quote-start -> quoted-scalar -> doc
+ block-scalar-header -> line-end -> block-scalar(min) -> line-start
+ [else] -> plain-scalar(false, min) -> doc
- // 2. Append the code point at position within input to value.
- value += input[position.position]
+flow
+ line-end -> flow
+ spaces -> flow
+ anchor -> flow
+ tag -> flow
+ flow-start -> flow -> flow
+ flow-end -> .
+ seq-item-start -> error -> flow
+ explicit-key-start -> flow
+ map-value-start -> flow
+ alias -> flow
+ quote-start -> quoted-scalar -> flow
+ comma -> flow
+ [else] -> plain-scalar(true, 0) -> flow
- // 3. Advance position by 1.
- position.position++
+quoted-scalar
+ quote-end -> .
+ [else] -> quoted-scalar
- // 6. Otherwise:
- } else {
- // 1. Assert: quoteOrBackslash is U+0022 (").
- assert(quoteOrBackslash === '"')
+block-scalar(min)
+ newline + peek(indent < min) -> .
+ [else] -> block-scalar(min)
- // 2. Break.
- break
+plain-scalar(is-flow, min)
+ scalar-end(is-flow) -> .
+ peek(newline + (indent < min)) -> .
+ [else] -> plain-scalar(min)
+*/
+function isEmpty(ch) {
+ switch (ch) {
+ case undefined:
+ case ' ':
+ case '\n':
+ case '\r':
+ case '\t':
+ return true;
+ default:
+ return false;
}
- }
-
- // 6. If the extract-value flag is set, then return value.
- if (extractValue) {
- return value
- }
-
- // 7. Return the code points from positionStart to position,
- // inclusive, within input.
- return input.slice(positionStart, position.position)
}
-
+const hexDigits = new Set('0123456789ABCDEFabcdef');
+const tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()");
+const flowIndicatorChars = new Set(',[]{}');
+const invalidAnchorChars = new Set(' ,[]{}\n\r\t');
+const isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch);
/**
- * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type
+ * Splits an input string into lexical tokens, i.e. smaller strings that are
+ * easily identifiable by `tokens.tokenType()`.
+ *
+ * Lexing starts always in a "stream" context. Incomplete input may be buffered
+ * until a complete token can be emitted.
+ *
+ * In addition to slices of the original input, the following control characters
+ * may also be emitted:
+ *
+ * - `\x02` (Start of Text): A document starts with the next token
+ * - `\x18` (Cancel): Unexpected end of flow-mode (indicates an error)
+ * - `\x1f` (Unit Separator): Next token is a scalar value
+ * - `\u{FEFF}` (Byte order mark): Emitted separately outside documents
*/
-function serializeAMimeType (mimeType) {
- assert(mimeType !== 'failure')
- const { parameters, essence } = mimeType
-
- // 1. Let serialization be the concatenation of mimeType’s
- // type, U+002F (/), and mimeType’s subtype.
- let serialization = essence
-
- // 2. For each name → value of mimeType’s parameters:
- for (let [name, value] of parameters.entries()) {
- // 1. Append U+003B (;) to serialization.
- serialization += ';'
-
- // 2. Append name to serialization.
- serialization += name
-
- // 3. Append U+003D (=) to serialization.
- serialization += '='
-
- // 4. If value does not solely contain HTTP token code
- // points or value is the empty string, then:
- if (!HTTP_TOKEN_CODEPOINTS.test(value)) {
- // 1. Precede each occurrence of U+0022 (") or
- // U+005C (\) in value with U+005C (\).
- value = value.replace(/(\\|")/g, '\\$1')
-
- // 2. Prepend U+0022 (") to value.
- value = '"' + value
-
- // 3. Append U+0022 (") to value.
- value += '"'
+class Lexer {
+ constructor() {
+ /**
+ * Flag indicating whether the end of the current buffer marks the end of
+ * all input
+ */
+ this.atEnd = false;
+ /**
+ * Explicit indent set in block scalar header, as an offset from the current
+ * minimum indent, so e.g. set to 1 from a header `|2+`. Set to -1 if not
+ * explicitly set.
+ */
+ this.blockScalarIndent = -1;
+ /**
+ * Block scalars that include a + (keep) chomping indicator in their header
+ * include trailing empty lines, which are otherwise excluded from the
+ * scalar's contents.
+ */
+ this.blockScalarKeep = false;
+ /** Current input */
+ this.buffer = '';
+ /**
+ * Flag noting whether the map value indicator : can immediately follow this
+ * node within a flow context.
+ */
+ this.flowKey = false;
+ /** Count of surrounding flow collection levels. */
+ this.flowLevel = 0;
+ /**
+ * Minimum level of indentation required for next lines to be parsed as a
+ * part of the current scalar value.
+ */
+ this.indentNext = 0;
+ /** Indentation level of the current line. */
+ this.indentValue = 0;
+ /** Position of the next \n character. */
+ this.lineEndPos = null;
+ /** Stores the state of the lexer if reaching the end of incpomplete input */
+ this.next = null;
+ /** A pointer to `buffer`; the current position of the lexer. */
+ this.pos = 0;
}
-
- // 5. Append value to serialization.
- serialization += value
- }
-
- // 3. Return serialization.
- return serialization
-}
-
-/**
- * @see https://fetch.spec.whatwg.org/#http-whitespace
- * @param {number} char
- */
-function isHTTPWhiteSpace (char) {
- // "\r\n\t "
- return char === 0x00d || char === 0x00a || char === 0x009 || char === 0x020
-}
-
-/**
- * @see https://fetch.spec.whatwg.org/#http-whitespace
- * @param {string} str
- * @param {boolean} [leading=true]
- * @param {boolean} [trailing=true]
- */
-function removeHTTPWhitespace (str, leading = true, trailing = true) {
- return removeChars(str, leading, trailing, isHTTPWhiteSpace)
-}
-
-/**
- * @see https://infra.spec.whatwg.org/#ascii-whitespace
- * @param {number} char
- */
-function isASCIIWhitespace (char) {
- // "\r\n\t\f "
- return char === 0x00d || char === 0x00a || char === 0x009 || char === 0x00c || char === 0x020
-}
-
-/**
- * @see https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace
- * @param {string} str
- * @param {boolean} [leading=true]
- * @param {boolean} [trailing=true]
- */
-function removeASCIIWhitespace (str, leading = true, trailing = true) {
- return removeChars(str, leading, trailing, isASCIIWhitespace)
-}
-
-/**
- * @param {string} str
- * @param {boolean} leading
- * @param {boolean} trailing
- * @param {(charCode: number) => boolean} predicate
- * @returns
- */
-function removeChars (str, leading, trailing, predicate) {
- let lead = 0
- let trail = str.length - 1
-
- if (leading) {
- while (lead < str.length && predicate(str.charCodeAt(lead))) lead++
- }
-
- if (trailing) {
- while (trail > 0 && predicate(str.charCodeAt(trail))) trail--
- }
-
- return lead === 0 && trail === str.length - 1 ? str : str.slice(lead, trail + 1)
-}
-
-/**
- * @see https://infra.spec.whatwg.org/#isomorphic-decode
- * @param {Uint8Array} input
- * @returns {string}
- */
-function isomorphicDecode (input) {
- // 1. To isomorphic decode a byte sequence input, return a string whose code point
- // length is equal to input’s length and whose code points have the same values
- // as the values of input’s bytes, in the same order.
- const length = input.length
- if ((2 << 15) - 1 > length) {
- return String.fromCharCode.apply(null, input)
- }
- let result = ''; let i = 0
- let addition = (2 << 15) - 1
- while (i < length) {
- if (i + addition > length) {
- addition = length - i
+ /**
+ * Generate YAML tokens from the `source` string. If `incomplete`,
+ * a part of the last line may be left as a buffer for the next call.
+ *
+ * @returns A generator of lexical tokens
+ */
+ *lex(source, incomplete = false) {
+ if (source) {
+ if (typeof source !== 'string')
+ throw TypeError('source is not a string');
+ this.buffer = this.buffer ? this.buffer + source : source;
+ this.lineEndPos = null;
+ }
+ this.atEnd = !incomplete;
+ let next = this.next ?? 'stream';
+ while (next && (incomplete || this.hasChars(1)))
+ next = yield* this.parseNext(next);
}
- result += String.fromCharCode.apply(null, input.subarray(i, i += addition))
- }
- return result
-}
-
-/**
- * @see https://mimesniff.spec.whatwg.org/#minimize-a-supported-mime-type
- * @param {Exclude, 'failure'>} mimeType
- */
-function minimizeSupportedMimeType (mimeType) {
- switch (mimeType.essence) {
- case 'application/ecmascript':
- case 'application/javascript':
- case 'application/x-ecmascript':
- case 'application/x-javascript':
- case 'text/ecmascript':
- case 'text/javascript':
- case 'text/javascript1.0':
- case 'text/javascript1.1':
- case 'text/javascript1.2':
- case 'text/javascript1.3':
- case 'text/javascript1.4':
- case 'text/javascript1.5':
- case 'text/jscript':
- case 'text/livescript':
- case 'text/x-ecmascript':
- case 'text/x-javascript':
- // 1. If mimeType is a JavaScript MIME type, then return "text/javascript".
- return 'text/javascript'
- case 'application/json':
- case 'text/json':
- // 2. If mimeType is a JSON MIME type, then return "application/json".
- return 'application/json'
- case 'image/svg+xml':
- // 3. If mimeType’s essence is "image/svg+xml", then return "image/svg+xml".
- return 'image/svg+xml'
- case 'text/xml':
- case 'application/xml':
- // 4. If mimeType is an XML MIME type, then return "application/xml".
- return 'application/xml'
- }
-
- // 2. If mimeType is a JSON MIME type, then return "application/json".
- if (mimeType.subtype.endsWith('+json')) {
- return 'application/json'
- }
-
- // 4. If mimeType is an XML MIME type, then return "application/xml".
- if (mimeType.subtype.endsWith('+xml')) {
- return 'application/xml'
- }
-
- // 5. If mimeType is supported by the user agent, then return mimeType’s essence.
- // Technically, node doesn't support any mimetypes.
-
- // 6. Return the empty string.
- return ''
-}
-
-module.exports = {
- dataURLProcessor,
- URLSerializer,
- collectASequenceOfCodePoints,
- collectASequenceOfCodePointsFast,
- stringPercentDecode,
- parseMIMEType,
- collectAnHTTPQuotedString,
- serializeAMimeType,
- removeChars,
- removeHTTPWhitespace,
- minimizeSupportedMimeType,
- HTTP_TOKEN_CODEPOINTS,
- isomorphicDecode
-}
-
-
-/***/ }),
-
-/***/ 933:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const { kConnected, kSize } = __nccwpck_require__(9411)
-
-class CompatWeakRef {
- constructor (value) {
- this.value = value
- }
-
- deref () {
- return this.value[kConnected] === 0 && this.value[kSize] === 0
- ? undefined
- : this.value
- }
-}
-
-class CompatFinalizer {
- constructor (finalizer) {
- this.finalizer = finalizer
- }
-
- register (dispatcher, key) {
- if (dispatcher.on) {
- dispatcher.on('disconnect', () => {
- if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) {
- this.finalizer(key)
+ atLineEnd() {
+ let i = this.pos;
+ let ch = this.buffer[i];
+ while (ch === ' ' || ch === '\t')
+ ch = this.buffer[++i];
+ if (!ch || ch === '#' || ch === '\n')
+ return true;
+ if (ch === '\r')
+ return this.buffer[i + 1] === '\n';
+ return false;
+ }
+ charAt(n) {
+ return this.buffer[this.pos + n];
+ }
+ continueScalar(offset) {
+ let ch = this.buffer[offset];
+ if (this.indentNext > 0) {
+ let indent = 0;
+ while (ch === ' ')
+ ch = this.buffer[++indent + offset];
+ if (ch === '\r') {
+ const next = this.buffer[indent + offset + 1];
+ if (next === '\n' || (!next && !this.atEnd))
+ return offset + indent + 1;
+ }
+ return ch === '\n' || indent >= this.indentNext || (!ch && !this.atEnd)
+ ? offset + indent
+ : -1;
}
- })
+ if (ch === '-' || ch === '.') {
+ const dt = this.buffer.substr(offset, 3);
+ if ((dt === '---' || dt === '...') && isEmpty(this.buffer[offset + 3]))
+ return -1;
+ }
+ return offset;
}
- }
-
- unregister (key) {}
-}
-
-module.exports = function () {
- // FIXME: remove workaround when the Node bug is backported to v18
- // https://github.com/nodejs/node/issues/49344#issuecomment-1741776308
- if (process.env.NODE_V8_COVERAGE && process.version.startsWith('v18')) {
- process._rawDebug('Using compatibility WeakRef and FinalizationRegistry')
- return {
- WeakRef: CompatWeakRef,
- FinalizationRegistry: CompatFinalizer
+ getLine() {
+ let end = this.lineEndPos;
+ if (typeof end !== 'number' || (end !== -1 && end < this.pos)) {
+ end = this.buffer.indexOf('\n', this.pos);
+ this.lineEndPos = end;
+ }
+ if (end === -1)
+ return this.atEnd ? this.buffer.substring(this.pos) : null;
+ if (this.buffer[end - 1] === '\r')
+ end -= 1;
+ return this.buffer.substring(this.pos, end);
}
- }
- return { WeakRef, FinalizationRegistry }
-}
-
-
-/***/ }),
-
-/***/ 1506:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const { Blob, File } = __nccwpck_require__(4573)
-const { kState } = __nccwpck_require__(4883)
-const { webidl } = __nccwpck_require__(253)
-
-// TODO(@KhafraDev): remove
-class FileLike {
- constructor (blobLike, fileName, options = {}) {
- // TODO: argument idl type check
-
- // The File constructor is invoked with two or three parameters, depending
- // on whether the optional dictionary parameter is used. When the File()
- // constructor is invoked, user agents must run the following steps:
-
- // 1. Let bytes be the result of processing blob parts given fileBits and
- // options.
-
- // 2. Let n be the fileName argument to the constructor.
- const n = fileName
-
- // 3. Process FilePropertyBag dictionary argument by running the following
- // substeps:
-
- // 1. If the type member is provided and is not the empty string, let t
- // be set to the type dictionary member. If t contains any characters
- // outside the range U+0020 to U+007E, then set t to the empty string
- // and return from these substeps.
- // TODO
- const t = options.type
-
- // 2. Convert every character in t to ASCII lowercase.
- // TODO
-
- // 3. If the lastModified member is provided, let d be set to the
- // lastModified dictionary member. If it is not provided, set d to the
- // current date and time represented as the number of milliseconds since
- // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]).
- const d = options.lastModified ?? Date.now()
-
- // 4. Return a new File object F such that:
- // F refers to the bytes byte sequence.
- // F.size is set to the number of total bytes in bytes.
- // F.name is set to n.
- // F.type is set to t.
- // F.lastModified is set to d.
-
- this[kState] = {
- blobLike,
- name: n,
- type: t,
- lastModified: d
+ hasChars(n) {
+ return this.pos + n <= this.buffer.length;
}
- }
-
- stream (...args) {
- webidl.brandCheck(this, FileLike)
-
- return this[kState].blobLike.stream(...args)
- }
-
- arrayBuffer (...args) {
- webidl.brandCheck(this, FileLike)
-
- return this[kState].blobLike.arrayBuffer(...args)
- }
-
- slice (...args) {
- webidl.brandCheck(this, FileLike)
-
- return this[kState].blobLike.slice(...args)
- }
-
- text (...args) {
- webidl.brandCheck(this, FileLike)
-
- return this[kState].blobLike.text(...args)
- }
-
- get size () {
- webidl.brandCheck(this, FileLike)
-
- return this[kState].blobLike.size
- }
-
- get type () {
- webidl.brandCheck(this, FileLike)
-
- return this[kState].blobLike.type
- }
-
- get name () {
- webidl.brandCheck(this, FileLike)
-
- return this[kState].name
- }
-
- get lastModified () {
- webidl.brandCheck(this, FileLike)
-
- return this[kState].lastModified
- }
-
- get [Symbol.toStringTag] () {
- return 'File'
- }
-}
-
-webidl.converters.Blob = webidl.interfaceConverter(Blob)
-
-// If this function is moved to ./util.js, some tools (such as
-// rollup) will warn about circular dependencies. See:
-// https://github.com/nodejs/undici/issues/1629
-function isFileLike (object) {
- return (
- (object instanceof File) ||
- (
- object &&
- (typeof object.stream === 'function' ||
- typeof object.arrayBuffer === 'function') &&
- object[Symbol.toStringTag] === 'File'
- )
- )
-}
-
-module.exports = { FileLike, isFileLike }
-
-
-/***/ }),
-
-/***/ 3100:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const { isUSVString, bufferToLowerCasedHeaderName } = __nccwpck_require__(1544)
-const { utf8DecodeBytes } = __nccwpck_require__(4296)
-const { HTTP_TOKEN_CODEPOINTS, isomorphicDecode } = __nccwpck_require__(980)
-const { isFileLike } = __nccwpck_require__(1506)
-const { makeEntry } = __nccwpck_require__(9662)
-const assert = __nccwpck_require__(4589)
-const { File: NodeFile } = __nccwpck_require__(4573)
-
-const File = globalThis.File ?? NodeFile
-
-const formDataNameBuffer = Buffer.from('form-data; name="')
-const filenameBuffer = Buffer.from('; filename')
-const dd = Buffer.from('--')
-const ddcrlf = Buffer.from('--\r\n')
-
-/**
- * @param {string} chars
- */
-function isAsciiString (chars) {
- for (let i = 0; i < chars.length; ++i) {
- if ((chars.charCodeAt(i) & ~0x7F) !== 0) {
- return false
+ setNext(state) {
+ this.buffer = this.buffer.substring(this.pos);
+ this.pos = 0;
+ this.lineEndPos = null;
+ this.next = state;
+ return null;
}
- }
- return true
-}
-
-/**
- * @see https://andreubotella.github.io/multipart-form-data/#multipart-form-data-boundary
- * @param {string} boundary
- */
-function validateBoundary (boundary) {
- const length = boundary.length
-
- // - its length is greater or equal to 27 and lesser or equal to 70, and
- if (length < 27 || length > 70) {
- return false
- }
-
- // - it is composed by bytes in the ranges 0x30 to 0x39, 0x41 to 0x5A, or
- // 0x61 to 0x7A, inclusive (ASCII alphanumeric), or which are 0x27 ('),
- // 0x2D (-) or 0x5F (_).
- for (let i = 0; i < length; ++i) {
- const cp = boundary.charCodeAt(i)
-
- if (!(
- (cp >= 0x30 && cp <= 0x39) ||
- (cp >= 0x41 && cp <= 0x5a) ||
- (cp >= 0x61 && cp <= 0x7a) ||
- cp === 0x27 ||
- cp === 0x2d ||
- cp === 0x5f
- )) {
- return false
- }
- }
-
- return true
-}
-
-/**
- * @see https://andreubotella.github.io/multipart-form-data/#multipart-form-data-parser
- * @param {Buffer} input
- * @param {ReturnType} mimeType
- */
-function multipartFormDataParser (input, mimeType) {
- // 1. Assert: mimeType’s essence is "multipart/form-data".
- assert(mimeType !== 'failure' && mimeType.essence === 'multipart/form-data')
-
- const boundaryString = mimeType.parameters.get('boundary')
-
- // 2. If mimeType’s parameters["boundary"] does not exist, return failure.
- // Otherwise, let boundary be the result of UTF-8 decoding mimeType’s
- // parameters["boundary"].
- if (boundaryString === undefined) {
- return 'failure'
- }
-
- const boundary = Buffer.from(`--${boundaryString}`, 'utf8')
-
- // 3. Let entry list be an empty entry list.
- const entryList = []
-
- // 4. Let position be a pointer to a byte in input, initially pointing at
- // the first byte.
- const position = { position: 0 }
-
- // Note: undici addition, allows leading and trailing CRLFs.
- while (input[position.position] === 0x0d && input[position.position + 1] === 0x0a) {
- position.position += 2
- }
-
- let trailing = input.length
-
- while (input[trailing - 1] === 0x0a && input[trailing - 2] === 0x0d) {
- trailing -= 2
- }
-
- if (trailing !== input.length) {
- input = input.subarray(0, trailing)
- }
-
- // 5. While true:
- while (true) {
- // 5.1. If position points to a sequence of bytes starting with 0x2D 0x2D
- // (`--`) followed by boundary, advance position by 2 + the length of
- // boundary. Otherwise, return failure.
- // Note: boundary is padded with 2 dashes already, no need to add 2.
- if (input.subarray(position.position, position.position + boundary.length).equals(boundary)) {
- position.position += boundary.length
- } else {
- return 'failure'
- }
-
- // 5.2. If position points to the sequence of bytes 0x2D 0x2D 0x0D 0x0A
- // (`--` followed by CR LF) followed by the end of input, return entry list.
- // Note: a body does NOT need to end with CRLF. It can end with --.
- if (
- (position.position === input.length - 2 && bufferStartsWith(input, dd, position)) ||
- (position.position === input.length - 4 && bufferStartsWith(input, ddcrlf, position))
- ) {
- return entryList
- }
-
- // 5.3. If position does not point to a sequence of bytes starting with 0x0D
- // 0x0A (CR LF), return failure.
- if (input[position.position] !== 0x0d || input[position.position + 1] !== 0x0a) {
- return 'failure'
- }
-
- // 5.4. Advance position by 2. (This skips past the newline.)
- position.position += 2
-
- // 5.5. Let name, filename and contentType be the result of parsing
- // multipart/form-data headers on input and position, if the result
- // is not failure. Otherwise, return failure.
- const result = parseMultipartFormDataHeaders(input, position)
-
- if (result === 'failure') {
- return 'failure'
+ peek(n) {
+ return this.buffer.substr(this.pos, n);
}
-
- let { name, filename, contentType, encoding } = result
-
- // 5.6. Advance position by 2. (This skips past the empty line that marks
- // the end of the headers.)
- position.position += 2
-
- // 5.7. Let body be the empty byte sequence.
- let body
-
- // 5.8. Body loop: While position is not past the end of input:
- // TODO: the steps here are completely wrong
- {
- const boundaryIndex = input.indexOf(boundary.subarray(2), position.position)
-
- if (boundaryIndex === -1) {
- return 'failure'
- }
-
- body = input.subarray(position.position, boundaryIndex - 4)
-
- position.position += body.length
-
- // Note: position must be advanced by the body's length before being
- // decoded, otherwise the parsing will fail.
- if (encoding === 'base64') {
- body = Buffer.from(body.toString(), 'base64')
- }
+ *parseNext(next) {
+ switch (next) {
+ case 'stream':
+ return yield* this.parseStream();
+ case 'line-start':
+ return yield* this.parseLineStart();
+ case 'block-start':
+ return yield* this.parseBlockStart();
+ case 'doc':
+ return yield* this.parseDocument();
+ case 'flow':
+ return yield* this.parseFlowCollection();
+ case 'quoted-scalar':
+ return yield* this.parseQuotedScalar();
+ case 'block-scalar':
+ return yield* this.parseBlockScalar();
+ case 'plain-scalar':
+ return yield* this.parsePlainScalar();
+ }
}
-
- // 5.9. If position does not point to a sequence of bytes starting with
- // 0x0D 0x0A (CR LF), return failure. Otherwise, advance position by 2.
- if (input[position.position] !== 0x0d || input[position.position + 1] !== 0x0a) {
- return 'failure'
- } else {
- position.position += 2
+ *parseStream() {
+ let line = this.getLine();
+ if (line === null)
+ return this.setNext('stream');
+ if (line[0] === cst.BOM) {
+ yield* this.pushCount(1);
+ line = line.substring(1);
+ }
+ if (line[0] === '%') {
+ let dirEnd = line.length;
+ let cs = line.indexOf('#');
+ while (cs !== -1) {
+ const ch = line[cs - 1];
+ if (ch === ' ' || ch === '\t') {
+ dirEnd = cs - 1;
+ break;
+ }
+ else {
+ cs = line.indexOf('#', cs + 1);
+ }
+ }
+ while (true) {
+ const ch = line[dirEnd - 1];
+ if (ch === ' ' || ch === '\t')
+ dirEnd -= 1;
+ else
+ break;
+ }
+ const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true));
+ yield* this.pushCount(line.length - n); // possible comment
+ this.pushNewline();
+ return 'stream';
+ }
+ if (this.atLineEnd()) {
+ const sp = yield* this.pushSpaces(true);
+ yield* this.pushCount(line.length - sp);
+ yield* this.pushNewline();
+ return 'stream';
+ }
+ yield cst.DOCUMENT;
+ return yield* this.parseLineStart();
}
-
- // 5.10. If filename is not null:
- let value
-
- if (filename !== null) {
- // 5.10.1. If contentType is null, set contentType to "text/plain".
- contentType ??= 'text/plain'
-
- // 5.10.2. If contentType is not an ASCII string, set contentType to the empty string.
-
- // Note: `buffer.isAscii` can be used at zero-cost, but converting a string to a buffer is a high overhead.
- // Content-Type is a relatively small string, so it is faster to use `String#charCodeAt`.
- if (!isAsciiString(contentType)) {
- contentType = ''
- }
-
- // 5.10.3. Let value be a new File object with name filename, type contentType, and body body.
- value = new File([body], filename, { type: contentType })
- } else {
- // 5.11. Otherwise:
-
- // 5.11.1. Let value be the UTF-8 decoding without BOM of body.
- value = utf8DecodeBytes(Buffer.from(body))
+ *parseLineStart() {
+ const ch = this.charAt(0);
+ if (!ch && !this.atEnd)
+ return this.setNext('line-start');
+ if (ch === '-' || ch === '.') {
+ if (!this.atEnd && !this.hasChars(4))
+ return this.setNext('line-start');
+ const s = this.peek(3);
+ if ((s === '---' || s === '...') && isEmpty(this.charAt(3))) {
+ yield* this.pushCount(3);
+ this.indentValue = 0;
+ this.indentNext = 0;
+ return s === '---' ? 'doc' : 'stream';
+ }
+ }
+ this.indentValue = yield* this.pushSpaces(false);
+ if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1)))
+ this.indentNext = this.indentValue;
+ return yield* this.parseBlockStart();
}
-
- // 5.12. Assert: name is a scalar value string and value is either a scalar value string or a File object.
- assert(isUSVString(name))
- assert((typeof value === 'string' && isUSVString(value)) || isFileLike(value))
-
- // 5.13. Create an entry with name and value, and append it to entry list.
- entryList.push(makeEntry(name, value, filename))
- }
-}
-
-/**
- * @see https://andreubotella.github.io/multipart-form-data/#parse-multipart-form-data-headers
- * @param {Buffer} input
- * @param {{ position: number }} position
- */
-function parseMultipartFormDataHeaders (input, position) {
- // 1. Let name, filename and contentType be null.
- let name = null
- let filename = null
- let contentType = null
- let encoding = null
-
- // 2. While true:
- while (true) {
- // 2.1. If position points to a sequence of bytes starting with 0x0D 0x0A (CR LF):
- if (input[position.position] === 0x0d && input[position.position + 1] === 0x0a) {
- // 2.1.1. If name is null, return failure.
- if (name === null) {
- return 'failure'
- }
-
- // 2.1.2. Return name, filename and contentType.
- return { name, filename, contentType, encoding }
+ *parseBlockStart() {
+ const [ch0, ch1] = this.peek(2);
+ if (!ch1 && !this.atEnd)
+ return this.setNext('block-start');
+ if ((ch0 === '-' || ch0 === '?' || ch0 === ':') && isEmpty(ch1)) {
+ const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true));
+ this.indentNext = this.indentValue + 1;
+ this.indentValue += n;
+ return 'block-start';
+ }
+ return 'doc';
}
-
- // 2.2. Let header name be the result of collecting a sequence of bytes that are
- // not 0x0A (LF), 0x0D (CR) or 0x3A (:), given position.
- let headerName = collectASequenceOfBytes(
- (char) => char !== 0x0a && char !== 0x0d && char !== 0x3a,
- input,
- position
- )
-
- // 2.3. Remove any HTTP tab or space bytes from the start or end of header name.
- headerName = removeChars(headerName, true, true, (char) => char === 0x9 || char === 0x20)
-
- // 2.4. If header name does not match the field-name token production, return failure.
- if (!HTTP_TOKEN_CODEPOINTS.test(headerName.toString())) {
- return 'failure'
+ *parseDocument() {
+ yield* this.pushSpaces(true);
+ const line = this.getLine();
+ if (line === null)
+ return this.setNext('doc');
+ let n = yield* this.pushIndicators();
+ switch (line[n]) {
+ case '#':
+ yield* this.pushCount(line.length - n);
+ // fallthrough
+ case undefined:
+ yield* this.pushNewline();
+ return yield* this.parseLineStart();
+ case '{':
+ case '[':
+ yield* this.pushCount(1);
+ this.flowKey = false;
+ this.flowLevel = 1;
+ return 'flow';
+ case '}':
+ case ']':
+ // this is an error
+ yield* this.pushCount(1);
+ return 'doc';
+ case '*':
+ yield* this.pushUntil(isNotAnchorChar);
+ return 'doc';
+ case '"':
+ case "'":
+ return yield* this.parseQuotedScalar();
+ case '|':
+ case '>':
+ n += yield* this.parseBlockScalarHeader();
+ n += yield* this.pushSpaces(true);
+ yield* this.pushCount(line.length - n);
+ yield* this.pushNewline();
+ return yield* this.parseBlockScalar();
+ default:
+ return yield* this.parsePlainScalar();
+ }
}
-
- // 2.5. If the byte at position is not 0x3A (:), return failure.
- if (input[position.position] !== 0x3a) {
- return 'failure'
+ *parseFlowCollection() {
+ let nl, sp;
+ let indent = -1;
+ do {
+ nl = yield* this.pushNewline();
+ if (nl > 0) {
+ sp = yield* this.pushSpaces(false);
+ this.indentValue = indent = sp;
+ }
+ else {
+ sp = 0;
+ }
+ sp += yield* this.pushSpaces(true);
+ } while (nl + sp > 0);
+ const line = this.getLine();
+ if (line === null)
+ return this.setNext('flow');
+ if ((indent !== -1 && indent < this.indentNext && line[0] !== '#') ||
+ (indent === 0 &&
+ (line.startsWith('---') || line.startsWith('...')) &&
+ isEmpty(line[3]))) {
+ // Allowing for the terminal ] or } at the same (rather than greater)
+ // indent level as the initial [ or { is technically invalid, but
+ // failing here would be surprising to users.
+ const atFlowEndMarker = indent === this.indentNext - 1 &&
+ this.flowLevel === 1 &&
+ (line[0] === ']' || line[0] === '}');
+ if (!atFlowEndMarker) {
+ // this is an error
+ this.flowLevel = 0;
+ yield cst.FLOW_END;
+ return yield* this.parseLineStart();
+ }
+ }
+ let n = 0;
+ while (line[n] === ',') {
+ n += yield* this.pushCount(1);
+ n += yield* this.pushSpaces(true);
+ this.flowKey = false;
+ }
+ n += yield* this.pushIndicators();
+ switch (line[n]) {
+ case undefined:
+ return 'flow';
+ case '#':
+ yield* this.pushCount(line.length - n);
+ return 'flow';
+ case '{':
+ case '[':
+ yield* this.pushCount(1);
+ this.flowKey = false;
+ this.flowLevel += 1;
+ return 'flow';
+ case '}':
+ case ']':
+ yield* this.pushCount(1);
+ this.flowKey = true;
+ this.flowLevel -= 1;
+ return this.flowLevel ? 'flow' : 'doc';
+ case '*':
+ yield* this.pushUntil(isNotAnchorChar);
+ return 'flow';
+ case '"':
+ case "'":
+ this.flowKey = true;
+ return yield* this.parseQuotedScalar();
+ case ':': {
+ const next = this.charAt(1);
+ if (this.flowKey || isEmpty(next) || next === ',') {
+ this.flowKey = false;
+ yield* this.pushCount(1);
+ yield* this.pushSpaces(true);
+ return 'flow';
+ }
+ }
+ // fallthrough
+ default:
+ this.flowKey = false;
+ return yield* this.parsePlainScalar();
+ }
}
-
- // 2.6. Advance position by 1.
- position.position++
-
- // 2.7. Collect a sequence of bytes that are HTTP tab or space bytes given position.
- // (Do nothing with those bytes.)
- collectASequenceOfBytes(
- (char) => char === 0x20 || char === 0x09,
- input,
- position
- )
-
- // 2.8. Byte-lowercase header name and switch on the result:
- switch (bufferToLowerCasedHeaderName(headerName)) {
- case 'content-disposition': {
- // 1. Set name and filename to null.
- name = filename = null
-
- // 2. If position does not point to a sequence of bytes starting with
- // `form-data; name="`, return failure.
- if (!bufferStartsWith(input, formDataNameBuffer, position)) {
- return 'failure'
+ *parseQuotedScalar() {
+ const quote = this.charAt(0);
+ let end = this.buffer.indexOf(quote, this.pos + 1);
+ if (quote === "'") {
+ while (end !== -1 && this.buffer[end + 1] === "'")
+ end = this.buffer.indexOf("'", end + 2);
}
-
- // 3. Advance position so it points at the byte after the next 0x22 (")
- // byte (the one in the sequence of bytes matched above).
- position.position += 17
-
- // 4. Set name to the result of parsing a multipart/form-data name given
- // input and position, if the result is not failure. Otherwise, return
- // failure.
- name = parseMultipartFormDataName(input, position)
-
- if (name === null) {
- return 'failure'
+ else {
+ // double-quote
+ while (end !== -1) {
+ let n = 0;
+ while (this.buffer[end - 1 - n] === '\\')
+ n += 1;
+ if (n % 2 === 0)
+ break;
+ end = this.buffer.indexOf('"', end + 1);
+ }
}
-
- // 5. If position points to a sequence of bytes starting with `; filename="`:
- if (bufferStartsWith(input, filenameBuffer, position)) {
- // Note: undici also handles filename*
- let check = position.position + filenameBuffer.length
-
- if (input[check] === 0x2a) {
- position.position += 1
- check += 1
- }
-
- if (input[check] !== 0x3d || input[check + 1] !== 0x22) { // ="
- return 'failure'
- }
-
- // 1. Advance position so it points at the byte after the next 0x22 (") byte
- // (the one in the sequence of bytes matched above).
- position.position += 12
-
- // 2. Set filename to the result of parsing a multipart/form-data name given
- // input and position, if the result is not failure. Otherwise, return failure.
- filename = parseMultipartFormDataName(input, position)
-
- if (filename === null) {
- return 'failure'
- }
+ // Only looking for newlines within the quotes
+ const qb = this.buffer.substring(0, end);
+ let nl = qb.indexOf('\n', this.pos);
+ if (nl !== -1) {
+ while (nl !== -1) {
+ const cs = this.continueScalar(nl + 1);
+ if (cs === -1)
+ break;
+ nl = qb.indexOf('\n', cs);
+ }
+ if (nl !== -1) {
+ // this is an error caused by an unexpected unindent
+ end = nl - (qb[nl - 1] === '\r' ? 2 : 1);
+ }
}
-
- break
- }
- case 'content-type': {
- // 1. Let header value be the result of collecting a sequence of bytes that are
- // not 0x0A (LF) or 0x0D (CR), given position.
- let headerValue = collectASequenceOfBytes(
- (char) => char !== 0x0a && char !== 0x0d,
- input,
- position
- )
-
- // 2. Remove any HTTP tab or space bytes from the end of header value.
- headerValue = removeChars(headerValue, false, true, (char) => char === 0x9 || char === 0x20)
-
- // 3. Set contentType to the isomorphic decoding of header value.
- contentType = isomorphicDecode(headerValue)
-
- break
- }
- case 'content-transfer-encoding': {
- let headerValue = collectASequenceOfBytes(
- (char) => char !== 0x0a && char !== 0x0d,
- input,
- position
- )
-
- headerValue = removeChars(headerValue, false, true, (char) => char === 0x9 || char === 0x20)
-
- encoding = isomorphicDecode(headerValue)
-
- break
- }
- default: {
- // Collect a sequence of bytes that are not 0x0A (LF) or 0x0D (CR), given position.
- // (Do nothing with those bytes.)
- collectASequenceOfBytes(
- (char) => char !== 0x0a && char !== 0x0d,
- input,
- position
- )
- }
+ if (end === -1) {
+ if (!this.atEnd)
+ return this.setNext('quoted-scalar');
+ end = this.buffer.length;
+ }
+ yield* this.pushToIndex(end + 1, false);
+ return this.flowLevel ? 'flow' : 'doc';
}
-
- // 2.9. If position does not point to a sequence of bytes starting with 0x0D 0x0A
- // (CR LF), return failure. Otherwise, advance position by 2 (past the newline).
- if (input[position.position] !== 0x0d && input[position.position + 1] !== 0x0a) {
- return 'failure'
- } else {
- position.position += 2
+ *parseBlockScalarHeader() {
+ this.blockScalarIndent = -1;
+ this.blockScalarKeep = false;
+ let i = this.pos;
+ while (true) {
+ const ch = this.buffer[++i];
+ if (ch === '+')
+ this.blockScalarKeep = true;
+ else if (ch > '0' && ch <= '9')
+ this.blockScalarIndent = Number(ch) - 1;
+ else if (ch !== '-')
+ break;
+ }
+ return yield* this.pushUntil(ch => isEmpty(ch) || ch === '#');
+ }
+ *parseBlockScalar() {
+ let nl = this.pos - 1; // may be -1 if this.pos === 0
+ let indent = 0;
+ let ch;
+ loop: for (let i = this.pos; (ch = this.buffer[i]); ++i) {
+ switch (ch) {
+ case ' ':
+ indent += 1;
+ break;
+ case '\n':
+ nl = i;
+ indent = 0;
+ break;
+ case '\r': {
+ const next = this.buffer[i + 1];
+ if (!next && !this.atEnd)
+ return this.setNext('block-scalar');
+ if (next === '\n')
+ break;
+ } // fallthrough
+ default:
+ break loop;
+ }
+ }
+ if (!ch && !this.atEnd)
+ return this.setNext('block-scalar');
+ if (indent >= this.indentNext) {
+ if (this.blockScalarIndent === -1)
+ this.indentNext = indent;
+ else {
+ this.indentNext =
+ this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext);
+ }
+ do {
+ const cs = this.continueScalar(nl + 1);
+ if (cs === -1)
+ break;
+ nl = this.buffer.indexOf('\n', cs);
+ } while (nl !== -1);
+ if (nl === -1) {
+ if (!this.atEnd)
+ return this.setNext('block-scalar');
+ nl = this.buffer.length;
+ }
+ }
+ // Trailing insufficiently indented tabs are invalid.
+ // To catch that during parsing, we include them in the block scalar value.
+ let i = nl + 1;
+ ch = this.buffer[i];
+ while (ch === ' ')
+ ch = this.buffer[++i];
+ if (ch === '\t') {
+ while (ch === '\t' || ch === ' ' || ch === '\r' || ch === '\n')
+ ch = this.buffer[++i];
+ nl = i - 1;
+ }
+ else if (!this.blockScalarKeep) {
+ do {
+ let i = nl - 1;
+ let ch = this.buffer[i];
+ if (ch === '\r')
+ ch = this.buffer[--i];
+ const lastChar = i; // Drop the line if last char not more indented
+ while (ch === ' ')
+ ch = this.buffer[--i];
+ if (ch === '\n' && i >= this.pos && i + 1 + indent > lastChar)
+ nl = i;
+ else
+ break;
+ } while (true);
+ }
+ yield cst.SCALAR;
+ yield* this.pushToIndex(nl + 1, true);
+ return yield* this.parseLineStart();
+ }
+ *parsePlainScalar() {
+ const inFlow = this.flowLevel > 0;
+ let end = this.pos - 1;
+ let i = this.pos - 1;
+ let ch;
+ while ((ch = this.buffer[++i])) {
+ if (ch === ':') {
+ const next = this.buffer[i + 1];
+ if (isEmpty(next) || (inFlow && flowIndicatorChars.has(next)))
+ break;
+ end = i;
+ }
+ else if (isEmpty(ch)) {
+ let next = this.buffer[i + 1];
+ if (ch === '\r') {
+ if (next === '\n') {
+ i += 1;
+ ch = '\n';
+ next = this.buffer[i + 1];
+ }
+ else
+ end = i;
+ }
+ if (next === '#' || (inFlow && flowIndicatorChars.has(next)))
+ break;
+ if (ch === '\n') {
+ const cs = this.continueScalar(i + 1);
+ if (cs === -1)
+ break;
+ i = Math.max(i, cs - 2); // to advance, but still account for ' #'
+ }
+ }
+ else {
+ if (inFlow && flowIndicatorChars.has(ch))
+ break;
+ end = i;
+ }
+ }
+ if (!ch && !this.atEnd)
+ return this.setNext('plain-scalar');
+ yield cst.SCALAR;
+ yield* this.pushToIndex(end + 1, true);
+ return inFlow ? 'flow' : 'doc';
+ }
+ *pushCount(n) {
+ if (n > 0) {
+ yield this.buffer.substr(this.pos, n);
+ this.pos += n;
+ return n;
+ }
+ return 0;
+ }
+ *pushToIndex(i, allowEmpty) {
+ const s = this.buffer.slice(this.pos, i);
+ if (s) {
+ yield s;
+ this.pos += s.length;
+ return s.length;
+ }
+ else if (allowEmpty)
+ yield '';
+ return 0;
+ }
+ *pushIndicators() {
+ let n = 0;
+ loop: while (true) {
+ switch (this.charAt(0)) {
+ case '!':
+ n += yield* this.pushTag();
+ n += yield* this.pushSpaces(true);
+ continue loop;
+ case '&':
+ n += yield* this.pushUntil(isNotAnchorChar);
+ n += yield* this.pushSpaces(true);
+ continue loop;
+ case '-': // this is an error
+ case '?': // this is an error outside flow collections
+ case ':': {
+ const inFlow = this.flowLevel > 0;
+ const ch1 = this.charAt(1);
+ if (isEmpty(ch1) || (inFlow && flowIndicatorChars.has(ch1))) {
+ if (!inFlow)
+ this.indentNext = this.indentValue + 1;
+ else if (this.flowKey)
+ this.flowKey = false;
+ n += yield* this.pushCount(1);
+ n += yield* this.pushSpaces(true);
+ continue loop;
+ }
+ }
+ }
+ break loop;
+ }
+ return n;
+ }
+ *pushTag() {
+ if (this.charAt(1) === '<') {
+ let i = this.pos + 2;
+ let ch = this.buffer[i];
+ while (!isEmpty(ch) && ch !== '>')
+ ch = this.buffer[++i];
+ return yield* this.pushToIndex(ch === '>' ? i + 1 : i, false);
+ }
+ else {
+ let i = this.pos + 1;
+ let ch = this.buffer[i];
+ while (ch) {
+ if (tagChars.has(ch))
+ ch = this.buffer[++i];
+ else if (ch === '%' &&
+ hexDigits.has(this.buffer[i + 1]) &&
+ hexDigits.has(this.buffer[i + 2])) {
+ ch = this.buffer[(i += 3)];
+ }
+ else
+ break;
+ }
+ return yield* this.pushToIndex(i, false);
+ }
+ }
+ *pushNewline() {
+ const ch = this.buffer[this.pos];
+ if (ch === '\n')
+ return yield* this.pushCount(1);
+ else if (ch === '\r' && this.charAt(1) === '\n')
+ return yield* this.pushCount(2);
+ else
+ return 0;
+ }
+ *pushSpaces(allowTabs) {
+ let i = this.pos - 1;
+ let ch;
+ do {
+ ch = this.buffer[++i];
+ } while (ch === ' ' || (allowTabs && ch === '\t'));
+ const n = i - this.pos;
+ if (n > 0) {
+ yield this.buffer.substr(this.pos, n);
+ this.pos = i;
+ }
+ return n;
+ }
+ *pushUntil(test) {
+ let i = this.pos;
+ let ch = this.buffer[i];
+ while (!test(ch))
+ ch = this.buffer[++i];
+ return yield* this.pushToIndex(i, false);
}
- }
-}
-
-/**
- * @see https://andreubotella.github.io/multipart-form-data/#parse-a-multipart-form-data-name
- * @param {Buffer} input
- * @param {{ position: number }} position
- */
-function parseMultipartFormDataName (input, position) {
- // 1. Assert: The byte at (position - 1) is 0x22 (").
- assert(input[position.position - 1] === 0x22)
-
- // 2. Let name be the result of collecting a sequence of bytes that are not 0x0A (LF), 0x0D (CR) or 0x22 ("), given position.
- /** @type {string | Buffer} */
- let name = collectASequenceOfBytes(
- (char) => char !== 0x0a && char !== 0x0d && char !== 0x22,
- input,
- position
- )
-
- // 3. If the byte at position is not 0x22 ("), return failure. Otherwise, advance position by 1.
- if (input[position.position] !== 0x22) {
- return null // name could be 'failure'
- } else {
- position.position++
- }
-
- // 4. Replace any occurrence of the following subsequences in name with the given byte:
- // - `%0A`: 0x0A (LF)
- // - `%0D`: 0x0D (CR)
- // - `%22`: 0x22 (")
- name = new TextDecoder().decode(name)
- .replace(/%0A/ig, '\n')
- .replace(/%0D/ig, '\r')
- .replace(/%22/g, '"')
-
- // 5. Return the UTF-8 decoding without BOM of name.
- return name
}
-/**
- * @param {(char: number) => boolean} condition
- * @param {Buffer} input
- * @param {{ position: number }} position
- */
-function collectASequenceOfBytes (condition, input, position) {
- let start = position.position
-
- while (start < input.length && condition(input[start])) {
- ++start
- }
+exports.Lexer = Lexer;
- return input.subarray(position.position, (position.position = start))
-}
-/**
- * @param {Buffer} buf
- * @param {boolean} leading
- * @param {boolean} trailing
- * @param {(charCode: number) => boolean} predicate
- * @returns {Buffer}
- */
-function removeChars (buf, leading, trailing, predicate) {
- let lead = 0
- let trail = buf.length - 1
+/***/ }),
- if (leading) {
- while (lead < buf.length && predicate(buf[lead])) lead++
- }
+/***/ 6628:
+/***/ ((__unused_webpack_module, exports) => {
- if (trailing) {
- while (trail > 0 && predicate(buf[trail])) trail--
- }
- return lead === 0 && trail === buf.length - 1 ? buf : buf.subarray(lead, trail + 1)
-}
/**
- * Checks if {@param buffer} starts with {@param start}
- * @param {Buffer} buffer
- * @param {Buffer} start
- * @param {{ position: number }} position
+ * Tracks newlines during parsing in order to provide an efficient API for
+ * determining the one-indexed `{ line, col }` position for any offset
+ * within the input.
*/
-function bufferStartsWith (buffer, start, position) {
- if (buffer.length < start.length) {
- return false
- }
-
- for (let i = 0; i < start.length; i++) {
- if (start[i] !== buffer[position.position + i]) {
- return false
+class LineCounter {
+ constructor() {
+ this.lineStarts = [];
+ /**
+ * Should be called in ascending order. Otherwise, call
+ * `lineCounter.lineStarts.sort()` before calling `linePos()`.
+ */
+ this.addNewLine = (offset) => this.lineStarts.push(offset);
+ /**
+ * Performs a binary search and returns the 1-indexed { line, col }
+ * position of `offset`. If `line === 0`, `addNewLine` has never been
+ * called or `offset` is before the first known newline.
+ */
+ this.linePos = (offset) => {
+ let low = 0;
+ let high = this.lineStarts.length;
+ while (low < high) {
+ const mid = (low + high) >> 1; // Math.floor((low + high) / 2)
+ if (this.lineStarts[mid] < offset)
+ low = mid + 1;
+ else
+ high = mid;
+ }
+ if (this.lineStarts[low] === offset)
+ return { line: low + 1, col: 1 };
+ if (low === 0)
+ return { line: 0, col: offset };
+ const start = this.lineStarts[low - 1];
+ return { line: low, col: offset - start + 1 };
+ };
}
- }
-
- return true
}
-module.exports = {
- multipartFormDataParser,
- validateBoundary
-}
+exports.LineCounter = LineCounter;
/***/ }),
-/***/ 9662:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const { isBlobLike, iteratorMixin } = __nccwpck_require__(4296)
-const { kState } = __nccwpck_require__(4883)
-const { kEnumerableProperty } = __nccwpck_require__(1544)
-const { FileLike, isFileLike } = __nccwpck_require__(1506)
-const { webidl } = __nccwpck_require__(253)
-const { File: NativeFile } = __nccwpck_require__(4573)
-const nodeUtil = __nccwpck_require__(7975)
-
-/** @type {globalThis['File']} */
-const File = globalThis.File ?? NativeFile
-
-// https://xhr.spec.whatwg.org/#formdata
-class FormData {
- constructor (form) {
- webidl.util.markAsUncloneable(this)
-
- if (form !== undefined) {
- throw webidl.errors.conversionFailed({
- prefix: 'FormData constructor',
- argument: 'Argument 1',
- types: ['undefined']
- })
- }
+/***/ 3456:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- this[kState] = []
- }
- append (name, value, filename = undefined) {
- webidl.brandCheck(this, FormData)
- const prefix = 'FormData.append'
- webidl.argumentLengthCheck(arguments, 2, prefix)
+var node_process = __nccwpck_require__(932);
+var cst = __nccwpck_require__(3461);
+var lexer = __nccwpck_require__(361);
- if (arguments.length === 3 && !isBlobLike(value)) {
- throw new TypeError(
- "Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'"
- )
+function includesToken(list, type) {
+ for (let i = 0; i < list.length; ++i)
+ if (list[i].type === type)
+ return true;
+ return false;
+}
+function findNonEmptyIndex(list) {
+ for (let i = 0; i < list.length; ++i) {
+ switch (list[i].type) {
+ case 'space':
+ case 'comment':
+ case 'newline':
+ break;
+ default:
+ return i;
+ }
}
-
- // 1. Let value be value if given; otherwise blobValue.
-
- name = webidl.converters.USVString(name, prefix, 'name')
- value = isBlobLike(value)
- ? webidl.converters.Blob(value, prefix, 'value', { strict: false })
- : webidl.converters.USVString(value, prefix, 'value')
- filename = arguments.length === 3
- ? webidl.converters.USVString(filename, prefix, 'filename')
- : undefined
-
- // 2. Let entry be the result of creating an entry with
- // name, value, and filename if given.
- const entry = makeEntry(name, value, filename)
-
- // 3. Append entry to this’s entry list.
- this[kState].push(entry)
- }
-
- delete (name) {
- webidl.brandCheck(this, FormData)
-
- const prefix = 'FormData.delete'
- webidl.argumentLengthCheck(arguments, 1, prefix)
-
- name = webidl.converters.USVString(name, prefix, 'name')
-
- // The delete(name) method steps are to remove all entries whose name
- // is name from this’s entry list.
- this[kState] = this[kState].filter(entry => entry.name !== name)
- }
-
- get (name) {
- webidl.brandCheck(this, FormData)
-
- const prefix = 'FormData.get'
- webidl.argumentLengthCheck(arguments, 1, prefix)
-
- name = webidl.converters.USVString(name, prefix, 'name')
-
- // 1. If there is no entry whose name is name in this’s entry list,
- // then return null.
- const idx = this[kState].findIndex((entry) => entry.name === name)
- if (idx === -1) {
- return null
+ return -1;
+}
+function isFlowToken(token) {
+ switch (token?.type) {
+ case 'alias':
+ case 'scalar':
+ case 'single-quoted-scalar':
+ case 'double-quoted-scalar':
+ case 'flow-collection':
+ return true;
+ default:
+ return false;
}
-
- // 2. Return the value of the first entry whose name is name from
- // this’s entry list.
- return this[kState][idx].value
- }
-
- getAll (name) {
- webidl.brandCheck(this, FormData)
-
- const prefix = 'FormData.getAll'
- webidl.argumentLengthCheck(arguments, 1, prefix)
-
- name = webidl.converters.USVString(name, prefix, 'name')
-
- // 1. If there is no entry whose name is name in this’s entry list,
- // then return the empty list.
- // 2. Return the values of all entries whose name is name, in order,
- // from this’s entry list.
- return this[kState]
- .filter((entry) => entry.name === name)
- .map((entry) => entry.value)
- }
-
- has (name) {
- webidl.brandCheck(this, FormData)
-
- const prefix = 'FormData.has'
- webidl.argumentLengthCheck(arguments, 1, prefix)
-
- name = webidl.converters.USVString(name, prefix, 'name')
-
- // The has(name) method steps are to return true if there is an entry
- // whose name is name in this’s entry list; otherwise false.
- return this[kState].findIndex((entry) => entry.name === name) !== -1
- }
-
- set (name, value, filename = undefined) {
- webidl.brandCheck(this, FormData)
-
- const prefix = 'FormData.set'
- webidl.argumentLengthCheck(arguments, 2, prefix)
-
- if (arguments.length === 3 && !isBlobLike(value)) {
- throw new TypeError(
- "Failed to execute 'set' on 'FormData': parameter 2 is not of type 'Blob'"
- )
- }
-
- // The set(name, value) and set(name, blobValue, filename) method steps
- // are:
-
- // 1. Let value be value if given; otherwise blobValue.
-
- name = webidl.converters.USVString(name, prefix, 'name')
- value = isBlobLike(value)
- ? webidl.converters.Blob(value, prefix, 'name', { strict: false })
- : webidl.converters.USVString(value, prefix, 'name')
- filename = arguments.length === 3
- ? webidl.converters.USVString(filename, prefix, 'name')
- : undefined
-
- // 2. Let entry be the result of creating an entry with name, value, and
- // filename if given.
- const entry = makeEntry(name, value, filename)
-
- // 3. If there are entries in this’s entry list whose name is name, then
- // replace the first such entry with entry and remove the others.
- const idx = this[kState].findIndex((entry) => entry.name === name)
- if (idx !== -1) {
- this[kState] = [
- ...this[kState].slice(0, idx),
- entry,
- ...this[kState].slice(idx + 1).filter((entry) => entry.name !== name)
- ]
- } else {
- // 4. Otherwise, append entry to this’s entry list.
- this[kState].push(entry)
- }
- }
-
- [nodeUtil.inspect.custom] (depth, options) {
- const state = this[kState].reduce((a, b) => {
- if (a[b.name]) {
- if (Array.isArray(a[b.name])) {
- a[b.name].push(b.value)
- } else {
- a[b.name] = [a[b.name], b.value]
+}
+function getPrevProps(parent) {
+ switch (parent.type) {
+ case 'document':
+ return parent.start;
+ case 'block-map': {
+ const it = parent.items[parent.items.length - 1];
+ return it.sep ?? it.start;
}
- } else {
- a[b.name] = b.value
- }
-
- return a
- }, { __proto__: null })
-
- options.depth ??= depth
- options.colors ??= true
-
- const output = nodeUtil.formatWithOptions(options, state)
-
- // remove [Object null prototype]
- return `FormData ${output.slice(output.indexOf(']') + 2)}`
- }
+ case 'block-seq':
+ return parent.items[parent.items.length - 1].start;
+ /* istanbul ignore next should not happen */
+ default:
+ return [];
+ }
}
-
-iteratorMixin('FormData', FormData, kState, 'name', 'value')
-
-Object.defineProperties(FormData.prototype, {
- append: kEnumerableProperty,
- delete: kEnumerableProperty,
- get: kEnumerableProperty,
- getAll: kEnumerableProperty,
- has: kEnumerableProperty,
- set: kEnumerableProperty,
- [Symbol.toStringTag]: {
- value: 'FormData',
- configurable: true
- }
-})
-
-/**
- * @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#create-an-entry
- * @param {string} name
- * @param {string|Blob} value
- * @param {?string} filename
- * @returns
- */
-function makeEntry (name, value, filename) {
- // 1. Set name to the result of converting name into a scalar value string.
- // Note: This operation was done by the webidl converter USVString.
-
- // 2. If value is a string, then set value to the result of converting
- // value into a scalar value string.
- if (typeof value === 'string') {
- // Note: This operation was done by the webidl converter USVString.
- } else {
- // 3. Otherwise:
-
- // 1. If value is not a File object, then set value to a new File object,
- // representing the same bytes, whose name attribute value is "blob"
- if (!isFileLike(value)) {
- value = value instanceof Blob
- ? new File([value], 'blob', { type: value.type })
- : new FileLike(value, 'blob', { type: value.type })
+/** Note: May modify input array */
+function getFirstKeyStartProps(prev) {
+ if (prev.length === 0)
+ return [];
+ let i = prev.length;
+ loop: while (--i >= 0) {
+ switch (prev[i].type) {
+ case 'doc-start':
+ case 'explicit-key-ind':
+ case 'map-value-ind':
+ case 'seq-item-ind':
+ case 'newline':
+ break loop;
+ }
}
-
- // 2. If filename is given, then set value to a new File object,
- // representing the same bytes, whose name attribute is filename.
- if (filename !== undefined) {
- /** @type {FilePropertyBag} */
- const options = {
- type: value.type,
- lastModified: value.lastModified
- }
-
- value = value instanceof NativeFile
- ? new File([value], filename, options)
- : new FileLike(value, filename, options)
+ while (prev[++i]?.type === 'space') {
+ /* loop */
}
- }
-
- // 4. Return an entry whose name is name and whose value is value.
- return { name, value }
-}
-
-module.exports = { FormData, makeEntry }
-
-
-/***/ }),
-
-/***/ 2443:
-/***/ ((module) => {
-
-
-
-// In case of breaking changes, increase the version
-// number to avoid conflicts.
-const globalOrigin = Symbol.for('undici.globalOrigin.1')
-
-function getGlobalOrigin () {
- return globalThis[globalOrigin]
-}
-
-function setGlobalOrigin (newOrigin) {
- if (newOrigin === undefined) {
- Object.defineProperty(globalThis, globalOrigin, {
- value: undefined,
- writable: true,
- enumerable: false,
- configurable: false
- })
-
- return
- }
-
- const parsedURL = new URL(newOrigin)
-
- if (parsedURL.protocol !== 'http:' && parsedURL.protocol !== 'https:') {
- throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`)
- }
-
- Object.defineProperty(globalThis, globalOrigin, {
- value: parsedURL,
- writable: true,
- enumerable: false,
- configurable: false
- })
-}
-
-module.exports = {
- getGlobalOrigin,
- setGlobalOrigin
-}
-
-
-/***/ }),
-
-/***/ 3676:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-// https://github.com/Ethan-Arrowood/undici-fetch
-
-
-
-const { kConstruct } = __nccwpck_require__(9411)
-const { kEnumerableProperty } = __nccwpck_require__(1544)
-const {
- iteratorMixin,
- isValidHeaderName,
- isValidHeaderValue
-} = __nccwpck_require__(4296)
-const { webidl } = __nccwpck_require__(253)
-const assert = __nccwpck_require__(4589)
-const util = __nccwpck_require__(7975)
-
-const kHeadersMap = Symbol('headers map')
-const kHeadersSortedMap = Symbol('headers map sorted')
-
-/**
- * @param {number} code
- */
-function isHTTPWhiteSpaceCharCode (code) {
- return code === 0x00a || code === 0x00d || code === 0x009 || code === 0x020
+ return prev.splice(i, prev.length);
}
-
-/**
- * @see https://fetch.spec.whatwg.org/#concept-header-value-normalize
- * @param {string} potentialValue
- */
-function headerValueNormalize (potentialValue) {
- // To normalize a byte sequence potentialValue, remove
- // any leading and trailing HTTP whitespace bytes from
- // potentialValue.
- let i = 0; let j = potentialValue.length
-
- while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j - 1))) --j
- while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i))) ++i
-
- return i === 0 && j === potentialValue.length ? potentialValue : potentialValue.substring(i, j)
+function arrayPushArray(target, source) {
+ // May exhaust call stack with large `source` array
+ if (source.length < 1e5)
+ Array.prototype.push.apply(target, source);
+ else
+ for (let i = 0; i < source.length; ++i)
+ target.push(source[i]);
}
-
-function fill (headers, object) {
- // To fill a Headers object headers with a given object object, run these steps:
-
- // 1. If object is a sequence, then for each header in object:
- // Note: webidl conversion to array has already been done.
- if (Array.isArray(object)) {
- for (let i = 0; i < object.length; ++i) {
- const header = object[i]
- // 1. If header does not contain exactly two items, then throw a TypeError.
- if (header.length !== 2) {
- throw webidl.errors.exception({
- header: 'Headers constructor',
- message: `expected name/value pair to be length 2, found ${header.length}.`
- })
- }
-
- // 2. Append (header’s first item, header’s second item) to headers.
- appendHeader(headers, header[0], header[1])
- }
- } else if (typeof object === 'object' && object !== null) {
- // Note: null should throw
-
- // 2. Otherwise, object is a record, then for each key → value in object,
- // append (key, value) to headers
- const keys = Object.keys(object)
- for (let i = 0; i < keys.length; ++i) {
- appendHeader(headers, keys[i], object[keys[i]])
+function fixFlowSeqItems(fc) {
+ if (fc.start.type === 'flow-seq-start') {
+ for (const it of fc.items) {
+ if (it.sep &&
+ !it.value &&
+ !includesToken(it.start, 'explicit-key-ind') &&
+ !includesToken(it.sep, 'map-value-ind')) {
+ if (it.key)
+ it.value = it.key;
+ delete it.key;
+ if (isFlowToken(it.value)) {
+ if (it.value.end)
+ arrayPushArray(it.value.end, it.sep);
+ else
+ it.value.end = it.sep;
+ }
+ else
+ arrayPushArray(it.start, it.sep);
+ delete it.sep;
+ }
+ }
}
- } else {
- throw webidl.errors.conversionFailed({
- prefix: 'Headers constructor',
- argument: 'Argument 1',
- types: ['sequence>', 'record']
- })
- }
}
-
/**
- * @see https://fetch.spec.whatwg.org/#concept-headers-append
+ * A YAML concrete syntax tree (CST) parser
+ *
+ * ```ts
+ * const src: string = ...
+ * for (const token of new Parser().parse(src)) {
+ * // token: Token
+ * }
+ * ```
+ *
+ * To use the parser with a user-provided lexer:
+ *
+ * ```ts
+ * function* parse(source: string, lexer: Lexer) {
+ * const parser = new Parser()
+ * for (const lexeme of lexer.lex(source))
+ * yield* parser.next(lexeme)
+ * yield* parser.end()
+ * }
+ *
+ * const src: string = ...
+ * const lexer = new Lexer()
+ * for (const token of parse(src, lexer)) {
+ * // token: Token
+ * }
+ * ```
*/
-function appendHeader (headers, name, value) {
- // 1. Normalize value.
- value = headerValueNormalize(value)
-
- // 2. If name is not a header name or value is not a
- // header value, then throw a TypeError.
- if (!isValidHeaderName(name)) {
- throw webidl.errors.invalidArgument({
- prefix: 'Headers.append',
- value: name,
- type: 'header name'
- })
- } else if (!isValidHeaderValue(value)) {
- throw webidl.errors.invalidArgument({
- prefix: 'Headers.append',
- value,
- type: 'header value'
- })
- }
-
- // 3. If headers’s guard is "immutable", then throw a TypeError.
- // 4. Otherwise, if headers’s guard is "request" and name is a
- // forbidden header name, return.
- // 5. Otherwise, if headers’s guard is "request-no-cors":
- // TODO
- // Note: undici does not implement forbidden header names
- if (getHeadersGuard(headers) === 'immutable') {
- throw new TypeError('immutable')
- }
-
- // 6. Otherwise, if headers’s guard is "response" and name is a
- // forbidden response-header name, return.
-
- // 7. Append (name, value) to headers’s header list.
- return getHeadersList(headers).append(name, value, false)
-
- // 8. If headers’s guard is "request-no-cors", then remove
- // privileged no-CORS request headers from headers
-}
-
-function compareHeaderName (a, b) {
- return a[0] < b[0] ? -1 : 1
-}
-
-class HeadersList {
- /** @type {[string, string][]|null} */
- cookies = null
-
- constructor (init) {
- if (init instanceof HeadersList) {
- this[kHeadersMap] = new Map(init[kHeadersMap])
- this[kHeadersSortedMap] = init[kHeadersSortedMap]
- this.cookies = init.cookies === null ? null : [...init.cookies]
- } else {
- this[kHeadersMap] = new Map(init)
- this[kHeadersSortedMap] = null
- }
- }
-
- /**
- * @see https://fetch.spec.whatwg.org/#header-list-contains
- * @param {string} name
- * @param {boolean} isLowerCase
- */
- contains (name, isLowerCase) {
- // A header list list contains a header name name if list
- // contains a header whose name is a byte-case-insensitive
- // match for name.
-
- return this[kHeadersMap].has(isLowerCase ? name : name.toLowerCase())
- }
-
- clear () {
- this[kHeadersMap].clear()
- this[kHeadersSortedMap] = null
- this.cookies = null
- }
-
- /**
- * @see https://fetch.spec.whatwg.org/#concept-header-list-append
- * @param {string} name
- * @param {string} value
- * @param {boolean} isLowerCase
- */
- append (name, value, isLowerCase) {
- this[kHeadersSortedMap] = null
-
- // 1. If list contains name, then set name to the first such
- // header’s name.
- const lowercaseName = isLowerCase ? name : name.toLowerCase()
- const exists = this[kHeadersMap].get(lowercaseName)
-
- // 2. Append (name, value) to list.
- if (exists) {
- const delimiter = lowercaseName === 'cookie' ? '; ' : ', '
- this[kHeadersMap].set(lowercaseName, {
- name: exists.name,
- value: `${exists.value}${delimiter}${value}`
- })
- } else {
- this[kHeadersMap].set(lowercaseName, { name, value })
- }
-
- if (lowercaseName === 'set-cookie') {
- (this.cookies ??= []).push(value)
+class Parser {
+ /**
+ * @param onNewLine - If defined, called separately with the start position of
+ * each new line (in `parse()`, including the start of input).
+ */
+ constructor(onNewLine) {
+ /** If true, space and sequence indicators count as indentation */
+ this.atNewLine = true;
+ /** If true, next token is a scalar value */
+ this.atScalar = false;
+ /** Current indentation level */
+ this.indent = 0;
+ /** Current offset since the start of parsing */
+ this.offset = 0;
+ /** On the same line with a block map key */
+ this.onKeyLine = false;
+ /** Top indicates the node that's currently being built */
+ this.stack = [];
+ /** The source of the current token, set in parse() */
+ this.source = '';
+ /** The type of the current token, set in parse() */
+ this.type = '';
+ // Must be defined after `next()`
+ this.lexer = new lexer.Lexer();
+ this.onNewLine = onNewLine;
}
- }
-
- /**
- * @see https://fetch.spec.whatwg.org/#concept-header-list-set
- * @param {string} name
- * @param {string} value
- * @param {boolean} isLowerCase
- */
- set (name, value, isLowerCase) {
- this[kHeadersSortedMap] = null
- const lowercaseName = isLowerCase ? name : name.toLowerCase()
-
- if (lowercaseName === 'set-cookie') {
- this.cookies = [value]
+ /**
+ * Parse `source` as a YAML stream.
+ * If `incomplete`, a part of the last line may be left as a buffer for the next call.
+ *
+ * Errors are not thrown, but yielded as `{ type: 'error', message }` tokens.
+ *
+ * @returns A generator of tokens representing each directive, document, and other structure.
+ */
+ *parse(source, incomplete = false) {
+ if (this.onNewLine && this.offset === 0)
+ this.onNewLine(0);
+ for (const lexeme of this.lexer.lex(source, incomplete))
+ yield* this.next(lexeme);
+ if (!incomplete)
+ yield* this.end();
}
-
- // 1. If list contains name, then set the value of
- // the first such header to value and remove the
- // others.
- // 2. Otherwise, append header (name, value) to list.
- this[kHeadersMap].set(lowercaseName, { name, value })
- }
-
- /**
- * @see https://fetch.spec.whatwg.org/#concept-header-list-delete
- * @param {string} name
- * @param {boolean} isLowerCase
- */
- delete (name, isLowerCase) {
- this[kHeadersSortedMap] = null
- if (!isLowerCase) name = name.toLowerCase()
-
- if (name === 'set-cookie') {
- this.cookies = null
+ /**
+ * Advance the parser by the `source` of one lexical token.
+ */
+ *next(source) {
+ this.source = source;
+ if (node_process.env.LOG_TOKENS)
+ console.log('|', cst.prettyToken(source));
+ if (this.atScalar) {
+ this.atScalar = false;
+ yield* this.step();
+ this.offset += source.length;
+ return;
+ }
+ const type = cst.tokenType(source);
+ if (!type) {
+ const message = `Not a YAML token: ${source}`;
+ yield* this.pop({ type: 'error', offset: this.offset, message, source });
+ this.offset += source.length;
+ }
+ else if (type === 'scalar') {
+ this.atNewLine = false;
+ this.atScalar = true;
+ this.type = 'scalar';
+ }
+ else {
+ this.type = type;
+ yield* this.step();
+ switch (type) {
+ case 'newline':
+ this.atNewLine = true;
+ this.indent = 0;
+ if (this.onNewLine)
+ this.onNewLine(this.offset + source.length);
+ break;
+ case 'space':
+ if (this.atNewLine && source[0] === ' ')
+ this.indent += source.length;
+ break;
+ case 'explicit-key-ind':
+ case 'map-value-ind':
+ case 'seq-item-ind':
+ if (this.atNewLine)
+ this.indent += source.length;
+ break;
+ case 'doc-mode':
+ case 'flow-error-end':
+ return;
+ default:
+ this.atNewLine = false;
+ }
+ this.offset += source.length;
+ }
}
-
- this[kHeadersMap].delete(name)
- }
-
- /**
- * @see https://fetch.spec.whatwg.org/#concept-header-list-get
- * @param {string} name
- * @param {boolean} isLowerCase
- * @returns {string | null}
- */
- get (name, isLowerCase) {
- // 1. If list does not contain name, then return null.
- // 2. Return the values of all headers in list whose name
- // is a byte-case-insensitive match for name,
- // separated from each other by 0x2C 0x20, in order.
- return this[kHeadersMap].get(isLowerCase ? name : name.toLowerCase())?.value ?? null
- }
-
- * [Symbol.iterator] () {
- // use the lowercased name
- for (const { 0: name, 1: { value } } of this[kHeadersMap]) {
- yield [name, value]
+ /** Call at end of input to push out any remaining constructions */
+ *end() {
+ while (this.stack.length > 0)
+ yield* this.pop();
}
- }
-
- get entries () {
- const headers = {}
-
- if (this[kHeadersMap].size !== 0) {
- for (const { name, value } of this[kHeadersMap].values()) {
- headers[name] = value
- }
+ get sourceToken() {
+ const st = {
+ type: this.type,
+ offset: this.offset,
+ indent: this.indent,
+ source: this.source
+ };
+ return st;
}
-
- return headers
- }
-
- rawValues () {
- return this[kHeadersMap].values()
- }
-
- get entriesList () {
- const headers = []
-
- if (this[kHeadersMap].size !== 0) {
- for (const { 0: lowerName, 1: { name, value } } of this[kHeadersMap]) {
- if (lowerName === 'set-cookie') {
- for (const cookie of this.cookies) {
- headers.push([name, cookie])
- }
- } else {
- headers.push([name, value])
+ *step() {
+ const top = this.peek(1);
+ if (this.type === 'doc-end' && top?.type !== 'doc-end') {
+ while (this.stack.length > 0)
+ yield* this.pop();
+ this.stack.push({
+ type: 'doc-end',
+ offset: this.offset,
+ source: this.source
+ });
+ return;
}
- }
+ if (!top)
+ return yield* this.stream();
+ switch (top.type) {
+ case 'document':
+ return yield* this.document(top);
+ case 'alias':
+ case 'scalar':
+ case 'single-quoted-scalar':
+ case 'double-quoted-scalar':
+ return yield* this.scalar(top);
+ case 'block-scalar':
+ return yield* this.blockScalar(top);
+ case 'block-map':
+ return yield* this.blockMap(top);
+ case 'block-seq':
+ return yield* this.blockSequence(top);
+ case 'flow-collection':
+ return yield* this.flowCollection(top);
+ case 'doc-end':
+ return yield* this.documentEnd(top);
+ }
+ /* istanbul ignore next should not happen */
+ yield* this.pop();
}
-
- return headers
- }
-
- // https://fetch.spec.whatwg.org/#convert-header-names-to-a-sorted-lowercase-set
- toSortedArray () {
- const size = this[kHeadersMap].size
- const array = new Array(size)
- // In most cases, you will use the fast-path.
- // fast-path: Use binary insertion sort for small arrays.
- if (size <= 32) {
- if (size === 0) {
- // If empty, it is an empty array. To avoid the first index assignment.
- return array
- }
- // Improve performance by unrolling loop and avoiding double-loop.
- // Double-loop-less version of the binary insertion sort.
- const iterator = this[kHeadersMap][Symbol.iterator]()
- const firstValue = iterator.next().value
- // set [name, value] to first index.
- array[0] = [firstValue[0], firstValue[1].value]
- // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine
- // 3.2.2. Assert: value is non-null.
- assert(firstValue[1].value !== null)
- for (
- let i = 1, j = 0, right = 0, left = 0, pivot = 0, x, value;
- i < size;
- ++i
- ) {
- // get next value
- value = iterator.next().value
- // set [name, value] to current index.
- x = array[i] = [value[0], value[1].value]
- // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine
- // 3.2.2. Assert: value is non-null.
- assert(x[1] !== null)
- left = 0
- right = i
- // binary search
- while (left < right) {
- // middle index
- pivot = left + ((right - left) >> 1)
- // compare header name
- if (array[pivot][0] <= x[0]) {
- left = pivot + 1
- } else {
- right = pivot
- }
+ peek(n) {
+ return this.stack[this.stack.length - n];
+ }
+ *pop(error) {
+ const token = error ?? this.stack.pop();
+ /* istanbul ignore if should not happen */
+ if (!token) {
+ const message = 'Tried to pop an empty stack';
+ yield { type: 'error', offset: this.offset, source: '', message };
}
- if (i !== pivot) {
- j = i
- while (j > left) {
- array[j] = array[--j]
- }
- array[left] = x
+ else if (this.stack.length === 0) {
+ yield token;
+ }
+ else {
+ const top = this.peek(1);
+ if (token.type === 'block-scalar') {
+ // Block scalars use their parent rather than header indent
+ token.indent = 'indent' in top ? top.indent : 0;
+ }
+ else if (token.type === 'flow-collection' && top.type === 'document') {
+ // Ignore all indent for top-level flow collections
+ token.indent = 0;
+ }
+ if (token.type === 'flow-collection')
+ fixFlowSeqItems(token);
+ switch (top.type) {
+ case 'document':
+ top.value = token;
+ break;
+ case 'block-scalar':
+ top.props.push(token); // error
+ break;
+ case 'block-map': {
+ const it = top.items[top.items.length - 1];
+ if (it.value) {
+ top.items.push({ start: [], key: token, sep: [] });
+ this.onKeyLine = true;
+ return;
+ }
+ else if (it.sep) {
+ it.value = token;
+ }
+ else {
+ Object.assign(it, { key: token, sep: [] });
+ this.onKeyLine = !it.explicitKey;
+ return;
+ }
+ break;
+ }
+ case 'block-seq': {
+ const it = top.items[top.items.length - 1];
+ if (it.value)
+ top.items.push({ start: [], value: token });
+ else
+ it.value = token;
+ break;
+ }
+ case 'flow-collection': {
+ const it = top.items[top.items.length - 1];
+ if (!it || it.value)
+ top.items.push({ start: [], key: token, sep: [] });
+ else if (it.sep)
+ it.value = token;
+ else
+ Object.assign(it, { key: token, sep: [] });
+ return;
+ }
+ /* istanbul ignore next should not happen */
+ default:
+ yield* this.pop();
+ yield* this.pop(token);
+ }
+ if ((top.type === 'document' ||
+ top.type === 'block-map' ||
+ top.type === 'block-seq') &&
+ (token.type === 'block-map' || token.type === 'block-seq')) {
+ const last = token.items[token.items.length - 1];
+ if (last &&
+ !last.sep &&
+ !last.value &&
+ last.start.length > 0 &&
+ findNonEmptyIndex(last.start) === -1 &&
+ (token.indent === 0 ||
+ last.start.every(st => st.type !== 'comment' || st.indent < token.indent))) {
+ if (top.type === 'document')
+ top.end = last.start;
+ else
+ top.items.push({ start: last.start });
+ token.items.splice(-1, 1);
+ }
+ }
}
- }
- /* c8 ignore next 4 */
- if (!iterator.next().done) {
- // This is for debugging and will never be called.
- throw new TypeError('Unreachable')
- }
- return array
- } else {
- // This case would be a rare occurrence.
- // slow-path: fallback
- let i = 0
- for (const { 0: name, 1: { value } } of this[kHeadersMap]) {
- array[i++] = [name, value]
- // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine
- // 3.2.2. Assert: value is non-null.
- assert(value !== null)
- }
- return array.sort(compareHeaderName)
}
- }
-}
-
-// https://fetch.spec.whatwg.org/#headers-class
-class Headers {
- #guard
- #headersList
-
- constructor (init = undefined) {
- webidl.util.markAsUncloneable(this)
-
- if (init === kConstruct) {
- return
+ *stream() {
+ switch (this.type) {
+ case 'directive-line':
+ yield { type: 'directive', offset: this.offset, source: this.source };
+ return;
+ case 'byte-order-mark':
+ case 'space':
+ case 'comment':
+ case 'newline':
+ yield this.sourceToken;
+ return;
+ case 'doc-mode':
+ case 'doc-start': {
+ const doc = {
+ type: 'document',
+ offset: this.offset,
+ start: []
+ };
+ if (this.type === 'doc-start')
+ doc.start.push(this.sourceToken);
+ this.stack.push(doc);
+ return;
+ }
+ }
+ yield {
+ type: 'error',
+ offset: this.offset,
+ message: `Unexpected ${this.type} token in YAML stream`,
+ source: this.source
+ };
}
-
- this.#headersList = new HeadersList()
-
- // The new Headers(init) constructor steps are:
-
- // 1. Set this’s guard to "none".
- this.#guard = 'none'
-
- // 2. If init is given, then fill this with init.
- if (init !== undefined) {
- init = webidl.converters.HeadersInit(init, 'Headers contructor', 'init')
- fill(this, init)
+ *document(doc) {
+ if (doc.value)
+ return yield* this.lineEnd(doc);
+ switch (this.type) {
+ case 'doc-start': {
+ if (findNonEmptyIndex(doc.start) !== -1) {
+ yield* this.pop();
+ yield* this.step();
+ }
+ else
+ doc.start.push(this.sourceToken);
+ return;
+ }
+ case 'anchor':
+ case 'tag':
+ case 'space':
+ case 'comment':
+ case 'newline':
+ doc.start.push(this.sourceToken);
+ return;
+ }
+ const bv = this.startBlockValue(doc);
+ if (bv)
+ this.stack.push(bv);
+ else {
+ yield {
+ type: 'error',
+ offset: this.offset,
+ message: `Unexpected ${this.type} token in YAML document`,
+ source: this.source
+ };
+ }
}
- }
-
- // https://fetch.spec.whatwg.org/#dom-headers-append
- append (name, value) {
- webidl.brandCheck(this, Headers)
-
- webidl.argumentLengthCheck(arguments, 2, 'Headers.append')
-
- const prefix = 'Headers.append'
- name = webidl.converters.ByteString(name, prefix, 'name')
- value = webidl.converters.ByteString(value, prefix, 'value')
-
- return appendHeader(this, name, value)
- }
-
- // https://fetch.spec.whatwg.org/#dom-headers-delete
- delete (name) {
- webidl.brandCheck(this, Headers)
-
- webidl.argumentLengthCheck(arguments, 1, 'Headers.delete')
-
- const prefix = 'Headers.delete'
- name = webidl.converters.ByteString(name, prefix, 'name')
-
- // 1. If name is not a header name, then throw a TypeError.
- if (!isValidHeaderName(name)) {
- throw webidl.errors.invalidArgument({
- prefix: 'Headers.delete',
- value: name,
- type: 'header name'
- })
+ *scalar(scalar) {
+ if (this.type === 'map-value-ind') {
+ const prev = getPrevProps(this.peek(2));
+ const start = getFirstKeyStartProps(prev);
+ let sep;
+ if (scalar.end) {
+ sep = scalar.end;
+ sep.push(this.sourceToken);
+ delete scalar.end;
+ }
+ else
+ sep = [this.sourceToken];
+ const map = {
+ type: 'block-map',
+ offset: scalar.offset,
+ indent: scalar.indent,
+ items: [{ start, key: scalar, sep }]
+ };
+ this.onKeyLine = true;
+ this.stack[this.stack.length - 1] = map;
+ }
+ else
+ yield* this.lineEnd(scalar);
}
-
- // 2. If this’s guard is "immutable", then throw a TypeError.
- // 3. Otherwise, if this’s guard is "request" and name is a
- // forbidden header name, return.
- // 4. Otherwise, if this’s guard is "request-no-cors", name
- // is not a no-CORS-safelisted request-header name, and
- // name is not a privileged no-CORS request-header name,
- // return.
- // 5. Otherwise, if this’s guard is "response" and name is
- // a forbidden response-header name, return.
- // Note: undici does not implement forbidden header names
- if (this.#guard === 'immutable') {
- throw new TypeError('immutable')
+ *blockScalar(scalar) {
+ switch (this.type) {
+ case 'space':
+ case 'comment':
+ case 'newline':
+ scalar.props.push(this.sourceToken);
+ return;
+ case 'scalar':
+ scalar.source = this.source;
+ // block-scalar source includes trailing newline
+ this.atNewLine = true;
+ this.indent = 0;
+ if (this.onNewLine) {
+ let nl = this.source.indexOf('\n') + 1;
+ while (nl !== 0) {
+ this.onNewLine(this.offset + nl);
+ nl = this.source.indexOf('\n', nl) + 1;
+ }
+ }
+ yield* this.pop();
+ break;
+ /* istanbul ignore next should not happen */
+ default:
+ yield* this.pop();
+ yield* this.step();
+ }
}
-
- // 6. If this’s header list does not contain name, then
- // return.
- if (!this.#headersList.contains(name, false)) {
- return
+ *blockMap(map) {
+ const it = map.items[map.items.length - 1];
+ // it.sep is true-ish if pair already has key or : separator
+ switch (this.type) {
+ case 'newline':
+ this.onKeyLine = false;
+ if (it.value) {
+ const end = 'end' in it.value ? it.value.end : undefined;
+ const last = Array.isArray(end) ? end[end.length - 1] : undefined;
+ if (last?.type === 'comment')
+ end?.push(this.sourceToken);
+ else
+ map.items.push({ start: [this.sourceToken] });
+ }
+ else if (it.sep) {
+ it.sep.push(this.sourceToken);
+ }
+ else {
+ it.start.push(this.sourceToken);
+ }
+ return;
+ case 'space':
+ case 'comment':
+ if (it.value) {
+ map.items.push({ start: [this.sourceToken] });
+ }
+ else if (it.sep) {
+ it.sep.push(this.sourceToken);
+ }
+ else {
+ if (this.atIndentedComment(it.start, map.indent)) {
+ const prev = map.items[map.items.length - 2];
+ const end = prev?.value?.end;
+ if (Array.isArray(end)) {
+ arrayPushArray(end, it.start);
+ end.push(this.sourceToken);
+ map.items.pop();
+ return;
+ }
+ }
+ it.start.push(this.sourceToken);
+ }
+ return;
+ }
+ if (this.indent >= map.indent) {
+ const atMapIndent = !this.onKeyLine && this.indent === map.indent;
+ const atNextItem = atMapIndent &&
+ (it.sep || it.explicitKey) &&
+ this.type !== 'seq-item-ind';
+ // For empty nodes, assign newline-separated not indented empty tokens to following node
+ let start = [];
+ if (atNextItem && it.sep && !it.value) {
+ const nl = [];
+ for (let i = 0; i < it.sep.length; ++i) {
+ const st = it.sep[i];
+ switch (st.type) {
+ case 'newline':
+ nl.push(i);
+ break;
+ case 'space':
+ break;
+ case 'comment':
+ if (st.indent > map.indent)
+ nl.length = 0;
+ break;
+ default:
+ nl.length = 0;
+ }
+ }
+ if (nl.length >= 2)
+ start = it.sep.splice(nl[1]);
+ }
+ switch (this.type) {
+ case 'anchor':
+ case 'tag':
+ if (atNextItem || it.value) {
+ start.push(this.sourceToken);
+ map.items.push({ start });
+ this.onKeyLine = true;
+ }
+ else if (it.sep) {
+ it.sep.push(this.sourceToken);
+ }
+ else {
+ it.start.push(this.sourceToken);
+ }
+ return;
+ case 'explicit-key-ind':
+ if (!it.sep && !it.explicitKey) {
+ it.start.push(this.sourceToken);
+ it.explicitKey = true;
+ }
+ else if (atNextItem || it.value) {
+ start.push(this.sourceToken);
+ map.items.push({ start, explicitKey: true });
+ }
+ else {
+ this.stack.push({
+ type: 'block-map',
+ offset: this.offset,
+ indent: this.indent,
+ items: [{ start: [this.sourceToken], explicitKey: true }]
+ });
+ }
+ this.onKeyLine = true;
+ return;
+ case 'map-value-ind':
+ if (it.explicitKey) {
+ if (!it.sep) {
+ if (includesToken(it.start, 'newline')) {
+ Object.assign(it, { key: null, sep: [this.sourceToken] });
+ }
+ else {
+ const start = getFirstKeyStartProps(it.start);
+ this.stack.push({
+ type: 'block-map',
+ offset: this.offset,
+ indent: this.indent,
+ items: [{ start, key: null, sep: [this.sourceToken] }]
+ });
+ }
+ }
+ else if (it.value) {
+ map.items.push({ start: [], key: null, sep: [this.sourceToken] });
+ }
+ else if (includesToken(it.sep, 'map-value-ind')) {
+ this.stack.push({
+ type: 'block-map',
+ offset: this.offset,
+ indent: this.indent,
+ items: [{ start, key: null, sep: [this.sourceToken] }]
+ });
+ }
+ else if (isFlowToken(it.key) &&
+ !includesToken(it.sep, 'newline')) {
+ const start = getFirstKeyStartProps(it.start);
+ const key = it.key;
+ const sep = it.sep;
+ sep.push(this.sourceToken);
+ // @ts-expect-error type guard is wrong here
+ delete it.key;
+ // @ts-expect-error type guard is wrong here
+ delete it.sep;
+ this.stack.push({
+ type: 'block-map',
+ offset: this.offset,
+ indent: this.indent,
+ items: [{ start, key, sep }]
+ });
+ }
+ else if (start.length > 0) {
+ // Not actually at next item
+ it.sep = it.sep.concat(start, this.sourceToken);
+ }
+ else {
+ it.sep.push(this.sourceToken);
+ }
+ }
+ else {
+ if (!it.sep) {
+ Object.assign(it, { key: null, sep: [this.sourceToken] });
+ }
+ else if (it.value || atNextItem) {
+ map.items.push({ start, key: null, sep: [this.sourceToken] });
+ }
+ else if (includesToken(it.sep, 'map-value-ind')) {
+ this.stack.push({
+ type: 'block-map',
+ offset: this.offset,
+ indent: this.indent,
+ items: [{ start: [], key: null, sep: [this.sourceToken] }]
+ });
+ }
+ else {
+ it.sep.push(this.sourceToken);
+ }
+ }
+ this.onKeyLine = true;
+ return;
+ case 'alias':
+ case 'scalar':
+ case 'single-quoted-scalar':
+ case 'double-quoted-scalar': {
+ const fs = this.flowScalar(this.type);
+ if (atNextItem || it.value) {
+ map.items.push({ start, key: fs, sep: [] });
+ this.onKeyLine = true;
+ }
+ else if (it.sep) {
+ this.stack.push(fs);
+ }
+ else {
+ Object.assign(it, { key: fs, sep: [] });
+ this.onKeyLine = true;
+ }
+ return;
+ }
+ default: {
+ const bv = this.startBlockValue(map);
+ if (bv) {
+ if (bv.type === 'block-seq') {
+ if (!it.explicitKey &&
+ it.sep &&
+ !includesToken(it.sep, 'newline')) {
+ yield* this.pop({
+ type: 'error',
+ offset: this.offset,
+ message: 'Unexpected block-seq-ind on same line with key',
+ source: this.source
+ });
+ return;
+ }
+ }
+ else if (atMapIndent) {
+ map.items.push({ start });
+ }
+ this.stack.push(bv);
+ return;
+ }
+ }
+ }
+ }
+ yield* this.pop();
+ yield* this.step();
+ }
+ *blockSequence(seq) {
+ const it = seq.items[seq.items.length - 1];
+ switch (this.type) {
+ case 'newline':
+ if (it.value) {
+ const end = 'end' in it.value ? it.value.end : undefined;
+ const last = Array.isArray(end) ? end[end.length - 1] : undefined;
+ if (last?.type === 'comment')
+ end?.push(this.sourceToken);
+ else
+ seq.items.push({ start: [this.sourceToken] });
+ }
+ else
+ it.start.push(this.sourceToken);
+ return;
+ case 'space':
+ case 'comment':
+ if (it.value)
+ seq.items.push({ start: [this.sourceToken] });
+ else {
+ if (this.atIndentedComment(it.start, seq.indent)) {
+ const prev = seq.items[seq.items.length - 2];
+ const end = prev?.value?.end;
+ if (Array.isArray(end)) {
+ arrayPushArray(end, it.start);
+ end.push(this.sourceToken);
+ seq.items.pop();
+ return;
+ }
+ }
+ it.start.push(this.sourceToken);
+ }
+ return;
+ case 'anchor':
+ case 'tag':
+ if (it.value || this.indent <= seq.indent)
+ break;
+ it.start.push(this.sourceToken);
+ return;
+ case 'seq-item-ind':
+ if (this.indent !== seq.indent)
+ break;
+ if (it.value || includesToken(it.start, 'seq-item-ind'))
+ seq.items.push({ start: [this.sourceToken] });
+ else
+ it.start.push(this.sourceToken);
+ return;
+ }
+ if (this.indent > seq.indent) {
+ const bv = this.startBlockValue(seq);
+ if (bv) {
+ this.stack.push(bv);
+ return;
+ }
+ }
+ yield* this.pop();
+ yield* this.step();
+ }
+ *flowCollection(fc) {
+ const it = fc.items[fc.items.length - 1];
+ if (this.type === 'flow-error-end') {
+ let top;
+ do {
+ yield* this.pop();
+ top = this.peek(1);
+ } while (top?.type === 'flow-collection');
+ }
+ else if (fc.end.length === 0) {
+ switch (this.type) {
+ case 'comma':
+ case 'explicit-key-ind':
+ if (!it || it.sep)
+ fc.items.push({ start: [this.sourceToken] });
+ else
+ it.start.push(this.sourceToken);
+ return;
+ case 'map-value-ind':
+ if (!it || it.value)
+ fc.items.push({ start: [], key: null, sep: [this.sourceToken] });
+ else if (it.sep)
+ it.sep.push(this.sourceToken);
+ else
+ Object.assign(it, { key: null, sep: [this.sourceToken] });
+ return;
+ case 'space':
+ case 'comment':
+ case 'newline':
+ case 'anchor':
+ case 'tag':
+ if (!it || it.value)
+ fc.items.push({ start: [this.sourceToken] });
+ else if (it.sep)
+ it.sep.push(this.sourceToken);
+ else
+ it.start.push(this.sourceToken);
+ return;
+ case 'alias':
+ case 'scalar':
+ case 'single-quoted-scalar':
+ case 'double-quoted-scalar': {
+ const fs = this.flowScalar(this.type);
+ if (!it || it.value)
+ fc.items.push({ start: [], key: fs, sep: [] });
+ else if (it.sep)
+ this.stack.push(fs);
+ else
+ Object.assign(it, { key: fs, sep: [] });
+ return;
+ }
+ case 'flow-map-end':
+ case 'flow-seq-end':
+ fc.end.push(this.sourceToken);
+ return;
+ }
+ const bv = this.startBlockValue(fc);
+ /* istanbul ignore else should not happen */
+ if (bv)
+ this.stack.push(bv);
+ else {
+ yield* this.pop();
+ yield* this.step();
+ }
+ }
+ else {
+ const parent = this.peek(2);
+ if (parent.type === 'block-map' &&
+ ((this.type === 'map-value-ind' && parent.indent === fc.indent) ||
+ (this.type === 'newline' &&
+ !parent.items[parent.items.length - 1].sep))) {
+ yield* this.pop();
+ yield* this.step();
+ }
+ else if (this.type === 'map-value-ind' &&
+ parent.type !== 'flow-collection') {
+ const prev = getPrevProps(parent);
+ const start = getFirstKeyStartProps(prev);
+ fixFlowSeqItems(fc);
+ const sep = fc.end.splice(1, fc.end.length);
+ sep.push(this.sourceToken);
+ const map = {
+ type: 'block-map',
+ offset: fc.offset,
+ indent: fc.indent,
+ items: [{ start, key: fc, sep }]
+ };
+ this.onKeyLine = true;
+ this.stack[this.stack.length - 1] = map;
+ }
+ else {
+ yield* this.lineEnd(fc);
+ }
+ }
+ }
+ flowScalar(type) {
+ if (this.onNewLine) {
+ let nl = this.source.indexOf('\n') + 1;
+ while (nl !== 0) {
+ this.onNewLine(this.offset + nl);
+ nl = this.source.indexOf('\n', nl) + 1;
+ }
+ }
+ return {
+ type,
+ offset: this.offset,
+ indent: this.indent,
+ source: this.source
+ };
+ }
+ startBlockValue(parent) {
+ switch (this.type) {
+ case 'alias':
+ case 'scalar':
+ case 'single-quoted-scalar':
+ case 'double-quoted-scalar':
+ return this.flowScalar(this.type);
+ case 'block-scalar-header':
+ return {
+ type: 'block-scalar',
+ offset: this.offset,
+ indent: this.indent,
+ props: [this.sourceToken],
+ source: ''
+ };
+ case 'flow-map-start':
+ case 'flow-seq-start':
+ return {
+ type: 'flow-collection',
+ offset: this.offset,
+ indent: this.indent,
+ start: this.sourceToken,
+ items: [],
+ end: []
+ };
+ case 'seq-item-ind':
+ return {
+ type: 'block-seq',
+ offset: this.offset,
+ indent: this.indent,
+ items: [{ start: [this.sourceToken] }]
+ };
+ case 'explicit-key-ind': {
+ this.onKeyLine = true;
+ const prev = getPrevProps(parent);
+ const start = getFirstKeyStartProps(prev);
+ start.push(this.sourceToken);
+ return {
+ type: 'block-map',
+ offset: this.offset,
+ indent: this.indent,
+ items: [{ start, explicitKey: true }]
+ };
+ }
+ case 'map-value-ind': {
+ this.onKeyLine = true;
+ const prev = getPrevProps(parent);
+ const start = getFirstKeyStartProps(prev);
+ return {
+ type: 'block-map',
+ offset: this.offset,
+ indent: this.indent,
+ items: [{ start, key: null, sep: [this.sourceToken] }]
+ };
+ }
+ }
+ return null;
+ }
+ atIndentedComment(start, indent) {
+ if (this.type !== 'comment')
+ return false;
+ if (this.indent <= indent)
+ return false;
+ return start.every(st => st.type === 'newline' || st.type === 'space');
+ }
+ *documentEnd(docEnd) {
+ if (this.type !== 'doc-mode') {
+ if (docEnd.end)
+ docEnd.end.push(this.sourceToken);
+ else
+ docEnd.end = [this.sourceToken];
+ if (this.type === 'newline')
+ yield* this.pop();
+ }
+ }
+ *lineEnd(token) {
+ switch (this.type) {
+ case 'comma':
+ case 'doc-start':
+ case 'doc-end':
+ case 'flow-seq-end':
+ case 'flow-map-end':
+ case 'map-value-ind':
+ yield* this.pop();
+ yield* this.step();
+ break;
+ case 'newline':
+ this.onKeyLine = false;
+ // fallthrough
+ case 'space':
+ case 'comment':
+ default:
+ // all other values are errors
+ if (token.end)
+ token.end.push(this.sourceToken);
+ else
+ token.end = [this.sourceToken];
+ if (this.type === 'newline')
+ yield* this.pop();
+ }
}
+}
- // 7. Delete name from this’s header list.
- // 8. If this’s guard is "request-no-cors", then remove
- // privileged no-CORS request headers from this.
- this.#headersList.delete(name, false)
- }
+exports.Parser = Parser;
- // https://fetch.spec.whatwg.org/#dom-headers-get
- get (name) {
- webidl.brandCheck(this, Headers)
- webidl.argumentLengthCheck(arguments, 1, 'Headers.get')
+/***/ }),
- const prefix = 'Headers.get'
- name = webidl.converters.ByteString(name, prefix, 'name')
+/***/ 4047:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 1. If name is not a header name, then throw a TypeError.
- if (!isValidHeaderName(name)) {
- throw webidl.errors.invalidArgument({
- prefix,
- value: name,
- type: 'header name'
- })
- }
- // 2. Return the result of getting name from this’s header
- // list.
- return this.#headersList.get(name, false)
- }
- // https://fetch.spec.whatwg.org/#dom-headers-has
- has (name) {
- webidl.brandCheck(this, Headers)
+var composer = __nccwpck_require__(9984);
+var Document = __nccwpck_require__(3021);
+var errors = __nccwpck_require__(1464);
+var log = __nccwpck_require__(7249);
+var identity = __nccwpck_require__(1127);
+var lineCounter = __nccwpck_require__(6628);
+var parser = __nccwpck_require__(3456);
- webidl.argumentLengthCheck(arguments, 1, 'Headers.has')
+function parseOptions(options) {
+ const prettyErrors = options.prettyErrors !== false;
+ const lineCounter$1 = options.lineCounter || (prettyErrors && new lineCounter.LineCounter()) || null;
+ return { lineCounter: lineCounter$1, prettyErrors };
+}
+/**
+ * Parse the input as a stream of YAML documents.
+ *
+ * Documents should be separated from each other by `...` or `---` marker lines.
+ *
+ * @returns If an empty `docs` array is returned, it will be of type
+ * EmptyStream and contain additional stream information. In
+ * TypeScript, you should use `'empty' in docs` as a type guard for it.
+ */
+function parseAllDocuments(source, options = {}) {
+ const { lineCounter, prettyErrors } = parseOptions(options);
+ const parser$1 = new parser.Parser(lineCounter?.addNewLine);
+ const composer$1 = new composer.Composer(options);
+ const docs = Array.from(composer$1.compose(parser$1.parse(source)));
+ if (prettyErrors && lineCounter)
+ for (const doc of docs) {
+ doc.errors.forEach(errors.prettifyError(source, lineCounter));
+ doc.warnings.forEach(errors.prettifyError(source, lineCounter));
+ }
+ if (docs.length > 0)
+ return docs;
+ return Object.assign([], { empty: true }, composer$1.streamInfo());
+}
+/** Parse an input string into a single YAML.Document */
+function parseDocument(source, options = {}) {
+ const { lineCounter, prettyErrors } = parseOptions(options);
+ const parser$1 = new parser.Parser(lineCounter?.addNewLine);
+ const composer$1 = new composer.Composer(options);
+ // `doc` is always set by compose.end(true) at the very latest
+ let doc = null;
+ for (const _doc of composer$1.compose(parser$1.parse(source), true, source.length)) {
+ if (!doc)
+ doc = _doc;
+ else if (doc.options.logLevel !== 'silent') {
+ doc.errors.push(new errors.YAMLParseError(_doc.range.slice(0, 2), 'MULTIPLE_DOCS', 'Source contains multiple documents; please use YAML.parseAllDocuments()'));
+ break;
+ }
+ }
+ if (prettyErrors && lineCounter) {
+ doc.errors.forEach(errors.prettifyError(source, lineCounter));
+ doc.warnings.forEach(errors.prettifyError(source, lineCounter));
+ }
+ return doc;
+}
+function parse(src, reviver, options) {
+ let _reviver = undefined;
+ if (typeof reviver === 'function') {
+ _reviver = reviver;
+ }
+ else if (options === undefined && reviver && typeof reviver === 'object') {
+ options = reviver;
+ }
+ const doc = parseDocument(src, options);
+ if (!doc)
+ return null;
+ doc.warnings.forEach(warning => log.warn(doc.options.logLevel, warning));
+ if (doc.errors.length > 0) {
+ if (doc.options.logLevel !== 'silent')
+ throw doc.errors[0];
+ else
+ doc.errors = [];
+ }
+ return doc.toJS(Object.assign({ reviver: _reviver }, options));
+}
+function stringify(value, replacer, options) {
+ let _replacer = null;
+ if (typeof replacer === 'function' || Array.isArray(replacer)) {
+ _replacer = replacer;
+ }
+ else if (options === undefined && replacer) {
+ options = replacer;
+ }
+ if (typeof options === 'string')
+ options = options.length;
+ if (typeof options === 'number') {
+ const indent = Math.round(options);
+ options = indent < 1 ? undefined : indent > 8 ? { indent: 8 } : { indent };
+ }
+ if (value === undefined) {
+ const { keepUndefined } = options ?? replacer ?? {};
+ if (!keepUndefined)
+ return undefined;
+ }
+ if (identity.isDocument(value) && !_replacer)
+ return value.toString(options);
+ return new Document.Document(value, _replacer, options).toString(options);
+}
- const prefix = 'Headers.has'
- name = webidl.converters.ByteString(name, prefix, 'name')
+exports.parse = parse;
+exports.parseAllDocuments = parseAllDocuments;
+exports.parseDocument = parseDocument;
+exports.stringify = stringify;
- // 1. If name is not a header name, then throw a TypeError.
- if (!isValidHeaderName(name)) {
- throw webidl.errors.invalidArgument({
- prefix,
- value: name,
- type: 'header name'
- })
- }
- // 2. Return true if this’s header list contains name;
- // otherwise false.
- return this.#headersList.contains(name, false)
- }
+/***/ }),
- // https://fetch.spec.whatwg.org/#dom-headers-set
- set (name, value) {
- webidl.brandCheck(this, Headers)
+/***/ 5840:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- webidl.argumentLengthCheck(arguments, 2, 'Headers.set')
- const prefix = 'Headers.set'
- name = webidl.converters.ByteString(name, prefix, 'name')
- value = webidl.converters.ByteString(value, prefix, 'value')
- // 1. Normalize value.
- value = headerValueNormalize(value)
+var identity = __nccwpck_require__(1127);
+var map = __nccwpck_require__(7451);
+var seq = __nccwpck_require__(1706);
+var string = __nccwpck_require__(6464);
+var tags = __nccwpck_require__(18);
- // 2. If name is not a header name or value is not a
- // header value, then throw a TypeError.
- if (!isValidHeaderName(name)) {
- throw webidl.errors.invalidArgument({
- prefix,
- value: name,
- type: 'header name'
- })
- } else if (!isValidHeaderValue(value)) {
- throw webidl.errors.invalidArgument({
- prefix,
- value,
- type: 'header value'
- })
+const sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0;
+class Schema {
+ constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults }) {
+ this.compat = Array.isArray(compat)
+ ? tags.getTags(compat, 'compat')
+ : compat
+ ? tags.getTags(null, compat)
+ : null;
+ this.name = (typeof schema === 'string' && schema) || 'core';
+ this.knownTags = resolveKnownTags ? tags.coreKnownTags : {};
+ this.tags = tags.getTags(customTags, this.name, merge);
+ this.toStringOptions = toStringDefaults ?? null;
+ Object.defineProperty(this, identity.MAP, { value: map.map });
+ Object.defineProperty(this, identity.SCALAR, { value: string.string });
+ Object.defineProperty(this, identity.SEQ, { value: seq.seq });
+ // Used by createMap()
+ this.sortMapEntries =
+ typeof sortMapEntries === 'function'
+ ? sortMapEntries
+ : sortMapEntries === true
+ ? sortMapEntriesByKey
+ : null;
}
-
- // 3. If this’s guard is "immutable", then throw a TypeError.
- // 4. Otherwise, if this’s guard is "request" and name is a
- // forbidden header name, return.
- // 5. Otherwise, if this’s guard is "request-no-cors" and
- // name/value is not a no-CORS-safelisted request-header,
- // return.
- // 6. Otherwise, if this’s guard is "response" and name is a
- // forbidden response-header name, return.
- // Note: undici does not implement forbidden header names
- if (this.#guard === 'immutable') {
- throw new TypeError('immutable')
+ clone() {
+ const copy = Object.create(Schema.prototype, Object.getOwnPropertyDescriptors(this));
+ copy.tags = this.tags.slice();
+ return copy;
}
+}
- // 7. Set (name, value) in this’s header list.
- // 8. If this’s guard is "request-no-cors", then remove
- // privileged no-CORS request headers from this
- this.#headersList.set(name, value, false)
- }
-
- // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie
- getSetCookie () {
- webidl.brandCheck(this, Headers)
+exports.Schema = Schema;
- // 1. If this’s header list does not contain `Set-Cookie`, then return « ».
- // 2. Return the values of all headers in this’s header list whose name is
- // a byte-case-insensitive match for `Set-Cookie`, in order.
- const list = this.#headersList.cookies
+/***/ }),
- if (list) {
- return [...list]
- }
+/***/ 7451:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- return []
- }
- // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine
- get [kHeadersSortedMap] () {
- if (this.#headersList[kHeadersSortedMap]) {
- return this.#headersList[kHeadersSortedMap]
- }
- // 1. Let headers be an empty list of headers with the key being the name
- // and value the value.
- const headers = []
+var identity = __nccwpck_require__(1127);
+var YAMLMap = __nccwpck_require__(4454);
- // 2. Let names be the result of convert header names to a sorted-lowercase
- // set with all the names of the headers in list.
- const names = this.#headersList.toSortedArray()
+const map = {
+ collection: 'map',
+ default: true,
+ nodeClass: YAMLMap.YAMLMap,
+ tag: 'tag:yaml.org,2002:map',
+ resolve(map, onError) {
+ if (!identity.isMap(map))
+ onError('Expected a mapping for this tag');
+ return map;
+ },
+ createNode: (schema, obj, ctx) => YAMLMap.YAMLMap.from(schema, obj, ctx)
+};
- const cookies = this.#headersList.cookies
+exports.map = map;
- // fast-path
- if (cookies === null || cookies.length === 1) {
- // Note: The non-null assertion of value has already been done by `HeadersList#toSortedArray`
- return (this.#headersList[kHeadersSortedMap] = names)
- }
- // 3. For each name of names:
- for (let i = 0; i < names.length; ++i) {
- const { 0: name, 1: value } = names[i]
- // 1. If name is `set-cookie`, then:
- if (name === 'set-cookie') {
- // 1. Let values be a list of all values of headers in list whose name
- // is a byte-case-insensitive match for name, in order.
+/***/ }),
- // 2. For each value of values:
- // 1. Append (name, value) to headers.
- for (let j = 0; j < cookies.length; ++j) {
- headers.push([name, cookies[j]])
- }
- } else {
- // 2. Otherwise:
+/***/ 1251:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 1. Let value be the result of getting name from list.
- // 2. Assert: value is non-null.
- // Note: This operation was done by `HeadersList#toSortedArray`.
- // 3. Append (name, value) to headers.
- headers.push([name, value])
- }
- }
+var Scalar = __nccwpck_require__(3301);
- // 4. Return headers.
- return (this.#headersList[kHeadersSortedMap] = headers)
- }
+const nullTag = {
+ identify: value => value == null,
+ createNode: () => new Scalar.Scalar(null),
+ default: true,
+ tag: 'tag:yaml.org,2002:null',
+ test: /^(?:~|[Nn]ull|NULL)?$/,
+ resolve: () => new Scalar.Scalar(null),
+ stringify: ({ source }, ctx) => typeof source === 'string' && nullTag.test.test(source)
+ ? source
+ : ctx.options.nullStr
+};
- [util.inspect.custom] (depth, options) {
- options.depth ??= depth
+exports.nullTag = nullTag;
- return `Headers ${util.formatWithOptions(options, this.#headersList.entries)}`
- }
- static getHeadersGuard (o) {
- return o.#guard
- }
+/***/ }),
- static setHeadersGuard (o, guard) {
- o.#guard = guard
- }
+/***/ 1706:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- static getHeadersList (o) {
- return o.#headersList
- }
- static setHeadersList (o, list) {
- o.#headersList = list
- }
-}
-const { getHeadersGuard, setHeadersGuard, getHeadersList, setHeadersList } = Headers
-Reflect.deleteProperty(Headers, 'getHeadersGuard')
-Reflect.deleteProperty(Headers, 'setHeadersGuard')
-Reflect.deleteProperty(Headers, 'getHeadersList')
-Reflect.deleteProperty(Headers, 'setHeadersList')
+var identity = __nccwpck_require__(1127);
+var YAMLSeq = __nccwpck_require__(2223);
-iteratorMixin('Headers', Headers, kHeadersSortedMap, 0, 1)
+const seq = {
+ collection: 'seq',
+ default: true,
+ nodeClass: YAMLSeq.YAMLSeq,
+ tag: 'tag:yaml.org,2002:seq',
+ resolve(seq, onError) {
+ if (!identity.isSeq(seq))
+ onError('Expected a sequence for this tag');
+ return seq;
+ },
+ createNode: (schema, obj, ctx) => YAMLSeq.YAMLSeq.from(schema, obj, ctx)
+};
-Object.defineProperties(Headers.prototype, {
- append: kEnumerableProperty,
- delete: kEnumerableProperty,
- get: kEnumerableProperty,
- has: kEnumerableProperty,
- set: kEnumerableProperty,
- getSetCookie: kEnumerableProperty,
- [Symbol.toStringTag]: {
- value: 'Headers',
- configurable: true
- },
- [util.inspect.custom]: {
- enumerable: false
- }
-})
+exports.seq = seq;
-webidl.converters.HeadersInit = function (V, prefix, argument) {
- if (webidl.util.Type(V) === 'Object') {
- const iterator = Reflect.get(V, Symbol.iterator)
- // A work-around to ensure we send the properly-cased Headers when V is a Headers object.
- // Read https://github.com/nodejs/undici/pull/3159#issuecomment-2075537226 before touching, please.
- if (!util.types.isProxy(V) && iterator === Headers.prototype.entries) { // Headers object
- try {
- return getHeadersList(V).entriesList
- } catch {
- // fall-through
- }
- }
+/***/ }),
- if (typeof iterator === 'function') {
- return webidl.converters['sequence>'](V, prefix, argument, iterator.bind(V))
- }
+/***/ 6464:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- return webidl.converters['record'](V, prefix, argument)
- }
- throw webidl.errors.conversionFailed({
- prefix: 'Headers constructor',
- argument: 'Argument 1',
- types: ['sequence>', 'record']
- })
-}
-module.exports = {
- fill,
- // for test.
- compareHeaderName,
- Headers,
- HeadersList,
- getHeadersGuard,
- setHeadersGuard,
- setHeadersList,
- getHeadersList
-}
+var stringifyString = __nccwpck_require__(3069);
+const string = {
+ identify: value => typeof value === 'string',
+ default: true,
+ tag: 'tag:yaml.org,2002:str',
+ resolve: str => str,
+ stringify(item, ctx, onComment, onChompKeep) {
+ ctx = Object.assign({ actualString: true }, ctx);
+ return stringifyString.stringifyString(item, ctx, onComment, onChompKeep);
+ }
+};
-/***/ }),
+exports.string = string;
-/***/ 7302:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-// https://github.com/Ethan-Arrowood/undici-fetch
+/***/ }),
+/***/ 3959:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-const {
- makeNetworkError,
- makeAppropriateNetworkError,
- filterResponse,
- makeResponse,
- fromInnerResponse
-} = __nccwpck_require__(9107)
-const { HeadersList } = __nccwpck_require__(3676)
-const { Request, cloneRequest } = __nccwpck_require__(6055)
-const zlib = __nccwpck_require__(8522)
-const {
- bytesMatch,
- makePolicyContainer,
- clonePolicyContainer,
- requestBadPort,
- TAOCheck,
- appendRequestOriginHeader,
- responseLocationURL,
- requestCurrentURL,
- setRequestReferrerPolicyOnRedirect,
- tryUpgradeRequestToAPotentiallyTrustworthyURL,
- createOpaqueTimingInfo,
- appendFetchMetadata,
- corsCheck,
- crossOriginResourcePolicyCheck,
- determineRequestsReferrer,
- coarsenedSharedCurrentTime,
- createDeferredPromise,
- isBlobLike,
- sameOrigin,
- isCancelled,
- isAborted,
- isErrorLike,
- fullyReadBody,
- readableStreamClose,
- isomorphicEncode,
- urlIsLocal,
- urlIsHttpHttpsScheme,
- urlHasHttpsScheme,
- clampAndCoarsenConnectionTimingInfo,
- simpleRangeHeaderValue,
- buildContentRange,
- createInflate,
- extractMimeType
-} = __nccwpck_require__(4296)
-const { kState, kDispatcher } = __nccwpck_require__(4883)
-const assert = __nccwpck_require__(4589)
-const { safelyExtractBody, extractBody } = __nccwpck_require__(8900)
-const {
- redirectStatusSet,
- nullBodyStatus,
- safeMethodsSet,
- requestBodyHeader,
- subresourceSet
-} = __nccwpck_require__(1207)
-const EE = __nccwpck_require__(8474)
-const { Readable, pipeline, finished } = __nccwpck_require__(7075)
-const { addAbortListener, isErrored, isReadable, bufferToLowerCasedHeaderName } = __nccwpck_require__(1544)
-const { dataURLProcessor, serializeAMimeType, minimizeSupportedMimeType } = __nccwpck_require__(980)
-const { getGlobalDispatcher } = __nccwpck_require__(5837)
-const { webidl } = __nccwpck_require__(253)
-const { STATUS_CODES } = __nccwpck_require__(7067)
-const GET_OR_HEAD = ['GET', 'HEAD']
-const defaultUserAgent = typeof __UNDICI_IS_NODE__ !== 'undefined' || typeof esbuildDetection !== 'undefined'
- ? 'node'
- : 'undici'
+var Scalar = __nccwpck_require__(3301);
-/** @type {import('buffer').resolveObjectURL} */
-let resolveObjectURL
+const boolTag = {
+ identify: value => typeof value === 'boolean',
+ default: true,
+ tag: 'tag:yaml.org,2002:bool',
+ test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,
+ resolve: str => new Scalar.Scalar(str[0] === 't' || str[0] === 'T'),
+ stringify({ source, value }, ctx) {
+ if (source && boolTag.test.test(source)) {
+ const sv = source[0] === 't' || source[0] === 'T';
+ if (value === sv)
+ return source;
+ }
+ return value ? ctx.options.trueStr : ctx.options.falseStr;
+ }
+};
-class Fetch extends EE {
- constructor (dispatcher) {
- super()
+exports.boolTag = boolTag;
- this.dispatcher = dispatcher
- this.connection = null
- this.dump = false
- this.state = 'ongoing'
- }
- terminate (reason) {
- if (this.state !== 'ongoing') {
- return
- }
+/***/ }),
- this.state = 'terminated'
- this.connection?.destroy(reason)
- this.emit('terminated', reason)
- }
+/***/ 8405:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // https://fetch.spec.whatwg.org/#fetch-controller-abort
- abort (error) {
- if (this.state !== 'ongoing') {
- return
- }
- // 1. Set controller’s state to "aborted".
- this.state = 'aborted'
- // 2. Let fallbackError be an "AbortError" DOMException.
- // 3. Set error to fallbackError if it is not given.
- if (!error) {
- error = new DOMException('The operation was aborted.', 'AbortError')
- }
+var Scalar = __nccwpck_require__(3301);
+var stringifyNumber = __nccwpck_require__(8689);
- // 4. Let serializedError be StructuredSerialize(error).
- // If that threw an exception, catch it, and let
- // serializedError be StructuredSerialize(fallbackError).
+const floatNaN = {
+ identify: value => typeof value === 'number',
+ default: true,
+ tag: 'tag:yaml.org,2002:float',
+ test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,
+ resolve: str => str.slice(-3).toLowerCase() === 'nan'
+ ? NaN
+ : str[0] === '-'
+ ? Number.NEGATIVE_INFINITY
+ : Number.POSITIVE_INFINITY,
+ stringify: stringifyNumber.stringifyNumber
+};
+const floatExp = {
+ identify: value => typeof value === 'number',
+ default: true,
+ tag: 'tag:yaml.org,2002:float',
+ format: 'EXP',
+ test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,
+ resolve: str => parseFloat(str),
+ stringify(node) {
+ const num = Number(node.value);
+ return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node);
+ }
+};
+const float = {
+ identify: value => typeof value === 'number',
+ default: true,
+ tag: 'tag:yaml.org,2002:float',
+ test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,
+ resolve(str) {
+ const node = new Scalar.Scalar(parseFloat(str));
+ const dot = str.indexOf('.');
+ if (dot !== -1 && str[str.length - 1] === '0')
+ node.minFractionDigits = str.length - dot - 1;
+ return node;
+ },
+ stringify: stringifyNumber.stringifyNumber
+};
- // 5. Set controller’s serialized abort reason to serializedError.
- this.serializedAbortReason = error
+exports.float = float;
+exports.floatExp = floatExp;
+exports.floatNaN = floatNaN;
- this.connection?.destroy(error)
- this.emit('terminated', error)
- }
-}
-function handleFetchDone (response) {
- finalizeAndReportTiming(response, 'fetch')
-}
+/***/ }),
-// https://fetch.spec.whatwg.org/#fetch-method
-function fetch (input, init = undefined) {
- webidl.argumentLengthCheck(arguments, 1, 'globalThis.fetch')
+/***/ 9874:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 1. Let p be a new promise.
- let p = createDeferredPromise()
- // 2. Let requestObject be the result of invoking the initial value of
- // Request as constructor with input and init as arguments. If this throws
- // an exception, reject p with it and return p.
- let requestObject
- try {
- requestObject = new Request(input, init)
- } catch (e) {
- p.reject(e)
- return p.promise
- }
+var stringifyNumber = __nccwpck_require__(8689);
- // 3. Let request be requestObject’s request.
- const request = requestObject[kState]
+const intIdentify = (value) => typeof value === 'bigint' || Number.isInteger(value);
+const intResolve = (str, offset, radix, { intAsBigInt }) => (intAsBigInt ? BigInt(str) : parseInt(str.substring(offset), radix));
+function intStringify(node, radix, prefix) {
+ const { value } = node;
+ if (intIdentify(value) && value >= 0)
+ return prefix + value.toString(radix);
+ return stringifyNumber.stringifyNumber(node);
+}
+const intOct = {
+ identify: value => intIdentify(value) && value >= 0,
+ default: true,
+ tag: 'tag:yaml.org,2002:int',
+ format: 'OCT',
+ test: /^0o[0-7]+$/,
+ resolve: (str, _onError, opt) => intResolve(str, 2, 8, opt),
+ stringify: node => intStringify(node, 8, '0o')
+};
+const int = {
+ identify: intIdentify,
+ default: true,
+ tag: 'tag:yaml.org,2002:int',
+ test: /^[-+]?[0-9]+$/,
+ resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),
+ stringify: stringifyNumber.stringifyNumber
+};
+const intHex = {
+ identify: value => intIdentify(value) && value >= 0,
+ default: true,
+ tag: 'tag:yaml.org,2002:int',
+ format: 'HEX',
+ test: /^0x[0-9a-fA-F]+$/,
+ resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),
+ stringify: node => intStringify(node, 16, '0x')
+};
- // 4. If requestObject’s signal’s aborted flag is set, then:
- if (requestObject.signal.aborted) {
- // 1. Abort the fetch() call with p, request, null, and
- // requestObject’s signal’s abort reason.
- abortFetch(p, request, null, requestObject.signal.reason)
+exports.int = int;
+exports.intHex = intHex;
+exports.intOct = intOct;
- // 2. Return p.
- return p.promise
- }
- // 5. Let globalObject be request’s client’s global object.
- const globalObject = request.client.globalObject
+/***/ }),
- // 6. If globalObject is a ServiceWorkerGlobalScope object, then set
- // request’s service-workers mode to "none".
- if (globalObject?.constructor?.name === 'ServiceWorkerGlobalScope') {
- request.serviceWorkers = 'none'
- }
+/***/ 896:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 7. Let responseObject be null.
- let responseObject = null
- // 8. Let relevantRealm be this’s relevant Realm.
- // 9. Let locallyAborted be false.
- let locallyAborted = false
+var map = __nccwpck_require__(7451);
+var _null = __nccwpck_require__(1251);
+var seq = __nccwpck_require__(1706);
+var string = __nccwpck_require__(6464);
+var bool = __nccwpck_require__(3959);
+var float = __nccwpck_require__(8405);
+var int = __nccwpck_require__(9874);
- // 10. Let controller be null.
- let controller = null
+const schema = [
+ map.map,
+ seq.seq,
+ string.string,
+ _null.nullTag,
+ bool.boolTag,
+ int.intOct,
+ int.int,
+ int.intHex,
+ float.floatNaN,
+ float.floatExp,
+ float.float
+];
- // 11. Add the following abort steps to requestObject’s signal:
- addAbortListener(
- requestObject.signal,
- () => {
- // 1. Set locallyAborted to true.
- locallyAborted = true
+exports.schema = schema;
- // 2. Assert: controller is non-null.
- assert(controller != null)
- // 3. Abort controller with requestObject’s signal’s abort reason.
- controller.abort(requestObject.signal.reason)
+/***/ }),
- const realResponse = responseObject?.deref()
+/***/ 3559:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 4. Abort the fetch() call with p, request, responseObject,
- // and requestObject’s signal’s abort reason.
- abortFetch(p, request, realResponse, requestObject.signal.reason)
- }
- )
- // 12. Let handleFetchDone given response response be to finalize and
- // report timing with response, globalObject, and "fetch".
- // see function handleFetchDone
- // 13. Set controller to the result of calling fetch given request,
- // with processResponseEndOfBody set to handleFetchDone, and processResponse
- // given response being these substeps:
+var Scalar = __nccwpck_require__(3301);
+var map = __nccwpck_require__(7451);
+var seq = __nccwpck_require__(1706);
- const processResponse = (response) => {
- // 1. If locallyAborted is true, terminate these substeps.
- if (locallyAborted) {
- return
+function intIdentify(value) {
+ return typeof value === 'bigint' || Number.isInteger(value);
+}
+const stringifyJSON = ({ value }) => JSON.stringify(value);
+const jsonScalars = [
+ {
+ identify: value => typeof value === 'string',
+ default: true,
+ tag: 'tag:yaml.org,2002:str',
+ resolve: str => str,
+ stringify: stringifyJSON
+ },
+ {
+ identify: value => value == null,
+ createNode: () => new Scalar.Scalar(null),
+ default: true,
+ tag: 'tag:yaml.org,2002:null',
+ test: /^null$/,
+ resolve: () => null,
+ stringify: stringifyJSON
+ },
+ {
+ identify: value => typeof value === 'boolean',
+ default: true,
+ tag: 'tag:yaml.org,2002:bool',
+ test: /^true$|^false$/,
+ resolve: str => str === 'true',
+ stringify: stringifyJSON
+ },
+ {
+ identify: intIdentify,
+ default: true,
+ tag: 'tag:yaml.org,2002:int',
+ test: /^-?(?:0|[1-9][0-9]*)$/,
+ resolve: (str, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str, 10),
+ stringify: ({ value }) => intIdentify(value) ? value.toString() : JSON.stringify(value)
+ },
+ {
+ identify: value => typeof value === 'number',
+ default: true,
+ tag: 'tag:yaml.org,2002:float',
+ test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,
+ resolve: str => parseFloat(str),
+ stringify: stringifyJSON
+ }
+];
+const jsonError = {
+ default: true,
+ tag: '',
+ test: /^/,
+ resolve(str, onError) {
+ onError(`Unresolved plain scalar ${JSON.stringify(str)}`);
+ return str;
}
+};
+const schema = [map.map, seq.seq].concat(jsonScalars, jsonError);
- // 2. If response’s aborted flag is set, then:
- if (response.aborted) {
- // 1. Let deserializedError be the result of deserialize a serialized
- // abort reason given controller’s serialized abort reason and
- // relevantRealm.
+exports.schema = schema;
- // 2. Abort the fetch() call with p, request, responseObject, and
- // deserializedError.
- abortFetch(p, request, responseObject, controller.serializedAbortReason)
- return
- }
+/***/ }),
- // 3. If response is a network error, then reject p with a TypeError
- // and terminate these substeps.
- if (response.type === 'error') {
- p.reject(new TypeError('fetch failed', { cause: response.error }))
- return
- }
+/***/ 18:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 4. Set responseObject to the result of creating a Response object,
- // given response, "immutable", and relevantRealm.
- responseObject = new WeakRef(fromInnerResponse(response, 'immutable'))
- // 5. Resolve p with responseObject.
- p.resolve(responseObject.deref())
- p = null
- }
- controller = fetching({
- request,
- processResponseEndOfBody: handleFetchDone,
- processResponse,
- dispatcher: requestObject[kDispatcher] // undici
- })
+var map = __nccwpck_require__(7451);
+var _null = __nccwpck_require__(1251);
+var seq = __nccwpck_require__(1706);
+var string = __nccwpck_require__(6464);
+var bool = __nccwpck_require__(3959);
+var float = __nccwpck_require__(8405);
+var int = __nccwpck_require__(9874);
+var schema = __nccwpck_require__(896);
+var schema$1 = __nccwpck_require__(3559);
+var binary = __nccwpck_require__(6083);
+var merge = __nccwpck_require__(452);
+var omap = __nccwpck_require__(303);
+var pairs = __nccwpck_require__(8385);
+var schema$2 = __nccwpck_require__(5913);
+var set = __nccwpck_require__(1528);
+var timestamp = __nccwpck_require__(4371);
- // 14. Return p.
- return p.promise
+const schemas = new Map([
+ ['core', schema.schema],
+ ['failsafe', [map.map, seq.seq, string.string]],
+ ['json', schema$1.schema],
+ ['yaml11', schema$2.schema],
+ ['yaml-1.1', schema$2.schema]
+]);
+const tagsByName = {
+ binary: binary.binary,
+ bool: bool.boolTag,
+ float: float.float,
+ floatExp: float.floatExp,
+ floatNaN: float.floatNaN,
+ floatTime: timestamp.floatTime,
+ int: int.int,
+ intHex: int.intHex,
+ intOct: int.intOct,
+ intTime: timestamp.intTime,
+ map: map.map,
+ merge: merge.merge,
+ null: _null.nullTag,
+ omap: omap.omap,
+ pairs: pairs.pairs,
+ seq: seq.seq,
+ set: set.set,
+ timestamp: timestamp.timestamp
+};
+const coreKnownTags = {
+ 'tag:yaml.org,2002:binary': binary.binary,
+ 'tag:yaml.org,2002:merge': merge.merge,
+ 'tag:yaml.org,2002:omap': omap.omap,
+ 'tag:yaml.org,2002:pairs': pairs.pairs,
+ 'tag:yaml.org,2002:set': set.set,
+ 'tag:yaml.org,2002:timestamp': timestamp.timestamp
+};
+function getTags(customTags, schemaName, addMergeTag) {
+ const schemaTags = schemas.get(schemaName);
+ if (schemaTags && !customTags) {
+ return addMergeTag && !schemaTags.includes(merge.merge)
+ ? schemaTags.concat(merge.merge)
+ : schemaTags.slice();
+ }
+ let tags = schemaTags;
+ if (!tags) {
+ if (Array.isArray(customTags))
+ tags = [];
+ else {
+ const keys = Array.from(schemas.keys())
+ .filter(key => key !== 'yaml11')
+ .map(key => JSON.stringify(key))
+ .join(', ');
+ throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`);
+ }
+ }
+ if (Array.isArray(customTags)) {
+ for (const tag of customTags)
+ tags = tags.concat(tag);
+ }
+ else if (typeof customTags === 'function') {
+ tags = customTags(tags.slice());
+ }
+ if (addMergeTag)
+ tags = tags.concat(merge.merge);
+ return tags.reduce((tags, tag) => {
+ const tagObj = typeof tag === 'string' ? tagsByName[tag] : tag;
+ if (!tagObj) {
+ const tagName = JSON.stringify(tag);
+ const keys = Object.keys(tagsByName)
+ .map(key => JSON.stringify(key))
+ .join(', ');
+ throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`);
+ }
+ if (!tags.includes(tagObj))
+ tags.push(tagObj);
+ return tags;
+ }, []);
}
-// https://fetch.spec.whatwg.org/#finalize-and-report-timing
-function finalizeAndReportTiming (response, initiatorType = 'other') {
- // 1. If response is an aborted network error, then return.
- if (response.type === 'error' && response.aborted) {
- return
- }
+exports.coreKnownTags = coreKnownTags;
+exports.getTags = getTags;
- // 2. If response’s URL list is null or empty, then return.
- if (!response.urlList?.length) {
- return
- }
- // 3. Let originalURL be response’s URL list[0].
- const originalURL = response.urlList[0]
+/***/ }),
- // 4. Let timingInfo be response’s timing info.
- let timingInfo = response.timingInfo
+/***/ 6083:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 5. Let cacheState be response’s cache state.
- let cacheState = response.cacheState
- // 6. If originalURL’s scheme is not an HTTP(S) scheme, then return.
- if (!urlIsHttpHttpsScheme(originalURL)) {
- return
- }
- // 7. If timingInfo is null, then return.
- if (timingInfo === null) {
- return
- }
+var node_buffer = __nccwpck_require__(181);
+var Scalar = __nccwpck_require__(3301);
+var stringifyString = __nccwpck_require__(3069);
- // 8. If response’s timing allow passed flag is not set, then:
- if (!response.timingAllowPassed) {
- // 1. Set timingInfo to a the result of creating an opaque timing info for timingInfo.
- timingInfo = createOpaqueTimingInfo({
- startTime: timingInfo.startTime
- })
+const binary = {
+ identify: value => value instanceof Uint8Array, // Buffer inherits from Uint8Array
+ default: false,
+ tag: 'tag:yaml.org,2002:binary',
+ /**
+ * Returns a Buffer in node and an Uint8Array in browsers
+ *
+ * To use the resulting buffer as an image, you'll want to do something like:
+ *
+ * const blob = new Blob([buffer], { type: 'image/jpeg' })
+ * document.querySelector('#photo').src = URL.createObjectURL(blob)
+ */
+ resolve(src, onError) {
+ if (typeof node_buffer.Buffer === 'function') {
+ return node_buffer.Buffer.from(src, 'base64');
+ }
+ else if (typeof atob === 'function') {
+ // On IE 11, atob() can't handle newlines
+ const str = atob(src.replace(/[\n\r]/g, ''));
+ const buffer = new Uint8Array(str.length);
+ for (let i = 0; i < str.length; ++i)
+ buffer[i] = str.charCodeAt(i);
+ return buffer;
+ }
+ else {
+ onError('This environment does not support reading binary tags; either Buffer or atob is required');
+ return src;
+ }
+ },
+ stringify({ comment, type, value }, ctx, onComment, onChompKeep) {
+ if (!value)
+ return '';
+ const buf = value; // checked earlier by binary.identify()
+ let str;
+ if (typeof node_buffer.Buffer === 'function') {
+ str =
+ buf instanceof node_buffer.Buffer
+ ? buf.toString('base64')
+ : node_buffer.Buffer.from(buf.buffer).toString('base64');
+ }
+ else if (typeof btoa === 'function') {
+ let s = '';
+ for (let i = 0; i < buf.length; ++i)
+ s += String.fromCharCode(buf[i]);
+ str = btoa(s);
+ }
+ else {
+ throw new Error('This environment does not support writing binary tags; either Buffer or btoa is required');
+ }
+ type ?? (type = Scalar.Scalar.BLOCK_LITERAL);
+ if (type !== Scalar.Scalar.QUOTE_DOUBLE) {
+ const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth);
+ const n = Math.ceil(str.length / lineWidth);
+ const lines = new Array(n);
+ for (let i = 0, o = 0; i < n; ++i, o += lineWidth) {
+ lines[i] = str.substr(o, lineWidth);
+ }
+ str = lines.join(type === Scalar.Scalar.BLOCK_LITERAL ? '\n' : ' ');
+ }
+ return stringifyString.stringifyString({ comment, type, value: str }, ctx, onComment, onChompKeep);
+ }
+};
- // 2. Set cacheState to the empty string.
- cacheState = ''
- }
+exports.binary = binary;
- // 9. Set timingInfo’s end time to the coarsened shared current time
- // given global’s relevant settings object’s cross-origin isolated
- // capability.
- // TODO: given global’s relevant settings object’s cross-origin isolated
- // capability?
- timingInfo.endTime = coarsenedSharedCurrentTime()
- // 10. Set response’s timing info to timingInfo.
- response.timingInfo = timingInfo
+/***/ }),
- // 11. Mark resource timing for timingInfo, originalURL, initiatorType,
- // global, and cacheState.
- markResourceTiming(
- timingInfo,
- originalURL.href,
- initiatorType,
- globalThis,
- cacheState
- )
-}
+/***/ 8398:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-// https://w3c.github.io/resource-timing/#dfn-mark-resource-timing
-const markResourceTiming = performance.markResourceTiming
-// https://fetch.spec.whatwg.org/#abort-fetch
-function abortFetch (p, request, responseObject, error) {
- // 1. Reject promise with error.
- if (p) {
- // We might have already resolved the promise at this stage
- p.reject(error)
- }
- // 2. If request’s body is not null and is readable, then cancel request’s
- // body with error.
- if (request.body != null && isReadable(request.body?.stream)) {
- request.body.stream.cancel(error).catch((err) => {
- if (err.code === 'ERR_INVALID_STATE') {
- // Node bug?
- return
- }
- throw err
- })
- }
+var Scalar = __nccwpck_require__(3301);
- // 3. If responseObject is null, then return.
- if (responseObject == null) {
- return
- }
+function boolStringify({ value, source }, ctx) {
+ const boolObj = value ? trueTag : falseTag;
+ if (source && boolObj.test.test(source))
+ return source;
+ return value ? ctx.options.trueStr : ctx.options.falseStr;
+}
+const trueTag = {
+ identify: value => value === true,
+ default: true,
+ tag: 'tag:yaml.org,2002:bool',
+ test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,
+ resolve: () => new Scalar.Scalar(true),
+ stringify: boolStringify
+};
+const falseTag = {
+ identify: value => value === false,
+ default: true,
+ tag: 'tag:yaml.org,2002:bool',
+ test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,
+ resolve: () => new Scalar.Scalar(false),
+ stringify: boolStringify
+};
- // 4. Let response be responseObject’s response.
- const response = responseObject[kState]
+exports.falseTag = falseTag;
+exports.trueTag = trueTag;
- // 5. If response’s body is not null and is readable, then error response’s
- // body with error.
- if (response.body != null && isReadable(response.body?.stream)) {
- response.body.stream.cancel(error).catch((err) => {
- if (err.code === 'ERR_INVALID_STATE') {
- // Node bug?
- return
- }
- throw err
- })
- }
-}
-// https://fetch.spec.whatwg.org/#fetching
-function fetching ({
- request,
- processRequestBodyChunkLength,
- processRequestEndOfBody,
- processResponse,
- processResponseEndOfBody,
- processResponseConsumeBody,
- useParallelQueue = false,
- dispatcher = getGlobalDispatcher() // undici
-}) {
- // Ensure that the dispatcher is set accordingly
- assert(dispatcher)
+/***/ }),
- // 1. Let taskDestination be null.
- let taskDestination = null
+/***/ 5782:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 2. Let crossOriginIsolatedCapability be false.
- let crossOriginIsolatedCapability = false
- // 3. If request’s client is non-null, then:
- if (request.client != null) {
- // 1. Set taskDestination to request’s client’s global object.
- taskDestination = request.client.globalObject
- // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin
- // isolated capability.
- crossOriginIsolatedCapability =
- request.client.crossOriginIsolatedCapability
- }
+var Scalar = __nccwpck_require__(3301);
+var stringifyNumber = __nccwpck_require__(8689);
- // 4. If useParallelQueue is true, then set taskDestination to the result of
- // starting a new parallel queue.
- // TODO
+const floatNaN = {
+ identify: value => typeof value === 'number',
+ default: true,
+ tag: 'tag:yaml.org,2002:float',
+ test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,
+ resolve: (str) => str.slice(-3).toLowerCase() === 'nan'
+ ? NaN
+ : str[0] === '-'
+ ? Number.NEGATIVE_INFINITY
+ : Number.POSITIVE_INFINITY,
+ stringify: stringifyNumber.stringifyNumber
+};
+const floatExp = {
+ identify: value => typeof value === 'number',
+ default: true,
+ tag: 'tag:yaml.org,2002:float',
+ format: 'EXP',
+ test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,
+ resolve: (str) => parseFloat(str.replace(/_/g, '')),
+ stringify(node) {
+ const num = Number(node.value);
+ return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node);
+ }
+};
+const float = {
+ identify: value => typeof value === 'number',
+ default: true,
+ tag: 'tag:yaml.org,2002:float',
+ test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,
+ resolve(str) {
+ const node = new Scalar.Scalar(parseFloat(str.replace(/_/g, '')));
+ const dot = str.indexOf('.');
+ if (dot !== -1) {
+ const f = str.substring(dot + 1).replace(/_/g, '');
+ if (f[f.length - 1] === '0')
+ node.minFractionDigits = f.length;
+ }
+ return node;
+ },
+ stringify: stringifyNumber.stringifyNumber
+};
- // 5. Let timingInfo be a new fetch timing info whose start time and
- // post-redirect start time are the coarsened shared current time given
- // crossOriginIsolatedCapability.
- const currentTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability)
- const timingInfo = createOpaqueTimingInfo({
- startTime: currentTime
- })
+exports.float = float;
+exports.floatExp = floatExp;
+exports.floatNaN = floatNaN;
- // 6. Let fetchParams be a new fetch params whose
- // request is request,
- // timing info is timingInfo,
- // process request body chunk length is processRequestBodyChunkLength,
- // process request end-of-body is processRequestEndOfBody,
- // process response is processResponse,
- // process response consume body is processResponseConsumeBody,
- // process response end-of-body is processResponseEndOfBody,
- // task destination is taskDestination,
- // and cross-origin isolated capability is crossOriginIsolatedCapability.
- const fetchParams = {
- controller: new Fetch(dispatcher),
- request,
- timingInfo,
- processRequestBodyChunkLength,
- processRequestEndOfBody,
- processResponse,
- processResponseConsumeBody,
- processResponseEndOfBody,
- taskDestination,
- crossOriginIsolatedCapability
- }
- // 7. If request’s body is a byte sequence, then set request’s body to
- // request’s body as a body.
- // NOTE: Since fetching is only called from fetch, body should already be
- // extracted.
- assert(!request.body || request.body.stream)
+/***/ }),
- // 8. If request’s window is "client", then set request’s window to request’s
- // client, if request’s client’s global object is a Window object; otherwise
- // "no-window".
- if (request.window === 'client') {
- // TODO: What if request.client is null?
- request.window =
- request.client?.globalObject?.constructor?.name === 'Window'
- ? request.client
- : 'no-window'
- }
+/***/ 873:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 9. If request’s origin is "client", then set request’s origin to request’s
- // client’s origin.
- if (request.origin === 'client') {
- request.origin = request.client.origin
- }
- // 10. If all of the following conditions are true:
- // TODO
- // 11. If request’s policy container is "client", then:
- if (request.policyContainer === 'client') {
- // 1. If request’s client is non-null, then set request’s policy
- // container to a clone of request’s client’s policy container. [HTML]
- if (request.client != null) {
- request.policyContainer = clonePolicyContainer(
- request.client.policyContainer
- )
- } else {
- // 2. Otherwise, set request’s policy container to a new policy
- // container.
- request.policyContainer = makePolicyContainer()
+var stringifyNumber = __nccwpck_require__(8689);
+
+const intIdentify = (value) => typeof value === 'bigint' || Number.isInteger(value);
+function intResolve(str, offset, radix, { intAsBigInt }) {
+ const sign = str[0];
+ if (sign === '-' || sign === '+')
+ offset += 1;
+ str = str.substring(offset).replace(/_/g, '');
+ if (intAsBigInt) {
+ switch (radix) {
+ case 2:
+ str = `0b${str}`;
+ break;
+ case 8:
+ str = `0o${str}`;
+ break;
+ case 16:
+ str = `0x${str}`;
+ break;
+ }
+ const n = BigInt(str);
+ return sign === '-' ? BigInt(-1) * n : n;
}
- }
+ const n = parseInt(str, radix);
+ return sign === '-' ? -1 * n : n;
+}
+function intStringify(node, radix, prefix) {
+ const { value } = node;
+ if (intIdentify(value)) {
+ const str = value.toString(radix);
+ return value < 0 ? '-' + prefix + str.substr(1) : prefix + str;
+ }
+ return stringifyNumber.stringifyNumber(node);
+}
+const intBin = {
+ identify: intIdentify,
+ default: true,
+ tag: 'tag:yaml.org,2002:int',
+ format: 'BIN',
+ test: /^[-+]?0b[0-1_]+$/,
+ resolve: (str, _onError, opt) => intResolve(str, 2, 2, opt),
+ stringify: node => intStringify(node, 2, '0b')
+};
+const intOct = {
+ identify: intIdentify,
+ default: true,
+ tag: 'tag:yaml.org,2002:int',
+ format: 'OCT',
+ test: /^[-+]?0[0-7_]+$/,
+ resolve: (str, _onError, opt) => intResolve(str, 1, 8, opt),
+ stringify: node => intStringify(node, 8, '0')
+};
+const int = {
+ identify: intIdentify,
+ default: true,
+ tag: 'tag:yaml.org,2002:int',
+ test: /^[-+]?[0-9][0-9_]*$/,
+ resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),
+ stringify: stringifyNumber.stringifyNumber
+};
+const intHex = {
+ identify: intIdentify,
+ default: true,
+ tag: 'tag:yaml.org,2002:int',
+ format: 'HEX',
+ test: /^[-+]?0x[0-9a-fA-F_]+$/,
+ resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),
+ stringify: node => intStringify(node, 16, '0x')
+};
- // 12. If request’s header list does not contain `Accept`, then:
- if (!request.headersList.contains('accept', true)) {
- // 1. Let value be `*/*`.
- const value = '*/*'
+exports.int = int;
+exports.intBin = intBin;
+exports.intHex = intHex;
+exports.intOct = intOct;
- // 2. A user agent should set value to the first matching statement, if
- // any, switching on request’s destination:
- // "document"
- // "frame"
- // "iframe"
- // `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8`
- // "image"
- // `image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5`
- // "style"
- // `text/css,*/*;q=0.1`
- // TODO
- // 3. Append `Accept`/value to request’s header list.
- request.headersList.append('accept', value, true)
- }
+/***/ }),
- // 13. If request’s header list does not contain `Accept-Language`, then
- // user agents should append `Accept-Language`/an appropriate value to
- // request’s header list.
- if (!request.headersList.contains('accept-language', true)) {
- request.headersList.append('accept-language', '*', true)
- }
+/***/ 452:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 14. If request’s priority is null, then use request’s initiator and
- // destination appropriately in setting request’s priority to a
- // user-agent-defined object.
- if (request.priority === null) {
- // TODO
- }
- // 15. If request is a subresource request, then:
- if (subresourceSet.has(request.destination)) {
- // TODO
- }
- // 16. Run main fetch given fetchParams.
- mainFetch(fetchParams)
- .catch(err => {
- fetchParams.controller.terminate(err)
- })
+var identity = __nccwpck_require__(1127);
+var Scalar = __nccwpck_require__(3301);
- // 17. Return fetchParam's controller
- return fetchParams.controller
+// If the value associated with a merge key is a single mapping node, each of
+// its key/value pairs is inserted into the current mapping, unless the key
+// already exists in it. If the value associated with the merge key is a
+// sequence, then this sequence is expected to contain mapping nodes and each
+// of these nodes is merged in turn according to its order in the sequence.
+// Keys in mapping nodes earlier in the sequence override keys specified in
+// later mapping nodes. -- http://yaml.org/type/merge.html
+const MERGE_KEY = '<<';
+const merge = {
+ identify: value => value === MERGE_KEY ||
+ (typeof value === 'symbol' && value.description === MERGE_KEY),
+ default: 'key',
+ tag: 'tag:yaml.org,2002:merge',
+ test: /^<<$/,
+ resolve: () => Object.assign(new Scalar.Scalar(Symbol(MERGE_KEY)), {
+ addToJSMap: addMergeToJSMap
+ }),
+ stringify: () => MERGE_KEY
+};
+const isMergeKey = (ctx, key) => (merge.identify(key) ||
+ (identity.isScalar(key) &&
+ (!key.type || key.type === Scalar.Scalar.PLAIN) &&
+ merge.identify(key.value))) &&
+ ctx?.doc.schema.tags.some(tag => tag.tag === merge.tag && tag.default);
+function addMergeToJSMap(ctx, map, value) {
+ const source = resolveAliasValue(ctx, value);
+ if (identity.isSeq(source))
+ for (const it of source.items)
+ mergeValue(ctx, map, it);
+ else if (Array.isArray(source))
+ for (const it of source)
+ mergeValue(ctx, map, it);
+ else
+ mergeValue(ctx, map, source);
+}
+function mergeValue(ctx, map, value) {
+ const source = resolveAliasValue(ctx, value);
+ if (!identity.isMap(source))
+ throw new Error('Merge sources must be maps or map aliases');
+ const srcMap = source.toJSON(null, ctx, Map);
+ for (const [key, value] of srcMap) {
+ if (map instanceof Map) {
+ if (!map.has(key))
+ map.set(key, value);
+ }
+ else if (map instanceof Set) {
+ map.add(key);
+ }
+ else if (!Object.prototype.hasOwnProperty.call(map, key)) {
+ Object.defineProperty(map, key, {
+ value,
+ writable: true,
+ enumerable: true,
+ configurable: true
+ });
+ }
+ }
+ return map;
+}
+function resolveAliasValue(ctx, value) {
+ return ctx && identity.isAlias(value) ? value.resolve(ctx.doc, ctx) : value;
}
-// https://fetch.spec.whatwg.org/#concept-main-fetch
-async function mainFetch (fetchParams, recursive = false) {
- // 1. Let request be fetchParams’s request.
- const request = fetchParams.request
+exports.addMergeToJSMap = addMergeToJSMap;
+exports.isMergeKey = isMergeKey;
+exports.merge = merge;
- // 2. Let response be null.
- let response = null
- // 3. If request’s local-URLs-only flag is set and request’s current URL is
- // not local, then set response to a network error.
- if (request.localURLsOnly && !urlIsLocal(requestCurrentURL(request))) {
- response = makeNetworkError('local URLs only')
- }
+/***/ }),
- // 4. Run report Content Security Policy violations for request.
- // TODO
+/***/ 303:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 5. Upgrade request to a potentially trustworthy URL, if appropriate.
- tryUpgradeRequestToAPotentiallyTrustworthyURL(request)
- // 6. If should request be blocked due to a bad port, should fetching request
- // be blocked as mixed content, or should request be blocked by Content
- // Security Policy returns blocked, then set response to a network error.
- if (requestBadPort(request) === 'blocked') {
- response = makeNetworkError('bad port')
- }
- // TODO: should fetching request be blocked as mixed content?
- // TODO: should request be blocked by Content Security Policy?
- // 7. If request’s referrer policy is the empty string, then set request’s
- // referrer policy to request’s policy container’s referrer policy.
- if (request.referrerPolicy === '') {
- request.referrerPolicy = request.policyContainer.referrerPolicy
- }
+var identity = __nccwpck_require__(1127);
+var toJS = __nccwpck_require__(6424);
+var YAMLMap = __nccwpck_require__(4454);
+var YAMLSeq = __nccwpck_require__(2223);
+var pairs = __nccwpck_require__(8385);
- // 8. If request’s referrer is not "no-referrer", then set request’s
- // referrer to the result of invoking determine request’s referrer.
- if (request.referrer !== 'no-referrer') {
- request.referrer = determineRequestsReferrer(request)
- }
+class YAMLOMap extends YAMLSeq.YAMLSeq {
+ constructor() {
+ super();
+ this.add = YAMLMap.YAMLMap.prototype.add.bind(this);
+ this.delete = YAMLMap.YAMLMap.prototype.delete.bind(this);
+ this.get = YAMLMap.YAMLMap.prototype.get.bind(this);
+ this.has = YAMLMap.YAMLMap.prototype.has.bind(this);
+ this.set = YAMLMap.YAMLMap.prototype.set.bind(this);
+ this.tag = YAMLOMap.tag;
+ }
+ /**
+ * If `ctx` is given, the return type is actually `Map`,
+ * but TypeScript won't allow widening the signature of a child method.
+ */
+ toJSON(_, ctx) {
+ if (!ctx)
+ return super.toJSON(_);
+ const map = new Map();
+ if (ctx?.onCreate)
+ ctx.onCreate(map);
+ for (const pair of this.items) {
+ let key, value;
+ if (identity.isPair(pair)) {
+ key = toJS.toJS(pair.key, '', ctx);
+ value = toJS.toJS(pair.value, key, ctx);
+ }
+ else {
+ key = toJS.toJS(pair, '', ctx);
+ }
+ if (map.has(key))
+ throw new Error('Ordered maps must not include duplicate keys');
+ map.set(key, value);
+ }
+ return map;
+ }
+ static from(schema, iterable, ctx) {
+ const pairs$1 = pairs.createPairs(schema, iterable, ctx);
+ const omap = new this();
+ omap.items = pairs$1.items;
+ return omap;
+ }
+}
+YAMLOMap.tag = 'tag:yaml.org,2002:omap';
+const omap = {
+ collection: 'seq',
+ identify: value => value instanceof Map,
+ nodeClass: YAMLOMap,
+ default: false,
+ tag: 'tag:yaml.org,2002:omap',
+ resolve(seq, onError) {
+ const pairs$1 = pairs.resolvePairs(seq, onError);
+ const seenKeys = [];
+ for (const { key } of pairs$1.items) {
+ if (identity.isScalar(key)) {
+ if (seenKeys.includes(key.value)) {
+ onError(`Ordered maps must not include duplicate keys: ${key.value}`);
+ }
+ else {
+ seenKeys.push(key.value);
+ }
+ }
+ }
+ return Object.assign(new YAMLOMap(), pairs$1);
+ },
+ createNode: (schema, iterable, ctx) => YAMLOMap.from(schema, iterable, ctx)
+};
- // 9. Set request’s current URL’s scheme to "https" if all of the following
- // conditions are true:
- // - request’s current URL’s scheme is "http"
- // - request’s current URL’s host is a domain
- // - Matching request’s current URL’s host per Known HSTS Host Domain Name
- // Matching results in either a superdomain match with an asserted
- // includeSubDomains directive or a congruent match (with or without an
- // asserted includeSubDomains directive). [HSTS]
- // TODO
+exports.YAMLOMap = YAMLOMap;
+exports.omap = omap;
- // 10. If recursive is false, then run the remaining steps in parallel.
- // TODO
- // 11. If response is null, then set response to the result of running
- // the steps corresponding to the first matching statement:
- if (response === null) {
- response = await (async () => {
- const currentURL = requestCurrentURL(request)
+/***/ }),
- if (
- // - request’s current URL’s origin is same origin with request’s origin,
- // and request’s response tainting is "basic"
- (sameOrigin(currentURL, request.url) && request.responseTainting === 'basic') ||
- // request’s current URL’s scheme is "data"
- (currentURL.protocol === 'data:') ||
- // - request’s mode is "navigate" or "websocket"
- (request.mode === 'navigate' || request.mode === 'websocket')
- ) {
- // 1. Set request’s response tainting to "basic".
- request.responseTainting = 'basic'
+/***/ 8385:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 2. Return the result of running scheme fetch given fetchParams.
- return await schemeFetch(fetchParams)
- }
- // request’s mode is "same-origin"
- if (request.mode === 'same-origin') {
- // 1. Return a network error.
- return makeNetworkError('request mode cannot be "same-origin"')
- }
- // request’s mode is "no-cors"
- if (request.mode === 'no-cors') {
- // 1. If request’s redirect mode is not "follow", then return a network
- // error.
- if (request.redirect !== 'follow') {
- return makeNetworkError(
- 'redirect mode cannot be "follow" for "no-cors" request'
- )
- }
+var identity = __nccwpck_require__(1127);
+var Pair = __nccwpck_require__(7165);
+var Scalar = __nccwpck_require__(3301);
+var YAMLSeq = __nccwpck_require__(2223);
- // 2. Set request’s response tainting to "opaque".
- request.responseTainting = 'opaque'
+function resolvePairs(seq, onError) {
+ if (identity.isSeq(seq)) {
+ for (let i = 0; i < seq.items.length; ++i) {
+ let item = seq.items[i];
+ if (identity.isPair(item))
+ continue;
+ else if (identity.isMap(item)) {
+ if (item.items.length > 1)
+ onError('Each pair must have its own sequence indicator');
+ const pair = item.items[0] || new Pair.Pair(new Scalar.Scalar(null));
+ if (item.commentBefore)
+ pair.key.commentBefore = pair.key.commentBefore
+ ? `${item.commentBefore}\n${pair.key.commentBefore}`
+ : item.commentBefore;
+ if (item.comment) {
+ const cn = pair.value ?? pair.key;
+ cn.comment = cn.comment
+ ? `${item.comment}\n${cn.comment}`
+ : item.comment;
+ }
+ item = pair;
+ }
+ seq.items[i] = identity.isPair(item) ? item : new Pair.Pair(item);
+ }
+ }
+ else
+ onError('Expected a sequence for this tag');
+ return seq;
+}
+function createPairs(schema, iterable, ctx) {
+ const { replacer } = ctx;
+ const pairs = new YAMLSeq.YAMLSeq(schema);
+ pairs.tag = 'tag:yaml.org,2002:pairs';
+ let i = 0;
+ if (iterable && Symbol.iterator in Object(iterable))
+ for (let it of iterable) {
+ if (typeof replacer === 'function')
+ it = replacer.call(iterable, String(i++), it);
+ let key, value;
+ if (Array.isArray(it)) {
+ if (it.length === 2) {
+ key = it[0];
+ value = it[1];
+ }
+ else
+ throw new TypeError(`Expected [key, value] tuple: ${it}`);
+ }
+ else if (it && it instanceof Object) {
+ const keys = Object.keys(it);
+ if (keys.length === 1) {
+ key = keys[0];
+ value = it[key];
+ }
+ else {
+ throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`);
+ }
+ }
+ else {
+ key = it;
+ }
+ pairs.items.push(Pair.createPair(key, value, ctx));
+ }
+ return pairs;
+}
+const pairs = {
+ collection: 'seq',
+ default: false,
+ tag: 'tag:yaml.org,2002:pairs',
+ resolve: resolvePairs,
+ createNode: createPairs
+};
- // 3. Return the result of running scheme fetch given fetchParams.
- return await schemeFetch(fetchParams)
- }
+exports.createPairs = createPairs;
+exports.pairs = pairs;
+exports.resolvePairs = resolvePairs;
- // request’s current URL’s scheme is not an HTTP(S) scheme
- if (!urlIsHttpHttpsScheme(requestCurrentURL(request))) {
- // Return a network error.
- return makeNetworkError('URL scheme must be a HTTP(S) scheme')
- }
- // - request’s use-CORS-preflight flag is set
- // - request’s unsafe-request flag is set and either request’s method is
- // not a CORS-safelisted method or CORS-unsafe request-header names with
- // request’s header list is not empty
- // 1. Set request’s response tainting to "cors".
- // 2. Let corsWithPreflightResponse be the result of running HTTP fetch
- // given fetchParams and true.
- // 3. If corsWithPreflightResponse is a network error, then clear cache
- // entries using request.
- // 4. Return corsWithPreflightResponse.
- // TODO
+/***/ }),
- // Otherwise
- // 1. Set request’s response tainting to "cors".
- request.responseTainting = 'cors'
+/***/ 5913:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 2. Return the result of running HTTP fetch given fetchParams.
- return await httpFetch(fetchParams)
- })()
- }
- // 12. If recursive is true, then return response.
- if (recursive) {
- return response
- }
- // 13. If response is not a network error and response is not a filtered
- // response, then:
- if (response.status !== 0 && !response.internalResponse) {
- // If request’s response tainting is "cors", then:
- if (request.responseTainting === 'cors') {
- // 1. Let headerNames be the result of extracting header list values
- // given `Access-Control-Expose-Headers` and response’s header list.
- // TODO
- // 2. If request’s credentials mode is not "include" and headerNames
- // contains `*`, then set response’s CORS-exposed header-name list to
- // all unique header names in response’s header list.
- // TODO
- // 3. Otherwise, if headerNames is not null or failure, then set
- // response’s CORS-exposed header-name list to headerNames.
- // TODO
- }
+var map = __nccwpck_require__(7451);
+var _null = __nccwpck_require__(1251);
+var seq = __nccwpck_require__(1706);
+var string = __nccwpck_require__(6464);
+var binary = __nccwpck_require__(6083);
+var bool = __nccwpck_require__(8398);
+var float = __nccwpck_require__(5782);
+var int = __nccwpck_require__(873);
+var merge = __nccwpck_require__(452);
+var omap = __nccwpck_require__(303);
+var pairs = __nccwpck_require__(8385);
+var set = __nccwpck_require__(1528);
+var timestamp = __nccwpck_require__(4371);
- // Set response to the following filtered response with response as its
- // internal response, depending on request’s response tainting:
- if (request.responseTainting === 'basic') {
- response = filterResponse(response, 'basic')
- } else if (request.responseTainting === 'cors') {
- response = filterResponse(response, 'cors')
- } else if (request.responseTainting === 'opaque') {
- response = filterResponse(response, 'opaque')
- } else {
- assert(false)
- }
- }
+const schema = [
+ map.map,
+ seq.seq,
+ string.string,
+ _null.nullTag,
+ bool.trueTag,
+ bool.falseTag,
+ int.intBin,
+ int.intOct,
+ int.int,
+ int.intHex,
+ float.floatNaN,
+ float.floatExp,
+ float.float,
+ binary.binary,
+ merge.merge,
+ omap.omap,
+ pairs.pairs,
+ set.set,
+ timestamp.intTime,
+ timestamp.floatTime,
+ timestamp.timestamp
+];
- // 14. Let internalResponse be response, if response is a network error,
- // and response’s internal response otherwise.
- let internalResponse =
- response.status === 0 ? response : response.internalResponse
+exports.schema = schema;
- // 15. If internalResponse’s URL list is empty, then set it to a clone of
- // request’s URL list.
- if (internalResponse.urlList.length === 0) {
- internalResponse.urlList.push(...request.urlList)
- }
- // 16. If request’s timing allow failed flag is unset, then set
- // internalResponse’s timing allow passed flag.
- if (!request.timingAllowFailed) {
- response.timingAllowPassed = true
- }
+/***/ }),
- // 17. If response is not a network error and any of the following returns
- // blocked
- // - should internalResponse to request be blocked as mixed content
- // - should internalResponse to request be blocked by Content Security Policy
- // - should internalResponse to request be blocked due to its MIME type
- // - should internalResponse to request be blocked due to nosniff
- // TODO
+/***/ 1528:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 18. If response’s type is "opaque", internalResponse’s status is 206,
- // internalResponse’s range-requested flag is set, and request’s header
- // list does not contain `Range`, then set response and internalResponse
- // to a network error.
- if (
- response.type === 'opaque' &&
- internalResponse.status === 206 &&
- internalResponse.rangeRequested &&
- !request.headers.contains('range', true)
- ) {
- response = internalResponse = makeNetworkError()
- }
- // 19. If response is not a network error and either request’s method is
- // `HEAD` or `CONNECT`, or internalResponse’s status is a null body status,
- // set internalResponse’s body to null and disregard any enqueuing toward
- // it (if any).
- if (
- response.status !== 0 &&
- (request.method === 'HEAD' ||
- request.method === 'CONNECT' ||
- nullBodyStatus.includes(internalResponse.status))
- ) {
- internalResponse.body = null
- fetchParams.controller.dump = true
- }
- // 20. If request’s integrity metadata is not the empty string, then:
- if (request.integrity) {
- // 1. Let processBodyError be this step: run fetch finale given fetchParams
- // and a network error.
- const processBodyError = (reason) =>
- fetchFinale(fetchParams, makeNetworkError(reason))
+var identity = __nccwpck_require__(1127);
+var Pair = __nccwpck_require__(7165);
+var YAMLMap = __nccwpck_require__(4454);
- // 2. If request’s response tainting is "opaque", or response’s body is null,
- // then run processBodyError and abort these steps.
- if (request.responseTainting === 'opaque' || response.body == null) {
- processBodyError(response.error)
- return
+class YAMLSet extends YAMLMap.YAMLMap {
+ constructor(schema) {
+ super(schema);
+ this.tag = YAMLSet.tag;
}
-
- // 3. Let processBody given bytes be these steps:
- const processBody = (bytes) => {
- // 1. If bytes do not match request’s integrity metadata,
- // then run processBodyError and abort these steps. [SRI]
- if (!bytesMatch(bytes, request.integrity)) {
- processBodyError('integrity mismatch')
- return
- }
-
- // 2. Set response’s body to bytes as a body.
- response.body = safelyExtractBody(bytes)[0]
-
- // 3. Run fetch finale given fetchParams and response.
- fetchFinale(fetchParams, response)
+ add(key) {
+ let pair;
+ if (identity.isPair(key))
+ pair = key;
+ else if (key &&
+ typeof key === 'object' &&
+ 'key' in key &&
+ 'value' in key &&
+ key.value === null)
+ pair = new Pair.Pair(key.key, null);
+ else
+ pair = new Pair.Pair(key, null);
+ const prev = YAMLMap.findPair(this.items, pair.key);
+ if (!prev)
+ this.items.push(pair);
+ }
+ /**
+ * If `keepPair` is `true`, returns the Pair matching `key`.
+ * Otherwise, returns the value of that Pair's key.
+ */
+ get(key, keepPair) {
+ const pair = YAMLMap.findPair(this.items, key);
+ return !keepPair && identity.isPair(pair)
+ ? identity.isScalar(pair.key)
+ ? pair.key.value
+ : pair.key
+ : pair;
+ }
+ set(key, value) {
+ if (typeof value !== 'boolean')
+ throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`);
+ const prev = YAMLMap.findPair(this.items, key);
+ if (prev && !value) {
+ this.items.splice(this.items.indexOf(prev), 1);
+ }
+ else if (!prev && value) {
+ this.items.push(new Pair.Pair(key));
+ }
+ }
+ toJSON(_, ctx) {
+ return super.toJSON(_, ctx, Set);
+ }
+ toString(ctx, onComment, onChompKeep) {
+ if (!ctx)
+ return JSON.stringify(this);
+ if (this.hasAllNullValues(true))
+ return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep);
+ else
+ throw new Error('Set items must all have null values');
+ }
+ static from(schema, iterable, ctx) {
+ const { replacer } = ctx;
+ const set = new this(schema);
+ if (iterable && Symbol.iterator in Object(iterable))
+ for (let value of iterable) {
+ if (typeof replacer === 'function')
+ value = replacer.call(iterable, value, value);
+ set.items.push(Pair.createPair(value, null, ctx));
+ }
+ return set;
}
-
- // 4. Fully read response’s body given processBody and processBodyError.
- await fullyReadBody(response.body, processBody, processBodyError)
- } else {
- // 21. Otherwise, run fetch finale given fetchParams and response.
- fetchFinale(fetchParams, response)
- }
}
+YAMLSet.tag = 'tag:yaml.org,2002:set';
+const set = {
+ collection: 'map',
+ identify: value => value instanceof Set,
+ nodeClass: YAMLSet,
+ default: false,
+ tag: 'tag:yaml.org,2002:set',
+ createNode: (schema, iterable, ctx) => YAMLSet.from(schema, iterable, ctx),
+ resolve(map, onError) {
+ if (identity.isMap(map)) {
+ if (map.hasAllNullValues(true))
+ return Object.assign(new YAMLSet(), map);
+ else
+ onError('Set items must all have null values');
+ }
+ else
+ onError('Expected a mapping for this tag');
+ return map;
+ }
+};
-// https://fetch.spec.whatwg.org/#concept-scheme-fetch
-// given a fetch params fetchParams
-function schemeFetch (fetchParams) {
- // Note: since the connection is destroyed on redirect, which sets fetchParams to a
- // cancelled state, we do not want this condition to trigger *unless* there have been
- // no redirects. See https://github.com/nodejs/undici/issues/1776
- // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
- if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) {
- return Promise.resolve(makeAppropriateNetworkError(fetchParams))
- }
+exports.YAMLSet = YAMLSet;
+exports.set = set;
- // 2. Let request be fetchParams’s request.
- const { request } = fetchParams
- const { protocol: scheme } = requestCurrentURL(request)
+/***/ }),
- // 3. Switch on request’s current URL’s scheme and run the associated steps:
- switch (scheme) {
- case 'about:': {
- // If request’s current URL’s path is the string "blank", then return a new response
- // whose status message is `OK`, header list is « (`Content-Type`, `text/html;charset=utf-8`) »,
- // and body is the empty byte sequence as a body.
+/***/ 4371:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // Otherwise, return a network error.
- return Promise.resolve(makeNetworkError('about scheme is not supported'))
- }
- case 'blob:': {
- if (!resolveObjectURL) {
- resolveObjectURL = (__nccwpck_require__(4573).resolveObjectURL)
- }
- // 1. Let blobURLEntry be request’s current URL’s blob URL entry.
- const blobURLEntry = requestCurrentURL(request)
- // https://github.com/web-platform-tests/wpt/blob/7b0ebaccc62b566a1965396e5be7bb2bc06f841f/FileAPI/url/resources/fetch-tests.js#L52-L56
- // Buffer.resolveObjectURL does not ignore URL queries.
- if (blobURLEntry.search.length !== 0) {
- return Promise.resolve(makeNetworkError('NetworkError when attempting to fetch resource.'))
- }
+var stringifyNumber = __nccwpck_require__(8689);
- const blob = resolveObjectURL(blobURLEntry.toString())
+/** Internal types handle bigint as number, because TS can't figure it out. */
+function parseSexagesimal(str, asBigInt) {
+ const sign = str[0];
+ const parts = sign === '-' || sign === '+' ? str.substring(1) : str;
+ const num = (n) => asBigInt ? BigInt(n) : Number(n);
+ const res = parts
+ .replace(/_/g, '')
+ .split(':')
+ .reduce((res, p) => res * num(60) + num(p), num(0));
+ return (sign === '-' ? num(-1) * res : res);
+}
+/**
+ * hhhh:mm:ss.sss
+ *
+ * Internal types handle bigint as number, because TS can't figure it out.
+ */
+function stringifySexagesimal(node) {
+ let { value } = node;
+ let num = (n) => n;
+ if (typeof value === 'bigint')
+ num = n => BigInt(n);
+ else if (isNaN(value) || !isFinite(value))
+ return stringifyNumber.stringifyNumber(node);
+ let sign = '';
+ if (value < 0) {
+ sign = '-';
+ value *= num(-1);
+ }
+ const _60 = num(60);
+ const parts = [value % _60]; // seconds, including ms
+ if (value < 60) {
+ parts.unshift(0); // at least one : is required
+ }
+ else {
+ value = (value - parts[0]) / _60;
+ parts.unshift(value % _60); // minutes
+ if (value >= 60) {
+ value = (value - parts[0]) / _60;
+ parts.unshift(value); // hours
+ }
+ }
+ return (sign +
+ parts
+ .map(n => String(n).padStart(2, '0'))
+ .join(':')
+ .replace(/000000\d*$/, '') // % 60 may introduce error
+ );
+}
+const intTime = {
+ identify: value => typeof value === 'bigint' || Number.isInteger(value),
+ default: true,
+ tag: 'tag:yaml.org,2002:int',
+ format: 'TIME',
+ test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,
+ resolve: (str, _onError, { intAsBigInt }) => parseSexagesimal(str, intAsBigInt),
+ stringify: stringifySexagesimal
+};
+const floatTime = {
+ identify: value => typeof value === 'number',
+ default: true,
+ tag: 'tag:yaml.org,2002:float',
+ format: 'TIME',
+ test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,
+ resolve: str => parseSexagesimal(str, false),
+ stringify: stringifySexagesimal
+};
+const timestamp = {
+ identify: value => value instanceof Date,
+ default: true,
+ tag: 'tag:yaml.org,2002:timestamp',
+ // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part
+ // may be omitted altogether, resulting in a date format. In such a case, the time part is
+ // assumed to be 00:00:00Z (start of day, UTC).
+ test: RegExp('^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})' + // YYYY-Mm-Dd
+ '(?:' + // time is optional
+ '(?:t|T|[ \\t]+)' + // t | T | whitespace
+ '([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)' + // Hh:Mm:Ss(.ss)?
+ '(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?' + // Z | +5 | -03:30
+ ')?$'),
+ resolve(str) {
+ const match = str.match(timestamp.test);
+ if (!match)
+ throw new Error('!!timestamp expects a date, starting with yyyy-mm-dd');
+ const [, year, month, day, hour, minute, second] = match.map(Number);
+ const millisec = match[7] ? Number((match[7] + '00').substr(1, 3)) : 0;
+ let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec);
+ const tz = match[8];
+ if (tz && tz !== 'Z') {
+ let d = parseSexagesimal(tz, false);
+ if (Math.abs(d) < 30)
+ d *= 60;
+ date -= 60000 * d;
+ }
+ return new Date(date);
+ },
+ stringify: ({ value }) => value?.toISOString().replace(/(T00:00:00)?\.000Z$/, '') ?? ''
+};
- // 2. If request’s method is not `GET`, blobURLEntry is null, or blobURLEntry’s
- // object is not a Blob object, then return a network error.
- if (request.method !== 'GET' || !isBlobLike(blob)) {
- return Promise.resolve(makeNetworkError('invalid method'))
- }
+exports.floatTime = floatTime;
+exports.intTime = intTime;
+exports.timestamp = timestamp;
- // 3. Let blob be blobURLEntry’s object.
- // Note: done above
- // 4. Let response be a new response.
- const response = makeResponse()
+/***/ }),
- // 5. Let fullLength be blob’s size.
- const fullLength = blob.size
+/***/ 4475:
+/***/ ((__unused_webpack_module, exports) => {
- // 6. Let serializedFullLength be fullLength, serialized and isomorphic encoded.
- const serializedFullLength = isomorphicEncode(`${fullLength}`)
- // 7. Let type be blob’s type.
- const type = blob.type
- // 8. If request’s header list does not contain `Range`:
- // 9. Otherwise:
- if (!request.headersList.contains('range', true)) {
- // 1. Let bodyWithType be the result of safely extracting blob.
- // Note: in the FileAPI a blob "object" is a Blob *or* a MediaSource.
- // In node, this can only ever be a Blob. Therefore we can safely
- // use extractBody directly.
- const bodyWithType = extractBody(blob)
-
- // 2. Set response’s status message to `OK`.
- response.statusText = 'OK'
-
- // 3. Set response’s body to bodyWithType’s body.
- response.body = bodyWithType[0]
-
- // 4. Set response’s header list to « (`Content-Length`, serializedFullLength), (`Content-Type`, type) ».
- response.headersList.set('content-length', serializedFullLength, true)
- response.headersList.set('content-type', type, true)
- } else {
- // 1. Set response’s range-requested flag.
- response.rangeRequested = true
-
- // 2. Let rangeHeader be the result of getting `Range` from request’s header list.
- const rangeHeader = request.headersList.get('range', true)
-
- // 3. Let rangeValue be the result of parsing a single range header value given rangeHeader and true.
- const rangeValue = simpleRangeHeaderValue(rangeHeader, true)
-
- // 4. If rangeValue is failure, then return a network error.
- if (rangeValue === 'failure') {
- return Promise.resolve(makeNetworkError('failed to fetch the data URL'))
+const FOLD_FLOW = 'flow';
+const FOLD_BLOCK = 'block';
+const FOLD_QUOTED = 'quoted';
+/**
+ * Tries to keep input at up to `lineWidth` characters, splitting only on spaces
+ * not followed by newlines or spaces unless `mode` is `'quoted'`. Lines are
+ * terminated with `\n` and started with `indent`.
+ */
+function foldFlowLines(text, indent, mode = 'flow', { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) {
+ if (!lineWidth || lineWidth < 0)
+ return text;
+ if (lineWidth < minContentWidth)
+ minContentWidth = 0;
+ const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length);
+ if (text.length <= endStep)
+ return text;
+ const folds = [];
+ const escapedFolds = {};
+ let end = lineWidth - indent.length;
+ if (typeof indentAtStart === 'number') {
+ if (indentAtStart > lineWidth - Math.max(2, minContentWidth))
+ folds.push(0);
+ else
+ end = lineWidth - indentAtStart;
+ }
+ let split = undefined;
+ let prev = undefined;
+ let overflow = false;
+ let i = -1;
+ let escStart = -1;
+ let escEnd = -1;
+ if (mode === FOLD_BLOCK) {
+ i = consumeMoreIndentedLines(text, i, indent.length);
+ if (i !== -1)
+ end = i + endStep;
+ }
+ for (let ch; (ch = text[(i += 1)]);) {
+ if (mode === FOLD_QUOTED && ch === '\\') {
+ escStart = i;
+ switch (text[i + 1]) {
+ case 'x':
+ i += 3;
+ break;
+ case 'u':
+ i += 5;
+ break;
+ case 'U':
+ i += 9;
+ break;
+ default:
+ i += 1;
+ }
+ escEnd = i;
}
-
- // 5. Let (rangeStart, rangeEnd) be rangeValue.
- let { rangeStartValue: rangeStart, rangeEndValue: rangeEnd } = rangeValue
-
- // 6. If rangeStart is null:
- // 7. Otherwise:
- if (rangeStart === null) {
- // 1. Set rangeStart to fullLength − rangeEnd.
- rangeStart = fullLength - rangeEnd
-
- // 2. Set rangeEnd to rangeStart + rangeEnd − 1.
- rangeEnd = rangeStart + rangeEnd - 1
- } else {
- // 1. If rangeStart is greater than or equal to fullLength, then return a network error.
- if (rangeStart >= fullLength) {
- return Promise.resolve(makeNetworkError('Range start is greater than the blob\'s size.'))
- }
-
- // 2. If rangeEnd is null or rangeEnd is greater than or equal to fullLength, then set
- // rangeEnd to fullLength − 1.
- if (rangeEnd === null || rangeEnd >= fullLength) {
- rangeEnd = fullLength - 1
- }
+ if (ch === '\n') {
+ if (mode === FOLD_BLOCK)
+ i = consumeMoreIndentedLines(text, i, indent.length);
+ end = i + indent.length + endStep;
+ split = undefined;
}
+ else {
+ if (ch === ' ' &&
+ prev &&
+ prev !== ' ' &&
+ prev !== '\n' &&
+ prev !== '\t') {
+ // space surrounded by non-space can be replaced with newline + indent
+ const next = text[i + 1];
+ if (next && next !== ' ' && next !== '\n' && next !== '\t')
+ split = i;
+ }
+ if (i >= end) {
+ if (split) {
+ folds.push(split);
+ end = split + endStep;
+ split = undefined;
+ }
+ else if (mode === FOLD_QUOTED) {
+ // white-space collected at end may stretch past lineWidth
+ while (prev === ' ' || prev === '\t') {
+ prev = ch;
+ ch = text[(i += 1)];
+ overflow = true;
+ }
+ // Account for newline escape, but don't break preceding escape
+ const j = i > escEnd + 1 ? i - 2 : escStart - 1;
+ // Bail out if lineWidth & minContentWidth are shorter than an escape string
+ if (escapedFolds[j])
+ return text;
+ folds.push(j);
+ escapedFolds[j] = true;
+ end = j + endStep;
+ split = undefined;
+ }
+ else {
+ overflow = true;
+ }
+ }
+ }
+ prev = ch;
+ }
+ if (overflow && onOverflow)
+ onOverflow();
+ if (folds.length === 0)
+ return text;
+ if (onFold)
+ onFold();
+ let res = text.slice(0, folds[0]);
+ for (let i = 0; i < folds.length; ++i) {
+ const fold = folds[i];
+ const end = folds[i + 1] || text.length;
+ if (fold === 0)
+ res = `\n${indent}${text.slice(0, end)}`;
+ else {
+ if (mode === FOLD_QUOTED && escapedFolds[fold])
+ res += `${text[fold]}\\`;
+ res += `\n${indent}${text.slice(fold + 1, end)}`;
+ }
+ }
+ return res;
+}
+/**
+ * Presumes `i + 1` is at the start of a line
+ * @returns index of last newline in more-indented block
+ */
+function consumeMoreIndentedLines(text, i, indent) {
+ let end = i;
+ let start = i + 1;
+ let ch = text[start];
+ while (ch === ' ' || ch === '\t') {
+ if (i < start + indent) {
+ ch = text[++i];
+ }
+ else {
+ do {
+ ch = text[++i];
+ } while (ch && ch !== '\n');
+ end = i;
+ start = i + 1;
+ ch = text[start];
+ }
+ }
+ return end;
+}
- // 8. Let slicedBlob be the result of invoking slice blob given blob, rangeStart,
- // rangeEnd + 1, and type.
- const slicedBlob = blob.slice(rangeStart, rangeEnd, type)
-
- // 9. Let slicedBodyWithType be the result of safely extracting slicedBlob.
- // Note: same reason as mentioned above as to why we use extractBody
- const slicedBodyWithType = extractBody(slicedBlob)
+exports.FOLD_BLOCK = FOLD_BLOCK;
+exports.FOLD_FLOW = FOLD_FLOW;
+exports.FOLD_QUOTED = FOLD_QUOTED;
+exports.foldFlowLines = foldFlowLines;
- // 10. Set response’s body to slicedBodyWithType’s body.
- response.body = slicedBodyWithType[0]
- // 11. Let serializedSlicedLength be slicedBlob’s size, serialized and isomorphic encoded.
- const serializedSlicedLength = isomorphicEncode(`${slicedBlob.size}`)
+/***/ }),
- // 12. Let contentRange be the result of invoking build a content range given rangeStart,
- // rangeEnd, and fullLength.
- const contentRange = buildContentRange(rangeStart, rangeEnd, fullLength)
+/***/ 2148:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 13. Set response’s status to 206.
- response.status = 206
- // 14. Set response’s status message to `Partial Content`.
- response.statusText = 'Partial Content'
- // 15. Set response’s header list to « (`Content-Length`, serializedSlicedLength),
- // (`Content-Type`, type), (`Content-Range`, contentRange) ».
- response.headersList.set('content-length', serializedSlicedLength, true)
- response.headersList.set('content-type', type, true)
- response.headersList.set('content-range', contentRange, true)
- }
+var anchors = __nccwpck_require__(1596);
+var identity = __nccwpck_require__(1127);
+var stringifyComment = __nccwpck_require__(9799);
+var stringifyString = __nccwpck_require__(3069);
- // 10. Return response.
- return Promise.resolve(response)
+function createStringifyContext(doc, options) {
+ const opt = Object.assign({
+ blockQuote: true,
+ commentString: stringifyComment.stringifyComment,
+ defaultKeyType: null,
+ defaultStringType: 'PLAIN',
+ directives: null,
+ doubleQuotedAsJSON: false,
+ doubleQuotedMinMultiLineLength: 40,
+ falseStr: 'false',
+ flowCollectionPadding: true,
+ indentSeq: true,
+ lineWidth: 80,
+ minContentWidth: 20,
+ nullStr: 'null',
+ simpleKeys: false,
+ singleQuote: null,
+ trailingComma: false,
+ trueStr: 'true',
+ verifyAliasOrder: true
+ }, doc.schema.toStringOptions, options);
+ let inFlow;
+ switch (opt.collectionStyle) {
+ case 'block':
+ inFlow = false;
+ break;
+ case 'flow':
+ inFlow = true;
+ break;
+ default:
+ inFlow = null;
}
- case 'data:': {
- // 1. Let dataURLStruct be the result of running the
- // data: URL processor on request’s current URL.
- const currentURL = requestCurrentURL(request)
- const dataURLStruct = dataURLProcessor(currentURL)
-
- // 2. If dataURLStruct is failure, then return a
- // network error.
- if (dataURLStruct === 'failure') {
- return Promise.resolve(makeNetworkError('failed to fetch the data URL'))
- }
-
- // 3. Let mimeType be dataURLStruct’s MIME type, serialized.
- const mimeType = serializeAMimeType(dataURLStruct.mimeType)
-
- // 4. Return a response whose status message is `OK`,
- // header list is « (`Content-Type`, mimeType) »,
- // and body is dataURLStruct’s body as a body.
- return Promise.resolve(makeResponse({
- statusText: 'OK',
- headersList: [
- ['content-type', { name: 'Content-Type', value: mimeType }]
- ],
- body: safelyExtractBody(dataURLStruct.body)[0]
- }))
+ return {
+ anchors: new Set(),
+ doc,
+ flowCollectionPadding: opt.flowCollectionPadding ? ' ' : '',
+ indent: '',
+ indentStep: typeof opt.indent === 'number' ? ' '.repeat(opt.indent) : ' ',
+ inFlow,
+ options: opt
+ };
+}
+function getTagObject(tags, item) {
+ if (item.tag) {
+ const match = tags.filter(t => t.tag === item.tag);
+ if (match.length > 0)
+ return match.find(t => t.format === item.format) ?? match[0];
}
- case 'file:': {
- // For now, unfortunate as it is, file URLs are left as an exercise for the reader.
- // When in doubt, return a network error.
- return Promise.resolve(makeNetworkError('not implemented... yet...'))
+ let tagObj = undefined;
+ let obj;
+ if (identity.isScalar(item)) {
+ obj = item.value;
+ let match = tags.filter(t => t.identify?.(obj));
+ if (match.length > 1) {
+ const testMatch = match.filter(t => t.test);
+ if (testMatch.length > 0)
+ match = testMatch;
+ }
+ tagObj =
+ match.find(t => t.format === item.format) ?? match.find(t => !t.format);
}
- case 'http:':
- case 'https:': {
- // Return the result of running HTTP fetch given fetchParams.
-
- return httpFetch(fetchParams)
- .catch((err) => makeNetworkError(err))
+ else {
+ obj = item;
+ tagObj = tags.find(t => t.nodeClass && obj instanceof t.nodeClass);
}
- default: {
- return Promise.resolve(makeNetworkError('unknown scheme'))
+ if (!tagObj) {
+ const name = obj?.constructor?.name ?? (obj === null ? 'null' : typeof obj);
+ throw new Error(`Tag not resolved for ${name} value`);
}
- }
+ return tagObj;
}
-
-// https://fetch.spec.whatwg.org/#finalize-response
-function finalizeResponse (fetchParams, response) {
- // 1. Set fetchParams’s request’s done flag.
- fetchParams.request.done = true
-
- // 2, If fetchParams’s process response done is not null, then queue a fetch
- // task to run fetchParams’s process response done given response, with
- // fetchParams’s task destination.
- if (fetchParams.processResponseDone != null) {
- queueMicrotask(() => fetchParams.processResponseDone(response))
- }
+// needs to be called before value stringifier to allow for circular anchor refs
+function stringifyProps(node, tagObj, { anchors: anchors$1, doc }) {
+ if (!doc.directives)
+ return '';
+ const props = [];
+ const anchor = (identity.isScalar(node) || identity.isCollection(node)) && node.anchor;
+ if (anchor && anchors.anchorIsValid(anchor)) {
+ anchors$1.add(anchor);
+ props.push(`&${anchor}`);
+ }
+ const tag = node.tag ?? (tagObj.default ? null : tagObj.tag);
+ if (tag)
+ props.push(doc.directives.tagString(tag));
+ return props.join(' ');
}
-
-// https://fetch.spec.whatwg.org/#fetch-finale
-function fetchFinale (fetchParams, response) {
- // 1. Let timingInfo be fetchParams’s timing info.
- let timingInfo = fetchParams.timingInfo
-
- // 2. If response is not a network error and fetchParams’s request’s client is a secure context,
- // then set timingInfo’s server-timing headers to the result of getting, decoding, and splitting
- // `Server-Timing` from response’s internal response’s header list.
- // TODO
-
- // 3. Let processResponseEndOfBody be the following steps:
- const processResponseEndOfBody = () => {
- // 1. Let unsafeEndTime be the unsafe shared current time.
- const unsafeEndTime = Date.now() // ?
-
- // 2. If fetchParams’s request’s destination is "document", then set fetchParams’s controller’s
- // full timing info to fetchParams’s timing info.
- if (fetchParams.request.destination === 'document') {
- fetchParams.controller.fullTimingInfo = timingInfo
+function stringify(item, ctx, onComment, onChompKeep) {
+ if (identity.isPair(item))
+ return item.toString(ctx, onComment, onChompKeep);
+ if (identity.isAlias(item)) {
+ if (ctx.doc.directives)
+ return item.toString(ctx);
+ if (ctx.resolvedAliases?.has(item)) {
+ throw new TypeError(`Cannot stringify circular structure without alias nodes`);
+ }
+ else {
+ if (ctx.resolvedAliases)
+ ctx.resolvedAliases.add(item);
+ else
+ ctx.resolvedAliases = new Set([item]);
+ item = item.resolve(ctx.doc);
+ }
}
+ let tagObj = undefined;
+ const node = identity.isNode(item)
+ ? item
+ : ctx.doc.createNode(item, { onTagObj: o => (tagObj = o) });
+ tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node));
+ const props = stringifyProps(node, tagObj, ctx);
+ if (props.length > 0)
+ ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1;
+ const str = typeof tagObj.stringify === 'function'
+ ? tagObj.stringify(node, ctx, onComment, onChompKeep)
+ : identity.isScalar(node)
+ ? stringifyString.stringifyString(node, ctx, onComment, onChompKeep)
+ : node.toString(ctx, onComment, onChompKeep);
+ if (!props)
+ return str;
+ return identity.isScalar(node) || str[0] === '{' || str[0] === '['
+ ? `${props} ${str}`
+ : `${props}\n${ctx.indent}${str}`;
+}
- // 3. Set fetchParams’s controller’s report timing steps to the following steps given a global object global:
- fetchParams.controller.reportTimingSteps = () => {
- // 1. If fetchParams’s request’s URL’s scheme is not an HTTP(S) scheme, then return.
- if (fetchParams.request.url.protocol !== 'https:') {
- return
- }
-
- // 2. Set timingInfo’s end time to the relative high resolution time given unsafeEndTime and global.
- timingInfo.endTime = unsafeEndTime
-
- // 3. Let cacheState be response’s cache state.
- let cacheState = response.cacheState
+exports.createStringifyContext = createStringifyContext;
+exports.stringify = stringify;
- // 4. Let bodyInfo be response’s body info.
- const bodyInfo = response.bodyInfo
- // 5. If response’s timing allow passed flag is not set, then set timingInfo to the result of creating an
- // opaque timing info for timingInfo and set cacheState to the empty string.
- if (!response.timingAllowPassed) {
- timingInfo = createOpaqueTimingInfo(timingInfo)
+/***/ }),
- cacheState = ''
- }
+/***/ 1212:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 6. Let responseStatus be 0.
- let responseStatus = 0
- // 7. If fetchParams’s request’s mode is not "navigate" or response’s has-cross-origin-redirects is false:
- if (fetchParams.request.mode !== 'navigator' || !response.hasCrossOriginRedirects) {
- // 1. Set responseStatus to response’s status.
- responseStatus = response.status
- // 2. Let mimeType be the result of extracting a MIME type from response’s header list.
- const mimeType = extractMimeType(response.headersList)
+var identity = __nccwpck_require__(1127);
+var stringify = __nccwpck_require__(2148);
+var stringifyComment = __nccwpck_require__(9799);
- // 3. If mimeType is not failure, then set bodyInfo’s content type to the result of minimizing a supported MIME type given mimeType.
- if (mimeType !== 'failure') {
- bodyInfo.contentType = minimizeSupportedMimeType(mimeType)
+function stringifyCollection(collection, ctx, options) {
+ const flow = ctx.inFlow ?? collection.flow;
+ const stringify = flow ? stringifyFlowCollection : stringifyBlockCollection;
+ return stringify(collection, ctx, options);
+}
+function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) {
+ const { indent, options: { commentString } } = ctx;
+ const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null });
+ let chompKeep = false; // flag for the preceding node's status
+ const lines = [];
+ for (let i = 0; i < items.length; ++i) {
+ const item = items[i];
+ let comment = null;
+ if (identity.isNode(item)) {
+ if (!chompKeep && item.spaceBefore)
+ lines.push('');
+ addCommentBefore(ctx, lines, item.commentBefore, chompKeep);
+ if (item.comment)
+ comment = item.comment;
}
- }
-
- // 8. If fetchParams’s request’s initiator type is non-null, then mark resource timing given timingInfo,
- // fetchParams’s request’s URL, fetchParams’s request’s initiator type, global, cacheState, bodyInfo,
- // and responseStatus.
- if (fetchParams.request.initiatorType != null) {
- // TODO: update markresourcetiming
- markResourceTiming(timingInfo, fetchParams.request.url.href, fetchParams.request.initiatorType, globalThis, cacheState, bodyInfo, responseStatus)
- }
+ else if (identity.isPair(item)) {
+ const ik = identity.isNode(item.key) ? item.key : null;
+ if (ik) {
+ if (!chompKeep && ik.spaceBefore)
+ lines.push('');
+ addCommentBefore(ctx, lines, ik.commentBefore, chompKeep);
+ }
+ }
+ chompKeep = false;
+ let str = stringify.stringify(item, itemCtx, () => (comment = null), () => (chompKeep = true));
+ if (comment)
+ str += stringifyComment.lineComment(str, itemIndent, commentString(comment));
+ if (chompKeep && comment)
+ chompKeep = false;
+ lines.push(blockItemPrefix + str);
}
-
- // 4. Let processResponseEndOfBodyTask be the following steps:
- const processResponseEndOfBodyTask = () => {
- // 1. Set fetchParams’s request’s done flag.
- fetchParams.request.done = true
-
- // 2. If fetchParams’s process response end-of-body is non-null, then run fetchParams’s process
- // response end-of-body given response.
- if (fetchParams.processResponseEndOfBody != null) {
- queueMicrotask(() => fetchParams.processResponseEndOfBody(response))
- }
-
- // 3. If fetchParams’s request’s initiator type is non-null and fetchParams’s request’s client’s
- // global object is fetchParams’s task destination, then run fetchParams’s controller’s report
- // timing steps given fetchParams’s request’s client’s global object.
- if (fetchParams.request.initiatorType != null) {
- fetchParams.controller.reportTimingSteps()
- }
+ let str;
+ if (lines.length === 0) {
+ str = flowChars.start + flowChars.end;
}
-
- // 5. Queue a fetch task to run processResponseEndOfBodyTask with fetchParams’s task destination
- queueMicrotask(() => processResponseEndOfBodyTask())
- }
-
- // 4. If fetchParams’s process response is non-null, then queue a fetch task to run fetchParams’s
- // process response given response, with fetchParams’s task destination.
- if (fetchParams.processResponse != null) {
- queueMicrotask(() => {
- fetchParams.processResponse(response)
- fetchParams.processResponse = null
- })
- }
-
- // 5. Let internalResponse be response, if response is a network error; otherwise response’s internal response.
- const internalResponse = response.type === 'error' ? response : (response.internalResponse ?? response)
-
- // 6. If internalResponse’s body is null, then run processResponseEndOfBody.
- // 7. Otherwise:
- if (internalResponse.body == null) {
- processResponseEndOfBody()
- } else {
- // mcollina: all the following steps of the specs are skipped.
- // The internal transform stream is not needed.
- // See https://github.com/nodejs/undici/pull/3093#issuecomment-2050198541
-
- // 1. Let transformStream be a new TransformStream.
- // 2. Let identityTransformAlgorithm be an algorithm which, given chunk, enqueues chunk in transformStream.
- // 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm and flushAlgorithm
- // set to processResponseEndOfBody.
- // 4. Set internalResponse’s body’s stream to the result of internalResponse’s body’s stream piped through transformStream.
-
- finished(internalResponse.body.stream, () => {
- processResponseEndOfBody()
- })
- }
-}
-
-// https://fetch.spec.whatwg.org/#http-fetch
-async function httpFetch (fetchParams) {
- // 1. Let request be fetchParams’s request.
- const request = fetchParams.request
-
- // 2. Let response be null.
- let response = null
-
- // 3. Let actualResponse be null.
- let actualResponse = null
-
- // 4. Let timingInfo be fetchParams’s timing info.
- const timingInfo = fetchParams.timingInfo
-
- // 5. If request’s service-workers mode is "all", then:
- if (request.serviceWorkers === 'all') {
- // TODO
- }
-
- // 6. If response is null, then:
- if (response === null) {
- // 1. If makeCORSPreflight is true and one of these conditions is true:
- // TODO
-
- // 2. If request’s redirect mode is "follow", then set request’s
- // service-workers mode to "none".
- if (request.redirect === 'follow') {
- request.serviceWorkers = 'none'
+ else {
+ str = lines[0];
+ for (let i = 1; i < lines.length; ++i) {
+ const line = lines[i];
+ str += line ? `\n${indent}${line}` : '\n';
+ }
}
-
- // 3. Set response and actualResponse to the result of running
- // HTTP-network-or-cache fetch given fetchParams.
- actualResponse = response = await httpNetworkOrCacheFetch(fetchParams)
-
- // 4. If request’s response tainting is "cors" and a CORS check
- // for request and response returns failure, then return a network error.
- if (
- request.responseTainting === 'cors' &&
- corsCheck(request, response) === 'failure'
- ) {
- return makeNetworkError('cors failure')
+ if (comment) {
+ str += '\n' + stringifyComment.indentComment(commentString(comment), indent);
+ if (onComment)
+ onComment();
}
-
- // 5. If the TAO check for request and response returns failure, then set
- // request’s timing allow failed flag.
- if (TAOCheck(request, response) === 'failure') {
- request.timingAllowFailed = true
+ else if (chompKeep && onChompKeep)
+ onChompKeep();
+ return str;
+}
+function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) {
+ const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx;
+ itemIndent += indentStep;
+ const itemCtx = Object.assign({}, ctx, {
+ indent: itemIndent,
+ inFlow: true,
+ type: null
+ });
+ let reqNewline = false;
+ let linesAtValue = 0;
+ const lines = [];
+ for (let i = 0; i < items.length; ++i) {
+ const item = items[i];
+ let comment = null;
+ if (identity.isNode(item)) {
+ if (item.spaceBefore)
+ lines.push('');
+ addCommentBefore(ctx, lines, item.commentBefore, false);
+ if (item.comment)
+ comment = item.comment;
+ }
+ else if (identity.isPair(item)) {
+ const ik = identity.isNode(item.key) ? item.key : null;
+ if (ik) {
+ if (ik.spaceBefore)
+ lines.push('');
+ addCommentBefore(ctx, lines, ik.commentBefore, false);
+ if (ik.comment)
+ reqNewline = true;
+ }
+ const iv = identity.isNode(item.value) ? item.value : null;
+ if (iv) {
+ if (iv.comment)
+ comment = iv.comment;
+ if (iv.commentBefore)
+ reqNewline = true;
+ }
+ else if (item.value == null && ik?.comment) {
+ comment = ik.comment;
+ }
+ }
+ if (comment)
+ reqNewline = true;
+ let str = stringify.stringify(item, itemCtx, () => (comment = null));
+ reqNewline || (reqNewline = lines.length > linesAtValue || str.includes('\n'));
+ if (i < items.length - 1) {
+ str += ',';
+ }
+ else if (ctx.options.trailingComma) {
+ if (ctx.options.lineWidth > 0) {
+ reqNewline || (reqNewline = lines.reduce((sum, line) => sum + line.length + 2, 2) +
+ (str.length + 2) >
+ ctx.options.lineWidth);
+ }
+ if (reqNewline) {
+ str += ',';
+ }
+ }
+ if (comment)
+ str += stringifyComment.lineComment(str, itemIndent, commentString(comment));
+ lines.push(str);
+ linesAtValue = lines.length;
}
- }
-
- // 7. If either request’s response tainting or response’s type
- // is "opaque", and the cross-origin resource policy check with
- // request’s origin, request’s client, request’s destination,
- // and actualResponse returns blocked, then return a network error.
- if (
- (request.responseTainting === 'opaque' || response.type === 'opaque') &&
- crossOriginResourcePolicyCheck(
- request.origin,
- request.client,
- request.destination,
- actualResponse
- ) === 'blocked'
- ) {
- return makeNetworkError('blocked')
- }
-
- // 8. If actualResponse’s status is a redirect status, then:
- if (redirectStatusSet.has(actualResponse.status)) {
- // 1. If actualResponse’s status is not 303, request’s body is not null,
- // and the connection uses HTTP/2, then user agents may, and are even
- // encouraged to, transmit an RST_STREAM frame.
- // See, https://github.com/whatwg/fetch/issues/1288
- if (request.redirect !== 'manual') {
- fetchParams.controller.connection.destroy(undefined, false)
+ const { start, end } = flowChars;
+ if (lines.length === 0) {
+ return start + end;
}
-
- // 2. Switch on request’s redirect mode:
- if (request.redirect === 'error') {
- // Set response to a network error.
- response = makeNetworkError('unexpected redirect')
- } else if (request.redirect === 'manual') {
- // Set response to an opaque-redirect filtered response whose internal
- // response is actualResponse.
- // NOTE(spec): On the web this would return an `opaqueredirect` response,
- // but that doesn't make sense server side.
- // See https://github.com/nodejs/undici/issues/1193.
- response = actualResponse
- } else if (request.redirect === 'follow') {
- // Set response to the result of running HTTP-redirect fetch given
- // fetchParams and response.
- response = await httpRedirectFetch(fetchParams, response)
- } else {
- assert(false)
+ else {
+ if (!reqNewline) {
+ const len = lines.reduce((sum, line) => sum + line.length + 2, 2);
+ reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth;
+ }
+ if (reqNewline) {
+ let str = start;
+ for (const line of lines)
+ str += line ? `\n${indentStep}${indent}${line}` : '\n';
+ return `${str}\n${indent}${end}`;
+ }
+ else {
+ return `${start}${fcPadding}${lines.join(' ')}${fcPadding}${end}`;
+ }
+ }
+}
+function addCommentBefore({ indent, options: { commentString } }, lines, comment, chompKeep) {
+ if (comment && chompKeep)
+ comment = comment.replace(/^\n+/, '');
+ if (comment) {
+ const ic = stringifyComment.indentComment(commentString(comment), indent);
+ lines.push(ic.trimStart()); // Avoid double indent on first line
}
- }
-
- // 9. Set response’s timing info to timingInfo.
- response.timingInfo = timingInfo
-
- // 10. Return response.
- return response
}
-// https://fetch.spec.whatwg.org/#http-redirect-fetch
-function httpRedirectFetch (fetchParams, response) {
- // 1. Let request be fetchParams’s request.
- const request = fetchParams.request
-
- // 2. Let actualResponse be response, if response is not a filtered response,
- // and response’s internal response otherwise.
- const actualResponse = response.internalResponse
- ? response.internalResponse
- : response
+exports.stringifyCollection = stringifyCollection;
- // 3. Let locationURL be actualResponse’s location URL given request’s current
- // URL’s fragment.
- let locationURL
- try {
- locationURL = responseLocationURL(
- actualResponse,
- requestCurrentURL(request).hash
- )
+/***/ }),
- // 4. If locationURL is null, then return response.
- if (locationURL == null) {
- return response
- }
- } catch (err) {
- // 5. If locationURL is failure, then return a network error.
- return Promise.resolve(makeNetworkError(err))
- }
+/***/ 9799:
+/***/ ((__unused_webpack_module, exports) => {
- // 6. If locationURL’s scheme is not an HTTP(S) scheme, then return a network
- // error.
- if (!urlIsHttpHttpsScheme(locationURL)) {
- return Promise.resolve(makeNetworkError('URL scheme must be a HTTP(S) scheme'))
- }
- // 7. If request’s redirect count is 20, then return a network error.
- if (request.redirectCount === 20) {
- return Promise.resolve(makeNetworkError('redirect count exceeded'))
- }
- // 8. Increase request’s redirect count by 1.
- request.redirectCount += 1
+/**
+ * Stringifies a comment.
+ *
+ * Empty comment lines are left empty,
+ * lines consisting of a single space are replaced by `#`,
+ * and all other lines are prefixed with a `#`.
+ */
+const stringifyComment = (str) => str.replace(/^(?!$)(?: $)?/gm, '#');
+function indentComment(comment, indent) {
+ if (/^\n+$/.test(comment))
+ return comment.substring(1);
+ return indent ? comment.replace(/^(?! *$)/gm, indent) : comment;
+}
+const lineComment = (str, indent, comment) => str.endsWith('\n')
+ ? indentComment(comment, indent)
+ : comment.includes('\n')
+ ? '\n' + indentComment(comment, indent)
+ : (str.endsWith(' ') ? '' : ' ') + comment;
- // 9. If request’s mode is "cors", locationURL includes credentials, and
- // request’s origin is not same origin with locationURL’s origin, then return
- // a network error.
- if (
- request.mode === 'cors' &&
- (locationURL.username || locationURL.password) &&
- !sameOrigin(request, locationURL)
- ) {
- return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"'))
- }
+exports.indentComment = indentComment;
+exports.lineComment = lineComment;
+exports.stringifyComment = stringifyComment;
- // 10. If request’s response tainting is "cors" and locationURL includes
- // credentials, then return a network error.
- if (
- request.responseTainting === 'cors' &&
- (locationURL.username || locationURL.password)
- ) {
- return Promise.resolve(makeNetworkError(
- 'URL cannot contain credentials for request mode "cors"'
- ))
- }
- // 11. If actualResponse’s status is not 303, request’s body is non-null,
- // and request’s body’s source is null, then return a network error.
- if (
- actualResponse.status !== 303 &&
- request.body != null &&
- request.body.source == null
- ) {
- return Promise.resolve(makeNetworkError())
- }
+/***/ }),
- // 12. If one of the following is true
- // - actualResponse’s status is 301 or 302 and request’s method is `POST`
- // - actualResponse’s status is 303 and request’s method is not `GET` or `HEAD`
- if (
- ([301, 302].includes(actualResponse.status) && request.method === 'POST') ||
- (actualResponse.status === 303 &&
- !GET_OR_HEAD.includes(request.method))
- ) {
- // then:
- // 1. Set request’s method to `GET` and request’s body to null.
- request.method = 'GET'
- request.body = null
+/***/ 6829:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 2. For each headerName of request-body-header name, delete headerName from
- // request’s header list.
- for (const headerName of requestBodyHeader) {
- request.headersList.delete(headerName)
- }
- }
- // 13. If request’s current URL’s origin is not same origin with locationURL’s
- // origin, then for each headerName of CORS non-wildcard request-header name,
- // delete headerName from request’s header list.
- if (!sameOrigin(requestCurrentURL(request), locationURL)) {
- // https://fetch.spec.whatwg.org/#cors-non-wildcard-request-header-name
- request.headersList.delete('authorization', true)
- // https://fetch.spec.whatwg.org/#authentication-entries
- request.headersList.delete('proxy-authorization', true)
+var identity = __nccwpck_require__(1127);
+var stringify = __nccwpck_require__(2148);
+var stringifyComment = __nccwpck_require__(9799);
- // "Cookie" and "Host" are forbidden request-headers, which undici doesn't implement.
- request.headersList.delete('cookie', true)
- request.headersList.delete('host', true)
- }
+function stringifyDocument(doc, options) {
+ const lines = [];
+ let hasDirectives = options.directives === true;
+ if (options.directives !== false && doc.directives) {
+ const dir = doc.directives.toString(doc);
+ if (dir) {
+ lines.push(dir);
+ hasDirectives = true;
+ }
+ else if (doc.directives.docStart)
+ hasDirectives = true;
+ }
+ if (hasDirectives)
+ lines.push('---');
+ const ctx = stringify.createStringifyContext(doc, options);
+ const { commentString } = ctx.options;
+ if (doc.commentBefore) {
+ if (lines.length !== 1)
+ lines.unshift('');
+ const cs = commentString(doc.commentBefore);
+ lines.unshift(stringifyComment.indentComment(cs, ''));
+ }
+ let chompKeep = false;
+ let contentComment = null;
+ if (doc.contents) {
+ if (identity.isNode(doc.contents)) {
+ if (doc.contents.spaceBefore && hasDirectives)
+ lines.push('');
+ if (doc.contents.commentBefore) {
+ const cs = commentString(doc.contents.commentBefore);
+ lines.push(stringifyComment.indentComment(cs, ''));
+ }
+ // top-level block scalars need to be indented if followed by a comment
+ ctx.forceBlockIndent = !!doc.comment;
+ contentComment = doc.contents.comment;
+ }
+ const onChompKeep = contentComment ? undefined : () => (chompKeep = true);
+ let body = stringify.stringify(doc.contents, ctx, () => (contentComment = null), onChompKeep);
+ if (contentComment)
+ body += stringifyComment.lineComment(body, '', commentString(contentComment));
+ if ((body[0] === '|' || body[0] === '>') &&
+ lines[lines.length - 1] === '---') {
+ // Top-level block scalars with a preceding doc marker ought to use the
+ // same line for their header.
+ lines[lines.length - 1] = `--- ${body}`;
+ }
+ else
+ lines.push(body);
+ }
+ else {
+ lines.push(stringify.stringify(doc.contents, ctx));
+ }
+ if (doc.directives?.docEnd) {
+ if (doc.comment) {
+ const cs = commentString(doc.comment);
+ if (cs.includes('\n')) {
+ lines.push('...');
+ lines.push(stringifyComment.indentComment(cs, ''));
+ }
+ else {
+ lines.push(`... ${cs}`);
+ }
+ }
+ else {
+ lines.push('...');
+ }
+ }
+ else {
+ let dc = doc.comment;
+ if (dc && chompKeep)
+ dc = dc.replace(/^\n+/, '');
+ if (dc) {
+ if ((!chompKeep || contentComment) && lines[lines.length - 1] !== '')
+ lines.push('');
+ lines.push(stringifyComment.indentComment(commentString(dc), ''));
+ }
+ }
+ return lines.join('\n') + '\n';
+}
- // 14. If request’s body is non-null, then set request’s body to the first return
- // value of safely extracting request’s body’s source.
- if (request.body != null) {
- assert(request.body.source != null)
- request.body = safelyExtractBody(request.body.source)[0]
- }
+exports.stringifyDocument = stringifyDocument;
- // 15. Let timingInfo be fetchParams’s timing info.
- const timingInfo = fetchParams.timingInfo
- // 16. Set timingInfo’s redirect end time and post-redirect start time to the
- // coarsened shared current time given fetchParams’s cross-origin isolated
- // capability.
- timingInfo.redirectEndTime = timingInfo.postRedirectStartTime =
- coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability)
+/***/ }),
- // 17. If timingInfo’s redirect start time is 0, then set timingInfo’s
- // redirect start time to timingInfo’s start time.
- if (timingInfo.redirectStartTime === 0) {
- timingInfo.redirectStartTime = timingInfo.startTime
- }
+/***/ 8689:
+/***/ ((__unused_webpack_module, exports) => {
- // 18. Append locationURL to request’s URL list.
- request.urlList.push(locationURL)
- // 19. Invoke set request’s referrer policy on redirect on request and
- // actualResponse.
- setRequestReferrerPolicyOnRedirect(request, actualResponse)
- // 20. Return the result of running main fetch given fetchParams and true.
- return mainFetch(fetchParams, true)
+function stringifyNumber({ format, minFractionDigits, tag, value }) {
+ if (typeof value === 'bigint')
+ return String(value);
+ const num = typeof value === 'number' ? value : Number(value);
+ if (!isFinite(num))
+ return isNaN(num) ? '.nan' : num < 0 ? '-.inf' : '.inf';
+ let n = Object.is(value, -0) ? '-0' : JSON.stringify(value);
+ if (!format &&
+ minFractionDigits &&
+ (!tag || tag === 'tag:yaml.org,2002:float') &&
+ /^-?\d/.test(n) &&
+ !n.includes('e')) {
+ let i = n.indexOf('.');
+ if (i < 0) {
+ i = n.length;
+ n += '.';
+ }
+ let d = minFractionDigits - (n.length - i - 1);
+ while (d-- > 0)
+ n += '0';
+ }
+ return n;
}
-// https://fetch.spec.whatwg.org/#http-network-or-cache-fetch
-async function httpNetworkOrCacheFetch (
- fetchParams,
- isAuthenticationFetch = false,
- isNewConnectionFetch = false
-) {
- // 1. Let request be fetchParams’s request.
- const request = fetchParams.request
+exports.stringifyNumber = stringifyNumber;
- // 2. Let httpFetchParams be null.
- let httpFetchParams = null
- // 3. Let httpRequest be null.
- let httpRequest = null
+/***/ }),
- // 4. Let response be null.
- let response = null
+/***/ 9748:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 5. Let storedResponse be null.
- // TODO: cache
- // 6. Let httpCache be null.
- const httpCache = null
- // 7. Let the revalidatingFlag be unset.
- const revalidatingFlag = false
-
- // 8. Run these steps, but abort when the ongoing fetch is terminated:
-
- // 1. If request’s window is "no-window" and request’s redirect mode is
- // "error", then set httpFetchParams to fetchParams and httpRequest to
- // request.
- if (request.window === 'no-window' && request.redirect === 'error') {
- httpFetchParams = fetchParams
- httpRequest = request
- } else {
- // Otherwise:
-
- // 1. Set httpRequest to a clone of request.
- httpRequest = cloneRequest(request)
-
- // 2. Set httpFetchParams to a copy of fetchParams.
- httpFetchParams = { ...fetchParams }
-
- // 3. Set httpFetchParams’s request to httpRequest.
- httpFetchParams.request = httpRequest
- }
-
- // 3. Let includeCredentials be true if one of
- const includeCredentials =
- request.credentials === 'include' ||
- (request.credentials === 'same-origin' &&
- request.responseTainting === 'basic')
-
- // 4. Let contentLength be httpRequest’s body’s length, if httpRequest’s
- // body is non-null; otherwise null.
- const contentLength = httpRequest.body ? httpRequest.body.length : null
-
- // 5. Let contentLengthHeaderValue be null.
- let contentLengthHeaderValue = null
-
- // 6. If httpRequest’s body is null and httpRequest’s method is `POST` or
- // `PUT`, then set contentLengthHeaderValue to `0`.
- if (
- httpRequest.body == null &&
- ['POST', 'PUT'].includes(httpRequest.method)
- ) {
- contentLengthHeaderValue = '0'
- }
-
- // 7. If contentLength is non-null, then set contentLengthHeaderValue to
- // contentLength, serialized and isomorphic encoded.
- if (contentLength != null) {
- contentLengthHeaderValue = isomorphicEncode(`${contentLength}`)
- }
-
- // 8. If contentLengthHeaderValue is non-null, then append
- // `Content-Length`/contentLengthHeaderValue to httpRequest’s header
- // list.
- if (contentLengthHeaderValue != null) {
- httpRequest.headersList.append('content-length', contentLengthHeaderValue, true)
- }
-
- // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`,
- // contentLengthHeaderValue) to httpRequest’s header list.
-
- // 10. If contentLength is non-null and httpRequest’s keepalive is true,
- // then:
- if (contentLength != null && httpRequest.keepalive) {
- // NOTE: keepalive is a noop outside of browser context.
- }
-
- // 11. If httpRequest’s referrer is a URL, then append
- // `Referer`/httpRequest’s referrer, serialized and isomorphic encoded,
- // to httpRequest’s header list.
- if (httpRequest.referrer instanceof URL) {
- httpRequest.headersList.append('referer', isomorphicEncode(httpRequest.referrer.href), true)
- }
-
- // 12. Append a request `Origin` header for httpRequest.
- appendRequestOriginHeader(httpRequest)
-
- // 13. Append the Fetch metadata headers for httpRequest. [FETCH-METADATA]
- appendFetchMetadata(httpRequest)
-
- // 14. If httpRequest’s header list does not contain `User-Agent`, then
- // user agents should append `User-Agent`/default `User-Agent` value to
- // httpRequest’s header list.
- if (!httpRequest.headersList.contains('user-agent', true)) {
- httpRequest.headersList.append('user-agent', defaultUserAgent)
- }
-
- // 15. If httpRequest’s cache mode is "default" and httpRequest’s header
- // list contains `If-Modified-Since`, `If-None-Match`,
- // `If-Unmodified-Since`, `If-Match`, or `If-Range`, then set
- // httpRequest’s cache mode to "no-store".
- if (
- httpRequest.cache === 'default' &&
- (httpRequest.headersList.contains('if-modified-since', true) ||
- httpRequest.headersList.contains('if-none-match', true) ||
- httpRequest.headersList.contains('if-unmodified-since', true) ||
- httpRequest.headersList.contains('if-match', true) ||
- httpRequest.headersList.contains('if-range', true))
- ) {
- httpRequest.cache = 'no-store'
- }
-
- // 16. If httpRequest’s cache mode is "no-cache", httpRequest’s prevent
- // no-cache cache-control header modification flag is unset, and
- // httpRequest’s header list does not contain `Cache-Control`, then append
- // `Cache-Control`/`max-age=0` to httpRequest’s header list.
- if (
- httpRequest.cache === 'no-cache' &&
- !httpRequest.preventNoCacheCacheControlHeaderModification &&
- !httpRequest.headersList.contains('cache-control', true)
- ) {
- httpRequest.headersList.append('cache-control', 'max-age=0', true)
- }
+var identity = __nccwpck_require__(1127);
+var Scalar = __nccwpck_require__(3301);
+var stringify = __nccwpck_require__(2148);
+var stringifyComment = __nccwpck_require__(9799);
- // 17. If httpRequest’s cache mode is "no-store" or "reload", then:
- if (httpRequest.cache === 'no-store' || httpRequest.cache === 'reload') {
- // 1. If httpRequest’s header list does not contain `Pragma`, then append
- // `Pragma`/`no-cache` to httpRequest’s header list.
- if (!httpRequest.headersList.contains('pragma', true)) {
- httpRequest.headersList.append('pragma', 'no-cache', true)
+function stringifyPair({ key, value }, ctx, onComment, onChompKeep) {
+ const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx;
+ let keyComment = (identity.isNode(key) && key.comment) || null;
+ if (simpleKeys) {
+ if (keyComment) {
+ throw new Error('With simple keys, key nodes cannot have comments');
+ }
+ if (identity.isCollection(key) || (!identity.isNode(key) && typeof key === 'object')) {
+ const msg = 'With simple keys, collection cannot be used as a key value';
+ throw new Error(msg);
+ }
}
-
- // 2. If httpRequest’s header list does not contain `Cache-Control`,
- // then append `Cache-Control`/`no-cache` to httpRequest’s header list.
- if (!httpRequest.headersList.contains('cache-control', true)) {
- httpRequest.headersList.append('cache-control', 'no-cache', true)
+ let explicitKey = !simpleKeys &&
+ (!key ||
+ (keyComment && value == null && !ctx.inFlow) ||
+ identity.isCollection(key) ||
+ (identity.isScalar(key)
+ ? key.type === Scalar.Scalar.BLOCK_FOLDED || key.type === Scalar.Scalar.BLOCK_LITERAL
+ : typeof key === 'object'));
+ ctx = Object.assign({}, ctx, {
+ allNullValues: false,
+ implicitKey: !explicitKey && (simpleKeys || !allNullValues),
+ indent: indent + indentStep
+ });
+ let keyCommentDone = false;
+ let chompKeep = false;
+ let str = stringify.stringify(key, ctx, () => (keyCommentDone = true), () => (chompKeep = true));
+ if (!explicitKey && !ctx.inFlow && str.length > 1024) {
+ if (simpleKeys)
+ throw new Error('With simple keys, single line scalar must not span more than 1024 characters');
+ explicitKey = true;
}
- }
-
- // 18. If httpRequest’s header list contains `Range`, then append
- // `Accept-Encoding`/`identity` to httpRequest’s header list.
- if (httpRequest.headersList.contains('range', true)) {
- httpRequest.headersList.append('accept-encoding', 'identity', true)
- }
-
- // 19. Modify httpRequest’s header list per HTTP. Do not append a given
- // header if httpRequest’s header list contains that header’s name.
- // TODO: https://github.com/whatwg/fetch/issues/1285#issuecomment-896560129
- if (!httpRequest.headersList.contains('accept-encoding', true)) {
- if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) {
- httpRequest.headersList.append('accept-encoding', 'br, gzip, deflate', true)
- } else {
- httpRequest.headersList.append('accept-encoding', 'gzip, deflate', true)
+ if (ctx.inFlow) {
+ if (allNullValues || value == null) {
+ if (keyCommentDone && onComment)
+ onComment();
+ return str === '' ? '?' : explicitKey ? `? ${str}` : str;
+ }
}
- }
-
- httpRequest.headersList.delete('host', true)
-
- // 20. If includeCredentials is true, then:
- if (includeCredentials) {
- // 1. If the user agent is not configured to block cookies for httpRequest
- // (see section 7 of [COOKIES]), then:
- // TODO: credentials
- // 2. If httpRequest’s header list does not contain `Authorization`, then:
- // TODO: credentials
- }
-
- // 21. If there’s a proxy-authentication entry, use it as appropriate.
- // TODO: proxy-authentication
-
- // 22. Set httpCache to the result of determining the HTTP cache
- // partition, given httpRequest.
- // TODO: cache
-
- // 23. If httpCache is null, then set httpRequest’s cache mode to
- // "no-store".
- if (httpCache == null) {
- httpRequest.cache = 'no-store'
- }
-
- // 24. If httpRequest’s cache mode is neither "no-store" nor "reload",
- // then:
- if (httpRequest.cache !== 'no-store' && httpRequest.cache !== 'reload') {
- // TODO: cache
- }
-
- // 9. If aborted, then return the appropriate network error for fetchParams.
- // TODO
-
- // 10. If response is null, then:
- if (response == null) {
- // 1. If httpRequest’s cache mode is "only-if-cached", then return a
- // network error.
- if (httpRequest.cache === 'only-if-cached') {
- return makeNetworkError('only if cached')
+ else if ((allNullValues && !simpleKeys) || (value == null && explicitKey)) {
+ str = `? ${str}`;
+ if (keyComment && !keyCommentDone) {
+ str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));
+ }
+ else if (chompKeep && onChompKeep)
+ onChompKeep();
+ return str;
}
-
- // 2. Let forwardResponse be the result of running HTTP-network fetch
- // given httpFetchParams, includeCredentials, and isNewConnectionFetch.
- const forwardResponse = await httpNetworkFetch(
- httpFetchParams,
- includeCredentials,
- isNewConnectionFetch
- )
-
- // 3. If httpRequest’s method is unsafe and forwardResponse’s status is
- // in the range 200 to 399, inclusive, invalidate appropriate stored
- // responses in httpCache, as per the "Invalidation" chapter of HTTP
- // Caching, and set storedResponse to null. [HTTP-CACHING]
- if (
- !safeMethodsSet.has(httpRequest.method) &&
- forwardResponse.status >= 200 &&
- forwardResponse.status <= 399
- ) {
- // TODO: cache
+ if (keyCommentDone)
+ keyComment = null;
+ if (explicitKey) {
+ if (keyComment)
+ str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));
+ str = `? ${str}\n${indent}:`;
}
-
- // 4. If the revalidatingFlag is set and forwardResponse’s status is 304,
- // then:
- if (revalidatingFlag && forwardResponse.status === 304) {
- // TODO: cache
+ else {
+ str = `${str}:`;
+ if (keyComment)
+ str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));
}
-
- // 5. If response is null, then:
- if (response == null) {
- // 1. Set response to forwardResponse.
- response = forwardResponse
-
- // 2. Store httpRequest and forwardResponse in httpCache, as per the
- // "Storing Responses in Caches" chapter of HTTP Caching. [HTTP-CACHING]
- // TODO: cache
+ let vsb, vcb, valueComment;
+ if (identity.isNode(value)) {
+ vsb = !!value.spaceBefore;
+ vcb = value.commentBefore;
+ valueComment = value.comment;
}
- }
-
- // 11. Set response’s URL list to a clone of httpRequest’s URL list.
- response.urlList = [...httpRequest.urlList]
-
- // 12. If httpRequest’s header list contains `Range`, then set response’s
- // range-requested flag.
- if (httpRequest.headersList.contains('range', true)) {
- response.rangeRequested = true
- }
-
- // 13. Set response’s request-includes-credentials to includeCredentials.
- response.requestIncludesCredentials = includeCredentials
-
- // 14. If response’s status is 401, httpRequest’s response tainting is not
- // "cors", includeCredentials is true, and request’s window is an environment
- // settings object, then:
- // TODO
-
- // 15. If response’s status is 407, then:
- if (response.status === 407) {
- // 1. If request’s window is "no-window", then return a network error.
- if (request.window === 'no-window') {
- return makeNetworkError()
+ else {
+ vsb = false;
+ vcb = null;
+ valueComment = null;
+ if (value && typeof value === 'object')
+ value = doc.createNode(value);
}
-
- // 2. ???
-
- // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams.
- if (isCancelled(fetchParams)) {
- return makeAppropriateNetworkError(fetchParams)
+ ctx.implicitKey = false;
+ if (!explicitKey && !keyComment && identity.isScalar(value))
+ ctx.indentAtStart = str.length + 1;
+ chompKeep = false;
+ if (!indentSeq &&
+ indentStep.length >= 2 &&
+ !ctx.inFlow &&
+ !explicitKey &&
+ identity.isSeq(value) &&
+ !value.flow &&
+ !value.tag &&
+ !value.anchor) {
+ // If indentSeq === false, consider '- ' as part of indentation where possible
+ ctx.indent = ctx.indent.substring(2);
}
-
- // 4. Prompt the end user as appropriate in request’s window and store
- // the result as a proxy-authentication entry. [HTTP-AUTH]
- // TODO: Invoke some kind of callback?
-
- // 5. Set response to the result of running HTTP-network-or-cache fetch given
- // fetchParams.
- // TODO
- return makeNetworkError('proxy authentication required')
- }
-
- // 16. If all of the following are true
- if (
- // response’s status is 421
- response.status === 421 &&
- // isNewConnectionFetch is false
- !isNewConnectionFetch &&
- // request’s body is null, or request’s body is non-null and request’s body’s source is non-null
- (request.body == null || request.body.source != null)
- ) {
- // then:
-
- // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
- if (isCancelled(fetchParams)) {
- return makeAppropriateNetworkError(fetchParams)
+ let valueCommentDone = false;
+ const valueStr = stringify.stringify(value, ctx, () => (valueCommentDone = true), () => (chompKeep = true));
+ let ws = ' ';
+ if (keyComment || vsb || vcb) {
+ ws = vsb ? '\n' : '';
+ if (vcb) {
+ const cs = commentString(vcb);
+ ws += `\n${stringifyComment.indentComment(cs, ctx.indent)}`;
+ }
+ if (valueStr === '' && !ctx.inFlow) {
+ if (ws === '\n' && valueComment)
+ ws = '\n\n';
+ }
+ else {
+ ws += `\n${ctx.indent}`;
+ }
}
-
- // 2. Set response to the result of running HTTP-network-or-cache
- // fetch given fetchParams, isAuthenticationFetch, and true.
-
- // TODO (spec): The spec doesn't specify this but we need to cancel
- // the active response before we can start a new one.
- // https://github.com/whatwg/fetch/issues/1293
- fetchParams.controller.connection.destroy()
-
- response = await httpNetworkOrCacheFetch(
- fetchParams,
- isAuthenticationFetch,
- true
- )
- }
-
- // 17. If isAuthenticationFetch is true, then create an authentication entry
- if (isAuthenticationFetch) {
- // TODO
- }
-
- // 18. Return response.
- return response
-}
-
-// https://fetch.spec.whatwg.org/#http-network-fetch
-async function httpNetworkFetch (
- fetchParams,
- includeCredentials = false,
- forceNewConnection = false
-) {
- assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed)
-
- fetchParams.controller.connection = {
- abort: null,
- destroyed: false,
- destroy (err, abort = true) {
- if (!this.destroyed) {
- this.destroyed = true
- if (abort) {
- this.abort?.(err ?? new DOMException('The operation was aborted.', 'AbortError'))
+ else if (!explicitKey && identity.isCollection(value)) {
+ const vs0 = valueStr[0];
+ const nl0 = valueStr.indexOf('\n');
+ const hasNewline = nl0 !== -1;
+ const flow = ctx.inFlow ?? value.flow ?? value.items.length === 0;
+ if (hasNewline || !flow) {
+ let hasPropsLine = false;
+ if (hasNewline && (vs0 === '&' || vs0 === '!')) {
+ let sp0 = valueStr.indexOf(' ');
+ if (vs0 === '&' &&
+ sp0 !== -1 &&
+ sp0 < nl0 &&
+ valueStr[sp0 + 1] === '!') {
+ sp0 = valueStr.indexOf(' ', sp0 + 1);
+ }
+ if (sp0 === -1 || nl0 < sp0)
+ hasPropsLine = true;
+ }
+ if (!hasPropsLine)
+ ws = `\n${ctx.indent}`;
}
- }
}
- }
-
- // 1. Let request be fetchParams’s request.
- const request = fetchParams.request
-
- // 2. Let response be null.
- let response = null
-
- // 3. Let timingInfo be fetchParams’s timing info.
- const timingInfo = fetchParams.timingInfo
-
- // 4. Let httpCache be the result of determining the HTTP cache partition,
- // given request.
- // TODO: cache
- const httpCache = null
-
- // 5. If httpCache is null, then set request’s cache mode to "no-store".
- if (httpCache == null) {
- request.cache = 'no-store'
- }
-
- // 6. Let networkPartitionKey be the result of determining the network
- // partition key given request.
- // TODO
-
- // 7. Let newConnection be "yes" if forceNewConnection is true; otherwise
- // "no".
- const newConnection = forceNewConnection ? 'yes' : 'no' // eslint-disable-line no-unused-vars
-
- // 8. Switch on request’s mode:
- if (request.mode === 'websocket') {
- // Let connection be the result of obtaining a WebSocket connection,
- // given request’s current URL.
- // TODO
- } else {
- // Let connection be the result of obtaining a connection, given
- // networkPartitionKey, request’s current URL’s origin,
- // includeCredentials, and forceNewConnection.
- // TODO
- }
-
- // 9. Run these steps, but abort when the ongoing fetch is terminated:
+ else if (valueStr === '' || valueStr[0] === '\n') {
+ ws = '';
+ }
+ str += ws + valueStr;
+ if (ctx.inFlow) {
+ if (valueCommentDone && onComment)
+ onComment();
+ }
+ else if (valueComment && !valueCommentDone) {
+ str += stringifyComment.lineComment(str, ctx.indent, commentString(valueComment));
+ }
+ else if (chompKeep && onChompKeep) {
+ onChompKeep();
+ }
+ return str;
+}
- // 1. If connection is failure, then return a network error.
+exports.stringifyPair = stringifyPair;
- // 2. Set timingInfo’s final connection timing info to the result of
- // calling clamp and coarsen connection timing info with connection’s
- // timing info, timingInfo’s post-redirect start time, and fetchParams’s
- // cross-origin isolated capability.
- // 3. If connection is not an HTTP/2 connection, request’s body is non-null,
- // and request’s body’s source is null, then append (`Transfer-Encoding`,
- // `chunked`) to request’s header list.
+/***/ }),
- // 4. Set timingInfo’s final network-request start time to the coarsened
- // shared current time given fetchParams’s cross-origin isolated
- // capability.
+/***/ 3069:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 5. Set response to the result of making an HTTP request over connection
- // using request with the following caveats:
- // - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS]
- // [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH]
- // - If request’s body is non-null, and request’s body’s source is null,
- // then the user agent may have a buffer of up to 64 kibibytes and store
- // a part of request’s body in that buffer. If the user agent reads from
- // request’s body beyond that buffer’s size and the user agent needs to
- // resend request, then instead return a network error.
+var Scalar = __nccwpck_require__(3301);
+var foldFlowLines = __nccwpck_require__(4475);
- // - Set timingInfo’s final network-response start time to the coarsened
- // shared current time given fetchParams’s cross-origin isolated capability,
- // immediately after the user agent’s HTTP parser receives the first byte
- // of the response (e.g., frame header bytes for HTTP/2 or response status
- // line for HTTP/1.x).
-
- // - Wait until all the headers are transmitted.
-
- // - Any responses whose status is in the range 100 to 199, inclusive,
- // and is not 101, are to be ignored, except for the purposes of setting
- // timingInfo’s final network-response start time above.
-
- // - If request’s header list contains `Transfer-Encoding`/`chunked` and
- // response is transferred via HTTP/1.0 or older, then return a network
- // error.
-
- // - If the HTTP request results in a TLS client certificate dialog, then:
-
- // 1. If request’s window is an environment settings object, make the
- // dialog available in request’s window.
-
- // 2. Otherwise, return a network error.
-
- // To transmit request’s body body, run these steps:
- let requestBody = null
- // 1. If body is null and fetchParams’s process request end-of-body is
- // non-null, then queue a fetch task given fetchParams’s process request
- // end-of-body and fetchParams’s task destination.
- if (request.body == null && fetchParams.processRequestEndOfBody) {
- queueMicrotask(() => fetchParams.processRequestEndOfBody())
- } else if (request.body != null) {
- // 2. Otherwise, if body is non-null:
-
- // 1. Let processBodyChunk given bytes be these steps:
- const processBodyChunk = async function * (bytes) {
- // 1. If the ongoing fetch is terminated, then abort these steps.
- if (isCancelled(fetchParams)) {
- return
- }
-
- // 2. Run this step in parallel: transmit bytes.
- yield bytes
-
- // 3. If fetchParams’s process request body is non-null, then run
- // fetchParams’s process request body given bytes’s length.
- fetchParams.processRequestBodyChunkLength?.(bytes.byteLength)
+const getFoldOptions = (ctx, isBlock) => ({
+ indentAtStart: isBlock ? ctx.indent.length : ctx.indentAtStart,
+ lineWidth: ctx.options.lineWidth,
+ minContentWidth: ctx.options.minContentWidth
+});
+// Also checks for lines starting with %, as parsing the output as YAML 1.1 will
+// presume that's starting a new document.
+const containsDocumentMarker = (str) => /^(%|---|\.\.\.)/m.test(str);
+function lineLengthOverLimit(str, lineWidth, indentLength) {
+ if (!lineWidth || lineWidth < 0)
+ return false;
+ const limit = lineWidth - indentLength;
+ const strLen = str.length;
+ if (strLen <= limit)
+ return false;
+ for (let i = 0, start = 0; i < strLen; ++i) {
+ if (str[i] === '\n') {
+ if (i - start > limit)
+ return true;
+ start = i + 1;
+ if (strLen - start <= limit)
+ return false;
+ }
}
-
- // 2. Let processEndOfBody be these steps:
- const processEndOfBody = () => {
- // 1. If fetchParams is canceled, then abort these steps.
- if (isCancelled(fetchParams)) {
- return
- }
-
- // 2. If fetchParams’s process request end-of-body is non-null,
- // then run fetchParams’s process request end-of-body.
- if (fetchParams.processRequestEndOfBody) {
- fetchParams.processRequestEndOfBody()
- }
+ return true;
+}
+function doubleQuotedString(value, ctx) {
+ const json = JSON.stringify(value);
+ if (ctx.options.doubleQuotedAsJSON)
+ return json;
+ const { implicitKey } = ctx;
+ const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength;
+ const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : '');
+ let str = '';
+ let start = 0;
+ for (let i = 0, ch = json[i]; ch; ch = json[++i]) {
+ if (ch === ' ' && json[i + 1] === '\\' && json[i + 2] === 'n') {
+ // space before newline needs to be escaped to not be folded
+ str += json.slice(start, i) + '\\ ';
+ i += 1;
+ start = i;
+ ch = '\\';
+ }
+ if (ch === '\\')
+ switch (json[i + 1]) {
+ case 'u':
+ {
+ str += json.slice(start, i);
+ const code = json.substr(i + 2, 4);
+ switch (code) {
+ case '0000':
+ str += '\\0';
+ break;
+ case '0007':
+ str += '\\a';
+ break;
+ case '000b':
+ str += '\\v';
+ break;
+ case '001b':
+ str += '\\e';
+ break;
+ case '0085':
+ str += '\\N';
+ break;
+ case '00a0':
+ str += '\\_';
+ break;
+ case '2028':
+ str += '\\L';
+ break;
+ case '2029':
+ str += '\\P';
+ break;
+ default:
+ if (code.substr(0, 2) === '00')
+ str += '\\x' + code.substr(2);
+ else
+ str += json.substr(i, 6);
+ }
+ i += 5;
+ start = i + 1;
+ }
+ break;
+ case 'n':
+ if (implicitKey ||
+ json[i + 2] === '"' ||
+ json.length < minMultiLineLength) {
+ i += 1;
+ }
+ else {
+ // folding will eat first newline
+ str += json.slice(start, i) + '\n\n';
+ while (json[i + 2] === '\\' &&
+ json[i + 3] === 'n' &&
+ json[i + 4] !== '"') {
+ str += '\n';
+ i += 2;
+ }
+ str += indent;
+ // space after newline needs to be escaped to not be folded
+ if (json[i + 2] === ' ')
+ str += '\\';
+ i += 1;
+ start = i + 1;
+ }
+ break;
+ default:
+ i += 1;
+ }
}
-
- // 3. Let processBodyError given e be these steps:
- const processBodyError = (e) => {
- // 1. If fetchParams is canceled, then abort these steps.
- if (isCancelled(fetchParams)) {
- return
- }
-
- // 2. If e is an "AbortError" DOMException, then abort fetchParams’s controller.
- if (e.name === 'AbortError') {
- fetchParams.controller.abort()
- } else {
- fetchParams.controller.terminate(e)
- }
+ str = start ? str + json.slice(start) : json;
+ return implicitKey
+ ? str
+ : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_QUOTED, getFoldOptions(ctx, false));
+}
+function singleQuotedString(value, ctx) {
+ if (ctx.options.singleQuote === false ||
+ (ctx.implicitKey && value.includes('\n')) ||
+ /[ \t]\n|\n[ \t]/.test(value) // single quoted string can't have leading or trailing whitespace around newline
+ )
+ return doubleQuotedString(value, ctx);
+ const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : '');
+ const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$&\n${indent}`) + "'";
+ return ctx.implicitKey
+ ? res
+ : foldFlowLines.foldFlowLines(res, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false));
+}
+function quotedString(value, ctx) {
+ const { singleQuote } = ctx.options;
+ let qs;
+ if (singleQuote === false)
+ qs = doubleQuotedString;
+ else {
+ const hasDouble = value.includes('"');
+ const hasSingle = value.includes("'");
+ if (hasDouble && !hasSingle)
+ qs = singleQuotedString;
+ else if (hasSingle && !hasDouble)
+ qs = doubleQuotedString;
+ else
+ qs = singleQuote ? singleQuotedString : doubleQuotedString;
}
-
- // 4. Incrementally read request’s body given processBodyChunk, processEndOfBody,
- // processBodyError, and fetchParams’s task destination.
- requestBody = (async function * () {
- try {
- for await (const bytes of request.body.stream) {
- yield * processBodyChunk(bytes)
+ return qs(value, ctx);
+}
+// The negative lookbehind avoids a polynomial search,
+// but isn't supported yet on Safari: https://caniuse.com/js-regexp-lookbehind
+let blockEndNewlines;
+try {
+ blockEndNewlines = new RegExp('(^|(?\n';
+ // determine chomping from whitespace at value end
+ let chomp;
+ let endStart;
+ for (endStart = value.length; endStart > 0; --endStart) {
+ const ch = value[endStart - 1];
+ if (ch !== '\n' && ch !== '\t' && ch !== ' ')
+ break;
+ }
+ let end = value.substring(endStart);
+ const endNlPos = end.indexOf('\n');
+ if (endNlPos === -1) {
+ chomp = '-'; // strip
+ }
+ else if (value === end || endNlPos !== end.length - 1) {
+ chomp = '+'; // keep
+ if (onChompKeep)
+ onChompKeep();
+ }
+ else {
+ chomp = ''; // clip
+ }
+ if (end) {
+ value = value.slice(0, -end.length);
+ if (end[end.length - 1] === '\n')
+ end = end.slice(0, -1);
+ end = end.replace(blockEndNewlines, `$&${indent}`);
+ }
+ // determine indent indicator from whitespace at value start
+ let startWithSpace = false;
+ let startEnd;
+ let startNlPos = -1;
+ for (startEnd = 0; startEnd < value.length; ++startEnd) {
+ const ch = value[startEnd];
+ if (ch === ' ')
+ startWithSpace = true;
+ else if (ch === '\n')
+ startNlPos = startEnd;
+ else
+ break;
+ }
+ let start = value.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd);
+ if (start) {
+ value = value.substring(start.length);
+ start = start.replace(/\n+/g, `$&${indent}`);
+ }
+ const indentSize = indent ? '2' : '1'; // root is at -1
+ // Leading | or > is added later
+ let header = (startWithSpace ? indentSize : '') + chomp;
+ if (comment) {
+ header += ' ' + commentString(comment.replace(/ ?[\r\n]+/g, ' '));
+ if (onComment)
+ onComment();
+ }
+ if (!literal) {
+ const foldedValue = value
+ .replace(/\n+/g, '\n$&')
+ .replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, '$1$2') // more-indented lines aren't folded
+ // ^ more-ind. ^ empty ^ capture next empty lines only at end of indent
+ .replace(/\n+/g, `$&${indent}`);
+ let literalFallback = false;
+ const foldOptions = getFoldOptions(ctx, true);
+ if (blockQuote !== 'folded' && type !== Scalar.Scalar.BLOCK_FOLDED) {
+ foldOptions.onOverflow = () => {
+ literalFallback = true;
+ };
}
- processEndOfBody()
- } catch (err) {
- processBodyError(err)
- }
- })()
- }
-
- try {
- // socket is only provided for websockets
- const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody })
-
- if (socket) {
- response = makeResponse({ status, statusText, headersList, socket })
- } else {
- const iterator = body[Symbol.asyncIterator]()
- fetchParams.controller.next = () => iterator.next()
-
- response = makeResponse({ status, statusText, headersList })
+ const body = foldFlowLines.foldFlowLines(`${start}${foldedValue}${end}`, indent, foldFlowLines.FOLD_BLOCK, foldOptions);
+ if (!literalFallback)
+ return `>${header}\n${indent}${body}`;
}
- } catch (err) {
- // 10. If aborted, then:
- if (err.name === 'AbortError') {
- // 1. If connection uses HTTP/2, then transmit an RST_STREAM frame.
- fetchParams.controller.connection.destroy()
-
- // 2. Return the appropriate network error for fetchParams.
- return makeAppropriateNetworkError(fetchParams, err)
+ value = value.replace(/\n+/g, `$&${indent}`);
+ return `|${header}\n${indent}${start}${value}${end}`;
+}
+function plainString(item, ctx, onComment, onChompKeep) {
+ const { type, value } = item;
+ const { actualString, implicitKey, indent, indentStep, inFlow } = ctx;
+ if ((implicitKey && value.includes('\n')) ||
+ (inFlow && /[[\]{},]/.test(value))) {
+ return quotedString(value, ctx);
}
-
- return makeNetworkError(err)
- }
-
- // 11. Let pullAlgorithm be an action that resumes the ongoing fetch
- // if it is suspended.
- const pullAlgorithm = async () => {
- await fetchParams.controller.resume()
- }
-
- // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s
- // controller with reason, given reason.
- const cancelAlgorithm = (reason) => {
- // If the aborted fetch was already terminated, then we do not
- // need to do anything.
- if (!isCancelled(fetchParams)) {
- fetchParams.controller.abort(reason)
+ if (/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) {
+ // not allowed:
+ // - '-' or '?'
+ // - start with an indicator character (except [?:-]) or /[?-] /
+ // - '\n ', ': ' or ' \n' anywhere
+ // - '#' not preceded by a non-space char
+ // - end with ' ' or ':'
+ return implicitKey || inFlow || !value.includes('\n')
+ ? quotedString(value, ctx)
+ : blockString(item, ctx, onComment, onChompKeep);
}
- }
-
- // 13. Let highWaterMark be a non-negative, non-NaN number, chosen by
- // the user agent.
- // TODO
-
- // 14. Let sizeAlgorithm be an algorithm that accepts a chunk object
- // and returns a non-negative, non-NaN, non-infinite number, chosen by the user agent.
- // TODO
-
- // 15. Let stream be a new ReadableStream.
- // 16. Set up stream with byte reading support with pullAlgorithm set to pullAlgorithm,
- // cancelAlgorithm set to cancelAlgorithm.
- const stream = new ReadableStream(
- {
- async start (controller) {
- fetchParams.controller.controller = controller
- },
- async pull (controller) {
- await pullAlgorithm(controller)
- },
- async cancel (reason) {
- await cancelAlgorithm(reason)
- },
- type: 'bytes'
+ if (!implicitKey &&
+ !inFlow &&
+ type !== Scalar.Scalar.PLAIN &&
+ value.includes('\n')) {
+ // Where allowed & type not set explicitly, prefer block style for multiline strings
+ return blockString(item, ctx, onComment, onChompKeep);
}
- )
-
- // 17. Run these steps, but abort when the ongoing fetch is terminated:
-
- // 1. Set response’s body to a new body whose stream is stream.
- response.body = { stream, source: null, length: null }
+ if (containsDocumentMarker(value)) {
+ if (indent === '') {
+ ctx.forceBlockIndent = true;
+ return blockString(item, ctx, onComment, onChompKeep);
+ }
+ else if (implicitKey && indent === indentStep) {
+ return quotedString(value, ctx);
+ }
+ }
+ const str = value.replace(/\n+/g, `$&\n${indent}`);
+ // Verify that output will be parsed as a string, as e.g. plain numbers and
+ // booleans get parsed with those types in v1.2 (e.g. '42', 'true' & '0.9e-3'),
+ // and others in v1.1.
+ if (actualString) {
+ const test = (tag) => tag.default && tag.tag !== 'tag:yaml.org,2002:str' && tag.test?.test(str);
+ const { compat, tags } = ctx.doc.schema;
+ if (tags.some(test) || compat?.some(test))
+ return quotedString(value, ctx);
+ }
+ return implicitKey
+ ? str
+ : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false));
+}
+function stringifyString(item, ctx, onComment, onChompKeep) {
+ const { implicitKey, inFlow } = ctx;
+ const ss = typeof item.value === 'string'
+ ? item
+ : Object.assign({}, item, { value: String(item.value) });
+ let { type } = item;
+ if (type !== Scalar.Scalar.QUOTE_DOUBLE) {
+ // force double quotes on control characters & unpaired surrogates
+ if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value))
+ type = Scalar.Scalar.QUOTE_DOUBLE;
+ }
+ const _stringify = (_type) => {
+ switch (_type) {
+ case Scalar.Scalar.BLOCK_FOLDED:
+ case Scalar.Scalar.BLOCK_LITERAL:
+ return implicitKey || inFlow
+ ? quotedString(ss.value, ctx) // blocks are not valid inside flow containers
+ : blockString(ss, ctx, onComment, onChompKeep);
+ case Scalar.Scalar.QUOTE_DOUBLE:
+ return doubleQuotedString(ss.value, ctx);
+ case Scalar.Scalar.QUOTE_SINGLE:
+ return singleQuotedString(ss.value, ctx);
+ case Scalar.Scalar.PLAIN:
+ return plainString(ss, ctx, onComment, onChompKeep);
+ default:
+ return null;
+ }
+ };
+ let res = _stringify(type);
+ if (res === null) {
+ const { defaultKeyType, defaultStringType } = ctx.options;
+ const t = (implicitKey && defaultKeyType) || defaultStringType;
+ res = _stringify(t);
+ if (res === null)
+ throw new Error(`Unsupported default string type ${t}`);
+ }
+ return res;
+}
- // 2. If response is not a network error and request’s cache mode is
- // not "no-store", then update response in httpCache for request.
- // TODO
+exports.stringifyString = stringifyString;
- // 3. If includeCredentials is true and the user agent is not configured
- // to block cookies for request (see section 7 of [COOKIES]), then run the
- // "set-cookie-string" parsing algorithm (see section 5.2 of [COOKIES]) on
- // the value of each header whose name is a byte-case-insensitive match for
- // `Set-Cookie` in response’s header list, if any, and request’s current URL.
- // TODO
- // 18. If aborted, then:
- // TODO
+/***/ }),
- // 19. Run these steps in parallel:
+/***/ 204:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 1. Run these steps, but abort when fetchParams is canceled:
- fetchParams.controller.onAborted = onAborted
- fetchParams.controller.on('terminated', onAborted)
- fetchParams.controller.resume = async () => {
- // 1. While true
- while (true) {
- // 1-3. See onData...
- // 4. Set bytes to the result of handling content codings given
- // codings and bytes.
- let bytes
- let isFailure
- try {
- const { done, value } = await fetchParams.controller.next()
- if (isAborted(fetchParams)) {
- break
- }
+var identity = __nccwpck_require__(1127);
- bytes = done ? undefined : value
- } catch (err) {
- if (fetchParams.controller.ended && !timingInfo.encodedBodySize) {
- // zlib doesn't like empty streams.
- bytes = undefined
- } else {
- bytes = err
-
- // err may be propagated from the result of calling readablestream.cancel,
- // which might not be an error. https://github.com/nodejs/undici/issues/2009
- isFailure = true
- }
- }
-
- if (bytes === undefined) {
- // 2. Otherwise, if the bytes transmission for response’s message
- // body is done normally and stream is readable, then close
- // stream, finalize response for fetchParams and response, and
- // abort these in-parallel steps.
- readableStreamClose(fetchParams.controller.controller)
-
- finalizeResponse(fetchParams, response)
-
- return
- }
-
- // 5. Increase timingInfo’s decoded body size by bytes’s length.
- timingInfo.decodedBodySize += bytes?.byteLength ?? 0
-
- // 6. If bytes is failure, then terminate fetchParams’s controller.
- if (isFailure) {
- fetchParams.controller.terminate(bytes)
- return
- }
-
- // 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes
- // into stream.
- const buffer = new Uint8Array(bytes)
- if (buffer.byteLength) {
- fetchParams.controller.controller.enqueue(buffer)
- }
-
- // 8. If stream is errored, then terminate the ongoing fetch.
- if (isErrored(stream)) {
- fetchParams.controller.terminate()
- return
- }
-
- // 9. If stream doesn’t need more data ask the user agent to suspend
- // the ongoing fetch.
- if (fetchParams.controller.controller.desiredSize <= 0) {
- return
- }
+const BREAK = Symbol('break visit');
+const SKIP = Symbol('skip children');
+const REMOVE = Symbol('remove node');
+/**
+ * Apply a visitor to an AST node or document.
+ *
+ * Walks through the tree (depth-first) starting from `node`, calling a
+ * `visitor` function with three arguments:
+ * - `key`: For sequence values and map `Pair`, the node's index in the
+ * collection. Within a `Pair`, `'key'` or `'value'`, correspondingly.
+ * `null` for the root node.
+ * - `node`: The current node.
+ * - `path`: The ancestry of the current node.
+ *
+ * The return value of the visitor may be used to control the traversal:
+ * - `undefined` (default): Do nothing and continue
+ * - `visit.SKIP`: Do not visit the children of this node, continue with next
+ * sibling
+ * - `visit.BREAK`: Terminate traversal completely
+ * - `visit.REMOVE`: Remove the current node, then continue with the next one
+ * - `Node`: Replace the current node, then continue by visiting it
+ * - `number`: While iterating the items of a sequence or map, set the index
+ * of the next step. This is useful especially if the index of the current
+ * node has changed.
+ *
+ * If `visitor` is a single function, it will be called with all values
+ * encountered in the tree, including e.g. `null` values. Alternatively,
+ * separate visitor functions may be defined for each `Map`, `Pair`, `Seq`,
+ * `Alias` and `Scalar` node. To define the same visitor function for more than
+ * one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar)
+ * and `Node` (alias, map, seq & scalar) targets. Of all these, only the most
+ * specific defined one will be used for each node.
+ */
+function visit(node, visitor) {
+ const visitor_ = initVisitor(visitor);
+ if (identity.isDocument(node)) {
+ const cd = visit_(null, node.contents, visitor_, Object.freeze([node]));
+ if (cd === REMOVE)
+ node.contents = null;
}
- }
-
- // 2. If aborted, then:
- function onAborted (reason) {
- // 2. If fetchParams is aborted, then:
- if (isAborted(fetchParams)) {
- // 1. Set response’s aborted flag.
- response.aborted = true
-
- // 2. If stream is readable, then error stream with the result of
- // deserialize a serialized abort reason given fetchParams’s
- // controller’s serialized abort reason and an
- // implementation-defined realm.
- if (isReadable(stream)) {
- fetchParams.controller.controller.error(
- fetchParams.controller.serializedAbortReason
- )
- }
- } else {
- // 3. Otherwise, if stream is readable, error stream with a TypeError.
- if (isReadable(stream)) {
- fetchParams.controller.controller.error(new TypeError('terminated', {
- cause: isErrorLike(reason) ? reason : undefined
- }))
- }
+ else
+ visit_(null, node, visitor_, Object.freeze([]));
+}
+// Without the `as symbol` casts, TS declares these in the `visit`
+// namespace using `var`, but then complains about that because
+// `unique symbol` must be `const`.
+/** Terminate visit traversal completely */
+visit.BREAK = BREAK;
+/** Do not visit the children of the current node */
+visit.SKIP = SKIP;
+/** Remove the current node */
+visit.REMOVE = REMOVE;
+function visit_(key, node, visitor, path) {
+ const ctrl = callVisitor(key, node, visitor, path);
+ if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
+ replaceNode(key, path, ctrl);
+ return visit_(key, ctrl, visitor, path);
}
-
- // 4. If connection uses HTTP/2, then transmit an RST_STREAM frame.
- // 5. Otherwise, the user agent should close connection unless it would be bad for performance to do so.
- fetchParams.controller.connection.destroy()
- }
-
- // 20. Return response.
- return response
-
- function dispatch ({ body }) {
- const url = requestCurrentURL(request)
- /** @type {import('../..').Agent} */
- const agent = fetchParams.controller.dispatcher
-
- return new Promise((resolve, reject) => agent.dispatch(
- {
- path: url.pathname + url.search,
- origin: url.origin,
- method: request.method,
- body: agent.isMockActive ? request.body && (request.body.source || request.body.stream) : body,
- headers: request.headersList.entries,
- maxRedirections: 0,
- upgrade: request.mode === 'websocket' ? 'websocket' : undefined
- },
- {
- body: null,
- abort: null,
-
- onConnect (abort) {
- // TODO (fix): Do we need connection here?
- const { connection } = fetchParams.controller
-
- // Set timingInfo’s final connection timing info to the result of calling clamp and coarsen
- // connection timing info with connection’s timing info, timingInfo’s post-redirect start
- // time, and fetchParams’s cross-origin isolated capability.
- // TODO: implement connection timing
- timingInfo.finalConnectionTimingInfo = clampAndCoarsenConnectionTimingInfo(undefined, timingInfo.postRedirectStartTime, fetchParams.crossOriginIsolatedCapability)
-
- if (connection.destroyed) {
- abort(new DOMException('The operation was aborted.', 'AbortError'))
- } else {
- fetchParams.controller.on('terminated', abort)
- this.abort = connection.abort = abort
- }
-
- // Set timingInfo’s final network-request start time to the coarsened shared current time given
- // fetchParams’s cross-origin isolated capability.
- timingInfo.finalNetworkRequestStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability)
- },
-
- onResponseStarted () {
- // Set timingInfo’s final network-response start time to the coarsened shared current
- // time given fetchParams’s cross-origin isolated capability, immediately after the
- // user agent’s HTTP parser receives the first byte of the response (e.g., frame header
- // bytes for HTTP/2 or response status line for HTTP/1.x).
- timingInfo.finalNetworkResponseStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability)
- },
-
- onHeaders (status, rawHeaders, resume, statusText) {
- if (status < 200) {
- return
- }
-
- let location = ''
-
- const headersList = new HeadersList()
-
- for (let i = 0; i < rawHeaders.length; i += 2) {
- headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i]), rawHeaders[i + 1].toString('latin1'), true)
- }
- location = headersList.get('location', true)
-
- this.body = new Readable({ read: resume })
-
- const decoders = []
-
- const willFollow = location && request.redirect === 'follow' &&
- redirectStatusSet.has(status)
-
- // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding
- if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) {
- // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1
- const contentEncoding = headersList.get('content-encoding', true)
- // "All content-coding values are case-insensitive..."
- /** @type {string[]} */
- const codings = contentEncoding ? contentEncoding.toLowerCase().split(',') : []
-
- // Limit the number of content-encodings to prevent resource exhaustion.
- // CVE fix similar to urllib3 (GHSA-gm62-xv2j-4w53) and curl (CVE-2022-32206).
- const maxContentEncodings = 5
- if (codings.length > maxContentEncodings) {
- reject(new Error(`too many content-encodings in response: ${codings.length}, maximum allowed is ${maxContentEncodings}`))
- return true
- }
-
- for (let i = codings.length - 1; i >= 0; --i) {
- const coding = codings[i].trim()
- // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.2
- if (coding === 'x-gzip' || coding === 'gzip') {
- decoders.push(zlib.createGunzip({
- // Be less strict when decoding compressed responses, since sometimes
- // servers send slightly invalid responses that are still accepted
- // by common browsers.
- // Always using Z_SYNC_FLUSH is what cURL does.
- flush: zlib.constants.Z_SYNC_FLUSH,
- finishFlush: zlib.constants.Z_SYNC_FLUSH
- }))
- } else if (coding === 'deflate') {
- decoders.push(createInflate({
- flush: zlib.constants.Z_SYNC_FLUSH,
- finishFlush: zlib.constants.Z_SYNC_FLUSH
- }))
- } else if (coding === 'br') {
- decoders.push(zlib.createBrotliDecompress({
- flush: zlib.constants.BROTLI_OPERATION_FLUSH,
- finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH
- }))
- } else {
- decoders.length = 0
- break
- }
+ if (typeof ctrl !== 'symbol') {
+ if (identity.isCollection(node)) {
+ path = Object.freeze(path.concat(node));
+ for (let i = 0; i < node.items.length; ++i) {
+ const ci = visit_(i, node.items[i], visitor, path);
+ if (typeof ci === 'number')
+ i = ci - 1;
+ else if (ci === BREAK)
+ return BREAK;
+ else if (ci === REMOVE) {
+ node.items.splice(i, 1);
+ i -= 1;
+ }
}
- }
-
- const onError = this.onError.bind(this)
-
- resolve({
- status,
- statusText,
- headersList,
- body: decoders.length
- ? pipeline(this.body, ...decoders, (err) => {
- if (err) {
- this.onError(err)
+ }
+ else if (identity.isPair(node)) {
+ path = Object.freeze(path.concat(node));
+ const ck = visit_('key', node.key, visitor, path);
+ if (ck === BREAK)
+ return BREAK;
+ else if (ck === REMOVE)
+ node.key = null;
+ const cv = visit_('value', node.value, visitor, path);
+ if (cv === BREAK)
+ return BREAK;
+ else if (cv === REMOVE)
+ node.value = null;
+ }
+ }
+ return ctrl;
+}
+/**
+ * Apply an async visitor to an AST node or document.
+ *
+ * Walks through the tree (depth-first) starting from `node`, calling a
+ * `visitor` function with three arguments:
+ * - `key`: For sequence values and map `Pair`, the node's index in the
+ * collection. Within a `Pair`, `'key'` or `'value'`, correspondingly.
+ * `null` for the root node.
+ * - `node`: The current node.
+ * - `path`: The ancestry of the current node.
+ *
+ * The return value of the visitor may be used to control the traversal:
+ * - `Promise`: Must resolve to one of the following values
+ * - `undefined` (default): Do nothing and continue
+ * - `visit.SKIP`: Do not visit the children of this node, continue with next
+ * sibling
+ * - `visit.BREAK`: Terminate traversal completely
+ * - `visit.REMOVE`: Remove the current node, then continue with the next one
+ * - `Node`: Replace the current node, then continue by visiting it
+ * - `number`: While iterating the items of a sequence or map, set the index
+ * of the next step. This is useful especially if the index of the current
+ * node has changed.
+ *
+ * If `visitor` is a single function, it will be called with all values
+ * encountered in the tree, including e.g. `null` values. Alternatively,
+ * separate visitor functions may be defined for each `Map`, `Pair`, `Seq`,
+ * `Alias` and `Scalar` node. To define the same visitor function for more than
+ * one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar)
+ * and `Node` (alias, map, seq & scalar) targets. Of all these, only the most
+ * specific defined one will be used for each node.
+ */
+async function visitAsync(node, visitor) {
+ const visitor_ = initVisitor(visitor);
+ if (identity.isDocument(node)) {
+ const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node]));
+ if (cd === REMOVE)
+ node.contents = null;
+ }
+ else
+ await visitAsync_(null, node, visitor_, Object.freeze([]));
+}
+// Without the `as symbol` casts, TS declares these in the `visit`
+// namespace using `var`, but then complains about that because
+// `unique symbol` must be `const`.
+/** Terminate visit traversal completely */
+visitAsync.BREAK = BREAK;
+/** Do not visit the children of the current node */
+visitAsync.SKIP = SKIP;
+/** Remove the current node */
+visitAsync.REMOVE = REMOVE;
+async function visitAsync_(key, node, visitor, path) {
+ const ctrl = await callVisitor(key, node, visitor, path);
+ if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
+ replaceNode(key, path, ctrl);
+ return visitAsync_(key, ctrl, visitor, path);
+ }
+ if (typeof ctrl !== 'symbol') {
+ if (identity.isCollection(node)) {
+ path = Object.freeze(path.concat(node));
+ for (let i = 0; i < node.items.length; ++i) {
+ const ci = await visitAsync_(i, node.items[i], visitor, path);
+ if (typeof ci === 'number')
+ i = ci - 1;
+ else if (ci === BREAK)
+ return BREAK;
+ else if (ci === REMOVE) {
+ node.items.splice(i, 1);
+ i -= 1;
}
- }).on('error', onError)
- : this.body.on('error', onError)
- })
-
- return true
- },
-
- onData (chunk) {
- if (fetchParams.controller.dump) {
- return
- }
-
- // 1. If one or more bytes have been transmitted from response’s
- // message body, then:
-
- // 1. Let bytes be the transmitted bytes.
- const bytes = chunk
-
- // 2. Let codings be the result of extracting header list values
- // given `Content-Encoding` and response’s header list.
- // See pullAlgorithm.
-
- // 3. Increase timingInfo’s encoded body size by bytes’s length.
- timingInfo.encodedBodySize += bytes.byteLength
-
- // 4. See pullAlgorithm...
-
- return this.body.push(bytes)
- },
-
- onComplete () {
- if (this.abort) {
- fetchParams.controller.off('terminated', this.abort)
- }
+ }
+ }
+ else if (identity.isPair(node)) {
+ path = Object.freeze(path.concat(node));
+ const ck = await visitAsync_('key', node.key, visitor, path);
+ if (ck === BREAK)
+ return BREAK;
+ else if (ck === REMOVE)
+ node.key = null;
+ const cv = await visitAsync_('value', node.value, visitor, path);
+ if (cv === BREAK)
+ return BREAK;
+ else if (cv === REMOVE)
+ node.value = null;
+ }
+ }
+ return ctrl;
+}
+function initVisitor(visitor) {
+ if (typeof visitor === 'object' &&
+ (visitor.Collection || visitor.Node || visitor.Value)) {
+ return Object.assign({
+ Alias: visitor.Node,
+ Map: visitor.Node,
+ Scalar: visitor.Node,
+ Seq: visitor.Node
+ }, visitor.Value && {
+ Map: visitor.Value,
+ Scalar: visitor.Value,
+ Seq: visitor.Value
+ }, visitor.Collection && {
+ Map: visitor.Collection,
+ Seq: visitor.Collection
+ }, visitor);
+ }
+ return visitor;
+}
+function callVisitor(key, node, visitor, path) {
+ if (typeof visitor === 'function')
+ return visitor(key, node, path);
+ if (identity.isMap(node))
+ return visitor.Map?.(key, node, path);
+ if (identity.isSeq(node))
+ return visitor.Seq?.(key, node, path);
+ if (identity.isPair(node))
+ return visitor.Pair?.(key, node, path);
+ if (identity.isScalar(node))
+ return visitor.Scalar?.(key, node, path);
+ if (identity.isAlias(node))
+ return visitor.Alias?.(key, node, path);
+ return undefined;
+}
+function replaceNode(key, path, node) {
+ const parent = path[path.length - 1];
+ if (identity.isCollection(parent)) {
+ parent.items[key] = node;
+ }
+ else if (identity.isPair(parent)) {
+ if (key === 'key')
+ parent.key = node;
+ else
+ parent.value = node;
+ }
+ else if (identity.isDocument(parent)) {
+ parent.contents = node;
+ }
+ else {
+ const pt = identity.isAlias(parent) ? 'alias' : 'scalar';
+ throw new Error(`Cannot replace node with ${pt} parent`);
+ }
+}
- if (fetchParams.controller.onAborted) {
- fetchParams.controller.off('terminated', fetchParams.controller.onAborted)
- }
+exports.visit = visit;
+exports.visitAsync = visitAsync;
- fetchParams.controller.ended = true
- this.body.push(null)
- },
+/***/ }),
- onError (error) {
- if (this.abort) {
- fetchParams.controller.off('terminated', this.abort)
- }
+/***/ 8658:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- this.body?.destroy(error)
+// This file exists as a CommonJS module to read the version from package.json.
+// In an ESM package, using `require()` directly in .ts files requires disabling
+// ESLint rules and doesn't work reliably across all Node.js versions.
+// By keeping this as a .cjs file, we can use require() naturally and export
+// the version for the ESM modules to import.
+const packageJson = __nccwpck_require__(4012)
+module.exports = { version: packageJson.version }
- fetchParams.controller.terminate(error)
- reject(error)
- },
+/***/ }),
- onUpgrade (status, rawHeaders, socket) {
- if (status !== 101) {
- return
- }
+/***/ 4012:
+/***/ ((module) => {
- const headersList = new HeadersList()
+module.exports = /*#__PURE__*/JSON.parse('{"name":"@actions/cache","version":"6.0.1","description":"Actions cache lib","keywords":["github","actions","cache"],"homepage":"https://github.com/actions/toolkit/tree/main/packages/cache","license":"MIT","type":"module","main":"lib/cache.js","types":"lib/cache.d.ts","exports":{".":{"types":"./lib/cache.d.ts","import":"./lib/cache.js"}},"directories":{"lib":"lib","test":"__tests__"},"files":["lib","!.DS_Store"],"publishConfig":{"access":"public"},"repository":{"type":"git","url":"git+https://github.com/actions/toolkit.git","directory":"packages/cache"},"scripts":{"audit-moderate":"npm install && npm audit --json --audit-level=moderate > audit.json","test":"echo \\"Error: run tests from root\\" && exit 1","tsc":"tsc && cp src/internal/shared/package-version.cjs lib/internal/shared/"},"bugs":{"url":"https://github.com/actions/toolkit/issues"},"dependencies":{"@actions/core":"^3.0.1","@actions/exec":"^3.0.0","@actions/glob":"^0.6.1","@actions/http-client":"^4.0.1","@actions/io":"^3.0.2","@azure/core-rest-pipeline":"^1.23.0","@azure/storage-blob":"^12.31.0","@protobuf-ts/runtime-rpc":"^2.11.1","semver":"^7.7.4"},"devDependencies":{"@protobuf-ts/plugin":"^2.11.1","@types/node":"^25.6.0","@types/semver":"^7.7.1","typescript":"^5.9.3"},"overrides":{"uri-js":"npm:uri-js-replace@^1.0.1","node-fetch":"^3.3.2"}}');
- for (let i = 0; i < rawHeaders.length; i += 2) {
- headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i]), rawHeaders[i + 1].toString('latin1'), true)
- }
+/***/ })
- resolve({
- status,
- statusText: STATUS_CODES[status],
- headersList,
- socket
- })
+/******/ });
+/************************************************************************/
+/******/ // The module cache
+/******/ var __webpack_module_cache__ = {};
+/******/
+/******/ // The require function
+/******/ function __nccwpck_require__(moduleId) {
+/******/ // Check if module is in cache
+/******/ var cachedModule = __webpack_module_cache__[moduleId];
+/******/ if (cachedModule !== undefined) {
+/******/ return cachedModule.exports;
+/******/ }
+/******/ // Create a new module (and put it into the cache)
+/******/ var module = __webpack_module_cache__[moduleId] = {
+/******/ // no module.id needed
+/******/ // no module.loaded needed
+/******/ exports: {}
+/******/ };
+/******/
+/******/ // Execute the module function
+/******/ var threw = true;
+/******/ try {
+/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __nccwpck_require__);
+/******/ threw = false;
+/******/ } finally {
+/******/ if(threw) delete __webpack_module_cache__[moduleId];
+/******/ }
+/******/
+/******/ // Return the exports of the module
+/******/ return module.exports;
+/******/ }
+/******/
+/************************************************************************/
+/******/ /* webpack/runtime/create fake namespace object */
+/******/ (() => {
+/******/ var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);
+/******/ var leafPrototypes;
+/******/ // create a fake namespace object
+/******/ // mode & 1: value is a module id, require it
+/******/ // mode & 2: merge all properties of value into the ns
+/******/ // mode & 4: return value when already ns object
+/******/ // mode & 16: return value when it's Promise-like
+/******/ // mode & 8|1: behave like require
+/******/ __nccwpck_require__.t = function(value, mode) {
+/******/ if(mode & 1) value = this(value);
+/******/ if(mode & 8) return value;
+/******/ if(typeof value === 'object' && value) {
+/******/ if((mode & 4) && value.__esModule) return value;
+/******/ if((mode & 16) && typeof value.then === 'function') return value;
+/******/ }
+/******/ var ns = Object.create(null);
+/******/ __nccwpck_require__.r(ns);
+/******/ var def = {};
+/******/ leafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];
+/******/ for(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) {
+/******/ Object.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));
+/******/ }
+/******/ def['default'] = () => (value);
+/******/ __nccwpck_require__.d(ns, def);
+/******/ return ns;
+/******/ };
+/******/ })();
+/******/
+/******/ /* webpack/runtime/define property getters */
+/******/ (() => {
+/******/ // define getter functions for harmony exports
+/******/ __nccwpck_require__.d = (exports, definition) => {
+/******/ for(var key in definition) {
+/******/ if(__nccwpck_require__.o(definition, key) && !__nccwpck_require__.o(exports, key)) {
+/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
+/******/ }
+/******/ }
+/******/ };
+/******/ })();
+/******/
+/******/ /* webpack/runtime/hasOwnProperty shorthand */
+/******/ (() => {
+/******/ __nccwpck_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
+/******/ })();
+/******/
+/******/ /* webpack/runtime/make namespace object */
+/******/ (() => {
+/******/ // define __esModule on exports
+/******/ __nccwpck_require__.r = (exports) => {
+/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
+/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
+/******/ }
+/******/ Object.defineProperty(exports, '__esModule', { value: true });
+/******/ };
+/******/ })();
+/******/
+/******/ /* webpack/runtime/compat */
+/******/
+/******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = new URL('.', import.meta.url).pathname.slice(import.meta.url.match(/^file:\/\/\/\w:/) ? 1 : 0, -1) + "/";
+/******/
+/************************************************************************/
+var __webpack_exports__ = {};
- return true
- }
- }
- ))
- }
-}
+// NAMESPACE OBJECT: ./node_modules/@azure/storage-blob/dist/esm/generated/src/models/mappers.js
+var mappers_namespaceObject = {};
+__nccwpck_require__.r(mappers_namespaceObject);
+__nccwpck_require__.d(mappers_namespaceObject, {
+ AccessPolicy: () => (AccessPolicy),
+ AppendBlobAppendBlockExceptionHeaders: () => (AppendBlobAppendBlockExceptionHeaders),
+ AppendBlobAppendBlockFromUrlExceptionHeaders: () => (AppendBlobAppendBlockFromUrlExceptionHeaders),
+ AppendBlobAppendBlockFromUrlHeaders: () => (AppendBlobAppendBlockFromUrlHeaders),
+ AppendBlobAppendBlockHeaders: () => (AppendBlobAppendBlockHeaders),
+ AppendBlobCreateExceptionHeaders: () => (AppendBlobCreateExceptionHeaders),
+ AppendBlobCreateHeaders: () => (AppendBlobCreateHeaders),
+ AppendBlobSealExceptionHeaders: () => (AppendBlobSealExceptionHeaders),
+ AppendBlobSealHeaders: () => (AppendBlobSealHeaders),
+ ArrowConfiguration: () => (ArrowConfiguration),
+ ArrowField: () => (ArrowField),
+ BlobAbortCopyFromURLExceptionHeaders: () => (BlobAbortCopyFromURLExceptionHeaders),
+ BlobAbortCopyFromURLHeaders: () => (BlobAbortCopyFromURLHeaders),
+ BlobAcquireLeaseExceptionHeaders: () => (BlobAcquireLeaseExceptionHeaders),
+ BlobAcquireLeaseHeaders: () => (BlobAcquireLeaseHeaders),
+ BlobBreakLeaseExceptionHeaders: () => (BlobBreakLeaseExceptionHeaders),
+ BlobBreakLeaseHeaders: () => (BlobBreakLeaseHeaders),
+ BlobChangeLeaseExceptionHeaders: () => (BlobChangeLeaseExceptionHeaders),
+ BlobChangeLeaseHeaders: () => (BlobChangeLeaseHeaders),
+ BlobCopyFromURLExceptionHeaders: () => (BlobCopyFromURLExceptionHeaders),
+ BlobCopyFromURLHeaders: () => (BlobCopyFromURLHeaders),
+ BlobCreateSnapshotExceptionHeaders: () => (BlobCreateSnapshotExceptionHeaders),
+ BlobCreateSnapshotHeaders: () => (BlobCreateSnapshotHeaders),
+ BlobDeleteExceptionHeaders: () => (BlobDeleteExceptionHeaders),
+ BlobDeleteHeaders: () => (BlobDeleteHeaders),
+ BlobDeleteImmutabilityPolicyExceptionHeaders: () => (BlobDeleteImmutabilityPolicyExceptionHeaders),
+ BlobDeleteImmutabilityPolicyHeaders: () => (BlobDeleteImmutabilityPolicyHeaders),
+ BlobDownloadExceptionHeaders: () => (BlobDownloadExceptionHeaders),
+ BlobDownloadHeaders: () => (BlobDownloadHeaders),
+ BlobFlatListSegment: () => (BlobFlatListSegment),
+ BlobGetAccountInfoExceptionHeaders: () => (BlobGetAccountInfoExceptionHeaders),
+ BlobGetAccountInfoHeaders: () => (BlobGetAccountInfoHeaders),
+ BlobGetPropertiesExceptionHeaders: () => (BlobGetPropertiesExceptionHeaders),
+ BlobGetPropertiesHeaders: () => (BlobGetPropertiesHeaders),
+ BlobGetTagsExceptionHeaders: () => (BlobGetTagsExceptionHeaders),
+ BlobGetTagsHeaders: () => (BlobGetTagsHeaders),
+ BlobHierarchyListSegment: () => (BlobHierarchyListSegment),
+ BlobItemInternal: () => (BlobItemInternal),
+ BlobName: () => (BlobName),
+ BlobPrefix: () => (BlobPrefix),
+ BlobPropertiesInternal: () => (BlobPropertiesInternal),
+ BlobQueryExceptionHeaders: () => (BlobQueryExceptionHeaders),
+ BlobQueryHeaders: () => (BlobQueryHeaders),
+ BlobReleaseLeaseExceptionHeaders: () => (BlobReleaseLeaseExceptionHeaders),
+ BlobReleaseLeaseHeaders: () => (BlobReleaseLeaseHeaders),
+ BlobRenewLeaseExceptionHeaders: () => (BlobRenewLeaseExceptionHeaders),
+ BlobRenewLeaseHeaders: () => (BlobRenewLeaseHeaders),
+ BlobServiceProperties: () => (BlobServiceProperties),
+ BlobServiceStatistics: () => (BlobServiceStatistics),
+ BlobSetExpiryExceptionHeaders: () => (BlobSetExpiryExceptionHeaders),
+ BlobSetExpiryHeaders: () => (BlobSetExpiryHeaders),
+ BlobSetHttpHeadersExceptionHeaders: () => (BlobSetHttpHeadersExceptionHeaders),
+ BlobSetHttpHeadersHeaders: () => (BlobSetHttpHeadersHeaders),
+ BlobSetImmutabilityPolicyExceptionHeaders: () => (BlobSetImmutabilityPolicyExceptionHeaders),
+ BlobSetImmutabilityPolicyHeaders: () => (BlobSetImmutabilityPolicyHeaders),
+ BlobSetLegalHoldExceptionHeaders: () => (BlobSetLegalHoldExceptionHeaders),
+ BlobSetLegalHoldHeaders: () => (BlobSetLegalHoldHeaders),
+ BlobSetMetadataExceptionHeaders: () => (BlobSetMetadataExceptionHeaders),
+ BlobSetMetadataHeaders: () => (BlobSetMetadataHeaders),
+ BlobSetTagsExceptionHeaders: () => (BlobSetTagsExceptionHeaders),
+ BlobSetTagsHeaders: () => (BlobSetTagsHeaders),
+ BlobSetTierExceptionHeaders: () => (BlobSetTierExceptionHeaders),
+ BlobSetTierHeaders: () => (BlobSetTierHeaders),
+ BlobStartCopyFromURLExceptionHeaders: () => (BlobStartCopyFromURLExceptionHeaders),
+ BlobStartCopyFromURLHeaders: () => (BlobStartCopyFromURLHeaders),
+ BlobTag: () => (BlobTag),
+ BlobTags: () => (BlobTags),
+ BlobUndeleteExceptionHeaders: () => (BlobUndeleteExceptionHeaders),
+ BlobUndeleteHeaders: () => (BlobUndeleteHeaders),
+ Block: () => (Block),
+ BlockBlobCommitBlockListExceptionHeaders: () => (BlockBlobCommitBlockListExceptionHeaders),
+ BlockBlobCommitBlockListHeaders: () => (BlockBlobCommitBlockListHeaders),
+ BlockBlobGetBlockListExceptionHeaders: () => (BlockBlobGetBlockListExceptionHeaders),
+ BlockBlobGetBlockListHeaders: () => (BlockBlobGetBlockListHeaders),
+ BlockBlobPutBlobFromUrlExceptionHeaders: () => (BlockBlobPutBlobFromUrlExceptionHeaders),
+ BlockBlobPutBlobFromUrlHeaders: () => (BlockBlobPutBlobFromUrlHeaders),
+ BlockBlobStageBlockExceptionHeaders: () => (BlockBlobStageBlockExceptionHeaders),
+ BlockBlobStageBlockFromURLExceptionHeaders: () => (BlockBlobStageBlockFromURLExceptionHeaders),
+ BlockBlobStageBlockFromURLHeaders: () => (BlockBlobStageBlockFromURLHeaders),
+ BlockBlobStageBlockHeaders: () => (BlockBlobStageBlockHeaders),
+ BlockBlobUploadExceptionHeaders: () => (BlockBlobUploadExceptionHeaders),
+ BlockBlobUploadHeaders: () => (BlockBlobUploadHeaders),
+ BlockList: () => (BlockList),
+ BlockLookupList: () => (BlockLookupList),
+ ClearRange: () => (ClearRange),
+ ContainerAcquireLeaseExceptionHeaders: () => (ContainerAcquireLeaseExceptionHeaders),
+ ContainerAcquireLeaseHeaders: () => (ContainerAcquireLeaseHeaders),
+ ContainerBreakLeaseExceptionHeaders: () => (ContainerBreakLeaseExceptionHeaders),
+ ContainerBreakLeaseHeaders: () => (ContainerBreakLeaseHeaders),
+ ContainerChangeLeaseExceptionHeaders: () => (ContainerChangeLeaseExceptionHeaders),
+ ContainerChangeLeaseHeaders: () => (ContainerChangeLeaseHeaders),
+ ContainerCreateExceptionHeaders: () => (ContainerCreateExceptionHeaders),
+ ContainerCreateHeaders: () => (ContainerCreateHeaders),
+ ContainerDeleteExceptionHeaders: () => (ContainerDeleteExceptionHeaders),
+ ContainerDeleteHeaders: () => (ContainerDeleteHeaders),
+ ContainerFilterBlobsExceptionHeaders: () => (ContainerFilterBlobsExceptionHeaders),
+ ContainerFilterBlobsHeaders: () => (ContainerFilterBlobsHeaders),
+ ContainerGetAccessPolicyExceptionHeaders: () => (ContainerGetAccessPolicyExceptionHeaders),
+ ContainerGetAccessPolicyHeaders: () => (ContainerGetAccessPolicyHeaders),
+ ContainerGetAccountInfoExceptionHeaders: () => (ContainerGetAccountInfoExceptionHeaders),
+ ContainerGetAccountInfoHeaders: () => (ContainerGetAccountInfoHeaders),
+ ContainerGetPropertiesExceptionHeaders: () => (ContainerGetPropertiesExceptionHeaders),
+ ContainerGetPropertiesHeaders: () => (ContainerGetPropertiesHeaders),
+ ContainerItem: () => (ContainerItem),
+ ContainerListBlobFlatSegmentExceptionHeaders: () => (ContainerListBlobFlatSegmentExceptionHeaders),
+ ContainerListBlobFlatSegmentHeaders: () => (ContainerListBlobFlatSegmentHeaders),
+ ContainerListBlobHierarchySegmentExceptionHeaders: () => (ContainerListBlobHierarchySegmentExceptionHeaders),
+ ContainerListBlobHierarchySegmentHeaders: () => (ContainerListBlobHierarchySegmentHeaders),
+ ContainerProperties: () => (ContainerProperties),
+ ContainerReleaseLeaseExceptionHeaders: () => (ContainerReleaseLeaseExceptionHeaders),
+ ContainerReleaseLeaseHeaders: () => (ContainerReleaseLeaseHeaders),
+ ContainerRenameExceptionHeaders: () => (ContainerRenameExceptionHeaders),
+ ContainerRenameHeaders: () => (ContainerRenameHeaders),
+ ContainerRenewLeaseExceptionHeaders: () => (ContainerRenewLeaseExceptionHeaders),
+ ContainerRenewLeaseHeaders: () => (ContainerRenewLeaseHeaders),
+ ContainerRestoreExceptionHeaders: () => (ContainerRestoreExceptionHeaders),
+ ContainerRestoreHeaders: () => (ContainerRestoreHeaders),
+ ContainerSetAccessPolicyExceptionHeaders: () => (ContainerSetAccessPolicyExceptionHeaders),
+ ContainerSetAccessPolicyHeaders: () => (ContainerSetAccessPolicyHeaders),
+ ContainerSetMetadataExceptionHeaders: () => (ContainerSetMetadataExceptionHeaders),
+ ContainerSetMetadataHeaders: () => (ContainerSetMetadataHeaders),
+ ContainerSubmitBatchExceptionHeaders: () => (ContainerSubmitBatchExceptionHeaders),
+ ContainerSubmitBatchHeaders: () => (ContainerSubmitBatchHeaders),
+ CorsRule: () => (CorsRule),
+ DelimitedTextConfiguration: () => (DelimitedTextConfiguration),
+ FilterBlobItem: () => (FilterBlobItem),
+ FilterBlobSegment: () => (FilterBlobSegment),
+ GeoReplication: () => (GeoReplication),
+ JsonTextConfiguration: () => (JsonTextConfiguration),
+ KeyInfo: () => (KeyInfo),
+ ListBlobsFlatSegmentResponse: () => (ListBlobsFlatSegmentResponse),
+ ListBlobsHierarchySegmentResponse: () => (ListBlobsHierarchySegmentResponse),
+ ListContainersSegmentResponse: () => (ListContainersSegmentResponse),
+ Logging: () => (Logging),
+ Metrics: () => (Metrics),
+ PageBlobClearPagesExceptionHeaders: () => (PageBlobClearPagesExceptionHeaders),
+ PageBlobClearPagesHeaders: () => (PageBlobClearPagesHeaders),
+ PageBlobCopyIncrementalExceptionHeaders: () => (PageBlobCopyIncrementalExceptionHeaders),
+ PageBlobCopyIncrementalHeaders: () => (PageBlobCopyIncrementalHeaders),
+ PageBlobCreateExceptionHeaders: () => (PageBlobCreateExceptionHeaders),
+ PageBlobCreateHeaders: () => (PageBlobCreateHeaders),
+ PageBlobGetPageRangesDiffExceptionHeaders: () => (PageBlobGetPageRangesDiffExceptionHeaders),
+ PageBlobGetPageRangesDiffHeaders: () => (PageBlobGetPageRangesDiffHeaders),
+ PageBlobGetPageRangesExceptionHeaders: () => (PageBlobGetPageRangesExceptionHeaders),
+ PageBlobGetPageRangesHeaders: () => (PageBlobGetPageRangesHeaders),
+ PageBlobResizeExceptionHeaders: () => (PageBlobResizeExceptionHeaders),
+ PageBlobResizeHeaders: () => (PageBlobResizeHeaders),
+ PageBlobUpdateSequenceNumberExceptionHeaders: () => (PageBlobUpdateSequenceNumberExceptionHeaders),
+ PageBlobUpdateSequenceNumberHeaders: () => (PageBlobUpdateSequenceNumberHeaders),
+ PageBlobUploadPagesExceptionHeaders: () => (PageBlobUploadPagesExceptionHeaders),
+ PageBlobUploadPagesFromURLExceptionHeaders: () => (PageBlobUploadPagesFromURLExceptionHeaders),
+ PageBlobUploadPagesFromURLHeaders: () => (PageBlobUploadPagesFromURLHeaders),
+ PageBlobUploadPagesHeaders: () => (PageBlobUploadPagesHeaders),
+ PageList: () => (PageList),
+ PageRange: () => (PageRange),
+ QueryFormat: () => (QueryFormat),
+ QueryRequest: () => (QueryRequest),
+ QuerySerialization: () => (QuerySerialization),
+ RetentionPolicy: () => (RetentionPolicy),
+ ServiceFilterBlobsExceptionHeaders: () => (ServiceFilterBlobsExceptionHeaders),
+ ServiceFilterBlobsHeaders: () => (ServiceFilterBlobsHeaders),
+ ServiceGetAccountInfoExceptionHeaders: () => (ServiceGetAccountInfoExceptionHeaders),
+ ServiceGetAccountInfoHeaders: () => (ServiceGetAccountInfoHeaders),
+ ServiceGetPropertiesExceptionHeaders: () => (ServiceGetPropertiesExceptionHeaders),
+ ServiceGetPropertiesHeaders: () => (ServiceGetPropertiesHeaders),
+ ServiceGetStatisticsExceptionHeaders: () => (ServiceGetStatisticsExceptionHeaders),
+ ServiceGetStatisticsHeaders: () => (ServiceGetStatisticsHeaders),
+ ServiceGetUserDelegationKeyExceptionHeaders: () => (ServiceGetUserDelegationKeyExceptionHeaders),
+ ServiceGetUserDelegationKeyHeaders: () => (ServiceGetUserDelegationKeyHeaders),
+ ServiceListContainersSegmentExceptionHeaders: () => (ServiceListContainersSegmentExceptionHeaders),
+ ServiceListContainersSegmentHeaders: () => (ServiceListContainersSegmentHeaders),
+ ServiceSetPropertiesExceptionHeaders: () => (ServiceSetPropertiesExceptionHeaders),
+ ServiceSetPropertiesHeaders: () => (ServiceSetPropertiesHeaders),
+ ServiceSubmitBatchExceptionHeaders: () => (ServiceSubmitBatchExceptionHeaders),
+ ServiceSubmitBatchHeaders: () => (ServiceSubmitBatchHeaders),
+ SignedIdentifier: () => (SignedIdentifier),
+ StaticWebsite: () => (StaticWebsite),
+ StorageError: () => (StorageError),
+ UserDelegationKey: () => (UserDelegationKey)
+});
-module.exports = {
- fetch,
- Fetch,
- fetching,
- finalizeAndReportTiming
+;// CONCATENATED MODULE: external "fs"
+const external_fs_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("fs");
+;// CONCATENATED MODULE: external "timers/promises"
+const promises_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("timers/promises");
+;// CONCATENATED MODULE: external "os"
+const external_os_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("os");
+;// CONCATENATED MODULE: ./node_modules/@actions/core/lib/utils.js
+// We use any as a valid input type
+/* eslint-disable @typescript-eslint/no-explicit-any */
+/**
+ * Sanitizes an input into a string so it can be passed into issueCommand safely
+ * @param input input to sanitize into a string
+ */
+function utils_toCommandValue(input) {
+ if (input === null || input === undefined) {
+ return '';
+ }
+ else if (typeof input === 'string' || input instanceof String) {
+ return input;
+ }
+ return JSON.stringify(input);
}
+/**
+ *
+ * @param annotationProperties
+ * @returns The command properties to send with the actual annotation command
+ * See IssueCommandProperties: https://github.com/actions/runner/blob/main/src/Runner.Worker/ActionCommandManager.cs#L646
+ */
+function utils_toCommandProperties(annotationProperties) {
+ if (!Object.keys(annotationProperties).length) {
+ return {};
+ }
+ return {
+ title: annotationProperties.title,
+ file: annotationProperties.file,
+ line: annotationProperties.startLine,
+ endLine: annotationProperties.endLine,
+ col: annotationProperties.startColumn,
+ endColumn: annotationProperties.endColumn
+ };
+}
+//# sourceMappingURL=utils.js.map
+;// CONCATENATED MODULE: ./node_modules/@actions/core/lib/command.js
-/***/ }),
-
-/***/ 6055:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-/* globals AbortController */
-
-
-
-const { extractBody, mixinBody, cloneBody, bodyUnusable } = __nccwpck_require__(8900)
-const { Headers, fill: fillHeaders, HeadersList, setHeadersGuard, getHeadersGuard, setHeadersList, getHeadersList } = __nccwpck_require__(3676)
-const { FinalizationRegistry } = __nccwpck_require__(933)()
-const util = __nccwpck_require__(1544)
-const nodeUtil = __nccwpck_require__(7975)
-const {
- isValidHTTPToken,
- sameOrigin,
- environmentSettingsObject
-} = __nccwpck_require__(4296)
-const {
- forbiddenMethodsSet,
- corsSafeListedMethodsSet,
- referrerPolicy,
- requestRedirect,
- requestMode,
- requestCredentials,
- requestCache,
- requestDuplex
-} = __nccwpck_require__(1207)
-const { kEnumerableProperty, normalizedMethodRecordsBase, normalizedMethodRecords } = util
-const { kHeaders, kSignal, kState, kDispatcher } = __nccwpck_require__(4883)
-const { webidl } = __nccwpck_require__(253)
-const { URLSerializer } = __nccwpck_require__(980)
-const { kConstruct } = __nccwpck_require__(9411)
-const assert = __nccwpck_require__(4589)
-const { getMaxListeners, setMaxListeners, getEventListeners, defaultMaxListeners } = __nccwpck_require__(8474)
-
-const kAbortController = Symbol('abortController')
-
-const requestFinalizer = new FinalizationRegistry(({ signal, abort }) => {
- signal.removeEventListener('abort', abort)
-})
-
-const dependentControllerMap = new WeakMap()
-
-function buildAbort (acRef) {
- return abort
-
- function abort () {
- const ac = acRef.deref()
- if (ac !== undefined) {
- // Currently, there is a problem with FinalizationRegistry.
- // https://github.com/nodejs/node/issues/49344
- // https://github.com/nodejs/node/issues/47748
- // In the case of abort, the first step is to unregister from it.
- // If the controller can refer to it, it is still registered.
- // It will be removed in the future.
- requestFinalizer.unregister(abort)
-
- // Unsubscribe a listener.
- // FinalizationRegistry will no longer be called, so this must be done.
- this.removeEventListener('abort', abort)
-
- ac.abort(this.reason)
-
- const controllerList = dependentControllerMap.get(ac.signal)
-
- if (controllerList !== undefined) {
- if (controllerList.size !== 0) {
- for (const ref of controllerList) {
- const ctrl = ref.deref()
- if (ctrl !== undefined) {
- ctrl.abort(this.reason)
+/**
+ * Issues a command to the GitHub Actions runner
+ *
+ * @param command - The command name to issue
+ * @param properties - Additional properties for the command (key-value pairs)
+ * @param message - The message to include with the command
+ * @remarks
+ * This function outputs a specially formatted string to stdout that the Actions
+ * runner interprets as a command. These commands can control workflow behavior,
+ * set outputs, create annotations, mask values, and more.
+ *
+ * Command Format:
+ * ::name key=value,key=value::message
+ *
+ * @example
+ * ```typescript
+ * // Issue a warning annotation
+ * issueCommand('warning', {}, 'This is a warning message');
+ * // Output: ::warning::This is a warning message
+ *
+ * // Set an environment variable
+ * issueCommand('set-env', { name: 'MY_VAR' }, 'some value');
+ * // Output: ::set-env name=MY_VAR::some value
+ *
+ * // Add a secret mask
+ * issueCommand('add-mask', {}, 'secretValue123');
+ * // Output: ::add-mask::secretValue123
+ * ```
+ *
+ * @internal
+ * This is an internal utility function that powers the public API functions
+ * such as setSecret, warning, error, and exportVariable.
+ */
+function command_issueCommand(command, properties, message) {
+ const cmd = new Command(command, properties, message);
+ process.stdout.write(cmd.toString() + external_os_namespaceObject.EOL);
+}
+function command_issue(name, message = '') {
+ command_issueCommand(name, {}, message);
+}
+const CMD_STRING = '::';
+class Command {
+ constructor(command, properties, message) {
+ if (!command) {
+ command = 'missing.command';
+ }
+ this.command = command;
+ this.properties = properties;
+ this.message = message;
+ }
+ toString() {
+ let cmdStr = CMD_STRING + this.command;
+ if (this.properties && Object.keys(this.properties).length > 0) {
+ cmdStr += ' ';
+ let first = true;
+ for (const key in this.properties) {
+ if (this.properties.hasOwnProperty(key)) {
+ const val = this.properties[key];
+ if (val) {
+ if (first) {
+ first = false;
+ }
+ else {
+ cmdStr += ',';
+ }
+ cmdStr += `${key}=${escapeProperty(val)}`;
+ }
+ }
}
- }
- controllerList.clear()
}
- dependentControllerMap.delete(ac.signal)
- }
+ cmdStr += `${CMD_STRING}${escapeData(this.message)}`;
+ return cmdStr;
}
- }
}
+function escapeData(s) {
+ return utils_toCommandValue(s)
+ .replace(/%/g, '%25')
+ .replace(/\r/g, '%0D')
+ .replace(/\n/g, '%0A');
+}
+function escapeProperty(s) {
+ return utils_toCommandValue(s)
+ .replace(/%/g, '%25')
+ .replace(/\r/g, '%0D')
+ .replace(/\n/g, '%0A')
+ .replace(/:/g, '%3A')
+ .replace(/,/g, '%2C');
+}
+//# sourceMappingURL=command.js.map
+;// CONCATENATED MODULE: external "crypto"
+const external_crypto_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("crypto");
+;// CONCATENATED MODULE: ./node_modules/@actions/core/lib/file-command.js
+// For internal use, subject to change.
+// We use any as a valid input type
+/* eslint-disable @typescript-eslint/no-explicit-any */
-let patchMethodWarning = false
-
-// https://fetch.spec.whatwg.org/#request-class
-class Request {
- // https://fetch.spec.whatwg.org/#dom-request
- constructor (input, init = {}) {
- webidl.util.markAsUncloneable(this)
- if (input === kConstruct) {
- return
- }
-
- const prefix = 'Request constructor'
- webidl.argumentLengthCheck(arguments, 1, prefix)
-
- input = webidl.converters.RequestInfo(input, prefix, 'input')
- init = webidl.converters.RequestInit(init, prefix, 'init')
- // 1. Let request be null.
- let request = null
- // 2. Let fallbackMode be null.
- let fallbackMode = null
- // 3. Let baseURL be this’s relevant settings object’s API base URL.
- const baseUrl = environmentSettingsObject.settingsObject.baseUrl
-
- // 4. Let signal be null.
- let signal = null
-
- // 5. If input is a string, then:
- if (typeof input === 'string') {
- this[kDispatcher] = init.dispatcher
-
- // 1. Let parsedURL be the result of parsing input with baseURL.
- // 2. If parsedURL is failure, then throw a TypeError.
- let parsedURL
- try {
- parsedURL = new URL(input, baseUrl)
- } catch (err) {
- throw new TypeError('Failed to parse URL from ' + input, { cause: err })
- }
-
- // 3. If parsedURL includes credentials, then throw a TypeError.
- if (parsedURL.username || parsedURL.password) {
- throw new TypeError(
- 'Request cannot be constructed from a URL that includes credentials: ' +
- input
- )
- }
-
- // 4. Set request to a new request whose URL is parsedURL.
- request = makeRequest({ urlList: [parsedURL] })
-
- // 5. Set fallbackMode to "cors".
- fallbackMode = 'cors'
- } else {
- this[kDispatcher] = init.dispatcher || input[kDispatcher]
-
- // 6. Otherwise:
-
- // 7. Assert: input is a Request object.
- assert(input instanceof Request)
-
- // 8. Set request to input’s request.
- request = input[kState]
-
- // 9. Set signal to input’s signal.
- signal = input[kSignal]
+function file_command_issueFileCommand(command, message) {
+ const filePath = process.env[`GITHUB_${command}`];
+ if (!filePath) {
+ throw new Error(`Unable to find environment variable for file command ${command}`);
}
-
- // 7. Let origin be this’s relevant settings object’s origin.
- const origin = environmentSettingsObject.settingsObject.origin
-
- // 8. Let window be "client".
- let window = 'client'
-
- // 9. If request’s window is an environment settings object and its origin
- // is same origin with origin, then set window to request’s window.
- if (
- request.window?.constructor?.name === 'EnvironmentSettingsObject' &&
- sameOrigin(request.window, origin)
- ) {
- window = request.window
+ if (!external_fs_namespaceObject.existsSync(filePath)) {
+ throw new Error(`Missing file at path: ${filePath}`);
}
-
- // 10. If init["window"] exists and is non-null, then throw a TypeError.
- if (init.window != null) {
- throw new TypeError(`'window' option '${window}' must be null`)
+ external_fs_namespaceObject.appendFileSync(filePath, `${utils_toCommandValue(message)}${external_os_namespaceObject.EOL}`, {
+ encoding: 'utf8'
+ });
+}
+function file_command_prepareKeyValueMessage(key, value) {
+ const delimiter = `ghadelimiter_${external_crypto_namespaceObject.randomUUID()}`;
+ const convertedValue = utils_toCommandValue(value);
+ // These should realistically never happen, but just in case someone finds a
+ // way to exploit uuid generation let's not allow keys or values that contain
+ // the delimiter.
+ if (key.includes(delimiter)) {
+ throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`);
}
-
- // 11. If init["window"] exists, then set window to "no-window".
- if ('window' in init) {
- window = 'no-window'
+ if (convertedValue.includes(delimiter)) {
+ throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`);
}
-
- // 12. Set request to a new request with the following properties:
- request = makeRequest({
- // URL request’s URL.
- // undici implementation note: this is set as the first item in request's urlList in makeRequest
- // method request’s method.
- method: request.method,
- // header list A copy of request’s header list.
- // undici implementation note: headersList is cloned in makeRequest
- headersList: request.headersList,
- // unsafe-request flag Set.
- unsafeRequest: request.unsafeRequest,
- // client This’s relevant settings object.
- client: environmentSettingsObject.settingsObject,
- // window window.
- window,
- // priority request’s priority.
- priority: request.priority,
- // origin request’s origin. The propagation of the origin is only significant for navigation requests
- // being handled by a service worker. In this scenario a request can have an origin that is different
- // from the current client.
- origin: request.origin,
- // referrer request’s referrer.
- referrer: request.referrer,
- // referrer policy request’s referrer policy.
- referrerPolicy: request.referrerPolicy,
- // mode request’s mode.
- mode: request.mode,
- // credentials mode request’s credentials mode.
- credentials: request.credentials,
- // cache mode request’s cache mode.
- cache: request.cache,
- // redirect mode request’s redirect mode.
- redirect: request.redirect,
- // integrity metadata request’s integrity metadata.
- integrity: request.integrity,
- // keepalive request’s keepalive.
- keepalive: request.keepalive,
- // reload-navigation flag request’s reload-navigation flag.
- reloadNavigation: request.reloadNavigation,
- // history-navigation flag request’s history-navigation flag.
- historyNavigation: request.historyNavigation,
- // URL list A clone of request’s URL list.
- urlList: [...request.urlList]
- })
-
- const initHasKey = Object.keys(init).length !== 0
-
- // 13. If init is not empty, then:
- if (initHasKey) {
- // 1. If request’s mode is "navigate", then set it to "same-origin".
- if (request.mode === 'navigate') {
- request.mode = 'same-origin'
- }
-
- // 2. Unset request’s reload-navigation flag.
- request.reloadNavigation = false
-
- // 3. Unset request’s history-navigation flag.
- request.historyNavigation = false
-
- // 4. Set request’s origin to "client".
- request.origin = 'client'
-
- // 5. Set request’s referrer to "client"
- request.referrer = 'client'
-
- // 6. Set request’s referrer policy to the empty string.
- request.referrerPolicy = ''
-
- // 7. Set request’s URL to request’s current URL.
- request.url = request.urlList[request.urlList.length - 1]
-
- // 8. Set request’s URL list to « request’s URL ».
- request.urlList = [request.url]
+ return `${key}<<${delimiter}${external_os_namespaceObject.EOL}${convertedValue}${external_os_namespaceObject.EOL}${delimiter}`;
+}
+//# sourceMappingURL=file-command.js.map
+// EXTERNAL MODULE: external "path"
+var external_path_ = __nccwpck_require__(6928);
+// EXTERNAL MODULE: external "http"
+var external_http_ = __nccwpck_require__(8611);
+var external_http_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(external_http_, 2);
+// EXTERNAL MODULE: external "https"
+var external_https_ = __nccwpck_require__(5692);
+var external_https_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(external_https_, 2);
+;// CONCATENATED MODULE: ./node_modules/@actions/http-client/lib/proxy.js
+function getProxyUrl(reqUrl) {
+ const usingSsl = reqUrl.protocol === 'https:';
+ if (checkBypass(reqUrl)) {
+ return undefined;
}
-
- // 14. If init["referrer"] exists, then:
- if (init.referrer !== undefined) {
- // 1. Let referrer be init["referrer"].
- const referrer = init.referrer
-
- // 2. If referrer is the empty string, then set request’s referrer to "no-referrer".
- if (referrer === '') {
- request.referrer = 'no-referrer'
- } else {
- // 1. Let parsedReferrer be the result of parsing referrer with
- // baseURL.
- // 2. If parsedReferrer is failure, then throw a TypeError.
- let parsedReferrer
+ const proxyVar = (() => {
+ if (usingSsl) {
+ return process.env['https_proxy'] || process.env['HTTPS_PROXY'];
+ }
+ else {
+ return process.env['http_proxy'] || process.env['HTTP_PROXY'];
+ }
+ })();
+ if (proxyVar) {
try {
- parsedReferrer = new URL(referrer, baseUrl)
- } catch (err) {
- throw new TypeError(`Referrer "${referrer}" is not a valid URL.`, { cause: err })
+ return new DecodedURL(proxyVar);
}
-
- // 3. If one of the following is true
- // - parsedReferrer’s scheme is "about" and path is the string "client"
- // - parsedReferrer’s origin is not same origin with origin
- // then set request’s referrer to "client".
- if (
- (parsedReferrer.protocol === 'about:' && parsedReferrer.hostname === 'client') ||
- (origin && !sameOrigin(parsedReferrer, environmentSettingsObject.settingsObject.baseUrl))
- ) {
- request.referrer = 'client'
- } else {
- // 4. Otherwise, set request’s referrer to parsedReferrer.
- request.referrer = parsedReferrer
+ catch (_a) {
+ if (!proxyVar.startsWith('http://') && !proxyVar.startsWith('https://'))
+ return new DecodedURL(`http://${proxyVar}`);
}
- }
- }
-
- // 15. If init["referrerPolicy"] exists, then set request’s referrer policy
- // to it.
- if (init.referrerPolicy !== undefined) {
- request.referrerPolicy = init.referrerPolicy
- }
-
- // 16. Let mode be init["mode"] if it exists, and fallbackMode otherwise.
- let mode
- if (init.mode !== undefined) {
- mode = init.mode
- } else {
- mode = fallbackMode
}
-
- // 17. If mode is "navigate", then throw a TypeError.
- if (mode === 'navigate') {
- throw webidl.errors.exception({
- header: 'Request constructor',
- message: 'invalid request mode navigate.'
- })
+ else {
+ return undefined;
}
-
- // 18. If mode is non-null, set request’s mode to mode.
- if (mode != null) {
- request.mode = mode
+}
+function checkBypass(reqUrl) {
+ if (!reqUrl.hostname) {
+ return false;
}
-
- // 19. If init["credentials"] exists, then set request’s credentials mode
- // to it.
- if (init.credentials !== undefined) {
- request.credentials = init.credentials
+ const reqHost = reqUrl.hostname;
+ if (isLoopbackAddress(reqHost)) {
+ return true;
}
-
- // 18. If init["cache"] exists, then set request’s cache mode to it.
- if (init.cache !== undefined) {
- request.cache = init.cache
+ const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || '';
+ if (!noProxy) {
+ return false;
}
-
- // 21. If request’s cache mode is "only-if-cached" and request’s mode is
- // not "same-origin", then throw a TypeError.
- if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {
- throw new TypeError(
- "'only-if-cached' can be set only with 'same-origin' mode"
- )
+ // Determine the request port
+ let reqPort;
+ if (reqUrl.port) {
+ reqPort = Number(reqUrl.port);
}
-
- // 22. If init["redirect"] exists, then set request’s redirect mode to it.
- if (init.redirect !== undefined) {
- request.redirect = init.redirect
+ else if (reqUrl.protocol === 'http:') {
+ reqPort = 80;
}
-
- // 23. If init["integrity"] exists, then set request’s integrity metadata to it.
- if (init.integrity != null) {
- request.integrity = String(init.integrity)
+ else if (reqUrl.protocol === 'https:') {
+ reqPort = 443;
}
-
- // 24. If init["keepalive"] exists, then set request’s keepalive to it.
- if (init.keepalive !== undefined) {
- request.keepalive = Boolean(init.keepalive)
+ // Format the request hostname and hostname with port
+ const upperReqHosts = [reqUrl.hostname.toUpperCase()];
+ if (typeof reqPort === 'number') {
+ upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`);
}
-
- // 25. If init["method"] exists, then:
- if (init.method !== undefined) {
- // 1. Let method be init["method"].
- let method = init.method
-
- const mayBeNormalized = normalizedMethodRecords[method]
-
- if (mayBeNormalized !== undefined) {
- // Note: Bypass validation DELETE, GET, HEAD, OPTIONS, POST, PUT, PATCH and these lowercase ones
- request.method = mayBeNormalized
- } else {
- // 2. If method is not a method or method is a forbidden method, then
- // throw a TypeError.
- if (!isValidHTTPToken(method)) {
- throw new TypeError(`'${method}' is not a valid HTTP method.`)
- }
-
- const upperCase = method.toUpperCase()
-
- if (forbiddenMethodsSet.has(upperCase)) {
- throw new TypeError(`'${method}' HTTP method is unsupported.`)
+ // Compare request host against noproxy
+ for (const upperNoProxyItem of noProxy
+ .split(',')
+ .map(x => x.trim().toUpperCase())
+ .filter(x => x)) {
+ if (upperNoProxyItem === '*' ||
+ upperReqHosts.some(x => x === upperNoProxyItem ||
+ x.endsWith(`.${upperNoProxyItem}`) ||
+ (upperNoProxyItem.startsWith('.') &&
+ x.endsWith(`${upperNoProxyItem}`)))) {
+ return true;
}
-
- // 3. Normalize method.
- // https://fetch.spec.whatwg.org/#concept-method-normalize
- // Note: must be in uppercase
- method = normalizedMethodRecordsBase[upperCase] ?? method
-
- // 4. Set request’s method to method.
- request.method = method
- }
-
- if (!patchMethodWarning && request.method === 'patch') {
- process.emitWarning('Using `patch` is highly likely to result in a `405 Method Not Allowed`. `PATCH` is much more likely to succeed.', {
- code: 'UNDICI-FETCH-patch'
- })
-
- patchMethodWarning = true
- }
- }
-
- // 26. If init["signal"] exists, then set signal to it.
- if (init.signal !== undefined) {
- signal = init.signal
}
-
- // 27. Set this’s request to request.
- this[kState] = request
-
- // 28. Set this’s signal to a new AbortSignal object with this’s relevant
- // Realm.
- // TODO: could this be simplified with AbortSignal.any
- // (https://dom.spec.whatwg.org/#dom-abortsignal-any)
- const ac = new AbortController()
- this[kSignal] = ac.signal
-
- // 29. If signal is not null, then make this’s signal follow signal.
- if (signal != null) {
- if (
- !signal ||
- typeof signal.aborted !== 'boolean' ||
- typeof signal.addEventListener !== 'function'
- ) {
- throw new TypeError(
- "Failed to construct 'Request': member signal is not of type AbortSignal."
- )
- }
-
- if (signal.aborted) {
- ac.abort(signal.reason)
- } else {
- // Keep a strong ref to ac while request object
- // is alive. This is needed to prevent AbortController
- // from being prematurely garbage collected.
- // See, https://github.com/nodejs/undici/issues/1926.
- this[kAbortController] = ac
-
- const acRef = new WeakRef(ac)
- const abort = buildAbort(acRef)
-
- // Third-party AbortControllers may not work with these.
- // See, https://github.com/nodejs/undici/pull/1910#issuecomment-1464495619.
- try {
- // If the max amount of listeners is equal to the default, increase it
- // This is only available in node >= v19.9.0
- if (typeof getMaxListeners === 'function' && getMaxListeners(signal) === defaultMaxListeners) {
- setMaxListeners(1500, signal)
- } else if (getEventListeners(signal, 'abort').length >= defaultMaxListeners) {
- setMaxListeners(1500, signal)
- }
- } catch {}
-
- util.addAbortListener(signal, abort)
- // The third argument must be a registry key to be unregistered.
- // Without it, you cannot unregister.
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry
- // abort is used as the unregister key. (because it is unique)
- requestFinalizer.register(ac, { signal, abort }, abort)
- }
+ return false;
+}
+function isLoopbackAddress(host) {
+ const hostLower = host.toLowerCase();
+ return (hostLower === 'localhost' ||
+ hostLower.startsWith('127.') ||
+ hostLower.startsWith('[::1]') ||
+ hostLower.startsWith('[0:0:0:0:0:0:0:1]'));
+}
+class DecodedURL extends URL {
+ constructor(url, base) {
+ super(url, base);
+ this._decodedUsername = decodeURIComponent(super.username);
+ this._decodedPassword = decodeURIComponent(super.password);
}
-
- // 30. Set this’s headers to a new Headers object with this’s relevant
- // Realm, whose header list is request’s header list and guard is
- // "request".
- this[kHeaders] = new Headers(kConstruct)
- setHeadersList(this[kHeaders], request.headersList)
- setHeadersGuard(this[kHeaders], 'request')
-
- // 31. If this’s request’s mode is "no-cors", then:
- if (mode === 'no-cors') {
- // 1. If this’s request’s method is not a CORS-safelisted method,
- // then throw a TypeError.
- if (!corsSafeListedMethodsSet.has(request.method)) {
- throw new TypeError(
- `'${request.method} is unsupported in no-cors mode.`
- )
- }
-
- // 2. Set this’s headers’s guard to "request-no-cors".
- setHeadersGuard(this[kHeaders], 'request-no-cors')
+ get username() {
+ return this._decodedUsername;
}
-
- // 32. If init is not empty, then:
- if (initHasKey) {
- /** @type {HeadersList} */
- const headersList = getHeadersList(this[kHeaders])
- // 1. Let headers be a copy of this’s headers and its associated header
- // list.
- // 2. If init["headers"] exists, then set headers to init["headers"].
- const headers = init.headers !== undefined ? init.headers : new HeadersList(headersList)
-
- // 3. Empty this’s headers’s header list.
- headersList.clear()
-
- // 4. If headers is a Headers object, then for each header in its header
- // list, append header’s name/header’s value to this’s headers.
- if (headers instanceof HeadersList) {
- for (const { name, value } of headers.rawValues()) {
- headersList.append(name, value, false)
- }
- // Note: Copy the `set-cookie` meta-data.
- headersList.cookies = headers.cookies
- } else {
- // 5. Otherwise, fill this’s headers with headers.
- fillHeaders(this[kHeaders], headers)
- }
+ get password() {
+ return this._decodedPassword;
}
+}
+//# sourceMappingURL=proxy.js.map
+// EXTERNAL MODULE: ./node_modules/tunnel/index.js
+var tunnel = __nccwpck_require__(770);
+// EXTERNAL MODULE: ./node_modules/undici/index.js
+var undici = __nccwpck_require__(6752);
+;// CONCATENATED MODULE: ./node_modules/@actions/http-client/lib/index.js
+/* eslint-disable @typescript-eslint/no-explicit-any */
+var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
- // 33. Let inputBody be input’s request’s body if input is a Request
- // object; otherwise null.
- const inputBody = input instanceof Request ? input[kState].body : null
- // 34. If either init["body"] exists and is non-null or inputBody is
- // non-null, and request’s method is `GET` or `HEAD`, then throw a
- // TypeError.
- if (
- (init.body != null || inputBody != null) &&
- (request.method === 'GET' || request.method === 'HEAD')
- ) {
- throw new TypeError('Request with GET/HEAD method cannot have body.')
- }
- // 35. Let initBody be null.
- let initBody = null
- // 36. If init["body"] exists and is non-null, then:
- if (init.body != null) {
- // 1. Let Content-Type be null.
- // 2. Set initBody and Content-Type to the result of extracting
- // init["body"], with keepalive set to request’s keepalive.
- const [extractedBody, contentType] = extractBody(
- init.body,
- request.keepalive
- )
- initBody = extractedBody
- // 3, If Content-Type is non-null and this’s headers’s header list does
- // not contain `Content-Type`, then append `Content-Type`/Content-Type to
- // this’s headers.
- if (contentType && !getHeadersList(this[kHeaders]).contains('content-type', true)) {
- this[kHeaders].append('content-type', contentType)
- }
+var HttpCodes;
+(function (HttpCodes) {
+ HttpCodes[HttpCodes["OK"] = 200] = "OK";
+ HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices";
+ HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently";
+ HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved";
+ HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther";
+ HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified";
+ HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy";
+ HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy";
+ HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect";
+ HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect";
+ HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest";
+ HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized";
+ HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired";
+ HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden";
+ HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound";
+ HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed";
+ HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable";
+ HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired";
+ HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout";
+ HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict";
+ HttpCodes[HttpCodes["Gone"] = 410] = "Gone";
+ HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests";
+ HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError";
+ HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented";
+ HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway";
+ HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable";
+ HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout";
+})(HttpCodes || (HttpCodes = {}));
+var Headers;
+(function (Headers) {
+ Headers["Accept"] = "accept";
+ Headers["ContentType"] = "content-type";
+})(Headers || (Headers = {}));
+var MediaTypes;
+(function (MediaTypes) {
+ MediaTypes["ApplicationJson"] = "application/json";
+})(MediaTypes || (MediaTypes = {}));
+/**
+ * Returns the proxy URL, depending upon the supplied url and proxy environment variables.
+ * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com
+ */
+function lib_getProxyUrl(serverUrl) {
+ const proxyUrl = pm.getProxyUrl(new URL(serverUrl));
+ return proxyUrl ? proxyUrl.href : '';
+}
+const HttpRedirectCodes = [
+ HttpCodes.MovedPermanently,
+ HttpCodes.ResourceMoved,
+ HttpCodes.SeeOther,
+ HttpCodes.TemporaryRedirect,
+ HttpCodes.PermanentRedirect
+];
+const HttpResponseRetryCodes = [
+ HttpCodes.BadGateway,
+ HttpCodes.ServiceUnavailable,
+ HttpCodes.GatewayTimeout
+];
+const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD'];
+const ExponentialBackoffCeiling = 10;
+const ExponentialBackoffTimeSlice = 5;
+class lib_HttpClientError extends Error {
+ constructor(message, statusCode) {
+ super(message);
+ this.name = 'HttpClientError';
+ this.statusCode = statusCode;
+ Object.setPrototypeOf(this, lib_HttpClientError.prototype);
}
-
- // 37. Let inputOrInitBody be initBody if it is non-null; otherwise
- // inputBody.
- const inputOrInitBody = initBody ?? inputBody
-
- // 38. If inputOrInitBody is non-null and inputOrInitBody’s source is
- // null, then:
- if (inputOrInitBody != null && inputOrInitBody.source == null) {
- // 1. If initBody is non-null and init["duplex"] does not exist,
- // then throw a TypeError.
- if (initBody != null && init.duplex == null) {
- throw new TypeError('RequestInit: duplex option is required when sending a body.')
- }
-
- // 2. If this’s request’s mode is neither "same-origin" nor "cors",
- // then throw a TypeError.
- if (request.mode !== 'same-origin' && request.mode !== 'cors') {
- throw new TypeError(
- 'If request is made from ReadableStream, mode should be "same-origin" or "cors"'
- )
- }
-
- // 3. Set this’s request’s use-CORS-preflight flag.
- request.useCORSPreflightFlag = true
+}
+class HttpClientResponse {
+ constructor(message) {
+ this.message = message;
}
-
- // 39. Let finalBody be inputOrInitBody.
- let finalBody = inputOrInitBody
-
- // 40. If initBody is null and inputBody is non-null, then:
- if (initBody == null && inputBody != null) {
- // 1. If input is unusable, then throw a TypeError.
- if (bodyUnusable(input)) {
- throw new TypeError(
- 'Cannot construct a Request with a Request object that has already been used.'
- )
- }
-
- // 2. Set finalBody to the result of creating a proxy for inputBody.
- // https://streams.spec.whatwg.org/#readablestream-create-a-proxy
- const identityTransform = new TransformStream()
- inputBody.stream.pipeThrough(identityTransform)
- finalBody = {
- source: inputBody.source,
- length: inputBody.length,
- stream: identityTransform.readable
- }
+ readBody() {
+ return __awaiter(this, void 0, void 0, function* () {
+ return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {
+ let output = Buffer.alloc(0);
+ this.message.on('data', (chunk) => {
+ output = Buffer.concat([output, chunk]);
+ });
+ this.message.on('end', () => {
+ resolve(output.toString());
+ });
+ }));
+ });
}
-
- // 41. Set this’s request’s body to finalBody.
- this[kState].body = finalBody
- }
-
- // Returns request’s HTTP method, which is "GET" by default.
- get method () {
- webidl.brandCheck(this, Request)
-
- // The method getter steps are to return this’s request’s method.
- return this[kState].method
- }
-
- // Returns the URL of request as a string.
- get url () {
- webidl.brandCheck(this, Request)
-
- // The url getter steps are to return this’s request’s URL, serialized.
- return URLSerializer(this[kState].url)
- }
-
- // Returns a Headers object consisting of the headers associated with request.
- // Note that headers added in the network layer by the user agent will not
- // be accounted for in this object, e.g., the "Host" header.
- get headers () {
- webidl.brandCheck(this, Request)
-
- // The headers getter steps are to return this’s headers.
- return this[kHeaders]
- }
-
- // Returns the kind of resource requested by request, e.g., "document"
- // or "script".
- get destination () {
- webidl.brandCheck(this, Request)
-
- // The destination getter are to return this’s request’s destination.
- return this[kState].destination
- }
-
- // Returns the referrer of request. Its value can be a same-origin URL if
- // explicitly set in init, the empty string to indicate no referrer, and
- // "about:client" when defaulting to the global’s default. This is used
- // during fetching to determine the value of the `Referer` header of the
- // request being made.
- get referrer () {
- webidl.brandCheck(this, Request)
-
- // 1. If this’s request’s referrer is "no-referrer", then return the
- // empty string.
- if (this[kState].referrer === 'no-referrer') {
- return ''
+ readBodyBuffer() {
+ return __awaiter(this, void 0, void 0, function* () {
+ return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {
+ const chunks = [];
+ this.message.on('data', (chunk) => {
+ chunks.push(chunk);
+ });
+ this.message.on('end', () => {
+ resolve(Buffer.concat(chunks));
+ });
+ }));
+ });
}
-
- // 2. If this’s request’s referrer is "client", then return
- // "about:client".
- if (this[kState].referrer === 'client') {
- return 'about:client'
+}
+function isHttps(requestUrl) {
+ const parsedUrl = new URL(requestUrl);
+ return parsedUrl.protocol === 'https:';
+}
+class lib_HttpClient {
+ constructor(userAgent, handlers, requestOptions) {
+ this._ignoreSslError = false;
+ this._allowRedirects = true;
+ this._allowRedirectDowngrade = false;
+ this._maxRedirects = 50;
+ this._allowRetries = false;
+ this._maxRetries = 1;
+ this._keepAlive = false;
+ this._disposed = false;
+ this.userAgent = this._getUserAgentWithOrchestrationId(userAgent);
+ this.handlers = handlers || [];
+ this.requestOptions = requestOptions;
+ if (requestOptions) {
+ if (requestOptions.ignoreSslError != null) {
+ this._ignoreSslError = requestOptions.ignoreSslError;
+ }
+ this._socketTimeout = requestOptions.socketTimeout;
+ if (requestOptions.allowRedirects != null) {
+ this._allowRedirects = requestOptions.allowRedirects;
+ }
+ if (requestOptions.allowRedirectDowngrade != null) {
+ this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade;
+ }
+ if (requestOptions.maxRedirects != null) {
+ this._maxRedirects = Math.max(requestOptions.maxRedirects, 0);
+ }
+ if (requestOptions.keepAlive != null) {
+ this._keepAlive = requestOptions.keepAlive;
+ }
+ if (requestOptions.allowRetries != null) {
+ this._allowRetries = requestOptions.allowRetries;
+ }
+ if (requestOptions.maxRetries != null) {
+ this._maxRetries = requestOptions.maxRetries;
+ }
+ }
}
-
- // Return this’s request’s referrer, serialized.
- return this[kState].referrer.toString()
- }
-
- // Returns the referrer policy associated with request.
- // This is used during fetching to compute the value of the request’s
- // referrer.
- get referrerPolicy () {
- webidl.brandCheck(this, Request)
-
- // The referrerPolicy getter steps are to return this’s request’s referrer policy.
- return this[kState].referrerPolicy
- }
-
- // Returns the mode associated with request, which is a string indicating
- // whether the request will use CORS, or will be restricted to same-origin
- // URLs.
- get mode () {
- webidl.brandCheck(this, Request)
-
- // The mode getter steps are to return this’s request’s mode.
- return this[kState].mode
- }
-
- // Returns the credentials mode associated with request,
- // which is a string indicating whether credentials will be sent with the
- // request always, never, or only when sent to a same-origin URL.
- get credentials () {
- // The credentials getter steps are to return this’s request’s credentials mode.
- return this[kState].credentials
- }
-
- // Returns the cache mode associated with request,
- // which is a string indicating how the request will
- // interact with the browser’s cache when fetching.
- get cache () {
- webidl.brandCheck(this, Request)
-
- // The cache getter steps are to return this’s request’s cache mode.
- return this[kState].cache
- }
-
- // Returns the redirect mode associated with request,
- // which is a string indicating how redirects for the
- // request will be handled during fetching. A request
- // will follow redirects by default.
- get redirect () {
- webidl.brandCheck(this, Request)
-
- // The redirect getter steps are to return this’s request’s redirect mode.
- return this[kState].redirect
- }
-
- // Returns request’s subresource integrity metadata, which is a
- // cryptographic hash of the resource being fetched. Its value
- // consists of multiple hashes separated by whitespace. [SRI]
- get integrity () {
- webidl.brandCheck(this, Request)
-
- // The integrity getter steps are to return this’s request’s integrity
- // metadata.
- return this[kState].integrity
- }
-
- // Returns a boolean indicating whether or not request can outlive the
- // global in which it was created.
- get keepalive () {
- webidl.brandCheck(this, Request)
-
- // The keepalive getter steps are to return this’s request’s keepalive.
- return this[kState].keepalive
- }
-
- // Returns a boolean indicating whether or not request is for a reload
- // navigation.
- get isReloadNavigation () {
- webidl.brandCheck(this, Request)
-
- // The isReloadNavigation getter steps are to return true if this’s
- // request’s reload-navigation flag is set; otherwise false.
- return this[kState].reloadNavigation
- }
-
- // Returns a boolean indicating whether or not request is for a history
- // navigation (a.k.a. back-forward navigation).
- get isHistoryNavigation () {
- webidl.brandCheck(this, Request)
-
- // The isHistoryNavigation getter steps are to return true if this’s request’s
- // history-navigation flag is set; otherwise false.
- return this[kState].historyNavigation
- }
-
- // Returns the signal associated with request, which is an AbortSignal
- // object indicating whether or not request has been aborted, and its
- // abort event handler.
- get signal () {
- webidl.brandCheck(this, Request)
-
- // The signal getter steps are to return this’s signal.
- return this[kSignal]
- }
-
- get body () {
- webidl.brandCheck(this, Request)
-
- return this[kState].body ? this[kState].body.stream : null
- }
-
- get bodyUsed () {
- webidl.brandCheck(this, Request)
-
- return !!this[kState].body && util.isDisturbed(this[kState].body.stream)
- }
-
- get duplex () {
- webidl.brandCheck(this, Request)
-
- return 'half'
- }
-
- // Returns a clone of request.
- clone () {
- webidl.brandCheck(this, Request)
-
- // 1. If this is unusable, then throw a TypeError.
- if (bodyUnusable(this)) {
- throw new TypeError('unusable')
+ options(requestUrl, additionalHeaders) {
+ return __awaiter(this, void 0, void 0, function* () {
+ return this.request('OPTIONS', requestUrl, null, additionalHeaders || {});
+ });
}
-
- // 2. Let clonedRequest be the result of cloning this’s request.
- const clonedRequest = cloneRequest(this[kState])
-
- // 3. Let clonedRequestObject be the result of creating a Request object,
- // given clonedRequest, this’s headers’s guard, and this’s relevant Realm.
- // 4. Make clonedRequestObject’s signal follow this’s signal.
- const ac = new AbortController()
- if (this.signal.aborted) {
- ac.abort(this.signal.reason)
- } else {
- let list = dependentControllerMap.get(this.signal)
- if (list === undefined) {
- list = new Set()
- dependentControllerMap.set(this.signal, list)
- }
- const acRef = new WeakRef(ac)
- list.add(acRef)
- util.addAbortListener(
- ac.signal,
- buildAbort(acRef)
- )
+ get(requestUrl, additionalHeaders) {
+ return __awaiter(this, void 0, void 0, function* () {
+ return this.request('GET', requestUrl, null, additionalHeaders || {});
+ });
}
-
- // 4. Return clonedRequestObject.
- return fromInnerRequest(clonedRequest, ac.signal, getHeadersGuard(this[kHeaders]))
- }
-
- [nodeUtil.inspect.custom] (depth, options) {
- if (options.depth === null) {
- options.depth = 2
+ del(requestUrl, additionalHeaders) {
+ return __awaiter(this, void 0, void 0, function* () {
+ return this.request('DELETE', requestUrl, null, additionalHeaders || {});
+ });
}
-
- options.colors ??= true
-
- const properties = {
- method: this.method,
- url: this.url,
- headers: this.headers,
- destination: this.destination,
- referrer: this.referrer,
- referrerPolicy: this.referrerPolicy,
- mode: this.mode,
- credentials: this.credentials,
- cache: this.cache,
- redirect: this.redirect,
- integrity: this.integrity,
- keepalive: this.keepalive,
- isReloadNavigation: this.isReloadNavigation,
- isHistoryNavigation: this.isHistoryNavigation,
- signal: this.signal
+ post(requestUrl, data, additionalHeaders) {
+ return __awaiter(this, void 0, void 0, function* () {
+ return this.request('POST', requestUrl, data, additionalHeaders || {});
+ });
}
-
- return `Request ${nodeUtil.formatWithOptions(options, properties)}`
- }
-}
-
-mixinBody(Request)
-
-// https://fetch.spec.whatwg.org/#requests
-function makeRequest (init) {
- return {
- method: init.method ?? 'GET',
- localURLsOnly: init.localURLsOnly ?? false,
- unsafeRequest: init.unsafeRequest ?? false,
- body: init.body ?? null,
- client: init.client ?? null,
- reservedClient: init.reservedClient ?? null,
- replacesClientId: init.replacesClientId ?? '',
- window: init.window ?? 'client',
- keepalive: init.keepalive ?? false,
- serviceWorkers: init.serviceWorkers ?? 'all',
- initiator: init.initiator ?? '',
- destination: init.destination ?? '',
- priority: init.priority ?? null,
- origin: init.origin ?? 'client',
- policyContainer: init.policyContainer ?? 'client',
- referrer: init.referrer ?? 'client',
- referrerPolicy: init.referrerPolicy ?? '',
- mode: init.mode ?? 'no-cors',
- useCORSPreflightFlag: init.useCORSPreflightFlag ?? false,
- credentials: init.credentials ?? 'same-origin',
- useCredentials: init.useCredentials ?? false,
- cache: init.cache ?? 'default',
- redirect: init.redirect ?? 'follow',
- integrity: init.integrity ?? '',
- cryptoGraphicsNonceMetadata: init.cryptoGraphicsNonceMetadata ?? '',
- parserMetadata: init.parserMetadata ?? '',
- reloadNavigation: init.reloadNavigation ?? false,
- historyNavigation: init.historyNavigation ?? false,
- userActivation: init.userActivation ?? false,
- taintedOrigin: init.taintedOrigin ?? false,
- redirectCount: init.redirectCount ?? 0,
- responseTainting: init.responseTainting ?? 'basic',
- preventNoCacheCacheControlHeaderModification: init.preventNoCacheCacheControlHeaderModification ?? false,
- done: init.done ?? false,
- timingAllowFailed: init.timingAllowFailed ?? false,
- urlList: init.urlList,
- url: init.urlList[0],
- headersList: init.headersList
- ? new HeadersList(init.headersList)
- : new HeadersList()
- }
-}
-
-// https://fetch.spec.whatwg.org/#concept-request-clone
-function cloneRequest (request) {
- // To clone a request request, run these steps:
-
- // 1. Let newRequest be a copy of request, except for its body.
- const newRequest = makeRequest({ ...request, body: null })
-
- // 2. If request’s body is non-null, set newRequest’s body to the
- // result of cloning request’s body.
- if (request.body != null) {
- newRequest.body = cloneBody(newRequest, request.body)
- }
-
- // 3. Return newRequest.
- return newRequest
-}
-
-/**
- * @see https://fetch.spec.whatwg.org/#request-create
- * @param {any} innerRequest
- * @param {AbortSignal} signal
- * @param {'request' | 'immutable' | 'request-no-cors' | 'response' | 'none'} guard
- * @returns {Request}
- */
-function fromInnerRequest (innerRequest, signal, guard) {
- const request = new Request(kConstruct)
- request[kState] = innerRequest
- request[kSignal] = signal
- request[kHeaders] = new Headers(kConstruct)
- setHeadersList(request[kHeaders], innerRequest.headersList)
- setHeadersGuard(request[kHeaders], guard)
- return request
-}
-
-Object.defineProperties(Request.prototype, {
- method: kEnumerableProperty,
- url: kEnumerableProperty,
- headers: kEnumerableProperty,
- redirect: kEnumerableProperty,
- clone: kEnumerableProperty,
- signal: kEnumerableProperty,
- duplex: kEnumerableProperty,
- destination: kEnumerableProperty,
- body: kEnumerableProperty,
- bodyUsed: kEnumerableProperty,
- isHistoryNavigation: kEnumerableProperty,
- isReloadNavigation: kEnumerableProperty,
- keepalive: kEnumerableProperty,
- integrity: kEnumerableProperty,
- cache: kEnumerableProperty,
- credentials: kEnumerableProperty,
- attribute: kEnumerableProperty,
- referrerPolicy: kEnumerableProperty,
- referrer: kEnumerableProperty,
- mode: kEnumerableProperty,
- [Symbol.toStringTag]: {
- value: 'Request',
- configurable: true
- }
-})
-
-webidl.converters.Request = webidl.interfaceConverter(
- Request
-)
-
-// https://fetch.spec.whatwg.org/#requestinfo
-webidl.converters.RequestInfo = function (V, prefix, argument) {
- if (typeof V === 'string') {
- return webidl.converters.USVString(V, prefix, argument)
- }
-
- if (V instanceof Request) {
- return webidl.converters.Request(V, prefix, argument)
- }
-
- return webidl.converters.USVString(V, prefix, argument)
-}
-
-webidl.converters.AbortSignal = webidl.interfaceConverter(
- AbortSignal
-)
-
-// https://fetch.spec.whatwg.org/#requestinit
-webidl.converters.RequestInit = webidl.dictionaryConverter([
- {
- key: 'method',
- converter: webidl.converters.ByteString
- },
- {
- key: 'headers',
- converter: webidl.converters.HeadersInit
- },
- {
- key: 'body',
- converter: webidl.nullableConverter(
- webidl.converters.BodyInit
- )
- },
- {
- key: 'referrer',
- converter: webidl.converters.USVString
- },
- {
- key: 'referrerPolicy',
- converter: webidl.converters.DOMString,
- // https://w3c.github.io/webappsec-referrer-policy/#referrer-policy
- allowedValues: referrerPolicy
- },
- {
- key: 'mode',
- converter: webidl.converters.DOMString,
- // https://fetch.spec.whatwg.org/#concept-request-mode
- allowedValues: requestMode
- },
- {
- key: 'credentials',
- converter: webidl.converters.DOMString,
- // https://fetch.spec.whatwg.org/#requestcredentials
- allowedValues: requestCredentials
- },
- {
- key: 'cache',
- converter: webidl.converters.DOMString,
- // https://fetch.spec.whatwg.org/#requestcache
- allowedValues: requestCache
- },
- {
- key: 'redirect',
- converter: webidl.converters.DOMString,
- // https://fetch.spec.whatwg.org/#requestredirect
- allowedValues: requestRedirect
- },
- {
- key: 'integrity',
- converter: webidl.converters.DOMString
- },
- {
- key: 'keepalive',
- converter: webidl.converters.boolean
- },
- {
- key: 'signal',
- converter: webidl.nullableConverter(
- (signal) => webidl.converters.AbortSignal(
- signal,
- 'RequestInit',
- 'signal',
- { strict: false }
- )
- )
- },
- {
- key: 'window',
- converter: webidl.converters.any
- },
- {
- key: 'duplex',
- converter: webidl.converters.DOMString,
- allowedValues: requestDuplex
- },
- {
- key: 'dispatcher', // undici specific option
- converter: webidl.converters.any
- }
-])
-
-module.exports = { Request, makeRequest, fromInnerRequest, cloneRequest }
-
-
-/***/ }),
-
-/***/ 9107:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const { Headers, HeadersList, fill, getHeadersGuard, setHeadersGuard, setHeadersList } = __nccwpck_require__(3676)
-const { extractBody, cloneBody, mixinBody, hasFinalizationRegistry, streamRegistry, bodyUnusable } = __nccwpck_require__(8900)
-const util = __nccwpck_require__(1544)
-const nodeUtil = __nccwpck_require__(7975)
-const { kEnumerableProperty } = util
-const {
- isValidReasonPhrase,
- isCancelled,
- isAborted,
- isBlobLike,
- serializeJavascriptValueToJSONString,
- isErrorLike,
- isomorphicEncode,
- environmentSettingsObject: relevantRealm
-} = __nccwpck_require__(4296)
-const {
- redirectStatusSet,
- nullBodyStatus
-} = __nccwpck_require__(1207)
-const { kState, kHeaders } = __nccwpck_require__(4883)
-const { webidl } = __nccwpck_require__(253)
-const { FormData } = __nccwpck_require__(9662)
-const { URLSerializer } = __nccwpck_require__(980)
-const { kConstruct } = __nccwpck_require__(9411)
-const assert = __nccwpck_require__(4589)
-const { types } = __nccwpck_require__(7975)
-
-const textEncoder = new TextEncoder('utf-8')
-
-// https://fetch.spec.whatwg.org/#response-class
-class Response {
- // Creates network error Response.
- static error () {
- // The static error() method steps are to return the result of creating a
- // Response object, given a new network error, "immutable", and this’s
- // relevant Realm.
- const responseObject = fromInnerResponse(makeNetworkError(), 'immutable')
-
- return responseObject
- }
-
- // https://fetch.spec.whatwg.org/#dom-response-json
- static json (data, init = {}) {
- webidl.argumentLengthCheck(arguments, 1, 'Response.json')
-
- if (init !== null) {
- init = webidl.converters.ResponseInit(init)
- }
-
- // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data.
- const bytes = textEncoder.encode(
- serializeJavascriptValueToJSONString(data)
- )
-
- // 2. Let body be the result of extracting bytes.
- const body = extractBody(bytes)
-
- // 3. Let responseObject be the result of creating a Response object, given a new response,
- // "response", and this’s relevant Realm.
- const responseObject = fromInnerResponse(makeResponse({}), 'response')
-
- // 4. Perform initialize a response given responseObject, init, and (body, "application/json").
- initializeResponse(responseObject, init, { body: body[0], type: 'application/json' })
-
- // 5. Return responseObject.
- return responseObject
- }
-
- // Creates a redirect Response that redirects to url with status status.
- static redirect (url, status = 302) {
- webidl.argumentLengthCheck(arguments, 1, 'Response.redirect')
-
- url = webidl.converters.USVString(url)
- status = webidl.converters['unsigned short'](status)
-
- // 1. Let parsedURL be the result of parsing url with current settings
- // object’s API base URL.
- // 2. If parsedURL is failure, then throw a TypeError.
- // TODO: base-URL?
- let parsedURL
- try {
- parsedURL = new URL(url, relevantRealm.settingsObject.baseUrl)
- } catch (err) {
- throw new TypeError(`Failed to parse URL from ${url}`, { cause: err })
- }
-
- // 3. If status is not a redirect status, then throw a RangeError.
- if (!redirectStatusSet.has(status)) {
- throw new RangeError(`Invalid status code ${status}`)
- }
-
- // 4. Let responseObject be the result of creating a Response object,
- // given a new response, "immutable", and this’s relevant Realm.
- const responseObject = fromInnerResponse(makeResponse({}), 'immutable')
-
- // 5. Set responseObject’s response’s status to status.
- responseObject[kState].status = status
-
- // 6. Let value be parsedURL, serialized and isomorphic encoded.
- const value = isomorphicEncode(URLSerializer(parsedURL))
-
- // 7. Append `Location`/value to responseObject’s response’s header list.
- responseObject[kState].headersList.append('location', value, true)
-
- // 8. Return responseObject.
- return responseObject
- }
-
- // https://fetch.spec.whatwg.org/#dom-response
- constructor (body = null, init = {}) {
- webidl.util.markAsUncloneable(this)
- if (body === kConstruct) {
- return
+ patch(requestUrl, data, additionalHeaders) {
+ return __awaiter(this, void 0, void 0, function* () {
+ return this.request('PATCH', requestUrl, data, additionalHeaders || {});
+ });
}
-
- if (body !== null) {
- body = webidl.converters.BodyInit(body)
+ put(requestUrl, data, additionalHeaders) {
+ return __awaiter(this, void 0, void 0, function* () {
+ return this.request('PUT', requestUrl, data, additionalHeaders || {});
+ });
}
-
- init = webidl.converters.ResponseInit(init)
-
- // 1. Set this’s response to a new response.
- this[kState] = makeResponse({})
-
- // 2. Set this’s headers to a new Headers object with this’s relevant
- // Realm, whose header list is this’s response’s header list and guard
- // is "response".
- this[kHeaders] = new Headers(kConstruct)
- setHeadersGuard(this[kHeaders], 'response')
- setHeadersList(this[kHeaders], this[kState].headersList)
-
- // 3. Let bodyWithType be null.
- let bodyWithType = null
-
- // 4. If body is non-null, then set bodyWithType to the result of extracting body.
- if (body != null) {
- const [extractedBody, type] = extractBody(body)
- bodyWithType = { body: extractedBody, type }
+ head(requestUrl, additionalHeaders) {
+ return __awaiter(this, void 0, void 0, function* () {
+ return this.request('HEAD', requestUrl, null, additionalHeaders || {});
+ });
}
-
- // 5. Perform initialize a response given this, init, and bodyWithType.
- initializeResponse(this, init, bodyWithType)
- }
-
- // Returns response’s type, e.g., "cors".
- get type () {
- webidl.brandCheck(this, Response)
-
- // The type getter steps are to return this’s response’s type.
- return this[kState].type
- }
-
- // Returns response’s URL, if it has one; otherwise the empty string.
- get url () {
- webidl.brandCheck(this, Response)
-
- const urlList = this[kState].urlList
-
- // The url getter steps are to return the empty string if this’s
- // response’s URL is null; otherwise this’s response’s URL,
- // serialized with exclude fragment set to true.
- const url = urlList[urlList.length - 1] ?? null
-
- if (url === null) {
- return ''
+ sendStream(verb, requestUrl, stream, additionalHeaders) {
+ return __awaiter(this, void 0, void 0, function* () {
+ return this.request(verb, requestUrl, stream, additionalHeaders);
+ });
}
-
- return URLSerializer(url, true)
- }
-
- // Returns whether response was obtained through a redirect.
- get redirected () {
- webidl.brandCheck(this, Response)
-
- // The redirected getter steps are to return true if this’s response’s URL
- // list has more than one item; otherwise false.
- return this[kState].urlList.length > 1
- }
-
- // Returns response’s status.
- get status () {
- webidl.brandCheck(this, Response)
-
- // The status getter steps are to return this’s response’s status.
- return this[kState].status
- }
-
- // Returns whether response’s status is an ok status.
- get ok () {
- webidl.brandCheck(this, Response)
-
- // The ok getter steps are to return true if this’s response’s status is an
- // ok status; otherwise false.
- return this[kState].status >= 200 && this[kState].status <= 299
- }
-
- // Returns response’s status message.
- get statusText () {
- webidl.brandCheck(this, Response)
-
- // The statusText getter steps are to return this’s response’s status
- // message.
- return this[kState].statusText
- }
-
- // Returns response’s headers as Headers.
- get headers () {
- webidl.brandCheck(this, Response)
-
- // The headers getter steps are to return this’s headers.
- return this[kHeaders]
- }
-
- get body () {
- webidl.brandCheck(this, Response)
-
- return this[kState].body ? this[kState].body.stream : null
- }
-
- get bodyUsed () {
- webidl.brandCheck(this, Response)
-
- return !!this[kState].body && util.isDisturbed(this[kState].body.stream)
- }
-
- // Returns a clone of response.
- clone () {
- webidl.brandCheck(this, Response)
-
- // 1. If this is unusable, then throw a TypeError.
- if (bodyUnusable(this)) {
- throw webidl.errors.exception({
- header: 'Response.clone',
- message: 'Body has already been consumed.'
- })
+ /**
+ * Gets a typed object from an endpoint
+ * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise
+ */
+ getJson(requestUrl_1) {
+ return __awaiter(this, arguments, void 0, function* (requestUrl, additionalHeaders = {}) {
+ additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+ const res = yield this.get(requestUrl, additionalHeaders);
+ return this._processResponse(res, this.requestOptions);
+ });
}
-
- // 2. Let clonedResponse be the result of cloning this’s response.
- const clonedResponse = cloneResponse(this[kState])
-
- // Note: To re-register because of a new stream.
- if (hasFinalizationRegistry && this[kState].body?.stream) {
- streamRegistry.register(this, new WeakRef(this[kState].body.stream))
+ postJson(requestUrl_1, obj_1) {
+ return __awaiter(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) {
+ const data = JSON.stringify(obj, null, 2);
+ additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+ additionalHeaders[Headers.ContentType] =
+ this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson);
+ const res = yield this.post(requestUrl, data, additionalHeaders);
+ return this._processResponse(res, this.requestOptions);
+ });
}
-
- // 3. Return the result of creating a Response object, given
- // clonedResponse, this’s headers’s guard, and this’s relevant Realm.
- return fromInnerResponse(clonedResponse, getHeadersGuard(this[kHeaders]))
- }
-
- [nodeUtil.inspect.custom] (depth, options) {
- if (options.depth === null) {
- options.depth = 2
+ putJson(requestUrl_1, obj_1) {
+ return __awaiter(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) {
+ const data = JSON.stringify(obj, null, 2);
+ additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+ additionalHeaders[Headers.ContentType] =
+ this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson);
+ const res = yield this.put(requestUrl, data, additionalHeaders);
+ return this._processResponse(res, this.requestOptions);
+ });
}
-
- options.colors ??= true
-
- const properties = {
- status: this.status,
- statusText: this.statusText,
- headers: this.headers,
- body: this.body,
- bodyUsed: this.bodyUsed,
- ok: this.ok,
- redirected: this.redirected,
- type: this.type,
- url: this.url
+ patchJson(requestUrl_1, obj_1) {
+ return __awaiter(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) {
+ const data = JSON.stringify(obj, null, 2);
+ additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
+ additionalHeaders[Headers.ContentType] =
+ this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson);
+ const res = yield this.patch(requestUrl, data, additionalHeaders);
+ return this._processResponse(res, this.requestOptions);
+ });
}
-
- return `Response ${nodeUtil.formatWithOptions(options, properties)}`
- }
-}
-
-mixinBody(Response)
-
-Object.defineProperties(Response.prototype, {
- type: kEnumerableProperty,
- url: kEnumerableProperty,
- status: kEnumerableProperty,
- ok: kEnumerableProperty,
- redirected: kEnumerableProperty,
- statusText: kEnumerableProperty,
- headers: kEnumerableProperty,
- clone: kEnumerableProperty,
- body: kEnumerableProperty,
- bodyUsed: kEnumerableProperty,
- [Symbol.toStringTag]: {
- value: 'Response',
- configurable: true
- }
-})
-
-Object.defineProperties(Response, {
- json: kEnumerableProperty,
- redirect: kEnumerableProperty,
- error: kEnumerableProperty
-})
-
-// https://fetch.spec.whatwg.org/#concept-response-clone
-function cloneResponse (response) {
- // To clone a response response, run these steps:
-
- // 1. If response is a filtered response, then return a new identical
- // filtered response whose internal response is a clone of response’s
- // internal response.
- if (response.internalResponse) {
- return filterResponse(
- cloneResponse(response.internalResponse),
- response.type
- )
- }
-
- // 2. Let newResponse be a copy of response, except for its body.
- const newResponse = makeResponse({ ...response, body: null })
-
- // 3. If response’s body is non-null, then set newResponse’s body to the
- // result of cloning response’s body.
- if (response.body != null) {
- newResponse.body = cloneBody(newResponse, response.body)
- }
-
- // 4. Return newResponse.
- return newResponse
-}
-
-function makeResponse (init) {
- return {
- aborted: false,
- rangeRequested: false,
- timingAllowPassed: false,
- requestIncludesCredentials: false,
- type: 'default',
- status: 200,
- timingInfo: null,
- cacheState: '',
- statusText: '',
- ...init,
- headersList: init?.headersList
- ? new HeadersList(init?.headersList)
- : new HeadersList(),
- urlList: init?.urlList ? [...init.urlList] : []
- }
-}
-
-function makeNetworkError (reason) {
- const isError = isErrorLike(reason)
- return makeResponse({
- type: 'error',
- status: 0,
- error: isError
- ? reason
- : new Error(reason ? String(reason) : reason),
- aborted: reason && reason.name === 'AbortError'
- })
-}
-
-// @see https://fetch.spec.whatwg.org/#concept-network-error
-function isNetworkError (response) {
- return (
- // A network error is a response whose type is "error",
- response.type === 'error' &&
- // status is 0
- response.status === 0
- )
-}
-
-function makeFilteredResponse (response, state) {
- state = {
- internalResponse: response,
- ...state
- }
-
- return new Proxy(response, {
- get (target, p) {
- return p in state ? state[p] : target[p]
- },
- set (target, p, value) {
- assert(!(p in state))
- target[p] = value
- return true
+ /**
+ * Makes a raw http request.
+ * All other methods such as get, post, patch, and request ultimately call this.
+ * Prefer get, del, post and patch
+ */
+ request(verb, requestUrl, data, headers) {
+ return __awaiter(this, void 0, void 0, function* () {
+ if (this._disposed) {
+ throw new Error('Client has already been disposed.');
+ }
+ const parsedUrl = new URL(requestUrl);
+ let info = this._prepareRequest(verb, parsedUrl, headers);
+ // Only perform retries on reads since writes may not be idempotent.
+ const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb)
+ ? this._maxRetries + 1
+ : 1;
+ let numTries = 0;
+ let response;
+ do {
+ response = yield this.requestRaw(info, data);
+ // Check if it's an authentication challenge
+ if (response &&
+ response.message &&
+ response.message.statusCode === HttpCodes.Unauthorized) {
+ let authenticationHandler;
+ for (const handler of this.handlers) {
+ if (handler.canHandleAuthentication(response)) {
+ authenticationHandler = handler;
+ break;
+ }
+ }
+ if (authenticationHandler) {
+ return authenticationHandler.handleAuthentication(this, info, data);
+ }
+ else {
+ // We have received an unauthorized response but have no handlers to handle it.
+ // Let the response return to the caller.
+ return response;
+ }
+ }
+ let redirectsRemaining = this._maxRedirects;
+ while (response.message.statusCode &&
+ HttpRedirectCodes.includes(response.message.statusCode) &&
+ this._allowRedirects &&
+ redirectsRemaining > 0) {
+ const redirectUrl = response.message.headers['location'];
+ if (!redirectUrl) {
+ // if there's no location to redirect to, we won't
+ break;
+ }
+ const parsedRedirectUrl = new URL(redirectUrl);
+ if (parsedUrl.protocol === 'https:' &&
+ parsedUrl.protocol !== parsedRedirectUrl.protocol &&
+ !this._allowRedirectDowngrade) {
+ throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.');
+ }
+ // we need to finish reading the response before reassigning response
+ // which will leak the open socket.
+ yield response.readBody();
+ // strip authorization header if redirected to a different hostname
+ if (parsedRedirectUrl.hostname !== parsedUrl.hostname) {
+ for (const header in headers) {
+ // header names are case insensitive
+ if (header.toLowerCase() === 'authorization') {
+ delete headers[header];
+ }
+ }
+ }
+ // let's make the request with the new redirectUrl
+ info = this._prepareRequest(verb, parsedRedirectUrl, headers);
+ response = yield this.requestRaw(info, data);
+ redirectsRemaining--;
+ }
+ if (!response.message.statusCode ||
+ !HttpResponseRetryCodes.includes(response.message.statusCode)) {
+ // If not a retry code, return immediately instead of retrying
+ return response;
+ }
+ numTries += 1;
+ if (numTries < maxTries) {
+ yield response.readBody();
+ yield this._performExponentialBackoff(numTries);
+ }
+ } while (numTries < maxTries);
+ return response;
+ });
}
- })
-}
-
-// https://fetch.spec.whatwg.org/#concept-filtered-response
-function filterResponse (response, type) {
- // Set response to the following filtered response with response as its
- // internal response, depending on request’s response tainting:
- if (type === 'basic') {
- // A basic filtered response is a filtered response whose type is "basic"
- // and header list excludes any headers in internal response’s header list
- // whose name is a forbidden response-header name.
-
- // Note: undici does not implement forbidden response-header names
- return makeFilteredResponse(response, {
- type: 'basic',
- headersList: response.headersList
- })
- } else if (type === 'cors') {
- // A CORS filtered response is a filtered response whose type is "cors"
- // and header list excludes any headers in internal response’s header
- // list whose name is not a CORS-safelisted response-header name, given
- // internal response’s CORS-exposed header-name list.
-
- // Note: undici does not implement CORS-safelisted response-header names
- return makeFilteredResponse(response, {
- type: 'cors',
- headersList: response.headersList
- })
- } else if (type === 'opaque') {
- // An opaque filtered response is a filtered response whose type is
- // "opaque", URL list is the empty list, status is 0, status message
- // is the empty byte sequence, header list is empty, and body is null.
-
- return makeFilteredResponse(response, {
- type: 'opaque',
- urlList: Object.freeze([]),
- status: 0,
- statusText: '',
- body: null
- })
- } else if (type === 'opaqueredirect') {
- // An opaque-redirect filtered response is a filtered response whose type
- // is "opaqueredirect", status is 0, status message is the empty byte
- // sequence, header list is empty, and body is null.
-
- return makeFilteredResponse(response, {
- type: 'opaqueredirect',
- status: 0,
- statusText: '',
- headersList: [],
- body: null
- })
- } else {
- assert(false)
- }
-}
-
-// https://fetch.spec.whatwg.org/#appropriate-network-error
-function makeAppropriateNetworkError (fetchParams, err = null) {
- // 1. Assert: fetchParams is canceled.
- assert(isCancelled(fetchParams))
-
- // 2. Return an aborted network error if fetchParams is aborted;
- // otherwise return a network error.
- return isAborted(fetchParams)
- ? makeNetworkError(Object.assign(new DOMException('The operation was aborted.', 'AbortError'), { cause: err }))
- : makeNetworkError(Object.assign(new DOMException('Request was cancelled.'), { cause: err }))
-}
-
-// https://whatpr.org/fetch/1392.html#initialize-a-response
-function initializeResponse (response, init, body) {
- // 1. If init["status"] is not in the range 200 to 599, inclusive, then
- // throw a RangeError.
- if (init.status !== null && (init.status < 200 || init.status > 599)) {
- throw new RangeError('init["status"] must be in the range of 200 to 599, inclusive.')
- }
-
- // 2. If init["statusText"] does not match the reason-phrase token production,
- // then throw a TypeError.
- if ('statusText' in init && init.statusText != null) {
- // See, https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2:
- // reason-phrase = *( HTAB / SP / VCHAR / obs-text )
- if (!isValidReasonPhrase(String(init.statusText))) {
- throw new TypeError('Invalid statusText')
+ /**
+ * Needs to be called if keepAlive is set to true in request options.
+ */
+ dispose() {
+ if (this._agent) {
+ this._agent.destroy();
+ }
+ this._disposed = true;
}
- }
-
- // 3. Set response’s response’s status to init["status"].
- if ('status' in init && init.status != null) {
- response[kState].status = init.status
- }
-
- // 4. Set response’s response’s status message to init["statusText"].
- if ('statusText' in init && init.statusText != null) {
- response[kState].statusText = init.statusText
- }
-
- // 5. If init["headers"] exists, then fill response’s headers with init["headers"].
- if ('headers' in init && init.headers != null) {
- fill(response[kHeaders], init.headers)
- }
-
- // 6. If body was given, then:
- if (body) {
- // 1. If response's status is a null body status, then throw a TypeError.
- if (nullBodyStatus.includes(response.status)) {
- throw webidl.errors.exception({
- header: 'Response constructor',
- message: `Invalid response status code ${response.status}`
- })
+ /**
+ * Raw request.
+ * @param info
+ * @param data
+ */
+ requestRaw(info, data) {
+ return __awaiter(this, void 0, void 0, function* () {
+ return new Promise((resolve, reject) => {
+ function callbackForResult(err, res) {
+ if (err) {
+ reject(err);
+ }
+ else if (!res) {
+ // If `err` is not passed, then `res` must be passed.
+ reject(new Error('Unknown error'));
+ }
+ else {
+ resolve(res);
+ }
+ }
+ this.requestRawWithCallback(info, data, callbackForResult);
+ });
+ });
}
-
- // 2. Set response's body to body's body.
- response[kState].body = body.body
-
- // 3. If body's type is non-null and response's header list does not contain
- // `Content-Type`, then append (`Content-Type`, body's type) to response's header list.
- if (body.type != null && !response[kState].headersList.contains('content-type', true)) {
- response[kState].headersList.append('content-type', body.type, true)
+ /**
+ * Raw request with callback.
+ * @param info
+ * @param data
+ * @param onResult
+ */
+ requestRawWithCallback(info, data, onResult) {
+ if (typeof data === 'string') {
+ if (!info.options.headers) {
+ info.options.headers = {};
+ }
+ info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8');
+ }
+ let callbackCalled = false;
+ function handleResult(err, res) {
+ if (!callbackCalled) {
+ callbackCalled = true;
+ onResult(err, res);
+ }
+ }
+ const req = info.httpModule.request(info.options, (msg) => {
+ const res = new HttpClientResponse(msg);
+ handleResult(undefined, res);
+ });
+ let socket;
+ req.on('socket', sock => {
+ socket = sock;
+ });
+ // If we ever get disconnected, we want the socket to timeout eventually
+ req.setTimeout(this._socketTimeout || 3 * 60000, () => {
+ if (socket) {
+ socket.end();
+ }
+ handleResult(new Error(`Request timeout: ${info.options.path}`));
+ });
+ req.on('error', function (err) {
+ // err has statusCode property
+ // res should have headers
+ handleResult(err);
+ });
+ if (data && typeof data === 'string') {
+ req.write(data, 'utf8');
+ }
+ if (data && typeof data !== 'string') {
+ data.on('close', function () {
+ req.end();
+ });
+ data.pipe(req);
+ }
+ else {
+ req.end();
+ }
}
- }
-}
-
-/**
- * @see https://fetch.spec.whatwg.org/#response-create
- * @param {any} innerResponse
- * @param {'request' | 'immutable' | 'request-no-cors' | 'response' | 'none'} guard
- * @returns {Response}
- */
-function fromInnerResponse (innerResponse, guard) {
- const response = new Response(kConstruct)
- response[kState] = innerResponse
- response[kHeaders] = new Headers(kConstruct)
- setHeadersList(response[kHeaders], innerResponse.headersList)
- setHeadersGuard(response[kHeaders], guard)
-
- if (hasFinalizationRegistry && innerResponse.body?.stream) {
- // If the target (response) is reclaimed, the cleanup callback may be called at some point with
- // the held value provided for it (innerResponse.body.stream). The held value can be any value:
- // a primitive or an object, even undefined. If the held value is an object, the registry keeps
- // a strong reference to it (so it can pass it to the cleanup callback later). Reworded from
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry
- streamRegistry.register(response, new WeakRef(innerResponse.body.stream))
- }
-
- return response
-}
-
-webidl.converters.ReadableStream = webidl.interfaceConverter(
- ReadableStream
-)
-
-webidl.converters.FormData = webidl.interfaceConverter(
- FormData
-)
-
-webidl.converters.URLSearchParams = webidl.interfaceConverter(
- URLSearchParams
-)
-
-// https://fetch.spec.whatwg.org/#typedefdef-xmlhttprequestbodyinit
-webidl.converters.XMLHttpRequestBodyInit = function (V, prefix, name) {
- if (typeof V === 'string') {
- return webidl.converters.USVString(V, prefix, name)
- }
-
- if (isBlobLike(V)) {
- return webidl.converters.Blob(V, prefix, name, { strict: false })
- }
-
- if (ArrayBuffer.isView(V) || types.isArrayBuffer(V)) {
- return webidl.converters.BufferSource(V, prefix, name)
- }
-
- if (util.isFormDataLike(V)) {
- return webidl.converters.FormData(V, prefix, name, { strict: false })
- }
-
- if (V instanceof URLSearchParams) {
- return webidl.converters.URLSearchParams(V, prefix, name)
- }
-
- return webidl.converters.DOMString(V, prefix, name)
-}
-
-// https://fetch.spec.whatwg.org/#bodyinit
-webidl.converters.BodyInit = function (V, prefix, argument) {
- if (V instanceof ReadableStream) {
- return webidl.converters.ReadableStream(V, prefix, argument)
- }
-
- // Note: the spec doesn't include async iterables,
- // this is an undici extension.
- if (V?.[Symbol.asyncIterator]) {
- return V
- }
-
- return webidl.converters.XMLHttpRequestBodyInit(V, prefix, argument)
-}
-
-webidl.converters.ResponseInit = webidl.dictionaryConverter([
- {
- key: 'status',
- converter: webidl.converters['unsigned short'],
- defaultValue: () => 200
- },
- {
- key: 'statusText',
- converter: webidl.converters.ByteString,
- defaultValue: () => ''
- },
- {
- key: 'headers',
- converter: webidl.converters.HeadersInit
- }
-])
-
-module.exports = {
- isNetworkError,
- makeNetworkError,
- makeResponse,
- makeAppropriateNetworkError,
- filterResponse,
- Response,
- cloneResponse,
- fromInnerResponse
-}
-
-
-/***/ }),
-
-/***/ 4883:
-/***/ ((module) => {
-
-
-
-module.exports = {
- kUrl: Symbol('url'),
- kHeaders: Symbol('headers'),
- kSignal: Symbol('signal'),
- kState: Symbol('state'),
- kDispatcher: Symbol('dispatcher')
-}
-
-
-/***/ }),
-
-/***/ 4296:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const { Transform } = __nccwpck_require__(7075)
-const zlib = __nccwpck_require__(8522)
-const { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = __nccwpck_require__(1207)
-const { getGlobalOrigin } = __nccwpck_require__(2443)
-const { collectASequenceOfCodePoints, collectAnHTTPQuotedString, removeChars, parseMIMEType } = __nccwpck_require__(980)
-const { performance } = __nccwpck_require__(643)
-const { isBlobLike, ReadableStreamFrom, isValidHTTPToken, normalizedMethodRecordsBase } = __nccwpck_require__(1544)
-const assert = __nccwpck_require__(4589)
-const { isUint8Array } = __nccwpck_require__(3429)
-const { webidl } = __nccwpck_require__(253)
-
-let supportedHashes = []
-
-// https://nodejs.org/api/crypto.html#determining-if-crypto-support-is-unavailable
-/** @type {import('crypto')} */
-let crypto
-try {
- crypto = __nccwpck_require__(7598)
- const possibleRelevantHashes = ['sha256', 'sha384', 'sha512']
- supportedHashes = crypto.getHashes().filter((hash) => possibleRelevantHashes.includes(hash))
-/* c8 ignore next 3 */
-} catch {
-
-}
-
-function responseURL (response) {
- // https://fetch.spec.whatwg.org/#responses
- // A response has an associated URL. It is a pointer to the last URL
- // in response’s URL list and null if response’s URL list is empty.
- const urlList = response.urlList
- const length = urlList.length
- return length === 0 ? null : urlList[length - 1].toString()
-}
-
-// https://fetch.spec.whatwg.org/#concept-response-location-url
-function responseLocationURL (response, requestFragment) {
- // 1. If response’s status is not a redirect status, then return null.
- if (!redirectStatusSet.has(response.status)) {
- return null
- }
-
- // 2. Let location be the result of extracting header list values given
- // `Location` and response’s header list.
- let location = response.headersList.get('location', true)
-
- // 3. If location is a header value, then set location to the result of
- // parsing location with response’s URL.
- if (location !== null && isValidHeaderValue(location)) {
- if (!isValidEncodedURL(location)) {
- // Some websites respond location header in UTF-8 form without encoding them as ASCII
- // and major browsers redirect them to correctly UTF-8 encoded addresses.
- // Here, we handle that behavior in the same way.
- location = normalizeBinaryStringToUtf8(location)
+ /**
+ * Gets an http agent. This function is useful when you need an http agent that handles
+ * routing through a proxy server - depending upon the url and proxy environment variables.
+ * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com
+ */
+ getAgent(serverUrl) {
+ const parsedUrl = new URL(serverUrl);
+ return this._getAgent(parsedUrl);
+ }
+ getAgentDispatcher(serverUrl) {
+ const parsedUrl = new URL(serverUrl);
+ const proxyUrl = getProxyUrl(parsedUrl);
+ const useProxy = proxyUrl && proxyUrl.hostname;
+ if (!useProxy) {
+ return;
+ }
+ return this._getProxyAgentDispatcher(parsedUrl, proxyUrl);
+ }
+ _prepareRequest(method, requestUrl, headers) {
+ const info = {};
+ info.parsedUrl = requestUrl;
+ const usingSsl = info.parsedUrl.protocol === 'https:';
+ info.httpModule = usingSsl ? external_https_namespaceObject : external_http_namespaceObject;
+ const defaultPort = usingSsl ? 443 : 80;
+ info.options = {};
+ info.options.host = info.parsedUrl.hostname;
+ info.options.port = info.parsedUrl.port
+ ? parseInt(info.parsedUrl.port)
+ : defaultPort;
+ info.options.path =
+ (info.parsedUrl.pathname || '') + (info.parsedUrl.search || '');
+ info.options.method = method;
+ info.options.headers = this._mergeHeaders(headers);
+ if (this.userAgent != null) {
+ info.options.headers['user-agent'] = this.userAgent;
+ }
+ info.options.agent = this._getAgent(info.parsedUrl);
+ // gives handlers an opportunity to participate
+ if (this.handlers) {
+ for (const handler of this.handlers) {
+ handler.prepareRequest(info.options);
+ }
+ }
+ return info;
+ }
+ _mergeHeaders(headers) {
+ if (this.requestOptions && this.requestOptions.headers) {
+ return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {}));
+ }
+ return lowercaseKeys(headers || {});
+ }
+ /**
+ * Gets an existing header value or returns a default.
+ * Handles converting number header values to strings since HTTP headers must be strings.
+ * Note: This returns string | string[] since some headers can have multiple values.
+ * For headers that must always be a single string (like Content-Type), use the
+ * specialized _getExistingOrDefaultContentTypeHeader method instead.
+ */
+ _getExistingOrDefaultHeader(additionalHeaders, header, _default) {
+ let clientHeader;
+ if (this.requestOptions && this.requestOptions.headers) {
+ const headerValue = lowercaseKeys(this.requestOptions.headers)[header];
+ if (headerValue) {
+ clientHeader =
+ typeof headerValue === 'number' ? headerValue.toString() : headerValue;
+ }
+ }
+ const additionalValue = additionalHeaders[header];
+ if (additionalValue !== undefined) {
+ return typeof additionalValue === 'number'
+ ? additionalValue.toString()
+ : additionalValue;
+ }
+ if (clientHeader !== undefined) {
+ return clientHeader;
+ }
+ return _default;
+ }
+ /**
+ * Specialized version of _getExistingOrDefaultHeader for Content-Type header.
+ * Always returns a single string (not an array) since Content-Type should be a single value.
+ * Converts arrays to comma-separated strings and numbers to strings to ensure type safety.
+ * This was split from _getExistingOrDefaultHeader to provide stricter typing for callers
+ * that assign the result to places expecting a string (e.g., additionalHeaders[Headers.ContentType]).
+ */
+ _getExistingOrDefaultContentTypeHeader(additionalHeaders, _default) {
+ let clientHeader;
+ if (this.requestOptions && this.requestOptions.headers) {
+ const headerValue = lowercaseKeys(this.requestOptions.headers)[Headers.ContentType];
+ if (headerValue) {
+ if (typeof headerValue === 'number') {
+ clientHeader = String(headerValue);
+ }
+ else if (Array.isArray(headerValue)) {
+ clientHeader = headerValue.join(', ');
+ }
+ else {
+ clientHeader = headerValue;
+ }
+ }
+ }
+ const additionalValue = additionalHeaders[Headers.ContentType];
+ // Return the first non-undefined value, converting numbers or arrays to strings if necessary
+ if (additionalValue !== undefined) {
+ if (typeof additionalValue === 'number') {
+ return String(additionalValue);
+ }
+ else if (Array.isArray(additionalValue)) {
+ return additionalValue.join(', ');
+ }
+ else {
+ return additionalValue;
+ }
+ }
+ if (clientHeader !== undefined) {
+ return clientHeader;
+ }
+ return _default;
+ }
+ _getAgent(parsedUrl) {
+ let agent;
+ const proxyUrl = getProxyUrl(parsedUrl);
+ const useProxy = proxyUrl && proxyUrl.hostname;
+ if (this._keepAlive && useProxy) {
+ agent = this._proxyAgent;
+ }
+ if (!useProxy) {
+ agent = this._agent;
+ }
+ // if agent is already assigned use that agent.
+ if (agent) {
+ return agent;
+ }
+ const usingSsl = parsedUrl.protocol === 'https:';
+ let maxSockets = 100;
+ if (this.requestOptions) {
+ maxSockets = this.requestOptions.maxSockets || external_http_.globalAgent.maxSockets;
+ }
+ // This is `useProxy` again, but we need to check `proxyURl` directly for TypeScripts's flow analysis.
+ if (proxyUrl && proxyUrl.hostname) {
+ const agentOptions = {
+ maxSockets,
+ keepAlive: this._keepAlive,
+ proxy: Object.assign(Object.assign({}, ((proxyUrl.username || proxyUrl.password) && {
+ proxyAuth: `${proxyUrl.username}:${proxyUrl.password}`
+ })), { host: proxyUrl.hostname, port: proxyUrl.port })
+ };
+ let tunnelAgent;
+ const overHttps = proxyUrl.protocol === 'https:';
+ if (usingSsl) {
+ tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp;
+ }
+ else {
+ tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp;
+ }
+ agent = tunnelAgent(agentOptions);
+ this._proxyAgent = agent;
+ }
+ // if tunneling agent isn't assigned create a new agent
+ if (!agent) {
+ const options = { keepAlive: this._keepAlive, maxSockets };
+ agent = usingSsl ? new external_https_.Agent(options) : new external_http_.Agent(options);
+ this._agent = agent;
+ }
+ if (usingSsl && this._ignoreSslError) {
+ // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process
+ // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options
+ // we have to cast it to any and change it directly
+ agent.options = Object.assign(agent.options || {}, {
+ rejectUnauthorized: false
+ });
+ }
+ return agent;
+ }
+ _getProxyAgentDispatcher(parsedUrl, proxyUrl) {
+ let proxyAgent;
+ if (this._keepAlive) {
+ proxyAgent = this._proxyAgentDispatcher;
+ }
+ // if agent is already assigned use that agent.
+ if (proxyAgent) {
+ return proxyAgent;
+ }
+ const usingSsl = parsedUrl.protocol === 'https:';
+ proxyAgent = new undici.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, ((proxyUrl.username || proxyUrl.password) && {
+ token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString('base64')}`
+ })));
+ this._proxyAgentDispatcher = proxyAgent;
+ if (usingSsl && this._ignoreSslError) {
+ // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process
+ // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options
+ // we have to cast it to any and change it directly
+ proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, {
+ rejectUnauthorized: false
+ });
+ }
+ return proxyAgent;
+ }
+ _getUserAgentWithOrchestrationId(userAgent) {
+ const baseUserAgent = userAgent || 'actions/http-client';
+ const orchId = process.env['ACTIONS_ORCHESTRATION_ID'];
+ if (orchId) {
+ // Sanitize the orchestration ID to ensure it contains only valid characters
+ // Valid characters: 0-9, a-z, _, -, .
+ const sanitizedId = orchId.replace(/[^a-z0-9_.-]/gi, '_');
+ return `${baseUserAgent} actions_orchestration_id/${sanitizedId}`;
+ }
+ return baseUserAgent;
+ }
+ _performExponentialBackoff(retryNumber) {
+ return __awaiter(this, void 0, void 0, function* () {
+ retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber);
+ const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber);
+ return new Promise(resolve => setTimeout(() => resolve(), ms));
+ });
+ }
+ _processResponse(res, options) {
+ return __awaiter(this, void 0, void 0, function* () {
+ return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
+ const statusCode = res.message.statusCode || 0;
+ const response = {
+ statusCode,
+ result: null,
+ headers: {}
+ };
+ // not found leads to null obj returned
+ if (statusCode === HttpCodes.NotFound) {
+ resolve(response);
+ }
+ // get the result from the body
+ function dateTimeDeserializer(key, value) {
+ if (typeof value === 'string') {
+ const a = new Date(value);
+ if (!isNaN(a.valueOf())) {
+ return a;
+ }
+ }
+ return value;
+ }
+ let obj;
+ let contents;
+ try {
+ contents = yield res.readBody();
+ if (contents && contents.length > 0) {
+ if (options && options.deserializeDates) {
+ obj = JSON.parse(contents, dateTimeDeserializer);
+ }
+ else {
+ obj = JSON.parse(contents);
+ }
+ response.result = obj;
+ }
+ response.headers = res.message.headers;
+ }
+ catch (err) {
+ // Invalid resource (contents not json); leaving result obj null
+ }
+ // note that 3xx redirects are handled by the http layer.
+ if (statusCode > 299) {
+ let msg;
+ // if exception/error in body, attempt to get better error
+ if (obj && obj.message) {
+ msg = obj.message;
+ }
+ else if (contents && contents.length > 0) {
+ // it may be the case that the exception is in the body message as string
+ msg = contents;
+ }
+ else {
+ msg = `Failed request: (${statusCode})`;
+ }
+ const err = new lib_HttpClientError(msg, statusCode);
+ err.result = response.result;
+ reject(err);
+ }
+ else {
+ resolve(response);
+ }
+ }));
+ });
}
- location = new URL(location, responseURL(response))
- }
-
- // 4. If location is a URL whose fragment is null, then set location’s
- // fragment to requestFragment.
- if (location && !location.hash) {
- location.hash = requestFragment
- }
-
- // 5. Return location.
- return location
}
-
-/**
- * @see https://www.rfc-editor.org/rfc/rfc1738#section-2.2
- * @param {string} url
- * @returns {boolean}
- */
-function isValidEncodedURL (url) {
- for (let i = 0; i < url.length; ++i) {
- const code = url.charCodeAt(i)
-
- if (
- code > 0x7E || // Non-US-ASCII + DEL
- code < 0x20 // Control characters NUL - US
- ) {
- return false
+const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {});
+//# sourceMappingURL=index.js.map
+;// CONCATENATED MODULE: ./node_modules/@actions/http-client/lib/auth.js
+var auth_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
+class BasicCredentialHandler {
+ constructor(username, password) {
+ this.username = username;
+ this.password = password;
+ }
+ prepareRequest(options) {
+ if (!options.headers) {
+ throw Error('The request has no headers');
+ }
+ options.headers['Authorization'] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString('base64')}`;
+ }
+ // This handler cannot handle 401
+ canHandleAuthentication() {
+ return false;
+ }
+ handleAuthentication() {
+ return auth_awaiter(this, void 0, void 0, function* () {
+ throw new Error('not implemented');
+ });
}
- }
- return true
}
-
-/**
- * If string contains non-ASCII characters, assumes it's UTF-8 encoded and decodes it.
- * Since UTF-8 is a superset of ASCII, this will work for ASCII strings as well.
- * @param {string} value
- * @returns {string}
- */
-function normalizeBinaryStringToUtf8 (value) {
- return Buffer.from(value, 'binary').toString('utf8')
+class auth_BearerCredentialHandler {
+ constructor(token) {
+ this.token = token;
+ }
+ // currently implements pre-authorization
+ // TODO: support preAuth = false where it hooks on 401
+ prepareRequest(options) {
+ if (!options.headers) {
+ throw Error('The request has no headers');
+ }
+ options.headers['Authorization'] = `Bearer ${this.token}`;
+ }
+ // This handler cannot handle 401
+ canHandleAuthentication() {
+ return false;
+ }
+ handleAuthentication() {
+ return auth_awaiter(this, void 0, void 0, function* () {
+ throw new Error('not implemented');
+ });
+ }
}
-
-/** @returns {URL} */
-function requestCurrentURL (request) {
- return request.urlList[request.urlList.length - 1]
+class PersonalAccessTokenCredentialHandler {
+ constructor(token) {
+ this.token = token;
+ }
+ // currently implements pre-authorization
+ // TODO: support preAuth = false where it hooks on 401
+ prepareRequest(options) {
+ if (!options.headers) {
+ throw Error('The request has no headers');
+ }
+ options.headers['Authorization'] = `Basic ${Buffer.from(`PAT:${this.token}`).toString('base64')}`;
+ }
+ // This handler cannot handle 401
+ canHandleAuthentication() {
+ return false;
+ }
+ handleAuthentication() {
+ return auth_awaiter(this, void 0, void 0, function* () {
+ throw new Error('not implemented');
+ });
+ }
}
+//# sourceMappingURL=auth.js.map
+;// CONCATENATED MODULE: ./node_modules/@actions/core/lib/oidc-utils.js
+var oidc_utils_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
-function requestBadPort (request) {
- // 1. Let url be request’s current URL.
- const url = requestCurrentURL(request)
- // 2. If url’s scheme is an HTTP(S) scheme and url’s port is a bad port,
- // then return blocked.
- if (urlIsHttpHttpsScheme(url) && badPortsSet.has(url.port)) {
- return 'blocked'
- }
- // 3. Return allowed.
- return 'allowed'
+class oidc_utils_OidcClient {
+ static createHttpClient(allowRetry = true, maxRetry = 10) {
+ const requestOptions = {
+ allowRetries: allowRetry,
+ maxRetries: maxRetry
+ };
+ return new HttpClient('actions/oidc-client', [new BearerCredentialHandler(oidc_utils_OidcClient.getRequestToken())], requestOptions);
+ }
+ static getRequestToken() {
+ const token = process.env['ACTIONS_ID_TOKEN_REQUEST_TOKEN'];
+ if (!token) {
+ throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable');
+ }
+ return token;
+ }
+ static getIDTokenUrl() {
+ const runtimeUrl = process.env['ACTIONS_ID_TOKEN_REQUEST_URL'];
+ if (!runtimeUrl) {
+ throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable');
+ }
+ return runtimeUrl;
+ }
+ static getCall(id_token_url) {
+ return oidc_utils_awaiter(this, void 0, void 0, function* () {
+ var _a;
+ const httpclient = oidc_utils_OidcClient.createHttpClient();
+ const res = yield httpclient
+ .getJson(id_token_url)
+ .catch(error => {
+ throw new Error(`Failed to get ID Token. \n
+ Error Code : ${error.statusCode}\n
+ Error Message: ${error.message}`);
+ });
+ const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value;
+ if (!id_token) {
+ throw new Error('Response json body do not have ID Token field');
+ }
+ return id_token;
+ });
+ }
+ static getIDToken(audience) {
+ return oidc_utils_awaiter(this, void 0, void 0, function* () {
+ try {
+ // New ID Token is requested from action service
+ let id_token_url = oidc_utils_OidcClient.getIDTokenUrl();
+ if (audience) {
+ const encodedAudience = encodeURIComponent(audience);
+ id_token_url = `${id_token_url}&audience=${encodedAudience}`;
+ }
+ debug(`ID token url is ${id_token_url}`);
+ const id_token = yield oidc_utils_OidcClient.getCall(id_token_url);
+ setSecret(id_token);
+ return id_token;
+ }
+ catch (error) {
+ throw new Error(`Error message: ${error.message}`);
+ }
+ });
+ }
}
+//# sourceMappingURL=oidc-utils.js.map
+;// CONCATENATED MODULE: ./node_modules/@actions/core/lib/summary.js
+var summary_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
-function isErrorLike (object) {
- return object instanceof Error || (
- object?.constructor?.name === 'Error' ||
- object?.constructor?.name === 'DOMException'
- )
-}
-// Check whether |statusText| is a ByteString and
-// matches the Reason-Phrase token production.
-// RFC 2616: https://tools.ietf.org/html/rfc2616
-// RFC 7230: https://tools.ietf.org/html/rfc7230
-// "reason-phrase = *( HTAB / SP / VCHAR / obs-text )"
-// https://github.com/chromium/chromium/blob/94.0.4604.1/third_party/blink/renderer/core/fetch/response.cc#L116
-function isValidReasonPhrase (statusText) {
- for (let i = 0; i < statusText.length; ++i) {
- const c = statusText.charCodeAt(i)
- if (
- !(
- (
- c === 0x09 || // HTAB
- (c >= 0x20 && c <= 0x7e) || // SP / VCHAR
- (c >= 0x80 && c <= 0xff)
- ) // obs-text
- )
- ) {
- return false
+const { access, appendFile, writeFile } = external_fs_namespaceObject.promises;
+const SUMMARY_ENV_VAR = 'GITHUB_STEP_SUMMARY';
+const SUMMARY_DOCS_URL = 'https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary';
+class Summary {
+ constructor() {
+ this._buffer = '';
+ }
+ /**
+ * Finds the summary file path from the environment, rejects if env var is not found or file does not exist
+ * Also checks r/w permissions.
+ *
+ * @returns step summary file path
+ */
+ filePath() {
+ return summary_awaiter(this, void 0, void 0, function* () {
+ if (this._filePath) {
+ return this._filePath;
+ }
+ const pathFromEnv = process.env[SUMMARY_ENV_VAR];
+ if (!pathFromEnv) {
+ throw new Error(`Unable to find environment variable for $${SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`);
+ }
+ try {
+ yield access(pathFromEnv, external_fs_namespaceObject.constants.R_OK | external_fs_namespaceObject.constants.W_OK);
+ }
+ catch (_a) {
+ throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`);
+ }
+ this._filePath = pathFromEnv;
+ return this._filePath;
+ });
+ }
+ /**
+ * Wraps content in an HTML tag, adding any HTML attributes
+ *
+ * @param {string} tag HTML tag to wrap
+ * @param {string | null} content content within the tag
+ * @param {[attribute: string]: string} attrs key-value list of HTML attributes to add
+ *
+ * @returns {string} content wrapped in HTML element
+ */
+ wrap(tag, content, attrs = {}) {
+ const htmlAttrs = Object.entries(attrs)
+ .map(([key, value]) => ` ${key}="${value}"`)
+ .join('');
+ if (!content) {
+ return `<${tag}${htmlAttrs}>`;
+ }
+ return `<${tag}${htmlAttrs}>${content}${tag}>`;
+ }
+ /**
+ * Writes text in the buffer to the summary buffer file and empties buffer. Will append by default.
+ *
+ * @param {SummaryWriteOptions} [options] (optional) options for write operation
+ *
+ * @returns {Promise} summary instance
+ */
+ write(options) {
+ return summary_awaiter(this, void 0, void 0, function* () {
+ const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite);
+ const filePath = yield this.filePath();
+ const writeFunc = overwrite ? writeFile : appendFile;
+ yield writeFunc(filePath, this._buffer, { encoding: 'utf8' });
+ return this.emptyBuffer();
+ });
+ }
+ /**
+ * Clears the summary buffer and wipes the summary file
+ *
+ * @returns {Summary} summary instance
+ */
+ clear() {
+ return summary_awaiter(this, void 0, void 0, function* () {
+ return this.emptyBuffer().write({ overwrite: true });
+ });
+ }
+ /**
+ * Returns the current summary buffer as a string
+ *
+ * @returns {string} string of summary buffer
+ */
+ stringify() {
+ return this._buffer;
+ }
+ /**
+ * If the summary buffer is empty
+ *
+ * @returns {boolen} true if the buffer is empty
+ */
+ isEmptyBuffer() {
+ return this._buffer.length === 0;
+ }
+ /**
+ * Resets the summary buffer without writing to summary file
+ *
+ * @returns {Summary} summary instance
+ */
+ emptyBuffer() {
+ this._buffer = '';
+ return this;
+ }
+ /**
+ * Adds raw text to the summary buffer
+ *
+ * @param {string} text content to add
+ * @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false)
+ *
+ * @returns {Summary} summary instance
+ */
+ addRaw(text, addEOL = false) {
+ this._buffer += text;
+ return addEOL ? this.addEOL() : this;
+ }
+ /**
+ * Adds the operating system-specific end-of-line marker to the buffer
+ *
+ * @returns {Summary} summary instance
+ */
+ addEOL() {
+ return this.addRaw(external_os_namespaceObject.EOL);
+ }
+ /**
+ * Adds an HTML codeblock to the summary buffer
+ *
+ * @param {string} code content to render within fenced code block
+ * @param {string} lang (optional) language to syntax highlight code
+ *
+ * @returns {Summary} summary instance
+ */
+ addCodeBlock(code, lang) {
+ const attrs = Object.assign({}, (lang && { lang }));
+ const element = this.wrap('pre', this.wrap('code', code), attrs);
+ return this.addRaw(element).addEOL();
+ }
+ /**
+ * Adds an HTML list to the summary buffer
+ *
+ * @param {string[]} items list of items to render
+ * @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false)
+ *
+ * @returns {Summary} summary instance
+ */
+ addList(items, ordered = false) {
+ const tag = ordered ? 'ol' : 'ul';
+ const listItems = items.map(item => this.wrap('li', item)).join('');
+ const element = this.wrap(tag, listItems);
+ return this.addRaw(element).addEOL();
+ }
+ /**
+ * Adds an HTML table to the summary buffer
+ *
+ * @param {SummaryTableCell[]} rows table rows
+ *
+ * @returns {Summary} summary instance
+ */
+ addTable(rows) {
+ const tableBody = rows
+ .map(row => {
+ const cells = row
+ .map(cell => {
+ if (typeof cell === 'string') {
+ return this.wrap('td', cell);
+ }
+ const { header, data, colspan, rowspan } = cell;
+ const tag = header ? 'th' : 'td';
+ const attrs = Object.assign(Object.assign({}, (colspan && { colspan })), (rowspan && { rowspan }));
+ return this.wrap(tag, data, attrs);
+ })
+ .join('');
+ return this.wrap('tr', cells);
+ })
+ .join('');
+ const element = this.wrap('table', tableBody);
+ return this.addRaw(element).addEOL();
+ }
+ /**
+ * Adds a collapsable HTML details element to the summary buffer
+ *
+ * @param {string} label text for the closed state
+ * @param {string} content collapsable content
+ *
+ * @returns {Summary} summary instance
+ */
+ addDetails(label, content) {
+ const element = this.wrap('details', this.wrap('summary', label) + content);
+ return this.addRaw(element).addEOL();
+ }
+ /**
+ * Adds an HTML image tag to the summary buffer
+ *
+ * @param {string} src path to the image you to embed
+ * @param {string} alt text description of the image
+ * @param {SummaryImageOptions} options (optional) addition image attributes
+ *
+ * @returns {Summary} summary instance
+ */
+ addImage(src, alt, options) {
+ const { width, height } = options || {};
+ const attrs = Object.assign(Object.assign({}, (width && { width })), (height && { height }));
+ const element = this.wrap('img', null, Object.assign({ src, alt }, attrs));
+ return this.addRaw(element).addEOL();
+ }
+ /**
+ * Adds an HTML section heading element
+ *
+ * @param {string} text heading text
+ * @param {number | string} [level=1] (optional) the heading level, default: 1
+ *
+ * @returns {Summary} summary instance
+ */
+ addHeading(text, level) {
+ const tag = `h${level}`;
+ const allowedTag = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tag)
+ ? tag
+ : 'h1';
+ const element = this.wrap(allowedTag, text);
+ return this.addRaw(element).addEOL();
+ }
+ /**
+ * Adds an HTML thematic break (
) to the summary buffer
+ *
+ * @returns {Summary} summary instance
+ */
+ addSeparator() {
+ const element = this.wrap('hr', null);
+ return this.addRaw(element).addEOL();
+ }
+ /**
+ * Adds an HTML line break (
) to the summary buffer
+ *
+ * @returns {Summary} summary instance
+ */
+ addBreak() {
+ const element = this.wrap('br', null);
+ return this.addRaw(element).addEOL();
+ }
+ /**
+ * Adds an HTML blockquote to the summary buffer
+ *
+ * @param {string} text quote text
+ * @param {string} cite (optional) citation url
+ *
+ * @returns {Summary} summary instance
+ */
+ addQuote(text, cite) {
+ const attrs = Object.assign({}, (cite && { cite }));
+ const element = this.wrap('blockquote', text, attrs);
+ return this.addRaw(element).addEOL();
+ }
+ /**
+ * Adds an HTML anchor tag to the summary buffer
+ *
+ * @param {string} text link text/content
+ * @param {string} href hyperlink
+ *
+ * @returns {Summary} summary instance
+ */
+ addLink(text, href) {
+ const element = this.wrap('a', text, { href });
+ return this.addRaw(element).addEOL();
}
- }
- return true
}
-
+const _summary = new Summary();
/**
- * @see https://fetch.spec.whatwg.org/#header-name
- * @param {string} potentialValue
+ * @deprecated use `core.summary`
*/
-const isValidHeaderName = isValidHTTPToken
+const markdownSummary = (/* unused pure expression or super */ null && (_summary));
+const summary = (/* unused pure expression or super */ null && (_summary));
+//# sourceMappingURL=summary.js.map
+;// CONCATENATED MODULE: ./node_modules/@actions/core/lib/path-utils.js
/**
- * @see https://fetch.spec.whatwg.org/#header-value
- * @param {string} potentialValue
+ * toPosixPath converts the given path to the posix form. On Windows, \\ will be
+ * replaced with /.
+ *
+ * @param pth. Path to transform.
+ * @return string Posix path.
*/
-function isValidHeaderValue (potentialValue) {
- // - Has no leading or trailing HTTP tab or space bytes.
- // - Contains no 0x00 (NUL) or HTTP newline bytes.
- return (
- potentialValue[0] === '\t' ||
- potentialValue[0] === ' ' ||
- potentialValue[potentialValue.length - 1] === '\t' ||
- potentialValue[potentialValue.length - 1] === ' ' ||
- potentialValue.includes('\n') ||
- potentialValue.includes('\r') ||
- potentialValue.includes('\0')
- ) === false
-}
-
-// https://w3c.github.io/webappsec-referrer-policy/#set-requests-referrer-policy-on-redirect
-function setRequestReferrerPolicyOnRedirect (request, actualResponse) {
- // Given a request request and a response actualResponse, this algorithm
- // updates request’s referrer policy according to the Referrer-Policy
- // header (if any) in actualResponse.
-
- // 1. Let policy be the result of executing § 8.1 Parse a referrer policy
- // from a Referrer-Policy header on actualResponse.
-
- // 8.1 Parse a referrer policy from a Referrer-Policy header
- // 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy` and response’s header list.
- const { headersList } = actualResponse
- // 2. Let policy be the empty string.
- // 3. For each token in policy-tokens, if token is a referrer policy and token is not the empty string, then set policy to token.
- // 4. Return policy.
- const policyHeader = (headersList.get('referrer-policy', true) ?? '').split(',')
-
- // Note: As the referrer-policy can contain multiple policies
- // separated by comma, we need to loop through all of them
- // and pick the first valid one.
- // Ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy#specify_a_fallback_policy
- let policy = ''
- if (policyHeader.length > 0) {
- // The right-most policy takes precedence.
- // The left-most policy is the fallback.
- for (let i = policyHeader.length; i !== 0; i--) {
- const token = policyHeader[i - 1].trim()
- if (referrerPolicyTokens.has(token)) {
- policy = token
- break
- }
- }
- }
-
- // 2. If policy is not the empty string, then set request’s referrer policy to policy.
- if (policy !== '') {
- request.referrerPolicy = policy
- }
-}
-
-// https://fetch.spec.whatwg.org/#cross-origin-resource-policy-check
-function crossOriginResourcePolicyCheck () {
- // TODO
- return 'allowed'
+function toPosixPath(pth) {
+ return pth.replace(/[\\]/g, '/');
}
-
-// https://fetch.spec.whatwg.org/#concept-cors-check
-function corsCheck () {
- // TODO
- return 'success'
+/**
+ * toWin32Path converts the given path to the win32 form. On Linux, / will be
+ * replaced with \\.
+ *
+ * @param pth. Path to transform.
+ * @return string Win32 path.
+ */
+function toWin32Path(pth) {
+ return pth.replace(/[/]/g, '\\');
}
-
-// https://fetch.spec.whatwg.org/#concept-tao-check
-function TAOCheck () {
- // TODO
- return 'success'
+/**
+ * toPlatformPath converts the given path to a platform-specific path. It does
+ * this by replacing instances of / and \ with the platform-specific path
+ * separator.
+ *
+ * @param pth The path to platformize.
+ * @return string The platform-specific path.
+ */
+function toPlatformPath(pth) {
+ return pth.replace(/[/\\]/g, path.sep);
}
+//# sourceMappingURL=path-utils.js.map
+// EXTERNAL MODULE: external "string_decoder"
+var external_string_decoder_ = __nccwpck_require__(3193);
+// EXTERNAL MODULE: external "events"
+var external_events_ = __nccwpck_require__(4434);
+;// CONCATENATED MODULE: external "child_process"
+const external_child_process_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("child_process");
+// EXTERNAL MODULE: external "assert"
+var external_assert_ = __nccwpck_require__(2613);
+;// CONCATENATED MODULE: ./node_modules/@actions/io/lib/io-util.js
+var io_util_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
-function appendFetchMetadata (httpRequest) {
- // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-dest-header
- // TODO
-
- // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-mode-header
-
- // 1. Assert: r’s url is a potentially trustworthy URL.
- // TODO
-
- // 2. Let header be a Structured Header whose value is a token.
- let header = null
-
- // 3. Set header’s value to r’s mode.
- header = httpRequest.mode
-
- // 4. Set a structured field value `Sec-Fetch-Mode`/header in r’s header list.
- httpRequest.headersList.set('sec-fetch-mode', header, true)
-
- // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-site-header
- // TODO
- // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-user-header
- // TODO
+const { chmod, copyFile, lstat, mkdir, open: io_util_open, readdir, rename, rm, rmdir, stat, symlink, unlink } = external_fs_namespaceObject.promises;
+// export const {open} = 'fs'
+const IS_WINDOWS = process.platform === 'win32';
+/**
+ * Custom implementation of readlink to ensure Windows junctions
+ * maintain trailing backslash for backward compatibility with Node.js < 24
+ *
+ * In Node.js 20, Windows junctions (directory symlinks) always returned paths
+ * with trailing backslashes. Node.js 24 removed this behavior, which breaks
+ * code that relied on this format for path operations.
+ *
+ * This implementation restores the Node 20 behavior by adding a trailing
+ * backslash to all junction results on Windows.
+ */
+function readlink(fsPath) {
+ return io_util_awaiter(this, void 0, void 0, function* () {
+ const result = yield external_fs_namespaceObject.promises.readlink(fsPath);
+ // On Windows, restore Node 20 behavior: add trailing backslash to all results
+ // since junctions on Windows are always directory links
+ if (IS_WINDOWS && !result.endsWith('\\')) {
+ return `${result}\\`;
+ }
+ return result;
+ });
}
-
-// https://fetch.spec.whatwg.org/#append-a-request-origin-header
-function appendRequestOriginHeader (request) {
- // 1. Let serializedOrigin be the result of byte-serializing a request origin
- // with request.
- // TODO: implement "byte-serializing a request origin"
- let serializedOrigin = request.origin
-
- // - "'client' is changed to an origin during fetching."
- // This doesn't happen in undici (in most cases) because undici, by default,
- // has no concept of origin.
- // - request.origin can also be set to request.client.origin (client being
- // an environment settings object), which is undefined without using
- // setGlobalOrigin.
- if (serializedOrigin === 'client' || serializedOrigin === undefined) {
- return
- }
-
- // 2. If request’s response tainting is "cors" or request’s mode is "websocket",
- // then append (`Origin`, serializedOrigin) to request’s header list.
- // 3. Otherwise, if request’s method is neither `GET` nor `HEAD`, then:
- if (request.responseTainting === 'cors' || request.mode === 'websocket') {
- request.headersList.append('origin', serializedOrigin, true)
- } else if (request.method !== 'GET' && request.method !== 'HEAD') {
- // 1. Switch on request’s referrer policy:
- switch (request.referrerPolicy) {
- case 'no-referrer':
- // Set serializedOrigin to `null`.
- serializedOrigin = null
- break
- case 'no-referrer-when-downgrade':
- case 'strict-origin':
- case 'strict-origin-when-cross-origin':
- // If request’s origin is a tuple origin, its scheme is "https", and
- // request’s current URL’s scheme is not "https", then set
- // serializedOrigin to `null`.
- if (request.origin && urlHasHttpsScheme(request.origin) && !urlHasHttpsScheme(requestCurrentURL(request))) {
- serializedOrigin = null
+// See https://github.com/nodejs/node/blob/d0153aee367422d0858105abec186da4dff0a0c5/deps/uv/include/uv/win.h#L691
+const UV_FS_O_EXLOCK = 0x10000000;
+const READONLY = external_fs_namespaceObject.constants.O_RDONLY;
+function exists(fsPath) {
+ return io_util_awaiter(this, void 0, void 0, function* () {
+ try {
+ yield stat(fsPath);
}
- break
- case 'same-origin':
- // If request’s origin is not same origin with request’s current URL’s
- // origin, then set serializedOrigin to `null`.
- if (!sameOrigin(request, requestCurrentURL(request))) {
- serializedOrigin = null
+ catch (err) {
+ if (err.code === 'ENOENT') {
+ return false;
+ }
+ throw err;
}
- break
- default:
- // Do nothing.
- }
-
- // 2. Append (`Origin`, serializedOrigin) to request’s header list.
- request.headersList.append('origin', serializedOrigin, true)
- }
-}
-
-// https://w3c.github.io/hr-time/#dfn-coarsen-time
-function coarsenTime (timestamp, crossOriginIsolatedCapability) {
- // TODO
- return timestamp
+ return true;
+ });
}
-
-// https://fetch.spec.whatwg.org/#clamp-and-coarsen-connection-timing-info
-function clampAndCoarsenConnectionTimingInfo (connectionTimingInfo, defaultStartTime, crossOriginIsolatedCapability) {
- if (!connectionTimingInfo?.startTime || connectionTimingInfo.startTime < defaultStartTime) {
- return {
- domainLookupStartTime: defaultStartTime,
- domainLookupEndTime: defaultStartTime,
- connectionStartTime: defaultStartTime,
- connectionEndTime: defaultStartTime,
- secureConnectionStartTime: defaultStartTime,
- ALPNNegotiatedProtocol: connectionTimingInfo?.ALPNNegotiatedProtocol
+function isDirectory(fsPath_1) {
+ return io_util_awaiter(this, arguments, void 0, function* (fsPath, useStat = false) {
+ const stats = useStat ? yield stat(fsPath) : yield lstat(fsPath);
+ return stats.isDirectory();
+ });
+}
+/**
+ * On OSX/Linux, true if path starts with '/'. On Windows, true for paths like:
+ * \, \hello, \\hello\share, C:, and C:\hello (and corresponding alternate separator cases).
+ */
+function isRooted(p) {
+ p = normalizeSeparators(p);
+ if (!p) {
+ throw new Error('isRooted() parameter "p" cannot be empty');
}
- }
-
- return {
- domainLookupStartTime: coarsenTime(connectionTimingInfo.domainLookupStartTime, crossOriginIsolatedCapability),
- domainLookupEndTime: coarsenTime(connectionTimingInfo.domainLookupEndTime, crossOriginIsolatedCapability),
- connectionStartTime: coarsenTime(connectionTimingInfo.connectionStartTime, crossOriginIsolatedCapability),
- connectionEndTime: coarsenTime(connectionTimingInfo.connectionEndTime, crossOriginIsolatedCapability),
- secureConnectionStartTime: coarsenTime(connectionTimingInfo.secureConnectionStartTime, crossOriginIsolatedCapability),
- ALPNNegotiatedProtocol: connectionTimingInfo.ALPNNegotiatedProtocol
- }
+ if (IS_WINDOWS) {
+ return (p.startsWith('\\') || /^[A-Z]:/i.test(p) // e.g. \ or \hello or \\hello
+ ); // e.g. C: or C:\hello
+ }
+ return p.startsWith('/');
}
-
-// https://w3c.github.io/hr-time/#dfn-coarsened-shared-current-time
-function coarsenedSharedCurrentTime (crossOriginIsolatedCapability) {
- return coarsenTime(performance.now(), crossOriginIsolatedCapability)
+/**
+ * Best effort attempt to determine whether a file exists and is executable.
+ * @param filePath file path to check
+ * @param extensions additional file extensions to try
+ * @return if file exists and is executable, returns the file path. otherwise empty string.
+ */
+function tryGetExecutablePath(filePath, extensions) {
+ return io_util_awaiter(this, void 0, void 0, function* () {
+ let stats = undefined;
+ try {
+ // test file exists
+ stats = yield stat(filePath);
+ }
+ catch (err) {
+ if (err.code !== 'ENOENT') {
+ // eslint-disable-next-line no-console
+ console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`);
+ }
+ }
+ if (stats && stats.isFile()) {
+ if (IS_WINDOWS) {
+ // on Windows, test for valid extension
+ const upperExt = external_path_.extname(filePath).toUpperCase();
+ if (extensions.some(validExt => validExt.toUpperCase() === upperExt)) {
+ return filePath;
+ }
+ }
+ else {
+ if (isUnixExecutable(stats)) {
+ return filePath;
+ }
+ }
+ }
+ // try each extension
+ const originalFilePath = filePath;
+ for (const extension of extensions) {
+ filePath = originalFilePath + extension;
+ stats = undefined;
+ try {
+ stats = yield stat(filePath);
+ }
+ catch (err) {
+ if (err.code !== 'ENOENT') {
+ // eslint-disable-next-line no-console
+ console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`);
+ }
+ }
+ if (stats && stats.isFile()) {
+ if (IS_WINDOWS) {
+ // preserve the case of the actual file (since an extension was appended)
+ try {
+ const directory = external_path_.dirname(filePath);
+ const upperName = external_path_.basename(filePath).toUpperCase();
+ for (const actualName of yield readdir(directory)) {
+ if (upperName === actualName.toUpperCase()) {
+ filePath = external_path_.join(directory, actualName);
+ break;
+ }
+ }
+ }
+ catch (err) {
+ // eslint-disable-next-line no-console
+ console.log(`Unexpected error attempting to determine the actual case of the file '${filePath}': ${err}`);
+ }
+ return filePath;
+ }
+ else {
+ if (isUnixExecutable(stats)) {
+ return filePath;
+ }
+ }
+ }
+ }
+ return '';
+ });
}
-
-// https://fetch.spec.whatwg.org/#create-an-opaque-timing-info
-function createOpaqueTimingInfo (timingInfo) {
- return {
- startTime: timingInfo.startTime ?? 0,
- redirectStartTime: 0,
- redirectEndTime: 0,
- postRedirectStartTime: timingInfo.startTime ?? 0,
- finalServiceWorkerStartTime: 0,
- finalNetworkResponseStartTime: 0,
- finalNetworkRequestStartTime: 0,
- endTime: 0,
- encodedBodySize: 0,
- decodedBodySize: 0,
- finalConnectionTimingInfo: null
- }
+function normalizeSeparators(p) {
+ p = p || '';
+ if (IS_WINDOWS) {
+ // convert slashes on Windows
+ p = p.replace(/\//g, '\\');
+ // remove redundant slashes
+ return p.replace(/\\\\+/g, '\\');
+ }
+ // remove redundant slashes
+ return p.replace(/\/\/+/g, '/');
}
-
-// https://html.spec.whatwg.org/multipage/origin.html#policy-container
-function makePolicyContainer () {
- // Note: the fetch spec doesn't make use of embedder policy or CSP list
- return {
- referrerPolicy: 'strict-origin-when-cross-origin'
- }
+// on Mac/Linux, test the execute bit
+// R W X R W X R W X
+// 256 128 64 32 16 8 4 2 1
+function isUnixExecutable(stats) {
+ return ((stats.mode & 1) > 0 ||
+ ((stats.mode & 8) > 0 &&
+ process.getgid !== undefined &&
+ stats.gid === process.getgid()) ||
+ ((stats.mode & 64) > 0 &&
+ process.getuid !== undefined &&
+ stats.uid === process.getuid()));
}
-
-// https://html.spec.whatwg.org/multipage/origin.html#clone-a-policy-container
-function clonePolicyContainer (policyContainer) {
- return {
- referrerPolicy: policyContainer.referrerPolicy
- }
+// Get the path of cmd.exe in windows
+function getCmdPath() {
+ var _a;
+ return (_a = process.env['COMSPEC']) !== null && _a !== void 0 ? _a : `cmd.exe`;
}
+//# sourceMappingURL=io-util.js.map
+;// CONCATENATED MODULE: ./node_modules/@actions/io/lib/io.js
+var io_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
-// https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer
-function determineRequestsReferrer (request) {
- // 1. Let policy be request's referrer policy.
- const policy = request.referrerPolicy
-
- // Note: policy cannot (shouldn't) be null or an empty string.
- assert(policy)
-
- // 2. Let environment be request’s client.
-
- let referrerSource = null
-
- // 3. Switch on request’s referrer:
- if (request.referrer === 'client') {
- // Note: node isn't a browser and doesn't implement document/iframes,
- // so we bypass this step and replace it with our own.
-
- const globalOrigin = getGlobalOrigin()
-
- if (!globalOrigin || globalOrigin.origin === 'null') {
- return 'no-referrer'
- }
-
- // note: we need to clone it as it's mutated
- referrerSource = new URL(globalOrigin)
- } else if (request.referrer instanceof URL) {
- // Let referrerSource be request’s referrer.
- referrerSource = request.referrer
- }
-
- // 4. Let request’s referrerURL be the result of stripping referrerSource for
- // use as a referrer.
- let referrerURL = stripURLForReferrer(referrerSource)
-
- // 5. Let referrerOrigin be the result of stripping referrerSource for use as
- // a referrer, with the origin-only flag set to true.
- const referrerOrigin = stripURLForReferrer(referrerSource, true)
-
- // 6. If the result of serializing referrerURL is a string whose length is
- // greater than 4096, set referrerURL to referrerOrigin.
- if (referrerURL.toString().length > 4096) {
- referrerURL = referrerOrigin
- }
-
- const areSameOrigin = sameOrigin(request, referrerURL)
- const isNonPotentiallyTrustWorthy = isURLPotentiallyTrustworthy(referrerURL) &&
- !isURLPotentiallyTrustworthy(request.url)
-
- // 8. Execute the switch statements corresponding to the value of policy:
- switch (policy) {
- case 'origin': return referrerOrigin != null ? referrerOrigin : stripURLForReferrer(referrerSource, true)
- case 'unsafe-url': return referrerURL
- case 'same-origin':
- return areSameOrigin ? referrerOrigin : 'no-referrer'
- case 'origin-when-cross-origin':
- return areSameOrigin ? referrerURL : referrerOrigin
- case 'strict-origin-when-cross-origin': {
- const currentURL = requestCurrentURL(request)
-
- // 1. If the origin of referrerURL and the origin of request’s current
- // URL are the same, then return referrerURL.
- if (sameOrigin(referrerURL, currentURL)) {
- return referrerURL
- }
-
- // 2. If referrerURL is a potentially trustworthy URL and request’s
- // current URL is not a potentially trustworthy URL, then return no
- // referrer.
- if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) {
- return 'no-referrer'
- }
-
- // 3. Return referrerOrigin.
- return referrerOrigin
- }
- case 'strict-origin': // eslint-disable-line
- /**
- * 1. If referrerURL is a potentially trustworthy URL and
- * request’s current URL is not a potentially trustworthy URL,
- * then return no referrer.
- * 2. Return referrerOrigin
- */
- case 'no-referrer-when-downgrade': // eslint-disable-line
- /**
- * 1. If referrerURL is a potentially trustworthy URL and
- * request’s current URL is not a potentially trustworthy URL,
- * then return no referrer.
- * 2. Return referrerOrigin
- */
- default: // eslint-disable-line
- return isNonPotentiallyTrustWorthy ? 'no-referrer' : referrerOrigin
- }
-}
/**
- * @see https://w3c.github.io/webappsec-referrer-policy/#strip-url
- * @param {URL} url
- * @param {boolean|undefined} originOnly
+ * Copies a file or folder.
+ * Based off of shelljs - https://github.com/shelljs/shelljs/blob/9237f66c52e5daa40458f94f9565e18e8132f5a6/src/cp.js
+ *
+ * @param source source path
+ * @param dest destination path
+ * @param options optional. See CopyOptions.
*/
-function stripURLForReferrer (url, originOnly) {
- // 1. Assert: url is a URL.
- assert(url instanceof URL)
-
- url = new URL(url)
-
- // 2. If url’s scheme is a local scheme, then return no referrer.
- if (url.protocol === 'file:' || url.protocol === 'about:' || url.protocol === 'blank:') {
- return 'no-referrer'
- }
-
- // 3. Set url’s username to the empty string.
- url.username = ''
-
- // 4. Set url’s password to the empty string.
- url.password = ''
-
- // 5. Set url’s fragment to null.
- url.hash = ''
-
- // 6. If the origin-only flag is true, then:
- if (originOnly) {
- // 1. Set url’s path to « the empty string ».
- url.pathname = ''
-
- // 2. Set url’s query to null.
- url.search = ''
- }
-
- // 7. Return url.
- return url
-}
-
-function isURLPotentiallyTrustworthy (url) {
- if (!(url instanceof URL)) {
- return false
- }
-
- // If child of about, return true
- if (url.href === 'about:blank' || url.href === 'about:srcdoc') {
- return true
- }
-
- // If scheme is data, return true
- if (url.protocol === 'data:') return true
-
- // If file, return true
- if (url.protocol === 'file:') return true
-
- return isOriginPotentiallyTrustworthy(url.origin)
-
- function isOriginPotentiallyTrustworthy (origin) {
- // If origin is explicitly null, return false
- if (origin == null || origin === 'null') return false
-
- const originAsURL = new URL(origin)
-
- // If secure, return true
- if (originAsURL.protocol === 'https:' || originAsURL.protocol === 'wss:') {
- return true
- }
-
- // If localhost or variants, return true
- if (/^127(?:\.[0-9]+){0,2}\.[0-9]+$|^\[(?:0*:)*?:?0*1\]$/.test(originAsURL.hostname) ||
- (originAsURL.hostname === 'localhost' || originAsURL.hostname.includes('localhost.')) ||
- (originAsURL.hostname.endsWith('.localhost'))) {
- return true
- }
-
- // If any other, return false
- return false
- }
+function io_cp(source_1, dest_1) {
+ return io_awaiter(this, arguments, void 0, function* (source, dest, options = {}) {
+ const { force, recursive, copySourceDirectory } = readCopyOptions(options);
+ const destStat = (yield exists(dest)) ? yield stat(dest) : null;
+ // Dest is an existing file, but not forcing
+ if (destStat && destStat.isFile() && !force) {
+ return;
+ }
+ // If dest is an existing directory, should copy inside.
+ const newDest = destStat && destStat.isDirectory() && copySourceDirectory
+ ? external_path_.join(dest, external_path_.basename(source))
+ : dest;
+ if (!(yield exists(source))) {
+ throw new Error(`no such file or directory: ${source}`);
+ }
+ const sourceStat = yield stat(source);
+ if (sourceStat.isDirectory()) {
+ if (!recursive) {
+ throw new Error(`Failed to copy. ${source} is a directory, but tried to copy without recursive flag.`);
+ }
+ else {
+ yield cpDirRecursive(source, newDest, 0, force);
+ }
+ }
+ else {
+ if (external_path_.relative(source, newDest) === '') {
+ // a file cannot be copied to itself
+ throw new Error(`'${newDest}' and '${source}' are the same file`);
+ }
+ yield io_copyFile(source, newDest, force);
+ }
+ });
}
-
/**
- * @see https://w3c.github.io/webappsec-subresource-integrity/#does-response-match-metadatalist
- * @param {Uint8Array} bytes
- * @param {string} metadataList
+ * Moves a path.
+ *
+ * @param source source path
+ * @param dest destination path
+ * @param options optional. See MoveOptions.
*/
-function bytesMatch (bytes, metadataList) {
- // If node is not built with OpenSSL support, we cannot check
- // a request's integrity, so allow it by default (the spec will
- // allow requests if an invalid hash is given, as precedence).
- /* istanbul ignore if: only if node is built with --without-ssl */
- if (crypto === undefined) {
- return true
- }
-
- // 1. Let parsedMetadata be the result of parsing metadataList.
- const parsedMetadata = parseMetadata(metadataList)
-
- // 2. If parsedMetadata is no metadata, return true.
- if (parsedMetadata === 'no metadata') {
- return true
- }
-
- // 3. If response is not eligible for integrity validation, return false.
- // TODO
-
- // 4. If parsedMetadata is the empty set, return true.
- if (parsedMetadata.length === 0) {
- return true
- }
-
- // 5. Let metadata be the result of getting the strongest
- // metadata from parsedMetadata.
- const strongest = getStrongestMetadata(parsedMetadata)
- const metadata = filterMetadataListByAlgorithm(parsedMetadata, strongest)
-
- // 6. For each item in metadata:
- for (const item of metadata) {
- // 1. Let algorithm be the alg component of item.
- const algorithm = item.algo
-
- // 2. Let expectedValue be the val component of item.
- const expectedValue = item.hash
-
- // See https://github.com/web-platform-tests/wpt/commit/e4c5cc7a5e48093220528dfdd1c4012dc3837a0e
- // "be liberal with padding". This is annoying, and it's not even in the spec.
-
- // 3. Let actualValue be the result of applying algorithm to bytes.
- let actualValue = crypto.createHash(algorithm).update(bytes).digest('base64')
-
- if (actualValue[actualValue.length - 1] === '=') {
- if (actualValue[actualValue.length - 2] === '=') {
- actualValue = actualValue.slice(0, -2)
- } else {
- actualValue = actualValue.slice(0, -1)
- }
- }
-
- // 4. If actualValue is a case-sensitive match for expectedValue,
- // return true.
- if (compareBase64Mixed(actualValue, expectedValue)) {
- return true
- }
- }
-
- // 7. Return false.
- return false
+function mv(source_1, dest_1) {
+ return io_awaiter(this, arguments, void 0, function* (source, dest, options = {}) {
+ if (yield ioUtil.exists(dest)) {
+ let destExists = true;
+ if (yield ioUtil.isDirectory(dest)) {
+ // If dest is directory copy src into dest
+ dest = path.join(dest, path.basename(source));
+ destExists = yield ioUtil.exists(dest);
+ }
+ if (destExists) {
+ if (options.force == null || options.force) {
+ yield rmRF(dest);
+ }
+ else {
+ throw new Error('Destination already exists');
+ }
+ }
+ }
+ yield mkdirP(path.dirname(dest));
+ yield ioUtil.rename(source, dest);
+ });
}
-
-// https://w3c.github.io/webappsec-subresource-integrity/#grammardef-hash-with-options
-// https://www.w3.org/TR/CSP2/#source-list-syntax
-// https://www.rfc-editor.org/rfc/rfc5234#appendix-B.1
-const parseHashWithOptions = /(?sha256|sha384|sha512)-((?[A-Za-z0-9+/]+|[A-Za-z0-9_-]+)={0,2}(?:\s|$)( +[!-~]*)?)?/i
-
/**
- * @see https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata
- * @param {string} metadata
+ * Remove a path recursively with force
+ *
+ * @param inputPath path to remove
*/
-function parseMetadata (metadata) {
- // 1. Let result be the empty set.
- /** @type {{ algo: string, hash: string }[]} */
- const result = []
-
- // 2. Let empty be equal to true.
- let empty = true
-
- // 3. For each token returned by splitting metadata on spaces:
- for (const token of metadata.split(' ')) {
- // 1. Set empty to false.
- empty = false
-
- // 2. Parse token as a hash-with-options.
- const parsedToken = parseHashWithOptions.exec(token)
-
- // 3. If token does not parse, continue to the next token.
- if (
- parsedToken === null ||
- parsedToken.groups === undefined ||
- parsedToken.groups.algo === undefined
- ) {
- // Note: Chromium blocks the request at this point, but Firefox
- // gives a warning that an invalid integrity was given. The
- // correct behavior is to ignore these, and subsequently not
- // check the integrity of the resource.
- continue
- }
-
- // 4. Let algorithm be the hash-algo component of token.
- const algorithm = parsedToken.groups.algo.toLowerCase()
-
- // 5. If algorithm is a hash function recognized by the user
- // agent, add the parsed token to result.
- if (supportedHashes.includes(algorithm)) {
- result.push(parsedToken.groups)
- }
- }
-
- // 4. Return no metadata if empty is true, otherwise return result.
- if (empty === true) {
- return 'no metadata'
- }
-
- return result
+function rmRF(inputPath) {
+ return io_awaiter(this, void 0, void 0, function* () {
+ if (IS_WINDOWS) {
+ // Check for invalid characters
+ // https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
+ if (/[*"<>|]/.test(inputPath)) {
+ throw new Error('File path must not contain `*`, `"`, `<`, `>` or `|` on Windows');
+ }
+ }
+ try {
+ // note if path does not exist, error is silent
+ yield rm(inputPath, {
+ force: true,
+ maxRetries: 3,
+ recursive: true,
+ retryDelay: 300
+ });
+ }
+ catch (err) {
+ throw new Error(`File was unable to be removed ${err}`);
+ }
+ });
}
-
/**
- * @param {{ algo: 'sha256' | 'sha384' | 'sha512' }[]} metadataList
+ * Make a directory. Creates the full path with folders in between
+ * Will throw if it fails
+ *
+ * @param fsPath path to create
+ * @returns Promise
*/
-function getStrongestMetadata (metadataList) {
- // Let algorithm be the algo component of the first item in metadataList.
- // Can be sha256
- let algorithm = metadataList[0].algo
- // If the algorithm is sha512, then it is the strongest
- // and we can return immediately
- if (algorithm[3] === '5') {
- return algorithm
- }
-
- for (let i = 1; i < metadataList.length; ++i) {
- const metadata = metadataList[i]
- // If the algorithm is sha512, then it is the strongest
- // and we can break the loop immediately
- if (metadata.algo[3] === '5') {
- algorithm = 'sha512'
- break
- // If the algorithm is sha384, then a potential sha256 or sha384 is ignored
- } else if (algorithm[3] === '3') {
- continue
- // algorithm is sha256, check if algorithm is sha384 and if so, set it as
- // the strongest
- } else if (metadata.algo[3] === '3') {
- algorithm = 'sha384'
- }
- }
- return algorithm
-}
-
-function filterMetadataListByAlgorithm (metadataList, algorithm) {
- if (metadataList.length === 1) {
- return metadataList
- }
-
- let pos = 0
- for (let i = 0; i < metadataList.length; ++i) {
- if (metadataList[i].algo === algorithm) {
- metadataList[pos++] = metadataList[i]
- }
- }
-
- metadataList.length = pos
-
- return metadataList
+function mkdirP(fsPath) {
+ return io_awaiter(this, void 0, void 0, function* () {
+ (0,external_assert_.ok)(fsPath, 'a path argument must be provided');
+ yield mkdir(fsPath, { recursive: true });
+ });
}
-
/**
- * Compares two base64 strings, allowing for base64url
- * in the second string.
+ * Returns path of a tool had the tool actually been invoked. Resolves via paths.
+ * If you check and the tool does not exist, it will throw.
*
-* @param {string} actualValue always base64
- * @param {string} expectedValue base64 or base64url
- * @returns {boolean}
+ * @param tool name of the tool
+ * @param check whether to check if tool exists
+ * @returns Promise path to tool
*/
-function compareBase64Mixed (actualValue, expectedValue) {
- if (actualValue.length !== expectedValue.length) {
- return false
- }
- for (let i = 0; i < actualValue.length; ++i) {
- if (actualValue[i] !== expectedValue[i]) {
- if (
- (actualValue[i] === '+' && expectedValue[i] === '-') ||
- (actualValue[i] === '/' && expectedValue[i] === '_')
- ) {
- continue
- }
- return false
- }
- }
-
- return true
-}
-
-// https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-request
-function tryUpgradeRequestToAPotentiallyTrustworthyURL (request) {
- // TODO
+function which(tool, check) {
+ return io_awaiter(this, void 0, void 0, function* () {
+ if (!tool) {
+ throw new Error("parameter 'tool' is required");
+ }
+ // recursive when check=true
+ if (check) {
+ const result = yield which(tool, false);
+ if (!result) {
+ if (IS_WINDOWS) {
+ throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.`);
+ }
+ else {
+ throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.`);
+ }
+ }
+ return result;
+ }
+ const matches = yield findInPath(tool);
+ if (matches && matches.length > 0) {
+ return matches[0];
+ }
+ return '';
+ });
}
-
/**
- * @link {https://html.spec.whatwg.org/multipage/origin.html#same-origin}
- * @param {URL} A
- * @param {URL} B
+ * Returns a list of all occurrences of the given tool on the system path.
+ *
+ * @returns Promise the paths of the tool
*/
-function sameOrigin (A, B) {
- // 1. If A and B are the same opaque origin, then return true.
- if (A.origin === B.origin && A.origin === 'null') {
- return true
- }
-
- // 2. If A and B are both tuple origins and their schemes,
- // hosts, and port are identical, then return true.
- if (A.protocol === B.protocol && A.hostname === B.hostname && A.port === B.port) {
- return true
- }
-
- // 3. Return false.
- return false
+function findInPath(tool) {
+ return io_awaiter(this, void 0, void 0, function* () {
+ if (!tool) {
+ throw new Error("parameter 'tool' is required");
+ }
+ // build the list of extensions to try
+ const extensions = [];
+ if (IS_WINDOWS && process.env['PATHEXT']) {
+ for (const extension of process.env['PATHEXT'].split(external_path_.delimiter)) {
+ if (extension) {
+ extensions.push(extension);
+ }
+ }
+ }
+ // if it's rooted, return it if exists. otherwise return empty.
+ if (isRooted(tool)) {
+ const filePath = yield tryGetExecutablePath(tool, extensions);
+ if (filePath) {
+ return [filePath];
+ }
+ return [];
+ }
+ // if any path separators, return empty
+ if (tool.includes(external_path_.sep)) {
+ return [];
+ }
+ // build the list of directories
+ //
+ // Note, technically "where" checks the current directory on Windows. From a toolkit perspective,
+ // it feels like we should not do this. Checking the current directory seems like more of a use
+ // case of a shell, and the which() function exposed by the toolkit should strive for consistency
+ // across platforms.
+ const directories = [];
+ if (process.env.PATH) {
+ for (const p of process.env.PATH.split(external_path_.delimiter)) {
+ if (p) {
+ directories.push(p);
+ }
+ }
+ }
+ // find all matches
+ const matches = [];
+ for (const directory of directories) {
+ const filePath = yield tryGetExecutablePath(external_path_.join(directory, tool), extensions);
+ if (filePath) {
+ matches.push(filePath);
+ }
+ }
+ return matches;
+ });
}
-
-function createDeferredPromise () {
- let res
- let rej
- const promise = new Promise((resolve, reject) => {
- res = resolve
- rej = reject
- })
-
- return { promise, resolve: res, reject: rej }
+function readCopyOptions(options) {
+ const force = options.force == null ? true : options.force;
+ const recursive = Boolean(options.recursive);
+ const copySourceDirectory = options.copySourceDirectory == null
+ ? true
+ : Boolean(options.copySourceDirectory);
+ return { force, recursive, copySourceDirectory };
}
-
-function isAborted (fetchParams) {
- return fetchParams.controller.state === 'aborted'
+function cpDirRecursive(sourceDir, destDir, currentDepth, force) {
+ return io_awaiter(this, void 0, void 0, function* () {
+ // Ensure there is not a run away recursive copy
+ if (currentDepth >= 255)
+ return;
+ currentDepth++;
+ yield mkdirP(destDir);
+ const files = yield readdir(sourceDir);
+ for (const fileName of files) {
+ const srcFile = `${sourceDir}/${fileName}`;
+ const destFile = `${destDir}/${fileName}`;
+ const srcFileStat = yield lstat(srcFile);
+ if (srcFileStat.isDirectory()) {
+ // Recurse
+ yield cpDirRecursive(srcFile, destFile, currentDepth, force);
+ }
+ else {
+ yield io_copyFile(srcFile, destFile, force);
+ }
+ }
+ // Change the mode for the newly created directory
+ yield chmod(destDir, (yield stat(sourceDir)).mode);
+ });
}
-
-function isCancelled (fetchParams) {
- return fetchParams.controller.state === 'aborted' ||
- fetchParams.controller.state === 'terminated'
+// Buffered file copy
+function io_copyFile(srcFile, destFile, force) {
+ return io_awaiter(this, void 0, void 0, function* () {
+ if ((yield lstat(srcFile)).isSymbolicLink()) {
+ // unlink/re-link it
+ try {
+ yield lstat(destFile);
+ yield unlink(destFile);
+ }
+ catch (e) {
+ // Try to override file permission
+ if (e.code === 'EPERM') {
+ yield chmod(destFile, '0666');
+ yield unlink(destFile);
+ }
+ // other errors = it doesn't exist, no work to do
+ }
+ // Copy over symlink
+ const symlinkFull = yield readlink(srcFile);
+ yield symlink(symlinkFull, destFile, IS_WINDOWS ? 'junction' : null);
+ }
+ else if (!(yield exists(destFile)) || force) {
+ yield copyFile(srcFile, destFile);
+ }
+ });
}
+//# sourceMappingURL=io.js.map
+;// CONCATENATED MODULE: external "timers"
+const external_timers_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("timers");
+;// CONCATENATED MODULE: ./node_modules/@actions/exec/lib/toolrunner.js
+var toolrunner_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
-/**
- * @see https://fetch.spec.whatwg.org/#concept-method-normalize
- * @param {string} method
- */
-function normalizeMethod (method) {
- return normalizedMethodRecordsBase[method.toLowerCase()] ?? method
-}
-// https://infra.spec.whatwg.org/#serialize-a-javascript-value-to-a-json-string
-function serializeJavascriptValueToJSONString (value) {
- // 1. Let result be ? Call(%JSON.stringify%, undefined, « value »).
- const result = JSON.stringify(value)
- // 2. If result is undefined, then throw a TypeError.
- if (result === undefined) {
- throw new TypeError('Value is not JSON serializable')
- }
- // 3. Assert: result is a string.
- assert(typeof result === 'string')
- // 4. Return result.
- return result
-}
-// https://tc39.es/ecma262/#sec-%25iteratorprototype%25-object
-const esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))
-/**
- * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object
- * @param {string} name name of the instance
- * @param {symbol} kInternalIterator
- * @param {string | number} [keyIndex]
- * @param {string | number} [valueIndex]
+/* eslint-disable @typescript-eslint/unbound-method */
+const toolrunner_IS_WINDOWS = process.platform === 'win32';
+/*
+ * Class for running command line tools. Handles quoting and arg parsing in a platform agnostic way.
*/
-function createIterator (name, kInternalIterator, keyIndex = 0, valueIndex = 1) {
- class FastIterableIterator {
- /** @type {any} */
- #target
- /** @type {'key' | 'value' | 'key+value'} */
- #kind
- /** @type {number} */
- #index
-
- /**
- * @see https://webidl.spec.whatwg.org/#dfn-default-iterator-object
- * @param {unknown} target
- * @param {'key' | 'value' | 'key+value'} kind
- */
- constructor (target, kind) {
- this.#target = target
- this.#kind = kind
- this.#index = 0
+class ToolRunner extends external_events_.EventEmitter {
+ constructor(toolPath, args, options) {
+ super();
+ if (!toolPath) {
+ throw new Error("Parameter 'toolPath' cannot be null or empty.");
+ }
+ this.toolPath = toolPath;
+ this.args = args || [];
+ this.options = options || {};
}
-
- next () {
- // 1. Let interface be the interface for which the iterator prototype object exists.
- // 2. Let thisValue be the this value.
- // 3. Let object be ? ToObject(thisValue).
- // 4. If object is a platform object, then perform a security
- // check, passing:
- // 5. If object is not a default iterator object for interface,
- // then throw a TypeError.
- if (typeof this !== 'object' || this === null || !(#target in this)) {
- throw new TypeError(
- `'next' called on an object that does not implement interface ${name} Iterator.`
- )
- }
-
- // 6. Let index be object’s index.
- // 7. Let kind be object’s kind.
- // 8. Let values be object’s target's value pairs to iterate over.
- const index = this.#index
- const values = this.#target[kInternalIterator]
-
- // 9. Let len be the length of values.
- const len = values.length
-
- // 10. If index is greater than or equal to len, then return
- // CreateIterResultObject(undefined, true).
- if (index >= len) {
- return {
- value: undefined,
- done: true
+ _debug(message) {
+ if (this.options.listeners && this.options.listeners.debug) {
+ this.options.listeners.debug(message);
}
- }
-
- // 11. Let pair be the entry in values at index index.
- const { [keyIndex]: key, [valueIndex]: value } = values[index]
-
- // 12. Set object’s index to index + 1.
- this.#index = index + 1
-
- // 13. Return the iterator result for pair and kind.
-
- // https://webidl.spec.whatwg.org/#iterator-result
-
- // 1. Let result be a value determined by the value of kind:
- let result
- switch (this.#kind) {
- case 'key':
- // 1. Let idlKey be pair’s key.
- // 2. Let key be the result of converting idlKey to an
- // ECMAScript value.
- // 3. result is key.
- result = key
- break
- case 'value':
- // 1. Let idlValue be pair’s value.
- // 2. Let value be the result of converting idlValue to
- // an ECMAScript value.
- // 3. result is value.
- result = value
- break
- case 'key+value':
- // 1. Let idlKey be pair’s key.
- // 2. Let idlValue be pair’s value.
- // 3. Let key be the result of converting idlKey to an
- // ECMAScript value.
- // 4. Let value be the result of converting idlValue to
- // an ECMAScript value.
- // 5. Let array be ! ArrayCreate(2).
- // 6. Call ! CreateDataProperty(array, "0", key).
- // 7. Call ! CreateDataProperty(array, "1", value).
- // 8. result is array.
- result = [key, value]
- break
- }
-
- // 2. Return CreateIterResultObject(result, false).
- return {
- value: result,
- done: false
- }
}
- }
-
- // https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object
- // @ts-ignore
- delete FastIterableIterator.prototype.constructor
-
- Object.setPrototypeOf(FastIterableIterator.prototype, esIteratorPrototype)
-
- Object.defineProperties(FastIterableIterator.prototype, {
- [Symbol.toStringTag]: {
- writable: false,
- enumerable: false,
- configurable: true,
- value: `${name} Iterator`
- },
- next: { writable: true, enumerable: true, configurable: true }
- })
-
- /**
- * @param {unknown} target
- * @param {'key' | 'value' | 'key+value'} kind
- * @returns {IterableIterator}
- */
- return function (target, kind) {
- return new FastIterableIterator(target, kind)
- }
-}
-
-/**
- * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object
- * @param {string} name name of the instance
- * @param {any} object class
- * @param {symbol} kInternalIterator
- * @param {string | number} [keyIndex]
- * @param {string | number} [valueIndex]
- */
-function iteratorMixin (name, object, kInternalIterator, keyIndex = 0, valueIndex = 1) {
- const makeIterator = createIterator(name, kInternalIterator, keyIndex, valueIndex)
-
- const properties = {
- keys: {
- writable: true,
- enumerable: true,
- configurable: true,
- value: function keys () {
- webidl.brandCheck(this, object)
- return makeIterator(this, 'key')
- }
- },
- values: {
- writable: true,
- enumerable: true,
- configurable: true,
- value: function values () {
- webidl.brandCheck(this, object)
- return makeIterator(this, 'value')
- }
- },
- entries: {
- writable: true,
- enumerable: true,
- configurable: true,
- value: function entries () {
- webidl.brandCheck(this, object)
- return makeIterator(this, 'key+value')
- }
- },
- forEach: {
- writable: true,
- enumerable: true,
- configurable: true,
- value: function forEach (callbackfn, thisArg = globalThis) {
- webidl.brandCheck(this, object)
- webidl.argumentLengthCheck(arguments, 1, `${name}.forEach`)
- if (typeof callbackfn !== 'function') {
- throw new TypeError(
- `Failed to execute 'forEach' on '${name}': parameter 1 is not of type 'Function'.`
- )
+ _getCommandString(options, noPrefix) {
+ const toolPath = this._getSpawnFileName();
+ const args = this._getSpawnArgs(options);
+ let cmd = noPrefix ? '' : '[command]'; // omit prefix when piped to a second tool
+ if (toolrunner_IS_WINDOWS) {
+ // Windows + cmd file
+ if (this._isCmdFile()) {
+ cmd += toolPath;
+ for (const a of args) {
+ cmd += ` ${a}`;
+ }
+ }
+ // Windows + verbatim
+ else if (options.windowsVerbatimArguments) {
+ cmd += `"${toolPath}"`;
+ for (const a of args) {
+ cmd += ` ${a}`;
+ }
+ }
+ // Windows (regular)
+ else {
+ cmd += this._windowsQuoteCmdArg(toolPath);
+ for (const a of args) {
+ cmd += ` ${this._windowsQuoteCmdArg(a)}`;
+ }
+ }
}
- for (const { 0: key, 1: value } of makeIterator(this, 'key+value')) {
- callbackfn.call(thisArg, value, key, this)
+ else {
+ // OSX/Linux - this can likely be improved with some form of quoting.
+ // creating processes on Unix is fundamentally different than Windows.
+ // on Unix, execvp() takes an arg array.
+ cmd += toolPath;
+ for (const a of args) {
+ cmd += ` ${a}`;
+ }
}
- }
- }
- }
-
- return Object.defineProperties(object.prototype, {
- ...properties,
- [Symbol.iterator]: {
- writable: true,
- enumerable: false,
- configurable: true,
- value: properties.entries.value
- }
- })
-}
-
-/**
- * @see https://fetch.spec.whatwg.org/#body-fully-read
- */
-async function fullyReadBody (body, processBody, processBodyError) {
- // 1. If taskDestination is null, then set taskDestination to
- // the result of starting a new parallel queue.
-
- // 2. Let successSteps given a byte sequence bytes be to queue a
- // fetch task to run processBody given bytes, with taskDestination.
- const successSteps = processBody
-
- // 3. Let errorSteps be to queue a fetch task to run processBodyError,
- // with taskDestination.
- const errorSteps = processBodyError
-
- // 4. Let reader be the result of getting a reader for body’s stream.
- // If that threw an exception, then run errorSteps with that
- // exception and return.
- let reader
-
- try {
- reader = body.stream.getReader()
- } catch (e) {
- errorSteps(e)
- return
- }
-
- // 5. Read all bytes from reader, given successSteps and errorSteps.
- try {
- successSteps(await readAllBytes(reader))
- } catch (e) {
- errorSteps(e)
- }
-}
-
-function isReadableStreamLike (stream) {
- return stream instanceof ReadableStream || (
- stream[Symbol.toStringTag] === 'ReadableStream' &&
- typeof stream.tee === 'function'
- )
-}
-
-/**
- * @param {ReadableStreamController} controller
- */
-function readableStreamClose (controller) {
- try {
- controller.close()
- controller.byobRequest?.respond(0)
- } catch (err) {
- // TODO: add comment explaining why this error occurs.
- if (!err.message.includes('Controller is already closed') && !err.message.includes('ReadableStream is already closed')) {
- throw err
+ return cmd;
}
- }
-}
-
-const invalidIsomorphicEncodeValueRegex = /[^\x00-\xFF]/ // eslint-disable-line
-
-/**
- * @see https://infra.spec.whatwg.org/#isomorphic-encode
- * @param {string} input
- */
-function isomorphicEncode (input) {
- // 1. Assert: input contains no code points greater than U+00FF.
- assert(!invalidIsomorphicEncodeValueRegex.test(input))
-
- // 2. Return a byte sequence whose length is equal to input’s code
- // point length and whose bytes have the same values as the
- // values of input’s code points, in the same order
- return input
-}
-
-/**
- * @see https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-all-bytes
- * @see https://streams.spec.whatwg.org/#read-loop
- * @param {ReadableStreamDefaultReader} reader
- */
-async function readAllBytes (reader) {
- const bytes = []
- let byteLength = 0
-
- while (true) {
- const { done, value: chunk } = await reader.read()
-
- if (done) {
- // 1. Call successSteps with bytes.
- return Buffer.concat(bytes, byteLength)
+ _processLineBuffer(data, strBuffer, onLine) {
+ try {
+ let s = strBuffer + data.toString();
+ let n = s.indexOf(external_os_namespaceObject.EOL);
+ while (n > -1) {
+ const line = s.substring(0, n);
+ onLine(line);
+ // the rest of the string ...
+ s = s.substring(n + external_os_namespaceObject.EOL.length);
+ n = s.indexOf(external_os_namespaceObject.EOL);
+ }
+ return s;
+ }
+ catch (err) {
+ // streaming lines to console is best effort. Don't fail a build.
+ this._debug(`error processing line. Failed with error ${err}`);
+ return '';
+ }
}
-
- // 1. If chunk is not a Uint8Array object, call failureSteps
- // with a TypeError and abort these steps.
- if (!isUint8Array(chunk)) {
- throw new TypeError('Received non-Uint8Array chunk')
+ _getSpawnFileName() {
+ if (toolrunner_IS_WINDOWS) {
+ if (this._isCmdFile()) {
+ return process.env['COMSPEC'] || 'cmd.exe';
+ }
+ }
+ return this.toolPath;
}
-
- // 2. Append the bytes represented by chunk to bytes.
- bytes.push(chunk)
- byteLength += chunk.length
-
- // 3. Read-loop given reader, bytes, successSteps, and failureSteps.
- }
-}
-
-/**
- * @see https://fetch.spec.whatwg.org/#is-local
- * @param {URL} url
- */
-function urlIsLocal (url) {
- assert('protocol' in url) // ensure it's a url object
-
- const protocol = url.protocol
-
- return protocol === 'about:' || protocol === 'blob:' || protocol === 'data:'
-}
-
-/**
- * @param {string|URL} url
- * @returns {boolean}
- */
-function urlHasHttpsScheme (url) {
- return (
- (
- typeof url === 'string' &&
- url[5] === ':' &&
- url[0] === 'h' &&
- url[1] === 't' &&
- url[2] === 't' &&
- url[3] === 'p' &&
- url[4] === 's'
- ) ||
- url.protocol === 'https:'
- )
-}
-
-/**
- * @see https://fetch.spec.whatwg.org/#http-scheme
- * @param {URL} url
- */
-function urlIsHttpHttpsScheme (url) {
- assert('protocol' in url) // ensure it's a url object
-
- const protocol = url.protocol
-
- return protocol === 'http:' || protocol === 'https:'
-}
-
-/**
- * @see https://fetch.spec.whatwg.org/#simple-range-header-value
- * @param {string} value
- * @param {boolean} allowWhitespace
- */
-function simpleRangeHeaderValue (value, allowWhitespace) {
- // 1. Let data be the isomorphic decoding of value.
- // Note: isomorphic decoding takes a sequence of bytes (ie. a Uint8Array) and turns it into a string,
- // nothing more. We obviously don't need to do that if value is a string already.
- const data = value
-
- // 2. If data does not start with "bytes", then return failure.
- if (!data.startsWith('bytes')) {
- return 'failure'
- }
-
- // 3. Let position be a position variable for data, initially pointing at the 5th code point of data.
- const position = { position: 5 }
-
- // 4. If allowWhitespace is true, collect a sequence of code points that are HTTP tab or space,
- // from data given position.
- if (allowWhitespace) {
- collectASequenceOfCodePoints(
- (char) => char === '\t' || char === ' ',
- data,
- position
- )
- }
-
- // 5. If the code point at position within data is not U+003D (=), then return failure.
- if (data.charCodeAt(position.position) !== 0x3D) {
- return 'failure'
- }
-
- // 6. Advance position by 1.
- position.position++
-
- // 7. If allowWhitespace is true, collect a sequence of code points that are HTTP tab or space, from
- // data given position.
- if (allowWhitespace) {
- collectASequenceOfCodePoints(
- (char) => char === '\t' || char === ' ',
- data,
- position
- )
- }
-
- // 8. Let rangeStart be the result of collecting a sequence of code points that are ASCII digits,
- // from data given position.
- const rangeStart = collectASequenceOfCodePoints(
- (char) => {
- const code = char.charCodeAt(0)
-
- return code >= 0x30 && code <= 0x39
- },
- data,
- position
- )
-
- // 9. Let rangeStartValue be rangeStart, interpreted as decimal number, if rangeStart is not the
- // empty string; otherwise null.
- const rangeStartValue = rangeStart.length ? Number(rangeStart) : null
-
- // 10. If allowWhitespace is true, collect a sequence of code points that are HTTP tab or space,
- // from data given position.
- if (allowWhitespace) {
- collectASequenceOfCodePoints(
- (char) => char === '\t' || char === ' ',
- data,
- position
- )
- }
-
- // 11. If the code point at position within data is not U+002D (-), then return failure.
- if (data.charCodeAt(position.position) !== 0x2D) {
- return 'failure'
- }
-
- // 12. Advance position by 1.
- position.position++
-
- // 13. If allowWhitespace is true, collect a sequence of code points that are HTTP tab
- // or space, from data given position.
- // Note from Khafra: its the same step as in #8 again lol
- if (allowWhitespace) {
- collectASequenceOfCodePoints(
- (char) => char === '\t' || char === ' ',
- data,
- position
- )
- }
-
- // 14. Let rangeEnd be the result of collecting a sequence of code points that are
- // ASCII digits, from data given position.
- // Note from Khafra: you wouldn't guess it, but this is also the same step as #8
- const rangeEnd = collectASequenceOfCodePoints(
- (char) => {
- const code = char.charCodeAt(0)
-
- return code >= 0x30 && code <= 0x39
- },
- data,
- position
- )
-
- // 15. Let rangeEndValue be rangeEnd, interpreted as decimal number, if rangeEnd
- // is not the empty string; otherwise null.
- // Note from Khafra: THE SAME STEP, AGAIN!!!
- // Note: why interpret as a decimal if we only collect ascii digits?
- const rangeEndValue = rangeEnd.length ? Number(rangeEnd) : null
-
- // 16. If position is not past the end of data, then return failure.
- if (position.position < data.length) {
- return 'failure'
- }
-
- // 17. If rangeEndValue and rangeStartValue are null, then return failure.
- if (rangeEndValue === null && rangeStartValue === null) {
- return 'failure'
- }
-
- // 18. If rangeStartValue and rangeEndValue are numbers, and rangeStartValue is
- // greater than rangeEndValue, then return failure.
- // Note: ... when can they not be numbers?
- if (rangeStartValue > rangeEndValue) {
- return 'failure'
- }
-
- // 19. Return (rangeStartValue, rangeEndValue).
- return { rangeStartValue, rangeEndValue }
-}
-
-/**
- * @see https://fetch.spec.whatwg.org/#build-a-content-range
- * @param {number} rangeStart
- * @param {number} rangeEnd
- * @param {number} fullLength
- */
-function buildContentRange (rangeStart, rangeEnd, fullLength) {
- // 1. Let contentRange be `bytes `.
- let contentRange = 'bytes '
-
- // 2. Append rangeStart, serialized and isomorphic encoded, to contentRange.
- contentRange += isomorphicEncode(`${rangeStart}`)
-
- // 3. Append 0x2D (-) to contentRange.
- contentRange += '-'
-
- // 4. Append rangeEnd, serialized and isomorphic encoded to contentRange.
- contentRange += isomorphicEncode(`${rangeEnd}`)
-
- // 5. Append 0x2F (/) to contentRange.
- contentRange += '/'
-
- // 6. Append fullLength, serialized and isomorphic encoded to contentRange.
- contentRange += isomorphicEncode(`${fullLength}`)
-
- // 7. Return contentRange.
- return contentRange
-}
-
-// A Stream, which pipes the response to zlib.createInflate() or
-// zlib.createInflateRaw() depending on the first byte of the Buffer.
-// If the lower byte of the first byte is 0x08, then the stream is
-// interpreted as a zlib stream, otherwise it's interpreted as a
-// raw deflate stream.
-class InflateStream extends Transform {
- #zlibOptions
-
- /** @param {zlib.ZlibOptions} [zlibOptions] */
- constructor (zlibOptions) {
- super()
- this.#zlibOptions = zlibOptions
- }
-
- _transform (chunk, encoding, callback) {
- if (!this._inflateStream) {
- if (chunk.length === 0) {
- callback()
- return
- }
- this._inflateStream = (chunk[0] & 0x0F) === 0x08
- ? zlib.createInflate(this.#zlibOptions)
- : zlib.createInflateRaw(this.#zlibOptions)
-
- this._inflateStream.on('data', this.push.bind(this))
- this._inflateStream.on('end', () => this.push(null))
- this._inflateStream.on('error', (err) => this.destroy(err))
+ _getSpawnArgs(options) {
+ if (toolrunner_IS_WINDOWS) {
+ if (this._isCmdFile()) {
+ let argline = `/D /S /C "${this._windowsQuoteCmdArg(this.toolPath)}`;
+ for (const a of this.args) {
+ argline += ' ';
+ argline += options.windowsVerbatimArguments
+ ? a
+ : this._windowsQuoteCmdArg(a);
+ }
+ argline += '"';
+ return [argline];
+ }
+ }
+ return this.args;
}
-
- this._inflateStream.write(chunk, encoding, callback)
- }
-
- _final (callback) {
- if (this._inflateStream) {
- this._inflateStream.end()
- this._inflateStream = null
+ _endsWith(str, end) {
+ return str.endsWith(end);
}
- callback()
- }
-}
-
-/**
- * @param {zlib.ZlibOptions} [zlibOptions]
- * @returns {InflateStream}
- */
-function createInflate (zlibOptions) {
- return new InflateStream(zlibOptions)
-}
-
-/**
- * @see https://fetch.spec.whatwg.org/#concept-header-extract-mime-type
- * @param {import('./headers').HeadersList} headers
- */
-function extractMimeType (headers) {
- // 1. Let charset be null.
- let charset = null
-
- // 2. Let essence be null.
- let essence = null
-
- // 3. Let mimeType be null.
- let mimeType = null
-
- // 4. Let values be the result of getting, decoding, and splitting `Content-Type` from headers.
- const values = getDecodeSplit('content-type', headers)
-
- // 5. If values is null, then return failure.
- if (values === null) {
- return 'failure'
- }
-
- // 6. For each value of values:
- for (const value of values) {
- // 6.1. Let temporaryMimeType be the result of parsing value.
- const temporaryMimeType = parseMIMEType(value)
-
- // 6.2. If temporaryMimeType is failure or its essence is "*/*", then continue.
- if (temporaryMimeType === 'failure' || temporaryMimeType.essence === '*/*') {
- continue
+ _isCmdFile() {
+ const upperToolPath = this.toolPath.toUpperCase();
+ return (this._endsWith(upperToolPath, '.CMD') ||
+ this._endsWith(upperToolPath, '.BAT'));
}
-
- // 6.3. Set mimeType to temporaryMimeType.
- mimeType = temporaryMimeType
-
- // 6.4. If mimeType’s essence is not essence, then:
- if (mimeType.essence !== essence) {
- // 6.4.1. Set charset to null.
- charset = null
-
- // 6.4.2. If mimeType’s parameters["charset"] exists, then set charset to
- // mimeType’s parameters["charset"].
- if (mimeType.parameters.has('charset')) {
- charset = mimeType.parameters.get('charset')
- }
-
- // 6.4.3. Set essence to mimeType’s essence.
- essence = mimeType.essence
- } else if (!mimeType.parameters.has('charset') && charset !== null) {
- // 6.5. Otherwise, if mimeType’s parameters["charset"] does not exist, and
- // charset is non-null, set mimeType’s parameters["charset"] to charset.
- mimeType.parameters.set('charset', charset)
+ _windowsQuoteCmdArg(arg) {
+ // for .exe, apply the normal quoting rules that libuv applies
+ if (!this._isCmdFile()) {
+ return this._uvQuoteCmdArg(arg);
+ }
+ // otherwise apply quoting rules specific to the cmd.exe command line parser.
+ // the libuv rules are generic and are not designed specifically for cmd.exe
+ // command line parser.
+ //
+ // for a detailed description of the cmd.exe command line parser, refer to
+ // http://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/7970912#7970912
+ // need quotes for empty arg
+ if (!arg) {
+ return '""';
+ }
+ // determine whether the arg needs to be quoted
+ const cmdSpecialChars = [
+ ' ',
+ '\t',
+ '&',
+ '(',
+ ')',
+ '[',
+ ']',
+ '{',
+ '}',
+ '^',
+ '=',
+ ';',
+ '!',
+ "'",
+ '+',
+ ',',
+ '`',
+ '~',
+ '|',
+ '<',
+ '>',
+ '"'
+ ];
+ let needsQuotes = false;
+ for (const char of arg) {
+ if (cmdSpecialChars.some(x => x === char)) {
+ needsQuotes = true;
+ break;
+ }
+ }
+ // short-circuit if quotes not needed
+ if (!needsQuotes) {
+ return arg;
+ }
+ // the following quoting rules are very similar to the rules that by libuv applies.
+ //
+ // 1) wrap the string in quotes
+ //
+ // 2) double-up quotes - i.e. " => ""
+ //
+ // this is different from the libuv quoting rules. libuv replaces " with \", which unfortunately
+ // doesn't work well with a cmd.exe command line.
+ //
+ // note, replacing " with "" also works well if the arg is passed to a downstream .NET console app.
+ // for example, the command line:
+ // foo.exe "myarg:""my val"""
+ // is parsed by a .NET console app into an arg array:
+ // [ "myarg:\"my val\"" ]
+ // which is the same end result when applying libuv quoting rules. although the actual
+ // command line from libuv quoting rules would look like:
+ // foo.exe "myarg:\"my val\""
+ //
+ // 3) double-up slashes that precede a quote,
+ // e.g. hello \world => "hello \world"
+ // hello\"world => "hello\\""world"
+ // hello\\"world => "hello\\\\""world"
+ // hello world\ => "hello world\\"
+ //
+ // technically this is not required for a cmd.exe command line, or the batch argument parser.
+ // the reasons for including this as a .cmd quoting rule are:
+ //
+ // a) this is optimized for the scenario where the argument is passed from the .cmd file to an
+ // external program. many programs (e.g. .NET console apps) rely on the slash-doubling rule.
+ //
+ // b) it's what we've been doing previously (by deferring to node default behavior) and we
+ // haven't heard any complaints about that aspect.
+ //
+ // note, a weakness of the quoting rules chosen here, is that % is not escaped. in fact, % cannot be
+ // escaped when used on the command line directly - even though within a .cmd file % can be escaped
+ // by using %%.
+ //
+ // the saving grace is, on the command line, %var% is left as-is if var is not defined. this contrasts
+ // the line parsing rules within a .cmd file, where if var is not defined it is replaced with nothing.
+ //
+ // one option that was explored was replacing % with ^% - i.e. %var% => ^%var^%. this hack would
+ // often work, since it is unlikely that var^ would exist, and the ^ character is removed when the
+ // variable is used. the problem, however, is that ^ is not removed when %* is used to pass the args
+ // to an external program.
+ //
+ // an unexplored potential solution for the % escaping problem, is to create a wrapper .cmd file.
+ // % can be escaped within a .cmd file.
+ let reverse = '"';
+ let quoteHit = true;
+ for (let i = arg.length; i > 0; i--) {
+ // walk the string in reverse
+ reverse += arg[i - 1];
+ if (quoteHit && arg[i - 1] === '\\') {
+ reverse += '\\'; // double the slash
+ }
+ else if (arg[i - 1] === '"') {
+ quoteHit = true;
+ reverse += '"'; // double the quote
+ }
+ else {
+ quoteHit = false;
+ }
+ }
+ reverse += '"';
+ return reverse.split('').reverse().join('');
}
- }
-
- // 7. If mimeType is null, then return failure.
- if (mimeType == null) {
- return 'failure'
- }
-
- // 8. Return mimeType.
- return mimeType
-}
-
-/**
- * @see https://fetch.spec.whatwg.org/#header-value-get-decode-and-split
- * @param {string|null} value
- */
-function gettingDecodingSplitting (value) {
- // 1. Let input be the result of isomorphic decoding value.
- const input = value
-
- // 2. Let position be a position variable for input, initially pointing at the start of input.
- const position = { position: 0 }
-
- // 3. Let values be a list of strings, initially empty.
- const values = []
-
- // 4. Let temporaryValue be the empty string.
- let temporaryValue = ''
-
- // 5. While position is not past the end of input:
- while (position.position < input.length) {
- // 5.1. Append the result of collecting a sequence of code points that are not U+0022 (")
- // or U+002C (,) from input, given position, to temporaryValue.
- temporaryValue += collectASequenceOfCodePoints(
- (char) => char !== '"' && char !== ',',
- input,
- position
- )
-
- // 5.2. If position is not past the end of input, then:
- if (position.position < input.length) {
- // 5.2.1. If the code point at position within input is U+0022 ("), then:
- if (input.charCodeAt(position.position) === 0x22) {
- // 5.2.1.1. Append the result of collecting an HTTP quoted string from input, given position, to temporaryValue.
- temporaryValue += collectAnHTTPQuotedString(
- input,
- position
- )
-
- // 5.2.1.2. If position is not past the end of input, then continue.
- if (position.position < input.length) {
- continue
+ _uvQuoteCmdArg(arg) {
+ // Tool runner wraps child_process.spawn() and needs to apply the same quoting as
+ // Node in certain cases where the undocumented spawn option windowsVerbatimArguments
+ // is used.
+ //
+ // Since this function is a port of quote_cmd_arg from Node 4.x (technically, lib UV,
+ // see https://github.com/nodejs/node/blob/v4.x/deps/uv/src/win/process.c for details),
+ // pasting copyright notice from Node within this function:
+ //
+ // 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.
+ if (!arg) {
+ // Need double quotation for empty argument
+ return '""';
}
- } else {
- // 5.2.2. Otherwise:
-
- // 5.2.2.1. Assert: the code point at position within input is U+002C (,).
- assert(input.charCodeAt(position.position) === 0x2C)
-
- // 5.2.2.2. Advance position by 1.
- position.position++
- }
+ if (!arg.includes(' ') && !arg.includes('\t') && !arg.includes('"')) {
+ // No quotation needed
+ return arg;
+ }
+ if (!arg.includes('"') && !arg.includes('\\')) {
+ // No embedded double quotes or backslashes, so I can just wrap
+ // quote marks around the whole thing.
+ return `"${arg}"`;
+ }
+ // Expected input/output:
+ // input : hello"world
+ // output: "hello\"world"
+ // input : hello""world
+ // output: "hello\"\"world"
+ // input : hello\world
+ // output: hello\world
+ // input : hello\\world
+ // output: hello\\world
+ // input : hello\"world
+ // output: "hello\\\"world"
+ // input : hello\\"world
+ // output: "hello\\\\\"world"
+ // input : hello world\
+ // output: "hello world\\" - note the comment in libuv actually reads "hello world\"
+ // but it appears the comment is wrong, it should be "hello world\\"
+ let reverse = '"';
+ let quoteHit = true;
+ for (let i = arg.length; i > 0; i--) {
+ // walk the string in reverse
+ reverse += arg[i - 1];
+ if (quoteHit && arg[i - 1] === '\\') {
+ reverse += '\\';
+ }
+ else if (arg[i - 1] === '"') {
+ quoteHit = true;
+ reverse += '\\';
+ }
+ else {
+ quoteHit = false;
+ }
+ }
+ reverse += '"';
+ return reverse.split('').reverse().join('');
+ }
+ _cloneExecOptions(options) {
+ options = options || {};
+ const result = {
+ cwd: options.cwd || process.cwd(),
+ env: options.env || process.env,
+ silent: options.silent || false,
+ windowsVerbatimArguments: options.windowsVerbatimArguments || false,
+ failOnStdErr: options.failOnStdErr || false,
+ ignoreReturnCode: options.ignoreReturnCode || false,
+ delay: options.delay || 10000
+ };
+ result.outStream = options.outStream || process.stdout;
+ result.errStream = options.errStream || process.stderr;
+ return result;
+ }
+ _getSpawnOptions(options, toolPath) {
+ options = options || {};
+ const result = {};
+ result.cwd = options.cwd;
+ result.env = options.env;
+ result['windowsVerbatimArguments'] =
+ options.windowsVerbatimArguments || this._isCmdFile();
+ if (options.windowsVerbatimArguments) {
+ result.argv0 = `"${toolPath}"`;
+ }
+ return result;
+ }
+ /**
+ * Exec a tool.
+ * Output will be streamed to the live console.
+ * Returns promise with return code
+ *
+ * @param tool path to tool to exec
+ * @param options optional exec options. See ExecOptions
+ * @returns number
+ */
+ exec() {
+ return toolrunner_awaiter(this, void 0, void 0, function* () {
+ // root the tool path if it is unrooted and contains relative pathing
+ if (!isRooted(this.toolPath) &&
+ (this.toolPath.includes('/') ||
+ (toolrunner_IS_WINDOWS && this.toolPath.includes('\\')))) {
+ // prefer options.cwd if it is specified, however options.cwd may also need to be rooted
+ this.toolPath = external_path_.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath);
+ }
+ // if the tool is only a file name, then resolve it from the PATH
+ // otherwise verify it exists (add extension on Windows if necessary)
+ this.toolPath = yield which(this.toolPath, true);
+ return new Promise((resolve, reject) => toolrunner_awaiter(this, void 0, void 0, function* () {
+ this._debug(`exec tool: ${this.toolPath}`);
+ this._debug('arguments:');
+ for (const arg of this.args) {
+ this._debug(` ${arg}`);
+ }
+ const optionsNonNull = this._cloneExecOptions(this.options);
+ if (!optionsNonNull.silent && optionsNonNull.outStream) {
+ optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + external_os_namespaceObject.EOL);
+ }
+ const state = new ExecState(optionsNonNull, this.toolPath);
+ state.on('debug', (message) => {
+ this._debug(message);
+ });
+ if (this.options.cwd && !(yield exists(this.options.cwd))) {
+ return reject(new Error(`The cwd: ${this.options.cwd} does not exist!`));
+ }
+ const fileName = this._getSpawnFileName();
+ const cp = external_child_process_namespaceObject.spawn(fileName, this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(this.options, fileName));
+ let stdbuffer = '';
+ if (cp.stdout) {
+ cp.stdout.on('data', (data) => {
+ if (this.options.listeners && this.options.listeners.stdout) {
+ this.options.listeners.stdout(data);
+ }
+ if (!optionsNonNull.silent && optionsNonNull.outStream) {
+ optionsNonNull.outStream.write(data);
+ }
+ stdbuffer = this._processLineBuffer(data, stdbuffer, (line) => {
+ if (this.options.listeners && this.options.listeners.stdline) {
+ this.options.listeners.stdline(line);
+ }
+ });
+ });
+ }
+ let errbuffer = '';
+ if (cp.stderr) {
+ cp.stderr.on('data', (data) => {
+ state.processStderr = true;
+ if (this.options.listeners && this.options.listeners.stderr) {
+ this.options.listeners.stderr(data);
+ }
+ if (!optionsNonNull.silent &&
+ optionsNonNull.errStream &&
+ optionsNonNull.outStream) {
+ const s = optionsNonNull.failOnStdErr
+ ? optionsNonNull.errStream
+ : optionsNonNull.outStream;
+ s.write(data);
+ }
+ errbuffer = this._processLineBuffer(data, errbuffer, (line) => {
+ if (this.options.listeners && this.options.listeners.errline) {
+ this.options.listeners.errline(line);
+ }
+ });
+ });
+ }
+ cp.on('error', (err) => {
+ state.processError = err.message;
+ state.processExited = true;
+ state.processClosed = true;
+ state.CheckComplete();
+ });
+ cp.on('exit', (code) => {
+ state.processExitCode = code;
+ state.processExited = true;
+ this._debug(`Exit code ${code} received from tool '${this.toolPath}'`);
+ state.CheckComplete();
+ });
+ cp.on('close', (code) => {
+ state.processExitCode = code;
+ state.processExited = true;
+ state.processClosed = true;
+ this._debug(`STDIO streams have closed for tool '${this.toolPath}'`);
+ state.CheckComplete();
+ });
+ state.on('done', (error, exitCode) => {
+ if (stdbuffer.length > 0) {
+ this.emit('stdline', stdbuffer);
+ }
+ if (errbuffer.length > 0) {
+ this.emit('errline', errbuffer);
+ }
+ cp.removeAllListeners();
+ if (error) {
+ reject(error);
+ }
+ else {
+ resolve(exitCode);
+ }
+ });
+ if (this.options.input) {
+ if (!cp.stdin) {
+ throw new Error('child process missing stdin');
+ }
+ cp.stdin.end(this.options.input);
+ }
+ }));
+ });
}
-
- // 5.3. Remove all HTTP tab or space from the start and end of temporaryValue.
- temporaryValue = removeChars(temporaryValue, true, true, (char) => char === 0x9 || char === 0x20)
-
- // 5.4. Append temporaryValue to values.
- values.push(temporaryValue)
-
- // 5.6. Set temporaryValue to the empty string.
- temporaryValue = ''
- }
-
- // 6. Return values.
- return values
}
-
/**
- * @see https://fetch.spec.whatwg.org/#concept-header-list-get-decode-split
- * @param {string} name lowercase header name
- * @param {import('./headers').HeadersList} list
+ * Convert an arg string to an array of args. Handles escaping
+ *
+ * @param argString string of arguments
+ * @returns string[] array of arguments
*/
-function getDecodeSplit (name, list) {
- // 1. Let value be the result of getting name from list.
- const value = list.get(name, true)
-
- // 2. If value is null, then return null.
- if (value === null) {
- return null
- }
-
- // 3. Return the result of getting, decoding, and splitting value.
- return gettingDecodingSplitting(value)
+function argStringToArray(argString) {
+ const args = [];
+ let inQuotes = false;
+ let escaped = false;
+ let arg = '';
+ function append(c) {
+ // we only escape double quotes.
+ if (escaped && c !== '"') {
+ arg += '\\';
+ }
+ arg += c;
+ escaped = false;
+ }
+ for (let i = 0; i < argString.length; i++) {
+ const c = argString.charAt(i);
+ if (c === '"') {
+ if (!escaped) {
+ inQuotes = !inQuotes;
+ }
+ else {
+ append(c);
+ }
+ continue;
+ }
+ if (c === '\\' && escaped) {
+ append(c);
+ continue;
+ }
+ if (c === '\\' && inQuotes) {
+ escaped = true;
+ continue;
+ }
+ if (c === ' ' && !inQuotes) {
+ if (arg.length > 0) {
+ args.push(arg);
+ arg = '';
+ }
+ continue;
+ }
+ append(c);
+ }
+ if (arg.length > 0) {
+ args.push(arg.trim());
+ }
+ return args;
}
-
-const textDecoder = new TextDecoder()
-
-/**
- * @see https://encoding.spec.whatwg.org/#utf-8-decode
- * @param {Buffer} buffer
- */
-function utf8DecodeBytes (buffer) {
- if (buffer.length === 0) {
- return ''
- }
-
- // 1. Let buffer be the result of peeking three bytes from
- // ioQueue, converted to a byte sequence.
-
- // 2. If buffer is 0xEF 0xBB 0xBF, then read three
- // bytes from ioQueue. (Do nothing with those bytes.)
- if (buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) {
- buffer = buffer.subarray(3)
- }
-
- // 3. Process a queue with an instance of UTF-8’s
- // decoder, ioQueue, output, and "replacement".
- const output = textDecoder.decode(buffer)
-
- // 4. Return output.
- return output
+class ExecState extends external_events_.EventEmitter {
+ constructor(options, toolPath) {
+ super();
+ this.processClosed = false; // tracks whether the process has exited and stdio is closed
+ this.processError = '';
+ this.processExitCode = 0;
+ this.processExited = false; // tracks whether the process has exited
+ this.processStderr = false; // tracks whether stderr was written to
+ this.delay = 10000; // 10 seconds
+ this.done = false;
+ this.timeout = null;
+ if (!toolPath) {
+ throw new Error('toolPath must not be empty');
+ }
+ this.options = options;
+ this.toolPath = toolPath;
+ if (options.delay) {
+ this.delay = options.delay;
+ }
+ }
+ CheckComplete() {
+ if (this.done) {
+ return;
+ }
+ if (this.processClosed) {
+ this._setResult();
+ }
+ else if (this.processExited) {
+ this.timeout = (0,external_timers_namespaceObject.setTimeout)(ExecState.HandleTimeout, this.delay, this);
+ }
+ }
+ _debug(message) {
+ this.emit('debug', message);
+ }
+ _setResult() {
+ // determine whether there is an error
+ let error;
+ if (this.processExited) {
+ if (this.processError) {
+ error = new Error(`There was an error when attempting to execute the process '${this.toolPath}'. This may indicate the process failed to start. Error: ${this.processError}`);
+ }
+ else if (this.processExitCode !== 0 && !this.options.ignoreReturnCode) {
+ error = new Error(`The process '${this.toolPath}' failed with exit code ${this.processExitCode}`);
+ }
+ else if (this.processStderr && this.options.failOnStdErr) {
+ error = new Error(`The process '${this.toolPath}' failed because one or more lines were written to the STDERR stream`);
+ }
+ }
+ // clear the timeout
+ if (this.timeout) {
+ clearTimeout(this.timeout);
+ this.timeout = null;
+ }
+ this.done = true;
+ this.emit('done', error, this.processExitCode);
+ }
+ static HandleTimeout(state) {
+ if (state.done) {
+ return;
+ }
+ if (!state.processClosed && state.processExited) {
+ const message = `The STDIO streams did not close within ${state.delay / 1000} seconds of the exit event from process '${state.toolPath}'. This may indicate a child process inherited the STDIO streams and has not yet exited.`;
+ state._debug(message);
+ }
+ state._setResult();
+ }
}
+//# sourceMappingURL=toolrunner.js.map
+;// CONCATENATED MODULE: ./node_modules/@actions/exec/lib/exec.js
+var exec_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
-class EnvironmentSettingsObjectBase {
- get baseUrl () {
- return getGlobalOrigin()
- }
-
- get origin () {
- return this.baseUrl?.origin
- }
- policyContainer = makePolicyContainer()
+/**
+ * Exec a command.
+ * Output will be streamed to the live console.
+ * Returns promise with return code
+ *
+ * @param commandLine command to execute (can include additional args). Must be correctly escaped.
+ * @param args optional arguments for tool. Escaping is handled by the lib.
+ * @param options optional exec options. See ExecOptions
+ * @returns Promise exit code
+ */
+function exec_exec(commandLine, args, options) {
+ return exec_awaiter(this, void 0, void 0, function* () {
+ const commandArgs = argStringToArray(commandLine);
+ if (commandArgs.length === 0) {
+ throw new Error(`Parameter 'commandLine' cannot be null or empty.`);
+ }
+ // Path to tool to execute should be first arg
+ const toolPath = commandArgs[0];
+ args = commandArgs.slice(1).concat(args || []);
+ const runner = new ToolRunner(toolPath, args, options);
+ return runner.exec();
+ });
}
-
-class EnvironmentSettingsObject {
- settingsObject = new EnvironmentSettingsObjectBase()
+/**
+ * Exec a command and get the output.
+ * Output will be streamed to the live console.
+ * Returns promise with the exit code and collected stdout and stderr
+ *
+ * @param commandLine command to execute (can include additional args). Must be correctly escaped.
+ * @param args optional arguments for tool. Escaping is handled by the lib.
+ * @param options optional exec options. See ExecOptions
+ * @returns Promise exit code, stdout, and stderr
+ */
+function getExecOutput(commandLine, args, options) {
+ return exec_awaiter(this, void 0, void 0, function* () {
+ var _a, _b;
+ let stdout = '';
+ let stderr = '';
+ //Using string decoder covers the case where a mult-byte character is split
+ const stdoutDecoder = new StringDecoder('utf8');
+ const stderrDecoder = new StringDecoder('utf8');
+ const originalStdoutListener = (_a = options === null || options === void 0 ? void 0 : options.listeners) === null || _a === void 0 ? void 0 : _a.stdout;
+ const originalStdErrListener = (_b = options === null || options === void 0 ? void 0 : options.listeners) === null || _b === void 0 ? void 0 : _b.stderr;
+ const stdErrListener = (data) => {
+ stderr += stderrDecoder.write(data);
+ if (originalStdErrListener) {
+ originalStdErrListener(data);
+ }
+ };
+ const stdOutListener = (data) => {
+ stdout += stdoutDecoder.write(data);
+ if (originalStdoutListener) {
+ originalStdoutListener(data);
+ }
+ };
+ const listeners = Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.listeners), { stdout: stdOutListener, stderr: stdErrListener });
+ const exitCode = yield exec_exec(commandLine, args, Object.assign(Object.assign({}, options), { listeners }));
+ //flush any remaining characters
+ stdout += stdoutDecoder.end();
+ stderr += stderrDecoder.end();
+ return {
+ exitCode,
+ stdout,
+ stderr
+ };
+ });
}
+//# sourceMappingURL=exec.js.map
+;// CONCATENATED MODULE: ./node_modules/@actions/core/lib/platform.js
+var platform_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
-const environmentSettingsObject = new EnvironmentSettingsObject()
-module.exports = {
- isAborted,
- isCancelled,
- isValidEncodedURL,
- createDeferredPromise,
- ReadableStreamFrom,
- tryUpgradeRequestToAPotentiallyTrustworthyURL,
- clampAndCoarsenConnectionTimingInfo,
- coarsenedSharedCurrentTime,
- determineRequestsReferrer,
- makePolicyContainer,
- clonePolicyContainer,
- appendFetchMetadata,
- appendRequestOriginHeader,
- TAOCheck,
- corsCheck,
- crossOriginResourcePolicyCheck,
- createOpaqueTimingInfo,
- setRequestReferrerPolicyOnRedirect,
- isValidHTTPToken,
- requestBadPort,
- requestCurrentURL,
- responseURL,
- responseLocationURL,
- isBlobLike,
- isURLPotentiallyTrustworthy,
- isValidReasonPhrase,
- sameOrigin,
- normalizeMethod,
- serializeJavascriptValueToJSONString,
- iteratorMixin,
- createIterator,
- isValidHeaderName,
- isValidHeaderValue,
- isErrorLike,
- fullyReadBody,
- bytesMatch,
- isReadableStreamLike,
- readableStreamClose,
- isomorphicEncode,
- urlIsLocal,
- urlHasHttpsScheme,
- urlIsHttpHttpsScheme,
- readAllBytes,
- simpleRangeHeaderValue,
- buildContentRange,
- parseMetadata,
- createInflate,
- extractMimeType,
- getDecodeSplit,
- utf8DecodeBytes,
- environmentSettingsObject
+const getWindowsInfo = () => platform_awaiter(void 0, void 0, void 0, function* () {
+ const { stdout: version } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Version"', undefined, {
+ silent: true
+ });
+ const { stdout: name } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Caption"', undefined, {
+ silent: true
+ });
+ return {
+ name: name.trim(),
+ version: version.trim()
+ };
+});
+const getMacOsInfo = () => platform_awaiter(void 0, void 0, void 0, function* () {
+ var _a, _b, _c, _d;
+ const { stdout } = yield exec.getExecOutput('sw_vers', undefined, {
+ silent: true
+ });
+ const version = (_b = (_a = stdout.match(/ProductVersion:\s*(.+)/)) === null || _a === void 0 ? void 0 : _a[1]) !== null && _b !== void 0 ? _b : '';
+ const name = (_d = (_c = stdout.match(/ProductName:\s*(.+)/)) === null || _c === void 0 ? void 0 : _c[1]) !== null && _d !== void 0 ? _d : '';
+ return {
+ name,
+ version
+ };
+});
+const getLinuxInfo = () => platform_awaiter(void 0, void 0, void 0, function* () {
+ const { stdout } = yield exec.getExecOutput('lsb_release', ['-i', '-r', '-s'], {
+ silent: true
+ });
+ const [name, version] = stdout.trim().split('\n');
+ return {
+ name,
+ version
+ };
+});
+const platform = external_os_namespaceObject.platform();
+const arch = external_os_namespaceObject.arch();
+const isWindows = platform === 'win32';
+const isMacOS = platform === 'darwin';
+const isLinux = platform === 'linux';
+function getDetails() {
+ return platform_awaiter(this, void 0, void 0, function* () {
+ return Object.assign(Object.assign({}, (yield (isWindows
+ ? getWindowsInfo()
+ : isMacOS
+ ? getMacOsInfo()
+ : getLinuxInfo()))), { platform,
+ arch,
+ isWindows,
+ isMacOS,
+ isLinux });
+ });
}
+//# sourceMappingURL=platform.js.map
+;// CONCATENATED MODULE: ./node_modules/@actions/core/lib/core.js
+var core_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
-/***/ }),
-
-/***/ 253:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-const { types, inspect } = __nccwpck_require__(7975)
-const { markAsUncloneable } = __nccwpck_require__(5919)
-const { toUSVString } = __nccwpck_require__(1544)
-/** @type {import('../../../types/webidl').Webidl} */
-const webidl = {}
-webidl.converters = {}
-webidl.util = {}
-webidl.errors = {}
-webidl.errors.exception = function (message) {
- return new TypeError(`${message.header}: ${message.message}`)
+/**
+ * The code to exit an action
+ */
+var ExitCode;
+(function (ExitCode) {
+ /**
+ * A code indicating that the action was successful
+ */
+ ExitCode[ExitCode["Success"] = 0] = "Success";
+ /**
+ * A code indicating that the action was a failure
+ */
+ ExitCode[ExitCode["Failure"] = 1] = "Failure";
+})(ExitCode || (ExitCode = {}));
+//-----------------------------------------------------------------------
+// Variables
+//-----------------------------------------------------------------------
+/**
+ * Sets env variable for this action and future actions in the job
+ * @param name the name of the variable to set
+ * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify
+ */
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+function exportVariable(name, val) {
+ const convertedVal = utils_toCommandValue(val);
+ process.env[name] = convertedVal;
+ const filePath = process.env['GITHUB_ENV'] || '';
+ if (filePath) {
+ return file_command_issueFileCommand('ENV', file_command_prepareKeyValueMessage(name, val));
+ }
+ command_issueCommand('set-env', { name }, convertedVal);
}
-
-webidl.errors.conversionFailed = function (context) {
- const plural = context.types.length === 1 ? '' : ' one of'
- const message =
- `${context.argument} could not be converted to` +
- `${plural}: ${context.types.join(', ')}.`
-
- return webidl.errors.exception({
- header: context.prefix,
- message
- })
+/**
+ * Registers a secret which will get masked from logs
+ *
+ * @param secret - Value of the secret to be masked
+ * @remarks
+ * This function instructs the Actions runner to mask the specified value in any
+ * logs produced during the workflow run. Once registered, the secret value will
+ * be replaced with asterisks (***) whenever it appears in console output, logs,
+ * or error messages.
+ *
+ * This is useful for protecting sensitive information such as:
+ * - API keys
+ * - Access tokens
+ * - Authentication credentials
+ * - URL parameters containing signatures (SAS tokens)
+ *
+ * Note that masking only affects future logs; any previous appearances of the
+ * secret in logs before calling this function will remain unmasked.
+ *
+ * @example
+ * ```typescript
+ * // Register an API token as a secret
+ * const apiToken = "abc123xyz456";
+ * setSecret(apiToken);
+ *
+ * // Now any logs containing this value will show *** instead
+ * console.log(`Using token: ${apiToken}`); // Outputs: "Using token: ***"
+ * ```
+ */
+function core_setSecret(secret) {
+ command_issueCommand('add-mask', {}, secret);
}
-
-webidl.errors.invalidArgument = function (context) {
- return webidl.errors.exception({
- header: context.prefix,
- message: `"${context.value}" is an invalid ${context.type}.`
- })
+/**
+ * Prepends inputPath to the PATH (for this action and future actions)
+ * @param inputPath
+ */
+function addPath(inputPath) {
+ const filePath = process.env['GITHUB_PATH'] || '';
+ if (filePath) {
+ file_command_issueFileCommand('PATH', inputPath);
+ }
+ else {
+ command_issueCommand('add-path', {}, inputPath);
+ }
+ process.env['PATH'] = `${inputPath}${external_path_.delimiter}${process.env['PATH']}`;
}
-
-// https://webidl.spec.whatwg.org/#implements
-webidl.brandCheck = function (V, I, opts) {
- if (opts?.strict !== false) {
- if (!(V instanceof I)) {
- const err = new TypeError('Illegal invocation')
- err.code = 'ERR_INVALID_THIS' // node compat.
- throw err
+/**
+ * Gets the value of an input.
+ * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed.
+ * Returns an empty string if the value is not defined.
+ *
+ * @param name name of the input to get
+ * @param options optional. See InputOptions.
+ * @returns string
+ */
+function getInput(name, options) {
+ const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || '';
+ if (options && options.required && !val) {
+ throw new Error(`Input required and not supplied: ${name}`);
}
- } else {
- if (V?.[Symbol.toStringTag] !== I.prototype[Symbol.toStringTag]) {
- const err = new TypeError('Illegal invocation')
- err.code = 'ERR_INVALID_THIS' // node compat.
- throw err
+ if (options && options.trimWhitespace === false) {
+ return val;
}
- }
+ return val.trim();
}
-
-webidl.argumentLengthCheck = function ({ length }, min, ctx) {
- if (length < min) {
- throw webidl.errors.exception({
- message: `${min} argument${min !== 1 ? 's' : ''} required, ` +
- `but${length ? ' only' : ''} ${length} found.`,
- header: ctx
- })
- }
+/**
+ * Gets the values of an multiline input. Each value is also trimmed.
+ *
+ * @param name name of the input to get
+ * @param options optional. See InputOptions.
+ * @returns string[]
+ *
+ */
+function getMultilineInput(name, options) {
+ const inputs = getInput(name, options)
+ .split('\n')
+ .filter(x => x !== '');
+ if (options && options.trimWhitespace === false) {
+ return inputs;
+ }
+ return inputs.map(input => input.trim());
}
-
-webidl.illegalConstructor = function () {
- throw webidl.errors.exception({
- header: 'TypeError',
- message: 'Illegal constructor'
- })
+/**
+ * Gets the input value of the boolean type in the YAML 1.2 "core schema" specification.
+ * Support boolean input list: `true | True | TRUE | false | False | FALSE` .
+ * The return value is also in boolean type.
+ * ref: https://yaml.org/spec/1.2/spec.html#id2804923
+ *
+ * @param name name of the input to get
+ * @param options optional. See InputOptions.
+ * @returns boolean
+ */
+function getBooleanInput(name, options) {
+ const trueValue = ['true', 'True', 'TRUE'];
+ const falseValue = ['false', 'False', 'FALSE'];
+ const val = getInput(name, options);
+ if (trueValue.includes(val))
+ return true;
+ if (falseValue.includes(val))
+ return false;
+ throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${name}\n` +
+ `Support boolean input list: \`true | True | TRUE | false | False | FALSE\``);
}
-
-// https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values
-webidl.util.Type = function (V) {
- switch (typeof V) {
- case 'undefined': return 'Undefined'
- case 'boolean': return 'Boolean'
- case 'string': return 'String'
- case 'symbol': return 'Symbol'
- case 'number': return 'Number'
- case 'bigint': return 'BigInt'
- case 'function':
- case 'object': {
- if (V === null) {
- return 'Null'
- }
-
- return 'Object'
+/**
+ * Sets the value of an output.
+ *
+ * @param name name of the output to set
+ * @param value value to store. Non-string values will be converted to a string via JSON.stringify
+ */
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+function setOutput(name, value) {
+ const filePath = process.env['GITHUB_OUTPUT'] || '';
+ if (filePath) {
+ return issueFileCommand('OUTPUT', prepareKeyValueMessage(name, value));
}
- }
+ process.stdout.write(os.EOL);
+ issueCommand('set-output', { name }, toCommandValue(value));
}
-
-webidl.util.markAsUncloneable = markAsUncloneable || (() => {})
-// https://webidl.spec.whatwg.org/#abstract-opdef-converttoint
-webidl.util.ConvertToInt = function (V, bitLength, signedness, opts) {
- let upperBound
- let lowerBound
-
- // 1. If bitLength is 64, then:
- if (bitLength === 64) {
- // 1. Let upperBound be 2^53 − 1.
- upperBound = Math.pow(2, 53) - 1
-
- // 2. If signedness is "unsigned", then let lowerBound be 0.
- if (signedness === 'unsigned') {
- lowerBound = 0
- } else {
- // 3. Otherwise let lowerBound be −2^53 + 1.
- lowerBound = Math.pow(-2, 53) + 1
+/**
+ * Enables or disables the echoing of commands into stdout for the rest of the step.
+ * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set.
+ *
+ */
+function setCommandEcho(enabled) {
+ issue('echo', enabled ? 'on' : 'off');
+}
+//-----------------------------------------------------------------------
+// Results
+//-----------------------------------------------------------------------
+/**
+ * Sets the action status to failed.
+ * When the action exits it will be with an exit code of 1
+ * @param message add error issue message
+ */
+function setFailed(message) {
+ process.exitCode = ExitCode.Failure;
+ core_error(message);
+}
+//-----------------------------------------------------------------------
+// Logging Commands
+//-----------------------------------------------------------------------
+/**
+ * Gets whether Actions Step Debug is on or not
+ */
+function isDebug() {
+ return process.env['RUNNER_DEBUG'] === '1';
+}
+/**
+ * Writes debug message to user log
+ * @param message debug message
+ */
+function core_debug(message) {
+ command_issueCommand('debug', {}, message);
+}
+/**
+ * Adds an error issue
+ * @param message error issue message. Errors will be converted to string via toString()
+ * @param properties optional properties to add to the annotation.
+ */
+function core_error(message, properties = {}) {
+ command_issueCommand('error', utils_toCommandProperties(properties), message instanceof Error ? message.toString() : message);
+}
+/**
+ * Adds a warning issue
+ * @param message warning issue message. Errors will be converted to string via toString()
+ * @param properties optional properties to add to the annotation.
+ */
+function warning(message, properties = {}) {
+ command_issueCommand('warning', utils_toCommandProperties(properties), message instanceof Error ? message.toString() : message);
+}
+/**
+ * Adds a notice issue
+ * @param message notice issue message. Errors will be converted to string via toString()
+ * @param properties optional properties to add to the annotation.
+ */
+function notice(message, properties = {}) {
+ issueCommand('notice', toCommandProperties(properties), message instanceof Error ? message.toString() : message);
+}
+/**
+ * Writes info to log with console.log.
+ * @param message info message
+ */
+function info(message) {
+ process.stdout.write(message + external_os_namespaceObject.EOL);
+}
+/**
+ * Begin an output group.
+ *
+ * Output until the next `groupEnd` will be foldable in this group
+ *
+ * @param name The name of the output group
+ */
+function startGroup(name) {
+ command_issue('group', name);
+}
+/**
+ * End an output group.
+ */
+function endGroup() {
+ command_issue('endgroup');
+}
+/**
+ * Wrap an asynchronous function call in a group.
+ *
+ * Returns the same type as the function itself.
+ *
+ * @param name The name of the group
+ * @param fn The function to wrap in the group
+ */
+function group(name, fn) {
+ return core_awaiter(this, void 0, void 0, function* () {
+ startGroup(name);
+ let result;
+ try {
+ result = yield fn();
+ }
+ finally {
+ endGroup();
+ }
+ return result;
+ });
+}
+//-----------------------------------------------------------------------
+// Wrapper action state
+//-----------------------------------------------------------------------
+/**
+ * Saves state for current action, the state can only be retrieved by this action's post job execution.
+ *
+ * @param name name of the state to store
+ * @param value value to store. Non-string values will be converted to a string via JSON.stringify
+ */
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+function saveState(name, value) {
+ const filePath = process.env['GITHUB_STATE'] || '';
+ if (filePath) {
+ return file_command_issueFileCommand('STATE', file_command_prepareKeyValueMessage(name, value));
}
- } else if (signedness === 'unsigned') {
- // 2. Otherwise, if signedness is "unsigned", then:
-
- // 1. Let lowerBound be 0.
- lowerBound = 0
-
- // 2. Let upperBound be 2^bitLength − 1.
- upperBound = Math.pow(2, bitLength) - 1
- } else {
- // 3. Otherwise:
+ command_issueCommand('save-state', { name }, utils_toCommandValue(value));
+}
+/**
+ * Gets the value of an state set by this action's main execution.
+ *
+ * @param name name of the state to get
+ * @returns string
+ */
+function getState(name) {
+ return process.env[`STATE_${name}`] || '';
+}
+function getIDToken(aud) {
+ return core_awaiter(this, void 0, void 0, function* () {
+ return yield OidcClient.getIDToken(aud);
+ });
+}
+/**
+ * Summary exports
+ */
- // 1. Let lowerBound be -2^bitLength − 1.
- lowerBound = Math.pow(-2, bitLength) - 1
+/**
+ * @deprecated use core.summary
+ */
- // 2. Let upperBound be 2^bitLength − 1 − 1.
- upperBound = Math.pow(2, bitLength - 1) - 1
- }
+/**
+ * Path exports
+ */
- // 4. Let x be ? ToNumber(V).
- let x = Number(V)
+/**
+ * Platform utilities exports
+ */
- // 5. If x is −0, then set x to +0.
- if (x === 0) {
- x = 0
- }
+//# sourceMappingURL=core.js.map
+;// CONCATENATED MODULE: ./node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-glob-options-helper.js
- // 6. If the conversion is to an IDL type associated
- // with the [EnforceRange] extended attribute, then:
- if (opts?.enforceRange === true) {
- // 1. If x is NaN, +∞, or −∞, then throw a TypeError.
- if (
- Number.isNaN(x) ||
- x === Number.POSITIVE_INFINITY ||
- x === Number.NEGATIVE_INFINITY
- ) {
- throw webidl.errors.exception({
- header: 'Integer conversion',
- message: `Could not convert ${webidl.util.Stringify(V)} to an integer.`
- })
+/**
+ * Returns a copy with defaults filled in.
+ */
+function getOptions(copy) {
+ const result = {
+ followSymbolicLinks: true,
+ implicitDescendants: true,
+ matchDirectories: true,
+ omitBrokenSymbolicLinks: true,
+ excludeHiddenFiles: false
+ };
+ if (copy) {
+ if (typeof copy.followSymbolicLinks === 'boolean') {
+ result.followSymbolicLinks = copy.followSymbolicLinks;
+ core.debug(`followSymbolicLinks '${result.followSymbolicLinks}'`);
+ }
+ if (typeof copy.implicitDescendants === 'boolean') {
+ result.implicitDescendants = copy.implicitDescendants;
+ core.debug(`implicitDescendants '${result.implicitDescendants}'`);
+ }
+ if (typeof copy.matchDirectories === 'boolean') {
+ result.matchDirectories = copy.matchDirectories;
+ core.debug(`matchDirectories '${result.matchDirectories}'`);
+ }
+ if (typeof copy.omitBrokenSymbolicLinks === 'boolean') {
+ result.omitBrokenSymbolicLinks = copy.omitBrokenSymbolicLinks;
+ core.debug(`omitBrokenSymbolicLinks '${result.omitBrokenSymbolicLinks}'`);
+ }
+ if (typeof copy.excludeHiddenFiles === 'boolean') {
+ result.excludeHiddenFiles = copy.excludeHiddenFiles;
+ core.debug(`excludeHiddenFiles '${result.excludeHiddenFiles}'`);
+ }
}
+ return result;
+}
+//# sourceMappingURL=internal-glob-options-helper.js.map
+;// CONCATENATED MODULE: ./node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-path-helper.js
- // 2. Set x to IntegerPart(x).
- x = webidl.util.IntegerPart(x)
- // 3. If x < lowerBound or x > upperBound, then
- // throw a TypeError.
- if (x < lowerBound || x > upperBound) {
- throw webidl.errors.exception({
- header: 'Integer conversion',
- message: `Value must be between ${lowerBound}-${upperBound}, got ${x}.`
- })
+const internal_path_helper_IS_WINDOWS = process.platform === 'win32';
+/**
+ * Similar to path.dirname except normalizes the path separators and slightly better handling for Windows UNC paths.
+ *
+ * For example, on Linux/macOS:
+ * - `/ => /`
+ * - `/hello => /`
+ *
+ * For example, on Windows:
+ * - `C:\ => C:\`
+ * - `C:\hello => C:\`
+ * - `C: => C:`
+ * - `C:hello => C:`
+ * - `\ => \`
+ * - `\hello => \`
+ * - `\\hello => \\hello`
+ * - `\\hello\world => \\hello\world`
+ */
+function dirname(p) {
+ // Normalize slashes and trim unnecessary trailing slash
+ p = safeTrimTrailingSeparator(p);
+ // Windows UNC root, e.g. \\hello or \\hello\world
+ if (internal_path_helper_IS_WINDOWS && /^\\\\[^\\]+(\\[^\\]+)?$/.test(p)) {
+ return p;
}
-
- // 4. Return x.
- return x
- }
-
- // 7. If x is not NaN and the conversion is to an IDL
- // type associated with the [Clamp] extended
- // attribute, then:
- if (!Number.isNaN(x) && opts?.clamp === true) {
- // 1. Set x to min(max(x, lowerBound), upperBound).
- x = Math.min(Math.max(x, lowerBound), upperBound)
-
- // 2. Round x to the nearest integer, choosing the
- // even integer if it lies halfway between two,
- // and choosing +0 rather than −0.
- if (Math.floor(x) % 2 === 0) {
- x = Math.floor(x)
- } else {
- x = Math.ceil(x)
+ // Get dirname
+ let result = path.dirname(p);
+ // Trim trailing slash for Windows UNC root, e.g. \\hello\world\
+ if (internal_path_helper_IS_WINDOWS && /^\\\\[^\\]+\\[^\\]+\\$/.test(result)) {
+ result = safeTrimTrailingSeparator(result);
}
-
- // 3. Return x.
- return x
- }
-
- // 8. If x is NaN, +0, +∞, or −∞, then return +0.
- if (
- Number.isNaN(x) ||
- (x === 0 && Object.is(0, x)) ||
- x === Number.POSITIVE_INFINITY ||
- x === Number.NEGATIVE_INFINITY
- ) {
- return 0
- }
-
- // 9. Set x to IntegerPart(x).
- x = webidl.util.IntegerPart(x)
-
- // 10. Set x to x modulo 2^bitLength.
- x = x % Math.pow(2, bitLength)
-
- // 11. If signedness is "signed" and x ≥ 2^bitLength − 1,
- // then return x − 2^bitLength.
- if (signedness === 'signed' && x >= Math.pow(2, bitLength) - 1) {
- return x - Math.pow(2, bitLength)
- }
-
- // 12. Otherwise, return x.
- return x
-}
-
-// https://webidl.spec.whatwg.org/#abstract-opdef-integerpart
-webidl.util.IntegerPart = function (n) {
- // 1. Let r be floor(abs(n)).
- const r = Math.floor(Math.abs(n))
-
- // 2. If n < 0, then return -1 × r.
- if (n < 0) {
- return -1 * r
- }
-
- // 3. Otherwise, return r.
- return r
+ return result;
}
-
-webidl.util.Stringify = function (V) {
- const type = webidl.util.Type(V)
-
- switch (type) {
- case 'Symbol':
- return `Symbol(${V.description})`
- case 'Object':
- return inspect(V)
- case 'String':
- return `"${V}"`
- default:
- return `${V}`
- }
+/**
+ * Roots the path if not already rooted. On Windows, relative roots like `\`
+ * or `C:` are expanded based on the current working directory.
+ */
+function ensureAbsoluteRoot(root, itemPath) {
+ assert(root, `ensureAbsoluteRoot parameter 'root' must not be empty`);
+ assert(itemPath, `ensureAbsoluteRoot parameter 'itemPath' must not be empty`);
+ // Already rooted
+ if (hasAbsoluteRoot(itemPath)) {
+ return itemPath;
+ }
+ // Windows
+ if (internal_path_helper_IS_WINDOWS) {
+ // Check for itemPath like C: or C:foo
+ if (itemPath.match(/^[A-Z]:[^\\/]|^[A-Z]:$/i)) {
+ let cwd = process.cwd();
+ assert(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`);
+ // Drive letter matches cwd? Expand to cwd
+ if (itemPath[0].toUpperCase() === cwd[0].toUpperCase()) {
+ // Drive only, e.g. C:
+ if (itemPath.length === 2) {
+ // Preserve specified drive letter case (upper or lower)
+ return `${itemPath[0]}:\\${cwd.substr(3)}`;
+ }
+ // Drive + path, e.g. C:foo
+ else {
+ if (!cwd.endsWith('\\')) {
+ cwd += '\\';
+ }
+ // Preserve specified drive letter case (upper or lower)
+ return `${itemPath[0]}:\\${cwd.substr(3)}${itemPath.substr(2)}`;
+ }
+ }
+ // Different drive
+ else {
+ return `${itemPath[0]}:\\${itemPath.substr(2)}`;
+ }
+ }
+ // Check for itemPath like \ or \foo
+ else if (internal_path_helper_normalizeSeparators(itemPath).match(/^\\$|^\\[^\\]/)) {
+ const cwd = process.cwd();
+ assert(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`);
+ return `${cwd[0]}:\\${itemPath.substr(1)}`;
+ }
+ }
+ assert(hasAbsoluteRoot(root), `ensureAbsoluteRoot parameter 'root' must have an absolute root`);
+ // Otherwise ensure root ends with a separator
+ if (root.endsWith('/') || (internal_path_helper_IS_WINDOWS && root.endsWith('\\'))) {
+ // Intentionally empty
+ }
+ else {
+ // Append separator
+ root += path.sep;
+ }
+ return root + itemPath;
}
-
-// https://webidl.spec.whatwg.org/#es-sequence
-webidl.sequenceConverter = function (converter) {
- return (V, prefix, argument, Iterable) => {
- // 1. If Type(V) is not Object, throw a TypeError.
- if (webidl.util.Type(V) !== 'Object') {
- throw webidl.errors.exception({
- header: prefix,
- message: `${argument} (${webidl.util.Stringify(V)}) is not iterable.`
- })
+/**
+ * On Linux/macOS, true if path starts with `/`. On Windows, true for paths like:
+ * `\\hello\share` and `C:\hello` (and using alternate separator).
+ */
+function hasAbsoluteRoot(itemPath) {
+ assert(itemPath, `hasAbsoluteRoot parameter 'itemPath' must not be empty`);
+ // Normalize separators
+ itemPath = internal_path_helper_normalizeSeparators(itemPath);
+ // Windows
+ if (internal_path_helper_IS_WINDOWS) {
+ // E.g. \\hello\share or C:\hello
+ return itemPath.startsWith('\\\\') || /^[A-Z]:\\/i.test(itemPath);
}
-
- // 2. Let method be ? GetMethod(V, @@iterator).
- /** @type {Generator} */
- const method = typeof Iterable === 'function' ? Iterable() : V?.[Symbol.iterator]?.()
- const seq = []
- let index = 0
-
- // 3. If method is undefined, throw a TypeError.
- if (
- method === undefined ||
- typeof method.next !== 'function'
- ) {
- throw webidl.errors.exception({
- header: prefix,
- message: `${argument} is not iterable.`
- })
+ // E.g. /hello
+ return itemPath.startsWith('/');
+}
+/**
+ * On Linux/macOS, true if path starts with `/`. On Windows, true for paths like:
+ * `\`, `\hello`, `\\hello\share`, `C:`, and `C:\hello` (and using alternate separator).
+ */
+function hasRoot(itemPath) {
+ assert(itemPath, `isRooted parameter 'itemPath' must not be empty`);
+ // Normalize separators
+ itemPath = internal_path_helper_normalizeSeparators(itemPath);
+ // Windows
+ if (internal_path_helper_IS_WINDOWS) {
+ // E.g. \ or \hello or \\hello
+ // E.g. C: or C:\hello
+ return itemPath.startsWith('\\') || /^[A-Z]:/i.test(itemPath);
}
-
- // https://webidl.spec.whatwg.org/#create-sequence-from-iterable
- while (true) {
- const { done, value } = method.next()
-
- if (done) {
- break
- }
-
- seq.push(converter(value, prefix, `${argument}[${index++}]`))
+ // E.g. /hello
+ return itemPath.startsWith('/');
+}
+/**
+ * Removes redundant slashes and converts `/` to `\` on Windows
+ */
+function internal_path_helper_normalizeSeparators(p) {
+ p = p || '';
+ // Windows
+ if (internal_path_helper_IS_WINDOWS) {
+ // Convert slashes on Windows
+ p = p.replace(/\//g, '\\');
+ // Remove redundant slashes
+ const isUnc = /^\\\\+[^\\]/.test(p); // e.g. \\hello
+ return (isUnc ? '\\' : '') + p.replace(/\\\\+/g, '\\'); // preserve leading \\ for UNC
}
-
- return seq
- }
+ // Remove redundant slashes
+ return p.replace(/\/\/+/g, '/');
}
-
-// https://webidl.spec.whatwg.org/#es-to-record
-webidl.recordConverter = function (keyConverter, valueConverter) {
- return (O, prefix, argument) => {
- // 1. If Type(O) is not Object, throw a TypeError.
- if (webidl.util.Type(O) !== 'Object') {
- throw webidl.errors.exception({
- header: prefix,
- message: `${argument} ("${webidl.util.Type(O)}") is not an Object.`
- })
+/**
+ * Normalizes the path separators and trims the trailing separator (when safe).
+ * For example, `/foo/ => /foo` but `/ => /`
+ */
+function safeTrimTrailingSeparator(p) {
+ // Short-circuit if empty
+ if (!p) {
+ return '';
+ }
+ // Normalize separators
+ p = internal_path_helper_normalizeSeparators(p);
+ // No trailing slash
+ if (!p.endsWith(path.sep)) {
+ return p;
+ }
+ // Check '/' on Linux/macOS and '\' on Windows
+ if (p === path.sep) {
+ return p;
+ }
+ // On Windows check if drive root. E.g. C:\
+ if (internal_path_helper_IS_WINDOWS && /^[A-Z]:\\$/i.test(p)) {
+ return p;
}
+ // Otherwise trim trailing slash
+ return p.substr(0, p.length - 1);
+}
+//# sourceMappingURL=internal-path-helper.js.map
+;// CONCATENATED MODULE: ./node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-match-kind.js
+/**
+ * Indicates whether a pattern matches a path
+ */
+var internal_match_kind_MatchKind;
+(function (MatchKind) {
+ /** Not matched */
+ MatchKind[MatchKind["None"] = 0] = "None";
+ /** Matched if the path is a directory */
+ MatchKind[MatchKind["Directory"] = 1] = "Directory";
+ /** Matched if the path is a regular file */
+ MatchKind[MatchKind["File"] = 2] = "File";
+ /** Matched */
+ MatchKind[MatchKind["All"] = 3] = "All";
+})(internal_match_kind_MatchKind || (internal_match_kind_MatchKind = {}));
+//# sourceMappingURL=internal-match-kind.js.map
+;// CONCATENATED MODULE: ./node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-pattern-helper.js
- // 2. Let result be a new empty instance of record.
- const result = {}
- if (!types.isProxy(O)) {
- // 1. Let desc be ? O.[[GetOwnProperty]](key).
- const keys = [...Object.getOwnPropertyNames(O), ...Object.getOwnPropertySymbols(O)]
-
- for (const key of keys) {
- // 1. Let typedKey be key converted to an IDL value of type K.
- const typedKey = keyConverter(key, prefix, argument)
-
- // 2. Let value be ? Get(O, key).
- // 3. Let typedValue be value converted to an IDL value of type V.
- const typedValue = valueConverter(O[key], prefix, argument)
-
- // 4. Set result[typedKey] to typedValue.
- result[typedKey] = typedValue
- }
-
- // 5. Return result.
- return result
+const internal_pattern_helper_IS_WINDOWS = process.platform === 'win32';
+/**
+ * Given an array of patterns, returns an array of paths to search.
+ * Duplicates and paths under other included paths are filtered out.
+ */
+function getSearchPaths(patterns) {
+ // Ignore negate patterns
+ patterns = patterns.filter(x => !x.negate);
+ // Create a map of all search paths
+ const searchPathMap = {};
+ for (const pattern of patterns) {
+ const key = internal_pattern_helper_IS_WINDOWS
+ ? pattern.searchPath.toUpperCase()
+ : pattern.searchPath;
+ searchPathMap[key] = 'candidate';
}
-
- // 3. Let keys be ? O.[[OwnPropertyKeys]]().
- const keys = Reflect.ownKeys(O)
-
- // 4. For each key of keys.
- for (const key of keys) {
- // 1. Let desc be ? O.[[GetOwnProperty]](key).
- const desc = Reflect.getOwnPropertyDescriptor(O, key)
-
- // 2. If desc is not undefined and desc.[[Enumerable]] is true:
- if (desc?.enumerable) {
- // 1. Let typedKey be key converted to an IDL value of type K.
- const typedKey = keyConverter(key, prefix, argument)
-
- // 2. Let value be ? Get(O, key).
- // 3. Let typedValue be value converted to an IDL value of type V.
- const typedValue = valueConverter(O[key], prefix, argument)
-
- // 4. Set result[typedKey] to typedValue.
- result[typedKey] = typedValue
- }
+ const result = [];
+ for (const pattern of patterns) {
+ // Check if already included
+ const key = internal_pattern_helper_IS_WINDOWS
+ ? pattern.searchPath.toUpperCase()
+ : pattern.searchPath;
+ if (searchPathMap[key] === 'included') {
+ continue;
+ }
+ // Check for an ancestor search path
+ let foundAncestor = false;
+ let tempKey = key;
+ let parent = pathHelper.dirname(tempKey);
+ while (parent !== tempKey) {
+ if (searchPathMap[parent]) {
+ foundAncestor = true;
+ break;
+ }
+ tempKey = parent;
+ parent = pathHelper.dirname(tempKey);
+ }
+ // Include the search pattern in the result
+ if (!foundAncestor) {
+ result.push(pattern.searchPath);
+ searchPathMap[key] = 'included';
+ }
}
-
- // 5. Return result.
- return result
- }
+ return result;
}
-
-webidl.interfaceConverter = function (i) {
- return (V, prefix, argument, opts) => {
- if (opts?.strict !== false && !(V instanceof i)) {
- throw webidl.errors.exception({
- header: prefix,
- message: `Expected ${argument} ("${webidl.util.Stringify(V)}") to be an instance of ${i.name}.`
- })
+/**
+ * Matches the patterns against the path
+ */
+function match(patterns, itemPath) {
+ let result = MatchKind.None;
+ for (const pattern of patterns) {
+ if (pattern.negate) {
+ result &= ~pattern.match(itemPath);
+ }
+ else {
+ result |= pattern.match(itemPath);
+ }
}
-
- return V
- }
+ return result;
}
+/**
+ * Checks whether to descend further into the directory
+ */
+function partialMatch(patterns, itemPath) {
+ return patterns.some(x => !x.negate && x.partialMatch(itemPath));
+}
+//# sourceMappingURL=internal-pattern-helper.js.map
+// EXTERNAL MODULE: ./node_modules/minimatch/minimatch.js
+var minimatch = __nccwpck_require__(3772);
+;// CONCATENATED MODULE: ./node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-path.js
-webidl.dictionaryConverter = function (converters) {
- return (dictionary, prefix, argument) => {
- const type = webidl.util.Type(dictionary)
- const dict = {}
-
- if (type === 'Null' || type === 'Undefined') {
- return dict
- } else if (type !== 'Object') {
- throw webidl.errors.exception({
- header: prefix,
- message: `Expected ${dictionary} to be one of: Null, Undefined, Object.`
- })
- }
- for (const options of converters) {
- const { key, defaultValue, required, converter } = options
- if (required === true) {
- if (!Object.hasOwn(dictionary, key)) {
- throw webidl.errors.exception({
- header: prefix,
- message: `Missing required key "${key}".`
- })
+const internal_path_IS_WINDOWS = process.platform === 'win32';
+/**
+ * Helper class for parsing paths into segments
+ */
+class internal_path_Path {
+ /**
+ * Constructs a Path
+ * @param itemPath Path or array of segments
+ */
+ constructor(itemPath) {
+ this.segments = [];
+ // String
+ if (typeof itemPath === 'string') {
+ assert(itemPath, `Parameter 'itemPath' must not be empty`);
+ // Normalize slashes and trim unnecessary trailing slash
+ itemPath = pathHelper.safeTrimTrailingSeparator(itemPath);
+ // Not rooted
+ if (!pathHelper.hasRoot(itemPath)) {
+ this.segments = itemPath.split(path.sep);
+ }
+ // Rooted
+ else {
+ // Add all segments, while not at the root
+ let remaining = itemPath;
+ let dir = pathHelper.dirname(remaining);
+ while (dir !== remaining) {
+ // Add the segment
+ const basename = path.basename(remaining);
+ this.segments.unshift(basename);
+ // Truncate the last segment
+ remaining = dir;
+ dir = pathHelper.dirname(remaining);
+ }
+ // Remainder is the root
+ this.segments.unshift(remaining);
+ }
}
- }
-
- let value = dictionary[key]
- const hasDefault = Object.hasOwn(options, 'defaultValue')
-
- // Only use defaultValue if value is undefined and
- // a defaultValue options was provided.
- if (hasDefault && value !== null) {
- value ??= defaultValue()
- }
-
- // A key can be optional and have no default value.
- // When this happens, do not perform a conversion,
- // and do not assign the key a value.
- if (required || hasDefault || value !== undefined) {
- value = converter(value, prefix, `${argument}.${key}`)
-
- if (
- options.allowedValues &&
- !options.allowedValues.includes(value)
- ) {
- throw webidl.errors.exception({
- header: prefix,
- message: `${value} is not an accepted type. Expected one of ${options.allowedValues.join(', ')}.`
- })
+ // Array
+ else {
+ // Must not be empty
+ assert(itemPath.length > 0, `Parameter 'itemPath' must not be an empty array`);
+ // Each segment
+ for (let i = 0; i < itemPath.length; i++) {
+ let segment = itemPath[i];
+ // Must not be empty
+ assert(segment, `Parameter 'itemPath' must not contain any empty segments`);
+ // Normalize slashes
+ segment = pathHelper.normalizeSeparators(itemPath[i]);
+ // Root segment
+ if (i === 0 && pathHelper.hasRoot(segment)) {
+ segment = pathHelper.safeTrimTrailingSeparator(segment);
+ assert(segment === pathHelper.dirname(segment), `Parameter 'itemPath' root segment contains information for multiple segments`);
+ this.segments.push(segment);
+ }
+ // All other segments
+ else {
+ // Must not contain slash
+ assert(!segment.includes(path.sep), `Parameter 'itemPath' contains unexpected path separators`);
+ this.segments.push(segment);
+ }
+ }
}
-
- dict[key] = value
- }
}
-
- return dict
- }
+ /**
+ * Converts the path to it's string representation
+ */
+ toString() {
+ // First segment
+ let result = this.segments[0];
+ // All others
+ let skipSlash = result.endsWith(path.sep) || (internal_path_IS_WINDOWS && /^[A-Z]:$/i.test(result));
+ for (let i = 1; i < this.segments.length; i++) {
+ if (skipSlash) {
+ skipSlash = false;
+ }
+ else {
+ result += path.sep;
+ }
+ result += this.segments[i];
+ }
+ return result;
+ }
}
+//# sourceMappingURL=internal-path.js.map
+;// CONCATENATED MODULE: ./node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-pattern.js
-webidl.nullableConverter = function (converter) {
- return (V, prefix, argument) => {
- if (V === null) {
- return V
- }
- return converter(V, prefix, argument)
- }
-}
-// https://webidl.spec.whatwg.org/#es-DOMString
-webidl.converters.DOMString = function (V, prefix, argument, opts) {
- // 1. If V is null and the conversion is to an IDL type
- // associated with the [LegacyNullToEmptyString]
- // extended attribute, then return the DOMString value
- // that represents the empty string.
- if (V === null && opts?.legacyNullToEmptyString) {
- return ''
- }
- // 2. Let x be ? ToString(V).
- if (typeof V === 'symbol') {
- throw webidl.errors.exception({
- header: prefix,
- message: `${argument} is a symbol, which cannot be converted to a DOMString.`
- })
- }
- // 3. Return the IDL DOMString value that represents the
- // same sequence of code units as the one the
- // ECMAScript String value x represents.
- return String(V)
-}
-// https://webidl.spec.whatwg.org/#es-ByteString
-webidl.converters.ByteString = function (V, prefix, argument) {
- // 1. Let x be ? ToString(V).
- // Note: DOMString converter perform ? ToString(V)
- const x = webidl.converters.DOMString(V, prefix, argument)
- // 2. If the value of any element of x is greater than
- // 255, then throw a TypeError.
- for (let index = 0; index < x.length; index++) {
- if (x.charCodeAt(index) > 255) {
- throw new TypeError(
- 'Cannot convert argument to a ByteString because the character at ' +
- `index ${index} has a value of ${x.charCodeAt(index)} which is greater than 255.`
- )
+const { Minimatch } = minimatch;
+const internal_pattern_IS_WINDOWS = process.platform === 'win32';
+class internal_pattern_Pattern {
+ constructor(patternOrNegate, isImplicitPattern = false, segments, homedir) {
+ /**
+ * Indicates whether matches should be excluded from the result set
+ */
+ this.negate = false;
+ // Pattern overload
+ let pattern;
+ if (typeof patternOrNegate === 'string') {
+ pattern = patternOrNegate.trim();
+ }
+ // Segments overload
+ else {
+ // Convert to pattern
+ segments = segments || [];
+ assert(segments.length, `Parameter 'segments' must not empty`);
+ const root = internal_pattern_Pattern.getLiteral(segments[0]);
+ assert(root && pathHelper.hasAbsoluteRoot(root), `Parameter 'segments' first element must be a root path`);
+ pattern = new Path(segments).toString().trim();
+ if (patternOrNegate) {
+ pattern = `!${pattern}`;
+ }
+ }
+ // Negate
+ while (pattern.startsWith('!')) {
+ this.negate = !this.negate;
+ pattern = pattern.substr(1).trim();
+ }
+ // Normalize slashes and ensures absolute root
+ pattern = internal_pattern_Pattern.fixupPattern(pattern, homedir);
+ // Segments
+ this.segments = new Path(pattern).segments;
+ // Trailing slash indicates the pattern should only match directories, not regular files
+ this.trailingSeparator = pathHelper
+ .normalizeSeparators(pattern)
+ .endsWith(path.sep);
+ pattern = pathHelper.safeTrimTrailingSeparator(pattern);
+ // Search path (literal path prior to the first glob segment)
+ let foundGlob = false;
+ const searchSegments = this.segments
+ .map(x => internal_pattern_Pattern.getLiteral(x))
+ .filter(x => !foundGlob && !(foundGlob = x === ''));
+ this.searchPath = new Path(searchSegments).toString();
+ // Root RegExp (required when determining partial match)
+ this.rootRegExp = new RegExp(internal_pattern_Pattern.regExpEscape(searchSegments[0]), internal_pattern_IS_WINDOWS ? 'i' : '');
+ this.isImplicitPattern = isImplicitPattern;
+ // Create minimatch
+ const minimatchOptions = {
+ dot: true,
+ nobrace: true,
+ nocase: internal_pattern_IS_WINDOWS,
+ nocomment: true,
+ noext: true,
+ nonegate: true
+ };
+ pattern = internal_pattern_IS_WINDOWS ? pattern.replace(/\\/g, '/') : pattern;
+ this.minimatch = new Minimatch(pattern, minimatchOptions);
+ }
+ /**
+ * Matches the pattern against the specified path
+ */
+ match(itemPath) {
+ // Last segment is globstar?
+ if (this.segments[this.segments.length - 1] === '**') {
+ // Normalize slashes
+ itemPath = pathHelper.normalizeSeparators(itemPath);
+ // Append a trailing slash. Otherwise Minimatch will not match the directory immediately
+ // preceding the globstar. For example, given the pattern `/foo/**`, Minimatch returns
+ // false for `/foo` but returns true for `/foo/`. Append a trailing slash to handle that quirk.
+ if (!itemPath.endsWith(path.sep) && this.isImplicitPattern === false) {
+ // Note, this is safe because the constructor ensures the pattern has an absolute root.
+ // For example, formats like C: and C:foo on Windows are resolved to an absolute root.
+ itemPath = `${itemPath}${path.sep}`;
+ }
+ }
+ else {
+ // Normalize slashes and trim unnecessary trailing slash
+ itemPath = pathHelper.safeTrimTrailingSeparator(itemPath);
+ }
+ // Match
+ if (this.minimatch.match(itemPath)) {
+ return this.trailingSeparator ? MatchKind.Directory : MatchKind.All;
+ }
+ return MatchKind.None;
+ }
+ /**
+ * Indicates whether the pattern may match descendants of the specified path
+ */
+ partialMatch(itemPath) {
+ // Normalize slashes and trim unnecessary trailing slash
+ itemPath = pathHelper.safeTrimTrailingSeparator(itemPath);
+ // matchOne does not handle root path correctly
+ if (pathHelper.dirname(itemPath) === itemPath) {
+ return this.rootRegExp.test(itemPath);
+ }
+ return this.minimatch.matchOne(itemPath.split(internal_pattern_IS_WINDOWS ? /\\+/ : /\/+/), this.minimatch.set[0], true);
+ }
+ /**
+ * Escapes glob patterns within a path
+ */
+ static globEscape(s) {
+ return (internal_pattern_IS_WINDOWS ? s : s.replace(/\\/g, '\\\\')) // escape '\' on Linux/macOS
+ .replace(/(\[)(?=[^/]+\])/g, '[[]') // escape '[' when ']' follows within the path segment
+ .replace(/\?/g, '[?]') // escape '?'
+ .replace(/\*/g, '[*]'); // escape '*'
+ }
+ /**
+ * Normalizes slashes and ensures absolute root
+ */
+ static fixupPattern(pattern, homedir) {
+ // Empty
+ assert(pattern, 'pattern cannot be empty');
+ // Must not contain `.` segment, unless first segment
+ // Must not contain `..` segment
+ const literalSegments = new Path(pattern).segments.map(x => internal_pattern_Pattern.getLiteral(x));
+ assert(literalSegments.every((x, i) => (x !== '.' || i === 0) && x !== '..'), `Invalid pattern '${pattern}'. Relative pathing '.' and '..' is not allowed.`);
+ // Must not contain globs in root, e.g. Windows UNC path \\foo\b*r
+ assert(!pathHelper.hasRoot(pattern) || literalSegments[0], `Invalid pattern '${pattern}'. Root segment must not contain globs.`);
+ // Normalize slashes
+ pattern = pathHelper.normalizeSeparators(pattern);
+ // Replace leading `.` segment
+ if (pattern === '.' || pattern.startsWith(`.${path.sep}`)) {
+ pattern = internal_pattern_Pattern.globEscape(process.cwd()) + pattern.substr(1);
+ }
+ // Replace leading `~` segment
+ else if (pattern === '~' || pattern.startsWith(`~${path.sep}`)) {
+ homedir = homedir || os.homedir();
+ assert(homedir, 'Unable to determine HOME directory');
+ assert(pathHelper.hasAbsoluteRoot(homedir), `Expected HOME directory to be a rooted path. Actual '${homedir}'`);
+ pattern = internal_pattern_Pattern.globEscape(homedir) + pattern.substr(1);
+ }
+ // Replace relative drive root, e.g. pattern is C: or C:foo
+ else if (internal_pattern_IS_WINDOWS &&
+ (pattern.match(/^[A-Z]:$/i) || pattern.match(/^[A-Z]:[^\\]/i))) {
+ let root = pathHelper.ensureAbsoluteRoot('C:\\dummy-root', pattern.substr(0, 2));
+ if (pattern.length > 2 && !root.endsWith('\\')) {
+ root += '\\';
+ }
+ pattern = internal_pattern_Pattern.globEscape(root) + pattern.substr(2);
+ }
+ // Replace relative root, e.g. pattern is \ or \foo
+ else if (internal_pattern_IS_WINDOWS && (pattern === '\\' || pattern.match(/^\\[^\\]/))) {
+ let root = pathHelper.ensureAbsoluteRoot('C:\\dummy-root', '\\');
+ if (!root.endsWith('\\')) {
+ root += '\\';
+ }
+ pattern = internal_pattern_Pattern.globEscape(root) + pattern.substr(1);
+ }
+ // Otherwise ensure absolute root
+ else {
+ pattern = pathHelper.ensureAbsoluteRoot(internal_pattern_Pattern.globEscape(process.cwd()), pattern);
+ }
+ return pathHelper.normalizeSeparators(pattern);
+ }
+ /**
+ * Attempts to unescape a pattern segment to create a literal path segment.
+ * Otherwise returns empty string.
+ */
+ static getLiteral(segment) {
+ let literal = '';
+ for (let i = 0; i < segment.length; i++) {
+ const c = segment[i];
+ // Escape
+ if (c === '\\' && !internal_pattern_IS_WINDOWS && i + 1 < segment.length) {
+ literal += segment[++i];
+ continue;
+ }
+ // Wildcard
+ else if (c === '*' || c === '?') {
+ return '';
+ }
+ // Character set
+ else if (c === '[' && i + 1 < segment.length) {
+ let set = '';
+ let closed = -1;
+ for (let i2 = i + 1; i2 < segment.length; i2++) {
+ const c2 = segment[i2];
+ // Escape
+ if (c2 === '\\' && !internal_pattern_IS_WINDOWS && i2 + 1 < segment.length) {
+ set += segment[++i2];
+ continue;
+ }
+ // Closed
+ else if (c2 === ']') {
+ closed = i2;
+ break;
+ }
+ // Otherwise
+ else {
+ set += c2;
+ }
+ }
+ // Closed?
+ if (closed >= 0) {
+ // Cannot convert
+ if (set.length > 1) {
+ return '';
+ }
+ // Convert to literal
+ if (set) {
+ literal += set;
+ i = closed;
+ continue;
+ }
+ }
+ // Otherwise fall thru
+ }
+ // Append
+ literal += c;
+ }
+ return literal;
+ }
+ /**
+ * Escapes regexp special characters
+ * https://javascript.info/regexp-escaping
+ */
+ static regExpEscape(s) {
+ return s.replace(/[[\\^$.|?*+()]/g, '\\$&');
}
- }
-
- // 3. Return an IDL ByteString value whose length is the
- // length of x, and where the value of each element is
- // the value of the corresponding element of x.
- return x
}
+//# sourceMappingURL=internal-pattern.js.map
+;// CONCATENATED MODULE: ./node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-globber.js
+var internal_globber_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
+var __asyncValues = (undefined && undefined.__asyncValues) || function (o) {
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
+ var m = o[Symbol.asyncIterator], i;
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
+};
+var __await = (undefined && undefined.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }
+var __asyncGenerator = (undefined && undefined.__asyncGenerator) || function (thisArg, _arguments, generator) {
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
+ return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
+ function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
+ function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
+ function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
+ function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
+ function fulfill(value) { resume("next", value); }
+ function reject(value) { resume("throw", value); }
+ function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
+};
-// https://webidl.spec.whatwg.org/#es-USVString
-// TODO: rewrite this so we can control the errors thrown
-webidl.converters.USVString = toUSVString
-// https://webidl.spec.whatwg.org/#es-boolean
-webidl.converters.boolean = function (V) {
- // 1. Let x be the result of computing ToBoolean(V).
- const x = Boolean(V)
- // 2. Return the IDL boolean value that is the one that represents
- // the same truth value as the ECMAScript Boolean value x.
- return x
-}
-// https://webidl.spec.whatwg.org/#es-any
-webidl.converters.any = function (V) {
- return V
-}
-// https://webidl.spec.whatwg.org/#es-long-long
-webidl.converters['long long'] = function (V, prefix, argument) {
- // 1. Let x be ? ConvertToInt(V, 64, "signed").
- const x = webidl.util.ConvertToInt(V, 64, 'signed', undefined, prefix, argument)
- // 2. Return the IDL long long value that represents
- // the same numeric value as x.
- return x
-}
-
-// https://webidl.spec.whatwg.org/#es-unsigned-long-long
-webidl.converters['unsigned long long'] = function (V, prefix, argument) {
- // 1. Let x be ? ConvertToInt(V, 64, "unsigned").
- const x = webidl.util.ConvertToInt(V, 64, 'unsigned', undefined, prefix, argument)
-
- // 2. Return the IDL unsigned long long value that
- // represents the same numeric value as x.
- return x
-}
-
-// https://webidl.spec.whatwg.org/#es-unsigned-long
-webidl.converters['unsigned long'] = function (V, prefix, argument) {
- // 1. Let x be ? ConvertToInt(V, 32, "unsigned").
- const x = webidl.util.ConvertToInt(V, 32, 'unsigned', undefined, prefix, argument)
- // 2. Return the IDL unsigned long value that
- // represents the same numeric value as x.
- return x
-}
-
-// https://webidl.spec.whatwg.org/#es-unsigned-short
-webidl.converters['unsigned short'] = function (V, prefix, argument, opts) {
- // 1. Let x be ? ConvertToInt(V, 16, "unsigned").
- const x = webidl.util.ConvertToInt(V, 16, 'unsigned', opts, prefix, argument)
- // 2. Return the IDL unsigned short value that represents
- // the same numeric value as x.
- return x
+const internal_globber_IS_WINDOWS = process.platform === 'win32';
+class internal_globber_DefaultGlobber {
+ constructor(options) {
+ this.patterns = [];
+ this.searchPaths = [];
+ this.options = globOptionsHelper.getOptions(options);
+ }
+ getSearchPaths() {
+ // Return a copy
+ return this.searchPaths.slice();
+ }
+ glob() {
+ return internal_globber_awaiter(this, void 0, void 0, function* () {
+ var _a, e_1, _b, _c;
+ const result = [];
+ try {
+ for (var _d = true, _e = __asyncValues(this.globGenerator()), _f; _f = yield _e.next(), _a = _f.done, !_a; _d = true) {
+ _c = _f.value;
+ _d = false;
+ const itemPath = _c;
+ result.push(itemPath);
+ }
+ }
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
+ finally {
+ try {
+ if (!_d && !_a && (_b = _e.return)) yield _b.call(_e);
+ }
+ finally { if (e_1) throw e_1.error; }
+ }
+ return result;
+ });
+ }
+ globGenerator() {
+ return __asyncGenerator(this, arguments, function* globGenerator_1() {
+ // Fill in defaults options
+ const options = globOptionsHelper.getOptions(this.options);
+ // Implicit descendants?
+ const patterns = [];
+ for (const pattern of this.patterns) {
+ patterns.push(pattern);
+ if (options.implicitDescendants &&
+ (pattern.trailingSeparator ||
+ pattern.segments[pattern.segments.length - 1] !== '**')) {
+ patterns.push(new Pattern(pattern.negate, true, pattern.segments.concat('**')));
+ }
+ }
+ // Push the search paths
+ const stack = [];
+ for (const searchPath of patternHelper.getSearchPaths(patterns)) {
+ core.debug(`Search path '${searchPath}'`);
+ // Exists?
+ try {
+ // Intentionally using lstat. Detection for broken symlink
+ // will be performed later (if following symlinks).
+ yield __await(fs.promises.lstat(searchPath));
+ }
+ catch (err) {
+ if (err.code === 'ENOENT') {
+ continue;
+ }
+ throw err;
+ }
+ stack.unshift(new SearchState(searchPath, 1));
+ }
+ // Search
+ const traversalChain = []; // used to detect cycles
+ while (stack.length) {
+ // Pop
+ const item = stack.pop();
+ // Match?
+ const match = patternHelper.match(patterns, item.path);
+ const partialMatch = !!match || patternHelper.partialMatch(patterns, item.path);
+ if (!match && !partialMatch) {
+ continue;
+ }
+ // Stat
+ const stats = yield __await(internal_globber_DefaultGlobber.stat(item, options, traversalChain)
+ // Broken symlink, or symlink cycle detected, or no longer exists
+ );
+ // Broken symlink, or symlink cycle detected, or no longer exists
+ if (!stats) {
+ continue;
+ }
+ // Hidden file or directory?
+ if (options.excludeHiddenFiles && path.basename(item.path).match(/^\./)) {
+ continue;
+ }
+ // Directory
+ if (stats.isDirectory()) {
+ // Matched
+ if (match & MatchKind.Directory && options.matchDirectories) {
+ yield yield __await(item.path);
+ }
+ // Descend?
+ else if (!partialMatch) {
+ continue;
+ }
+ // Push the child items in reverse
+ const childLevel = item.level + 1;
+ const childItems = (yield __await(fs.promises.readdir(item.path))).map(x => new SearchState(path.join(item.path, x), childLevel));
+ stack.push(...childItems.reverse());
+ }
+ // File
+ else if (match & MatchKind.File) {
+ yield yield __await(item.path);
+ }
+ }
+ });
+ }
+ /**
+ * Constructs a DefaultGlobber
+ */
+ static create(patterns, options) {
+ return internal_globber_awaiter(this, void 0, void 0, function* () {
+ const result = new internal_globber_DefaultGlobber(options);
+ if (internal_globber_IS_WINDOWS) {
+ patterns = patterns.replace(/\r\n/g, '\n');
+ patterns = patterns.replace(/\r/g, '\n');
+ }
+ const lines = patterns.split('\n').map(x => x.trim());
+ for (const line of lines) {
+ // Empty or comment
+ if (!line || line.startsWith('#')) {
+ continue;
+ }
+ // Pattern
+ else {
+ result.patterns.push(new Pattern(line));
+ }
+ }
+ result.searchPaths.push(...patternHelper.getSearchPaths(result.patterns));
+ return result;
+ });
+ }
+ static stat(item, options, traversalChain) {
+ return internal_globber_awaiter(this, void 0, void 0, function* () {
+ // Note:
+ // `stat` returns info about the target of a symlink (or symlink chain)
+ // `lstat` returns info about a symlink itself
+ let stats;
+ if (options.followSymbolicLinks) {
+ try {
+ // Use `stat` (following symlinks)
+ stats = yield fs.promises.stat(item.path);
+ }
+ catch (err) {
+ if (err.code === 'ENOENT') {
+ if (options.omitBrokenSymbolicLinks) {
+ core.debug(`Broken symlink '${item.path}'`);
+ return undefined;
+ }
+ throw new Error(`No information found for the path '${item.path}'. This may indicate a broken symbolic link.`);
+ }
+ throw err;
+ }
+ }
+ else {
+ // Use `lstat` (not following symlinks)
+ stats = yield fs.promises.lstat(item.path);
+ }
+ // Note, isDirectory() returns false for the lstat of a symlink
+ if (stats.isDirectory() && options.followSymbolicLinks) {
+ // Get the realpath
+ const realPath = yield fs.promises.realpath(item.path);
+ // Fixup the traversal chain to match the item level
+ while (traversalChain.length >= item.level) {
+ traversalChain.pop();
+ }
+ // Test for a cycle
+ if (traversalChain.some((x) => x === realPath)) {
+ core.debug(`Symlink cycle detected for path '${item.path}' and realpath '${realPath}'`);
+ return undefined;
+ }
+ // Update the traversal chain
+ traversalChain.push(realPath);
+ }
+ return stats;
+ });
+ }
}
+//# sourceMappingURL=internal-globber.js.map
+;// CONCATENATED MODULE: external "stream"
+const external_stream_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("stream");
+// EXTERNAL MODULE: external "util"
+var external_util_ = __nccwpck_require__(9023);
+;// CONCATENATED MODULE: ./node_modules/@actions/cache/node_modules/@actions/glob/lib/internal-hash-files.js
+var internal_hash_files_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
+var internal_hash_files_asyncValues = (undefined && undefined.__asyncValues) || function (o) {
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
+ var m = o[Symbol.asyncIterator], i;
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
+};
-// https://webidl.spec.whatwg.org/#idl-ArrayBuffer
-webidl.converters.ArrayBuffer = function (V, prefix, argument, opts) {
- // 1. If Type(V) is not Object, or V does not have an
- // [[ArrayBufferData]] internal slot, then throw a
- // TypeError.
- // see: https://tc39.es/ecma262/#sec-properties-of-the-arraybuffer-instances
- // see: https://tc39.es/ecma262/#sec-properties-of-the-sharedarraybuffer-instances
- if (
- webidl.util.Type(V) !== 'Object' ||
- !types.isAnyArrayBuffer(V)
- ) {
- throw webidl.errors.conversionFailed({
- prefix,
- argument: `${argument} ("${webidl.util.Stringify(V)}")`,
- types: ['ArrayBuffer']
- })
- }
-
- // 2. If the conversion is not to an IDL type associated
- // with the [AllowShared] extended attribute, and
- // IsSharedArrayBuffer(V) is true, then throw a
- // TypeError.
- if (opts?.allowShared === false && types.isSharedArrayBuffer(V)) {
- throw webidl.errors.exception({
- header: 'ArrayBuffer',
- message: 'SharedArrayBuffer is not allowed.'
- })
- }
-
- // 3. If the conversion is not to an IDL type associated
- // with the [AllowResizable] extended attribute, and
- // IsResizableArrayBuffer(V) is true, then throw a
- // TypeError.
- if (V.resizable || V.growable) {
- throw webidl.errors.exception({
- header: 'ArrayBuffer',
- message: 'Received a resizable ArrayBuffer.'
- })
- }
-
- // 4. Return the IDL ArrayBuffer value that is a
- // reference to the same object as V.
- return V
-}
-webidl.converters.TypedArray = function (V, T, prefix, name, opts) {
- // 1. Let T be the IDL type V is being converted to.
- // 2. If Type(V) is not Object, or V does not have a
- // [[TypedArrayName]] internal slot with a value
- // equal to T’s name, then throw a TypeError.
- if (
- webidl.util.Type(V) !== 'Object' ||
- !types.isTypedArray(V) ||
- V.constructor.name !== T.name
- ) {
- throw webidl.errors.conversionFailed({
- prefix,
- argument: `${name} ("${webidl.util.Stringify(V)}")`,
- types: [T.name]
- })
- }
- // 3. If the conversion is not to an IDL type associated
- // with the [AllowShared] extended attribute, and
- // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is
- // true, then throw a TypeError.
- if (opts?.allowShared === false && types.isSharedArrayBuffer(V.buffer)) {
- throw webidl.errors.exception({
- header: 'ArrayBuffer',
- message: 'SharedArrayBuffer is not allowed.'
- })
- }
- // 4. If the conversion is not to an IDL type associated
- // with the [AllowResizable] extended attribute, and
- // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is
- // true, then throw a TypeError.
- if (V.buffer.resizable || V.buffer.growable) {
- throw webidl.errors.exception({
- header: 'ArrayBuffer',
- message: 'Received a resizable ArrayBuffer.'
- })
- }
- // 5. Return the IDL value of type T that is a reference
- // to the same object as V.
- return V
+function hashFiles(globber_1, currentWorkspace_1) {
+ return internal_hash_files_awaiter(this, arguments, void 0, function* (globber, currentWorkspace, verbose = false) {
+ var _a, e_1, _b, _c;
+ var _d;
+ const writeDelegate = verbose ? core.info : core.debug;
+ let hasMatch = false;
+ const githubWorkspace = currentWorkspace
+ ? currentWorkspace
+ : ((_d = process.env['GITHUB_WORKSPACE']) !== null && _d !== void 0 ? _d : process.cwd());
+ const result = crypto.createHash('sha256');
+ let count = 0;
+ try {
+ for (var _e = true, _f = internal_hash_files_asyncValues(globber.globGenerator()), _g; _g = yield _f.next(), _a = _g.done, !_a; _e = true) {
+ _c = _g.value;
+ _e = false;
+ const file = _c;
+ writeDelegate(file);
+ if (!file.startsWith(`${githubWorkspace}${path.sep}`)) {
+ writeDelegate(`Ignore '${file}' since it is not under GITHUB_WORKSPACE.`);
+ continue;
+ }
+ if (fs.statSync(file).isDirectory()) {
+ writeDelegate(`Skip directory '${file}'.`);
+ continue;
+ }
+ const hash = crypto.createHash('sha256');
+ const pipeline = util.promisify(stream.pipeline);
+ yield pipeline(fs.createReadStream(file), hash);
+ result.write(hash.digest());
+ count++;
+ if (!hasMatch) {
+ hasMatch = true;
+ }
+ }
+ }
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
+ finally {
+ try {
+ if (!_e && !_a && (_b = _f.return)) yield _b.call(_f);
+ }
+ finally { if (e_1) throw e_1.error; }
+ }
+ result.end();
+ if (hasMatch) {
+ writeDelegate(`Found ${count} files to hash.`);
+ return result.digest('hex');
+ }
+ else {
+ writeDelegate(`No matches found for glob`);
+ return '';
+ }
+ });
}
+//# sourceMappingURL=internal-hash-files.js.map
+;// CONCATENATED MODULE: ./node_modules/@actions/cache/node_modules/@actions/glob/lib/glob.js
+var glob_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
-webidl.converters.DataView = function (V, prefix, name, opts) {
- // 1. If Type(V) is not Object, or V does not have a
- // [[DataView]] internal slot, then throw a TypeError.
- if (webidl.util.Type(V) !== 'Object' || !types.isDataView(V)) {
- throw webidl.errors.exception({
- header: prefix,
- message: `${name} is not a DataView.`
- })
- }
-
- // 2. If the conversion is not to an IDL type associated
- // with the [AllowShared] extended attribute, and
- // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true,
- // then throw a TypeError.
- if (opts?.allowShared === false && types.isSharedArrayBuffer(V.buffer)) {
- throw webidl.errors.exception({
- header: 'ArrayBuffer',
- message: 'SharedArrayBuffer is not allowed.'
- })
- }
-
- // 3. If the conversion is not to an IDL type associated
- // with the [AllowResizable] extended attribute, and
- // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is
- // true, then throw a TypeError.
- if (V.buffer.resizable || V.buffer.growable) {
- throw webidl.errors.exception({
- header: 'ArrayBuffer',
- message: 'Received a resizable ArrayBuffer.'
- })
- }
- // 4. Return the IDL DataView value that is a reference
- // to the same object as V.
- return V
+/**
+ * Constructs a globber
+ *
+ * @param patterns Patterns separated by newlines
+ * @param options Glob options
+ */
+function create(patterns, options) {
+ return glob_awaiter(this, void 0, void 0, function* () {
+ return yield DefaultGlobber.create(patterns, options);
+ });
}
-
-// https://webidl.spec.whatwg.org/#BufferSource
-webidl.converters.BufferSource = function (V, prefix, name, opts) {
- if (types.isAnyArrayBuffer(V)) {
- return webidl.converters.ArrayBuffer(V, prefix, name, { ...opts, allowShared: false })
- }
-
- if (types.isTypedArray(V)) {
- return webidl.converters.TypedArray(V, V.constructor, prefix, name, { ...opts, allowShared: false })
- }
-
- if (types.isDataView(V)) {
- return webidl.converters.DataView(V, prefix, name, { ...opts, allowShared: false })
- }
-
- throw webidl.errors.conversionFailed({
- prefix,
- argument: `${name} ("${webidl.util.Stringify(V)}")`,
- types: ['BufferSource']
- })
+/**
+ * Computes the sha256 hash of a glob
+ *
+ * @param patterns Patterns separated by newlines
+ * @param currentWorkspace Workspace used when matching files
+ * @param options Glob options
+ * @param verbose Enables verbose logging
+ */
+function glob_hashFiles(patterns_1) {
+ return glob_awaiter(this, arguments, void 0, function* (patterns, currentWorkspace = '', options, verbose = false) {
+ let followSymbolicLinks = true;
+ if (options && typeof options.followSymbolicLinks === 'boolean') {
+ followSymbolicLinks = options.followSymbolicLinks;
+ }
+ const globber = yield create(patterns, { followSymbolicLinks });
+ return _hashFiles(globber, currentWorkspace, verbose);
+ });
}
+//# sourceMappingURL=glob.js.map
+// EXTERNAL MODULE: ./node_modules/semver/index.js
+var node_modules_semver = __nccwpck_require__(2088);
+;// CONCATENATED MODULE: ./node_modules/@actions/cache/lib/internal/constants.js
+var CacheFilename;
+(function (CacheFilename) {
+ CacheFilename["Gzip"] = "cache.tgz";
+ CacheFilename["Zstd"] = "cache.tzst";
+})(CacheFilename || (CacheFilename = {}));
+var CompressionMethod;
+(function (CompressionMethod) {
+ CompressionMethod["Gzip"] = "gzip";
+ // Long range mode was added to zstd in v1.3.2.
+ // This enum is for earlier version of zstd that does not have --long support
+ CompressionMethod["ZstdWithoutLong"] = "zstd-without-long";
+ CompressionMethod["Zstd"] = "zstd";
+})(CompressionMethod || (CompressionMethod = {}));
+var ArchiveToolType;
+(function (ArchiveToolType) {
+ ArchiveToolType["GNU"] = "gnu";
+ ArchiveToolType["BSD"] = "bsd";
+})(ArchiveToolType || (ArchiveToolType = {}));
+// The default number of retry attempts.
+const DefaultRetryAttempts = 2;
+// The default delay in milliseconds between retry attempts.
+const DefaultRetryDelay = 5000;
+// Socket timeout in milliseconds during download. If no traffic is received
+// over the socket during this period, the socket is destroyed and the download
+// is aborted.
+const SocketTimeout = 5000;
+// The default path of GNUtar on hosted Windows runners
+const GnuTarPathOnWindows = `${process.env['PROGRAMFILES']}\\Git\\usr\\bin\\tar.exe`;
+// The default path of BSDtar on hosted Windows runners
+const SystemTarPathOnWindows = `${process.env['SYSTEMDRIVE']}\\Windows\\System32\\tar.exe`;
+const TarFilename = 'cache.tar';
+const constants_ManifestFilename = 'manifest.txt';
+const CacheFileSizeLimit = 10 * Math.pow(1024, 3); // 10GiB per repository
+//# sourceMappingURL=constants.js.map
+;// CONCATENATED MODULE: ./node_modules/@actions/cache/lib/internal/cacheUtils.js
+var cacheUtils_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
+var cacheUtils_asyncValues = (undefined && undefined.__asyncValues) || function (o) {
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
+ var m = o[Symbol.asyncIterator], i;
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
+};
-webidl.converters['sequence'] = webidl.sequenceConverter(
- webidl.converters.ByteString
-)
-
-webidl.converters['sequence>'] = webidl.sequenceConverter(
- webidl.converters['sequence']
-)
-webidl.converters['record'] = webidl.recordConverter(
- webidl.converters.ByteString,
- webidl.converters.ByteString
-)
-module.exports = {
- webidl
-}
-/***/ }),
-/***/ 5207:
-/***/ ((module) => {
-/**
- * @see https://encoding.spec.whatwg.org/#concept-encoding-get
- * @param {string|undefined} label
- */
-function getEncoding (label) {
- if (!label) {
- return 'failure'
- }
- // 1. Remove any leading and trailing ASCII whitespace from label.
- // 2. If label is an ASCII case-insensitive match for any of the
- // labels listed in the table below, then return the
- // corresponding encoding; otherwise return failure.
- switch (label.trim().toLowerCase()) {
- case 'unicode-1-1-utf-8':
- case 'unicode11utf8':
- case 'unicode20utf8':
- case 'utf-8':
- case 'utf8':
- case 'x-unicode20utf8':
- return 'UTF-8'
- case '866':
- case 'cp866':
- case 'csibm866':
- case 'ibm866':
- return 'IBM866'
- case 'csisolatin2':
- case 'iso-8859-2':
- case 'iso-ir-101':
- case 'iso8859-2':
- case 'iso88592':
- case 'iso_8859-2':
- case 'iso_8859-2:1987':
- case 'l2':
- case 'latin2':
- return 'ISO-8859-2'
- case 'csisolatin3':
- case 'iso-8859-3':
- case 'iso-ir-109':
- case 'iso8859-3':
- case 'iso88593':
- case 'iso_8859-3':
- case 'iso_8859-3:1988':
- case 'l3':
- case 'latin3':
- return 'ISO-8859-3'
- case 'csisolatin4':
- case 'iso-8859-4':
- case 'iso-ir-110':
- case 'iso8859-4':
- case 'iso88594':
- case 'iso_8859-4':
- case 'iso_8859-4:1988':
- case 'l4':
- case 'latin4':
- return 'ISO-8859-4'
- case 'csisolatincyrillic':
- case 'cyrillic':
- case 'iso-8859-5':
- case 'iso-ir-144':
- case 'iso8859-5':
- case 'iso88595':
- case 'iso_8859-5':
- case 'iso_8859-5:1988':
- return 'ISO-8859-5'
- case 'arabic':
- case 'asmo-708':
- case 'csiso88596e':
- case 'csiso88596i':
- case 'csisolatinarabic':
- case 'ecma-114':
- case 'iso-8859-6':
- case 'iso-8859-6-e':
- case 'iso-8859-6-i':
- case 'iso-ir-127':
- case 'iso8859-6':
- case 'iso88596':
- case 'iso_8859-6':
- case 'iso_8859-6:1987':
- return 'ISO-8859-6'
- case 'csisolatingreek':
- case 'ecma-118':
- case 'elot_928':
- case 'greek':
- case 'greek8':
- case 'iso-8859-7':
- case 'iso-ir-126':
- case 'iso8859-7':
- case 'iso88597':
- case 'iso_8859-7':
- case 'iso_8859-7:1987':
- case 'sun_eu_greek':
- return 'ISO-8859-7'
- case 'csiso88598e':
- case 'csisolatinhebrew':
- case 'hebrew':
- case 'iso-8859-8':
- case 'iso-8859-8-e':
- case 'iso-ir-138':
- case 'iso8859-8':
- case 'iso88598':
- case 'iso_8859-8':
- case 'iso_8859-8:1988':
- case 'visual':
- return 'ISO-8859-8'
- case 'csiso88598i':
- case 'iso-8859-8-i':
- case 'logical':
- return 'ISO-8859-8-I'
- case 'csisolatin6':
- case 'iso-8859-10':
- case 'iso-ir-157':
- case 'iso8859-10':
- case 'iso885910':
- case 'l6':
- case 'latin6':
- return 'ISO-8859-10'
- case 'iso-8859-13':
- case 'iso8859-13':
- case 'iso885913':
- return 'ISO-8859-13'
- case 'iso-8859-14':
- case 'iso8859-14':
- case 'iso885914':
- return 'ISO-8859-14'
- case 'csisolatin9':
- case 'iso-8859-15':
- case 'iso8859-15':
- case 'iso885915':
- case 'iso_8859-15':
- case 'l9':
- return 'ISO-8859-15'
- case 'iso-8859-16':
- return 'ISO-8859-16'
- case 'cskoi8r':
- case 'koi':
- case 'koi8':
- case 'koi8-r':
- case 'koi8_r':
- return 'KOI8-R'
- case 'koi8-ru':
- case 'koi8-u':
- return 'KOI8-U'
- case 'csmacintosh':
- case 'mac':
- case 'macintosh':
- case 'x-mac-roman':
- return 'macintosh'
- case 'iso-8859-11':
- case 'iso8859-11':
- case 'iso885911':
- case 'tis-620':
- case 'windows-874':
- return 'windows-874'
- case 'cp1250':
- case 'windows-1250':
- case 'x-cp1250':
- return 'windows-1250'
- case 'cp1251':
- case 'windows-1251':
- case 'x-cp1251':
- return 'windows-1251'
- case 'ansi_x3.4-1968':
- case 'ascii':
- case 'cp1252':
- case 'cp819':
- case 'csisolatin1':
- case 'ibm819':
- case 'iso-8859-1':
- case 'iso-ir-100':
- case 'iso8859-1':
- case 'iso88591':
- case 'iso_8859-1':
- case 'iso_8859-1:1987':
- case 'l1':
- case 'latin1':
- case 'us-ascii':
- case 'windows-1252':
- case 'x-cp1252':
- return 'windows-1252'
- case 'cp1253':
- case 'windows-1253':
- case 'x-cp1253':
- return 'windows-1253'
- case 'cp1254':
- case 'csisolatin5':
- case 'iso-8859-9':
- case 'iso-ir-148':
- case 'iso8859-9':
- case 'iso88599':
- case 'iso_8859-9':
- case 'iso_8859-9:1989':
- case 'l5':
- case 'latin5':
- case 'windows-1254':
- case 'x-cp1254':
- return 'windows-1254'
- case 'cp1255':
- case 'windows-1255':
- case 'x-cp1255':
- return 'windows-1255'
- case 'cp1256':
- case 'windows-1256':
- case 'x-cp1256':
- return 'windows-1256'
- case 'cp1257':
- case 'windows-1257':
- case 'x-cp1257':
- return 'windows-1257'
- case 'cp1258':
- case 'windows-1258':
- case 'x-cp1258':
- return 'windows-1258'
- case 'x-mac-cyrillic':
- case 'x-mac-ukrainian':
- return 'x-mac-cyrillic'
- case 'chinese':
- case 'csgb2312':
- case 'csiso58gb231280':
- case 'gb2312':
- case 'gb_2312':
- case 'gb_2312-80':
- case 'gbk':
- case 'iso-ir-58':
- case 'x-gbk':
- return 'GBK'
- case 'gb18030':
- return 'gb18030'
- case 'big5':
- case 'big5-hkscs':
- case 'cn-big5':
- case 'csbig5':
- case 'x-x-big5':
- return 'Big5'
- case 'cseucpkdfmtjapanese':
- case 'euc-jp':
- case 'x-euc-jp':
- return 'EUC-JP'
- case 'csiso2022jp':
- case 'iso-2022-jp':
- return 'ISO-2022-JP'
- case 'csshiftjis':
- case 'ms932':
- case 'ms_kanji':
- case 'shift-jis':
- case 'shift_jis':
- case 'sjis':
- case 'windows-31j':
- case 'x-sjis':
- return 'Shift_JIS'
- case 'cseuckr':
- case 'csksc56011987':
- case 'euc-kr':
- case 'iso-ir-149':
- case 'korean':
- case 'ks_c_5601-1987':
- case 'ks_c_5601-1989':
- case 'ksc5601':
- case 'ksc_5601':
- case 'windows-949':
- return 'EUC-KR'
- case 'csiso2022kr':
- case 'hz-gb-2312':
- case 'iso-2022-cn':
- case 'iso-2022-cn-ext':
- case 'iso-2022-kr':
- case 'replacement':
- return 'replacement'
- case 'unicodefffe':
- case 'utf-16be':
- return 'UTF-16BE'
- case 'csunicode':
- case 'iso-10646-ucs-2':
- case 'ucs-2':
- case 'unicode':
- case 'unicodefeff':
- case 'utf-16':
- case 'utf-16le':
- return 'UTF-16LE'
- case 'x-user-defined':
- return 'x-user-defined'
- default: return 'failure'
- }
+const versionSalt = '1.0';
+// From https://github.com/actions/toolkit/blob/main/packages/tool-cache/src/tool-cache.ts#L23
+function createTempDirectory() {
+ return cacheUtils_awaiter(this, void 0, void 0, function* () {
+ const IS_WINDOWS = process.platform === 'win32';
+ let tempDirectory = process.env['RUNNER_TEMP'] || '';
+ if (!tempDirectory) {
+ let baseLocation;
+ if (IS_WINDOWS) {
+ // On Windows use the USERPROFILE env variable
+ baseLocation = process.env['USERPROFILE'] || 'C:\\';
+ }
+ else {
+ if (process.platform === 'darwin') {
+ baseLocation = '/Users';
+ }
+ else {
+ baseLocation = '/home';
+ }
+ }
+ tempDirectory = external_path_.join(baseLocation, 'actions', 'temp');
+ }
+ const dest = external_path_.join(tempDirectory, external_crypto_namespaceObject.randomUUID());
+ yield mkdirP(dest);
+ return dest;
+ });
}
-
-module.exports = {
- getEncoding
+function getArchiveFileSizeInBytes(filePath) {
+ return external_fs_namespaceObject.statSync(filePath).size;
}
+function resolvePaths(patterns) {
+ return cacheUtils_awaiter(this, void 0, void 0, function* () {
+ var _a, e_1, _b, _c;
+ var _d;
+ const paths = [];
+ const workspace = (_d = process.env['GITHUB_WORKSPACE']) !== null && _d !== void 0 ? _d : process.cwd();
+ const globber = yield glob.create(patterns.join('\n'), {
+ implicitDescendants: false
+ });
+ try {
+ for (var _e = true, _f = cacheUtils_asyncValues(globber.globGenerator()), _g; _g = yield _f.next(), _a = _g.done, !_a; _e = true) {
+ _c = _g.value;
+ _e = false;
+ const file = _c;
+ const relativeFile = path
+ .relative(workspace, file)
+ .replace(new RegExp(`\\${path.sep}`, 'g'), '/');
+ core.debug(`Matched: ${relativeFile}`);
+ // Paths are made relative so the tar entries are all relative to the root of the workspace.
+ if (relativeFile === '') {
+ // path.relative returns empty string if workspace and file are equal
+ paths.push('.');
+ }
+ else {
+ paths.push(`${relativeFile}`);
+ }
+ }
+ }
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
+ finally {
+ try {
+ if (!_e && !_a && (_b = _f.return)) yield _b.call(_f);
+ }
+ finally { if (e_1) throw e_1.error; }
+ }
+ return paths;
+ });
+}
+function unlinkFile(filePath) {
+ return cacheUtils_awaiter(this, void 0, void 0, function* () {
+ return external_util_.promisify(external_fs_namespaceObject.unlink)(filePath);
+ });
+}
+function getVersion(app_1) {
+ return cacheUtils_awaiter(this, arguments, void 0, function* (app, additionalArgs = []) {
+ let versionOutput = '';
+ additionalArgs.push('--version');
+ core_debug(`Checking ${app} ${additionalArgs.join(' ')}`);
+ try {
+ yield exec_exec(`${app}`, additionalArgs, {
+ ignoreReturnCode: true,
+ silent: true,
+ listeners: {
+ stdout: (data) => (versionOutput += data.toString()),
+ stderr: (data) => (versionOutput += data.toString())
+ }
+ });
+ }
+ catch (err) {
+ core_debug(err.message);
+ }
+ versionOutput = versionOutput.trim();
+ core_debug(versionOutput);
+ return versionOutput;
+ });
+}
+// Use zstandard if possible to maximize cache performance
+function getCompressionMethod() {
+ return cacheUtils_awaiter(this, void 0, void 0, function* () {
+ const versionOutput = yield getVersion('zstd', ['--quiet']);
+ const version = node_modules_semver.clean(versionOutput);
+ core_debug(`zstd version: ${version}`);
+ if (versionOutput === '') {
+ return CompressionMethod.Gzip;
+ }
+ else {
+ return CompressionMethod.ZstdWithoutLong;
+ }
+ });
+}
+function getCacheFileName(compressionMethod) {
+ return compressionMethod === CompressionMethod.Gzip
+ ? CacheFilename.Gzip
+ : CacheFilename.Zstd;
+}
+function getGnuTarPathOnWindows() {
+ return cacheUtils_awaiter(this, void 0, void 0, function* () {
+ if (external_fs_namespaceObject.existsSync(GnuTarPathOnWindows)) {
+ return GnuTarPathOnWindows;
+ }
+ const versionOutput = yield getVersion('tar');
+ return versionOutput.toLowerCase().includes('gnu tar') ? which('tar') : '';
+ });
+}
+function assertDefined(name, value) {
+ if (value === undefined) {
+ throw Error(`Expected ${name} but value was undefiend`);
+ }
+ return value;
+}
+function getCacheVersion(paths, compressionMethod, enableCrossOsArchive = false) {
+ // don't pass changes upstream
+ const components = paths.slice();
+ // Add compression method to cache version to restore
+ // compressed cache as per compression method
+ if (compressionMethod) {
+ components.push(compressionMethod);
+ }
+ // Only check for windows platforms if enableCrossOsArchive is false
+ if (process.platform === 'win32' && !enableCrossOsArchive) {
+ components.push('windows-only');
+ }
+ // Add salt to cache version to support breaking changes in cache entry
+ components.push(versionSalt);
+ return external_crypto_namespaceObject.createHash('sha256').update(components.join('|')).digest('hex');
+}
+function getRuntimeToken() {
+ const token = process.env['ACTIONS_RUNTIME_TOKEN'];
+ if (!token) {
+ throw new Error('Unable to get the ACTIONS_RUNTIME_TOKEN env variable');
+ }
+ return token;
+}
+//# sourceMappingURL=cacheUtils.js.map
+// EXTERNAL MODULE: external "url"
+var external_url_ = __nccwpck_require__(7016);
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/abort-controller/AbortError.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+/**
+ * This error is thrown when an asynchronous operation has been aborted.
+ * Check for this error by testing the `name` that the name property of the
+ * error matches `"AbortError"`.
+ *
+ * @example
+ * ```ts snippet:ReadmeSampleAbortError
+ * import { AbortError } from "@typespec/ts-http-runtime";
+ *
+ * async function doAsyncWork(options: { abortSignal: AbortSignal }): Promise {
+ * if (options.abortSignal.aborted) {
+ * throw new AbortError();
+ * }
+ *
+ * // do async work
+ * }
+ *
+ * const controller = new AbortController();
+ * controller.abort();
+ *
+ * try {
+ * doAsyncWork({ abortSignal: controller.signal });
+ * } catch (e) {
+ * if (e instanceof Error && e.name === "AbortError") {
+ * // handle abort error here.
+ * }
+ * }
+ * ```
+ */
+class AbortError extends Error {
+ constructor(message) {
+ super(message);
+ this.name = "AbortError";
+ }
+}
+//# sourceMappingURL=AbortError.js.map
+// EXTERNAL MODULE: external "node:os"
+var external_node_os_ = __nccwpck_require__(8161);
+// EXTERNAL MODULE: external "node:util"
+var external_node_util_ = __nccwpck_require__(7975);
+// EXTERNAL MODULE: external "node:process"
+var external_node_process_ = __nccwpck_require__(1708);
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/logger/log.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
-/***/ }),
-
-/***/ 6299:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const {
- staticPropertyDescriptors,
- readOperation,
- fireAProgressEvent
-} = __nccwpck_require__(7522)
-const {
- kState,
- kError,
- kResult,
- kEvents,
- kAborted
-} = __nccwpck_require__(9657)
-const { webidl } = __nccwpck_require__(253)
-const { kEnumerableProperty } = __nccwpck_require__(1544)
-class FileReader extends EventTarget {
- constructor () {
- super()
+function log(message, ...args) {
+ external_node_process_.stderr.write(`${external_node_util_.format(message, ...args)}${external_node_os_.EOL}`);
+}
+//# sourceMappingURL=log.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/logger/debug.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- this[kState] = 'empty'
- this[kResult] = null
- this[kError] = null
- this[kEvents] = {
- loadend: null,
- error: null,
- abort: null,
- load: null,
- progress: null,
- loadstart: null
- }
- }
-
- /**
- * @see https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer
- * @param {import('buffer').Blob} blob
- */
- readAsArrayBuffer (blob) {
- webidl.brandCheck(this, FileReader)
-
- webidl.argumentLengthCheck(arguments, 1, 'FileReader.readAsArrayBuffer')
-
- blob = webidl.converters.Blob(blob, { strict: false })
-
- // The readAsArrayBuffer(blob) method, when invoked,
- // must initiate a read operation for blob with ArrayBuffer.
- readOperation(this, blob, 'ArrayBuffer')
- }
-
- /**
- * @see https://w3c.github.io/FileAPI/#readAsBinaryString
- * @param {import('buffer').Blob} blob
- */
- readAsBinaryString (blob) {
- webidl.brandCheck(this, FileReader)
-
- webidl.argumentLengthCheck(arguments, 1, 'FileReader.readAsBinaryString')
-
- blob = webidl.converters.Blob(blob, { strict: false })
-
- // The readAsBinaryString(blob) method, when invoked,
- // must initiate a read operation for blob with BinaryString.
- readOperation(this, blob, 'BinaryString')
- }
-
- /**
- * @see https://w3c.github.io/FileAPI/#readAsDataText
- * @param {import('buffer').Blob} blob
- * @param {string?} encoding
- */
- readAsText (blob, encoding = undefined) {
- webidl.brandCheck(this, FileReader)
-
- webidl.argumentLengthCheck(arguments, 1, 'FileReader.readAsText')
-
- blob = webidl.converters.Blob(blob, { strict: false })
-
- if (encoding !== undefined) {
- encoding = webidl.converters.DOMString(encoding, 'FileReader.readAsText', 'encoding')
- }
-
- // The readAsText(blob, encoding) method, when invoked,
- // must initiate a read operation for blob with Text and encoding.
- readOperation(this, blob, 'Text', encoding)
- }
-
- /**
- * @see https://w3c.github.io/FileAPI/#dfn-readAsDataURL
- * @param {import('buffer').Blob} blob
- */
- readAsDataURL (blob) {
- webidl.brandCheck(this, FileReader)
-
- webidl.argumentLengthCheck(arguments, 1, 'FileReader.readAsDataURL')
-
- blob = webidl.converters.Blob(blob, { strict: false })
-
- // The readAsDataURL(blob) method, when invoked, must
- // initiate a read operation for blob with DataURL.
- readOperation(this, blob, 'DataURL')
- }
-
- /**
- * @see https://w3c.github.io/FileAPI/#dfn-abort
- */
- abort () {
- // 1. If this's state is "empty" or if this's state is
- // "done" set this's result to null and terminate
- // this algorithm.
- if (this[kState] === 'empty' || this[kState] === 'done') {
- this[kResult] = null
- return
+const debugEnvVariable = (typeof process !== "undefined" && process.env && process.env.DEBUG) || undefined;
+let enabledString;
+let enabledNamespaces = [];
+let skippedNamespaces = [];
+const debuggers = [];
+if (debugEnvVariable) {
+ enable(debugEnvVariable);
+}
+const debugObj = Object.assign((namespace) => {
+ return createDebugger(namespace);
+}, {
+ enable,
+ enabled,
+ disable,
+ log: log,
+});
+function enable(namespaces) {
+ enabledString = namespaces;
+ enabledNamespaces = [];
+ skippedNamespaces = [];
+ const namespaceList = namespaces.split(",").map((ns) => ns.trim());
+ for (const ns of namespaceList) {
+ if (ns.startsWith("-")) {
+ skippedNamespaces.push(ns.substring(1));
+ }
+ else {
+ enabledNamespaces.push(ns);
+ }
}
-
- // 2. If this's state is "loading" set this's state to
- // "done" and set this's result to null.
- if (this[kState] === 'loading') {
- this[kState] = 'done'
- this[kResult] = null
+ for (const instance of debuggers) {
+ instance.enabled = enabled(instance.namespace);
}
-
- // 3. If there are any tasks from this on the file reading
- // task source in an affiliated task queue, then remove
- // those tasks from that task queue.
- this[kAborted] = true
-
- // 4. Terminate the algorithm for the read method being processed.
- // TODO
-
- // 5. Fire a progress event called abort at this.
- fireAProgressEvent('abort', this)
-
- // 6. If this's state is not "loading", fire a progress
- // event called loadend at this.
- if (this[kState] !== 'loading') {
- fireAProgressEvent('loadend', this)
+}
+function enabled(namespace) {
+ if (namespace.endsWith("*")) {
+ return true;
}
- }
-
- /**
- * @see https://w3c.github.io/FileAPI/#dom-filereader-readystate
- */
- get readyState () {
- webidl.brandCheck(this, FileReader)
-
- switch (this[kState]) {
- case 'empty': return this.EMPTY
- case 'loading': return this.LOADING
- case 'done': return this.DONE
+ for (const skipped of skippedNamespaces) {
+ if (namespaceMatches(namespace, skipped)) {
+ return false;
+ }
}
- }
-
- /**
- * @see https://w3c.github.io/FileAPI/#dom-filereader-result
- */
- get result () {
- webidl.brandCheck(this, FileReader)
-
- // The result attribute’s getter, when invoked, must return
- // this's result.
- return this[kResult]
- }
-
- /**
- * @see https://w3c.github.io/FileAPI/#dom-filereader-error
- */
- get error () {
- webidl.brandCheck(this, FileReader)
-
- // The error attribute’s getter, when invoked, must return
- // this's error.
- return this[kError]
- }
-
- get onloadend () {
- webidl.brandCheck(this, FileReader)
-
- return this[kEvents].loadend
- }
-
- set onloadend (fn) {
- webidl.brandCheck(this, FileReader)
-
- if (this[kEvents].loadend) {
- this.removeEventListener('loadend', this[kEvents].loadend)
+ for (const enabledNamespace of enabledNamespaces) {
+ if (namespaceMatches(namespace, enabledNamespace)) {
+ return true;
+ }
}
-
- if (typeof fn === 'function') {
- this[kEvents].loadend = fn
- this.addEventListener('loadend', fn)
- } else {
- this[kEvents].loadend = null
+ return false;
+}
+/**
+ * Given a namespace, check if it matches a pattern.
+ * Patterns only have a single wildcard character which is *.
+ * The behavior of * is that it matches zero or more other characters.
+ */
+function namespaceMatches(namespace, patternToMatch) {
+ // simple case, no pattern matching required
+ if (patternToMatch.indexOf("*") === -1) {
+ return namespace === patternToMatch;
}
- }
-
- get onerror () {
- webidl.brandCheck(this, FileReader)
-
- return this[kEvents].error
- }
-
- set onerror (fn) {
- webidl.brandCheck(this, FileReader)
-
- if (this[kEvents].error) {
- this.removeEventListener('error', this[kEvents].error)
+ let pattern = patternToMatch;
+ // normalize successive * if needed
+ if (patternToMatch.indexOf("**") !== -1) {
+ const patternParts = [];
+ let lastCharacter = "";
+ for (const character of patternToMatch) {
+ if (character === "*" && lastCharacter === "*") {
+ continue;
+ }
+ else {
+ lastCharacter = character;
+ patternParts.push(character);
+ }
+ }
+ pattern = patternParts.join("");
}
-
- if (typeof fn === 'function') {
- this[kEvents].error = fn
- this.addEventListener('error', fn)
- } else {
- this[kEvents].error = null
+ let namespaceIndex = 0;
+ let patternIndex = 0;
+ const patternLength = pattern.length;
+ const namespaceLength = namespace.length;
+ let lastWildcard = -1;
+ let lastWildcardNamespace = -1;
+ while (namespaceIndex < namespaceLength && patternIndex < patternLength) {
+ if (pattern[patternIndex] === "*") {
+ lastWildcard = patternIndex;
+ patternIndex++;
+ if (patternIndex === patternLength) {
+ // if wildcard is the last character, it will match the remaining namespace string
+ return true;
+ }
+ // now we let the wildcard eat characters until we match the next literal in the pattern
+ while (namespace[namespaceIndex] !== pattern[patternIndex]) {
+ namespaceIndex++;
+ // reached the end of the namespace without a match
+ if (namespaceIndex === namespaceLength) {
+ return false;
+ }
+ }
+ // now that we have a match, let's try to continue on
+ // however, it's possible we could find a later match
+ // so keep a reference in case we have to backtrack
+ lastWildcardNamespace = namespaceIndex;
+ namespaceIndex++;
+ patternIndex++;
+ continue;
+ }
+ else if (pattern[patternIndex] === namespace[namespaceIndex]) {
+ // simple case: literal pattern matches so keep going
+ patternIndex++;
+ namespaceIndex++;
+ }
+ else if (lastWildcard >= 0) {
+ // special case: we don't have a literal match, but there is a previous wildcard
+ // which we can backtrack to and try having the wildcard eat the match instead
+ patternIndex = lastWildcard + 1;
+ namespaceIndex = lastWildcardNamespace + 1;
+ // we've reached the end of the namespace without a match
+ if (namespaceIndex === namespaceLength) {
+ return false;
+ }
+ // similar to the previous logic, let's keep going until we find the next literal match
+ while (namespace[namespaceIndex] !== pattern[patternIndex]) {
+ namespaceIndex++;
+ if (namespaceIndex === namespaceLength) {
+ return false;
+ }
+ }
+ lastWildcardNamespace = namespaceIndex;
+ namespaceIndex++;
+ patternIndex++;
+ continue;
+ }
+ else {
+ return false;
+ }
}
- }
-
- get onloadstart () {
- webidl.brandCheck(this, FileReader)
-
- return this[kEvents].loadstart
- }
-
- set onloadstart (fn) {
- webidl.brandCheck(this, FileReader)
-
- if (this[kEvents].loadstart) {
- this.removeEventListener('loadstart', this[kEvents].loadstart)
+ const namespaceDone = namespaceIndex === namespace.length;
+ const patternDone = patternIndex === pattern.length;
+ // this is to detect the case of an unneeded final wildcard
+ // e.g. the pattern `ab*` should match the string `ab`
+ const trailingWildCard = patternIndex === pattern.length - 1 && pattern[patternIndex] === "*";
+ return namespaceDone && (patternDone || trailingWildCard);
+}
+function disable() {
+ const result = enabledString || "";
+ enable("");
+ return result;
+}
+function createDebugger(namespace) {
+ const newDebugger = Object.assign(debug, {
+ enabled: enabled(namespace),
+ destroy,
+ log: debugObj.log,
+ namespace,
+ extend,
+ });
+ function debug(...args) {
+ if (!newDebugger.enabled) {
+ return;
+ }
+ if (args.length > 0) {
+ args[0] = `${namespace} ${args[0]}`;
+ }
+ newDebugger.log(...args);
}
-
- if (typeof fn === 'function') {
- this[kEvents].loadstart = fn
- this.addEventListener('loadstart', fn)
- } else {
- this[kEvents].loadstart = null
+ debuggers.push(newDebugger);
+ return newDebugger;
+}
+function destroy() {
+ const index = debuggers.indexOf(this);
+ if (index >= 0) {
+ debuggers.splice(index, 1);
+ return true;
}
- }
-
- get onprogress () {
- webidl.brandCheck(this, FileReader)
-
- return this[kEvents].progress
- }
-
- set onprogress (fn) {
- webidl.brandCheck(this, FileReader)
+ return false;
+}
+function extend(namespace) {
+ const newDebugger = createDebugger(`${this.namespace}:${namespace}`);
+ newDebugger.log = this.log;
+ return newDebugger;
+}
+/* harmony default export */ const logger_debug = (debugObj);
+//# sourceMappingURL=debug.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/logger/logger.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- if (this[kEvents].progress) {
- this.removeEventListener('progress', this[kEvents].progress)
+const TYPESPEC_RUNTIME_LOG_LEVELS = ["verbose", "info", "warning", "error"];
+const levelMap = {
+ verbose: 400,
+ info: 300,
+ warning: 200,
+ error: 100,
+};
+function patchLogMethod(parent, child) {
+ child.log = (...args) => {
+ parent.log(...args);
+ };
+}
+function isTypeSpecRuntimeLogLevel(level) {
+ return TYPESPEC_RUNTIME_LOG_LEVELS.includes(level);
+}
+/**
+ * Creates a logger context base on the provided options.
+ * @param options - The options for creating a logger context.
+ * @returns The logger context.
+ */
+function createLoggerContext(options) {
+ const registeredLoggers = new Set();
+ const logLevelFromEnv = (typeof process !== "undefined" && process.env && process.env[options.logLevelEnvVarName]) ||
+ undefined;
+ let logLevel;
+ const clientLogger = logger_debug(options.namespace);
+ clientLogger.log = (...args) => {
+ logger_debug.log(...args);
+ };
+ function contextSetLogLevel(level) {
+ if (level && !isTypeSpecRuntimeLogLevel(level)) {
+ throw new Error(`Unknown log level '${level}'. Acceptable values: ${TYPESPEC_RUNTIME_LOG_LEVELS.join(",")}`);
+ }
+ logLevel = level;
+ const enabledNamespaces = [];
+ for (const logger of registeredLoggers) {
+ if (shouldEnable(logger)) {
+ enabledNamespaces.push(logger.namespace);
+ }
+ }
+ logger_debug.enable(enabledNamespaces.join(","));
}
-
- if (typeof fn === 'function') {
- this[kEvents].progress = fn
- this.addEventListener('progress', fn)
- } else {
- this[kEvents].progress = null
+ if (logLevelFromEnv) {
+ // avoid calling setLogLevel because we don't want a mis-set environment variable to crash
+ if (isTypeSpecRuntimeLogLevel(logLevelFromEnv)) {
+ contextSetLogLevel(logLevelFromEnv);
+ }
+ else {
+ console.error(`${options.logLevelEnvVarName} set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${TYPESPEC_RUNTIME_LOG_LEVELS.join(", ")}.`);
+ }
}
- }
-
- get onload () {
- webidl.brandCheck(this, FileReader)
-
- return this[kEvents].load
- }
-
- set onload (fn) {
- webidl.brandCheck(this, FileReader)
-
- if (this[kEvents].load) {
- this.removeEventListener('load', this[kEvents].load)
+ function shouldEnable(logger) {
+ return Boolean(logLevel && levelMap[logger.level] <= levelMap[logLevel]);
}
-
- if (typeof fn === 'function') {
- this[kEvents].load = fn
- this.addEventListener('load', fn)
- } else {
- this[kEvents].load = null
+ function createLogger(parent, level) {
+ const logger = Object.assign(parent.extend(level), {
+ level,
+ });
+ patchLogMethod(parent, logger);
+ if (shouldEnable(logger)) {
+ const enabledNamespaces = logger_debug.disable();
+ logger_debug.enable(enabledNamespaces + "," + logger.namespace);
+ }
+ registeredLoggers.add(logger);
+ return logger;
}
- }
-
- get onabort () {
- webidl.brandCheck(this, FileReader)
-
- return this[kEvents].abort
- }
-
- set onabort (fn) {
- webidl.brandCheck(this, FileReader)
-
- if (this[kEvents].abort) {
- this.removeEventListener('abort', this[kEvents].abort)
+ function contextGetLogLevel() {
+ return logLevel;
}
-
- if (typeof fn === 'function') {
- this[kEvents].abort = fn
- this.addEventListener('abort', fn)
- } else {
- this[kEvents].abort = null
+ function contextCreateClientLogger(namespace) {
+ const clientRootLogger = clientLogger.extend(namespace);
+ patchLogMethod(clientLogger, clientRootLogger);
+ return {
+ error: createLogger(clientRootLogger, "error"),
+ warning: createLogger(clientRootLogger, "warning"),
+ info: createLogger(clientRootLogger, "info"),
+ verbose: createLogger(clientRootLogger, "verbose"),
+ };
}
- }
+ return {
+ setLogLevel: contextSetLogLevel,
+ getLogLevel: contextGetLogLevel,
+ createClientLogger: contextCreateClientLogger,
+ logger: clientLogger,
+ };
}
-
-// https://w3c.github.io/FileAPI/#dom-filereader-empty
-FileReader.EMPTY = FileReader.prototype.EMPTY = 0
-// https://w3c.github.io/FileAPI/#dom-filereader-loading
-FileReader.LOADING = FileReader.prototype.LOADING = 1
-// https://w3c.github.io/FileAPI/#dom-filereader-done
-FileReader.DONE = FileReader.prototype.DONE = 2
-
-Object.defineProperties(FileReader.prototype, {
- EMPTY: staticPropertyDescriptors,
- LOADING: staticPropertyDescriptors,
- DONE: staticPropertyDescriptors,
- readAsArrayBuffer: kEnumerableProperty,
- readAsBinaryString: kEnumerableProperty,
- readAsText: kEnumerableProperty,
- readAsDataURL: kEnumerableProperty,
- abort: kEnumerableProperty,
- readyState: kEnumerableProperty,
- result: kEnumerableProperty,
- error: kEnumerableProperty,
- onloadstart: kEnumerableProperty,
- onprogress: kEnumerableProperty,
- onload: kEnumerableProperty,
- onabort: kEnumerableProperty,
- onerror: kEnumerableProperty,
- onloadend: kEnumerableProperty,
- [Symbol.toStringTag]: {
- value: 'FileReader',
- writable: false,
- enumerable: false,
- configurable: true
- }
-})
-
-Object.defineProperties(FileReader, {
- EMPTY: staticPropertyDescriptors,
- LOADING: staticPropertyDescriptors,
- DONE: staticPropertyDescriptors
-})
-
-module.exports = {
- FileReader
+const context = createLoggerContext({
+ logLevelEnvVarName: "TYPESPEC_RUNTIME_LOG_LEVEL",
+ namespace: "typeSpecRuntime",
+});
+/**
+ * Immediately enables logging at the specified log level. If no level is specified, logging is disabled.
+ * @param level - The log level to enable for logging.
+ * Options from most verbose to least verbose are:
+ * - verbose
+ * - info
+ * - warning
+ * - error
+ */
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+const TypeSpecRuntimeLogger = context.logger;
+/**
+ * Retrieves the currently specified log level.
+ */
+function setLogLevel(logLevel) {
+ context.setLogLevel(logLevel);
}
-
-
-/***/ }),
-
-/***/ 2981:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const { webidl } = __nccwpck_require__(253)
-
-const kState = Symbol('ProgressEvent state')
-
/**
- * @see https://xhr.spec.whatwg.org/#progressevent
+ * Retrieves the currently specified log level.
*/
-class ProgressEvent extends Event {
- constructor (type, eventInitDict = {}) {
- type = webidl.converters.DOMString(type, 'ProgressEvent constructor', 'type')
- eventInitDict = webidl.converters.ProgressEventInit(eventInitDict ?? {})
-
- super(type, eventInitDict)
-
- this[kState] = {
- lengthComputable: eventInitDict.lengthComputable,
- loaded: eventInitDict.loaded,
- total: eventInitDict.total
- }
- }
-
- get lengthComputable () {
- webidl.brandCheck(this, ProgressEvent)
-
- return this[kState].lengthComputable
- }
-
- get loaded () {
- webidl.brandCheck(this, ProgressEvent)
-
- return this[kState].loaded
- }
-
- get total () {
- webidl.brandCheck(this, ProgressEvent)
-
- return this[kState].total
- }
+function getLogLevel() {
+ return context.getLogLevel();
}
-
-webidl.converters.ProgressEventInit = webidl.dictionaryConverter([
- {
- key: 'lengthComputable',
- converter: webidl.converters.boolean,
- defaultValue: () => false
- },
- {
- key: 'loaded',
- converter: webidl.converters['unsigned long long'],
- defaultValue: () => 0
- },
- {
- key: 'total',
- converter: webidl.converters['unsigned long long'],
- defaultValue: () => 0
- },
- {
- key: 'bubbles',
- converter: webidl.converters.boolean,
- defaultValue: () => false
- },
- {
- key: 'cancelable',
- converter: webidl.converters.boolean,
- defaultValue: () => false
- },
- {
- key: 'composed',
- converter: webidl.converters.boolean,
- defaultValue: () => false
- }
-])
-
-module.exports = {
- ProgressEvent
+/**
+ * Creates a logger for use by the SDKs that inherits from `TypeSpecRuntimeLogger`.
+ * @param namespace - The name of the SDK package.
+ * @hidden
+ */
+function createClientLogger(namespace) {
+ return context.createClientLogger(namespace);
}
-
-
-/***/ }),
-
-/***/ 9657:
-/***/ ((module) => {
-
-
-
-module.exports = {
- kState: Symbol('FileReader state'),
- kResult: Symbol('FileReader result'),
- kError: Symbol('FileReader error'),
- kLastProgressEventFired: Symbol('FileReader last progress event fired timestamp'),
- kEvents: Symbol('FileReader events'),
- kAborted: Symbol('FileReader aborted')
+//# sourceMappingURL=logger.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/httpHeaders.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+function normalizeName(name) {
+ return name.toLowerCase();
}
-
-
-/***/ }),
-
-/***/ 7522:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const {
- kState,
- kError,
- kResult,
- kAborted,
- kLastProgressEventFired
-} = __nccwpck_require__(9657)
-const { ProgressEvent } = __nccwpck_require__(2981)
-const { getEncoding } = __nccwpck_require__(5207)
-const { serializeAMimeType, parseMIMEType } = __nccwpck_require__(980)
-const { types } = __nccwpck_require__(7975)
-const { StringDecoder } = __nccwpck_require__(3193)
-const { btoa } = __nccwpck_require__(4573)
-
-/** @type {PropertyDescriptor} */
-const staticPropertyDescriptors = {
- enumerable: true,
- writable: false,
- configurable: false
+function* headerIterator(map) {
+ for (const entry of map.values()) {
+ yield [entry.name, entry.value];
+ }
}
-
-/**
- * @see https://w3c.github.io/FileAPI/#readOperation
- * @param {import('./filereader').FileReader} fr
- * @param {import('buffer').Blob} blob
- * @param {string} type
- * @param {string?} encodingName
- */
-function readOperation (fr, blob, type, encodingName) {
- // 1. If fr’s state is "loading", throw an InvalidStateError
- // DOMException.
- if (fr[kState] === 'loading') {
- throw new DOMException('Invalid state', 'InvalidStateError')
- }
-
- // 2. Set fr’s state to "loading".
- fr[kState] = 'loading'
-
- // 3. Set fr’s result to null.
- fr[kResult] = null
-
- // 4. Set fr’s error to null.
- fr[kError] = null
-
- // 5. Let stream be the result of calling get stream on blob.
- /** @type {import('stream/web').ReadableStream} */
- const stream = blob.stream()
-
- // 6. Let reader be the result of getting a reader from stream.
- const reader = stream.getReader()
-
- // 7. Let bytes be an empty byte sequence.
- /** @type {Uint8Array[]} */
- const bytes = []
-
- // 8. Let chunkPromise be the result of reading a chunk from
- // stream with reader.
- let chunkPromise = reader.read()
-
- // 9. Let isFirstChunk be true.
- let isFirstChunk = true
-
- // 10. In parallel, while true:
- // Note: "In parallel" just means non-blocking
- // Note 2: readOperation itself cannot be async as double
- // reading the body would then reject the promise, instead
- // of throwing an error.
- ;(async () => {
- while (!fr[kAborted]) {
- // 1. Wait for chunkPromise to be fulfilled or rejected.
- try {
- const { done, value } = await chunkPromise
-
- // 2. If chunkPromise is fulfilled, and isFirstChunk is
- // true, queue a task to fire a progress event called
- // loadstart at fr.
- if (isFirstChunk && !fr[kAborted]) {
- queueMicrotask(() => {
- fireAProgressEvent('loadstart', fr)
- })
- }
-
- // 3. Set isFirstChunk to false.
- isFirstChunk = false
-
- // 4. If chunkPromise is fulfilled with an object whose
- // done property is false and whose value property is
- // a Uint8Array object, run these steps:
- if (!done && types.isUint8Array(value)) {
- // 1. Let bs be the byte sequence represented by the
- // Uint8Array object.
-
- // 2. Append bs to bytes.
- bytes.push(value)
-
- // 3. If roughly 50ms have passed since these steps
- // were last invoked, queue a task to fire a
- // progress event called progress at fr.
- if (
- (
- fr[kLastProgressEventFired] === undefined ||
- Date.now() - fr[kLastProgressEventFired] >= 50
- ) &&
- !fr[kAborted]
- ) {
- fr[kLastProgressEventFired] = Date.now()
- queueMicrotask(() => {
- fireAProgressEvent('progress', fr)
- })
- }
-
- // 4. Set chunkPromise to the result of reading a
- // chunk from stream with reader.
- chunkPromise = reader.read()
- } else if (done) {
- // 5. Otherwise, if chunkPromise is fulfilled with an
- // object whose done property is true, queue a task
- // to run the following steps and abort this algorithm:
- queueMicrotask(() => {
- // 1. Set fr’s state to "done".
- fr[kState] = 'done'
-
- // 2. Let result be the result of package data given
- // bytes, type, blob’s type, and encodingName.
- try {
- const result = packageData(bytes, type, blob.type, encodingName)
-
- // 4. Else:
-
- if (fr[kAborted]) {
- return
- }
-
- // 1. Set fr’s result to result.
- fr[kResult] = result
-
- // 2. Fire a progress event called load at the fr.
- fireAProgressEvent('load', fr)
- } catch (error) {
- // 3. If package data threw an exception error:
-
- // 1. Set fr’s error to error.
- fr[kError] = error
-
- // 2. Fire a progress event called error at fr.
- fireAProgressEvent('error', fr)
+class HttpHeadersImpl {
+ _headersMap;
+ constructor(rawHeaders) {
+ this._headersMap = new Map();
+ if (rawHeaders) {
+ for (const headerName of Object.keys(rawHeaders)) {
+ this.set(headerName, rawHeaders[headerName]);
}
-
- // 5. If fr’s state is not "loading", fire a progress
- // event called loadend at the fr.
- if (fr[kState] !== 'loading') {
- fireAProgressEvent('loadend', fr)
+ }
+ }
+ /**
+ * Set a header in this collection with the provided name and value. The name is
+ * case-insensitive.
+ * @param name - The name of the header to set. This value is case-insensitive.
+ * @param value - The value of the header to set.
+ */
+ set(name, value) {
+ this._headersMap.set(normalizeName(name), { name, value: String(value).trim() });
+ }
+ /**
+ * Get the header value for the provided header name, or undefined if no header exists in this
+ * collection with the provided name.
+ * @param name - The name of the header. This value is case-insensitive.
+ */
+ get(name) {
+ return this._headersMap.get(normalizeName(name))?.value;
+ }
+ /**
+ * Get whether or not this header collection contains a header entry for the provided header name.
+ * @param name - The name of the header to set. This value is case-insensitive.
+ */
+ has(name) {
+ return this._headersMap.has(normalizeName(name));
+ }
+ /**
+ * Remove the header with the provided headerName.
+ * @param name - The name of the header to remove.
+ */
+ delete(name) {
+ this._headersMap.delete(normalizeName(name));
+ }
+ /**
+ * Get the JSON object representation of this HTTP header collection.
+ */
+ toJSON(options = {}) {
+ const result = {};
+ if (options.preserveCase) {
+ for (const entry of this._headersMap.values()) {
+ result[entry.name] = entry.value;
}
- })
-
- break
}
- } catch (error) {
- if (fr[kAborted]) {
- return
+ else {
+ for (const [normalizedName, entry] of this._headersMap) {
+ result[normalizedName] = entry.value;
+ }
}
-
- // 6. Otherwise, if chunkPromise is rejected with an
- // error error, queue a task to run the following
- // steps and abort this algorithm:
- queueMicrotask(() => {
- // 1. Set fr’s state to "done".
- fr[kState] = 'done'
-
- // 2. Set fr’s error to error.
- fr[kError] = error
-
- // 3. Fire a progress event called error at fr.
- fireAProgressEvent('error', fr)
-
- // 4. If fr’s state is not "loading", fire a progress
- // event called loadend at fr.
- if (fr[kState] !== 'loading') {
- fireAProgressEvent('loadend', fr)
- }
- })
-
- break
- }
+ return result;
+ }
+ /**
+ * Get the string representation of this HTTP header collection.
+ */
+ toString() {
+ return JSON.stringify(this.toJSON({ preserveCase: true }));
+ }
+ /**
+ * Iterate over tuples of header [name, value] pairs.
+ */
+ [Symbol.iterator]() {
+ return headerIterator(this._headersMap);
}
- })()
}
-
/**
- * @see https://w3c.github.io/FileAPI/#fire-a-progress-event
- * @see https://dom.spec.whatwg.org/#concept-event-fire
- * @param {string} e The name of the event
- * @param {import('./filereader').FileReader} reader
+ * Creates an object that satisfies the `HttpHeaders` interface.
+ * @param rawHeaders - A simple object representing initial headers
*/
-function fireAProgressEvent (e, reader) {
- // The progress event e does not bubble. e.bubbles must be false
- // The progress event e is NOT cancelable. e.cancelable must be false
- const event = new ProgressEvent(e, {
- bubbles: false,
- cancelable: false
- })
-
- reader.dispatchEvent(event)
+function httpHeaders_createHttpHeaders(rawHeaders) {
+ return new HttpHeadersImpl(rawHeaders);
}
-
+//# sourceMappingURL=httpHeaders.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/util/uuidUtils.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
/**
- * @see https://w3c.github.io/FileAPI/#blob-package-data
- * @param {Uint8Array[]} bytes
- * @param {string} type
- * @param {string?} mimeType
- * @param {string?} encodingName
+ * Generated Universally Unique Identifier
+ *
+ * @returns RFC4122 v4 UUID.
*/
-function packageData (bytes, type, mimeType, encodingName) {
- // 1. A Blob has an associated package data algorithm, given
- // bytes, a type, a optional mimeType, and a optional
- // encodingName, which switches on type and runs the
- // associated steps:
-
- switch (type) {
- case 'DataURL': {
- // 1. Return bytes as a DataURL [RFC2397] subject to
- // the considerations below:
- // * Use mimeType as part of the Data URL if it is
- // available in keeping with the Data URL
- // specification [RFC2397].
- // * If mimeType is not available return a Data URL
- // without a media-type. [RFC2397].
-
- // https://datatracker.ietf.org/doc/html/rfc2397#section-3
- // dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
- // mediatype := [ type "/" subtype ] *( ";" parameter )
- // data := *urlchar
- // parameter := attribute "=" value
- let dataURL = 'data:'
-
- const parsed = parseMIMEType(mimeType || 'application/octet-stream')
-
- if (parsed !== 'failure') {
- dataURL += serializeAMimeType(parsed)
- }
-
- dataURL += ';base64,'
-
- const decoder = new StringDecoder('latin1')
-
- for (const chunk of bytes) {
- dataURL += btoa(decoder.write(chunk))
- }
-
- dataURL += btoa(decoder.end())
-
- return dataURL
- }
- case 'Text': {
- // 1. Let encoding be failure
- let encoding = 'failure'
-
- // 2. If the encodingName is present, set encoding to the
- // result of getting an encoding from encodingName.
- if (encodingName) {
- encoding = getEncoding(encodingName)
- }
+function randomUUID() {
+ return crypto.randomUUID();
+}
+//# sourceMappingURL=uuidUtils.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/pipelineRequest.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- // 3. If encoding is failure, and mimeType is present:
- if (encoding === 'failure' && mimeType) {
- // 1. Let type be the result of parse a MIME type
- // given mimeType.
- const type = parseMIMEType(mimeType)
- // 2. If type is not failure, set encoding to the result
- // of getting an encoding from type’s parameters["charset"].
- if (type !== 'failure') {
- encoding = getEncoding(type.parameters.get('charset'))
+class PipelineRequestImpl {
+ url;
+ method;
+ headers;
+ timeout;
+ withCredentials;
+ body;
+ multipartBody;
+ formData;
+ streamResponseStatusCodes;
+ enableBrowserStreams;
+ proxySettings;
+ disableKeepAlive;
+ abortSignal;
+ requestId;
+ allowInsecureConnection;
+ onUploadProgress;
+ onDownloadProgress;
+ requestOverrides;
+ authSchemes;
+ constructor(options) {
+ this.url = options.url;
+ this.body = options.body;
+ this.headers = options.headers ?? httpHeaders_createHttpHeaders();
+ this.method = options.method ?? "GET";
+ this.timeout = options.timeout ?? 0;
+ this.multipartBody = options.multipartBody;
+ this.formData = options.formData;
+ this.disableKeepAlive = options.disableKeepAlive ?? false;
+ this.proxySettings = options.proxySettings;
+ this.streamResponseStatusCodes = options.streamResponseStatusCodes;
+ this.withCredentials = options.withCredentials ?? false;
+ this.abortSignal = options.abortSignal;
+ this.onUploadProgress = options.onUploadProgress;
+ this.onDownloadProgress = options.onDownloadProgress;
+ this.requestId = options.requestId || randomUUID();
+ this.allowInsecureConnection = options.allowInsecureConnection ?? false;
+ this.enableBrowserStreams = options.enableBrowserStreams ?? false;
+ this.requestOverrides = options.requestOverrides;
+ this.authSchemes = options.authSchemes;
+ }
+}
+/**
+ * Creates a new pipeline request with the given options.
+ * This method is to allow for the easy setting of default values and not required.
+ * @param options - The options to create the request with.
+ */
+function pipelineRequest_createPipelineRequest(options) {
+ return new PipelineRequestImpl(options);
+}
+//# sourceMappingURL=pipelineRequest.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/pipeline.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+const ValidPhaseNames = new Set(["Deserialize", "Serialize", "Retry", "Sign"]);
+/**
+ * A private implementation of Pipeline.
+ * Do not export this class from the package.
+ * @internal
+ */
+class HttpPipeline {
+ _policies = [];
+ _orderedPolicies;
+ constructor(policies) {
+ this._policies = policies?.slice(0) ?? [];
+ this._orderedPolicies = undefined;
+ }
+ addPolicy(policy, options = {}) {
+ if (options.phase && options.afterPhase) {
+ throw new Error("Policies inside a phase cannot specify afterPhase.");
}
- }
-
- // 4. If encoding is failure, then set encoding to UTF-8.
- if (encoding === 'failure') {
- encoding = 'UTF-8'
- }
-
- // 5. Decode bytes using fallback encoding encoding, and
- // return the result.
- return decode(bytes, encoding)
+ if (options.phase && !ValidPhaseNames.has(options.phase)) {
+ throw new Error(`Invalid phase name: ${options.phase}`);
+ }
+ if (options.afterPhase && !ValidPhaseNames.has(options.afterPhase)) {
+ throw new Error(`Invalid afterPhase name: ${options.afterPhase}`);
+ }
+ this._policies.push({
+ policy,
+ options,
+ });
+ this._orderedPolicies = undefined;
}
- case 'ArrayBuffer': {
- // Return a new ArrayBuffer whose contents are bytes.
- const sequence = combineByteSequences(bytes)
-
- return sequence.buffer
+ removePolicy(options) {
+ const removedPolicies = [];
+ this._policies = this._policies.filter((policyDescriptor) => {
+ if ((options.name && policyDescriptor.policy.name === options.name) ||
+ (options.phase && policyDescriptor.options.phase === options.phase)) {
+ removedPolicies.push(policyDescriptor.policy);
+ return false;
+ }
+ else {
+ return true;
+ }
+ });
+ this._orderedPolicies = undefined;
+ return removedPolicies;
}
- case 'BinaryString': {
- // Return bytes as a binary string, in which every byte
- // is represented by a code unit of equal value [0..255].
- let binaryString = ''
-
- const decoder = new StringDecoder('latin1')
-
- for (const chunk of bytes) {
- binaryString += decoder.write(chunk)
- }
-
- binaryString += decoder.end()
-
- return binaryString
+ sendRequest(httpClient, request) {
+ const policies = this.getOrderedPolicies();
+ const pipeline = policies.reduceRight((next, policy) => {
+ return (req) => {
+ return policy.sendRequest(req, next);
+ };
+ }, (req) => httpClient.sendRequest(req));
+ return pipeline(request);
+ }
+ getOrderedPolicies() {
+ if (!this._orderedPolicies) {
+ this._orderedPolicies = this.orderPolicies();
+ }
+ return this._orderedPolicies;
+ }
+ clone() {
+ return new HttpPipeline(this._policies);
+ }
+ static create() {
+ return new HttpPipeline();
+ }
+ orderPolicies() {
+ /**
+ * The goal of this method is to reliably order pipeline policies
+ * based on their declared requirements when they were added.
+ *
+ * Order is first determined by phase:
+ *
+ * 1. Serialize Phase
+ * 2. Policies not in a phase
+ * 3. Deserialize Phase
+ * 4. Retry Phase
+ * 5. Sign Phase
+ *
+ * Within each phase, policies are executed in the order
+ * they were added unless they were specified to execute
+ * before/after other policies or after a particular phase.
+ *
+ * To determine the final order, we will walk the policy list
+ * in phase order multiple times until all dependencies are
+ * satisfied.
+ *
+ * `afterPolicies` are the set of policies that must be
+ * executed before a given policy. This requirement is
+ * considered satisfied when each of the listed policies
+ * have been scheduled.
+ *
+ * `beforePolicies` are the set of policies that must be
+ * executed after a given policy. Since this dependency
+ * can be expressed by converting it into a equivalent
+ * `afterPolicies` declarations, they are normalized
+ * into that form for simplicity.
+ *
+ * An `afterPhase` dependency is considered satisfied when all
+ * policies in that phase have scheduled.
+ *
+ */
+ const result = [];
+ // Track all policies we know about.
+ const policyMap = new Map();
+ function createPhase(name) {
+ return {
+ name,
+ policies: new Set(),
+ hasRun: false,
+ hasAfterPolicies: false,
+ };
+ }
+ // Track policies for each phase.
+ const serializePhase = createPhase("Serialize");
+ const noPhase = createPhase("None");
+ const deserializePhase = createPhase("Deserialize");
+ const retryPhase = createPhase("Retry");
+ const signPhase = createPhase("Sign");
+ // a list of phases in order
+ const orderedPhases = [serializePhase, noPhase, deserializePhase, retryPhase, signPhase];
+ // Small helper function to map phase name to each Phase
+ function getPhase(phase) {
+ if (phase === "Retry") {
+ return retryPhase;
+ }
+ else if (phase === "Serialize") {
+ return serializePhase;
+ }
+ else if (phase === "Deserialize") {
+ return deserializePhase;
+ }
+ else if (phase === "Sign") {
+ return signPhase;
+ }
+ else {
+ return noPhase;
+ }
+ }
+ // First walk each policy and create a node to track metadata.
+ for (const descriptor of this._policies) {
+ const policy = descriptor.policy;
+ const options = descriptor.options;
+ const policyName = policy.name;
+ if (policyMap.has(policyName)) {
+ throw new Error("Duplicate policy names not allowed in pipeline");
+ }
+ const node = {
+ policy,
+ dependsOn: new Set(),
+ dependants: new Set(),
+ };
+ if (options.afterPhase) {
+ node.afterPhase = getPhase(options.afterPhase);
+ node.afterPhase.hasAfterPolicies = true;
+ }
+ policyMap.set(policyName, node);
+ const phase = getPhase(options.phase);
+ phase.policies.add(node);
+ }
+ // Now that each policy has a node, connect dependency references.
+ for (const descriptor of this._policies) {
+ const { policy, options } = descriptor;
+ const policyName = policy.name;
+ const node = policyMap.get(policyName);
+ if (!node) {
+ throw new Error(`Missing node for policy ${policyName}`);
+ }
+ if (options.afterPolicies) {
+ for (const afterPolicyName of options.afterPolicies) {
+ const afterNode = policyMap.get(afterPolicyName);
+ if (afterNode) {
+ // Linking in both directions helps later
+ // when we want to notify dependants.
+ node.dependsOn.add(afterNode);
+ afterNode.dependants.add(node);
+ }
+ }
+ }
+ if (options.beforePolicies) {
+ for (const beforePolicyName of options.beforePolicies) {
+ const beforeNode = policyMap.get(beforePolicyName);
+ if (beforeNode) {
+ // To execute before another node, make it
+ // depend on the current node.
+ beforeNode.dependsOn.add(node);
+ node.dependants.add(beforeNode);
+ }
+ }
+ }
+ }
+ function walkPhase(phase) {
+ phase.hasRun = true;
+ // Sets iterate in insertion order
+ for (const node of phase.policies) {
+ if (node.afterPhase && (!node.afterPhase.hasRun || node.afterPhase.policies.size)) {
+ // If this node is waiting on a phase to complete,
+ // we need to skip it for now.
+ // Even if the phase is empty, we should wait for it
+ // to be walked to avoid re-ordering policies.
+ continue;
+ }
+ if (node.dependsOn.size === 0) {
+ // If there's nothing else we're waiting for, we can
+ // add this policy to the result list.
+ result.push(node.policy);
+ // Notify anything that depends on this policy that
+ // the policy has been scheduled.
+ for (const dependant of node.dependants) {
+ dependant.dependsOn.delete(node);
+ }
+ policyMap.delete(node.policy.name);
+ phase.policies.delete(node);
+ }
+ }
+ }
+ function walkPhases() {
+ for (const phase of orderedPhases) {
+ walkPhase(phase);
+ // if the phase isn't complete
+ if (phase.policies.size > 0 && phase !== noPhase) {
+ if (!noPhase.hasRun) {
+ // Try running noPhase to see if that unblocks this phase next tick.
+ // This can happen if a phase that happens before noPhase
+ // is waiting on a noPhase policy to complete.
+ walkPhase(noPhase);
+ }
+ // Don't proceed to the next phase until this phase finishes.
+ return;
+ }
+ if (phase.hasAfterPolicies) {
+ // Run any policies unblocked by this phase
+ walkPhase(noPhase);
+ }
+ }
+ }
+ // Iterate until we've put every node in the result list.
+ let iteration = 0;
+ while (policyMap.size > 0) {
+ iteration++;
+ const initialResultLength = result.length;
+ // Keep walking each phase in order until we can order every node.
+ walkPhases();
+ // The result list *should* get at least one larger each time
+ // after the first full pass.
+ // Otherwise, we're going to loop forever.
+ if (result.length <= initialResultLength && iteration > 1) {
+ throw new Error("Cannot satisfy policy dependencies due to requirements cycle.");
+ }
+ }
+ return result;
}
- }
}
-
/**
- * @see https://encoding.spec.whatwg.org/#decode
- * @param {Uint8Array[]} ioQueue
- * @param {string} encoding
+ * Creates a totally empty pipeline.
+ * Useful for testing or creating a custom one.
*/
-function decode (ioQueue, encoding) {
- const bytes = combineByteSequences(ioQueue)
-
- // 1. Let BOMEncoding be the result of BOM sniffing ioQueue.
- const BOMEncoding = BOMSniffing(bytes)
-
- let slice = 0
-
- // 2. If BOMEncoding is non-null:
- if (BOMEncoding !== null) {
- // 1. Set encoding to BOMEncoding.
- encoding = BOMEncoding
-
- // 2. Read three bytes from ioQueue, if BOMEncoding is
- // UTF-8; otherwise read two bytes.
- // (Do nothing with those bytes.)
- slice = BOMEncoding === 'UTF-8' ? 3 : 2
- }
-
- // 3. Process a queue with an instance of encoding’s
- // decoder, ioQueue, output, and "replacement".
-
- // 4. Return output.
-
- const sliced = bytes.slice(slice)
- return new TextDecoder(encoding).decode(sliced)
+function pipeline_createEmptyPipeline() {
+ return HttpPipeline.create();
}
-
+//# sourceMappingURL=pipeline.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/util/object.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
/**
- * @see https://encoding.spec.whatwg.org/#bom-sniff
- * @param {Uint8Array} ioQueue
+ * Helper to determine when an input is a generic JS object.
+ * @returns true when input is an object type that is not null, Array, RegExp, or Date.
*/
-function BOMSniffing (ioQueue) {
- // 1. Let BOM be the result of peeking 3 bytes from ioQueue,
- // converted to a byte sequence.
- const [a, b, c] = ioQueue
-
- // 2. For each of the rows in the table below, starting with
- // the first one and going down, if BOM starts with the
- // bytes given in the first column, then return the
- // encoding given in the cell in the second column of that
- // row. Otherwise, return null.
- if (a === 0xEF && b === 0xBB && c === 0xBF) {
- return 'UTF-8'
- } else if (a === 0xFE && b === 0xFF) {
- return 'UTF-16BE'
- } else if (a === 0xFF && b === 0xFE) {
- return 'UTF-16LE'
- }
-
- return null
+function isObject(input) {
+ return (typeof input === "object" &&
+ input !== null &&
+ !Array.isArray(input) &&
+ !(input instanceof RegExp) &&
+ !(input instanceof Date));
}
+//# sourceMappingURL=object.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/util/error.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
/**
- * @param {Uint8Array[]} sequences
+ * Typeguard for an error object shape (has name and message)
+ * @param e - Something caught by a catch clause.
*/
-function combineByteSequences (sequences) {
- const size = sequences.reduce((a, b) => {
- return a + b.byteLength
- }, 0)
-
- let offset = 0
-
- return sequences.reduce((a, b) => {
- a.set(b, offset)
- offset += b.byteLength
- return a
- }, new Uint8Array(size))
-}
-
-module.exports = {
- staticPropertyDescriptors,
- readOperation,
- fireAProgressEvent
+function isError(e) {
+ if (isObject(e)) {
+ const hasName = typeof e.name === "string";
+ const hasMessage = typeof e.message === "string";
+ return hasName && hasMessage;
+ }
+ return false;
}
+//# sourceMappingURL=error.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/util/inspect.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+const custom = external_node_util_.inspect.custom;
+//# sourceMappingURL=inspect.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/util/sanitizer.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
-/***/ }),
-
-/***/ 2569:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const { uid, states, sentCloseFrameState, emptyBuffer, opcodes } = __nccwpck_require__(1816)
-const {
- kReadyState,
- kSentClose,
- kByteParser,
- kReceivedClose,
- kResponse
-} = __nccwpck_require__(2456)
-const { fireEvent, failWebsocketConnection, isClosing, isClosed, isEstablished, parseExtensions } = __nccwpck_require__(5673)
-const { channels } = __nccwpck_require__(8150)
-const { CloseEvent } = __nccwpck_require__(44)
-const { makeRequest } = __nccwpck_require__(6055)
-const { fetching } = __nccwpck_require__(7302)
-const { Headers, getHeadersList } = __nccwpck_require__(3676)
-const { getDecodeSplit } = __nccwpck_require__(4296)
-const { WebsocketFrameSend } = __nccwpck_require__(9272)
-
-/** @type {import('crypto')} */
-let crypto
-try {
- crypto = __nccwpck_require__(7598)
-/* c8 ignore next 3 */
-} catch {
-
-}
-
+const RedactedString = "REDACTED";
+// Make sure this list is up-to-date with the one under core/logger/Readme#Keyconcepts
+const defaultAllowedHeaderNames = [
+ "x-ms-client-request-id",
+ "x-ms-return-client-request-id",
+ "x-ms-useragent",
+ "x-ms-correlation-request-id",
+ "x-ms-request-id",
+ "client-request-id",
+ "ms-cv",
+ "return-client-request-id",
+ "traceparent",
+ "Access-Control-Allow-Credentials",
+ "Access-Control-Allow-Headers",
+ "Access-Control-Allow-Methods",
+ "Access-Control-Allow-Origin",
+ "Access-Control-Expose-Headers",
+ "Access-Control-Max-Age",
+ "Access-Control-Request-Headers",
+ "Access-Control-Request-Method",
+ "Origin",
+ "Accept",
+ "Accept-Encoding",
+ "Cache-Control",
+ "Connection",
+ "Content-Length",
+ "Content-Type",
+ "Date",
+ "ETag",
+ "Expires",
+ "If-Match",
+ "If-Modified-Since",
+ "If-None-Match",
+ "If-Unmodified-Since",
+ "Last-Modified",
+ "Pragma",
+ "Request-Id",
+ "Retry-After",
+ "Server",
+ "Transfer-Encoding",
+ "User-Agent",
+ "WWW-Authenticate",
+];
+const defaultAllowedQueryParameters = ["api-version"];
/**
- * @see https://websockets.spec.whatwg.org/#concept-websocket-establish
- * @param {URL} url
- * @param {string|string[]} protocols
- * @param {import('./websocket').WebSocket} ws
- * @param {(response: any, extensions: string[] | undefined) => void} onEstablish
- * @param {Partial} options
+ * A utility class to sanitize objects for logging.
*/
-function establishWebSocketConnection (url, protocols, client, ws, onEstablish, options) {
- // 1. Let requestURL be a copy of url, with its scheme set to "http", if url’s
- // scheme is "ws", and to "https" otherwise.
- const requestURL = url
-
- requestURL.protocol = url.protocol === 'ws:' ? 'http:' : 'https:'
-
- // 2. Let request be a new request, whose URL is requestURL, client is client,
- // service-workers mode is "none", referrer is "no-referrer", mode is
- // "websocket", credentials mode is "include", cache mode is "no-store" ,
- // and redirect mode is "error".
- const request = makeRequest({
- urlList: [requestURL],
- client,
- serviceWorkers: 'none',
- referrer: 'no-referrer',
- mode: 'websocket',
- credentials: 'include',
- cache: 'no-store',
- redirect: 'error'
- })
-
- // Note: undici extension, allow setting custom headers.
- if (options.headers) {
- const headersList = getHeadersList(new Headers(options.headers))
-
- request.headersList = headersList
- }
-
- // 3. Append (`Upgrade`, `websocket`) to request’s header list.
- // 4. Append (`Connection`, `Upgrade`) to request’s header list.
- // Note: both of these are handled by undici currently.
- // https://github.com/nodejs/undici/blob/68c269c4144c446f3f1220951338daef4a6b5ec4/lib/client.js#L1397
-
- // 5. Let keyValue be a nonce consisting of a randomly selected
- // 16-byte value that has been forgiving-base64-encoded and
- // isomorphic encoded.
- const keyValue = crypto.randomBytes(16).toString('base64')
-
- // 6. Append (`Sec-WebSocket-Key`, keyValue) to request’s
- // header list.
- request.headersList.append('sec-websocket-key', keyValue)
-
- // 7. Append (`Sec-WebSocket-Version`, `13`) to request’s
- // header list.
- request.headersList.append('sec-websocket-version', '13')
-
- // 8. For each protocol in protocols, combine
- // (`Sec-WebSocket-Protocol`, protocol) in request’s header
- // list.
- for (const protocol of protocols) {
- request.headersList.append('sec-websocket-protocol', protocol)
- }
-
- // 9. Let permessageDeflate be a user-agent defined
- // "permessage-deflate" extension header value.
- // https://github.com/mozilla/gecko-dev/blob/ce78234f5e653a5d3916813ff990f053510227bc/netwerk/protocol/websocket/WebSocketChannel.cpp#L2673
- const permessageDeflate = 'permessage-deflate; client_max_window_bits'
-
- // 10. Append (`Sec-WebSocket-Extensions`, permessageDeflate) to
- // request’s header list.
- request.headersList.append('sec-websocket-extensions', permessageDeflate)
-
- // 11. Fetch request with useParallelQueue set to true, and
- // processResponse given response being these steps:
- const controller = fetching({
- request,
- useParallelQueue: true,
- dispatcher: options.dispatcher,
- processResponse (response) {
- // 1. If response is a network error or its status is not 101,
- // fail the WebSocket connection.
- if (response.type === 'error' || response.status !== 101) {
- failWebsocketConnection(ws, 'Received network error or non-101 status code.')
- return
- }
-
- // 2. If protocols is not the empty list and extracting header
- // list values given `Sec-WebSocket-Protocol` and response’s
- // header list results in null, failure, or the empty byte
- // sequence, then fail the WebSocket connection.
- if (protocols.length !== 0 && !response.headersList.get('Sec-WebSocket-Protocol')) {
- failWebsocketConnection(ws, 'Server did not respond with sent protocols.')
- return
- }
-
- // 3. Follow the requirements stated step 2 to step 6, inclusive,
- // of the last set of steps in section 4.1 of The WebSocket
- // Protocol to validate response. This either results in fail
- // the WebSocket connection or the WebSocket connection is
- // established.
-
- // 2. If the response lacks an |Upgrade| header field or the |Upgrade|
- // header field contains a value that is not an ASCII case-
- // insensitive match for the value "websocket", the client MUST
- // _Fail the WebSocket Connection_.
- if (response.headersList.get('Upgrade')?.toLowerCase() !== 'websocket') {
- failWebsocketConnection(ws, 'Server did not set Upgrade header to "websocket".')
- return
- }
-
- // 3. If the response lacks a |Connection| header field or the
- // |Connection| header field doesn't contain a token that is an
- // ASCII case-insensitive match for the value "Upgrade", the client
- // MUST _Fail the WebSocket Connection_.
- if (response.headersList.get('Connection')?.toLowerCase() !== 'upgrade') {
- failWebsocketConnection(ws, 'Server did not set Connection header to "upgrade".')
- return
- }
-
- // 4. If the response lacks a |Sec-WebSocket-Accept| header field or
- // the |Sec-WebSocket-Accept| contains a value other than the
- // base64-encoded SHA-1 of the concatenation of the |Sec-WebSocket-
- // Key| (as a string, not base64-decoded) with the string "258EAFA5-
- // E914-47DA-95CA-C5AB0DC85B11" but ignoring any leading and
- // trailing whitespace, the client MUST _Fail the WebSocket
- // Connection_.
- const secWSAccept = response.headersList.get('Sec-WebSocket-Accept')
- const digest = crypto.createHash('sha1').update(keyValue + uid).digest('base64')
- if (secWSAccept !== digest) {
- failWebsocketConnection(ws, 'Incorrect hash received in Sec-WebSocket-Accept header.')
- return
- }
-
- // 5. If the response includes a |Sec-WebSocket-Extensions| header
- // field and this header field indicates the use of an extension
- // that was not present in the client's handshake (the server has
- // indicated an extension not requested by the client), the client
- // MUST _Fail the WebSocket Connection_. (The parsing of this
- // header field to determine which extensions are requested is
- // discussed in Section 9.1.)
- const secExtension = response.headersList.get('Sec-WebSocket-Extensions')
- let extensions
-
- if (secExtension !== null) {
- extensions = parseExtensions(secExtension)
-
- if (!extensions.has('permessage-deflate')) {
- failWebsocketConnection(ws, 'Sec-WebSocket-Extensions header does not match.')
- return
+class Sanitizer {
+ allowedHeaderNames;
+ allowedQueryParameters;
+ constructor({ additionalAllowedHeaderNames: allowedHeaderNames = [], additionalAllowedQueryParameters: allowedQueryParameters = [], } = {}) {
+ allowedHeaderNames = defaultAllowedHeaderNames.concat(allowedHeaderNames);
+ allowedQueryParameters = defaultAllowedQueryParameters.concat(allowedQueryParameters);
+ this.allowedHeaderNames = new Set(allowedHeaderNames.map((n) => n.toLowerCase()));
+ this.allowedQueryParameters = new Set(allowedQueryParameters.map((p) => p.toLowerCase()));
+ }
+ /**
+ * Sanitizes an object for logging.
+ * @param obj - The object to sanitize
+ * @returns - The sanitized object as a string
+ */
+ sanitize(obj) {
+ const seen = new Set();
+ return JSON.stringify(obj, (key, value) => {
+ // Ensure Errors include their interesting non-enumerable members
+ if (value instanceof Error) {
+ return {
+ ...value,
+ name: value.name,
+ message: value.message,
+ };
+ }
+ if (key === "headers" && isObject(value)) {
+ return this.sanitizeHeaders(value);
+ }
+ else if (key === "url" && typeof value === "string") {
+ return this.sanitizeUrl(value);
+ }
+ else if (key === "query" && isObject(value)) {
+ return this.sanitizeQuery(value);
+ }
+ else if (key === "body") {
+ // Don't log the request body
+ return undefined;
+ }
+ else if (key === "response") {
+ // Don't log response again
+ return undefined;
+ }
+ else if (key === "operationSpec") {
+ // When using sendOperationRequest, the request carries a massive
+ // field with the autorest spec. No need to log it.
+ return undefined;
+ }
+ else if (Array.isArray(value) || isObject(value)) {
+ if (seen.has(value)) {
+ return "[Circular]";
+ }
+ seen.add(value);
+ }
+ return value;
+ }, 2);
+ }
+ /**
+ * Sanitizes a URL for logging.
+ * @param value - The URL to sanitize
+ * @returns - The sanitized URL as a string
+ */
+ sanitizeUrl(value) {
+ if (typeof value !== "string" || value === null || value === "") {
+ return value;
}
- }
-
- // 6. If the response includes a |Sec-WebSocket-Protocol| header field
- // and this header field indicates the use of a subprotocol that was
- // not present in the client's handshake (the server has indicated a
- // subprotocol not requested by the client), the client MUST _Fail
- // the WebSocket Connection_.
- const secProtocol = response.headersList.get('Sec-WebSocket-Protocol')
-
- if (secProtocol !== null) {
- const requestProtocols = getDecodeSplit('sec-websocket-protocol', request.headersList)
-
- // The client can request that the server use a specific subprotocol by
- // including the |Sec-WebSocket-Protocol| field in its handshake. If it
- // is specified, the server needs to include the same field and one of
- // the selected subprotocol values in its response for the connection to
- // be established.
- if (!requestProtocols.includes(secProtocol)) {
- failWebsocketConnection(ws, 'Protocol was not set in the opening handshake.')
- return
+ const url = new URL(value);
+ if (!url.search) {
+ return value;
}
- }
-
- response.socket.on('data', onSocketData)
- response.socket.on('close', onSocketClose)
- response.socket.on('error', onSocketError)
-
- if (channels.open.hasSubscribers) {
- channels.open.publish({
- address: response.socket.address(),
- protocol: secProtocol,
- extensions: secExtension
- })
- }
-
- onEstablish(response, extensions)
+ for (const [key] of url.searchParams) {
+ if (!this.allowedQueryParameters.has(key.toLowerCase())) {
+ url.searchParams.set(key, RedactedString);
+ }
+ }
+ return url.toString();
}
- })
-
- return controller
-}
-
-function closeWebSocketConnection (ws, code, reason, reasonByteLength) {
- if (isClosing(ws) || isClosed(ws)) {
- // If this's ready state is CLOSING (2) or CLOSED (3)
- // Do nothing.
- } else if (!isEstablished(ws)) {
- // If the WebSocket connection is not yet established
- // Fail the WebSocket connection and set this's ready state
- // to CLOSING (2).
- failWebsocketConnection(ws, 'Connection was closed before it was established.')
- ws[kReadyState] = states.CLOSING
- } else if (ws[kSentClose] === sentCloseFrameState.NOT_SENT) {
- // If the WebSocket closing handshake has not yet been started
- // Start the WebSocket closing handshake and set this's ready
- // state to CLOSING (2).
- // - If neither code nor reason is present, the WebSocket Close
- // message must not have a body.
- // - If code is present, then the status code to use in the
- // WebSocket Close message must be the integer given by code.
- // - If reason is also present, then reasonBytes must be
- // provided in the Close message after the status code.
-
- ws[kSentClose] = sentCloseFrameState.PROCESSING
-
- const frame = new WebsocketFrameSend()
-
- // If neither code nor reason is present, the WebSocket Close
- // message must not have a body.
-
- // If code is present, then the status code to use in the
- // WebSocket Close message must be the integer given by code.
- if (code !== undefined && reason === undefined) {
- frame.frameData = Buffer.allocUnsafe(2)
- frame.frameData.writeUInt16BE(code, 0)
- } else if (code !== undefined && reason !== undefined) {
- // If reason is also present, then reasonBytes must be
- // provided in the Close message after the status code.
- frame.frameData = Buffer.allocUnsafe(2 + reasonByteLength)
- frame.frameData.writeUInt16BE(code, 0)
- // the body MAY contain UTF-8-encoded data with value /reason/
- frame.frameData.write(reason, 2, 'utf-8')
- } else {
- frame.frameData = emptyBuffer
+ sanitizeHeaders(obj) {
+ const sanitized = {};
+ for (const key of Object.keys(obj)) {
+ if (this.allowedHeaderNames.has(key.toLowerCase())) {
+ sanitized[key] = obj[key];
+ }
+ else {
+ sanitized[key] = RedactedString;
+ }
+ }
+ return sanitized;
}
+ sanitizeQuery(value) {
+ if (typeof value !== "object" || value === null) {
+ return value;
+ }
+ const sanitized = {};
+ for (const k of Object.keys(value)) {
+ if (this.allowedQueryParameters.has(k.toLowerCase())) {
+ sanitized[k] = value[k];
+ }
+ else {
+ sanitized[k] = RedactedString;
+ }
+ }
+ return sanitized;
+ }
+}
+//# sourceMappingURL=sanitizer.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/restError.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- /** @type {import('stream').Duplex} */
- const socket = ws[kResponse].socket
-
- socket.write(frame.createFrame(opcodes.CLOSE))
-
- ws[kSentClose] = sentCloseFrameState.SENT
- // Upon either sending or receiving a Close control frame, it is said
- // that _The WebSocket Closing Handshake is Started_ and that the
- // WebSocket connection is in the CLOSING state.
- ws[kReadyState] = states.CLOSING
- } else {
- // Otherwise
- // Set this's ready state to CLOSING (2).
- ws[kReadyState] = states.CLOSING
- }
-}
+const errorSanitizer = new Sanitizer();
/**
- * @param {Buffer} chunk
+ * A custom error type for failed pipeline requests.
*/
-function onSocketData (chunk) {
- if (!this.ws[kByteParser].write(chunk)) {
- this.pause()
- }
+class restError_RestError extends Error {
+ /**
+ * Something went wrong when making the request.
+ * This means the actual request failed for some reason,
+ * such as a DNS issue or the connection being lost.
+ */
+ static REQUEST_SEND_ERROR = "REQUEST_SEND_ERROR";
+ /**
+ * This means that parsing the response from the server failed.
+ * It may have been malformed.
+ */
+ static PARSE_ERROR = "PARSE_ERROR";
+ /**
+ * The code of the error itself (use statics on RestError if possible.)
+ */
+ code;
+ /**
+ * The HTTP status code of the request (if applicable.)
+ */
+ statusCode;
+ /**
+ * The request that was made.
+ * This property is non-enumerable.
+ */
+ request;
+ /**
+ * The response received (if any.)
+ * This property is non-enumerable.
+ */
+ response;
+ /**
+ * Bonus property set by the throw site.
+ */
+ details;
+ constructor(message, options = {}) {
+ super(message);
+ this.name = "RestError";
+ this.code = options.code;
+ this.statusCode = options.statusCode;
+ // The request and response may contain sensitive information in the headers or body.
+ // To help prevent this sensitive information being accidentally logged, the request and response
+ // properties are marked as non-enumerable here. This prevents them showing up in the output of
+ // JSON.stringify and console.log.
+ Object.defineProperty(this, "request", { value: options.request, enumerable: false });
+ Object.defineProperty(this, "response", { value: options.response, enumerable: false });
+ // Only include useful agent information in the request for logging, as the full agent object
+ // may contain large binary data.
+ const agent = this.request?.agent
+ ? {
+ maxFreeSockets: this.request.agent.maxFreeSockets,
+ maxSockets: this.request.agent.maxSockets,
+ }
+ : undefined;
+ // Logging method for util.inspect in Node
+ Object.defineProperty(this, custom, {
+ value: () => {
+ // Extract non-enumerable properties and add them back. This is OK since in this output the request and
+ // response get sanitized.
+ return `RestError: ${this.message} \n ${errorSanitizer.sanitize({
+ ...this,
+ request: { ...this.request, agent },
+ response: this.response,
+ })}`;
+ },
+ enumerable: false,
+ });
+ Object.setPrototypeOf(this, restError_RestError.prototype);
+ }
}
-
/**
- * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
- * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4
+ * Typeguard for RestError
+ * @param e - Something caught by a catch clause.
*/
-function onSocketClose () {
- const { ws } = this
- const { [kResponse]: response } = ws
-
- response.socket.off('data', onSocketData)
- response.socket.off('close', onSocketClose)
- response.socket.off('error', onSocketError)
-
- // If the TCP connection was closed after the
- // WebSocket closing handshake was completed, the WebSocket connection
- // is said to have been closed _cleanly_.
- const wasClean = ws[kSentClose] === sentCloseFrameState.SENT && ws[kReceivedClose]
-
- let code = 1005
- let reason = ''
+function restError_isRestError(e) {
+ if (e instanceof restError_RestError) {
+ return true;
+ }
+ return isError(e) && e.name === "RestError";
+}
+//# sourceMappingURL=restError.js.map
+// EXTERNAL MODULE: external "node:http"
+var external_node_http_ = __nccwpck_require__(7067);
+;// CONCATENATED MODULE: external "node:https"
+const external_node_https_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:https");
+// EXTERNAL MODULE: external "node:zlib"
+var external_node_zlib_ = __nccwpck_require__(8522);
+// EXTERNAL MODULE: external "node:stream"
+var external_node_stream_ = __nccwpck_require__(7075);
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/log.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- const result = ws[kByteParser].closingInfo
+const log_logger = createClientLogger("ts-http-runtime");
+//# sourceMappingURL=log.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/nodeHttpClient.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- if (result && !result.error) {
- code = result.code ?? 1005
- reason = result.reason
- } else if (!ws[kReceivedClose]) {
- // If _The WebSocket
- // Connection is Closed_ and no Close control frame was received by the
- // endpoint (such as could occur if the underlying transport connection
- // is lost), _The WebSocket Connection Close Code_ is considered to be
- // 1006.
- code = 1006
- }
- // 1. Change the ready state to CLOSED (3).
- ws[kReadyState] = states.CLOSED
- // 2. If the user agent was required to fail the WebSocket
- // connection, or if the WebSocket connection was closed
- // after being flagged as full, fire an event named error
- // at the WebSocket object.
- // TODO
- // 3. Fire an event named close at the WebSocket object,
- // using CloseEvent, with the wasClean attribute
- // initialized to true if the connection closed cleanly
- // and false otherwise, the code attribute initialized to
- // the WebSocket connection close code, and the reason
- // attribute initialized to the result of applying UTF-8
- // decode without BOM to the WebSocket connection close
- // reason.
- // TODO: process.nextTick
- fireEvent('close', ws, (type, init) => new CloseEvent(type, init), {
- wasClean, code, reason
- })
- if (channels.close.hasSubscribers) {
- channels.close.publish({
- websocket: ws,
- code,
- reason
- })
- }
-}
-function onSocketError (error) {
- const { ws } = this
- ws[kReadyState] = states.CLOSING
- if (channels.socketError.hasSubscribers) {
- channels.socketError.publish(error)
- }
- this.destroy()
+const DEFAULT_TLS_SETTINGS = {};
+function nodeHttpClient_isReadableStream(body) {
+ return body && typeof body.pipe === "function";
}
-
-module.exports = {
- establishWebSocketConnection,
- closeWebSocketConnection
+function isStreamComplete(stream) {
+ if (stream.readable === false) {
+ return Promise.resolve();
+ }
+ return new Promise((resolve) => {
+ const handler = () => {
+ resolve();
+ stream.removeListener("close", handler);
+ stream.removeListener("end", handler);
+ stream.removeListener("error", handler);
+ };
+ stream.on("close", handler);
+ stream.on("end", handler);
+ stream.on("error", handler);
+ });
}
-
-
-/***/ }),
-
-/***/ 1816:
-/***/ ((module) => {
-
-
-
-// This is a Globally Unique Identifier unique used
-// to validate that the endpoint accepts websocket
-// connections.
-// See https://www.rfc-editor.org/rfc/rfc6455.html#section-1.3
-const uid = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
-
-/** @type {PropertyDescriptor} */
-const staticPropertyDescriptors = {
- enumerable: true,
- writable: false,
- configurable: false
+function isArrayBuffer(body) {
+ return body && typeof body.byteLength === "number";
}
-
-const states = {
- CONNECTING: 0,
- OPEN: 1,
- CLOSING: 2,
- CLOSED: 3
+class ReportTransform extends external_node_stream_.Transform {
+ loadedBytes = 0;
+ progressCallback;
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
+ _transform(chunk, _encoding, callback) {
+ this.push(chunk);
+ this.loadedBytes += chunk.length;
+ try {
+ this.progressCallback({ loadedBytes: this.loadedBytes });
+ callback();
+ }
+ catch (e) {
+ callback(e);
+ }
+ }
+ constructor(progressCallback) {
+ super();
+ this.progressCallback = progressCallback;
+ }
}
-
-const sentCloseFrameState = {
- NOT_SENT: 0,
- PROCESSING: 1,
- SENT: 2
+/**
+ * A HttpClient implementation that uses Node's "https" module to send HTTPS requests.
+ * @internal
+ */
+class NodeHttpClient {
+ cachedHttpAgent;
+ cachedHttpsAgents = new WeakMap();
+ /**
+ * Makes a request over an underlying transport layer and returns the response.
+ * @param request - The request to be made.
+ */
+ async sendRequest(request) {
+ const abortController = new AbortController();
+ let abortListener;
+ if (request.abortSignal) {
+ if (request.abortSignal.aborted) {
+ throw new AbortError("The operation was aborted. Request has already been canceled.");
+ }
+ abortListener = (event) => {
+ if (event.type === "abort") {
+ abortController.abort();
+ }
+ };
+ request.abortSignal.addEventListener("abort", abortListener);
+ }
+ let timeoutId;
+ if (request.timeout > 0) {
+ timeoutId = setTimeout(() => {
+ const sanitizer = new Sanitizer();
+ log_logger.info(`request to '${sanitizer.sanitizeUrl(request.url)}' timed out. canceling...`);
+ abortController.abort();
+ }, request.timeout);
+ }
+ const acceptEncoding = request.headers.get("Accept-Encoding");
+ const shouldDecompress = acceptEncoding?.includes("gzip") || acceptEncoding?.includes("deflate");
+ let body = typeof request.body === "function" ? request.body() : request.body;
+ if (body && !request.headers.has("Content-Length")) {
+ const bodyLength = getBodyLength(body);
+ if (bodyLength !== null) {
+ request.headers.set("Content-Length", bodyLength);
+ }
+ }
+ let responseStream;
+ try {
+ if (body && request.onUploadProgress) {
+ const onUploadProgress = request.onUploadProgress;
+ const uploadReportStream = new ReportTransform(onUploadProgress);
+ uploadReportStream.on("error", (e) => {
+ log_logger.error("Error in upload progress", e);
+ });
+ if (nodeHttpClient_isReadableStream(body)) {
+ body.pipe(uploadReportStream);
+ }
+ else {
+ uploadReportStream.end(body);
+ }
+ body = uploadReportStream;
+ }
+ const res = await this.makeRequest(request, abortController, body);
+ if (timeoutId !== undefined) {
+ clearTimeout(timeoutId);
+ }
+ const headers = getResponseHeaders(res);
+ const status = res.statusCode ?? 0;
+ const response = {
+ status,
+ headers,
+ request,
+ };
+ // Responses to HEAD must not have a body.
+ // If they do return a body, that body must be ignored.
+ if (request.method === "HEAD") {
+ // call resume() and not destroy() to avoid closing the socket
+ // and losing keep alive
+ res.resume();
+ return response;
+ }
+ responseStream = shouldDecompress ? getDecodedResponseStream(res, headers) : res;
+ const onDownloadProgress = request.onDownloadProgress;
+ if (onDownloadProgress) {
+ const downloadReportStream = new ReportTransform(onDownloadProgress);
+ downloadReportStream.on("error", (e) => {
+ log_logger.error("Error in download progress", e);
+ });
+ responseStream.pipe(downloadReportStream);
+ responseStream = downloadReportStream;
+ }
+ if (
+ // Value of POSITIVE_INFINITY in streamResponseStatusCodes is considered as any status code
+ request.streamResponseStatusCodes?.has(Number.POSITIVE_INFINITY) ||
+ request.streamResponseStatusCodes?.has(response.status)) {
+ response.readableStreamBody = responseStream;
+ }
+ else {
+ response.bodyAsText = await streamToText(responseStream);
+ }
+ return response;
+ }
+ finally {
+ // clean up event listener
+ if (request.abortSignal && abortListener) {
+ let uploadStreamDone = Promise.resolve();
+ if (nodeHttpClient_isReadableStream(body)) {
+ uploadStreamDone = isStreamComplete(body);
+ }
+ let downloadStreamDone = Promise.resolve();
+ if (nodeHttpClient_isReadableStream(responseStream)) {
+ downloadStreamDone = isStreamComplete(responseStream);
+ }
+ Promise.all([uploadStreamDone, downloadStreamDone])
+ .then(() => {
+ // eslint-disable-next-line promise/always-return
+ if (abortListener) {
+ request.abortSignal?.removeEventListener("abort", abortListener);
+ }
+ })
+ .catch((e) => {
+ log_logger.warning("Error when cleaning up abortListener on httpRequest", e);
+ });
+ }
+ }
+ }
+ makeRequest(request, abortController, body) {
+ const url = new URL(request.url);
+ const isInsecure = url.protocol !== "https:";
+ if (isInsecure && !request.allowInsecureConnection) {
+ throw new Error(`Cannot connect to ${request.url} while allowInsecureConnection is false.`);
+ }
+ const agent = request.agent ?? this.getOrCreateAgent(request, isInsecure);
+ const options = {
+ agent,
+ hostname: url.hostname,
+ path: `${url.pathname}${url.search}`,
+ port: url.port,
+ method: request.method,
+ headers: request.headers.toJSON({ preserveCase: true }),
+ ...request.requestOverrides,
+ };
+ return new Promise((resolve, reject) => {
+ const req = isInsecure ? external_node_http_.request(options, resolve) : external_node_https_namespaceObject.request(options, resolve);
+ req.once("error", (err) => {
+ reject(new restError_RestError(err.message, { code: err.code ?? restError_RestError.REQUEST_SEND_ERROR, request }));
+ });
+ abortController.signal.addEventListener("abort", () => {
+ const abortError = new AbortError("The operation was aborted. Rejecting from abort signal callback while making request.");
+ req.destroy(abortError);
+ reject(abortError);
+ });
+ if (body && nodeHttpClient_isReadableStream(body)) {
+ body.pipe(req);
+ }
+ else if (body) {
+ if (typeof body === "string" || Buffer.isBuffer(body)) {
+ req.end(body);
+ }
+ else if (isArrayBuffer(body)) {
+ req.end(ArrayBuffer.isView(body) ? Buffer.from(body.buffer) : Buffer.from(body));
+ }
+ else {
+ log_logger.error("Unrecognized body type", body);
+ reject(new restError_RestError("Unrecognized body type"));
+ }
+ }
+ else {
+ // streams don't like "undefined" being passed as data
+ req.end();
+ }
+ });
+ }
+ getOrCreateAgent(request, isInsecure) {
+ const disableKeepAlive = request.disableKeepAlive;
+ // Handle Insecure requests first
+ if (isInsecure) {
+ if (disableKeepAlive) {
+ // keepAlive:false is the default so we don't need a custom Agent
+ return external_node_http_.globalAgent;
+ }
+ if (!this.cachedHttpAgent) {
+ // If there is no cached agent create a new one and cache it.
+ this.cachedHttpAgent = new external_node_http_.Agent({ keepAlive: true });
+ }
+ return this.cachedHttpAgent;
+ }
+ else {
+ if (disableKeepAlive && !request.tlsSettings) {
+ // When there are no tlsSettings and keepAlive is false
+ // we don't need a custom agent
+ return external_node_https_namespaceObject.globalAgent;
+ }
+ // We use the tlsSettings to index cached clients
+ const tlsSettings = request.tlsSettings ?? DEFAULT_TLS_SETTINGS;
+ // Get the cached agent or create a new one with the
+ // provided values for keepAlive and tlsSettings
+ let agent = this.cachedHttpsAgents.get(tlsSettings);
+ if (agent && agent.options.keepAlive === !disableKeepAlive) {
+ return agent;
+ }
+ log_logger.info("No cached TLS Agent exist, creating a new Agent");
+ agent = new external_node_https_namespaceObject.Agent({
+ // keepAlive is true if disableKeepAlive is false.
+ keepAlive: !disableKeepAlive,
+ // Since we are spreading, if no tslSettings were provided, nothing is added to the agent options.
+ ...tlsSettings,
+ });
+ this.cachedHttpsAgents.set(tlsSettings, agent);
+ return agent;
+ }
+ }
}
-
-const opcodes = {
- CONTINUATION: 0x0,
- TEXT: 0x1,
- BINARY: 0x2,
- CLOSE: 0x8,
- PING: 0x9,
- PONG: 0xA
+function getResponseHeaders(res) {
+ const headers = httpHeaders_createHttpHeaders();
+ for (const header of Object.keys(res.headers)) {
+ const value = res.headers[header];
+ if (Array.isArray(value)) {
+ if (value.length > 0) {
+ headers.set(header, value[0]);
+ }
+ }
+ else if (value) {
+ headers.set(header, value);
+ }
+ }
+ return headers;
}
-
-const maxUnsigned16Bit = 2 ** 16 - 1 // 65535
-
-const parserStates = {
- INFO: 0,
- PAYLOADLENGTH_16: 2,
- PAYLOADLENGTH_64: 3,
- READ_DATA: 4
+function getDecodedResponseStream(stream, headers) {
+ const contentEncoding = headers.get("Content-Encoding");
+ if (contentEncoding === "gzip") {
+ const unzip = external_node_zlib_.createGunzip();
+ stream.pipe(unzip);
+ return unzip;
+ }
+ else if (contentEncoding === "deflate") {
+ const inflate = external_node_zlib_.createInflate();
+ stream.pipe(inflate);
+ return inflate;
+ }
+ return stream;
}
-
-const emptyBuffer = Buffer.allocUnsafe(0)
-
-const sendHints = {
- string: 1,
- typedArray: 2,
- arrayBuffer: 3,
- blob: 4
+function streamToText(stream) {
+ return new Promise((resolve, reject) => {
+ const buffer = [];
+ stream.on("data", (chunk) => {
+ if (Buffer.isBuffer(chunk)) {
+ buffer.push(chunk);
+ }
+ else {
+ buffer.push(Buffer.from(chunk));
+ }
+ });
+ stream.on("end", () => {
+ resolve(Buffer.concat(buffer).toString("utf8"));
+ });
+ stream.on("error", (e) => {
+ if (e && e?.name === "AbortError") {
+ reject(e);
+ }
+ else {
+ reject(new restError_RestError(`Error reading response as text: ${e.message}`, {
+ code: restError_RestError.PARSE_ERROR,
+ }));
+ }
+ });
+ });
}
-
-module.exports = {
- uid,
- sentCloseFrameState,
- staticPropertyDescriptors,
- states,
- opcodes,
- maxUnsigned16Bit,
- parserStates,
- emptyBuffer,
- sendHints
+/** @internal */
+function getBodyLength(body) {
+ if (!body) {
+ return 0;
+ }
+ else if (Buffer.isBuffer(body)) {
+ return body.length;
+ }
+ else if (nodeHttpClient_isReadableStream(body)) {
+ return null;
+ }
+ else if (isArrayBuffer(body)) {
+ return body.byteLength;
+ }
+ else if (typeof body === "string") {
+ return Buffer.from(body).length;
+ }
+ else {
+ return null;
+ }
}
+/**
+ * Create a new HttpClient instance for the NodeJS environment.
+ * @internal
+ */
+function createNodeHttpClient() {
+ return new NodeHttpClient();
+}
+//# sourceMappingURL=nodeHttpClient.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/defaultHttpClient.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+/**
+ * Create the correct HttpClient for the current environment.
+ */
+function defaultHttpClient_createDefaultHttpClient() {
+ return createNodeHttpClient();
+}
+//# sourceMappingURL=defaultHttpClient.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/policies/logPolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
-/***/ }),
-
-/***/ 44:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const { webidl } = __nccwpck_require__(253)
-const { kEnumerableProperty } = __nccwpck_require__(1544)
-const { kConstruct } = __nccwpck_require__(9411)
-const { MessagePort } = __nccwpck_require__(5919)
/**
- * @see https://html.spec.whatwg.org/multipage/comms.html#messageevent
+ * The programmatic identifier of the logPolicy.
*/
-class MessageEvent extends Event {
- #eventInit
+const logPolicyName = "logPolicy";
+/**
+ * A policy that logs all requests and responses.
+ * @param options - Options to configure logPolicy.
+ */
+function logPolicy_logPolicy(options = {}) {
+ const logger = options.logger ?? log_logger.info;
+ const sanitizer = new Sanitizer({
+ additionalAllowedHeaderNames: options.additionalAllowedHeaderNames,
+ additionalAllowedQueryParameters: options.additionalAllowedQueryParameters,
+ });
+ return {
+ name: logPolicyName,
+ async sendRequest(request, next) {
+ if (!logger.enabled) {
+ return next(request);
+ }
+ logger(`Request: ${sanitizer.sanitize(request)}`);
+ const response = await next(request);
+ logger(`Response status code: ${response.status}`);
+ logger(`Headers: ${sanitizer.sanitize(response.headers)}`);
+ return response;
+ },
+ };
+}
+//# sourceMappingURL=logPolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/policies/redirectPolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- constructor (type, eventInitDict = {}) {
- if (type === kConstruct) {
- super(arguments[1], arguments[2])
- webidl.util.markAsUncloneable(this)
- return
+/**
+ * The programmatic identifier of the redirectPolicy.
+ */
+const redirectPolicyName = "redirectPolicy";
+/**
+ * Methods that are allowed to follow redirects 301 and 302
+ */
+const allowedRedirect = ["GET", "HEAD"];
+/**
+ * A policy to follow Location headers from the server in order
+ * to support server-side redirection.
+ * In the browser, this policy is not used.
+ * @param options - Options to control policy behavior.
+ */
+function redirectPolicy_redirectPolicy(options = {}) {
+ const { maxRetries = 20, allowCrossOriginRedirects = false } = options;
+ return {
+ name: redirectPolicyName,
+ async sendRequest(request, next) {
+ const response = await next(request);
+ return handleRedirect(next, response, maxRetries, allowCrossOriginRedirects);
+ },
+ };
+}
+async function handleRedirect(next, response, maxRetries, allowCrossOriginRedirects, currentRetries = 0) {
+ const { request, status, headers } = response;
+ const locationHeader = headers.get("location");
+ if (locationHeader &&
+ (status === 300 ||
+ (status === 301 && allowedRedirect.includes(request.method)) ||
+ (status === 302 && allowedRedirect.includes(request.method)) ||
+ (status === 303 && request.method === "POST") ||
+ status === 307) &&
+ currentRetries < maxRetries) {
+ const url = new URL(locationHeader, request.url);
+ // Only follow redirects to the same origin by default.
+ if (!allowCrossOriginRedirects) {
+ const originalUrl = new URL(request.url);
+ if (url.origin !== originalUrl.origin) {
+ log_logger.verbose(`Skipping cross-origin redirect from ${originalUrl.origin} to ${url.origin}.`);
+ return response;
+ }
+ }
+ request.url = url.toString();
+ // POST request with Status code 303 should be converted into a
+ // redirected GET request if the redirect url is present in the location header
+ if (status === 303) {
+ request.method = "GET";
+ request.headers.delete("Content-Length");
+ delete request.body;
+ }
+ request.headers.delete("Authorization");
+ const res = await next(request);
+ return handleRedirect(next, res, maxRetries, allowCrossOriginRedirects, currentRetries + 1);
}
+ return response;
+}
+//# sourceMappingURL=redirectPolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/util/userAgentPlatform.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- const prefix = 'MessageEvent constructor'
- webidl.argumentLengthCheck(arguments, 1, prefix)
-
- type = webidl.converters.DOMString(type, prefix, 'type')
- eventInitDict = webidl.converters.MessageEventInit(eventInitDict, prefix, 'eventInitDict')
-
- super(type, eventInitDict)
-
- this.#eventInit = eventInitDict
- webidl.util.markAsUncloneable(this)
- }
- get data () {
- webidl.brandCheck(this, MessageEvent)
-
- return this.#eventInit.data
- }
-
- get origin () {
- webidl.brandCheck(this, MessageEvent)
-
- return this.#eventInit.origin
- }
-
- get lastEventId () {
- webidl.brandCheck(this, MessageEvent)
-
- return this.#eventInit.lastEventId
- }
-
- get source () {
- webidl.brandCheck(this, MessageEvent)
-
- return this.#eventInit.source
- }
-
- get ports () {
- webidl.brandCheck(this, MessageEvent)
-
- if (!Object.isFrozen(this.#eventInit.ports)) {
- Object.freeze(this.#eventInit.ports)
+/**
+ * @internal
+ */
+function getHeaderName() {
+ return "User-Agent";
+}
+/**
+ * @internal
+ */
+async function userAgentPlatform_setPlatformSpecificData(map) {
+ if (process && process.versions) {
+ const osInfo = `${os.type()} ${os.release()}; ${os.arch()}`;
+ if (process.versions.bun) {
+ map.set("Bun", `${process.versions.bun} (${osInfo})`);
+ }
+ else if (process.versions.deno) {
+ map.set("Deno", `${process.versions.deno} (${osInfo})`);
+ }
+ else if (process.versions.node) {
+ map.set("Node", `${process.versions.node} (${osInfo})`);
+ }
}
+}
+//# sourceMappingURL=userAgentPlatform.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/util/userAgent.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- return this.#eventInit.ports
- }
-
- initMessageEvent (
- type,
- bubbles = false,
- cancelable = false,
- data = null,
- origin = '',
- lastEventId = '',
- source = null,
- ports = []
- ) {
- webidl.brandCheck(this, MessageEvent)
-
- webidl.argumentLengthCheck(arguments, 1, 'MessageEvent.initMessageEvent')
-
- return new MessageEvent(type, {
- bubbles, cancelable, data, origin, lastEventId, source, ports
- })
- }
- static createFastMessageEvent (type, init) {
- const messageEvent = new MessageEvent(kConstruct, type, init)
- messageEvent.#eventInit = init
- messageEvent.#eventInit.data ??= null
- messageEvent.#eventInit.origin ??= ''
- messageEvent.#eventInit.lastEventId ??= ''
- messageEvent.#eventInit.source ??= null
- messageEvent.#eventInit.ports ??= []
- return messageEvent
- }
+function getUserAgentString(telemetryInfo) {
+ const parts = [];
+ for (const [key, value] of telemetryInfo) {
+ const token = value ? `${key}/${value}` : key;
+ parts.push(token);
+ }
+ return parts.join(" ");
}
+/**
+ * @internal
+ */
+function getUserAgentHeaderName() {
+ return getHeaderName();
+}
+/**
+ * @internal
+ */
+async function userAgent_getUserAgentValue(prefix) {
+ const runtimeInfo = new Map();
+ runtimeInfo.set("ts-http-runtime", SDK_VERSION);
+ await setPlatformSpecificData(runtimeInfo);
+ const defaultAgent = getUserAgentString(runtimeInfo);
+ const userAgentValue = prefix ? `${prefix} ${defaultAgent}` : defaultAgent;
+ return userAgentValue;
+}
+//# sourceMappingURL=userAgent.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/policies/userAgentPolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
-const { createFastMessageEvent } = MessageEvent
-delete MessageEvent.createFastMessageEvent
-
+const UserAgentHeaderName = getUserAgentHeaderName();
/**
- * @see https://websockets.spec.whatwg.org/#the-closeevent-interface
+ * The programmatic identifier of the userAgentPolicy.
*/
-class CloseEvent extends Event {
- #eventInit
+const userAgentPolicyName = "userAgentPolicy";
+/**
+ * A policy that sets the User-Agent header (or equivalent) to reflect
+ * the library version.
+ * @param options - Options to customize the user agent value.
+ */
+function userAgentPolicy_userAgentPolicy(options = {}) {
+ const userAgentValue = getUserAgentValue(options.userAgentPrefix);
+ return {
+ name: userAgentPolicyName,
+ async sendRequest(request, next) {
+ if (!request.headers.has(UserAgentHeaderName)) {
+ request.headers.set(UserAgentHeaderName, await userAgentValue);
+ }
+ return next(request);
+ },
+ };
+}
+//# sourceMappingURL=userAgentPolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/util/random.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+/**
+ * Returns a random integer value between a lower and upper bound,
+ * inclusive of both bounds.
+ * Note that this uses Math.random and isn't secure. If you need to use
+ * this for any kind of security purpose, find a better source of random.
+ * @param min - The smallest integer value allowed.
+ * @param max - The largest integer value allowed.
+ */
+function random_getRandomIntegerInclusive(min, max) {
+ // Make sure inputs are integers.
+ min = Math.ceil(min);
+ max = Math.floor(max);
+ // Pick a random offset from zero to the size of the range.
+ // Since Math.random() can never return 1, we have to make the range one larger
+ // in order to be inclusive of the maximum value after we take the floor.
+ const offset = Math.floor(Math.random() * (max - min + 1));
+ return offset + min;
+}
+//# sourceMappingURL=random.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/util/delay.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- constructor (type, eventInitDict = {}) {
- const prefix = 'CloseEvent constructor'
- webidl.argumentLengthCheck(arguments, 1, prefix)
+/**
+ * Calculates the delay interval for retry attempts using exponential delay with jitter.
+ * @param retryAttempt - The current retry attempt number.
+ * @param config - The exponential retry configuration.
+ * @returns An object containing the calculated retry delay.
+ */
+function calculateRetryDelay(retryAttempt, config) {
+ // Exponentially increase the delay each time
+ const exponentialDelay = config.retryDelayInMs * Math.pow(2, retryAttempt);
+ // Don't let the delay exceed the maximum
+ const clampedDelay = Math.min(config.maxRetryDelayInMs, exponentialDelay);
+ // Allow the final value to have some "jitter" (within 50% of the delay size) so
+ // that retries across multiple clients don't occur simultaneously.
+ const retryAfterInMs = clampedDelay / 2 + random_getRandomIntegerInclusive(0, clampedDelay / 2);
+ return { retryAfterInMs };
+}
+//# sourceMappingURL=delay.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/util/helpers.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- type = webidl.converters.DOMString(type, prefix, 'type')
- eventInitDict = webidl.converters.CloseEventInit(eventInitDict)
+const StandardAbortMessage = "The operation was aborted.";
+/**
+ * A wrapper for setTimeout that resolves a promise after delayInMs milliseconds.
+ * @param delayInMs - The number of milliseconds to be delayed.
+ * @param value - The value to be resolved with after a timeout of t milliseconds.
+ * @param options - The options for delay - currently abort options
+ * - abortSignal - The abortSignal associated with containing operation.
+ * - abortErrorMsg - The abort error message associated with containing operation.
+ * @returns Resolved promise
+ */
+function delay(delayInMs, value, options) {
+ return new Promise((resolve, reject) => {
+ let timer = undefined;
+ let onAborted = undefined;
+ const rejectOnAbort = () => {
+ return reject(new AbortError(options?.abortErrorMsg ? options?.abortErrorMsg : StandardAbortMessage));
+ };
+ const removeListeners = () => {
+ if (options?.abortSignal && onAborted) {
+ options.abortSignal.removeEventListener("abort", onAborted);
+ }
+ };
+ onAborted = () => {
+ if (timer) {
+ clearTimeout(timer);
+ }
+ removeListeners();
+ return rejectOnAbort();
+ };
+ if (options?.abortSignal && options.abortSignal.aborted) {
+ return rejectOnAbort();
+ }
+ timer = setTimeout(() => {
+ removeListeners();
+ resolve(value);
+ }, delayInMs);
+ if (options?.abortSignal) {
+ options.abortSignal.addEventListener("abort", onAborted);
+ }
+ });
+}
+/**
+ * @internal
+ * @returns the parsed value or undefined if the parsed value is invalid.
+ */
+function parseHeaderValueAsNumber(response, headerName) {
+ const value = response.headers.get(headerName);
+ if (!value)
+ return;
+ const valueAsNum = Number(value);
+ if (Number.isNaN(valueAsNum))
+ return;
+ return valueAsNum;
+}
+//# sourceMappingURL=helpers.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/retryStrategies/throttlingRetryStrategy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- super(type, eventInitDict)
+/**
+ * The header that comes back from services representing
+ * the amount of time (minimum) to wait to retry (in seconds or timestamp after which we can retry).
+ */
+const RetryAfterHeader = "Retry-After";
+/**
+ * The headers that come back from services representing
+ * the amount of time (minimum) to wait to retry.
+ *
+ * "retry-after-ms", "x-ms-retry-after-ms" : milliseconds
+ * "Retry-After" : seconds or timestamp
+ */
+const AllRetryAfterHeaders = ["retry-after-ms", "x-ms-retry-after-ms", RetryAfterHeader];
+/**
+ * A response is a throttling retry response if it has a throttling status code (429 or 503),
+ * as long as one of the [ "Retry-After" or "retry-after-ms" or "x-ms-retry-after-ms" ] headers has a valid value.
+ *
+ * Returns the `retryAfterInMs` value if the response is a throttling retry response.
+ * If not throttling retry response, returns `undefined`.
+ *
+ * @internal
+ */
+function getRetryAfterInMs(response) {
+ if (!(response && [429, 503].includes(response.status)))
+ return undefined;
+ try {
+ // Headers: "retry-after-ms", "x-ms-retry-after-ms", "Retry-After"
+ for (const header of AllRetryAfterHeaders) {
+ const retryAfterValue = parseHeaderValueAsNumber(response, header);
+ if (retryAfterValue === 0 || retryAfterValue) {
+ // "Retry-After" header ==> seconds
+ // "retry-after-ms", "x-ms-retry-after-ms" headers ==> milli-seconds
+ const multiplyingFactor = header === RetryAfterHeader ? 1000 : 1;
+ return retryAfterValue * multiplyingFactor; // in milli-seconds
+ }
+ }
+ // RetryAfterHeader ("Retry-After") has a special case where it might be formatted as a date instead of a number of seconds
+ const retryAfterHeader = response.headers.get(RetryAfterHeader);
+ if (!retryAfterHeader)
+ return;
+ const date = Date.parse(retryAfterHeader);
+ const diff = date - Date.now();
+ // negative diff would mean a date in the past, so retry asap with 0 milliseconds
+ return Number.isFinite(diff) ? Math.max(0, diff) : undefined;
+ }
+ catch {
+ return undefined;
+ }
+}
+/**
+ * A response is a retry response if it has a throttling status code (429 or 503),
+ * as long as one of the [ "Retry-After" or "retry-after-ms" or "x-ms-retry-after-ms" ] headers has a valid value.
+ */
+function isThrottlingRetryResponse(response) {
+ return Number.isFinite(getRetryAfterInMs(response));
+}
+function throttlingRetryStrategy_throttlingRetryStrategy() {
+ return {
+ name: "throttlingRetryStrategy",
+ retry({ response }) {
+ const retryAfterInMs = getRetryAfterInMs(response);
+ if (!Number.isFinite(retryAfterInMs)) {
+ return { skipStrategy: true };
+ }
+ return {
+ retryAfterInMs,
+ };
+ },
+ };
+}
+//# sourceMappingURL=throttlingRetryStrategy.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/retryStrategies/exponentialRetryStrategy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- this.#eventInit = eventInitDict
- webidl.util.markAsUncloneable(this)
- }
- get wasClean () {
- webidl.brandCheck(this, CloseEvent)
+// intervals are in milliseconds
+const DEFAULT_CLIENT_RETRY_INTERVAL = 1000;
+const DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 64;
+/**
+ * A retry strategy that retries with an exponentially increasing delay in these two cases:
+ * - When there are errors in the underlying transport layer (e.g. DNS lookup failures).
+ * - Or otherwise if the outgoing request fails (408, greater or equal than 500, except for 501 and 505).
+ */
+function exponentialRetryStrategy_exponentialRetryStrategy(options = {}) {
+ const retryInterval = options.retryDelayInMs ?? DEFAULT_CLIENT_RETRY_INTERVAL;
+ const maxRetryInterval = options.maxRetryDelayInMs ?? DEFAULT_CLIENT_MAX_RETRY_INTERVAL;
+ return {
+ name: "exponentialRetryStrategy",
+ retry({ retryCount, response, responseError }) {
+ const matchedSystemError = isSystemError(responseError);
+ const ignoreSystemErrors = matchedSystemError && options.ignoreSystemErrors;
+ const isExponential = isExponentialRetryResponse(response);
+ const ignoreExponentialResponse = isExponential && options.ignoreHttpStatusCodes;
+ const unknownResponse = response && (isThrottlingRetryResponse(response) || !isExponential);
+ if (unknownResponse || ignoreExponentialResponse || ignoreSystemErrors) {
+ return { skipStrategy: true };
+ }
+ if (responseError && !matchedSystemError && !isExponential) {
+ return { errorToThrow: responseError };
+ }
+ return calculateRetryDelay(retryCount, {
+ retryDelayInMs: retryInterval,
+ maxRetryDelayInMs: maxRetryInterval,
+ });
+ },
+ };
+}
+/**
+ * A response is a retry response if it has status codes:
+ * - 408, or
+ * - Greater or equal than 500, except for 501 and 505.
+ */
+function isExponentialRetryResponse(response) {
+ return Boolean(response &&
+ response.status !== undefined &&
+ (response.status >= 500 || response.status === 408) &&
+ response.status !== 501 &&
+ response.status !== 505);
+}
+/**
+ * Determines whether an error from a pipeline response was triggered in the network layer.
+ */
+function isSystemError(err) {
+ if (!err) {
+ return false;
+ }
+ return (err.code === "ETIMEDOUT" ||
+ err.code === "ESOCKETTIMEDOUT" ||
+ err.code === "ECONNREFUSED" ||
+ err.code === "ECONNRESET" ||
+ err.code === "ENOENT" ||
+ err.code === "ENOTFOUND");
+}
+//# sourceMappingURL=exponentialRetryStrategy.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/constants.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+const constants_SDK_VERSION = "0.3.5";
+const constants_DEFAULT_RETRY_POLICY_COUNT = 3;
+//# sourceMappingURL=constants.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/policies/retryPolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- return this.#eventInit.wasClean
- }
- get code () {
- webidl.brandCheck(this, CloseEvent)
- return this.#eventInit.code
- }
- get reason () {
- webidl.brandCheck(this, CloseEvent)
- return this.#eventInit.reason
- }
+const retryPolicyLogger = createClientLogger("ts-http-runtime retryPolicy");
+/**
+ * The programmatic identifier of the retryPolicy.
+ */
+const retryPolicyName = "retryPolicy";
+/**
+ * retryPolicy is a generic policy to enable retrying requests when certain conditions are met
+ */
+function retryPolicy_retryPolicy(strategies, options = { maxRetries: constants_DEFAULT_RETRY_POLICY_COUNT }) {
+ const logger = options.logger || retryPolicyLogger;
+ return {
+ name: retryPolicyName,
+ async sendRequest(request, next) {
+ let response;
+ let responseError;
+ let retryCount = -1;
+ retryRequest: while (true) {
+ retryCount += 1;
+ response = undefined;
+ responseError = undefined;
+ try {
+ logger.info(`Retry ${retryCount}: Attempting to send request`, request.requestId);
+ response = await next(request);
+ logger.info(`Retry ${retryCount}: Received a response from request`, request.requestId);
+ }
+ catch (e) {
+ logger.error(`Retry ${retryCount}: Received an error from request`, request.requestId);
+ // RestErrors are valid targets for the retry strategies.
+ // If none of the retry strategies can work with them, they will be thrown later in this policy.
+ // If the received error is not a RestError, it is immediately thrown.
+ if (!restError_isRestError(e)) {
+ throw e;
+ }
+ responseError = e;
+ response = e.response;
+ }
+ if (request.abortSignal?.aborted) {
+ logger.error(`Retry ${retryCount}: Request aborted.`);
+ const abortError = new AbortError();
+ throw abortError;
+ }
+ if (retryCount >= (options.maxRetries ?? constants_DEFAULT_RETRY_POLICY_COUNT)) {
+ logger.info(`Retry ${retryCount}: Maximum retries reached. Returning the last received response, or throwing the last received error.`);
+ if (responseError) {
+ throw responseError;
+ }
+ else if (response) {
+ return response;
+ }
+ else {
+ throw new Error("Maximum retries reached with no response or error to throw");
+ }
+ }
+ logger.info(`Retry ${retryCount}: Processing ${strategies.length} retry strategies.`);
+ strategiesLoop: for (const strategy of strategies) {
+ const strategyLogger = strategy.logger || logger;
+ strategyLogger.info(`Retry ${retryCount}: Processing retry strategy ${strategy.name}.`);
+ const modifiers = strategy.retry({
+ retryCount,
+ response,
+ responseError,
+ });
+ if (modifiers.skipStrategy) {
+ strategyLogger.info(`Retry ${retryCount}: Skipped.`);
+ continue strategiesLoop;
+ }
+ const { errorToThrow, retryAfterInMs, redirectTo } = modifiers;
+ if (errorToThrow) {
+ strategyLogger.error(`Retry ${retryCount}: Retry strategy ${strategy.name} throws error:`, errorToThrow);
+ throw errorToThrow;
+ }
+ if (retryAfterInMs || retryAfterInMs === 0) {
+ strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} retries after ${retryAfterInMs}`);
+ await delay(retryAfterInMs, undefined, { abortSignal: request.abortSignal });
+ continue retryRequest;
+ }
+ if (redirectTo) {
+ strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} redirects to ${redirectTo}`);
+ request.url = redirectTo;
+ continue retryRequest;
+ }
+ }
+ if (responseError) {
+ logger.info(`None of the retry strategies could work with the received error. Throwing it.`);
+ throw responseError;
+ }
+ if (response) {
+ logger.info(`None of the retry strategies could work with the received response. Returning it.`);
+ return response;
+ }
+ // If all the retries skip and there's no response,
+ // we're still in the retry loop, so a new request will be sent
+ // until `maxRetries` is reached.
+ }
+ },
+ };
}
+//# sourceMappingURL=retryPolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/policies/defaultRetryPolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
-// https://html.spec.whatwg.org/multipage/webappapis.html#the-errorevent-interface
-class ErrorEvent extends Event {
- #eventInit
-
- constructor (type, eventInitDict) {
- const prefix = 'ErrorEvent constructor'
- webidl.argumentLengthCheck(arguments, 1, prefix)
-
- super(type, eventInitDict)
- webidl.util.markAsUncloneable(this)
- type = webidl.converters.DOMString(type, prefix, 'type')
- eventInitDict = webidl.converters.ErrorEventInit(eventInitDict ?? {})
- this.#eventInit = eventInitDict
- }
- get message () {
- webidl.brandCheck(this, ErrorEvent)
-
- return this.#eventInit.message
- }
-
- get filename () {
- webidl.brandCheck(this, ErrorEvent)
-
- return this.#eventInit.filename
- }
-
- get lineno () {
- webidl.brandCheck(this, ErrorEvent)
-
- return this.#eventInit.lineno
- }
-
- get colno () {
- webidl.brandCheck(this, ErrorEvent)
-
- return this.#eventInit.colno
- }
-
- get error () {
- webidl.brandCheck(this, ErrorEvent)
-
- return this.#eventInit.error
- }
-}
-
-Object.defineProperties(MessageEvent.prototype, {
- [Symbol.toStringTag]: {
- value: 'MessageEvent',
- configurable: true
- },
- data: kEnumerableProperty,
- origin: kEnumerableProperty,
- lastEventId: kEnumerableProperty,
- source: kEnumerableProperty,
- ports: kEnumerableProperty,
- initMessageEvent: kEnumerableProperty
-})
-
-Object.defineProperties(CloseEvent.prototype, {
- [Symbol.toStringTag]: {
- value: 'CloseEvent',
- configurable: true
- },
- reason: kEnumerableProperty,
- code: kEnumerableProperty,
- wasClean: kEnumerableProperty
-})
-
-Object.defineProperties(ErrorEvent.prototype, {
- [Symbol.toStringTag]: {
- value: 'ErrorEvent',
- configurable: true
- },
- message: kEnumerableProperty,
- filename: kEnumerableProperty,
- lineno: kEnumerableProperty,
- colno: kEnumerableProperty,
- error: kEnumerableProperty
-})
-
-webidl.converters.MessagePort = webidl.interfaceConverter(MessagePort)
-
-webidl.converters['sequence'] = webidl.sequenceConverter(
- webidl.converters.MessagePort
-)
-
-const eventInit = [
- {
- key: 'bubbles',
- converter: webidl.converters.boolean,
- defaultValue: () => false
- },
- {
- key: 'cancelable',
- converter: webidl.converters.boolean,
- defaultValue: () => false
- },
- {
- key: 'composed',
- converter: webidl.converters.boolean,
- defaultValue: () => false
- }
-]
-
-webidl.converters.MessageEventInit = webidl.dictionaryConverter([
- ...eventInit,
- {
- key: 'data',
- converter: webidl.converters.any,
- defaultValue: () => null
- },
- {
- key: 'origin',
- converter: webidl.converters.USVString,
- defaultValue: () => ''
- },
- {
- key: 'lastEventId',
- converter: webidl.converters.DOMString,
- defaultValue: () => ''
- },
- {
- key: 'source',
- // Node doesn't implement WindowProxy or ServiceWorker, so the only
- // valid value for source is a MessagePort.
- converter: webidl.nullableConverter(webidl.converters.MessagePort),
- defaultValue: () => null
- },
- {
- key: 'ports',
- converter: webidl.converters['sequence'],
- defaultValue: () => new Array(0)
- }
-])
-
-webidl.converters.CloseEventInit = webidl.dictionaryConverter([
- ...eventInit,
- {
- key: 'wasClean',
- converter: webidl.converters.boolean,
- defaultValue: () => false
- },
- {
- key: 'code',
- converter: webidl.converters['unsigned short'],
- defaultValue: () => 0
- },
- {
- key: 'reason',
- converter: webidl.converters.USVString,
- defaultValue: () => ''
- }
-])
-
-webidl.converters.ErrorEventInit = webidl.dictionaryConverter([
- ...eventInit,
- {
- key: 'message',
- converter: webidl.converters.DOMString,
- defaultValue: () => ''
- },
- {
- key: 'filename',
- converter: webidl.converters.USVString,
- defaultValue: () => ''
- },
- {
- key: 'lineno',
- converter: webidl.converters['unsigned long'],
- defaultValue: () => 0
- },
- {
- key: 'colno',
- converter: webidl.converters['unsigned long'],
- defaultValue: () => 0
- },
- {
- key: 'error',
- converter: webidl.converters.any
- }
-])
-
-module.exports = {
- MessageEvent,
- CloseEvent,
- ErrorEvent,
- createFastMessageEvent
+/**
+ * Name of the {@link defaultRetryPolicy}
+ */
+const defaultRetryPolicyName = "defaultRetryPolicy";
+/**
+ * A policy that retries according to three strategies:
+ * - When the server sends a 429 response with a Retry-After header.
+ * - When there are errors in the underlying transport layer (e.g. DNS lookup failures).
+ * - Or otherwise if the outgoing request fails, it will retry with an exponentially increasing delay.
+ */
+function defaultRetryPolicy_defaultRetryPolicy(options = {}) {
+ return {
+ name: defaultRetryPolicyName,
+ sendRequest: retryPolicy_retryPolicy([throttlingRetryStrategy_throttlingRetryStrategy(), exponentialRetryStrategy_exponentialRetryStrategy(options)], {
+ maxRetries: options.maxRetries ?? constants_DEFAULT_RETRY_POLICY_COUNT,
+ }).sendRequest,
+ };
}
-
-
-/***/ }),
-
-/***/ 9272:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const { maxUnsigned16Bit } = __nccwpck_require__(1816)
-
-const BUFFER_SIZE = 16386
-
-/** @type {import('crypto')} */
-let crypto
-let buffer = null
-let bufIdx = BUFFER_SIZE
-
-try {
- crypto = __nccwpck_require__(7598)
-/* c8 ignore next 3 */
-} catch {
- crypto = {
- // not full compatibility, but minimum.
- randomFillSync: function randomFillSync (buffer, _offset, _size) {
- for (let i = 0; i < buffer.length; ++i) {
- buffer[i] = Math.random() * 255 | 0
- }
- return buffer
- }
- }
+//# sourceMappingURL=defaultRetryPolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/util/bytesEncoding.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+/**
+ * The helper that transforms bytes with specific character encoding into string
+ * @param bytes - the uint8array bytes
+ * @param format - the format we use to encode the byte
+ * @returns a string of the encoded string
+ */
+function bytesEncoding_uint8ArrayToString(bytes, format) {
+ return Buffer.from(bytes).toString(format);
}
-
-function generateMask () {
- if (bufIdx === BUFFER_SIZE) {
- bufIdx = 0
- crypto.randomFillSync((buffer ??= Buffer.allocUnsafe(BUFFER_SIZE)), 0, BUFFER_SIZE)
- }
- return [buffer[bufIdx++], buffer[bufIdx++], buffer[bufIdx++], buffer[bufIdx++]]
+/**
+ * The helper that transforms string to specific character encoded bytes array.
+ * @param value - the string to be converted
+ * @param format - the format we use to decode the value
+ * @returns a uint8array
+ */
+function bytesEncoding_stringToUint8Array(value, format) {
+ return Buffer.from(value, format);
}
+//# sourceMappingURL=bytesEncoding.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/util/checkEnvironment.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+/**
+ * A constant that indicates whether the environment the code is running is a Web Browser.
+ */
+// eslint-disable-next-line @azure/azure-sdk/ts-no-window
+const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined";
+/**
+ * A constant that indicates whether the environment the code is running is a Web Worker.
+ */
+const isWebWorker = typeof self === "object" &&
+ typeof self?.importScripts === "function" &&
+ (self.constructor?.name === "DedicatedWorkerGlobalScope" ||
+ self.constructor?.name === "ServiceWorkerGlobalScope" ||
+ self.constructor?.name === "SharedWorkerGlobalScope");
+/**
+ * A constant that indicates whether the environment the code is running is Deno.
+ */
+const isDeno = typeof Deno !== "undefined" &&
+ typeof Deno.version !== "undefined" &&
+ typeof Deno.version.deno !== "undefined";
+/**
+ * A constant that indicates whether the environment the code is running is Bun.sh.
+ */
+const isBun = typeof Bun !== "undefined" && typeof Bun.version !== "undefined";
+/**
+ * A constant that indicates whether the environment the code is running is a Node.js compatible environment.
+ */
+const checkEnvironment_isNodeLike = typeof globalThis.process !== "undefined" &&
+ Boolean(globalThis.process.version) &&
+ Boolean(globalThis.process.versions?.node);
+/**
+ * A constant that indicates whether the environment the code is running is Node.JS.
+ */
+const isNodeRuntime = checkEnvironment_isNodeLike && !isBun && !isDeno;
+/**
+ * A constant that indicates whether the environment the code is running is in React-Native.
+ */
+// https://github.com/facebook/react-native/blob/main/packages/react-native/Libraries/Core/setUpNavigator.js
+const isReactNative = typeof navigator !== "undefined" && navigator?.product === "ReactNative";
+//# sourceMappingURL=checkEnvironment.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/policies/formDataPolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
-class WebsocketFrameSend {
- /**
- * @param {Buffer|undefined} data
- */
- constructor (data) {
- this.frameData = data
- }
-
- createFrame (opcode) {
- const frameData = this.frameData
- const maskKey = generateMask()
- const bodyLength = frameData?.byteLength ?? 0
-
- /** @type {number} */
- let payloadLength = bodyLength // 0-125
- let offset = 6
-
- if (bodyLength > maxUnsigned16Bit) {
- offset += 8 // payload length is next 8 bytes
- payloadLength = 127
- } else if (bodyLength > 125) {
- offset += 2 // payload length is next 2 bytes
- payloadLength = 126
- }
-
- const buffer = Buffer.allocUnsafe(bodyLength + offset)
-
- // Clear first 2 bytes, everything else is overwritten
- buffer[0] = buffer[1] = 0
- buffer[0] |= 0x80 // FIN
- buffer[0] = (buffer[0] & 0xF0) + opcode // opcode
-
- /*! ws. MIT License. Einar Otto Stangvik */
- buffer[offset - 4] = maskKey[0]
- buffer[offset - 3] = maskKey[1]
- buffer[offset - 2] = maskKey[2]
- buffer[offset - 1] = maskKey[3]
-
- buffer[1] = payloadLength
-
- if (payloadLength === 126) {
- buffer.writeUInt16BE(bodyLength, 2)
- } else if (payloadLength === 127) {
- // Clear extended payload length
- buffer[2] = buffer[3] = 0
- buffer.writeUIntBE(bodyLength, 4, 6)
- }
- buffer[1] |= 0x80 // MASK
- // mask body
- for (let i = 0; i < bodyLength; ++i) {
- buffer[offset + i] = frameData[i] ^ maskKey[i & 3]
+/**
+ * The programmatic identifier of the formDataPolicy.
+ */
+const formDataPolicyName = "formDataPolicy";
+function formDataToFormDataMap(formData) {
+ const formDataMap = {};
+ for (const [key, value] of formData.entries()) {
+ formDataMap[key] ??= [];
+ formDataMap[key].push(value);
}
-
- return buffer
- }
+ return formDataMap;
}
-
-module.exports = {
- WebsocketFrameSend
+/**
+ * A policy that encodes FormData on the request into the body.
+ */
+function formDataPolicy_formDataPolicy() {
+ return {
+ name: formDataPolicyName,
+ async sendRequest(request, next) {
+ if (checkEnvironment_isNodeLike && typeof FormData !== "undefined" && request.body instanceof FormData) {
+ request.formData = formDataToFormDataMap(request.body);
+ request.body = undefined;
+ }
+ if (request.formData) {
+ const contentType = request.headers.get("Content-Type");
+ if (contentType && contentType.indexOf("application/x-www-form-urlencoded") !== -1) {
+ request.body = wwwFormUrlEncode(request.formData);
+ }
+ else {
+ await prepareFormData(request.formData, request);
+ }
+ request.formData = undefined;
+ }
+ return next(request);
+ },
+ };
}
-
-
-/***/ }),
-
-/***/ 2869:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const { createInflateRaw, Z_DEFAULT_WINDOWBITS } = __nccwpck_require__(8522)
-const { isValidClientWindowBits } = __nccwpck_require__(5673)
-
-const tail = Buffer.from([0x00, 0x00, 0xff, 0xff])
-const kBuffer = Symbol('kBuffer')
-const kLength = Symbol('kLength')
-
-class PerMessageDeflate {
- /** @type {import('node:zlib').InflateRaw} */
- #inflate
-
- #options = {}
-
- constructor (extensions) {
- this.#options.serverNoContextTakeover = extensions.has('server_no_context_takeover')
- this.#options.serverMaxWindowBits = extensions.get('server_max_window_bits')
- }
-
- decompress (chunk, fin, callback) {
- // An endpoint uses the following algorithm to decompress a message.
- // 1. Append 4 octets of 0x00 0x00 0xff 0xff to the tail end of the
- // payload of the message.
- // 2. Decompress the resulting data using DEFLATE.
-
- if (!this.#inflate) {
- let windowBits = Z_DEFAULT_WINDOWBITS
-
- if (this.#options.serverMaxWindowBits) { // empty values default to Z_DEFAULT_WINDOWBITS
- if (!isValidClientWindowBits(this.#options.serverMaxWindowBits)) {
- callback(new Error('Invalid server_max_window_bits'))
- return
+function wwwFormUrlEncode(formData) {
+ const urlSearchParams = new URLSearchParams();
+ for (const [key, value] of Object.entries(formData)) {
+ if (Array.isArray(value)) {
+ for (const subValue of value) {
+ urlSearchParams.append(key, subValue.toString());
+ }
+ }
+ else {
+ urlSearchParams.append(key, value.toString());
}
-
- windowBits = Number.parseInt(this.#options.serverMaxWindowBits)
- }
-
- this.#inflate = createInflateRaw({ windowBits })
- this.#inflate[kBuffer] = []
- this.#inflate[kLength] = 0
-
- this.#inflate.on('data', (data) => {
- this.#inflate[kBuffer].push(data)
- this.#inflate[kLength] += data.length
- })
-
- this.#inflate.on('error', (err) => {
- this.#inflate = null
- callback(err)
- })
}
-
- this.#inflate.write(chunk)
- if (fin) {
- this.#inflate.write(tail)
+ return urlSearchParams.toString();
+}
+async function prepareFormData(formData, request) {
+ // validate content type (multipart/form-data)
+ const contentType = request.headers.get("Content-Type");
+ if (contentType && !contentType.startsWith("multipart/form-data")) {
+ // content type is specified and is not multipart/form-data. Exit.
+ return;
}
-
- this.#inflate.flush(() => {
- const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength])
-
- this.#inflate[kBuffer].length = 0
- this.#inflate[kLength] = 0
-
- callback(null, full)
- })
- }
+ request.headers.set("Content-Type", contentType ?? "multipart/form-data");
+ // set body to MultipartRequestBody using content from FormDataMap
+ const parts = [];
+ for (const [fieldName, values] of Object.entries(formData)) {
+ for (const value of Array.isArray(values) ? values : [values]) {
+ if (typeof value === "string") {
+ parts.push({
+ headers: httpHeaders_createHttpHeaders({
+ "Content-Disposition": `form-data; name="${fieldName}"`,
+ }),
+ body: bytesEncoding_stringToUint8Array(value, "utf-8"),
+ });
+ }
+ else if (value === undefined || value === null || typeof value !== "object") {
+ throw new Error(`Unexpected value for key ${fieldName}: ${value}. Value should be serialized to string first.`);
+ }
+ else {
+ // using || instead of ?? here since if value.name is empty we should create a file name
+ const fileName = value.name || "blob";
+ const headers = httpHeaders_createHttpHeaders();
+ headers.set("Content-Disposition", `form-data; name="${fieldName}"; filename="${fileName}"`);
+ // again, || is used since an empty value.type means the content type is unset
+ headers.set("Content-Type", value.type || "application/octet-stream");
+ parts.push({
+ headers,
+ body: value,
+ });
+ }
+ }
+ }
+ request.multipartBody = { parts };
}
+//# sourceMappingURL=formDataPolicy.js.map
+// EXTERNAL MODULE: ./node_modules/https-proxy-agent/dist/index.js
+var dist = __nccwpck_require__(3669);
+// EXTERNAL MODULE: ./node_modules/http-proxy-agent/dist/index.js
+var http_proxy_agent_dist = __nccwpck_require__(1970);
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/policies/proxyPolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
-module.exports = { PerMessageDeflate }
-
-
-/***/ }),
-/***/ 4588:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+const HTTPS_PROXY = "HTTPS_PROXY";
+const HTTP_PROXY = "HTTP_PROXY";
+const ALL_PROXY = "ALL_PROXY";
+const NO_PROXY = "NO_PROXY";
+/**
+ * The programmatic identifier of the proxyPolicy.
+ */
+const proxyPolicyName = "proxyPolicy";
+/**
+ * Stores the patterns specified in NO_PROXY environment variable.
+ * @internal
+ */
+const globalNoProxyList = [];
+let noProxyListLoaded = false;
+/** A cache of whether a host should bypass the proxy. */
+const globalBypassedMap = new Map();
+function getEnvironmentValue(name) {
+ if (process.env[name]) {
+ return process.env[name];
+ }
+ else if (process.env[name.toLowerCase()]) {
+ return process.env[name.toLowerCase()];
+ }
+ return undefined;
+}
+function loadEnvironmentProxyValue() {
+ if (!process) {
+ return undefined;
+ }
+ const httpsProxy = getEnvironmentValue(HTTPS_PROXY);
+ const allProxy = getEnvironmentValue(ALL_PROXY);
+ const httpProxy = getEnvironmentValue(HTTP_PROXY);
+ return httpsProxy || allProxy || httpProxy;
+}
+/**
+ * Check whether the host of a given `uri` matches any pattern in the no proxy list.
+ * If there's a match, any request sent to the same host shouldn't have the proxy settings set.
+ * This implementation is a port of https://github.com/Azure/azure-sdk-for-net/blob/8cca811371159e527159c7eb65602477898683e2/sdk/core/Azure.Core/src/Pipeline/Internal/HttpEnvironmentProxy.cs#L210
+ */
+function isBypassed(uri, noProxyList, bypassedMap) {
+ if (noProxyList.length === 0) {
+ return false;
+ }
+ const host = new URL(uri).hostname;
+ if (bypassedMap?.has(host)) {
+ return bypassedMap.get(host);
+ }
+ let isBypassedFlag = false;
+ for (const pattern of noProxyList) {
+ if (pattern[0] === ".") {
+ // This should match either domain it self or any subdomain or host
+ // .foo.com will match foo.com it self or *.foo.com
+ if (host.endsWith(pattern)) {
+ isBypassedFlag = true;
+ }
+ else {
+ if (host.length === pattern.length - 1 && host === pattern.slice(1)) {
+ isBypassedFlag = true;
+ }
+ }
+ }
+ else {
+ if (host === pattern) {
+ isBypassedFlag = true;
+ }
+ }
+ }
+ bypassedMap?.set(host, isBypassedFlag);
+ return isBypassedFlag;
+}
+function loadNoProxy() {
+ const noProxy = getEnvironmentValue(NO_PROXY);
+ noProxyListLoaded = true;
+ if (noProxy) {
+ return noProxy
+ .split(",")
+ .map((item) => item.trim())
+ .filter((item) => item.length);
+ }
+ return [];
+}
+/**
+ * This method converts a proxy url into `ProxySettings` for use with ProxyPolicy.
+ * If no argument is given, it attempts to parse a proxy URL from the environment
+ * variables `HTTPS_PROXY` or `HTTP_PROXY`.
+ * @param proxyUrl - The url of the proxy to use. May contain authentication information.
+ * @deprecated - Internally this method is no longer necessary when setting proxy information.
+ */
+function getDefaultProxySettings(proxyUrl) {
+ if (!proxyUrl) {
+ proxyUrl = loadEnvironmentProxyValue();
+ if (!proxyUrl) {
+ return undefined;
+ }
+ }
+ const parsedUrl = new URL(proxyUrl);
+ const schema = parsedUrl.protocol ? parsedUrl.protocol + "//" : "";
+ return {
+ host: schema + parsedUrl.hostname,
+ port: Number.parseInt(parsedUrl.port || "80"),
+ username: parsedUrl.username,
+ password: parsedUrl.password,
+ };
+}
+/**
+ * This method attempts to parse a proxy URL from the environment
+ * variables `HTTPS_PROXY` or `HTTP_PROXY`.
+ */
+function getDefaultProxySettingsInternal() {
+ const envProxy = loadEnvironmentProxyValue();
+ return envProxy ? new URL(envProxy) : undefined;
+}
+function getUrlFromProxySettings(settings) {
+ let parsedProxyUrl;
+ try {
+ parsedProxyUrl = new URL(settings.host);
+ }
+ catch {
+ throw new Error(`Expecting a valid host string in proxy settings, but found "${settings.host}".`);
+ }
+ parsedProxyUrl.port = String(settings.port);
+ if (settings.username) {
+ parsedProxyUrl.username = settings.username;
+ }
+ if (settings.password) {
+ parsedProxyUrl.password = settings.password;
+ }
+ return parsedProxyUrl;
+}
+function setProxyAgentOnRequest(request, cachedAgents, proxyUrl) {
+ // Custom Agent should take precedence so if one is present
+ // we should skip to avoid overwriting it.
+ if (request.agent) {
+ return;
+ }
+ const url = new URL(request.url);
+ const isInsecure = url.protocol !== "https:";
+ if (request.tlsSettings) {
+ log_logger.warning("TLS settings are not supported in combination with custom Proxy, certificates provided to the client will be ignored.");
+ }
+ if (isInsecure) {
+ if (!cachedAgents.httpProxyAgent) {
+ cachedAgents.httpProxyAgent = new http_proxy_agent_dist.HttpProxyAgent(proxyUrl);
+ }
+ request.agent = cachedAgents.httpProxyAgent;
+ }
+ else {
+ if (!cachedAgents.httpsProxyAgent) {
+ cachedAgents.httpsProxyAgent = new dist.HttpsProxyAgent(proxyUrl);
+ }
+ request.agent = cachedAgents.httpsProxyAgent;
+ }
+}
+/**
+ * A policy that allows one to apply proxy settings to all requests.
+ * If not passed static settings, they will be retrieved from the HTTPS_PROXY
+ * or HTTP_PROXY environment variables.
+ * @param proxySettings - ProxySettings to use on each request.
+ * @param options - additional settings, for example, custom NO_PROXY patterns
+ */
+function proxyPolicy_proxyPolicy(proxySettings, options) {
+ if (!noProxyListLoaded) {
+ globalNoProxyList.push(...loadNoProxy());
+ }
+ const defaultProxy = proxySettings
+ ? getUrlFromProxySettings(proxySettings)
+ : getDefaultProxySettingsInternal();
+ const cachedAgents = {};
+ return {
+ name: proxyPolicyName,
+ async sendRequest(request, next) {
+ if (!request.proxySettings &&
+ defaultProxy &&
+ !isBypassed(request.url, options?.customNoProxyList ?? globalNoProxyList, options?.customNoProxyList ? undefined : globalBypassedMap)) {
+ setProxyAgentOnRequest(request, cachedAgents, defaultProxy);
+ }
+ else if (request.proxySettings) {
+ setProxyAgentOnRequest(request, cachedAgents, getUrlFromProxySettings(request.proxySettings));
+ }
+ return next(request);
+ },
+ };
+}
+//# sourceMappingURL=proxyPolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/util/typeGuards.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+function isNodeReadableStream(x) {
+ return Boolean(x && typeof x["pipe"] === "function");
+}
+function isWebReadableStream(x) {
+ return Boolean(x &&
+ typeof x.getReader === "function" &&
+ typeof x.tee === "function");
+}
+function typeGuards_isBinaryBody(body) {
+ return (body !== undefined &&
+ (body instanceof Uint8Array ||
+ typeGuards_isReadableStream(body) ||
+ typeof body === "function" ||
+ (typeof Blob !== "undefined" && body instanceof Blob)));
+}
+function typeGuards_isReadableStream(x) {
+ return isNodeReadableStream(x) || isWebReadableStream(x);
+}
+function typeGuards_isBlob(x) {
+ return typeof Blob !== "undefined" && x instanceof Blob;
+}
+//# sourceMappingURL=typeGuards.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/util/concat.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
-const { Writable } = __nccwpck_require__(7075)
-const assert = __nccwpck_require__(4589)
-const { parserStates, opcodes, states, emptyBuffer, sentCloseFrameState } = __nccwpck_require__(1816)
-const { kReadyState, kSentClose, kResponse, kReceivedClose } = __nccwpck_require__(2456)
-const { channels } = __nccwpck_require__(8150)
-const {
- isValidStatusCode,
- isValidOpcode,
- failWebsocketConnection,
- websocketMessageReceived,
- utf8Decode,
- isControlFrame,
- isTextBinaryFrame,
- isContinuationFrame
-} = __nccwpck_require__(5673)
-const { WebsocketFrameSend } = __nccwpck_require__(9272)
-const { closeWebSocketConnection } = __nccwpck_require__(2569)
-const { PerMessageDeflate } = __nccwpck_require__(2869)
-
-// This code was influenced by ws released under the MIT license.
-// Copyright (c) 2011 Einar Otto Stangvik
-// Copyright (c) 2013 Arnout Kazemier and contributors
-// Copyright (c) 2016 Luigi Pinca and contributors
-
-class ByteParser extends Writable {
- #buffers = []
- #byteOffset = 0
- #loop = false
-
- #state = parserStates.INFO
-
- #info = {}
- #fragments = []
+async function* streamAsyncIterator() {
+ const reader = this.getReader();
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) {
+ return;
+ }
+ yield value;
+ }
+ }
+ finally {
+ reader.releaseLock();
+ }
+}
+function makeAsyncIterable(webStream) {
+ if (!webStream[Symbol.asyncIterator]) {
+ webStream[Symbol.asyncIterator] = streamAsyncIterator.bind(webStream);
+ }
+ if (!webStream.values) {
+ webStream.values = streamAsyncIterator.bind(webStream);
+ }
+}
+function ensureNodeStream(stream) {
+ if (stream instanceof ReadableStream) {
+ makeAsyncIterable(stream);
+ return external_stream_namespaceObject.Readable.fromWeb(stream);
+ }
+ else {
+ return stream;
+ }
+}
+function toStream(source) {
+ if (source instanceof Uint8Array) {
+ return external_stream_namespaceObject.Readable.from(Buffer.from(source));
+ }
+ else if (typeGuards_isBlob(source)) {
+ return ensureNodeStream(source.stream());
+ }
+ else {
+ return ensureNodeStream(source);
+ }
+}
+/**
+ * Utility function that concatenates a set of binary inputs into one combined output.
+ *
+ * @param sources - array of sources for the concatenation
+ * @returns - in Node, a (() =\> NodeJS.ReadableStream) which, when read, produces a concatenation of all the inputs.
+ * In browser, returns a `Blob` representing all the concatenated inputs.
+ *
+ * @internal
+ */
+async function concat(sources) {
+ return function () {
+ const streams = sources.map((x) => (typeof x === "function" ? x() : x)).map(toStream);
+ return external_stream_namespaceObject.Readable.from((async function* () {
+ for (const stream of streams) {
+ for await (const chunk of stream) {
+ yield chunk;
+ }
+ }
+ })());
+ };
+}
+//# sourceMappingURL=concat.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/policies/multipartPolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- /** @type {Map} */
- #extensions
- constructor (ws, extensions) {
- super()
- this.ws = ws
- this.#extensions = extensions == null ? new Map() : extensions
- if (this.#extensions.has('permessage-deflate')) {
- this.#extensions.set('permessage-deflate', new PerMessageDeflate(extensions))
+function generateBoundary() {
+ return `----AzSDKFormBoundary${randomUUID()}`;
+}
+function encodeHeaders(headers) {
+ let result = "";
+ for (const [key, value] of headers) {
+ result += `${key}: ${value}\r\n`;
}
- }
-
- /**
- * @param {Buffer} chunk
- * @param {() => void} callback
- */
- _write (chunk, _, callback) {
- this.#buffers.push(chunk)
- this.#byteOffset += chunk.length
- this.#loop = true
-
- this.run(callback)
- }
-
- /**
- * Runs whenever a new chunk is received.
- * Callback is called whenever there are no more chunks buffering,
- * or not enough bytes are buffered to parse.
- */
- run (callback) {
- while (this.#loop) {
- if (this.#state === parserStates.INFO) {
- // If there aren't enough bytes to parse the payload length, etc.
- if (this.#byteOffset < 2) {
- return callback()
+ return result;
+}
+function getLength(source) {
+ if (source instanceof Uint8Array) {
+ return source.byteLength;
+ }
+ else if (typeGuards_isBlob(source)) {
+ // if was created using createFile then -1 means we have an unknown size
+ return source.size === -1 ? undefined : source.size;
+ }
+ else {
+ return undefined;
+ }
+}
+function getTotalLength(sources) {
+ let total = 0;
+ for (const source of sources) {
+ const partLength = getLength(source);
+ if (partLength === undefined) {
+ return undefined;
+ }
+ else {
+ total += partLength;
}
+ }
+ return total;
+}
+async function buildRequestBody(request, parts, boundary) {
+ const sources = [
+ bytesEncoding_stringToUint8Array(`--${boundary}`, "utf-8"),
+ ...parts.flatMap((part) => [
+ bytesEncoding_stringToUint8Array("\r\n", "utf-8"),
+ bytesEncoding_stringToUint8Array(encodeHeaders(part.headers), "utf-8"),
+ bytesEncoding_stringToUint8Array("\r\n", "utf-8"),
+ part.body,
+ bytesEncoding_stringToUint8Array(`\r\n--${boundary}`, "utf-8"),
+ ]),
+ bytesEncoding_stringToUint8Array("--\r\n\r\n", "utf-8"),
+ ];
+ const contentLength = getTotalLength(sources);
+ if (contentLength) {
+ request.headers.set("Content-Length", contentLength);
+ }
+ request.body = await concat(sources);
+}
+/**
+ * Name of multipart policy
+ */
+const multipartPolicy_multipartPolicyName = "multipartPolicy";
+const maxBoundaryLength = 70;
+const validBoundaryCharacters = new Set(`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'()+,-./:=?`);
+function assertValidBoundary(boundary) {
+ if (boundary.length > maxBoundaryLength) {
+ throw new Error(`Multipart boundary "${boundary}" exceeds maximum length of 70 characters`);
+ }
+ if (Array.from(boundary).some((x) => !validBoundaryCharacters.has(x))) {
+ throw new Error(`Multipart boundary "${boundary}" contains invalid characters`);
+ }
+}
+/**
+ * Pipeline policy for multipart requests
+ */
+function multipartPolicy_multipartPolicy() {
+ return {
+ name: multipartPolicy_multipartPolicyName,
+ async sendRequest(request, next) {
+ if (!request.multipartBody) {
+ return next(request);
+ }
+ if (request.body) {
+ throw new Error("multipartBody and regular body cannot be set at the same time");
+ }
+ let boundary = request.multipartBody.boundary;
+ const contentTypeHeader = request.headers.get("Content-Type") ?? "multipart/mixed";
+ const parsedHeader = contentTypeHeader.match(/^(multipart\/[^ ;]+)(?:; *boundary=(.+))?$/);
+ if (!parsedHeader) {
+ throw new Error(`Got multipart request body, but content-type header was not multipart: ${contentTypeHeader}`);
+ }
+ const [, contentType, parsedBoundary] = parsedHeader;
+ if (parsedBoundary && boundary && parsedBoundary !== boundary) {
+ throw new Error(`Multipart boundary was specified as ${parsedBoundary} in the header, but got ${boundary} in the request body`);
+ }
+ boundary ??= parsedBoundary;
+ if (boundary) {
+ assertValidBoundary(boundary);
+ }
+ else {
+ boundary = generateBoundary();
+ }
+ request.headers.set("Content-Type", `${contentType}; boundary=${boundary}`);
+ await buildRequestBody(request, request.multipartBody.parts, boundary);
+ request.multipartBody = undefined;
+ return next(request);
+ },
+ };
+}
+//# sourceMappingURL=multipartPolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/createPipelineFromOptions.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- const buffer = this.consume(2)
- const fin = (buffer[0] & 0x80) !== 0
- const opcode = buffer[0] & 0x0F
- const masked = (buffer[1] & 0x80) === 0x80
- const fragmented = !fin && opcode !== opcodes.CONTINUATION
- const payloadLength = buffer[1] & 0x7F
- const rsv1 = buffer[0] & 0x40
- const rsv2 = buffer[0] & 0x20
- const rsv3 = buffer[0] & 0x10
- if (!isValidOpcode(opcode)) {
- failWebsocketConnection(this.ws, 'Invalid opcode received')
- return callback()
- }
- if (masked) {
- failWebsocketConnection(this.ws, 'Frame cannot be masked')
- return callback()
- }
- // MUST be 0 unless an extension is negotiated that defines meanings
- // for non-zero values. If a nonzero value is received and none of
- // the negotiated extensions defines the meaning of such a nonzero
- // value, the receiving endpoint MUST _Fail the WebSocket
- // Connection_.
- // This document allocates the RSV1 bit of the WebSocket header for
- // PMCEs and calls the bit the "Per-Message Compressed" bit. On a
- // WebSocket connection where a PMCE is in use, this bit indicates
- // whether a message is compressed or not.
- if (rsv1 !== 0 && !this.#extensions.has('permessage-deflate')) {
- failWebsocketConnection(this.ws, 'Expected RSV1 to be clear.')
- return
- }
- if (rsv2 !== 0 || rsv3 !== 0) {
- failWebsocketConnection(this.ws, 'RSV1, RSV2, RSV3 must be clear')
- return
- }
- if (fragmented && !isTextBinaryFrame(opcode)) {
- // Only text and binary frames can be fragmented
- failWebsocketConnection(this.ws, 'Invalid frame type was fragmented.')
- return
- }
- // If we are already parsing a text/binary frame and do not receive either
- // a continuation frame or close frame, fail the connection.
- if (isTextBinaryFrame(opcode) && this.#fragments.length > 0) {
- failWebsocketConnection(this.ws, 'Expected continuation frame')
- return
- }
- if (this.#info.fragmented && fragmented) {
- // A fragmented frame can't be fragmented itself
- failWebsocketConnection(this.ws, 'Fragmented frame exceeded 125 bytes.')
- return
- }
- // "All control frames MUST have a payload length of 125 bytes or less
- // and MUST NOT be fragmented."
- if ((payloadLength > 125 || fragmented) && isControlFrame(opcode)) {
- failWebsocketConnection(this.ws, 'Control frame either too large or fragmented')
- return
- }
- if (isContinuationFrame(opcode) && this.#fragments.length === 0 && !this.#info.compressed) {
- failWebsocketConnection(this.ws, 'Unexpected continuation frame')
- return
+/**
+ * Create a new pipeline with a default set of customizable policies.
+ * @param options - Options to configure a custom pipeline.
+ */
+function createPipelineFromOptions_createPipelineFromOptions(options) {
+ const pipeline = createEmptyPipeline();
+ if (isNodeLike) {
+ if (options.agent) {
+ pipeline.addPolicy(agentPolicy(options.agent));
}
-
- if (payloadLength <= 125) {
- this.#info.payloadLength = payloadLength
- this.#state = parserStates.READ_DATA
- } else if (payloadLength === 126) {
- this.#state = parserStates.PAYLOADLENGTH_16
- } else if (payloadLength === 127) {
- this.#state = parserStates.PAYLOADLENGTH_64
+ if (options.tlsOptions) {
+ pipeline.addPolicy(tlsPolicy(options.tlsOptions));
}
+ pipeline.addPolicy(proxyPolicy(options.proxyOptions));
+ pipeline.addPolicy(decompressResponsePolicy());
+ }
+ pipeline.addPolicy(formDataPolicy(), { beforePolicies: [multipartPolicyName] });
+ pipeline.addPolicy(userAgentPolicy(options.userAgentOptions));
+ // The multipart policy is added after policies with no phase, so that
+ // policies can be added between it and formDataPolicy to modify
+ // properties (e.g., making the boundary constant in recorded tests).
+ pipeline.addPolicy(multipartPolicy(), { afterPhase: "Deserialize" });
+ pipeline.addPolicy(defaultRetryPolicy(options.retryOptions), { phase: "Retry" });
+ if (isNodeLike) {
+ // Both XHR and Fetch expect to handle redirects automatically,
+ // so only include this policy when we're in Node.
+ pipeline.addPolicy(redirectPolicy(options.redirectOptions), { afterPhase: "Retry" });
+ }
+ pipeline.addPolicy(logPolicy(options.loggingOptions), { afterPhase: "Sign" });
+ return pipeline;
+}
+//# sourceMappingURL=createPipelineFromOptions.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/policies/auth/checkInsecureConnection.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- if (isTextBinaryFrame(opcode)) {
- this.#info.binaryType = opcode
- this.#info.compressed = rsv1 !== 0
+// Ensure the warining is only emitted once
+let insecureConnectionWarningEmmitted = false;
+/**
+ * Checks if the request is allowed to be sent over an insecure connection.
+ *
+ * A request is allowed to be sent over an insecure connection when:
+ * - The `allowInsecureConnection` option is set to `true`.
+ * - The request has the `allowInsecureConnection` property set to `true`.
+ * - The request is being sent to `localhost` or `127.0.0.1`
+ */
+function allowInsecureConnection(request, options) {
+ if (options.allowInsecureConnection && request.allowInsecureConnection) {
+ const url = new URL(request.url);
+ if (url.hostname === "localhost" || url.hostname === "127.0.0.1") {
+ return true;
}
-
- this.#info.opcode = opcode
- this.#info.masked = masked
- this.#info.fin = fin
- this.#info.fragmented = fragmented
- } else if (this.#state === parserStates.PAYLOADLENGTH_16) {
- if (this.#byteOffset < 2) {
- return callback()
+ }
+ return false;
+}
+/**
+ * Logs a warning about sending a token over an insecure connection.
+ *
+ * This function will emit a node warning once, but log the warning every time.
+ */
+function emitInsecureConnectionWarning() {
+ const warning = "Sending token over insecure transport. Assume any token issued is compromised.";
+ logger.warning(warning);
+ if (typeof process?.emitWarning === "function" && !insecureConnectionWarningEmmitted) {
+ insecureConnectionWarningEmmitted = true;
+ process.emitWarning(warning);
+ }
+}
+/**
+ * Ensures that authentication is only allowed over HTTPS unless explicitly allowed.
+ * Throws an error if the connection is not secure and not explicitly allowed.
+ */
+function checkInsecureConnection_ensureSecureConnection(request, options) {
+ if (!request.url.toLowerCase().startsWith("https://")) {
+ if (allowInsecureConnection(request, options)) {
+ emitInsecureConnectionWarning();
}
-
- const buffer = this.consume(2)
-
- this.#info.payloadLength = buffer.readUInt16BE(0)
- this.#state = parserStates.READ_DATA
- } else if (this.#state === parserStates.PAYLOADLENGTH_64) {
- if (this.#byteOffset < 8) {
- return callback()
+ else {
+ throw new Error("Authentication is not permitted for non-TLS protected (non-https) URLs when allowInsecureConnection is false.");
}
+ }
+}
+//# sourceMappingURL=checkInsecureConnection.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/policies/auth/apiKeyAuthenticationPolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- const buffer = this.consume(8)
- const upper = buffer.readUInt32BE(0)
+/**
+ * Name of the API Key Authentication Policy
+ */
+const apiKeyAuthenticationPolicyName = "apiKeyAuthenticationPolicy";
+/**
+ * Gets a pipeline policy that adds API key authentication to requests
+ */
+function apiKeyAuthenticationPolicy_apiKeyAuthenticationPolicy(options) {
+ return {
+ name: apiKeyAuthenticationPolicyName,
+ async sendRequest(request, next) {
+ // Ensure allowInsecureConnection is explicitly set when sending request to non-https URLs
+ ensureSecureConnection(request, options);
+ const scheme = (request.authSchemes ?? options.authSchemes)?.find((x) => x.kind === "apiKey");
+ // Skip adding authentication header if no API key authentication scheme is found
+ if (!scheme) {
+ return next(request);
+ }
+ if (scheme.apiKeyLocation !== "header") {
+ throw new Error(`Unsupported API key location: ${scheme.apiKeyLocation}`);
+ }
+ request.headers.set(scheme.name, options.credential.key);
+ return next(request);
+ },
+ };
+}
+//# sourceMappingURL=apiKeyAuthenticationPolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/policies/auth/basicAuthenticationPolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- // 2^31 is the maximum bytes an arraybuffer can contain
- // on 32-bit systems. Although, on 64-bit systems, this is
- // 2^53-1 bytes.
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_array_length
- // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/common/globals.h;drc=1946212ac0100668f14eb9e2843bdd846e510a1e;bpv=1;bpt=1;l=1275
- // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/js-array-buffer.h;l=34;drc=1946212ac0100668f14eb9e2843bdd846e510a1e
- if (upper > 2 ** 31 - 1) {
- failWebsocketConnection(this.ws, 'Received payload length > 2^31 bytes.')
- return
- }
- const lower = buffer.readUInt32BE(4)
+/**
+ * Name of the Basic Authentication Policy
+ */
+const basicAuthenticationPolicyName = "bearerAuthenticationPolicy";
+/**
+ * Gets a pipeline policy that adds basic authentication to requests
+ */
+function basicAuthenticationPolicy_basicAuthenticationPolicy(options) {
+ return {
+ name: basicAuthenticationPolicyName,
+ async sendRequest(request, next) {
+ // Ensure allowInsecureConnection is explicitly set when sending request to non-https URLs
+ ensureSecureConnection(request, options);
+ const scheme = (request.authSchemes ?? options.authSchemes)?.find((x) => x.kind === "http" && x.scheme === "basic");
+ // Skip adding authentication header if no basic authentication scheme is found
+ if (!scheme) {
+ return next(request);
+ }
+ const { username, password } = options.credential;
+ const headerValue = uint8ArrayToString(stringToUint8Array(`${username}:${password}`, "utf-8"), "base64");
+ request.headers.set("Authorization", `Basic ${headerValue}`);
+ return next(request);
+ },
+ };
+}
+//# sourceMappingURL=basicAuthenticationPolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/policies/auth/bearerAuthenticationPolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- this.#info.payloadLength = (upper << 8) + lower
- this.#state = parserStates.READ_DATA
- } else if (this.#state === parserStates.READ_DATA) {
- if (this.#byteOffset < this.#info.payloadLength) {
- return callback()
- }
+/**
+ * Name of the Bearer Authentication Policy
+ */
+const bearerAuthenticationPolicyName = "bearerAuthenticationPolicy";
+/**
+ * Gets a pipeline policy that adds bearer token authentication to requests
+ */
+function bearerAuthenticationPolicy_bearerAuthenticationPolicy(options) {
+ return {
+ name: bearerAuthenticationPolicyName,
+ async sendRequest(request, next) {
+ // Ensure allowInsecureConnection is explicitly set when sending request to non-https URLs
+ ensureSecureConnection(request, options);
+ const scheme = (request.authSchemes ?? options.authSchemes)?.find((x) => x.kind === "http" && x.scheme === "bearer");
+ // Skip adding authentication header if no bearer authentication scheme is found
+ if (!scheme) {
+ return next(request);
+ }
+ const token = await options.credential.getBearerToken({
+ abortSignal: request.abortSignal,
+ });
+ request.headers.set("Authorization", `Bearer ${token}`);
+ return next(request);
+ },
+ };
+}
+//# sourceMappingURL=bearerAuthenticationPolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/policies/auth/oauth2AuthenticationPolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- const body = this.consume(this.#info.payloadLength)
+/**
+ * Name of the OAuth2 Authentication Policy
+ */
+const oauth2AuthenticationPolicyName = "oauth2AuthenticationPolicy";
+/**
+ * Gets a pipeline policy that adds authorization header from OAuth2 schemes
+ */
+function oauth2AuthenticationPolicy_oauth2AuthenticationPolicy(options) {
+ return {
+ name: oauth2AuthenticationPolicyName,
+ async sendRequest(request, next) {
+ // Ensure allowInsecureConnection is explicitly set when sending request to non-https URLs
+ ensureSecureConnection(request, options);
+ const scheme = (request.authSchemes ?? options.authSchemes)?.find((x) => x.kind === "oauth2");
+ // Skip adding authentication header if no OAuth2 authentication scheme is found
+ if (!scheme) {
+ return next(request);
+ }
+ const token = await options.credential.getOAuth2Token(scheme.flows, {
+ abortSignal: request.abortSignal,
+ });
+ request.headers.set("Authorization", `Bearer ${token}`);
+ return next(request);
+ },
+ };
+}
+//# sourceMappingURL=oauth2AuthenticationPolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/client/clientHelpers.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- if (isControlFrame(this.#info.opcode)) {
- this.#loop = this.parseControlFrame(body)
- this.#state = parserStates.INFO
- } else {
- if (!this.#info.compressed) {
- this.#fragments.push(body)
- // If the frame is not fragmented, a message has been received.
- // If the frame is fragmented, it will terminate with a fin bit set
- // and an opcode of 0 (continuation), therefore we handle that when
- // parsing continuation frames, not here.
- if (!this.#info.fragmented && this.#info.fin) {
- const fullMessage = Buffer.concat(this.#fragments)
- websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage)
- this.#fragments.length = 0
- }
- this.#state = parserStates.INFO
- } else {
- this.#extensions.get('permessage-deflate').decompress(body, this.#info.fin, (error, data) => {
- if (error) {
- closeWebSocketConnection(this.ws, 1007, error.message, error.message.length)
- return
- }
- this.#fragments.push(data)
- if (!this.#info.fin) {
- this.#state = parserStates.INFO
- this.#loop = true
- this.run(callback)
- return
- }
- websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments))
- this.#loop = true
- this.#state = parserStates.INFO
- this.#fragments.length = 0
- this.run(callback)
- })
- this.#loop = false
- break
- }
+let cachedHttpClient;
+/**
+ * Creates a default rest pipeline to re-use accross Rest Level Clients
+ */
+function clientHelpers_createDefaultPipeline(options = {}) {
+ const pipeline = createPipelineFromOptions(options);
+ pipeline.addPolicy(apiVersionPolicy(options));
+ const { credential, authSchemes, allowInsecureConnection } = options;
+ if (credential) {
+ if (isApiKeyCredential(credential)) {
+ pipeline.addPolicy(apiKeyAuthenticationPolicy({ authSchemes, credential, allowInsecureConnection }));
+ }
+ else if (isBasicCredential(credential)) {
+ pipeline.addPolicy(basicAuthenticationPolicy({ authSchemes, credential, allowInsecureConnection }));
+ }
+ else if (isBearerTokenCredential(credential)) {
+ pipeline.addPolicy(bearerAuthenticationPolicy({ authSchemes, credential, allowInsecureConnection }));
+ }
+ else if (isOAuth2TokenCredential(credential)) {
+ pipeline.addPolicy(oauth2AuthenticationPolicy({ authSchemes, credential, allowInsecureConnection }));
}
- }
}
- }
-
- /**
- * Take n bytes from the buffered Buffers
- * @param {number} n
- * @returns {Buffer}
- */
- consume (n) {
- if (n > this.#byteOffset) {
- throw new Error('Called consume() before buffers satiated.')
- } else if (n === 0) {
- return emptyBuffer
+ return pipeline;
+}
+function clientHelpers_getCachedDefaultHttpsClient() {
+ if (!cachedHttpClient) {
+ cachedHttpClient = createDefaultHttpClient();
}
+ return cachedHttpClient;
+}
+//# sourceMappingURL=clientHelpers.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/client/multipart.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- if (this.#buffers[0].length === n) {
- this.#byteOffset -= this.#buffers[0].length
- return this.#buffers.shift()
- }
- const buffer = Buffer.allocUnsafe(n)
- let offset = 0
- while (offset !== n) {
- const next = this.#buffers[0]
- const { length } = next
- if (length + offset === n) {
- buffer.set(this.#buffers.shift(), offset)
- break
- } else if (length + offset > n) {
- buffer.set(next.subarray(0, n - offset), offset)
- this.#buffers[0] = next.subarray(n - offset)
- break
- } else {
- buffer.set(this.#buffers.shift(), offset)
- offset += next.length
- }
+/**
+ * Get value of a header in the part descriptor ignoring case
+ */
+function getHeaderValue(descriptor, headerName) {
+ if (descriptor.headers) {
+ const actualHeaderName = Object.keys(descriptor.headers).find((x) => x.toLowerCase() === headerName.toLowerCase());
+ if (actualHeaderName) {
+ return descriptor.headers[actualHeaderName];
+ }
}
-
- this.#byteOffset -= n
-
- return buffer
- }
-
- parseCloseBody (data) {
- assert(data.length !== 1)
-
- // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5
- /** @type {number|undefined} */
- let code
-
- if (data.length >= 2) {
- // _The WebSocket Connection Close Code_ is
- // defined as the status code (Section 7.4) contained in the first Close
- // control frame received by the application
- code = data.readUInt16BE(0)
+ return undefined;
+}
+function getPartContentType(descriptor) {
+ const contentTypeHeader = getHeaderValue(descriptor, "content-type");
+ if (contentTypeHeader) {
+ return contentTypeHeader;
}
-
- if (code !== undefined && !isValidStatusCode(code)) {
- return { code: 1002, reason: 'Invalid status code', error: true }
+ // Special value of null means content type is to be omitted
+ if (descriptor.contentType === null) {
+ return undefined;
}
-
- // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6
- /** @type {Buffer} */
- let reason = data.subarray(2)
-
- // Remove BOM
- if (reason[0] === 0xEF && reason[1] === 0xBB && reason[2] === 0xBF) {
- reason = reason.subarray(3)
+ if (descriptor.contentType) {
+ return descriptor.contentType;
}
-
- try {
- reason = utf8Decode(reason)
- } catch {
- return { code: 1007, reason: 'Invalid UTF-8', error: true }
+ const { body } = descriptor;
+ if (body === null || body === undefined) {
+ return undefined;
}
+ if (typeof body === "string" || typeof body === "number" || typeof body === "boolean") {
+ return "text/plain; charset=UTF-8";
+ }
+ if (body instanceof Blob) {
+ return body.type || "application/octet-stream";
+ }
+ if (isBinaryBody(body)) {
+ return "application/octet-stream";
+ }
+ // arbitrary non-text object -> generic JSON content type by default. We will try to JSON.stringify the body.
+ return "application/json";
+}
+/**
+ * Enclose value in quotes and escape special characters, for use in the Content-Disposition header
+ */
+function escapeDispositionField(value) {
+ return JSON.stringify(value);
+}
+function getContentDisposition(descriptor) {
+ const contentDispositionHeader = getHeaderValue(descriptor, "content-disposition");
+ if (contentDispositionHeader) {
+ return contentDispositionHeader;
+ }
+ if (descriptor.dispositionType === undefined &&
+ descriptor.name === undefined &&
+ descriptor.filename === undefined) {
+ return undefined;
+ }
+ const dispositionType = descriptor.dispositionType ?? "form-data";
+ let disposition = dispositionType;
+ if (descriptor.name) {
+ disposition += `; name=${escapeDispositionField(descriptor.name)}`;
+ }
+ let filename = undefined;
+ if (descriptor.filename) {
+ filename = descriptor.filename;
+ }
+ else if (typeof File !== "undefined" && descriptor.body instanceof File) {
+ const filenameFromFile = descriptor.body.name;
+ if (filenameFromFile !== "") {
+ filename = filenameFromFile;
+ }
+ }
+ if (filename) {
+ disposition += `; filename=${escapeDispositionField(filename)}`;
+ }
+ return disposition;
+}
+function normalizeBody(body, contentType) {
+ if (body === undefined) {
+ // zero-length body
+ return new Uint8Array([]);
+ }
+ // binary and primitives should go straight on the wire regardless of content type
+ if (isBinaryBody(body)) {
+ return body;
+ }
+ if (typeof body === "string" || typeof body === "number" || typeof body === "boolean") {
+ return stringToUint8Array(String(body), "utf-8");
+ }
+ // stringify objects for JSON-ish content types e.g. application/json, application/merge-patch+json, application/vnd.oci.manifest.v1+json, application.json; charset=UTF-8
+ if (contentType && /application\/(.+\+)?json(;.+)?/i.test(String(contentType))) {
+ return stringToUint8Array(JSON.stringify(body), "utf-8");
+ }
+ throw new RestError(`Unsupported body/content-type combination: ${body}, ${contentType}`);
+}
+function buildBodyPart(descriptor) {
+ const contentType = getPartContentType(descriptor);
+ const contentDisposition = getContentDisposition(descriptor);
+ const headers = createHttpHeaders(descriptor.headers ?? {});
+ if (contentType) {
+ headers.set("content-type", contentType);
+ }
+ if (contentDisposition) {
+ headers.set("content-disposition", contentDisposition);
+ }
+ const body = normalizeBody(descriptor.body, contentType);
+ return {
+ headers,
+ body,
+ };
+}
+function multipart_buildMultipartBody(parts) {
+ return { parts: parts.map(buildBodyPart) };
+}
+//# sourceMappingURL=multipart.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/client/sendRequest.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- return { code, reason, error: false }
- }
-
- /**
- * Parses control frames.
- * @param {Buffer} body
- */
- parseControlFrame (body) {
- const { opcode, payloadLength } = this.#info
-
- if (opcode === opcodes.CLOSE) {
- if (payloadLength === 1) {
- failWebsocketConnection(this.ws, 'Received close frame with a 1-byte body.')
- return false
- }
- this.#info.closeInfo = this.parseCloseBody(body)
- if (this.#info.closeInfo.error) {
- const { code, reason } = this.#info.closeInfo
- closeWebSocketConnection(this.ws, code, reason, reason.length)
- failWebsocketConnection(this.ws, reason)
- return false
- }
- if (this.ws[kSentClose] !== sentCloseFrameState.SENT) {
- // If an endpoint receives a Close frame and did not previously send a
- // Close frame, the endpoint MUST send a Close frame in response. (When
- // sending a Close frame in response, the endpoint typically echos the
- // status code it received.)
- let body = emptyBuffer
- if (this.#info.closeInfo.code) {
- body = Buffer.allocUnsafe(2)
- body.writeUInt16BE(this.#info.closeInfo.code, 0)
- }
- const closeFrame = new WebsocketFrameSend(body)
- this.ws[kResponse].socket.write(
- closeFrame.createFrame(opcodes.CLOSE),
- (err) => {
- if (!err) {
- this.ws[kSentClose] = sentCloseFrameState.SENT
+/**
+ * Helper function to send request used by the client
+ * @param method - method to use to send the request
+ * @param url - url to send the request to
+ * @param pipeline - pipeline with the policies to run when sending the request
+ * @param options - request options
+ * @param customHttpClient - a custom HttpClient to use when making the request
+ * @returns returns and HttpResponse
+ */
+async function sendRequest_sendRequest(method, url, pipeline, options = {}, customHttpClient) {
+ const httpClient = customHttpClient ?? getCachedDefaultHttpsClient();
+ const request = buildPipelineRequest(method, url, options);
+ try {
+ const response = await pipeline.sendRequest(httpClient, request);
+ const headers = response.headers.toJSON();
+ const stream = response.readableStreamBody ?? response.browserStreamBody;
+ const parsedBody = options.responseAsStream || stream !== undefined ? undefined : getResponseBody(response);
+ const body = stream ?? parsedBody;
+ if (options?.onResponse) {
+ options.onResponse({ ...response, request, rawHeaders: headers, parsedBody });
+ }
+ return {
+ request,
+ headers,
+ status: `${response.status}`,
+ body,
+ };
+ }
+ catch (e) {
+ if (isRestError(e) && e.response && options.onResponse) {
+ const { response } = e;
+ const rawHeaders = response.headers.toJSON();
+ // UNBRANDED DIFFERENCE: onResponse callback does not have a second __legacyError property
+ options?.onResponse({ ...response, request, rawHeaders }, e);
+ }
+ throw e;
+ }
+}
+/**
+ * Function to determine the request content type
+ * @param options - request options InternalRequestParameters
+ * @returns returns the content-type
+ */
+function getRequestContentType(options = {}) {
+ if (options.contentType) {
+ return options.contentType;
+ }
+ const headerContentType = options.headers?.["content-type"];
+ if (typeof headerContentType === "string") {
+ return headerContentType;
+ }
+ return getContentType(options.body);
+}
+/**
+ * Function to determine the content-type of a body
+ * this is used if an explicit content-type is not provided
+ * @param body - body in the request
+ * @returns returns the content-type
+ */
+function getContentType(body) {
+ if (body === undefined) {
+ return undefined;
+ }
+ if (ArrayBuffer.isView(body)) {
+ return "application/octet-stream";
+ }
+ if (isBlob(body) && body.type) {
+ return body.type;
+ }
+ if (typeof body === "string") {
+ try {
+ JSON.parse(body);
+ return "application/json";
+ }
+ catch (error) {
+ // If we fail to parse the body, it is not json
+ return undefined;
+ }
+ }
+ // By default return json
+ return "application/json";
+}
+function buildPipelineRequest(method, url, options = {}) {
+ const requestContentType = getRequestContentType(options);
+ const { body, multipartBody } = getRequestBody(options.body, requestContentType);
+ const headers = createHttpHeaders({
+ ...(options.headers ? options.headers : {}),
+ accept: options.accept ?? options.headers?.accept ?? "application/json",
+ ...(requestContentType && {
+ "content-type": requestContentType,
+ }),
+ });
+ return createPipelineRequest({
+ url,
+ method,
+ body,
+ multipartBody,
+ headers,
+ allowInsecureConnection: options.allowInsecureConnection,
+ abortSignal: options.abortSignal,
+ onUploadProgress: options.onUploadProgress,
+ onDownloadProgress: options.onDownloadProgress,
+ timeout: options.timeout,
+ enableBrowserStreams: true,
+ streamResponseStatusCodes: options.responseAsStream
+ ? new Set([Number.POSITIVE_INFINITY])
+ : undefined,
+ });
+}
+/**
+ * Prepares the body before sending the request
+ */
+function getRequestBody(body, contentType = "") {
+ if (body === undefined) {
+ return { body: undefined };
+ }
+ if (typeof FormData !== "undefined" && body instanceof FormData) {
+ return { body };
+ }
+ if (isBlob(body)) {
+ return { body };
+ }
+ if (isReadableStream(body)) {
+ return { body };
+ }
+ if (typeof body === "function") {
+ return { body: body };
+ }
+ if (ArrayBuffer.isView(body)) {
+ return { body: body instanceof Uint8Array ? body : JSON.stringify(body) };
+ }
+ const firstType = contentType.split(";")[0];
+ switch (firstType) {
+ case "application/json":
+ return { body: JSON.stringify(body) };
+ case "multipart/form-data":
+ if (Array.isArray(body)) {
+ return { multipartBody: buildMultipartBody(body) };
}
- }
- )
- }
-
- // Upon either sending or receiving a Close control frame, it is said
- // that _The WebSocket Closing Handshake is Started_ and that the
- // WebSocket connection is in the CLOSING state.
- this.ws[kReadyState] = states.CLOSING
- this.ws[kReceivedClose] = true
-
- return false
- } else if (opcode === opcodes.PING) {
- // Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in
- // response, unless it already received a Close frame.
- // A Pong frame sent in response to a Ping frame must have identical
- // "Application data"
-
- if (!this.ws[kReceivedClose]) {
- const frame = new WebsocketFrameSend(body)
-
- this.ws[kResponse].socket.write(frame.createFrame(opcodes.PONG))
-
- if (channels.ping.hasSubscribers) {
- channels.ping.publish({
- payload: body
- })
+ return { body: JSON.stringify(body) };
+ case "text/plain":
+ return { body: String(body) };
+ default:
+ if (typeof body === "string") {
+ return { body };
+ }
+ return { body: JSON.stringify(body) };
+ }
+}
+/**
+ * Prepares the response body
+ */
+function getResponseBody(response) {
+ // Set the default response type
+ const contentType = response.headers.get("content-type") ?? "";
+ const firstType = contentType.split(";")[0];
+ const bodyToParse = response.bodyAsText ?? "";
+ if (firstType === "text/plain") {
+ return String(bodyToParse);
+ }
+ // Default to "application/json" and fallback to string;
+ try {
+ return bodyToParse ? JSON.parse(bodyToParse) : undefined;
+ }
+ catch (error) {
+ // If we were supposed to get a JSON object and failed to
+ // parse, throw a parse error
+ if (firstType === "application/json") {
+ throw createParseError(response, error);
}
- }
- } else if (opcode === opcodes.PONG) {
- // A Pong frame MAY be sent unsolicited. This serves as a
- // unidirectional heartbeat. A response to an unsolicited Pong frame is
- // not expected.
-
- if (channels.pong.hasSubscribers) {
- channels.pong.publish({
- payload: body
- })
- }
+ // We are not sure how to handle the response so we return it as
+ // plain text.
+ return String(bodyToParse);
}
-
- return true
- }
-
- get closingInfo () {
- return this.#info.closeInfo
- }
}
-
-module.exports = {
- ByteParser
+function createParseError(response, err) {
+ const msg = `Error "${err}" occurred while parsing the response body - ${response.bodyAsText}.`;
+ const errCode = err.code ?? RestError.PARSE_ERROR;
+ return new RestError(msg, {
+ code: errCode,
+ statusCode: response.status,
+ request: response.request,
+ response: response,
+ });
}
+//# sourceMappingURL=sendRequest.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/client/getClient.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
-/***/ }),
-
-/***/ 228:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const { WebsocketFrameSend } = __nccwpck_require__(9272)
-const { opcodes, sendHints } = __nccwpck_require__(1816)
-const FixedQueue = __nccwpck_require__(6524)
-/** @type {typeof Uint8Array} */
-const FastBuffer = Buffer[Symbol.species]
/**
- * @typedef {object} SendQueueNode
- * @property {Promise | null} promise
- * @property {((...args: any[]) => any)} callback
- * @property {Buffer | null} frame
+ * Creates a client with a default pipeline
+ * @param endpoint - Base endpoint for the client
+ * @param credentials - Credentials to authenticate the requests
+ * @param options - Client options
*/
-
-class SendQueue {
- /**
- * @type {FixedQueue}
- */
- #queue = new FixedQueue()
-
- /**
- * @type {boolean}
- */
- #running = false
-
- /** @type {import('node:net').Socket} */
- #socket
-
- constructor (socket) {
- this.#socket = socket
- }
-
- add (item, cb, hint) {
- if (hint !== sendHints.blob) {
- const frame = createFrame(item, hint)
- if (!this.#running) {
- // fast-path
- this.#socket.write(frame, cb)
- } else {
- /** @type {SendQueueNode} */
- const node = {
- promise: null,
- callback: cb,
- frame
+function getClient(endpoint, clientOptions = {}) {
+ const pipeline = clientOptions.pipeline ?? createDefaultPipeline(clientOptions);
+ if (clientOptions.additionalPolicies?.length) {
+ for (const { policy, position } of clientOptions.additionalPolicies) {
+ // Sign happens after Retry and is commonly needed to occur
+ // before policies that intercept post-retry.
+ const afterPhase = position === "perRetry" ? "Sign" : undefined;
+ pipeline.addPolicy(policy, {
+ afterPhase,
+ });
}
- this.#queue.push(node)
- }
- return
- }
-
- /** @type {SendQueueNode} */
- const node = {
- promise: item.arrayBuffer().then((ab) => {
- node.promise = null
- node.frame = createFrame(ab, hint)
- }),
- callback: cb,
- frame: null
}
+ const { allowInsecureConnection, httpClient } = clientOptions;
+ const endpointUrl = clientOptions.endpoint ?? endpoint;
+ const client = (path, ...args) => {
+ const getUrl = (requestOptions) => buildRequestUrl(endpointUrl, path, args, { allowInsecureConnection, ...requestOptions });
+ return {
+ get: (requestOptions = {}) => {
+ return buildOperation("GET", getUrl(requestOptions), pipeline, requestOptions, allowInsecureConnection, httpClient);
+ },
+ post: (requestOptions = {}) => {
+ return buildOperation("POST", getUrl(requestOptions), pipeline, requestOptions, allowInsecureConnection, httpClient);
+ },
+ put: (requestOptions = {}) => {
+ return buildOperation("PUT", getUrl(requestOptions), pipeline, requestOptions, allowInsecureConnection, httpClient);
+ },
+ patch: (requestOptions = {}) => {
+ return buildOperation("PATCH", getUrl(requestOptions), pipeline, requestOptions, allowInsecureConnection, httpClient);
+ },
+ delete: (requestOptions = {}) => {
+ return buildOperation("DELETE", getUrl(requestOptions), pipeline, requestOptions, allowInsecureConnection, httpClient);
+ },
+ head: (requestOptions = {}) => {
+ return buildOperation("HEAD", getUrl(requestOptions), pipeline, requestOptions, allowInsecureConnection, httpClient);
+ },
+ options: (requestOptions = {}) => {
+ return buildOperation("OPTIONS", getUrl(requestOptions), pipeline, requestOptions, allowInsecureConnection, httpClient);
+ },
+ trace: (requestOptions = {}) => {
+ return buildOperation("TRACE", getUrl(requestOptions), pipeline, requestOptions, allowInsecureConnection, httpClient);
+ },
+ };
+ };
+ return {
+ path: client,
+ pathUnchecked: client,
+ pipeline,
+ };
+}
+function buildOperation(method, url, pipeline, options, allowInsecureConnection, httpClient) {
+ allowInsecureConnection = options.allowInsecureConnection ?? allowInsecureConnection;
+ return {
+ then: function (onFulfilled, onrejected) {
+ return sendRequest(method, url, pipeline, { ...options, allowInsecureConnection }, httpClient).then(onFulfilled, onrejected);
+ },
+ async asBrowserStream() {
+ if (isNodeLike) {
+ throw new Error("`asBrowserStream` is supported only in the browser environment. Use `asNodeStream` instead to obtain the response body stream. If you require a Web stream of the response in Node, consider using `Readable.toWeb` on the result of `asNodeStream`.");
+ }
+ else {
+ return sendRequest(method, url, pipeline, { ...options, allowInsecureConnection, responseAsStream: true }, httpClient);
+ }
+ },
+ async asNodeStream() {
+ if (isNodeLike) {
+ return sendRequest(method, url, pipeline, { ...options, allowInsecureConnection, responseAsStream: true }, httpClient);
+ }
+ else {
+ throw new Error("`isNodeStream` is not supported in the browser environment. Use `asBrowserStream` to obtain the response body stream.");
+ }
+ },
+ };
+}
+//# sourceMappingURL=getClient.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/client/restError.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- this.#queue.push(node)
-
- if (!this.#running) {
- this.#run()
- }
- }
- async #run () {
- this.#running = true
- const queue = this.#queue
- while (!queue.isEmpty()) {
- const node = queue.shift()
- // wait pending promise
- if (node.promise !== null) {
- await node.promise
- }
- // write
- this.#socket.write(node.frame, node.callback)
- // cleanup
- node.callback = node.frame = null
- }
- this.#running = false
- }
+function createRestError(messageOrResponse, response) {
+ const resp = typeof messageOrResponse === "string" ? response : messageOrResponse;
+ const internalError = resp.body?.error ?? resp.body;
+ const message = typeof messageOrResponse === "string"
+ ? messageOrResponse
+ : (internalError?.message ?? `Unexpected status code: ${resp.status}`);
+ return new RestError(message, {
+ statusCode: statusCodeToNumber(resp.status),
+ code: internalError?.code,
+ request: resp.request,
+ response: toPipelineResponse(resp),
+ });
}
-
-function createFrame (data, hint) {
- return new WebsocketFrameSend(toBuffer(data, hint)).createFrame(hint === sendHints.string ? opcodes.TEXT : opcodes.BINARY)
+function toPipelineResponse(response) {
+ return {
+ headers: createHttpHeaders(response.headers),
+ request: response.request,
+ status: statusCodeToNumber(response.status) ?? -1,
+ };
}
-
-function toBuffer (data, hint) {
- switch (hint) {
- case sendHints.string:
- return Buffer.from(data)
- case sendHints.arrayBuffer:
- case sendHints.blob:
- return new FastBuffer(data)
- case sendHints.typedArray:
- return new FastBuffer(data.buffer, data.byteOffset, data.byteLength)
- }
+function statusCodeToNumber(statusCode) {
+ const status = Number.parseInt(statusCode);
+ return Number.isNaN(status) ? undefined : status;
}
+//# sourceMappingURL=restError.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/index.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
-module.exports = { SendQueue }
-
-
-/***/ }),
-
-/***/ 2456:
-/***/ ((module) => {
-module.exports = {
- kWebSocketURL: Symbol('url'),
- kReadyState: Symbol('ready state'),
- kController: Symbol('controller'),
- kResponse: Symbol('response'),
- kBinaryType: Symbol('binary type'),
- kSentClose: Symbol('sent close'),
- kReceivedClose: Symbol('received close'),
- kByteParser: Symbol('byte parser')
-}
-/***/ }),
-/***/ 5673:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const { kReadyState, kController, kResponse, kBinaryType, kWebSocketURL } = __nccwpck_require__(2456)
-const { states, opcodes } = __nccwpck_require__(1816)
-const { ErrorEvent, createFastMessageEvent } = __nccwpck_require__(44)
-const { isUtf8 } = __nccwpck_require__(4573)
-const { collectASequenceOfCodePointsFast, removeHTTPWhitespace } = __nccwpck_require__(980)
-/* globals Blob */
+//# sourceMappingURL=index.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/pipeline.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
/**
- * @param {import('./websocket').WebSocket} ws
- * @returns {boolean}
+ * Creates a totally empty pipeline.
+ * Useful for testing or creating a custom one.
*/
-function isConnecting (ws) {
- // If the WebSocket connection is not yet established, and the connection
- // is not yet closed, then the WebSocket connection is in the CONNECTING state.
- return ws[kReadyState] === states.CONNECTING
+function esm_pipeline_createEmptyPipeline() {
+ return pipeline_createEmptyPipeline();
}
+//# sourceMappingURL=pipeline.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/logger/internal.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+
+//# sourceMappingURL=internal.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/logger/dist/esm/index.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+const esm_context = createLoggerContext({
+ logLevelEnvVarName: "AZURE_LOG_LEVEL",
+ namespace: "azure",
+});
/**
- * @param {import('./websocket').WebSocket} ws
- * @returns {boolean}
+ * The AzureLogger provides a mechanism for overriding where logs are output to.
+ * By default, logs are sent to stderr.
+ * Override the `log` method to redirect logs to another location.
*/
-function isEstablished (ws) {
- // If the server's response is validated as provided for above, it is
- // said that _The WebSocket Connection is Established_ and that the
- // WebSocket Connection is in the OPEN state.
- return ws[kReadyState] === states.OPEN
-}
-
+const AzureLogger = esm_context.logger;
/**
- * @param {import('./websocket').WebSocket} ws
- * @returns {boolean}
+ * Immediately enables logging at the specified log level. If no level is specified, logging is disabled.
+ * @param level - The log level to enable for logging.
+ * Options from most verbose to least verbose are:
+ * - verbose
+ * - info
+ * - warning
+ * - error
*/
-function isClosing (ws) {
- // Upon either sending or receiving a Close control frame, it is said
- // that _The WebSocket Closing Handshake is Started_ and that the
- // WebSocket connection is in the CLOSING state.
- return ws[kReadyState] === states.CLOSING
+function esm_setLogLevel(level) {
+ esm_context.setLogLevel(level);
}
-
/**
- * @param {import('./websocket').WebSocket} ws
- * @returns {boolean}
+ * Retrieves the currently specified log level.
*/
-function isClosed (ws) {
- return ws[kReadyState] === states.CLOSED
+function esm_getLogLevel() {
+ return esm_context.getLogLevel();
}
-
/**
- * @see https://dom.spec.whatwg.org/#concept-event-fire
- * @param {string} e
- * @param {EventTarget} target
- * @param {(...args: ConstructorParameters) => Event} eventFactory
- * @param {EventInit | undefined} eventInitDict
+ * Creates a logger for use by the Azure SDKs that inherits from `AzureLogger`.
+ * @param namespace - The name of the SDK package.
+ * @hidden
*/
-function fireEvent (e, target, eventFactory = (type, init) => new Event(type, init), eventInitDict = {}) {
- // 1. If eventConstructor is not given, then let eventConstructor be Event.
-
- // 2. Let event be the result of creating an event given eventConstructor,
- // in the relevant realm of target.
- // 3. Initialize event’s type attribute to e.
- const event = eventFactory(e, eventInitDict)
-
- // 4. Initialize any other IDL attributes of event as described in the
- // invocation of this algorithm.
-
- // 5. Return the result of dispatching event at target, with legacy target
- // override flag set if set.
- target.dispatchEvent(event)
+function esm_createClientLogger(namespace) {
+ return esm_context.createClientLogger(namespace);
}
+//# sourceMappingURL=index.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/log.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+const esm_log_logger = esm_createClientLogger("core-rest-pipeline");
+//# sourceMappingURL=log.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/policies/agentPolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
/**
- * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
- * @param {import('./websocket').WebSocket} ws
- * @param {number} type Opcode
- * @param {Buffer} data application data
+ * Name of the Agent Policy
*/
-function websocketMessageReceived (ws, type, data) {
- // 1. If ready state is not OPEN (1), then return.
- if (ws[kReadyState] !== states.OPEN) {
- return
- }
-
- // 2. Let dataForEvent be determined by switching on type and binary type:
- let dataForEvent
-
- if (type === opcodes.TEXT) {
- // -> type indicates that the data is Text
- // a new DOMString containing data
- try {
- dataForEvent = utf8Decode(data)
- } catch {
- failWebsocketConnection(ws, 'Received invalid UTF-8 in text frame.')
- return
- }
- } else if (type === opcodes.BINARY) {
- if (ws[kBinaryType] === 'blob') {
- // -> type indicates that the data is Binary and binary type is "blob"
- // a new Blob object, created in the relevant Realm of the WebSocket
- // object, that represents data as its raw data
- dataForEvent = new Blob([data])
- } else {
- // -> type indicates that the data is Binary and binary type is "arraybuffer"
- // a new ArrayBuffer object, created in the relevant Realm of the
- // WebSocket object, whose contents are data
- dataForEvent = toArrayBuffer(data)
- }
- }
-
- // 3. Fire an event named message at the WebSocket object, using MessageEvent,
- // with the origin attribute initialized to the serialization of the WebSocket
- // object’s url's origin, and the data attribute initialized to dataForEvent.
- fireEvent('message', ws, createFastMessageEvent, {
- origin: ws[kWebSocketURL].origin,
- data: dataForEvent
- })
-}
-
-function toArrayBuffer (buffer) {
- if (buffer.byteLength === buffer.buffer.byteLength) {
- return buffer.buffer
- }
- return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength)
-}
-
+const agentPolicyName = "agentPolicy";
/**
- * @see https://datatracker.ietf.org/doc/html/rfc6455
- * @see https://datatracker.ietf.org/doc/html/rfc2616
- * @see https://bugs.chromium.org/p/chromium/issues/detail?id=398407
- * @param {string} protocol
+ * Gets a pipeline policy that sets http.agent
*/
-function isValidSubprotocol (protocol) {
- // If present, this value indicates one
- // or more comma-separated subprotocol the client wishes to speak,
- // ordered by preference. The elements that comprise this value
- // MUST be non-empty strings with characters in the range U+0021 to
- // U+007E not including separator characters as defined in
- // [RFC2616] and MUST all be unique strings.
- if (protocol.length === 0) {
- return false
- }
-
- for (let i = 0; i < protocol.length; ++i) {
- const code = protocol.charCodeAt(i)
-
- if (
- code < 0x21 || // CTL, contains SP (0x20) and HT (0x09)
- code > 0x7E ||
- code === 0x22 || // "
- code === 0x28 || // (
- code === 0x29 || // )
- code === 0x2C || // ,
- code === 0x2F || // /
- code === 0x3A || // :
- code === 0x3B || // ;
- code === 0x3C || // <
- code === 0x3D || // =
- code === 0x3E || // >
- code === 0x3F || // ?
- code === 0x40 || // @
- code === 0x5B || // [
- code === 0x5C || // \
- code === 0x5D || // ]
- code === 0x7B || // {
- code === 0x7D // }
- ) {
- return false
- }
- }
-
- return true
+function agentPolicy_agentPolicy(agent) {
+ return {
+ name: agentPolicyName,
+ sendRequest: async (req, next) => {
+ // Users may define an agent on the request, honor it over the client level one
+ if (!req.agent) {
+ req.agent = agent;
+ }
+ return next(req);
+ },
+ };
}
-
+//# sourceMappingURL=agentPolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/policies/decompressResponsePolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
/**
- * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7-4
- * @param {number} code
+ * The programmatic identifier of the decompressResponsePolicy.
*/
-function isValidStatusCode (code) {
- if (code >= 1000 && code < 1015) {
- return (
- code !== 1004 && // reserved
- code !== 1005 && // "MUST NOT be set as a status code"
- code !== 1006 // "MUST NOT be set as a status code"
- )
- }
-
- return code >= 3000 && code <= 4999
-}
-
+const decompressResponsePolicyName = "decompressResponsePolicy";
/**
- * @param {import('./websocket').WebSocket} ws
- * @param {string|undefined} reason
+ * A policy to enable response decompression according to Accept-Encoding header
+ * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding
*/
-function failWebsocketConnection (ws, reason) {
- const { [kController]: controller, [kResponse]: response } = ws
-
- controller.abort()
+function decompressResponsePolicy_decompressResponsePolicy() {
+ return {
+ name: decompressResponsePolicyName,
+ async sendRequest(request, next) {
+ // HEAD requests have no body
+ if (request.method !== "HEAD") {
+ request.headers.set("Accept-Encoding", "gzip,deflate");
+ }
+ return next(request);
+ },
+ };
+}
+//# sourceMappingURL=decompressResponsePolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/policies/exponentialRetryPolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- if (response?.socket && !response.socket.destroyed) {
- response.socket.destroy()
- }
- if (reason) {
- // TODO: process.nextTick
- fireEvent('error', ws, (type, init) => new ErrorEvent(type, init), {
- error: new Error(reason),
- message: reason
- })
- }
-}
/**
- * @see https://datatracker.ietf.org/doc/html/rfc6455#section-5.5
- * @param {number} opcode
+ * The programmatic identifier of the exponentialRetryPolicy.
*/
-function isControlFrame (opcode) {
- return (
- opcode === opcodes.CLOSE ||
- opcode === opcodes.PING ||
- opcode === opcodes.PONG
- )
-}
-
-function isContinuationFrame (opcode) {
- return opcode === opcodes.CONTINUATION
+const exponentialRetryPolicyName = "exponentialRetryPolicy";
+/**
+ * A policy that attempts to retry requests while introducing an exponentially increasing delay.
+ * @param options - Options that configure retry logic.
+ */
+function exponentialRetryPolicy(options = {}) {
+ return retryPolicy([
+ exponentialRetryStrategy({
+ ...options,
+ ignoreSystemErrors: true,
+ }),
+ ], {
+ maxRetries: options.maxRetries ?? DEFAULT_RETRY_POLICY_COUNT,
+ });
}
+//# sourceMappingURL=exponentialRetryPolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/policies/systemErrorRetryPolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
-function isTextBinaryFrame (opcode) {
- return opcode === opcodes.TEXT || opcode === opcodes.BINARY
-}
-function isValidOpcode (opcode) {
- return isTextBinaryFrame(opcode) || isContinuationFrame(opcode) || isControlFrame(opcode)
-}
/**
- * Parses a Sec-WebSocket-Extensions header value.
- * @param {string} extensions
- * @returns {Map}
+ * Name of the {@link systemErrorRetryPolicy}
*/
-// TODO(@Uzlopak, @KhafraDev): make compliant https://datatracker.ietf.org/doc/html/rfc6455#section-9.1
-function parseExtensions (extensions) {
- const position = { position: 0 }
- const extensionList = new Map()
-
- while (position.position < extensions.length) {
- const pair = collectASequenceOfCodePointsFast(';', extensions, position)
- const [name, value = ''] = pair.split('=')
-
- extensionList.set(
- removeHTTPWhitespace(name, true, false),
- removeHTTPWhitespace(value, false, true)
- )
+const systemErrorRetryPolicyName = "systemErrorRetryPolicy";
+/**
+ * A retry policy that specifically seeks to handle errors in the
+ * underlying transport layer (e.g. DNS lookup failures) rather than
+ * retryable error codes from the server itself.
+ * @param options - Options that customize the policy.
+ */
+function systemErrorRetryPolicy(options = {}) {
+ return {
+ name: systemErrorRetryPolicyName,
+ sendRequest: retryPolicy([
+ exponentialRetryStrategy({
+ ...options,
+ ignoreHttpStatusCodes: true,
+ }),
+ ], {
+ maxRetries: options.maxRetries ?? DEFAULT_RETRY_POLICY_COUNT,
+ }).sendRequest,
+ };
+}
+//# sourceMappingURL=systemErrorRetryPolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/policies/throttlingRetryPolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- position.position++
- }
- return extensionList
-}
/**
- * @see https://www.rfc-editor.org/rfc/rfc7692#section-7.1.2.2
- * @description "client-max-window-bits = 1*DIGIT"
- * @param {string} value
+ * Name of the {@link throttlingRetryPolicy}
*/
-function isValidClientWindowBits (value) {
- for (let i = 0; i < value.length; i++) {
- const byte = value.charCodeAt(i)
-
- if (byte < 0x30 || byte > 0x39) {
- return false
- }
- }
-
- return true
+const throttlingRetryPolicyName = "throttlingRetryPolicy";
+/**
+ * A policy that retries when the server sends a 429 response with a Retry-After header.
+ *
+ * To learn more, please refer to
+ * https://learn.microsoft.com/azure/azure-resource-manager/resource-manager-request-limits,
+ * https://learn.microsoft.com/azure/azure-subscription-service-limits and
+ * https://learn.microsoft.com/azure/virtual-machines/troubleshooting/troubleshooting-throttling-errors
+ *
+ * @param options - Options that configure retry logic.
+ */
+function throttlingRetryPolicy(options = {}) {
+ return {
+ name: throttlingRetryPolicyName,
+ sendRequest: retryPolicy([throttlingRetryStrategy()], {
+ maxRetries: options.maxRetries ?? DEFAULT_RETRY_POLICY_COUNT,
+ }).sendRequest,
+ };
}
-
-// https://nodejs.org/api/intl.html#detecting-internationalization-support
-const hasIntl = typeof process.versions.icu === 'string'
-const fatalDecoder = hasIntl ? new TextDecoder('utf-8', { fatal: true }) : undefined
-
+//# sourceMappingURL=throttlingRetryPolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/policies/tlsPolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
/**
- * Converts a Buffer to utf-8, even on platforms without icu.
- * @param {Buffer} buffer
+ * Name of the TLS Policy
*/
-const utf8Decode = hasIntl
- ? fatalDecoder.decode.bind(fatalDecoder)
- : function (buffer) {
- if (isUtf8(buffer)) {
- return buffer.toString('utf-8')
- }
- throw new TypeError('Invalid utf-8 received.')
- }
-
-module.exports = {
- isConnecting,
- isEstablished,
- isClosing,
- isClosed,
- fireEvent,
- isValidSubprotocol,
- isValidStatusCode,
- failWebsocketConnection,
- websocketMessageReceived,
- utf8Decode,
- isControlFrame,
- isContinuationFrame,
- isTextBinaryFrame,
- isValidOpcode,
- parseExtensions,
- isValidClientWindowBits
+const tlsPolicyName = "tlsPolicy";
+/**
+ * Gets a pipeline policy that adds the client certificate to the HttpClient agent for authentication.
+ */
+function tlsPolicy_tlsPolicy(tlsSettings) {
+ return {
+ name: tlsPolicyName,
+ sendRequest: async (req, next) => {
+ // Users may define a request tlsSettings, honor those over the client level one
+ if (!req.tlsSettings) {
+ req.tlsSettings = tlsSettings;
+ }
+ return next(req);
+ },
+ };
}
+//# sourceMappingURL=tlsPolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/policies/internal.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
-/***/ }),
-/***/ 5366:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const { webidl } = __nccwpck_require__(253)
-const { URLSerializer } = __nccwpck_require__(980)
-const { environmentSettingsObject } = __nccwpck_require__(4296)
-const { staticPropertyDescriptors, states, sentCloseFrameState, sendHints } = __nccwpck_require__(1816)
-const {
- kWebSocketURL,
- kReadyState,
- kController,
- kBinaryType,
- kResponse,
- kSentClose,
- kByteParser
-} = __nccwpck_require__(2456)
-const {
- isConnecting,
- isEstablished,
- isClosing,
- isValidSubprotocol,
- fireEvent
-} = __nccwpck_require__(5673)
-const { establishWebSocketConnection, closeWebSocketConnection } = __nccwpck_require__(2569)
-const { ByteParser } = __nccwpck_require__(4588)
-const { kEnumerableProperty, isBlobLike } = __nccwpck_require__(1544)
-const { getGlobalDispatcher } = __nccwpck_require__(5837)
-const { types } = __nccwpck_require__(7975)
-const { ErrorEvent, CloseEvent } = __nccwpck_require__(44)
-const { SendQueue } = __nccwpck_require__(228)
-// https://websockets.spec.whatwg.org/#interface-definition
-class WebSocket extends EventTarget {
- #events = {
- open: null,
- error: null,
- close: null,
- message: null
- }
- #bufferedAmount = 0
- #protocol = ''
- #extensions = ''
- /** @type {SendQueue} */
- #sendQueue
- /**
- * @param {string} url
- * @param {string|string[]} protocols
- */
- constructor (url, protocols = []) {
- super()
- webidl.util.markAsUncloneable(this)
- const prefix = 'WebSocket constructor'
- webidl.argumentLengthCheck(arguments, 1, prefix)
- const options = webidl.converters['DOMString or sequence or WebSocketInit'](protocols, prefix, 'options')
- url = webidl.converters.USVString(url, prefix, 'url')
- protocols = options.protocols
+//# sourceMappingURL=internal.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/policies/logPolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- // 1. Let baseURL be this's relevant settings object's API base URL.
- const baseURL = environmentSettingsObject.settingsObject.baseUrl
- // 1. Let urlRecord be the result of applying the URL parser to url with baseURL.
- let urlRecord
+/**
+ * The programmatic identifier of the logPolicy.
+ */
+const logPolicy_logPolicyName = (/* unused pure expression or super */ null && (tspLogPolicyName));
+/**
+ * A policy that logs all requests and responses.
+ * @param options - Options to configure logPolicy.
+ */
+function policies_logPolicy_logPolicy(options = {}) {
+ return logPolicy_logPolicy({
+ logger: esm_log_logger.info,
+ ...options,
+ });
+}
+//# sourceMappingURL=logPolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/policies/redirectPolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- try {
- urlRecord = new URL(url, baseURL)
- } catch (e) {
- // 3. If urlRecord is failure, then throw a "SyntaxError" DOMException.
- throw new DOMException(e, 'SyntaxError')
- }
+/**
+ * The programmatic identifier of the redirectPolicy.
+ */
+const redirectPolicy_redirectPolicyName = redirectPolicyName;
+/**
+ * A policy to follow Location headers from the server in order
+ * to support server-side redirection.
+ * In the browser, this policy is not used.
+ * @param options - Options to control policy behavior.
+ */
+function policies_redirectPolicy_redirectPolicy(options = {}) {
+ return redirectPolicy_redirectPolicy(options);
+}
+//# sourceMappingURL=redirectPolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/util/userAgentPlatform.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- // 4. If urlRecord’s scheme is "http", then set urlRecord’s scheme to "ws".
- if (urlRecord.protocol === 'http:') {
- urlRecord.protocol = 'ws:'
- } else if (urlRecord.protocol === 'https:') {
- // 5. Otherwise, if urlRecord’s scheme is "https", set urlRecord’s scheme to "wss".
- urlRecord.protocol = 'wss:'
- }
- // 6. If urlRecord’s scheme is not "ws" or "wss", then throw a "SyntaxError" DOMException.
- if (urlRecord.protocol !== 'ws:' && urlRecord.protocol !== 'wss:') {
- throw new DOMException(
- `Expected a ws: or wss: protocol, got ${urlRecord.protocol}`,
- 'SyntaxError'
- )
+/**
+ * @internal
+ */
+function userAgentPlatform_getHeaderName() {
+ return "User-Agent";
+}
+/**
+ * @internal
+ */
+async function util_userAgentPlatform_setPlatformSpecificData(map) {
+ if (external_node_process_ && external_node_process_.versions) {
+ const osInfo = `${external_node_os_.type()} ${external_node_os_.release()}; ${external_node_os_.arch()}`;
+ const versions = external_node_process_.versions;
+ if (versions.bun) {
+ map.set("Bun", `${versions.bun} (${osInfo})`);
+ }
+ else if (versions.deno) {
+ map.set("Deno", `${versions.deno} (${osInfo})`);
+ }
+ else if (versions.node) {
+ map.set("Node", `${versions.node} (${osInfo})`);
+ }
}
+}
+//# sourceMappingURL=userAgentPlatform.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/constants.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+const esm_constants_SDK_VERSION = "1.22.3";
+const esm_constants_DEFAULT_RETRY_POLICY_COUNT = 3;
+//# sourceMappingURL=constants.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/util/userAgent.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- // 7. If urlRecord’s fragment is non-null, then throw a "SyntaxError"
- // DOMException.
- if (urlRecord.hash || urlRecord.href.endsWith('#')) {
- throw new DOMException('Got fragment', 'SyntaxError')
- }
- // 8. If protocols is a string, set protocols to a sequence consisting
- // of just that string.
- if (typeof protocols === 'string') {
- protocols = [protocols]
+function userAgent_getUserAgentString(telemetryInfo) {
+ const parts = [];
+ for (const [key, value] of telemetryInfo) {
+ const token = value ? `${key}/${value}` : key;
+ parts.push(token);
}
+ return parts.join(" ");
+}
+/**
+ * @internal
+ */
+function userAgent_getUserAgentHeaderName() {
+ return userAgentPlatform_getHeaderName();
+}
+/**
+ * @internal
+ */
+async function util_userAgent_getUserAgentValue(prefix) {
+ const runtimeInfo = new Map();
+ runtimeInfo.set("core-rest-pipeline", esm_constants_SDK_VERSION);
+ await util_userAgentPlatform_setPlatformSpecificData(runtimeInfo);
+ const defaultAgent = userAgent_getUserAgentString(runtimeInfo);
+ const userAgentValue = prefix ? `${prefix} ${defaultAgent}` : defaultAgent;
+ return userAgentValue;
+}
+//# sourceMappingURL=userAgent.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/policies/userAgentPolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- // 9. If any of the values in protocols occur more than once or otherwise
- // fail to match the requirements for elements that comprise the value
- // of `Sec-WebSocket-Protocol` fields as defined by The WebSocket
- // protocol, then throw a "SyntaxError" DOMException.
- if (protocols.length !== new Set(protocols.map(p => p.toLowerCase())).size) {
- throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError')
- }
-
- if (protocols.length > 0 && !protocols.every(p => isValidSubprotocol(p))) {
- throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError')
- }
-
- // 10. Set this's url to urlRecord.
- this[kWebSocketURL] = new URL(urlRecord.href)
-
- // 11. Let client be this's relevant settings object.
- const client = environmentSettingsObject.settingsObject
-
- // 12. Run this step in parallel:
-
- // 1. Establish a WebSocket connection given urlRecord, protocols,
- // and client.
- this[kController] = establishWebSocketConnection(
- urlRecord,
- protocols,
- client,
- this,
- (response, extensions) => this.#onConnectionEstablished(response, extensions),
- options
- )
-
- // Each WebSocket object has an associated ready state, which is a
- // number representing the state of the connection. Initially it must
- // be CONNECTING (0).
- this[kReadyState] = WebSocket.CONNECTING
-
- this[kSentClose] = sentCloseFrameState.NOT_SENT
-
- // The extensions attribute must initially return the empty string.
+const userAgentPolicy_UserAgentHeaderName = userAgent_getUserAgentHeaderName();
+/**
+ * The programmatic identifier of the userAgentPolicy.
+ */
+const userAgentPolicy_userAgentPolicyName = "userAgentPolicy";
+/**
+ * A policy that sets the User-Agent header (or equivalent) to reflect
+ * the library version.
+ * @param options - Options to customize the user agent value.
+ */
+function policies_userAgentPolicy_userAgentPolicy(options = {}) {
+ const userAgentValue = util_userAgent_getUserAgentValue(options.userAgentPrefix);
+ return {
+ name: userAgentPolicy_userAgentPolicyName,
+ async sendRequest(request, next) {
+ if (!request.headers.has(userAgentPolicy_UserAgentHeaderName)) {
+ request.headers.set(userAgentPolicy_UserAgentHeaderName, await userAgentValue);
+ }
+ return next(request);
+ },
+ };
+}
+//# sourceMappingURL=userAgentPolicy.js.map
+// EXTERNAL MODULE: external "node:crypto"
+var external_node_crypto_ = __nccwpck_require__(7598);
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/util/sha256.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- // The protocol attribute must initially return the empty string.
+/**
+ * Generates a SHA-256 HMAC signature.
+ * @param key - The HMAC key represented as a base64 string, used to generate the cryptographic HMAC hash.
+ * @param stringToSign - The data to be signed.
+ * @param encoding - The textual encoding to use for the returned HMAC digest.
+ */
+async function computeSha256Hmac(key, stringToSign, encoding) {
+ const decodedKey = Buffer.from(key, "base64");
+ return createHmac("sha256", decodedKey).update(stringToSign).digest(encoding);
+}
+/**
+ * Generates a SHA-256 hash.
+ * @param content - The data to be included in the hash.
+ * @param encoding - The textual encoding to use for the returned hash.
+ */
+async function computeSha256Hash(content, encoding) {
+ return createHash("sha256").update(content).digest(encoding);
+}
+//# sourceMappingURL=sha256.js.map
+;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/util/internal.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- // Each WebSocket object has an associated binary type, which is a
- // BinaryType. Initially it must be "blob".
- this[kBinaryType] = 'blob'
- }
- /**
- * @see https://websockets.spec.whatwg.org/#dom-websocket-close
- * @param {number|undefined} code
- * @param {string|undefined} reason
- */
- close (code = undefined, reason = undefined) {
- webidl.brandCheck(this, WebSocket)
- const prefix = 'WebSocket.close'
- if (code !== undefined) {
- code = webidl.converters['unsigned short'](code, prefix, 'code', { clamp: true })
- }
- if (reason !== undefined) {
- reason = webidl.converters.USVString(reason, prefix, 'reason')
- }
- // 1. If code is present, but is neither an integer equal to 1000 nor an
- // integer in the range 3000 to 4999, inclusive, throw an
- // "InvalidAccessError" DOMException.
- if (code !== undefined) {
- if (code !== 1000 && (code < 3000 || code > 4999)) {
- throw new DOMException('invalid code', 'InvalidAccessError')
- }
- }
- let reasonByteLength = 0
- // 2. If reason is present, then run these substeps:
- if (reason !== undefined) {
- // 1. Let reasonBytes be the result of encoding reason.
- // 2. If reasonBytes is longer than 123 bytes, then throw a
- // "SyntaxError" DOMException.
- reasonByteLength = Buffer.byteLength(reason)
- if (reasonByteLength > 123) {
- throw new DOMException(
- `Reason must be less than 123 bytes; received ${reasonByteLength}`,
- 'SyntaxError'
- )
- }
+//# sourceMappingURL=internal.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/esm/AbortError.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+/**
+ * This error is thrown when an asynchronous operation has been aborted.
+ * Check for this error by testing the `name` that the name property of the
+ * error matches `"AbortError"`.
+ *
+ * @example
+ * ```ts
+ * const controller = new AbortController();
+ * controller.abort();
+ * try {
+ * doAsyncWork(controller.signal)
+ * } catch (e) {
+ * if (e.name === 'AbortError') {
+ * // handle abort error here.
+ * }
+ * }
+ * ```
+ */
+class AbortError_AbortError extends Error {
+ constructor(message) {
+ super(message);
+ this.name = "AbortError";
}
+}
+//# sourceMappingURL=AbortError.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/esm/index.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
- // 3. Run the first matching steps from the following list:
- closeWebSocketConnection(this, code, reason, reasonByteLength)
- }
+//# sourceMappingURL=index.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-util/dist/esm/createAbortablePromise.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- /**
- * @see https://websockets.spec.whatwg.org/#dom-websocket-send
- * @param {NodeJS.TypedArray|ArrayBuffer|Blob|string} data
- */
- send (data) {
- webidl.brandCheck(this, WebSocket)
+/**
+ * Creates an abortable promise.
+ * @param buildPromise - A function that takes the resolve and reject functions as parameters.
+ * @param options - The options for the abortable promise.
+ * @returns A promise that can be aborted.
+ */
+function createAbortablePromise(buildPromise, options) {
+ const { cleanupBeforeAbort, abortSignal, abortErrorMsg } = options ?? {};
+ return new Promise((resolve, reject) => {
+ function rejectOnAbort() {
+ reject(new AbortError_AbortError(abortErrorMsg ?? "The operation was aborted."));
+ }
+ function removeListeners() {
+ abortSignal?.removeEventListener("abort", onAbort);
+ }
+ function onAbort() {
+ cleanupBeforeAbort?.();
+ removeListeners();
+ rejectOnAbort();
+ }
+ if (abortSignal?.aborted) {
+ return rejectOnAbort();
+ }
+ try {
+ buildPromise((x) => {
+ removeListeners();
+ resolve(x);
+ }, (x) => {
+ removeListeners();
+ reject(x);
+ });
+ }
+ catch (err) {
+ reject(err);
+ }
+ abortSignal?.addEventListener("abort", onAbort);
+ });
+}
+//# sourceMappingURL=createAbortablePromise.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-util/dist/esm/delay.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- const prefix = 'WebSocket.send'
- webidl.argumentLengthCheck(arguments, 1, prefix)
- data = webidl.converters.WebSocketSendData(data, prefix, 'data')
+const delay_StandardAbortMessage = "The delay was aborted.";
+/**
+ * A wrapper for setTimeout that resolves a promise after timeInMs milliseconds.
+ * @param timeInMs - The number of milliseconds to be delayed.
+ * @param options - The options for delay - currently abort options
+ * @returns Promise that is resolved after timeInMs
+ */
+function delay_delay(timeInMs, options) {
+ let token;
+ const { abortSignal, abortErrorMsg } = options ?? {};
+ return createAbortablePromise((resolve) => {
+ token = setTimeout(resolve, timeInMs);
+ }, {
+ cleanupBeforeAbort: () => clearTimeout(token),
+ abortSignal,
+ abortErrorMsg: abortErrorMsg ?? delay_StandardAbortMessage,
+ });
+}
+/**
+ * Calculates the delay interval for retry attempts using exponential delay with jitter.
+ * @param retryAttempt - The current retry attempt number.
+ * @param config - The exponential retry configuration.
+ * @returns An object containing the calculated retry delay.
+ */
+function delay_calculateRetryDelay(retryAttempt, config) {
+ // Exponentially increase the delay each time
+ const exponentialDelay = config.retryDelayInMs * Math.pow(2, retryAttempt);
+ // Don't let the delay exceed the maximum
+ const clampedDelay = Math.min(config.maxRetryDelayInMs, exponentialDelay);
+ // Allow the final value to have some "jitter" (within 50% of the delay size) so
+ // that retries across multiple clients don't occur simultaneously.
+ const retryAfterInMs = clampedDelay / 2 + getRandomIntegerInclusive(0, clampedDelay / 2);
+ return { retryAfterInMs };
+}
+//# sourceMappingURL=delay.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-util/dist/esm/error.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- // 1. If this's ready state is CONNECTING, then throw an
- // "InvalidStateError" DOMException.
- if (isConnecting(this)) {
- throw new DOMException('Sent before connected.', 'InvalidStateError')
+/**
+ * Given what is thought to be an error object, return the message if possible.
+ * If the message is missing, returns a stringified version of the input.
+ * @param e - Something thrown from a try block
+ * @returns The error message or a string of the input
+ */
+function getErrorMessage(e) {
+ if (isError(e)) {
+ return e.message;
}
-
- // 2. Run the appropriate set of steps from the following list:
- // https://datatracker.ietf.org/doc/html/rfc6455#section-6.1
- // https://datatracker.ietf.org/doc/html/rfc6455#section-5.2
-
- if (!isEstablished(this) || isClosing(this)) {
- return
+ else {
+ let stringified;
+ try {
+ if (typeof e === "object" && e) {
+ stringified = JSON.stringify(e);
+ }
+ else {
+ stringified = String(e);
+ }
+ }
+ catch (err) {
+ stringified = "[unable to stringify input]";
+ }
+ return `Unknown error ${stringified}`;
}
+}
+//# sourceMappingURL=error.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-util/dist/esm/index.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- // If data is a string
- if (typeof data === 'string') {
- // If the WebSocket connection is established and the WebSocket
- // closing handshake has not yet started, then the user agent
- // must send a WebSocket Message comprised of the data argument
- // using a text frame opcode; if the data cannot be sent, e.g.
- // because it would need to be buffered but the buffer is full,
- // the user agent must flag the WebSocket as full and then close
- // the WebSocket connection. Any invocation of this method with a
- // string argument that does not throw an exception must increase
- // the bufferedAmount attribute by the number of bytes needed to
- // express the argument as UTF-8.
-
- const length = Buffer.byteLength(data)
- this.#bufferedAmount += length
- this.#sendQueue.add(data, () => {
- this.#bufferedAmount -= length
- }, sendHints.string)
- } else if (types.isArrayBuffer(data)) {
- // If the WebSocket connection is established, and the WebSocket
- // closing handshake has not yet started, then the user agent must
- // send a WebSocket Message comprised of data using a binary frame
- // opcode; if the data cannot be sent, e.g. because it would need
- // to be buffered but the buffer is full, the user agent must flag
- // the WebSocket as full and then close the WebSocket connection.
- // The data to be sent is the data stored in the buffer described
- // by the ArrayBuffer object. Any invocation of this method with an
- // ArrayBuffer argument that does not throw an exception must
- // increase the bufferedAmount attribute by the length of the
- // ArrayBuffer in bytes.
- this.#bufferedAmount += data.byteLength
- this.#sendQueue.add(data, () => {
- this.#bufferedAmount -= data.byteLength
- }, sendHints.arrayBuffer)
- } else if (ArrayBuffer.isView(data)) {
- // If the WebSocket connection is established, and the WebSocket
- // closing handshake has not yet started, then the user agent must
- // send a WebSocket Message comprised of data using a binary frame
- // opcode; if the data cannot be sent, e.g. because it would need to
- // be buffered but the buffer is full, the user agent must flag the
- // WebSocket as full and then close the WebSocket connection. The
- // data to be sent is the data stored in the section of the buffer
- // described by the ArrayBuffer object that data references. Any
- // invocation of this method with this kind of argument that does
- // not throw an exception must increase the bufferedAmount attribute
- // by the length of data’s buffer in bytes.
- this.#bufferedAmount += data.byteLength
- this.#sendQueue.add(data, () => {
- this.#bufferedAmount -= data.byteLength
- }, sendHints.typedArray)
- } else if (isBlobLike(data)) {
- // If the WebSocket connection is established, and the WebSocket
- // closing handshake has not yet started, then the user agent must
- // send a WebSocket Message comprised of data using a binary frame
- // opcode; if the data cannot be sent, e.g. because it would need to
- // be buffered but the buffer is full, the user agent must flag the
- // WebSocket as full and then close the WebSocket connection. The data
- // to be sent is the raw data represented by the Blob object. Any
- // invocation of this method with a Blob argument that does not throw
- // an exception must increase the bufferedAmount attribute by the size
- // of the Blob object’s raw data, in bytes.
- this.#bufferedAmount += data.size
- this.#sendQueue.add(data, () => {
- this.#bufferedAmount -= data.size
- }, sendHints.blob)
- }
- }
- get readyState () {
- webidl.brandCheck(this, WebSocket)
+/**
+ * Calculates the delay interval for retry attempts using exponential delay with jitter.
+ *
+ * @param retryAttempt - The current retry attempt number.
+ *
+ * @param config - The exponential retry configuration.
+ *
+ * @returns An object containing the calculated retry delay.
+ */
+function esm_calculateRetryDelay(retryAttempt, config) {
+ return tspRuntime.calculateRetryDelay(retryAttempt, config);
+}
+/**
+ * Generates a SHA-256 hash.
+ *
+ * @param content - The data to be included in the hash.
+ *
+ * @param encoding - The textual encoding to use for the returned hash.
+ */
+function esm_computeSha256Hash(content, encoding) {
+ return tspRuntime.computeSha256Hash(content, encoding);
+}
+/**
+ * Generates a SHA-256 HMAC signature.
+ *
+ * @param key - The HMAC key represented as a base64 string, used to generate the cryptographic HMAC hash.
+ *
+ * @param stringToSign - The data to be signed.
+ *
+ * @param encoding - The textual encoding to use for the returned HMAC digest.
+ */
+function esm_computeSha256Hmac(key, stringToSign, encoding) {
+ return tspRuntime.computeSha256Hmac(key, stringToSign, encoding);
+}
+/**
+ * Returns a random integer value between a lower and upper bound, inclusive of both bounds. Note that this uses Math.random and isn't secure. If you need to use this for any kind of security purpose, find a better source of random.
+ *
+ * @param min - The smallest integer value allowed.
+ *
+ * @param max - The largest integer value allowed.
+ */
+function esm_getRandomIntegerInclusive(min, max) {
+ return tspRuntime.getRandomIntegerInclusive(min, max);
+}
+/**
+ * Typeguard for an error object shape (has name and message)
+ *
+ * @param e - Something caught by a catch clause.
+ */
+function esm_isError(e) {
+ return isError(e);
+}
+/**
+ * Helper to determine when an input is a generic JS object.
+ *
+ * @returns true when input is an object type that is not null, Array, RegExp, or Date.
+ */
+function esm_isObject(input) {
+ return tspRuntime.isObject(input);
+}
+/**
+ * Generated Universally Unique Identifier
+ *
+ * @returns RFC4122 v4 UUID.
+ */
+function esm_randomUUID() {
+ return randomUUID();
+}
+/**
+ * A constant that indicates whether the environment the code is running is a Web Browser.
+ */
+const esm_isBrowser = isBrowser;
+/**
+ * A constant that indicates whether the environment the code is running is Bun.sh.
+ */
+const esm_isBun = isBun;
+/**
+ * A constant that indicates whether the environment the code is running is Deno.
+ */
+const esm_isDeno = isDeno;
+/**
+ * A constant that indicates whether the environment the code is running is a Node.js compatible environment.
+ *
+ * @deprecated
+ *
+ * Use `isNodeLike` instead.
+ */
+const isNode = checkEnvironment_isNodeLike;
+/**
+ * A constant that indicates whether the environment the code is running is a Node.js compatible environment.
+ */
+const esm_isNodeLike = checkEnvironment_isNodeLike;
+/**
+ * A constant that indicates whether the environment the code is running is Node.JS.
+ */
+const esm_isNodeRuntime = isNodeRuntime;
+/**
+ * A constant that indicates whether the environment the code is running is in React-Native.
+ */
+const esm_isReactNative = isReactNative;
+/**
+ * A constant that indicates whether the environment the code is running is a Web Worker.
+ */
+const esm_isWebWorker = isWebWorker;
+/**
+ * The helper that transforms bytes with specific character encoding into string
+ * @param bytes - the uint8array bytes
+ * @param format - the format we use to encode the byte
+ * @returns a string of the encoded string
+ */
+function esm_uint8ArrayToString(bytes, format) {
+ return tspRuntime.uint8ArrayToString(bytes, format);
+}
+/**
+ * The helper that transforms string to specific character encoded bytes array.
+ * @param value - the string to be converted
+ * @param format - the format we use to decode the value
+ * @returns a uint8array
+ */
+function esm_stringToUint8Array(value, format) {
+ return tspRuntime.stringToUint8Array(value, format);
+}
+//# sourceMappingURL=index.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/util/file.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- // The readyState getter steps are to return this's ready state.
- return this[kReadyState]
- }
-
- get bufferedAmount () {
- webidl.brandCheck(this, WebSocket)
-
- return this.#bufferedAmount
- }
-
- get url () {
- webidl.brandCheck(this, WebSocket)
-
- // The url getter steps are to return this's url, serialized.
- return URLSerializer(this[kWebSocketURL])
- }
-
- get extensions () {
- webidl.brandCheck(this, WebSocket)
-
- return this.#extensions
- }
-
- get protocol () {
- webidl.brandCheck(this, WebSocket)
-
- return this.#protocol
- }
-
- get onopen () {
- webidl.brandCheck(this, WebSocket)
-
- return this.#events.open
- }
-
- set onopen (fn) {
- webidl.brandCheck(this, WebSocket)
-
- if (this.#events.open) {
- this.removeEventListener('open', this.#events.open)
- }
-
- if (typeof fn === 'function') {
- this.#events.open = fn
- this.addEventListener('open', fn)
- } else {
- this.#events.open = null
- }
- }
-
- get onerror () {
- webidl.brandCheck(this, WebSocket)
-
- return this.#events.error
- }
-
- set onerror (fn) {
- webidl.brandCheck(this, WebSocket)
-
- if (this.#events.error) {
- this.removeEventListener('error', this.#events.error)
- }
-
- if (typeof fn === 'function') {
- this.#events.error = fn
- this.addEventListener('error', fn)
- } else {
- this.#events.error = null
- }
- }
-
- get onclose () {
- webidl.brandCheck(this, WebSocket)
-
- return this.#events.close
- }
-
- set onclose (fn) {
- webidl.brandCheck(this, WebSocket)
-
- if (this.#events.close) {
- this.removeEventListener('close', this.#events.close)
- }
-
- if (typeof fn === 'function') {
- this.#events.close = fn
- this.addEventListener('close', fn)
- } else {
- this.#events.close = null
- }
- }
-
- get onmessage () {
- webidl.brandCheck(this, WebSocket)
-
- return this.#events.message
- }
-
- set onmessage (fn) {
- webidl.brandCheck(this, WebSocket)
-
- if (this.#events.message) {
- this.removeEventListener('message', this.#events.message)
+function file_isNodeReadableStream(x) {
+ return Boolean(x && typeof x["pipe"] === "function");
+}
+const unimplementedMethods = {
+ arrayBuffer: () => {
+ throw new Error("Not implemented");
+ },
+ bytes: () => {
+ throw new Error("Not implemented");
+ },
+ slice: () => {
+ throw new Error("Not implemented");
+ },
+ text: () => {
+ throw new Error("Not implemented");
+ },
+};
+/**
+ * Private symbol used as key on objects created using createFile containing the
+ * original source of the file object.
+ *
+ * This is used in Node to access the original Node stream without using Blob#stream, which
+ * returns a web stream. This is done to avoid a couple of bugs to do with Blob#stream and
+ * Readable#to/fromWeb in Node versions we support:
+ * - https://github.com/nodejs/node/issues/42694 (fixed in Node 18.14)
+ * - https://github.com/nodejs/node/issues/48916 (fixed in Node 20.6)
+ *
+ * Once these versions are no longer supported, we may be able to stop doing this.
+ *
+ * @internal
+ */
+const rawContent = Symbol("rawContent");
+/**
+ * Type guard to check if a given object is a blob-like object with a raw content property.
+ */
+function hasRawContent(x) {
+ return typeof x[rawContent] === "function";
+}
+/**
+ * Extract the raw content from a given blob-like object. If the input was created using createFile
+ * or createFileFromStream, the exact content passed into createFile/createFileFromStream will be used.
+ * For true instances of Blob and File, returns the actual blob.
+ *
+ * @internal
+ */
+function getRawContent(blob) {
+ if (hasRawContent(blob)) {
+ return blob[rawContent]();
}
-
- if (typeof fn === 'function') {
- this.#events.message = fn
- this.addEventListener('message', fn)
- } else {
- this.#events.message = null
+ else {
+ return blob;
}
- }
-
- get binaryType () {
- webidl.brandCheck(this, WebSocket)
-
- return this[kBinaryType]
- }
-
- set binaryType (type) {
- webidl.brandCheck(this, WebSocket)
-
- if (type !== 'blob' && type !== 'arraybuffer') {
- this[kBinaryType] = 'blob'
- } else {
- this[kBinaryType] = type
+}
+/**
+ * Create an object that implements the File interface. This object is intended to be
+ * passed into RequestBodyType.formData, and is not guaranteed to work as expected in
+ * other situations.
+ *
+ * Use this function to:
+ * - Create a File object for use in RequestBodyType.formData in environments where the
+ * global File object is unavailable.
+ * - Create a File-like object from a readable stream without reading the stream into memory.
+ *
+ * @param stream - the content of the file as a callback returning a stream. When a File object made using createFile is
+ * passed in a request's form data map, the stream will not be read into memory
+ * and instead will be streamed when the request is made. In the event of a retry, the
+ * stream needs to be read again, so this callback SHOULD return a fresh stream if possible.
+ * @param name - the name of the file.
+ * @param options - optional metadata about the file, e.g. file name, file size, MIME type.
+ */
+function createFileFromStream(stream, name, options = {}) {
+ return {
+ ...unimplementedMethods,
+ type: options.type ?? "",
+ lastModified: options.lastModified ?? new Date().getTime(),
+ webkitRelativePath: options.webkitRelativePath ?? "",
+ size: options.size ?? -1,
+ name,
+ stream: () => {
+ const s = stream();
+ if (file_isNodeReadableStream(s)) {
+ throw new Error("Not supported: a Node stream was provided as input to createFileFromStream.");
+ }
+ return s;
+ },
+ [rawContent]: stream,
+ };
+}
+/**
+ * Create an object that implements the File interface. This object is intended to be
+ * passed into RequestBodyType.formData, and is not guaranteed to work as expected in
+ * other situations.
+ *
+ * Use this function create a File object for use in RequestBodyType.formData in environments where the global File object is unavailable.
+ *
+ * @param content - the content of the file as a Uint8Array in memory.
+ * @param name - the name of the file.
+ * @param options - optional metadata about the file, e.g. file name, file size, MIME type.
+ */
+function createFile(content, name, options = {}) {
+ if (isNodeLike) {
+ return {
+ ...unimplementedMethods,
+ type: options.type ?? "",
+ lastModified: options.lastModified ?? new Date().getTime(),
+ webkitRelativePath: options.webkitRelativePath ?? "",
+ size: content.byteLength,
+ name,
+ arrayBuffer: async () => content.buffer,
+ stream: () => new Blob([toArrayBuffer(content)]).stream(),
+ [rawContent]: () => content,
+ };
}
- }
-
- /**
- * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
- */
- #onConnectionEstablished (response, parsedExtensions) {
- // processResponse is called when the "response’s header list has been received and initialized."
- // once this happens, the connection is open
- this[kResponse] = response
-
- const parser = new ByteParser(this, parsedExtensions)
- parser.on('drain', onParserDrain)
- parser.on('error', onParserError.bind(this))
-
- response.socket.ws = this
- this[kByteParser] = parser
-
- this.#sendQueue = new SendQueue(response.socket)
-
- // 1. Change the ready state to OPEN (1).
- this[kReadyState] = states.OPEN
-
- // 2. Change the extensions attribute’s value to the extensions in use, if
- // it is not the null value.
- // https://datatracker.ietf.org/doc/html/rfc6455#section-9.1
- const extensions = response.headersList.get('sec-websocket-extensions')
-
- if (extensions !== null) {
- this.#extensions = extensions
+ else {
+ return new File([toArrayBuffer(content)], name, options);
}
-
- // 3. Change the protocol attribute’s value to the subprotocol in use, if
- // it is not the null value.
- // https://datatracker.ietf.org/doc/html/rfc6455#section-1.9
- const protocol = response.headersList.get('sec-websocket-protocol')
-
- if (protocol !== null) {
- this.#protocol = protocol
+}
+function toArrayBuffer(source) {
+ if ("resize" in source.buffer) {
+ // ArrayBuffer
+ return source;
}
-
- // 4. Fire an event named open at the WebSocket object.
- fireEvent('open', this)
- }
+ // SharedArrayBuffer
+ return source.map((x) => x);
}
+//# sourceMappingURL=file.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/policies/multipartPolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
-// https://websockets.spec.whatwg.org/#dom-websocket-connecting
-WebSocket.CONNECTING = WebSocket.prototype.CONNECTING = states.CONNECTING
-// https://websockets.spec.whatwg.org/#dom-websocket-open
-WebSocket.OPEN = WebSocket.prototype.OPEN = states.OPEN
-// https://websockets.spec.whatwg.org/#dom-websocket-closing
-WebSocket.CLOSING = WebSocket.prototype.CLOSING = states.CLOSING
-// https://websockets.spec.whatwg.org/#dom-websocket-closed
-WebSocket.CLOSED = WebSocket.prototype.CLOSED = states.CLOSED
-
-Object.defineProperties(WebSocket.prototype, {
- CONNECTING: staticPropertyDescriptors,
- OPEN: staticPropertyDescriptors,
- CLOSING: staticPropertyDescriptors,
- CLOSED: staticPropertyDescriptors,
- url: kEnumerableProperty,
- readyState: kEnumerableProperty,
- bufferedAmount: kEnumerableProperty,
- onopen: kEnumerableProperty,
- onerror: kEnumerableProperty,
- onclose: kEnumerableProperty,
- close: kEnumerableProperty,
- onmessage: kEnumerableProperty,
- binaryType: kEnumerableProperty,
- send: kEnumerableProperty,
- extensions: kEnumerableProperty,
- protocol: kEnumerableProperty,
- [Symbol.toStringTag]: {
- value: 'WebSocket',
- writable: false,
- enumerable: false,
- configurable: true
- }
-})
-
-Object.defineProperties(WebSocket, {
- CONNECTING: staticPropertyDescriptors,
- OPEN: staticPropertyDescriptors,
- CLOSING: staticPropertyDescriptors,
- CLOSED: staticPropertyDescriptors
-})
-
-webidl.converters['sequence'] = webidl.sequenceConverter(
- webidl.converters.DOMString
-)
-
-webidl.converters['DOMString or sequence'] = function (V, prefix, argument) {
- if (webidl.util.Type(V) === 'Object' && Symbol.iterator in V) {
- return webidl.converters['sequence'](V)
- }
- return webidl.converters.DOMString(V, prefix, argument)
+/**
+ * Name of multipart policy
+ */
+const policies_multipartPolicy_multipartPolicyName = multipartPolicy_multipartPolicyName;
+/**
+ * Pipeline policy for multipart requests
+ */
+function policies_multipartPolicy_multipartPolicy() {
+ const tspPolicy = multipartPolicy_multipartPolicy();
+ return {
+ name: policies_multipartPolicy_multipartPolicyName,
+ sendRequest: async (request, next) => {
+ if (request.multipartBody) {
+ for (const part of request.multipartBody.parts) {
+ if (hasRawContent(part.body)) {
+ part.body = getRawContent(part.body);
+ }
+ }
+ }
+ return tspPolicy.sendRequest(request, next);
+ },
+ };
}
+//# sourceMappingURL=multipartPolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/policies/decompressResponsePolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
-// This implements the proposal made in https://github.com/whatwg/websockets/issues/42
-webidl.converters.WebSocketInit = webidl.dictionaryConverter([
- {
- key: 'protocols',
- converter: webidl.converters['DOMString or sequence'],
- defaultValue: () => new Array(0)
- },
- {
- key: 'dispatcher',
- converter: webidl.converters.any,
- defaultValue: () => getGlobalDispatcher()
- },
- {
- key: 'headers',
- converter: webidl.nullableConverter(webidl.converters.HeadersInit)
- }
-])
-
-webidl.converters['DOMString or sequence or WebSocketInit'] = function (V) {
- if (webidl.util.Type(V) === 'Object' && !(Symbol.iterator in V)) {
- return webidl.converters.WebSocketInit(V)
- }
-
- return { protocols: webidl.converters['DOMString or sequence'](V) }
+/**
+ * The programmatic identifier of the decompressResponsePolicy.
+ */
+const decompressResponsePolicy_decompressResponsePolicyName = decompressResponsePolicyName;
+/**
+ * A policy to enable response decompression according to Accept-Encoding header
+ * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding
+ */
+function policies_decompressResponsePolicy_decompressResponsePolicy() {
+ return decompressResponsePolicy_decompressResponsePolicy();
}
+//# sourceMappingURL=decompressResponsePolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/policies/defaultRetryPolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
-webidl.converters.WebSocketSendData = function (V) {
- if (webidl.util.Type(V) === 'Object') {
- if (isBlobLike(V)) {
- return webidl.converters.Blob(V, { strict: false })
- }
-
- if (ArrayBuffer.isView(V) || types.isArrayBuffer(V)) {
- return webidl.converters.BufferSource(V)
- }
- }
-
- return webidl.converters.USVString(V)
+/**
+ * Name of the {@link defaultRetryPolicy}
+ */
+const defaultRetryPolicy_defaultRetryPolicyName = (/* unused pure expression or super */ null && (tspDefaultRetryPolicyName));
+/**
+ * A policy that retries according to three strategies:
+ * - When the server sends a 429 response with a Retry-After header.
+ * - When there are errors in the underlying transport layer (e.g. DNS lookup failures).
+ * - Or otherwise if the outgoing request fails, it will retry with an exponentially increasing delay.
+ */
+function policies_defaultRetryPolicy_defaultRetryPolicy(options = {}) {
+ return defaultRetryPolicy_defaultRetryPolicy(options);
}
+//# sourceMappingURL=defaultRetryPolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/policies/formDataPolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
-function onParserDrain () {
- this.ws[kResponse].socket.resume()
+/**
+ * The programmatic identifier of the formDataPolicy.
+ */
+const formDataPolicy_formDataPolicyName = (/* unused pure expression or super */ null && (tspFormDataPolicyName));
+/**
+ * A policy that encodes FormData on the request into the body.
+ */
+function policies_formDataPolicy_formDataPolicy() {
+ return formDataPolicy_formDataPolicy();
}
+//# sourceMappingURL=formDataPolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/policies/proxyPolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
-function onParserError (err) {
- let message
- let code
-
- if (err instanceof CloseEvent) {
- message = err.reason
- code = err.code
- } else {
- message = err.message
- }
-
- fireEvent('error', this, () => new ErrorEvent('error', { error: err, message }))
-
- closeWebSocketConnection(this, code)
+/**
+ * The programmatic identifier of the proxyPolicy.
+ */
+const proxyPolicy_proxyPolicyName = (/* unused pure expression or super */ null && (tspProxyPolicyName));
+/**
+ * This method converts a proxy url into `ProxySettings` for use with ProxyPolicy.
+ * If no argument is given, it attempts to parse a proxy URL from the environment
+ * variables `HTTPS_PROXY` or `HTTP_PROXY`.
+ * @param proxyUrl - The url of the proxy to use. May contain authentication information.
+ * @deprecated - Internally this method is no longer necessary when setting proxy information.
+ */
+function proxyPolicy_getDefaultProxySettings(proxyUrl) {
+ return getDefaultProxySettings(proxyUrl);
}
-
-module.exports = {
- WebSocket
+/**
+ * A policy that allows one to apply proxy settings to all requests.
+ * If not passed static settings, they will be retrieved from the HTTPS_PROXY
+ * or HTTP_PROXY environment variables.
+ * @param proxySettings - ProxySettings to use on each request.
+ * @param options - additional settings, for example, custom NO_PROXY patterns
+ */
+function policies_proxyPolicy_proxyPolicy(proxySettings, options) {
+ return proxyPolicy_proxyPolicy(proxySettings, options);
}
-
-
-/***/ }),
-
-/***/ 8110:
-/***/ ((__unused_webpack_module, exports) => {
-
-
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-
+//# sourceMappingURL=proxyPolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/policies/setClientRequestIdPolicy.js
// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-///
-const listenersMap = new WeakMap();
-const abortedMap = new WeakMap();
+// Licensed under the MIT License.
/**
- * An aborter instance implements AbortSignal interface, can abort HTTP requests.
- *
- * - Call AbortSignal.none to create a new AbortSignal instance that cannot be cancelled.
- * Use `AbortSignal.none` when you are required to pass a cancellation token but the operation
- * cannot or will not ever be cancelled.
- *
- * @example
- * Abort without timeout
- * ```ts
- * await doAsyncWork(AbortSignal.none);
- * ```
+ * The programmatic identifier of the setClientRequestIdPolicy.
*/
-class AbortSignal {
- constructor() {
- /**
- * onabort event listener.
- */
- this.onabort = null;
- listenersMap.set(this, []);
- abortedMap.set(this, false);
- }
- /**
- * Status of whether aborted or not.
- *
- * @readonly
- */
- get aborted() {
- if (!abortedMap.has(this)) {
- throw new TypeError("Expected `this` to be an instance of AbortSignal.");
- }
- return abortedMap.get(this);
- }
- /**
- * Creates a new AbortSignal instance that will never be aborted.
- *
- * @readonly
- */
- static get none() {
- return new AbortSignal();
- }
- /**
- * Added new "abort" event listener, only support "abort" event.
- *
- * @param _type - Only support "abort" event
- * @param listener - The listener to be added
- */
- addEventListener(
- // tslint:disable-next-line:variable-name
- _type, listener) {
- if (!listenersMap.has(this)) {
- throw new TypeError("Expected `this` to be an instance of AbortSignal.");
- }
- const listeners = listenersMap.get(this);
- listeners.push(listener);
- }
- /**
- * Remove "abort" event listener, only support "abort" event.
- *
- * @param _type - Only support "abort" event
- * @param listener - The listener to be removed
- */
- removeEventListener(
- // tslint:disable-next-line:variable-name
- _type, listener) {
- if (!listenersMap.has(this)) {
- throw new TypeError("Expected `this` to be an instance of AbortSignal.");
- }
- const listeners = listenersMap.get(this);
- const index = listeners.indexOf(listener);
- if (index > -1) {
- listeners.splice(index, 1);
- }
- }
- /**
- * Dispatches a synthetic event to the AbortSignal.
- */
- dispatchEvent(_event) {
- throw new Error("This is a stub dispatchEvent implementation that should not be used. It only exists for type-checking purposes.");
- }
+const setClientRequestIdPolicyName = "setClientRequestIdPolicy";
+/**
+ * Each PipelineRequest gets a unique id upon creation.
+ * This policy passes that unique id along via an HTTP header to enable better
+ * telemetry and tracing.
+ * @param requestIdHeaderName - The name of the header to pass the request ID to.
+ */
+function setClientRequestIdPolicy(requestIdHeaderName = "x-ms-client-request-id") {
+ return {
+ name: setClientRequestIdPolicyName,
+ async sendRequest(request, next) {
+ if (!request.headers.has(requestIdHeaderName)) {
+ request.headers.set(requestIdHeaderName, request.requestId);
+ }
+ return next(request);
+ },
+ };
}
+//# sourceMappingURL=setClientRequestIdPolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/policies/agentPolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+
/**
- * Helper to trigger an abort event immediately, the onabort and all abort event listeners will be triggered.
- * Will try to trigger abort event for all linked AbortSignal nodes.
- *
- * - If there is a timeout, the timer will be cancelled.
- * - If aborted is true, nothing will happen.
+ * Name of the Agent Policy
+ */
+const agentPolicy_agentPolicyName = (/* unused pure expression or super */ null && (tspAgentPolicyName));
+/**
+ * Gets a pipeline policy that sets http.agent
+ */
+function policies_agentPolicy_agentPolicy(agent) {
+ return agentPolicy_agentPolicy(agent);
+}
+//# sourceMappingURL=agentPolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/policies/tlsPolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+
+/**
+ * Name of the TLS Policy
+ */
+const tlsPolicy_tlsPolicyName = (/* unused pure expression or super */ null && (tspTlsPolicyName));
+/**
+ * Gets a pipeline policy that adds the client certificate to the HttpClient agent for authentication.
+ */
+function policies_tlsPolicy_tlsPolicy(tlsSettings) {
+ return tlsPolicy_tlsPolicy(tlsSettings);
+}
+//# sourceMappingURL=tlsPolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-tracing/dist/esm/tracingContext.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+/** @internal */
+const knownContextKeys = {
+ span: Symbol.for("@azure/core-tracing span"),
+ namespace: Symbol.for("@azure/core-tracing namespace"),
+};
+/**
+ * Creates a new {@link TracingContext} with the given options.
+ * @param options - A set of known keys that may be set on the context.
+ * @returns A new {@link TracingContext} with the given options.
*
* @internal
*/
-// eslint-disable-next-line @azure/azure-sdk/ts-use-interface-parameters
-function abortSignal(signal) {
- if (signal.aborted) {
- return;
+function createTracingContext(options = {}) {
+ let context = new TracingContextImpl(options.parentContext);
+ if (options.span) {
+ context = context.setValue(knownContextKeys.span, options.span);
}
- if (signal.onabort) {
- signal.onabort.call(signal);
+ if (options.namespace) {
+ context = context.setValue(knownContextKeys.namespace, options.namespace);
}
- const listeners = listenersMap.get(signal);
- if (listeners) {
- // Create a copy of listeners so mutations to the array
- // (e.g. via removeListener calls) don't affect the listeners
- // we invoke.
- listeners.slice().forEach((listener) => {
- listener.call(signal, { type: "abort" });
- });
+ return context;
+}
+/** @internal */
+class TracingContextImpl {
+ _contextMap;
+ constructor(initialContext) {
+ this._contextMap =
+ initialContext instanceof TracingContextImpl
+ ? new Map(initialContext._contextMap)
+ : new Map();
+ }
+ setValue(key, value) {
+ const newContext = new TracingContextImpl(this);
+ newContext._contextMap.set(key, value);
+ return newContext;
+ }
+ getValue(key) {
+ return this._contextMap.get(key);
+ }
+ deleteValue(key) {
+ const newContext = new TracingContextImpl(this);
+ newContext._contextMap.delete(key);
+ return newContext;
}
- abortedMap.set(signal, true);
}
+//# sourceMappingURL=tracingContext.js.map
+// EXTERNAL MODULE: ./node_modules/@azure/core-tracing/dist/commonjs/state.js
+var commonjs_state = __nccwpck_require__(8914);
+;// CONCATENATED MODULE: ./node_modules/@azure/core-tracing/dist/esm/state.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+// @ts-expect-error The recommended approach to sharing module state between ESM and CJS.
+// See https://github.com/isaacs/tshy/blob/main/README.md#module-local-state for additional information.
+/**
+ * Defines the shared state between CJS and ESM by re-exporting the CJS state.
+ */
+const state_state = commonjs_state/* state */.w;
+//# sourceMappingURL=state.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-tracing/dist/esm/instrumenter.js
// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+
+
+function createDefaultTracingSpan() {
+ return {
+ end: () => {
+ // noop
+ },
+ isRecording: () => false,
+ recordException: () => {
+ // noop
+ },
+ setAttribute: () => {
+ // noop
+ },
+ setStatus: () => {
+ // noop
+ },
+ addEvent: () => {
+ // noop
+ },
+ };
+}
+function createDefaultInstrumenter() {
+ return {
+ createRequestHeaders: () => {
+ return {};
+ },
+ parseTraceparentHeader: () => {
+ return undefined;
+ },
+ startSpan: (_name, spanOptions) => {
+ return {
+ span: createDefaultTracingSpan(),
+ tracingContext: createTracingContext({ parentContext: spanOptions.tracingContext }),
+ };
+ },
+ withContext(_context, callback, ...callbackArgs) {
+ return callback(...callbackArgs);
+ },
+ };
+}
/**
- * This error is thrown when an asynchronous operation has been aborted.
- * Check for this error by testing the `name` that the name property of the
- * error matches `"AbortError"`.
+ * Extends the Azure SDK with support for a given instrumenter implementation.
*
- * @example
- * ```ts
- * const controller = new AbortController();
- * controller.abort();
- * try {
- * doAsyncWork(controller.signal)
- * } catch (e) {
- * if (e.name === 'AbortError') {
- * // handle abort error here.
- * }
- * }
- * ```
+ * @param instrumenter - The instrumenter implementation to use.
*/
-class AbortError extends Error {
- constructor(message) {
- super(message);
- this.name = "AbortError";
- }
+function useInstrumenter(instrumenter) {
+ state.instrumenterImplementation = instrumenter;
}
/**
- * An AbortController provides an AbortSignal and the associated controls to signal
- * that an asynchronous operation should be aborted.
- *
- * @example
- * Abort an operation when another event fires
- * ```ts
- * const controller = new AbortController();
- * const signal = controller.signal;
- * doAsyncWork(signal);
- * button.addEventListener('click', () => controller.abort());
- * ```
- *
- * @example
- * Share aborter cross multiple operations in 30s
- * ```ts
- * // Upload the same data to 2 different data centers at the same time,
- * // abort another when any of them is finished
- * const controller = AbortController.withTimeout(30 * 1000);
- * doAsyncWork(controller.signal).then(controller.abort);
- * doAsyncWork(controller.signal).then(controller.abort);
- *```
+ * Gets the currently set instrumenter, a No-Op instrumenter by default.
*
- * @example
- * Cascaded aborting
- * ```ts
- * // All operations can't take more than 30 seconds
- * const aborter = Aborter.timeout(30 * 1000);
+ * @returns The currently set instrumenter
+ */
+function getInstrumenter() {
+ if (!state_state.instrumenterImplementation) {
+ state_state.instrumenterImplementation = createDefaultInstrumenter();
+ }
+ return state_state.instrumenterImplementation;
+}
+//# sourceMappingURL=instrumenter.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-tracing/dist/esm/tracingClient.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+
+
+/**
+ * Creates a new tracing client.
*
- * // Following 2 operations can't take more than 25 seconds
- * await doAsyncWork(aborter.withTimeout(25 * 1000));
- * await doAsyncWork(aborter.withTimeout(25 * 1000));
- * ```
+ * @param options - Options used to configure the tracing client.
+ * @returns - An instance of {@link TracingClient}.
*/
-class AbortController {
- // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
- constructor(parentSignals) {
- this._signal = new AbortSignal();
- if (!parentSignals) {
- return;
+function createTracingClient(options) {
+ const { namespace, packageName, packageVersion } = options;
+ function startSpan(name, operationOptions, spanOptions) {
+ const startSpanResult = getInstrumenter().startSpan(name, {
+ ...spanOptions,
+ packageName: packageName,
+ packageVersion: packageVersion,
+ tracingContext: operationOptions?.tracingOptions?.tracingContext,
+ });
+ let tracingContext = startSpanResult.tracingContext;
+ const span = startSpanResult.span;
+ if (!tracingContext.getValue(knownContextKeys.namespace)) {
+ tracingContext = tracingContext.setValue(knownContextKeys.namespace, namespace);
}
- // coerce parentSignals into an array
- if (!Array.isArray(parentSignals)) {
- // eslint-disable-next-line prefer-rest-params
- parentSignals = arguments;
+ span.setAttribute("az.namespace", tracingContext.getValue(knownContextKeys.namespace));
+ const updatedOptions = Object.assign({}, operationOptions, {
+ tracingOptions: { ...operationOptions?.tracingOptions, tracingContext },
+ });
+ return {
+ span,
+ updatedOptions,
+ };
+ }
+ async function withSpan(name, operationOptions, callback, spanOptions) {
+ const { span, updatedOptions } = startSpan(name, operationOptions, spanOptions);
+ try {
+ const result = await withContext(updatedOptions.tracingOptions.tracingContext, () => Promise.resolve(callback(updatedOptions, span)));
+ span.setStatus({ status: "success" });
+ return result;
}
- for (const parentSignal of parentSignals) {
- // if the parent signal has already had abort() called,
- // then call abort on this signal as well.
- if (parentSignal.aborted) {
- this.abort();
- }
- else {
- // when the parent signal aborts, this signal should as well.
- parentSignal.addEventListener("abort", () => {
- this.abort();
- });
- }
+ catch (err) {
+ span.setStatus({ status: "error", error: err });
+ throw err;
+ }
+ finally {
+ span.end();
}
}
- /**
- * The AbortSignal associated with this controller that will signal aborted
- * when the abort method is called on this controller.
- *
- * @readonly
- */
- get signal() {
- return this._signal;
+ function withContext(context, callback, ...callbackArgs) {
+ return getInstrumenter().withContext(context, callback, ...callbackArgs);
}
/**
- * Signal that any operations passed this controller's associated abort signal
- * to cancel any remaining work and throw an `AbortError`.
+ * Parses a traceparent header value into a span identifier.
+ *
+ * @param traceparentHeader - The traceparent header to parse.
+ * @returns An implementation-specific identifier for the span.
*/
- abort() {
- abortSignal(this._signal);
+ function parseTraceparentHeader(traceparentHeader) {
+ return getInstrumenter().parseTraceparentHeader(traceparentHeader);
}
/**
- * Creates a new AbortSignal instance that will abort after the provided ms.
- * @param ms - Elapsed time in milliseconds to trigger an abort.
+ * Creates a set of request headers to propagate tracing information to a backend.
+ *
+ * @param tracingContext - The context containing the span to serialize.
+ * @returns The set of headers to add to a request.
*/
- static timeout(ms) {
- const signal = new AbortSignal();
- const timer = setTimeout(abortSignal, ms, signal);
- // Prevent the active Timer from keeping the Node.js event loop active.
- if (typeof timer.unref === "function") {
- timer.unref();
- }
- return signal;
+ function createRequestHeaders(tracingContext) {
+ return getInstrumenter().createRequestHeaders(tracingContext);
}
+ return {
+ startSpan,
+ withSpan,
+ withContext,
+ parseTraceparentHeader,
+ createRequestHeaders,
+ };
}
+//# sourceMappingURL=tracingClient.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-tracing/dist/esm/index.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
-exports.AbortController = AbortController;
-exports.AbortError = AbortError;
-exports.AbortSignal = AbortSignal;
-//# sourceMappingURL=index.js.map
+//# sourceMappingURL=index.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/restError.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
-/***/ }),
+/**
+ * A custom error type for failed pipeline requests.
+ */
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+const esm_restError_RestError = restError_RestError;
+/**
+ * Typeguard for RestError
+ * @param e - Something caught by a catch clause.
+ */
+function esm_restError_isRestError(e) {
+ return restError_isRestError(e);
+}
+//# sourceMappingURL=restError.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/policies/tracingPolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
-/***/ 5862:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-var __webpack_unused_export__;
-__webpack_unused_export__ = ({ value: true });
-var logger$1 = __nccwpck_require__(6515);
-var abortController = __nccwpck_require__(8110);
-var coreUtil = __nccwpck_require__(7779);
-// Copyright (c) Microsoft Corporation.
-/**
- * The `@azure/logger` configuration for this package.
- * @internal
- */
-const logger = logger$1.createClientLogger("core-lro");
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-/**
- * The default time interval to wait before sending the next polling request.
- */
-const POLL_INTERVAL_IN_MS = 2000;
/**
- * The closed set of terminal states.
+ * The programmatic identifier of the tracingPolicy.
*/
-const terminalStates = ["succeeded", "canceled", "failed"];
-
-// Copyright (c) Microsoft Corporation.
+const tracingPolicyName = "tracingPolicy";
/**
- * Deserializes the state
+ * A simple policy to create OpenTelemetry Spans for each request made by the pipeline
+ * that has SpanOptions with a parent.
+ * Requests made without a parent Span will not be recorded.
+ * @param options - Options to configure the telemetry logged by the tracing policy.
*/
-function deserializeState(serializedState) {
+function tracingPolicy(options = {}) {
+ const userAgentPromise = util_userAgent_getUserAgentValue(options.userAgentPrefix);
+ const sanitizer = new Sanitizer({
+ additionalAllowedQueryParameters: options.additionalAllowedQueryParameters,
+ });
+ const tracingClient = tryCreateTracingClient();
+ return {
+ name: tracingPolicyName,
+ async sendRequest(request, next) {
+ if (!tracingClient) {
+ return next(request);
+ }
+ const userAgent = await userAgentPromise;
+ const spanAttributes = {
+ "http.url": sanitizer.sanitizeUrl(request.url),
+ "http.method": request.method,
+ "http.user_agent": userAgent,
+ requestId: request.requestId,
+ };
+ if (userAgent) {
+ spanAttributes["http.user_agent"] = userAgent;
+ }
+ const { span, tracingContext } = tryCreateSpan(tracingClient, request, spanAttributes) ?? {};
+ if (!span || !tracingContext) {
+ return next(request);
+ }
+ try {
+ const response = await tracingClient.withContext(tracingContext, next, request);
+ tryProcessResponse(span, response);
+ return response;
+ }
+ catch (err) {
+ tryProcessError(span, err);
+ throw err;
+ }
+ },
+ };
+}
+function tryCreateTracingClient() {
try {
- return JSON.parse(serializedState).state;
+ return createTracingClient({
+ namespace: "",
+ packageName: "@azure/core-rest-pipeline",
+ packageVersion: esm_constants_SDK_VERSION,
+ });
}
catch (e) {
- throw new Error(`Unable to deserialize input state: ${serializedState}`);
+ esm_log_logger.warning(`Error when creating the TracingClient: ${getErrorMessage(e)}`);
+ return undefined;
}
}
-function setStateError(inputs) {
- const { state, stateProxy, isOperationError } = inputs;
- return (error) => {
- if (isOperationError(error)) {
- stateProxy.setError(state, error);
- stateProxy.setFailed(state);
+function tryCreateSpan(tracingClient, request, spanAttributes) {
+ try {
+ // As per spec, we do not need to differentiate between HTTP and HTTPS in span name.
+ const { span, updatedOptions } = tracingClient.startSpan(`HTTP ${request.method}`, { tracingOptions: request.tracingOptions }, {
+ spanKind: "client",
+ spanAttributes,
+ });
+ // If the span is not recording, don't do any more work.
+ if (!span.isRecording()) {
+ span.end();
+ return undefined;
}
- throw error;
- };
-}
-function appendReadableErrorMessage(currentMessage, innerMessage) {
- let message = currentMessage;
- if (message.slice(-1) !== ".") {
- message = message + ".";
+ // set headers
+ const headers = tracingClient.createRequestHeaders(updatedOptions.tracingOptions.tracingContext);
+ for (const [key, value] of Object.entries(headers)) {
+ request.headers.set(key, value);
+ }
+ return { span, tracingContext: updatedOptions.tracingOptions.tracingContext };
}
- return message + " " + innerMessage;
-}
-function simplifyError(err) {
- let message = err.message;
- let code = err.code;
- let curErr = err;
- while (curErr.innererror) {
- curErr = curErr.innererror;
- code = curErr.code;
- message = appendReadableErrorMessage(message, curErr.message);
+ catch (e) {
+ esm_log_logger.warning(`Skipping creating a tracing span due to an error: ${getErrorMessage(e)}`);
+ return undefined;
}
- return {
- code,
- message,
- };
}
-function processOperationStatus(result) {
- const { state, stateProxy, status, isDone, processResult, getError, response, setErrorAsResult } = result;
- switch (status) {
- case "succeeded": {
- stateProxy.setSucceeded(state);
- break;
+function tryProcessError(span, error) {
+ try {
+ span.setStatus({
+ status: "error",
+ error: esm_isError(error) ? error : undefined,
+ });
+ if (esm_restError_isRestError(error) && error.statusCode) {
+ span.setAttribute("http.status_code", error.statusCode);
}
- case "failed": {
- const err = getError === null || getError === void 0 ? void 0 : getError(response);
- let postfix = "";
- if (err) {
- const { code, message } = simplifyError(err);
- postfix = `. ${code}. ${message}`;
- }
- const errStr = `The long-running operation has failed${postfix}`;
- stateProxy.setError(state, new Error(errStr));
- stateProxy.setFailed(state);
- logger.warning(errStr);
- break;
+ span.end();
+ }
+ catch (e) {
+ esm_log_logger.warning(`Skipping tracing span processing due to an error: ${getErrorMessage(e)}`);
+ }
+}
+function tryProcessResponse(span, response) {
+ try {
+ span.setAttribute("http.status_code", response.status);
+ const serviceRequestId = response.headers.get("x-ms-request-id");
+ if (serviceRequestId) {
+ span.setAttribute("serviceRequestId", serviceRequestId);
}
- case "canceled": {
- stateProxy.setCanceled(state);
- break;
+ // Per semantic conventions, only set the status to error if the status code is 4xx or 5xx.
+ // Otherwise, the status MUST remain unset.
+ // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
+ if (response.status >= 400) {
+ span.setStatus({
+ status: "error",
+ });
}
+ span.end();
}
- if ((isDone === null || isDone === void 0 ? void 0 : isDone(response, state)) ||
- (isDone === undefined &&
- ["succeeded", "canceled"].concat(setErrorAsResult ? [] : ["failed"]).includes(status))) {
- stateProxy.setResult(state, buildResult({
- response,
- state,
- processResult,
- }));
+ catch (e) {
+ esm_log_logger.warning(`Skipping tracing span processing due to an error: ${getErrorMessage(e)}`);
}
}
-function buildResult(inputs) {
- const { processResult, response, state } = inputs;
- return processResult ? processResult(response, state) : response;
+//# sourceMappingURL=tracingPolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/util/wrapAbortSignal.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+/**
+ * Creates a native AbortSignal which reflects the state of the provided AbortSignalLike.
+ * If the AbortSignalLike is already a native AbortSignal, it is returned as is.
+ * @param abortSignalLike - The AbortSignalLike to wrap.
+ * @returns - An object containing the native AbortSignal and an optional cleanup function. The cleanup function should be called when the AbortSignal is no longer needed.
+ */
+function wrapAbortSignalLike(abortSignalLike) {
+ if (abortSignalLike instanceof AbortSignal) {
+ return { abortSignal: abortSignalLike };
+ }
+ if (abortSignalLike.aborted) {
+ return { abortSignal: AbortSignal.abort(abortSignalLike.reason) };
+ }
+ const controller = new AbortController();
+ let needsCleanup = true;
+ function cleanup() {
+ if (needsCleanup) {
+ abortSignalLike.removeEventListener("abort", listener);
+ needsCleanup = false;
+ }
+ }
+ function listener() {
+ controller.abort(abortSignalLike.reason);
+ cleanup();
+ }
+ abortSignalLike.addEventListener("abort", listener);
+ return { abortSignal: controller.signal, cleanup };
}
+//# sourceMappingURL=wrapAbortSignal.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/policies/wrapAbortSignalLikePolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+
+const wrapAbortSignalLikePolicyName = "wrapAbortSignalLikePolicy";
/**
- * Initiates the long-running operation.
+ * Policy that ensure that any AbortSignalLike is wrapped in a native AbortSignal for processing by the pipeline.
+ * Since the ts-http-runtime expects a native AbortSignal, this policy is used to ensure that any AbortSignalLike is wrapped in a native AbortSignal.
+ *
+ * @returns - created policy
*/
-async function initOperation(inputs) {
- const { init, stateProxy, processResult, getOperationStatus, withOperationLocation, setErrorAsResult, } = inputs;
- const { operationLocation, resourceLocation, metadata, response } = await init();
- if (operationLocation)
- withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(operationLocation, false);
- const config = {
- metadata,
- operationLocation,
- resourceLocation,
+function wrapAbortSignalLikePolicy() {
+ return {
+ name: wrapAbortSignalLikePolicyName,
+ sendRequest: async (request, next) => {
+ if (!request.abortSignal) {
+ return next(request);
+ }
+ const { abortSignal, cleanup } = wrapAbortSignalLike(request.abortSignal);
+ request.abortSignal = abortSignal;
+ try {
+ return await next(request);
+ }
+ finally {
+ cleanup?.();
+ }
+ },
};
- logger.verbose(`LRO: Operation description:`, config);
- const state = stateProxy.initState(config);
- const status = getOperationStatus({ response, state, operationLocation });
- processOperationStatus({ state, status, stateProxy, response, setErrorAsResult, processResult });
- return state;
}
-async function pollOperationHelper(inputs) {
- const { poll, state, stateProxy, operationLocation, getOperationStatus, getResourceLocation, isOperationError, options, } = inputs;
- const response = await poll(operationLocation, options).catch(setStateError({
- state,
- stateProxy,
- isOperationError,
- }));
- const status = getOperationStatus(response, state);
- logger.verbose(`LRO: Status:\n\tPolling from: ${state.config.operationLocation}\n\tOperation status: ${status}\n\tPolling status: ${terminalStates.includes(status) ? "Stopped" : "Running"}`);
- if (status === "succeeded") {
- const resourceLocation = getResourceLocation(response, state);
- if (resourceLocation !== undefined) {
- return {
- response: await poll(resourceLocation).catch(setStateError({ state, stateProxy, isOperationError })),
- status,
- };
+//# sourceMappingURL=wrapAbortSignalLikePolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/createPipelineFromOptions.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+/**
+ * Create a new pipeline with a default set of customizable policies.
+ * @param options - Options to configure a custom pipeline.
+ */
+function esm_createPipelineFromOptions_createPipelineFromOptions(options) {
+ const pipeline = esm_pipeline_createEmptyPipeline();
+ if (esm_isNodeLike) {
+ if (options.agent) {
+ pipeline.addPolicy(policies_agentPolicy_agentPolicy(options.agent));
}
+ if (options.tlsOptions) {
+ pipeline.addPolicy(policies_tlsPolicy_tlsPolicy(options.tlsOptions));
+ }
+ pipeline.addPolicy(policies_proxyPolicy_proxyPolicy(options.proxyOptions));
+ pipeline.addPolicy(policies_decompressResponsePolicy_decompressResponsePolicy());
}
- return { response, status };
+ pipeline.addPolicy(wrapAbortSignalLikePolicy());
+ pipeline.addPolicy(policies_formDataPolicy_formDataPolicy(), { beforePolicies: [policies_multipartPolicy_multipartPolicyName] });
+ pipeline.addPolicy(policies_userAgentPolicy_userAgentPolicy(options.userAgentOptions));
+ pipeline.addPolicy(setClientRequestIdPolicy(options.telemetryOptions?.clientRequestIdHeaderName));
+ // The multipart policy is added after policies with no phase, so that
+ // policies can be added between it and formDataPolicy to modify
+ // properties (e.g., making the boundary constant in recorded tests).
+ pipeline.addPolicy(policies_multipartPolicy_multipartPolicy(), { afterPhase: "Deserialize" });
+ pipeline.addPolicy(policies_defaultRetryPolicy_defaultRetryPolicy(options.retryOptions), { phase: "Retry" });
+ pipeline.addPolicy(tracingPolicy({ ...options.userAgentOptions, ...options.loggingOptions }), {
+ afterPhase: "Retry",
+ });
+ if (esm_isNodeLike) {
+ // Both XHR and Fetch expect to handle redirects automatically,
+ // so only include this policy when we're in Node.
+ pipeline.addPolicy(policies_redirectPolicy_redirectPolicy(options.redirectOptions), { afterPhase: "Retry" });
+ }
+ pipeline.addPolicy(policies_logPolicy_logPolicy(options.loggingOptions), { afterPhase: "Sign" });
+ return pipeline;
}
-/** Polls the long-running operation. */
-async function pollOperation(inputs) {
- const { poll, state, stateProxy, options, getOperationStatus, getResourceLocation, getOperationLocation, isOperationError, withOperationLocation, getPollingInterval, processResult, getError, updateState, setDelay, isDone, setErrorAsResult, } = inputs;
- const { operationLocation } = state.config;
- if (operationLocation !== undefined) {
- const { response, status } = await pollOperationHelper({
- poll,
- getOperationStatus,
- state,
- stateProxy,
- operationLocation,
- getResourceLocation,
- isOperationError,
- options,
- });
- processOperationStatus({
- status,
- response,
- state,
- stateProxy,
- isDone,
- processResult,
- getError,
- setErrorAsResult,
- });
- if (!terminalStates.includes(status)) {
- const intervalInMs = getPollingInterval === null || getPollingInterval === void 0 ? void 0 : getPollingInterval(response);
- if (intervalInMs)
- setDelay(intervalInMs);
- const location = getOperationLocation === null || getOperationLocation === void 0 ? void 0 : getOperationLocation(response, state);
- if (location !== undefined) {
- const isUpdated = operationLocation !== location;
- state.config.operationLocation = location;
- withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(location, isUpdated);
+//# sourceMappingURL=createPipelineFromOptions.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/defaultHttpClient.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+
+
+/**
+ * Create the correct HttpClient for the current environment.
+ */
+function esm_defaultHttpClient_createDefaultHttpClient() {
+ const client = defaultHttpClient_createDefaultHttpClient();
+ return {
+ async sendRequest(request) {
+ // we wrap any AbortSignalLike here since the TypeSpec runtime expects a native AbortSignal.
+ // 99% of the time, this should be a no-op since a native AbortSignal is passed in.
+ const { abortSignal, cleanup } = request.abortSignal
+ ? wrapAbortSignalLike(request.abortSignal)
+ : {};
+ try {
+ request.abortSignal = abortSignal;
+ return await client.sendRequest(request);
}
- else
- withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(operationLocation, false);
- }
- updateState === null || updateState === void 0 ? void 0 : updateState(state, response);
- }
+ finally {
+ cleanup?.();
+ }
+ },
+ };
}
+//# sourceMappingURL=defaultHttpClient.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/httpHeaders.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+/**
+ * Creates an object that satisfies the `HttpHeaders` interface.
+ * @param rawHeaders - A simple object representing initial headers
+ */
+function esm_httpHeaders_createHttpHeaders(rawHeaders) {
+ return httpHeaders_createHttpHeaders(rawHeaders);
+}
+//# sourceMappingURL=httpHeaders.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/pipelineRequest.js
// Copyright (c) Microsoft Corporation.
-function getOperationLocationPollingUrl(inputs) {
- const { azureAsyncOperation, operationLocation } = inputs;
- return operationLocation !== null && operationLocation !== void 0 ? operationLocation : azureAsyncOperation;
+// Licensed under the MIT License.
+
+/**
+ * Creates a new pipeline request with the given options.
+ * This method is to allow for the easy setting of default values and not required.
+ * @param options - The options to create the request with.
+ */
+function esm_pipelineRequest_createPipelineRequest(options) {
+ // Cast required due to difference between ts-http-runtime requiring AbortSignal while core-rest-pipeline allows
+ // the more generic AbortSignalLike. The wrapAbortSignalLike pipeline policy will take care of ensuring that any AbortSignalLike in the request
+ // is converted into a true AbortSignal.
+ return pipelineRequest_createPipelineRequest(options);
}
-function getLocationHeader(rawResponse) {
- return rawResponse.headers["location"];
+//# sourceMappingURL=pipelineRequest.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/policies/exponentialRetryPolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+
+/**
+ * The programmatic identifier of the exponentialRetryPolicy.
+ */
+const exponentialRetryPolicy_exponentialRetryPolicyName = (/* unused pure expression or super */ null && (tspExponentialRetryPolicyName));
+/**
+ * A policy that attempts to retry requests while introducing an exponentially increasing delay.
+ * @param options - Options that configure retry logic.
+ */
+function exponentialRetryPolicy_exponentialRetryPolicy(options = {}) {
+ return tspExponentialRetryPolicy(options);
}
-function getOperationLocationHeader(rawResponse) {
- return rawResponse.headers["operation-location"];
+//# sourceMappingURL=exponentialRetryPolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/policies/systemErrorRetryPolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+
+/**
+ * Name of the {@link systemErrorRetryPolicy}
+ */
+const systemErrorRetryPolicy_systemErrorRetryPolicyName = (/* unused pure expression or super */ null && (tspSystemErrorRetryPolicyName));
+/**
+ * A retry policy that specifically seeks to handle errors in the
+ * underlying transport layer (e.g. DNS lookup failures) rather than
+ * retryable error codes from the server itself.
+ * @param options - Options that customize the policy.
+ */
+function systemErrorRetryPolicy_systemErrorRetryPolicy(options = {}) {
+ return tspSystemErrorRetryPolicy(options);
}
-function getAzureAsyncOperationHeader(rawResponse) {
- return rawResponse.headers["azure-asyncoperation"];
+//# sourceMappingURL=systemErrorRetryPolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/policies/throttlingRetryPolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+
+/**
+ * Name of the {@link throttlingRetryPolicy}
+ */
+const throttlingRetryPolicy_throttlingRetryPolicyName = (/* unused pure expression or super */ null && (tspThrottlingRetryPolicyName));
+/**
+ * A policy that retries when the server sends a 429 response with a Retry-After header.
+ *
+ * To learn more, please refer to
+ * https://learn.microsoft.com/azure/azure-resource-manager/resource-manager-request-limits,
+ * https://learn.microsoft.com/azure/azure-subscription-service-limits and
+ * https://learn.microsoft.com/azure/virtual-machines/troubleshooting/troubleshooting-throttling-errors
+ *
+ * @param options - Options that configure retry logic.
+ */
+function throttlingRetryPolicy_throttlingRetryPolicy(options = {}) {
+ return tspThrottlingRetryPolicy(options);
}
-function findResourceLocation(inputs) {
- var _a;
- const { location, requestMethod, requestPath, resourceLocationConfig } = inputs;
- switch (requestMethod) {
- case "PUT": {
- return requestPath;
- }
- case "DELETE": {
- return undefined;
- }
- case "PATCH": {
- return (_a = getDefault()) !== null && _a !== void 0 ? _a : requestPath;
- }
- default: {
- return getDefault();
- }
- }
- function getDefault() {
- switch (resourceLocationConfig) {
- case "azure-async-operation": {
- return undefined;
+//# sourceMappingURL=throttlingRetryPolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/policies/retryPolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+
+
+
+const retryPolicy_retryPolicyLogger = esm_createClientLogger("core-rest-pipeline retryPolicy");
+/**
+ * retryPolicy is a generic policy to enable retrying requests when certain conditions are met
+ */
+function policies_retryPolicy_retryPolicy(strategies, options = { maxRetries: DEFAULT_RETRY_POLICY_COUNT }) {
+ // Cast is required since the TSP runtime retry strategy type is slightly different
+ // very deep down (using real AbortSignal vs. AbortSignalLike in RestError).
+ // In practice the difference doesn't actually matter.
+ return tspRetryPolicy(strategies, {
+ logger: retryPolicy_retryPolicyLogger,
+ ...options,
+ });
+}
+//# sourceMappingURL=retryPolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/util/tokenCycler.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+
+// Default options for the cycler if none are provided
+const DEFAULT_CYCLER_OPTIONS = {
+ forcedRefreshWindowInMs: 1000, // Force waiting for a refresh 1s before the token expires
+ retryIntervalInMs: 3000, // Allow refresh attempts every 3s
+ refreshWindowInMs: 1000 * 60 * 2, // Start refreshing 2m before expiry
+};
+/**
+ * Converts an an unreliable access token getter (which may resolve with null)
+ * into an AccessTokenGetter by retrying the unreliable getter in a regular
+ * interval.
+ *
+ * @param getAccessToken - A function that produces a promise of an access token that may fail by returning null.
+ * @param retryIntervalInMs - The time (in milliseconds) to wait between retry attempts.
+ * @param refreshTimeout - The timestamp after which the refresh attempt will fail, throwing an exception.
+ * @returns - A promise that, if it resolves, will resolve with an access token.
+ */
+async function beginRefresh(getAccessToken, retryIntervalInMs, refreshTimeout) {
+ // This wrapper handles exceptions gracefully as long as we haven't exceeded
+ // the timeout.
+ async function tryGetAccessToken() {
+ if (Date.now() < refreshTimeout) {
+ try {
+ return await getAccessToken();
}
- case "original-uri": {
- return requestPath;
+ catch {
+ return null;
}
- case "location":
- default: {
- return location;
+ }
+ else {
+ const finalToken = await getAccessToken();
+ // Timeout is up, so throw if it's still null
+ if (finalToken === null) {
+ throw new Error("Failed to refresh access token.");
}
+ return finalToken;
}
}
-}
-function inferLroMode(inputs) {
- const { rawResponse, requestMethod, requestPath, resourceLocationConfig } = inputs;
- const operationLocation = getOperationLocationHeader(rawResponse);
- const azureAsyncOperation = getAzureAsyncOperationHeader(rawResponse);
- const pollingUrl = getOperationLocationPollingUrl({ operationLocation, azureAsyncOperation });
- const location = getLocationHeader(rawResponse);
- const normalizedRequestMethod = requestMethod === null || requestMethod === void 0 ? void 0 : requestMethod.toLocaleUpperCase();
- if (pollingUrl !== undefined) {
- return {
- mode: "OperationLocation",
- operationLocation: pollingUrl,
- resourceLocation: findResourceLocation({
- requestMethod: normalizedRequestMethod,
- location,
- requestPath,
- resourceLocationConfig,
- }),
- };
+ let token = await tryGetAccessToken();
+ while (token === null) {
+ await delay_delay(retryIntervalInMs);
+ token = await tryGetAccessToken();
}
- else if (location !== undefined) {
- return {
- mode: "ResourceLocation",
- operationLocation: location,
- };
- }
- else if (normalizedRequestMethod === "PUT" && requestPath) {
- return {
- mode: "Body",
- operationLocation: requestPath,
- };
- }
- else {
- return undefined;
- }
-}
-function transformStatus(inputs) {
- const { status, statusCode } = inputs;
- if (typeof status !== "string" && status !== undefined) {
- throw new Error(`Polling was unsuccessful. Expected status to have a string value or no value but it has instead: ${status}. This doesn't necessarily indicate the operation has failed. Check your Azure subscription or resource status for more information.`);
- }
- switch (status === null || status === void 0 ? void 0 : status.toLocaleLowerCase()) {
- case undefined:
- return toOperationStatus(statusCode);
- case "succeeded":
- return "succeeded";
- case "failed":
- return "failed";
- case "running":
- case "accepted":
- case "started":
- case "canceling":
- case "cancelling":
- return "running";
- case "canceled":
- case "cancelled":
- return "canceled";
- default: {
- logger.verbose(`LRO: unrecognized operation status: ${status}`);
- return status;
- }
- }
-}
-function getStatus(rawResponse) {
- var _a;
- const { status } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {};
- return transformStatus({ status, statusCode: rawResponse.statusCode });
-}
-function getProvisioningState(rawResponse) {
- var _a, _b;
- const { properties, provisioningState } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {};
- const status = (_b = properties === null || properties === void 0 ? void 0 : properties.provisioningState) !== null && _b !== void 0 ? _b : provisioningState;
- return transformStatus({ status, statusCode: rawResponse.statusCode });
-}
-function toOperationStatus(statusCode) {
- if (statusCode === 202) {
- return "running";
- }
- else if (statusCode < 300) {
- return "succeeded";
- }
- else {
- return "failed";
- }
-}
-function parseRetryAfter({ rawResponse }) {
- const retryAfter = rawResponse.headers["retry-after"];
- if (retryAfter !== undefined) {
- // Retry-After header value is either in HTTP date format, or in seconds
- const retryAfterInSeconds = parseInt(retryAfter);
- return isNaN(retryAfterInSeconds)
- ? calculatePollingIntervalFromDate(new Date(retryAfter))
- : retryAfterInSeconds * 1000;
- }
- return undefined;
-}
-function getErrorFromResponse(response) {
- const error = response.flatResponse.error;
- if (!error) {
- logger.warning(`The long-running operation failed but there is no error property in the response's body`);
- return;
- }
- if (!error.code || !error.message) {
- logger.warning(`The long-running operation failed but the error property in the response's body doesn't contain code or message`);
- return;
- }
- return error;
-}
-function calculatePollingIntervalFromDate(retryAfterDate) {
- const timeNow = Math.floor(new Date().getTime());
- const retryAfterTime = retryAfterDate.getTime();
- if (timeNow < retryAfterTime) {
- return retryAfterTime - timeNow;
- }
- return undefined;
-}
-function getStatusFromInitialResponse(inputs) {
- const { response, state, operationLocation } = inputs;
- function helper() {
- var _a;
- const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"];
- switch (mode) {
- case undefined:
- return toOperationStatus(response.rawResponse.statusCode);
- case "Body":
- return getOperationStatus(response, state);
- default:
- return "running";
- }
- }
- const status = helper();
- return status === "running" && operationLocation === undefined ? "succeeded" : status;
+ return token;
}
/**
- * Initiates the long-running operation.
+ * Creates a token cycler from a credential, scopes, and optional settings.
+ *
+ * A token cycler represents a way to reliably retrieve a valid access token
+ * from a TokenCredential. It will handle initializing the token, refreshing it
+ * when it nears expiration, and synchronizes refresh attempts to avoid
+ * concurrency hazards.
+ *
+ * @param credential - the underlying TokenCredential that provides the access
+ * token
+ * @param tokenCyclerOptions - optionally override default settings for the cycler
+ *
+ * @returns - a function that reliably produces a valid access token
*/
-async function initHttpOperation(inputs) {
- const { stateProxy, resourceLocationConfig, processResult, lro, setErrorAsResult } = inputs;
- return initOperation({
- init: async () => {
- const response = await lro.sendInitialRequest();
- const config = inferLroMode({
- rawResponse: response.rawResponse,
- requestPath: lro.requestPath,
- requestMethod: lro.requestMethod,
- resourceLocationConfig,
- });
- return Object.assign({ response, operationLocation: config === null || config === void 0 ? void 0 : config.operationLocation, resourceLocation: config === null || config === void 0 ? void 0 : config.resourceLocation }, ((config === null || config === void 0 ? void 0 : config.mode) ? { metadata: { mode: config.mode } } : {}));
+function tokenCycler_createTokenCycler(credential, tokenCyclerOptions) {
+ let refreshWorker = null;
+ let token = null;
+ let tenantId;
+ const options = {
+ ...DEFAULT_CYCLER_OPTIONS,
+ ...tokenCyclerOptions,
+ };
+ /**
+ * This little holder defines several predicates that we use to construct
+ * the rules of refreshing the token.
+ */
+ const cycler = {
+ /**
+ * Produces true if a refresh job is currently in progress.
+ */
+ get isRefreshing() {
+ return refreshWorker !== null;
},
- stateProxy,
- processResult: processResult
- ? ({ flatResponse }, state) => processResult(flatResponse, state)
- : ({ flatResponse }) => flatResponse,
- getOperationStatus: getStatusFromInitialResponse,
- setErrorAsResult,
- });
-}
-function getOperationLocation({ rawResponse }, state) {
- var _a;
- const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"];
- switch (mode) {
- case "OperationLocation": {
- return getOperationLocationPollingUrl({
- operationLocation: getOperationLocationHeader(rawResponse),
- azureAsyncOperation: getAzureAsyncOperationHeader(rawResponse),
+ /**
+ * Produces true if the cycler SHOULD refresh (we are within the refresh
+ * window and not already refreshing)
+ */
+ get shouldRefresh() {
+ if (cycler.isRefreshing) {
+ return false;
+ }
+ if (token?.refreshAfterTimestamp && token.refreshAfterTimestamp < Date.now()) {
+ return true;
+ }
+ return (token?.expiresOnTimestamp ?? 0) - options.refreshWindowInMs < Date.now();
+ },
+ /**
+ * Produces true if the cycler MUST refresh (null or nearly-expired
+ * token).
+ */
+ get mustRefresh() {
+ return (token === null || token.expiresOnTimestamp - options.forcedRefreshWindowInMs < Date.now());
+ },
+ };
+ /**
+ * Starts a refresh job or returns the existing job if one is already
+ * running.
+ */
+ function refresh(scopes, getTokenOptions) {
+ if (!cycler.isRefreshing) {
+ // We bind `scopes` here to avoid passing it around a lot
+ const tryGetAccessToken = () => credential.getToken(scopes, getTokenOptions);
+ // Take advantage of promise chaining to insert an assignment to `token`
+ // before the refresh can be considered done.
+ refreshWorker = beginRefresh(tryGetAccessToken, options.retryIntervalInMs,
+ // If we don't have a token, then we should timeout immediately
+ token?.expiresOnTimestamp ?? Date.now())
+ .then((_token) => {
+ refreshWorker = null;
+ token = _token;
+ tenantId = getTokenOptions.tenantId;
+ return token;
+ })
+ .catch((reason) => {
+ // We also should reset the refresher if we enter a failed state. All
+ // existing awaiters will throw, but subsequent requests will start a
+ // new retry chain.
+ refreshWorker = null;
+ token = null;
+ tenantId = undefined;
+ throw reason;
});
}
- case "ResourceLocation": {
- return getLocationHeader(rawResponse);
+ return refreshWorker;
+ }
+ return async (scopes, tokenOptions) => {
+ //
+ // Simple rules:
+ // - If we MUST refresh, then return the refresh task, blocking
+ // the pipeline until a token is available.
+ // - If we SHOULD refresh, then run refresh but don't return it
+ // (we can still use the cached token).
+ // - Return the token, since it's fine if we didn't return in
+ // step 1.
+ //
+ const hasClaimChallenge = Boolean(tokenOptions.claims);
+ const tenantIdChanged = tenantId !== tokenOptions.tenantId;
+ if (hasClaimChallenge) {
+ // If we've received a claim, we know the existing token isn't valid
+ // We want to clear it so that that refresh worker won't use the old expiration time as a timeout
+ token = null;
}
- case "Body":
- default: {
- return undefined;
+ // If the tenantId passed in token options is different to the one we have
+ // Or if we are in claim challenge and the token was rejected and a new access token need to be issued, we need to
+ // refresh the token with the new tenantId or token.
+ const mustRefresh = tenantIdChanged || hasClaimChallenge || cycler.mustRefresh;
+ if (mustRefresh) {
+ return refresh(scopes, tokenOptions);
}
- }
-}
-function getOperationStatus({ rawResponse }, state) {
- var _a;
- const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"];
- switch (mode) {
- case "OperationLocation": {
- return getStatus(rawResponse);
+ if (cycler.shouldRefresh) {
+ refresh(scopes, tokenOptions);
}
- case "ResourceLocation": {
- return toOperationStatus(rawResponse.statusCode);
+ return token;
+ };
+}
+//# sourceMappingURL=tokenCycler.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/policies/bearerTokenAuthenticationPolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+
+
+
+/**
+ * The programmatic identifier of the bearerTokenAuthenticationPolicy.
+ */
+const bearerTokenAuthenticationPolicyName = "bearerTokenAuthenticationPolicy";
+/**
+ * Try to send the given request.
+ *
+ * When a response is received, returns a tuple of the response received and, if the response was received
+ * inside a thrown RestError, the RestError that was thrown.
+ *
+ * Otherwise, if an error was thrown while sending the request that did not provide an underlying response, it
+ * will be rethrown.
+ */
+async function trySendRequest(request, next) {
+ try {
+ return [await next(request), undefined];
+ }
+ catch (e) {
+ if (esm_restError_isRestError(e) && e.response) {
+ return [e.response, e];
}
- case "Body": {
- return getProvisioningState(rawResponse);
+ else {
+ throw e;
}
- default:
- throw new Error(`Internal error: Unexpected operation mode: ${mode}`);
}
}
-function getResourceLocation({ flatResponse }, state) {
- if (typeof flatResponse === "object") {
- const resourceLocation = flatResponse.resourceLocation;
- if (resourceLocation !== undefined) {
- state.config.resourceLocation = resourceLocation;
- }
+/**
+ * Default authorize request handler
+ */
+async function defaultAuthorizeRequest(options) {
+ const { scopes, getAccessToken, request } = options;
+ // Enable CAE true by default
+ const getTokenOptions = {
+ abortSignal: request.abortSignal,
+ tracingOptions: request.tracingOptions,
+ enableCae: true,
+ };
+ const accessToken = await getAccessToken(scopes, getTokenOptions);
+ if (accessToken) {
+ options.request.headers.set("Authorization", `Bearer ${accessToken.token}`);
}
- return state.config.resourceLocation;
}
-function isOperationError(e) {
- return e.name === "RestError";
+/**
+ * We will retrieve the challenge only if the response status code was 401,
+ * and if the response contained the header "WWW-Authenticate" with a non-empty value.
+ */
+function isChallengeResponse(response) {
+ return response.status === 401 && response.headers.has("WWW-Authenticate");
}
-/** Polls the long-running operation. */
-async function pollHttpOperation(inputs) {
- const { lro, stateProxy, options, processResult, updateState, setDelay, state, setErrorAsResult, } = inputs;
- return pollOperation({
- state,
- stateProxy,
- setDelay,
- processResult: processResult
- ? ({ flatResponse }, inputState) => processResult(flatResponse, inputState)
- : ({ flatResponse }) => flatResponse,
- getError: getErrorFromResponse,
- updateState,
- getPollingInterval: parseRetryAfter,
- getOperationLocation,
- getOperationStatus,
- isOperationError,
- getResourceLocation,
- options,
- /**
- * The expansion here is intentional because `lro` could be an object that
- * references an inner this, so we need to preserve a reference to it.
- */
- poll: async (location, inputOptions) => lro.sendPollRequest(location, inputOptions),
- setErrorAsResult,
+/**
+ * Re-authorize the request for CAE challenge.
+ * The response containing the challenge is `options.response`.
+ * If this method returns true, the underlying request will be sent once again.
+ */
+async function authorizeRequestOnCaeChallenge(onChallengeOptions, caeClaims) {
+ const { scopes } = onChallengeOptions;
+ const accessToken = await onChallengeOptions.getAccessToken(scopes, {
+ enableCae: true,
+ claims: caeClaims,
});
+ if (!accessToken) {
+ return false;
+ }
+ onChallengeOptions.request.headers.set("Authorization", `${accessToken.tokenType ?? "Bearer"} ${accessToken.token}`);
+ return true;
}
-
-// Copyright (c) Microsoft Corporation.
-const createStateProxy$1 = () => ({
- /**
- * The state at this point is created to be of type OperationState.
- * It will be updated later to be of type TState when the
- * customer-provided callback, `updateState`, is called during polling.
- */
- initState: (config) => ({ status: "running", config }),
- setCanceled: (state) => (state.status = "canceled"),
- setError: (state, error) => (state.error = error),
- setResult: (state, result) => (state.result = result),
- setRunning: (state) => (state.status = "running"),
- setSucceeded: (state) => (state.status = "succeeded"),
- setFailed: (state) => (state.status = "failed"),
- getError: (state) => state.error,
- getResult: (state) => state.result,
- isCanceled: (state) => state.status === "canceled",
- isFailed: (state) => state.status === "failed",
- isRunning: (state) => state.status === "running",
- isSucceeded: (state) => state.status === "succeeded",
-});
/**
- * Returns a poller factory.
+ * A policy that can request a token from a TokenCredential implementation and
+ * then apply it to the Authorization header of a request as a Bearer token.
*/
-function buildCreatePoller(inputs) {
- const { getOperationLocation, getStatusFromInitialResponse, getStatusFromPollResponse, isOperationError, getResourceLocation, getPollingInterval, getError, resolveOnUnsuccessful, } = inputs;
- return async ({ init, poll }, options) => {
- const { processResult, updateState, withOperationLocation: withOperationLocationCallback, intervalInMs = POLL_INTERVAL_IN_MS, restoreFrom, } = options || {};
- const stateProxy = createStateProxy$1();
- const withOperationLocation = withOperationLocationCallback
- ? (() => {
- let called = false;
- return (operationLocation, isUpdated) => {
- if (isUpdated)
- withOperationLocationCallback(operationLocation);
- else if (!called)
- withOperationLocationCallback(operationLocation);
- called = true;
- };
- })()
- : undefined;
- const state = restoreFrom
- ? deserializeState(restoreFrom)
- : await initOperation({
- init,
- stateProxy,
- processResult,
- getOperationStatus: getStatusFromInitialResponse,
- withOperationLocation,
- setErrorAsResult: !resolveOnUnsuccessful,
+function bearerTokenAuthenticationPolicy(options) {
+ const { credential, scopes, challengeCallbacks } = options;
+ const logger = options.logger || esm_log_logger;
+ const callbacks = {
+ authorizeRequest: challengeCallbacks?.authorizeRequest?.bind(challengeCallbacks) ?? defaultAuthorizeRequest,
+ authorizeRequestOnChallenge: challengeCallbacks?.authorizeRequestOnChallenge?.bind(challengeCallbacks),
+ };
+ // This function encapsulates the entire process of reliably retrieving the token
+ // The options are left out of the public API until there's demand to configure this.
+ // Remember to extend `BearerTokenAuthenticationPolicyOptions` with `TokenCyclerOptions`
+ // in order to pass through the `options` object.
+ const getAccessToken = credential
+ ? tokenCycler_createTokenCycler(credential /* , options */)
+ : () => Promise.resolve(null);
+ return {
+ name: bearerTokenAuthenticationPolicyName,
+ /**
+ * If there's no challenge parameter:
+ * - It will try to retrieve the token using the cache, or the credential's getToken.
+ * - Then it will try the next policy with or without the retrieved token.
+ *
+ * It uses the challenge parameters to:
+ * - Skip a first attempt to get the token from the credential if there's no cached token,
+ * since it expects the token to be retrievable only after the challenge.
+ * - Prepare the outgoing request if the `prepareRequest` method has been provided.
+ * - Send an initial request to receive the challenge if it fails.
+ * - Process a challenge if the response contains it.
+ * - Retrieve a token with the challenge information, then re-send the request.
+ */
+ async sendRequest(request, next) {
+ if (!request.url.toLowerCase().startsWith("https://")) {
+ throw new Error("Bearer token authentication is not permitted for non-TLS protected (non-https) URLs.");
+ }
+ await callbacks.authorizeRequest({
+ scopes: Array.isArray(scopes) ? scopes : [scopes],
+ request,
+ getAccessToken,
+ logger,
});
- let resultPromise;
- const abortController$1 = new abortController.AbortController();
- const handlers = new Map();
- const handleProgressEvents = async () => handlers.forEach((h) => h(state));
- const cancelErrMsg = "Operation was canceled";
- let currentPollIntervalInMs = intervalInMs;
- const poller = {
- getOperationState: () => state,
- getResult: () => state.result,
- isDone: () => ["succeeded", "failed", "canceled"].includes(state.status),
- isStopped: () => resultPromise === undefined,
- stopPolling: () => {
- abortController$1.abort();
- },
- toString: () => JSON.stringify({
- state,
- }),
- onProgress: (callback) => {
- const s = Symbol();
- handlers.set(s, callback);
- return () => handlers.delete(s);
- },
- pollUntilDone: (pollOptions) => (resultPromise !== null && resultPromise !== void 0 ? resultPromise : (resultPromise = (async () => {
- const { abortSignal: inputAbortSignal } = pollOptions || {};
- const { signal: abortSignal } = inputAbortSignal
- ? new abortController.AbortController([inputAbortSignal, abortController$1.signal])
- : abortController$1;
- if (!poller.isDone()) {
- await poller.poll({ abortSignal });
- while (!poller.isDone()) {
- await coreUtil.delay(currentPollIntervalInMs, { abortSignal });
- await poller.poll({ abortSignal });
+ let response;
+ let error;
+ let shouldSendRequest;
+ [response, error] = await trySendRequest(request, next);
+ if (isChallengeResponse(response)) {
+ let claims = getCaeChallengeClaims(response.headers.get("WWW-Authenticate"));
+ // Handle CAE by default when receive CAE claim
+ if (claims) {
+ let parsedClaim;
+ // Return the response immediately if claims is not a valid base64 encoded string
+ try {
+ parsedClaim = atob(claims);
}
- }
- if (resolveOnUnsuccessful) {
- return poller.getResult();
- }
- else {
- switch (state.status) {
- case "succeeded":
- return poller.getResult();
- case "canceled":
- throw new Error(cancelErrMsg);
- case "failed":
- throw state.error;
- case "notStarted":
- case "running":
- throw new Error(`Polling completed without succeeding or failing`);
+ catch (e) {
+ logger.warning(`The WWW-Authenticate header contains "claims" that cannot be parsed. Unable to perform the Continuous Access Evaluation authentication flow. Unparsable claims: ${claims}`);
+ return response;
}
- }
- })().finally(() => {
- resultPromise = undefined;
- }))),
- async poll(pollOptions) {
- if (resolveOnUnsuccessful) {
- if (poller.isDone())
- return;
- }
- else {
- switch (state.status) {
- case "succeeded":
- return;
- case "canceled":
- throw new Error(cancelErrMsg);
- case "failed":
- throw state.error;
+ shouldSendRequest = await authorizeRequestOnCaeChallenge({
+ scopes: Array.isArray(scopes) ? scopes : [scopes],
+ response,
+ request,
+ getAccessToken,
+ logger,
+ }, parsedClaim);
+ // Send updated request and handle response for RestError
+ if (shouldSendRequest) {
+ [response, error] = await trySendRequest(request, next);
}
}
- await pollOperation({
- poll,
- state,
- stateProxy,
- getOperationLocation,
- isOperationError,
- withOperationLocation,
- getPollingInterval,
- getOperationStatus: getStatusFromPollResponse,
- getResourceLocation,
- processResult,
- getError,
- updateState,
- options: pollOptions,
- setDelay: (pollIntervalInMs) => {
- currentPollIntervalInMs = pollIntervalInMs;
- },
- setErrorAsResult: !resolveOnUnsuccessful,
- });
- await handleProgressEvents();
- if (!resolveOnUnsuccessful) {
- switch (state.status) {
- case "canceled":
- throw new Error(cancelErrMsg);
- case "failed":
- throw state.error;
+ else if (callbacks.authorizeRequestOnChallenge) {
+ // Handle custom challenges when client provides custom callback
+ shouldSendRequest = await callbacks.authorizeRequestOnChallenge({
+ scopes: Array.isArray(scopes) ? scopes : [scopes],
+ request,
+ response,
+ getAccessToken,
+ logger,
+ });
+ // Send updated request and handle response for RestError
+ if (shouldSendRequest) {
+ [response, error] = await trySendRequest(request, next);
+ }
+ // If we get another CAE Claim, we will handle it by default and return whatever value we receive for this
+ if (isChallengeResponse(response)) {
+ claims = getCaeChallengeClaims(response.headers.get("WWW-Authenticate"));
+ if (claims) {
+ let parsedClaim;
+ try {
+ parsedClaim = atob(claims);
+ }
+ catch (e) {
+ logger.warning(`The WWW-Authenticate header contains "claims" that cannot be parsed. Unable to perform the Continuous Access Evaluation authentication flow. Unparsable claims: ${claims}`);
+ return response;
+ }
+ shouldSendRequest = await authorizeRequestOnCaeChallenge({
+ scopes: Array.isArray(scopes) ? scopes : [scopes],
+ response,
+ request,
+ getAccessToken,
+ logger,
+ }, parsedClaim);
+ // Send updated request and handle response for RestError
+ if (shouldSendRequest) {
+ [response, error] = await trySendRequest(request, next);
+ }
+ }
}
}
- },
- };
- return poller;
+ }
+ if (error) {
+ throw error;
+ }
+ else {
+ return response;
+ }
+ },
};
}
-
+/**
+ * Converts: `Bearer a="b", c="d", Pop e="f", g="h"`.
+ * Into: `[ { scheme: 'Bearer', params: { a: 'b', c: 'd' } }, { scheme: 'Pop', params: { e: 'f', g: 'h' } } ]`.
+ *
+ * @internal
+ */
+function parseChallenges(challenges) {
+ // Challenge regex seperates the string to individual challenges with different schemes in the format `Scheme a="b", c=d`
+ // The challenge regex captures parameteres with either quotes values or unquoted values
+ const challengeRegex = /(\w+)\s+((?:\w+=(?:"[^"]*"|[^,]*),?\s*)+)/g;
+ // Parameter regex captures the claims group removed from the scheme in the format `a="b"` and `c="d"`
+ // CAE challenge always have quoted parameters. For more reference, https://learn.microsoft.com/entra/identity-platform/claims-challenge
+ const paramRegex = /(\w+)="([^"]*)"/g;
+ const parsedChallenges = [];
+ let match;
+ // Iterate over each challenge match
+ while ((match = challengeRegex.exec(challenges)) !== null) {
+ const scheme = match[1];
+ const paramsString = match[2];
+ const params = {};
+ let paramMatch;
+ // Iterate over each parameter match
+ while ((paramMatch = paramRegex.exec(paramsString)) !== null) {
+ params[paramMatch[1]] = paramMatch[2];
+ }
+ parsedChallenges.push({ scheme, params });
+ }
+ return parsedChallenges;
+}
+/**
+ * Parse a pipeline response and look for a CAE challenge with "Bearer" scheme
+ * Return the value in the header without parsing the challenge
+ * @internal
+ */
+function getCaeChallengeClaims(challenges) {
+ if (!challenges) {
+ return;
+ }
+ // Find all challenges present in the header
+ const parsedChallenges = parseChallenges(challenges);
+ return parsedChallenges.find((x) => x.scheme === "Bearer" && x.params.claims && x.params.error === "insufficient_claims")?.params.claims;
+}
+//# sourceMappingURL=bearerTokenAuthenticationPolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/policies/auxiliaryAuthenticationHeaderPolicy.js
// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+
+
/**
- * Creates a poller that can be used to poll a long-running operation.
- * @param lro - Description of the long-running operation
- * @param options - options to configure the poller
- * @returns an initialized poller
+ * The programmatic identifier of the auxiliaryAuthenticationHeaderPolicy.
*/
-async function createHttpPoller(lro, options) {
- const { resourceLocationConfig, intervalInMs, processResult, restoreFrom, updateState, withOperationLocation, resolveOnUnsuccessful = false, } = options || {};
- return buildCreatePoller({
- getStatusFromInitialResponse,
- getStatusFromPollResponse: getOperationStatus,
- isOperationError,
- getOperationLocation,
- getResourceLocation,
- getPollingInterval: parseRetryAfter,
- getError: getErrorFromResponse,
- resolveOnUnsuccessful,
- })({
- init: async () => {
- const response = await lro.sendInitialRequest();
- const config = inferLroMode({
- rawResponse: response.rawResponse,
- requestPath: lro.requestPath,
- requestMethod: lro.requestMethod,
- resourceLocationConfig,
- });
- return Object.assign({ response, operationLocation: config === null || config === void 0 ? void 0 : config.operationLocation, resourceLocation: config === null || config === void 0 ? void 0 : config.resourceLocation }, ((config === null || config === void 0 ? void 0 : config.mode) ? { metadata: { mode: config.mode } } : {}));
+const auxiliaryAuthenticationHeaderPolicyName = "auxiliaryAuthenticationHeaderPolicy";
+const AUTHORIZATION_AUXILIARY_HEADER = "x-ms-authorization-auxiliary";
+async function sendAuthorizeRequest(options) {
+ const { scopes, getAccessToken, request } = options;
+ const getTokenOptions = {
+ abortSignal: request.abortSignal,
+ tracingOptions: request.tracingOptions,
+ };
+ return (await getAccessToken(scopes, getTokenOptions))?.token ?? "";
+}
+/**
+ * A policy for external tokens to `x-ms-authorization-auxiliary` header.
+ * This header will be used when creating a cross-tenant application we may need to handle authentication requests
+ * for resources that are in different tenants.
+ * You could see [ARM docs](https://learn.microsoft.com/azure/azure-resource-manager/management/authenticate-multi-tenant) for a rundown of how this feature works
+ */
+function auxiliaryAuthenticationHeaderPolicy(options) {
+ const { credentials, scopes } = options;
+ const logger = options.logger || coreLogger;
+ const tokenCyclerMap = new WeakMap();
+ return {
+ name: auxiliaryAuthenticationHeaderPolicyName,
+ async sendRequest(request, next) {
+ if (!request.url.toLowerCase().startsWith("https://")) {
+ throw new Error("Bearer token authentication for auxiliary header is not permitted for non-TLS protected (non-https) URLs.");
+ }
+ if (!credentials || credentials.length === 0) {
+ logger.info(`${auxiliaryAuthenticationHeaderPolicyName} header will not be set due to empty credentials.`);
+ return next(request);
+ }
+ const tokenPromises = [];
+ for (const credential of credentials) {
+ let getAccessToken = tokenCyclerMap.get(credential);
+ if (!getAccessToken) {
+ getAccessToken = createTokenCycler(credential);
+ tokenCyclerMap.set(credential, getAccessToken);
+ }
+ tokenPromises.push(sendAuthorizeRequest({
+ scopes: Array.isArray(scopes) ? scopes : [scopes],
+ request,
+ getAccessToken,
+ logger,
+ }));
+ }
+ const auxiliaryTokens = (await Promise.all(tokenPromises)).filter((token) => Boolean(token));
+ if (auxiliaryTokens.length === 0) {
+ logger.warning(`None of the auxiliary tokens are valid. ${AUTHORIZATION_AUXILIARY_HEADER} header will not be set.`);
+ return next(request);
+ }
+ request.headers.set(AUTHORIZATION_AUXILIARY_HEADER, auxiliaryTokens.map((token) => `Bearer ${token}`).join(", "));
+ return next(request);
},
- poll: lro.sendPollRequest,
- }, {
- intervalInMs,
- withOperationLocation,
- restoreFrom,
- updateState,
- processResult: processResult
- ? ({ flatResponse }, state) => processResult(flatResponse, state)
- : ({ flatResponse }) => flatResponse,
- });
+ };
}
+//# sourceMappingURL=auxiliaryAuthenticationHeaderPolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/index.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+//# sourceMappingURL=index.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-auth/dist/esm/keyCredential.js
// Copyright (c) Microsoft Corporation.
-const createStateProxy = () => ({
- initState: (config) => ({ config, isStarted: true }),
- setCanceled: (state) => (state.isCancelled = true),
- setError: (state, error) => (state.error = error),
- setResult: (state, result) => (state.result = result),
- setRunning: (state) => (state.isStarted = true),
- setSucceeded: (state) => (state.isCompleted = true),
- setFailed: () => {
- /** empty body */
- },
- getError: (state) => state.error,
- getResult: (state) => state.result,
- isCanceled: (state) => !!state.isCancelled,
- isFailed: (state) => !!state.error,
- isRunning: (state) => !!state.isStarted,
- isSucceeded: (state) => Boolean(state.isCompleted && !state.isCancelled && !state.error),
-});
-class GenericPollOperation {
- constructor(state, lro, setErrorAsResult, lroResourceLocationConfig, processResult, updateState, isDone) {
- this.state = state;
- this.lro = lro;
- this.setErrorAsResult = setErrorAsResult;
- this.lroResourceLocationConfig = lroResourceLocationConfig;
- this.processResult = processResult;
- this.updateState = updateState;
- this.isDone = isDone;
+// Licensed under the MIT License.
+
+/**
+ * Tests an object to determine whether it implements KeyCredential.
+ *
+ * @param credential - The assumed KeyCredential to be tested.
+ */
+function isKeyCredential(credential) {
+ return isObjectWithProperties(credential, ["key"]) && typeof credential.key === "string";
+}
+//# sourceMappingURL=keyCredential.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-auth/dist/esm/azureNamedKeyCredential.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+
+/**
+ * A static name/key-based credential that supports updating
+ * the underlying name and key values.
+ */
+class AzureNamedKeyCredential {
+ _key;
+ _name;
+ /**
+ * The value of the key to be used in authentication.
+ */
+ get key() {
+ return this._key;
}
- setPollerConfig(pollerConfig) {
- this.pollerConfig = pollerConfig;
+ /**
+ * The value of the name to be used in authentication.
+ */
+ get name() {
+ return this._name;
}
- async update(options) {
- var _a;
- const stateProxy = createStateProxy();
- if (!this.state.isStarted) {
- this.state = Object.assign(Object.assign({}, this.state), (await initHttpOperation({
- lro: this.lro,
- stateProxy,
- resourceLocationConfig: this.lroResourceLocationConfig,
- processResult: this.processResult,
- setErrorAsResult: this.setErrorAsResult,
- })));
+ /**
+ * Create an instance of an AzureNamedKeyCredential for use
+ * with a service client.
+ *
+ * @param name - The initial value of the name to use in authentication.
+ * @param key - The initial value of the key to use in authentication.
+ */
+ constructor(name, key) {
+ if (!name || !key) {
+ throw new TypeError("name and key must be non-empty strings");
}
- const updateState = this.updateState;
- const isDone = this.isDone;
- if (!this.state.isCompleted && this.state.error === undefined) {
- await pollHttpOperation({
- lro: this.lro,
- state: this.state,
- stateProxy,
- processResult: this.processResult,
- updateState: updateState
- ? (state, { rawResponse }) => updateState(state, rawResponse)
- : undefined,
- isDone: isDone
- ? ({ flatResponse }, state) => isDone(flatResponse, state)
- : undefined,
- options,
- setDelay: (intervalInMs) => {
- this.pollerConfig.intervalInMs = intervalInMs;
- },
- setErrorAsResult: this.setErrorAsResult,
- });
+ this._name = name;
+ this._key = key;
+ }
+ /**
+ * Change the value of the key.
+ *
+ * Updates will take effect upon the next request after
+ * updating the key value.
+ *
+ * @param newName - The new name value to be used.
+ * @param newKey - The new key value to be used.
+ */
+ update(newName, newKey) {
+ if (!newName || !newKey) {
+ throw new TypeError("newName and newKey must be non-empty strings");
}
- (_a = options === null || options === void 0 ? void 0 : options.fireProgress) === null || _a === void 0 ? void 0 : _a.call(options, this.state);
- return this;
+ this._name = newName;
+ this._key = newKey;
}
- async cancel() {
- logger.error("`cancelOperation` is deprecated because it wasn't implemented");
- return this;
+}
+/**
+ * Tests an object to determine whether it implements NamedKeyCredential.
+ *
+ * @param credential - The assumed NamedKeyCredential to be tested.
+ */
+function isNamedKeyCredential(credential) {
+ return (isObjectWithProperties(credential, ["name", "key"]) &&
+ typeof credential.key === "string" &&
+ typeof credential.name === "string");
+}
+//# sourceMappingURL=azureNamedKeyCredential.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-auth/dist/esm/azureSASCredential.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+
+/**
+ * A static-signature-based credential that supports updating
+ * the underlying signature value.
+ */
+class AzureSASCredential {
+ _signature;
+ /**
+ * The value of the shared access signature to be used in authentication
+ */
+ get signature() {
+ return this._signature;
}
/**
- * Serializes the Poller operation.
+ * Create an instance of an AzureSASCredential for use
+ * with a service client.
+ *
+ * @param signature - The initial value of the shared access signature to use in authentication
*/
- toString() {
- return JSON.stringify({
- state: this.state,
- });
+ constructor(signature) {
+ if (!signature) {
+ throw new Error("shared access signature must be a non-empty string");
+ }
+ this._signature = signature;
+ }
+ /**
+ * Change the value of the signature.
+ *
+ * Updates will take effect upon the next request after
+ * updating the signature value.
+ *
+ * @param newSignature - The new shared access signature value to be used
+ */
+ update(newSignature) {
+ if (!newSignature) {
+ throw new Error("shared access signature must be a non-empty string");
+ }
+ this._signature = newSignature;
}
}
-
+/**
+ * Tests an object to determine whether it implements SASCredential.
+ *
+ * @param credential - The assumed SASCredential to be tested.
+ */
+function isSASCredential(credential) {
+ return (isObjectWithProperties(credential, ["signature"]) && typeof credential.signature === "string");
+}
+//# sourceMappingURL=azureSASCredential.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-auth/dist/esm/tokenCredential.js
// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
+// Licensed under the MIT License.
/**
- * When a poller is manually stopped through the `stopPolling` method,
- * the poller will be rejected with an instance of the PollerStoppedError.
+ * @internal
+ * @param accessToken - Access token
+ * @returns Whether a token is bearer type or not
*/
-class PollerStoppedError extends Error {
- constructor(message) {
- super(message);
- this.name = "PollerStoppedError";
- Object.setPrototypeOf(this, PollerStoppedError.prototype);
- }
+function isBearerToken(accessToken) {
+ return !accessToken.tokenType || accessToken.tokenType === "Bearer";
}
/**
- * When the operation is cancelled, the poller will be rejected with an instance
- * of the PollerCancelledError.
+ * @internal
+ * @param accessToken - Access token
+ * @returns Whether a token is Pop token or not
*/
-class PollerCancelledError extends Error {
- constructor(message) {
- super(message);
- this.name = "PollerCancelledError";
- Object.setPrototypeOf(this, PollerCancelledError.prototype);
- }
+function isPopToken(accessToken) {
+ return accessToken.tokenType === "pop";
}
/**
- * A class that represents the definition of a program that polls through consecutive requests
- * until it reaches a state of completion.
- *
- * A poller can be executed manually, by polling request by request by calling to the `poll()` method repeatedly, until its operation is completed.
- * It also provides a way to wait until the operation completes, by calling `pollUntilDone()` and waiting until the operation finishes.
- * Pollers can also request the cancellation of the ongoing process to whom is providing the underlying long running operation.
- *
- * ```ts
- * const poller = new MyPoller();
- *
- * // Polling just once:
- * await poller.poll();
- *
- * // We can try to cancel the request here, by calling:
- * //
- * // await poller.cancelOperation();
- * //
- *
- * // Getting the final result:
- * const result = await poller.pollUntilDone();
- * ```
- *
- * The Poller is defined by two types, a type representing the state of the poller, which
- * must include a basic set of properties from `PollOperationState`,
- * and a return type defined by `TResult`, which can be anything.
+ * Tests an object to determine whether it implements TokenCredential.
*
- * The Poller class implements the `PollerLike` interface, which allows poller implementations to avoid having
- * to export the Poller's class directly, and instead only export the already instantiated poller with the PollerLike type.
- *
- * ```ts
- * class Client {
- * public async makePoller: PollerLike {
- * const poller = new MyPoller({});
- * // It might be preferred to return the poller after the first request is made,
- * // so that some information can be obtained right away.
- * await poller.poll();
- * return poller;
- * }
- * }
- *
- * const poller: PollerLike = myClient.makePoller();
- * ```
+ * @param credential - The assumed TokenCredential to be tested.
+ */
+function isTokenCredential(credential) {
+ // Check for an object with a 'getToken' function and possibly with
+ // a 'signRequest' function. We do this check to make sure that
+ // a ServiceClientCredentials implementor (like TokenClientCredentials
+ // in ms-rest-nodeauth) doesn't get mistaken for a TokenCredential if
+ // it doesn't actually implement TokenCredential also.
+ const castCredential = credential;
+ return (castCredential &&
+ typeof castCredential.getToken === "function" &&
+ (castCredential.signRequest === undefined || castCredential.getToken.length > 0));
+}
+//# sourceMappingURL=tokenCredential.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-auth/dist/esm/index.js
+
+
+
+
+
+//# sourceMappingURL=index.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-http-compat/dist/esm/policies/disableKeepAlivePolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+const disableKeepAlivePolicyName = "DisableKeepAlivePolicy";
+function createDisableKeepAlivePolicy() {
+ return {
+ name: disableKeepAlivePolicyName,
+ async sendRequest(request, next) {
+ request.disableKeepAlive = true;
+ return next(request);
+ },
+ };
+}
+/**
+ * @internal
+ */
+function pipelineContainsDisableKeepAlivePolicy(pipeline) {
+ return pipeline.getOrderedPolicies().some((policy) => policy.name === disableKeepAlivePolicyName);
+}
+//# sourceMappingURL=disableKeepAlivePolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-client/dist/esm/base64.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+/**
+ * Encodes a string in base64 format.
+ * @param value - the string to encode
+ * @internal
+ */
+function encodeString(value) {
+ return Buffer.from(value).toString("base64");
+}
+/**
+ * Encodes a byte array in base64 format.
+ * @param value - the Uint8Aray to encode
+ * @internal
+ */
+function encodeByteArray(value) {
+ const bufferValue = value instanceof Buffer ? value : Buffer.from(value.buffer);
+ return bufferValue.toString("base64");
+}
+/**
+ * Decodes a base64 string into a byte array.
+ * @param value - the base64 string to decode
+ * @internal
+ */
+function decodeString(value) {
+ return Buffer.from(value, "base64");
+}
+/**
+ * Decodes a base64 string into a string.
+ * @param value - the base64 string to decode
+ * @internal
+ */
+function base64_decodeStringToString(value) {
+ return Buffer.from(value, "base64").toString();
+}
+//# sourceMappingURL=base64.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-client/dist/esm/interfaces.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+/**
+ * Default key used to access the XML attributes.
+ */
+const XML_ATTRKEY = "$";
+/**
+ * Default key used to access the XML value content.
+ */
+const XML_CHARKEY = "_";
+//# sourceMappingURL=interfaces.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-client/dist/esm/utils.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+/**
+ * A type guard for a primitive response body.
+ * @param value - Value to test
*
- * A poller can be created through its constructor, then it can be polled until it's completed.
- * At any point in time, the state of the poller can be obtained without delay through the getOperationState method.
- * At any point in time, the intermediate forms of the result type can be requested without delay.
- * Once the underlying operation is marked as completed, the poller will stop and the final value will be returned.
+ * @internal
+ */
+function isPrimitiveBody(value, mapperTypeName) {
+ return (mapperTypeName !== "Composite" &&
+ mapperTypeName !== "Dictionary" &&
+ (typeof value === "string" ||
+ typeof value === "number" ||
+ typeof value === "boolean" ||
+ mapperTypeName?.match(/^(Date|DateTime|DateTimeRfc1123|UnixTime|ByteArray|Base64Url)$/i) !==
+ null ||
+ value === undefined ||
+ value === null));
+}
+const validateISODuration = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;
+/**
+ * Returns true if the given string is in ISO 8601 format.
+ * @param value - The value to be validated for ISO 8601 duration format.
+ * @internal
+ */
+function isDuration(value) {
+ return validateISODuration.test(value);
+}
+const validUuidRegex = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/i;
+/**
+ * Returns true if the provided uuid is valid.
*
- * ```ts
- * const poller = myClient.makePoller();
- * const state: MyOperationState = poller.getOperationState();
+ * @param uuid - The uuid that needs to be validated.
*
- * // The intermediate result can be obtained at any time.
- * const result: MyResult | undefined = poller.getResult();
+ * @internal
+ */
+function isValidUuid(uuid) {
+ return validUuidRegex.test(uuid);
+}
+/**
+ * Maps the response as follows:
+ * - wraps the response body if needed (typically if its type is primitive).
+ * - returns null if the combination of the headers and the body is empty.
+ * - otherwise, returns the combination of the headers and the body.
*
- * // The final result can only be obtained after the poller finishes.
- * const result: MyResult = await poller.pollUntilDone();
- * ```
+ * @param responseObject - a representation of the parsed response
+ * @returns the response that will be returned to the user which can be null and/or wrapped
*
+ * @internal
*/
-// eslint-disable-next-line no-use-before-define
-class Poller {
- /**
- * A poller needs to be initialized by passing in at least the basic properties of the `PollOperation`.
- *
- * When writing an implementation of a Poller, this implementation needs to deal with the initialization
- * of any custom state beyond the basic definition of the poller. The basic poller assumes that the poller's
- * operation has already been defined, at least its basic properties. The code below shows how to approach
- * the definition of the constructor of a new custom poller.
- *
- * ```ts
- * export class MyPoller extends Poller {
- * constructor({
- * // Anything you might need outside of the basics
- * }) {
- * let state: MyOperationState = {
- * privateProperty: private,
- * publicProperty: public,
- * };
- *
- * const operation = {
- * state,
- * update,
- * cancel,
- * toString
- * }
- *
- * // Sending the operation to the parent's constructor.
- * super(operation);
- *
- * // You can assign more local properties here.
- * }
- * }
- * ```
- *
- * Inside of this constructor, a new promise is created. This will be used to
- * tell the user when the poller finishes (see `pollUntilDone()`). The promise's
- * resolve and reject methods are also used internally to control when to resolve
- * or reject anyone waiting for the poller to finish.
- *
- * The constructor of a custom implementation of a poller is where any serialized version of
- * a previous poller's operation should be deserialized into the operation sent to the
- * base constructor. For example:
- *
- * ```ts
- * export class MyPoller extends Poller {
- * constructor(
- * baseOperation: string | undefined
- * ) {
- * let state: MyOperationState = {};
- * if (baseOperation) {
- * state = {
- * ...JSON.parse(baseOperation).state,
- * ...state
- * };
- * }
- * const operation = {
- * state,
- * // ...
- * }
- * super(operation);
- * }
- * }
- * ```
- *
- * @param operation - Must contain the basic properties of `PollOperation`.
- */
- constructor(operation) {
- /** controls whether to throw an error if the operation failed or was canceled. */
- this.resolveOnUnsuccessful = false;
- this.stopped = true;
- this.pollProgressCallbacks = [];
- this.operation = operation;
- this.promise = new Promise((resolve, reject) => {
- this.resolve = resolve;
- this.reject = reject;
- });
- // This prevents the UnhandledPromiseRejectionWarning in node.js from being thrown.
- // The above warning would get thrown if `poller.poll` is called, it returns an error,
- // and pullUntilDone did not have a .catch or await try/catch on it's return value.
- this.promise.catch(() => {
- /* intentionally blank */
- });
- }
- /**
- * Starts a loop that will break only if the poller is done
- * or if the poller is stopped.
- */
- async startPolling(pollOptions = {}) {
- if (this.stopped) {
- this.stopped = false;
- }
- while (!this.isStopped() && !this.isDone()) {
- await this.poll(pollOptions);
- await this.delay();
- }
- }
- /**
- * pollOnce does one polling, by calling to the update method of the underlying
- * poll operation to make any relevant change effective.
- *
- * It only optionally receives an object with an abortSignal property, from \@azure/abort-controller's AbortSignalLike.
- *
- * @param options - Optional properties passed to the operation's update method.
- */
- async pollOnce(options = {}) {
- if (!this.isDone()) {
- this.operation = await this.operation.update({
- abortSignal: options.abortSignal,
- fireProgress: this.fireProgress.bind(this),
- });
- }
- this.processUpdatedState();
+function handleNullableResponseAndWrappableBody(responseObject) {
+ const combinedHeadersAndBody = {
+ ...responseObject.headers,
+ ...responseObject.body,
+ };
+ if (responseObject.hasNullableType &&
+ Object.getOwnPropertyNames(combinedHeadersAndBody).length === 0) {
+ return responseObject.shouldWrapBody ? { body: null } : null;
}
- /**
- * fireProgress calls the functions passed in via onProgress the method of the poller.
- *
- * It loops over all of the callbacks received from onProgress, and executes them, sending them
- * the current operation state.
- *
- * @param state - The current operation state.
- */
- fireProgress(state) {
- for (const callback of this.pollProgressCallbacks) {
- callback(state);
- }
+ else {
+ return responseObject.shouldWrapBody
+ ? {
+ ...responseObject.headers,
+ body: responseObject.body,
+ }
+ : combinedHeadersAndBody;
}
- /**
- * Invokes the underlying operation's cancel method.
- */
- async cancelOnce(options = {}) {
- this.operation = await this.operation.cancel(options);
+}
+/**
+ * Take a `FullOperationResponse` and turn it into a flat
+ * response object to hand back to the consumer.
+ * @param fullResponse - The processed response from the operation request
+ * @param responseSpec - The response map from the OperationSpec
+ *
+ * @internal
+ */
+function flattenResponse(fullResponse, responseSpec) {
+ const parsedHeaders = fullResponse.parsedHeaders;
+ // head methods never have a body, but we return a boolean set to body property
+ // to indicate presence/absence of the resource
+ if (fullResponse.request.method === "HEAD") {
+ return {
+ ...parsedHeaders,
+ body: fullResponse.parsedBody,
+ };
}
- /**
- * Returns a promise that will resolve once a single polling request finishes.
- * It does this by calling the update method of the Poller's operation.
- *
- * It only optionally receives an object with an abortSignal property, from \@azure/abort-controller's AbortSignalLike.
- *
- * @param options - Optional properties passed to the operation's update method.
- */
- poll(options = {}) {
- if (!this.pollOncePromise) {
- this.pollOncePromise = this.pollOnce(options);
- const clearPollOncePromise = () => {
- this.pollOncePromise = undefined;
- };
- this.pollOncePromise.then(clearPollOncePromise, clearPollOncePromise).catch(this.reject);
- }
- return this.pollOncePromise;
+ const bodyMapper = responseSpec && responseSpec.bodyMapper;
+ const isNullable = Boolean(bodyMapper?.nullable);
+ const expectedBodyTypeName = bodyMapper?.type.name;
+ /** If the body is asked for, we look at the expected body type to handle it */
+ if (expectedBodyTypeName === "Stream") {
+ return {
+ ...parsedHeaders,
+ blobBody: fullResponse.blobBody,
+ readableStreamBody: fullResponse.readableStreamBody,
+ };
}
- processUpdatedState() {
- if (this.operation.state.error) {
- this.stopped = true;
- if (!this.resolveOnUnsuccessful) {
- this.reject(this.operation.state.error);
- throw this.operation.state.error;
+ const modelProperties = (expectedBodyTypeName === "Composite" &&
+ bodyMapper.type.modelProperties) ||
+ {};
+ const isPageableResponse = Object.keys(modelProperties).some((k) => modelProperties[k].serializedName === "");
+ if (expectedBodyTypeName === "Sequence" || isPageableResponse) {
+ const arrayResponse = fullResponse.parsedBody ?? [];
+ for (const key of Object.keys(modelProperties)) {
+ if (modelProperties[key].serializedName) {
+ arrayResponse[key] = fullResponse.parsedBody?.[key];
}
}
- if (this.operation.state.isCancelled) {
- this.stopped = true;
- if (!this.resolveOnUnsuccessful) {
- const error = new PollerCancelledError("Operation was canceled");
- this.reject(error);
- throw error;
+ if (parsedHeaders) {
+ for (const key of Object.keys(parsedHeaders)) {
+ arrayResponse[key] = parsedHeaders[key];
}
}
- if (this.isDone() && this.resolve) {
- // If the poller has finished polling, this means we now have a result.
- // However, it can be the case that TResult is instantiated to void, so
- // we are not expecting a result anyway. To assert that we might not
- // have a result eventually after finishing polling, we cast the result
- // to TResult.
- this.resolve(this.getResult());
- }
+ return isNullable &&
+ !fullResponse.parsedBody &&
+ !parsedHeaders &&
+ Object.getOwnPropertyNames(modelProperties).length === 0
+ ? null
+ : arrayResponse;
}
- /**
- * Returns a promise that will resolve once the underlying operation is completed.
- */
- async pollUntilDone(pollOptions = {}) {
- if (this.stopped) {
- this.startPolling(pollOptions).catch(this.reject);
- }
- // This is needed because the state could have been updated by
- // `cancelOperation`, e.g. the operation is canceled or an error occurred.
- this.processUpdatedState();
- return this.promise;
+ return handleNullableResponseAndWrappableBody({
+ body: fullResponse.parsedBody,
+ headers: parsedHeaders,
+ hasNullableType: isNullable,
+ shouldWrapBody: isPrimitiveBody(fullResponse.parsedBody, expectedBodyTypeName),
+ });
+}
+//# sourceMappingURL=utils.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-client/dist/esm/serializer.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+
+
+
+class SerializerImpl {
+ modelMappers;
+ isXML;
+ constructor(modelMappers = {}, isXML = false) {
+ this.modelMappers = modelMappers;
+ this.isXML = isXML;
}
/**
- * Invokes the provided callback after each polling is completed,
- * sending the current state of the poller's operation.
- *
- * It returns a method that can be used to stop receiving updates on the given callback function.
+ * @deprecated Removing the constraints validation on client side.
*/
- onProgress(callback) {
- this.pollProgressCallbacks.push(callback);
- return () => {
- this.pollProgressCallbacks = this.pollProgressCallbacks.filter((c) => c !== callback);
+ validateConstraints(mapper, value, objectName) {
+ const failValidation = (constraintName, constraintValue) => {
+ throw new Error(`"${objectName}" with value "${value}" should satisfy the constraint "${constraintName}": ${constraintValue}.`);
};
- }
- /**
- * Returns true if the poller has finished polling.
- */
- isDone() {
- const state = this.operation.state;
- return Boolean(state.isCompleted || state.isCancelled || state.error);
- }
- /**
- * Stops the poller from continuing to poll.
- */
- stopPolling() {
- if (!this.stopped) {
- this.stopped = true;
- if (this.reject) {
- this.reject(new PollerStoppedError("This poller is already stopped"));
+ if (mapper.constraints && value !== undefined && value !== null) {
+ const { ExclusiveMaximum, ExclusiveMinimum, InclusiveMaximum, InclusiveMinimum, MaxItems, MaxLength, MinItems, MinLength, MultipleOf, Pattern, UniqueItems, } = mapper.constraints;
+ if (ExclusiveMaximum !== undefined && value >= ExclusiveMaximum) {
+ failValidation("ExclusiveMaximum", ExclusiveMaximum);
+ }
+ if (ExclusiveMinimum !== undefined && value <= ExclusiveMinimum) {
+ failValidation("ExclusiveMinimum", ExclusiveMinimum);
+ }
+ if (InclusiveMaximum !== undefined && value > InclusiveMaximum) {
+ failValidation("InclusiveMaximum", InclusiveMaximum);
+ }
+ if (InclusiveMinimum !== undefined && value < InclusiveMinimum) {
+ failValidation("InclusiveMinimum", InclusiveMinimum);
+ }
+ if (MaxItems !== undefined && value.length > MaxItems) {
+ failValidation("MaxItems", MaxItems);
+ }
+ if (MaxLength !== undefined && value.length > MaxLength) {
+ failValidation("MaxLength", MaxLength);
+ }
+ if (MinItems !== undefined && value.length < MinItems) {
+ failValidation("MinItems", MinItems);
+ }
+ if (MinLength !== undefined && value.length < MinLength) {
+ failValidation("MinLength", MinLength);
+ }
+ if (MultipleOf !== undefined && value % MultipleOf !== 0) {
+ failValidation("MultipleOf", MultipleOf);
+ }
+ if (Pattern) {
+ const pattern = typeof Pattern === "string" ? new RegExp(Pattern) : Pattern;
+ if (typeof value !== "string" || value.match(pattern) === null) {
+ failValidation("Pattern", Pattern);
+ }
+ }
+ if (UniqueItems &&
+ value.some((item, i, ar) => ar.indexOf(item) !== i)) {
+ failValidation("UniqueItems", UniqueItems);
}
}
}
/**
- * Returns true if the poller is stopped.
- */
- isStopped() {
- return this.stopped;
- }
- /**
- * Attempts to cancel the underlying operation.
+ * Serialize the given object based on its metadata defined in the mapper
*
- * It only optionally receives an object with an abortSignal property, from \@azure/abort-controller's AbortSignalLike.
+ * @param mapper - The mapper which defines the metadata of the serializable object
*
- * If it's called again before it finishes, it will throw an error.
+ * @param object - A valid Javascript object to be serialized
*
- * @param options - Optional properties passed to the operation's update method.
- */
- cancelOperation(options = {}) {
- if (!this.cancelPromise) {
- this.cancelPromise = this.cancelOnce(options);
- }
- else if (options.abortSignal) {
- throw new Error("A cancel request is currently pending");
- }
- return this.cancelPromise;
- }
- /**
- * Returns the state of the operation.
+ * @param objectName - Name of the serialized object
*
- * Even though TState will be the same type inside any of the methods of any extension of the Poller class,
- * implementations of the pollers can customize what's shared with the public by writing their own
- * version of the `getOperationState` method, and by defining two types, one representing the internal state of the poller
- * and a public type representing a safe to share subset of the properties of the internal state.
- * Their definition of getOperationState can then return their public type.
- *
- * Example:
+ * @param options - additional options to serialization
*
- * ```ts
- * // Let's say we have our poller's operation state defined as:
- * interface MyOperationState extends PollOperationState {
- * privateProperty?: string;
- * publicProperty?: string;
- * }
+ * @returns A valid serialized Javascript object
+ */
+ serialize(mapper, object, objectName, options = { xml: {} }) {
+ const updatedOptions = {
+ xml: {
+ rootName: options.xml.rootName ?? "",
+ includeRoot: options.xml.includeRoot ?? false,
+ xmlCharKey: options.xml.xmlCharKey ?? XML_CHARKEY,
+ },
+ };
+ let payload = {};
+ const mapperType = mapper.type.name;
+ if (!objectName) {
+ objectName = mapper.serializedName;
+ }
+ if (mapperType.match(/^Sequence$/i) !== null) {
+ payload = [];
+ }
+ if (mapper.isConstant) {
+ object = mapper.defaultValue;
+ }
+ // This table of allowed values should help explain
+ // the mapper.required and mapper.nullable properties.
+ // X means "neither undefined or null are allowed".
+ // || required
+ // || true | false
+ // nullable || ==========================
+ // true || null | undefined/null
+ // false || X | undefined
+ // undefined || X | undefined/null
+ const { required, nullable } = mapper;
+ if (required && nullable && object === undefined) {
+ throw new Error(`${objectName} cannot be undefined.`);
+ }
+ if (required && !nullable && (object === undefined || object === null)) {
+ throw new Error(`${objectName} cannot be null or undefined.`);
+ }
+ if (!required && nullable === false && object === null) {
+ throw new Error(`${objectName} cannot be null.`);
+ }
+ if (object === undefined || object === null) {
+ payload = object;
+ }
+ else {
+ if (mapperType.match(/^any$/i) !== null) {
+ payload = object;
+ }
+ else if (mapperType.match(/^(Number|String|Boolean|Object|Stream|Uuid)$/i) !== null) {
+ payload = serializeBasicTypes(mapperType, objectName, object);
+ }
+ else if (mapperType.match(/^Enum$/i) !== null) {
+ const enumMapper = mapper;
+ payload = serializeEnumType(objectName, enumMapper.type.allowedValues, object);
+ }
+ else if (mapperType.match(/^(Date|DateTime|TimeSpan|DateTimeRfc1123|UnixTime)$/i) !== null) {
+ payload = serializeDateTypes(mapperType, object, objectName);
+ }
+ else if (mapperType.match(/^ByteArray$/i) !== null) {
+ payload = serializeByteArrayType(objectName, object);
+ }
+ else if (mapperType.match(/^Base64Url$/i) !== null) {
+ payload = serializeBase64UrlType(objectName, object);
+ }
+ else if (mapperType.match(/^Sequence$/i) !== null) {
+ payload = serializeSequenceType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions);
+ }
+ else if (mapperType.match(/^Dictionary$/i) !== null) {
+ payload = serializeDictionaryType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions);
+ }
+ else if (mapperType.match(/^Composite$/i) !== null) {
+ payload = serializeCompositeType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions);
+ }
+ }
+ return payload;
+ }
+ /**
+ * Deserialize the given object based on its metadata defined in the mapper
*
- * // To allow us to have a true separation of public and private state, we have to define another interface:
- * interface PublicState extends PollOperationState {
- * publicProperty?: string;
- * }
+ * @param mapper - The mapper which defines the metadata of the serializable object
*
- * // Then, we define our Poller as follows:
- * export class MyPoller extends Poller {
- * // ... More content is needed here ...
+ * @param responseBody - A valid Javascript entity to be deserialized
*
- * public getOperationState(): PublicState {
- * const state: PublicState = this.operation.state;
- * return {
- * // Properties from PollOperationState
- * isStarted: state.isStarted,
- * isCompleted: state.isCompleted,
- * isCancelled: state.isCancelled,
- * error: state.error,
- * result: state.result,
+ * @param objectName - Name of the deserialized object
*
- * // The only other property needed by PublicState.
- * publicProperty: state.publicProperty
- * }
- * }
- * }
- * ```
+ * @param options - Controls behavior of XML parser and builder.
*
- * You can see this in the tests of this repository, go to the file:
- * `../test/utils/testPoller.ts`
- * and look for the getOperationState implementation.
- */
- getOperationState() {
- return this.operation.state;
- }
- /**
- * Returns the result value of the operation,
- * regardless of the state of the poller.
- * It can return undefined or an incomplete form of the final TResult value
- * depending on the implementation.
- */
- getResult() {
- const state = this.operation.state;
- return state.result;
- }
- /**
- * Returns a serialized version of the poller's operation
- * by invoking the operation's toString method.
+ * @returns A valid deserialized Javascript object
*/
- toString() {
- return this.operation.toString();
+ deserialize(mapper, responseBody, objectName, options = { xml: {} }) {
+ const updatedOptions = {
+ xml: {
+ rootName: options.xml.rootName ?? "",
+ includeRoot: options.xml.includeRoot ?? false,
+ xmlCharKey: options.xml.xmlCharKey ?? XML_CHARKEY,
+ },
+ ignoreUnknownProperties: options.ignoreUnknownProperties ?? false,
+ };
+ if (responseBody === undefined || responseBody === null) {
+ if (this.isXML && mapper.type.name === "Sequence" && !mapper.xmlIsWrapped) {
+ // Edge case for empty XML non-wrapped lists. xml2js can't distinguish
+ // between the list being empty versus being missing,
+ // so let's do the more user-friendly thing and return an empty list.
+ responseBody = [];
+ }
+ // specifically check for undefined as default value can be a falsey value `0, "", false, null`
+ if (mapper.defaultValue !== undefined) {
+ responseBody = mapper.defaultValue;
+ }
+ return responseBody;
+ }
+ let payload;
+ const mapperType = mapper.type.name;
+ if (!objectName) {
+ objectName = mapper.serializedName;
+ }
+ if (mapperType.match(/^Composite$/i) !== null) {
+ payload = deserializeCompositeType(this, mapper, responseBody, objectName, updatedOptions);
+ }
+ else {
+ if (this.isXML) {
+ const xmlCharKey = updatedOptions.xml.xmlCharKey;
+ /**
+ * If the mapper specifies this as a non-composite type value but the responseBody contains
+ * both header ("$" i.e., XML_ATTRKEY) and body ("#" i.e., XML_CHARKEY) properties,
+ * then just reduce the responseBody value to the body ("#" i.e., XML_CHARKEY) property.
+ */
+ if (responseBody[XML_ATTRKEY] !== undefined && responseBody[xmlCharKey] !== undefined) {
+ responseBody = responseBody[xmlCharKey];
+ }
+ }
+ if (mapperType.match(/^Number$/i) !== null) {
+ payload = parseFloat(responseBody);
+ if (isNaN(payload)) {
+ payload = responseBody;
+ }
+ }
+ else if (mapperType.match(/^Boolean$/i) !== null) {
+ if (responseBody === "true") {
+ payload = true;
+ }
+ else if (responseBody === "false") {
+ payload = false;
+ }
+ else {
+ payload = responseBody;
+ }
+ }
+ else if (mapperType.match(/^(String|Enum|Object|Stream|Uuid|TimeSpan|any)$/i) !== null) {
+ payload = responseBody;
+ }
+ else if (mapperType.match(/^(Date|DateTime|DateTimeRfc1123)$/i) !== null) {
+ payload = new Date(responseBody);
+ }
+ else if (mapperType.match(/^UnixTime$/i) !== null) {
+ payload = unixTimeToDate(responseBody);
+ }
+ else if (mapperType.match(/^ByteArray$/i) !== null) {
+ payload = decodeString(responseBody);
+ }
+ else if (mapperType.match(/^Base64Url$/i) !== null) {
+ payload = base64UrlToByteArray(responseBody);
+ }
+ else if (mapperType.match(/^Sequence$/i) !== null) {
+ payload = deserializeSequenceType(this, mapper, responseBody, objectName, updatedOptions);
+ }
+ else if (mapperType.match(/^Dictionary$/i) !== null) {
+ payload = deserializeDictionaryType(this, mapper, responseBody, objectName, updatedOptions);
+ }
+ }
+ if (mapper.isConstant) {
+ payload = mapper.defaultValue;
+ }
+ return payload;
}
}
-
-// Copyright (c) Microsoft Corporation.
/**
- * The LRO Engine, a class that performs polling.
+ * Method that creates and returns a Serializer.
+ * @param modelMappers - Known models to map
+ * @param isXML - If XML should be supported
*/
-class LroEngine extends Poller {
- constructor(lro, options) {
- const { intervalInMs = POLL_INTERVAL_IN_MS, resumeFrom, resolveOnUnsuccessful = false, isDone, lroResourceLocationConfig, processResult, updateState, } = options || {};
- const state = resumeFrom
- ? deserializeState(resumeFrom)
- : {};
- const operation = new GenericPollOperation(state, lro, !resolveOnUnsuccessful, lroResourceLocationConfig, processResult, updateState, isDone);
- super(operation);
- this.resolveOnUnsuccessful = resolveOnUnsuccessful;
- this.config = { intervalInMs: intervalInMs };
- operation.setPollerConfig(this.config);
- }
- /**
- * The method used by the poller to wait before attempting to update its operation.
- */
- delay() {
- return new Promise((resolve) => setTimeout(() => resolve(), this.config.intervalInMs));
+function createSerializer(modelMappers = {}, isXML = false) {
+ return new SerializerImpl(modelMappers, isXML);
+}
+function trimEnd(str, ch) {
+ let len = str.length;
+ while (len - 1 >= 0 && str[len - 1] === ch) {
+ --len;
}
+ return str.substr(0, len);
}
-
-__webpack_unused_export__ = LroEngine;
-exports.vu = Poller;
-__webpack_unused_export__ = PollerCancelledError;
-__webpack_unused_export__ = PollerStoppedError;
-__webpack_unused_export__ = createHttpPoller;
-//# sourceMappingURL=index.js.map
-
-
-/***/ }),
-
-/***/ 7889:
-/***/ (function(__unused_webpack_module, exports) {
-
-
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.ClientStreamingCall = void 0;
-/**
- * A client streaming RPC call. This means that the clients sends 0, 1, or
- * more messages to the server, and the server replies with exactly one
- * message.
- */
-class ClientStreamingCall {
- constructor(method, requestHeaders, request, headers, response, status, trailers) {
- this.method = method;
- this.requestHeaders = requestHeaders;
- this.requests = request;
- this.headers = headers;
- this.response = response;
- this.status = status;
- this.trailers = trailers;
+function bufferToBase64Url(buffer) {
+ if (!buffer) {
+ return undefined;
}
- /**
- * Instead of awaiting the response status and trailers, you can
- * just as well await this call itself to receive the server outcome.
- * Note that it may still be valid to send more request messages.
- */
- then(onfulfilled, onrejected) {
- return this.promiseFinished().then(value => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, reason => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason));
+ if (!(buffer instanceof Uint8Array)) {
+ throw new Error(`Please provide an input of type Uint8Array for converting to Base64Url.`);
}
- promiseFinished() {
- return __awaiter(this, void 0, void 0, function* () {
- let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]);
- return {
- method: this.method,
- requestHeaders: this.requestHeaders,
- headers,
- response,
- status,
- trailers
- };
- });
+ // Uint8Array to Base64.
+ const str = encodeByteArray(buffer);
+ // Base64 to Base64Url.
+ return trimEnd(str, "=").replace(/\+/g, "-").replace(/\//g, "_");
+}
+function base64UrlToByteArray(str) {
+ if (!str) {
+ return undefined;
}
+ if (str && typeof str.valueOf() !== "string") {
+ throw new Error("Please provide an input of type string for converting to Uint8Array");
+ }
+ // Base64Url to Base64.
+ str = str.replace(/-/g, "+").replace(/_/g, "/");
+ // Base64 to Uint8Array.
+ return decodeString(str);
}
-exports.ClientStreamingCall = ClientStreamingCall;
-
-
-/***/ }),
-
-/***/ 1409:
-/***/ ((__unused_webpack_module, exports) => {
-
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.Deferred = exports.DeferredState = void 0;
-var DeferredState;
-(function (DeferredState) {
- DeferredState[DeferredState["PENDING"] = 0] = "PENDING";
- DeferredState[DeferredState["REJECTED"] = 1] = "REJECTED";
- DeferredState[DeferredState["RESOLVED"] = 2] = "RESOLVED";
-})(DeferredState = exports.DeferredState || (exports.DeferredState = {}));
-/**
- * A deferred promise. This is a "controller" for a promise, which lets you
- * pass a promise around and reject or resolve it from the outside.
- *
- * Warning: This class is to be used with care. Using it can make code very
- * difficult to read. It is intended for use in library code that exposes
- * promises, not for regular business logic.
- */
-class Deferred {
- /**
- * @param preventUnhandledRejectionWarning - prevents the warning
- * "Unhandled Promise rejection" by adding a noop rejection handler.
- * Working with calls returned from the runtime-rpc package in an
- * async function usually means awaiting one call property after
- * the other. This means that the "status" is not being awaited when
- * an earlier await for the "headers" is rejected. This causes the
- * "unhandled promise reject" warning. A more correct behaviour for
- * calls might be to become aware whether at least one of the
- * promises is handled and swallow the rejection warning for the
- * others.
- */
- constructor(preventUnhandledRejectionWarning = true) {
- this._state = DeferredState.PENDING;
- this._promise = new Promise((resolve, reject) => {
- this._resolve = resolve;
- this._reject = reject;
- });
- if (preventUnhandledRejectionWarning) {
- this._promise.catch(_ => { });
+function splitSerializeName(prop) {
+ const classes = [];
+ let partialclass = "";
+ if (prop) {
+ const subwords = prop.split(".");
+ for (const item of subwords) {
+ if (item.charAt(item.length - 1) === "\\") {
+ partialclass += item.substr(0, item.length - 1) + ".";
+ }
+ else {
+ partialclass += item;
+ classes.push(partialclass);
+ partialclass = "";
+ }
}
}
- /**
- * Get the current state of the promise.
- */
- get state() {
- return this._state;
+ return classes;
+}
+function dateToUnixTime(d) {
+ if (!d) {
+ return undefined;
}
- /**
- * Get the deferred promise.
- */
- get promise() {
- return this._promise;
+ if (typeof d.valueOf() === "string") {
+ d = new Date(d);
}
- /**
- * Resolve the promise. Throws if the promise is already resolved or rejected.
- */
- resolve(value) {
- if (this.state !== DeferredState.PENDING)
- throw new Error(`cannot resolve ${DeferredState[this.state].toLowerCase()}`);
- this._resolve(value);
- this._state = DeferredState.RESOLVED;
+ return Math.floor(d.getTime() / 1000);
+}
+function unixTimeToDate(n) {
+ if (!n) {
+ return undefined;
}
- /**
- * Reject the promise. Throws if the promise is already resolved or rejected.
- */
- reject(reason) {
- if (this.state !== DeferredState.PENDING)
- throw new Error(`cannot reject ${DeferredState[this.state].toLowerCase()}`);
- this._reject(reason);
- this._state = DeferredState.REJECTED;
+ return new Date(n * 1000);
+}
+function serializeBasicTypes(typeName, objectName, value) {
+ if (value !== null && value !== undefined) {
+ if (typeName.match(/^Number$/i) !== null) {
+ if (typeof value !== "number") {
+ throw new Error(`${objectName} with value ${value} must be of type number.`);
+ }
+ }
+ else if (typeName.match(/^String$/i) !== null) {
+ if (typeof value.valueOf() !== "string") {
+ throw new Error(`${objectName} with value "${value}" must be of type string.`);
+ }
+ }
+ else if (typeName.match(/^Uuid$/i) !== null) {
+ if (!(typeof value.valueOf() === "string" && isValidUuid(value))) {
+ throw new Error(`${objectName} with value "${value}" must be of type string and a valid uuid.`);
+ }
+ }
+ else if (typeName.match(/^Boolean$/i) !== null) {
+ if (typeof value !== "boolean") {
+ throw new Error(`${objectName} with value ${value} must be of type boolean.`);
+ }
+ }
+ else if (typeName.match(/^Stream$/i) !== null) {
+ const objectType = typeof value;
+ if (objectType !== "string" &&
+ typeof value.pipe !== "function" && // NodeJS.ReadableStream
+ typeof value.tee !== "function" && // browser ReadableStream
+ !(value instanceof ArrayBuffer) &&
+ !ArrayBuffer.isView(value) &&
+ // File objects count as a type of Blob, so we want to use instanceof explicitly
+ !((typeof Blob === "function" || typeof Blob === "object") && value instanceof Blob) &&
+ objectType !== "function") {
+ throw new Error(`${objectName} must be a string, Blob, ArrayBuffer, ArrayBufferView, ReadableStream, or () => ReadableStream.`);
+ }
+ }
}
- /**
- * Resolve the promise. Ignore if not pending.
- */
- resolvePending(val) {
- if (this._state === DeferredState.PENDING)
- this.resolve(val);
+ return value;
+}
+function serializeEnumType(objectName, allowedValues, value) {
+ if (!allowedValues) {
+ throw new Error(`Please provide a set of allowedValues to validate ${objectName} as an Enum Type.`);
}
- /**
- * Reject the promise. Ignore if not pending.
- */
- rejectPending(reason) {
- if (this._state === DeferredState.PENDING)
- this.reject(reason);
+ const isPresent = allowedValues.some((item) => {
+ if (typeof item.valueOf() === "string") {
+ return item.toLowerCase() === value.toLowerCase();
+ }
+ return item === value;
+ });
+ if (!isPresent) {
+ throw new Error(`${value} is not a valid value for ${objectName}. The valid values are: ${JSON.stringify(allowedValues)}.`);
}
+ return value;
}
-exports.Deferred = Deferred;
-
-
-/***/ }),
-
-/***/ 6826:
-/***/ (function(__unused_webpack_module, exports) {
-
-
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.DuplexStreamingCall = void 0;
-/**
- * A duplex streaming RPC call. This means that the clients sends an
- * arbitrary amount of messages to the server, while at the same time,
- * the server sends an arbitrary amount of messages to the client.
- */
-class DuplexStreamingCall {
- constructor(method, requestHeaders, request, headers, response, status, trailers) {
- this.method = method;
- this.requestHeaders = requestHeaders;
- this.requests = request;
- this.headers = headers;
- this.responses = response;
- this.status = status;
- this.trailers = trailers;
- }
- /**
- * Instead of awaiting the response status and trailers, you can
- * just as well await this call itself to receive the server outcome.
- * Note that it may still be valid to send more request messages.
- */
- then(onfulfilled, onrejected) {
- return this.promiseFinished().then(value => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, reason => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason));
- }
- promiseFinished() {
- return __awaiter(this, void 0, void 0, function* () {
- let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]);
- return {
- method: this.method,
- requestHeaders: this.requestHeaders,
- headers,
- status,
- trailers,
- };
- });
- }
-}
-exports.DuplexStreamingCall = DuplexStreamingCall;
-
-
-/***/ }),
-
-/***/ 4420:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-var __webpack_unused_export__;
-
-// Public API of the rpc runtime.
-// Note: we do not use `export * from ...` to help tree shakers,
-// webpack verbose output hints that this should be useful
-__webpack_unused_export__ = ({ value: true });
-var service_type_1 = __nccwpck_require__(6892);
-Object.defineProperty(exports, "C0", ({ enumerable: true, get: function () { return service_type_1.ServiceType; } }));
-var reflection_info_1 = __nccwpck_require__(2496);
-__webpack_unused_export__ = ({ enumerable: true, get: function () { return reflection_info_1.readMethodOptions; } });
-__webpack_unused_export__ = ({ enumerable: true, get: function () { return reflection_info_1.readMethodOption; } });
-__webpack_unused_export__ = ({ enumerable: true, get: function () { return reflection_info_1.readServiceOption; } });
-var rpc_error_1 = __nccwpck_require__(8636);
-__webpack_unused_export__ = ({ enumerable: true, get: function () { return rpc_error_1.RpcError; } });
-var rpc_options_1 = __nccwpck_require__(8576);
-__webpack_unused_export__ = ({ enumerable: true, get: function () { return rpc_options_1.mergeRpcOptions; } });
-var rpc_output_stream_1 = __nccwpck_require__(2726);
-__webpack_unused_export__ = ({ enumerable: true, get: function () { return rpc_output_stream_1.RpcOutputStreamController; } });
-var test_transport_1 = __nccwpck_require__(9122);
-__webpack_unused_export__ = ({ enumerable: true, get: function () { return test_transport_1.TestTransport; } });
-var deferred_1 = __nccwpck_require__(1409);
-__webpack_unused_export__ = ({ enumerable: true, get: function () { return deferred_1.Deferred; } });
-__webpack_unused_export__ = ({ enumerable: true, get: function () { return deferred_1.DeferredState; } });
-var duplex_streaming_call_1 = __nccwpck_require__(6826);
-__webpack_unused_export__ = ({ enumerable: true, get: function () { return duplex_streaming_call_1.DuplexStreamingCall; } });
-var client_streaming_call_1 = __nccwpck_require__(7889);
-__webpack_unused_export__ = ({ enumerable: true, get: function () { return client_streaming_call_1.ClientStreamingCall; } });
-var server_streaming_call_1 = __nccwpck_require__(6173);
-__webpack_unused_export__ = ({ enumerable: true, get: function () { return server_streaming_call_1.ServerStreamingCall; } });
-var unary_call_1 = __nccwpck_require__(9288);
-__webpack_unused_export__ = ({ enumerable: true, get: function () { return unary_call_1.UnaryCall; } });
-var rpc_interceptor_1 = __nccwpck_require__(2849);
-__webpack_unused_export__ = ({ enumerable: true, get: function () { return rpc_interceptor_1.stackIntercept; } });
-__webpack_unused_export__ = ({ enumerable: true, get: function () { return rpc_interceptor_1.stackDuplexStreamingInterceptors; } });
-__webpack_unused_export__ = ({ enumerable: true, get: function () { return rpc_interceptor_1.stackClientStreamingInterceptors; } });
-__webpack_unused_export__ = ({ enumerable: true, get: function () { return rpc_interceptor_1.stackServerStreamingInterceptors; } });
-__webpack_unused_export__ = ({ enumerable: true, get: function () { return rpc_interceptor_1.stackUnaryInterceptors; } });
-var server_call_context_1 = __nccwpck_require__(3352);
-__webpack_unused_export__ = ({ enumerable: true, get: function () { return server_call_context_1.ServerCallContextController; } });
-
-
-/***/ }),
-
-/***/ 2496:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.readServiceOption = exports.readMethodOption = exports.readMethodOptions = exports.normalizeMethodInfo = void 0;
-const runtime_1 = __nccwpck_require__(8886);
-/**
- * Turns PartialMethodInfo into MethodInfo.
- */
-function normalizeMethodInfo(method, service) {
- var _a, _b, _c;
- let m = method;
- m.service = service;
- m.localName = (_a = m.localName) !== null && _a !== void 0 ? _a : runtime_1.lowerCamelCase(m.name);
- // noinspection PointlessBooleanExpressionJS
- m.serverStreaming = !!m.serverStreaming;
- // noinspection PointlessBooleanExpressionJS
- m.clientStreaming = !!m.clientStreaming;
- m.options = (_b = m.options) !== null && _b !== void 0 ? _b : {};
- m.idempotency = (_c = m.idempotency) !== null && _c !== void 0 ? _c : undefined;
- return m;
-}
-exports.normalizeMethodInfo = normalizeMethodInfo;
-/**
- * Read custom method options from a generated service client.
- *
- * @deprecated use readMethodOption()
- */
-function readMethodOptions(service, methodName, extensionName, extensionType) {
- var _a;
- const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options;
- return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : undefined;
-}
-exports.readMethodOptions = readMethodOptions;
-function readMethodOption(service, methodName, extensionName, extensionType) {
- var _a;
- const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options;
- if (!options) {
- return undefined;
- }
- const optionVal = options[extensionName];
- if (optionVal === undefined) {
- return optionVal;
+function serializeByteArrayType(objectName, value) {
+ if (value !== undefined && value !== null) {
+ if (!(value instanceof Uint8Array)) {
+ throw new Error(`${objectName} must be of type Uint8Array.`);
+ }
+ value = encodeByteArray(value);
}
- return extensionType ? extensionType.fromJson(optionVal) : optionVal;
+ return value;
}
-exports.readMethodOption = readMethodOption;
-function readServiceOption(service, extensionName, extensionType) {
- const options = service.options;
- if (!options) {
- return undefined;
- }
- const optionVal = options[extensionName];
- if (optionVal === undefined) {
- return optionVal;
+function serializeBase64UrlType(objectName, value) {
+ if (value !== undefined && value !== null) {
+ if (!(value instanceof Uint8Array)) {
+ throw new Error(`${objectName} must be of type Uint8Array.`);
+ }
+ value = bufferToBase64Url(value);
}
- return extensionType ? extensionType.fromJson(optionVal) : optionVal;
+ return value;
}
-exports.readServiceOption = readServiceOption;
-
-
-/***/ }),
-
-/***/ 8636:
-/***/ ((__unused_webpack_module, exports) => {
-
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.RpcError = void 0;
-/**
- * An error that occurred while calling a RPC method.
- */
-class RpcError extends Error {
- constructor(message, code = 'UNKNOWN', meta) {
- super(message);
- this.name = 'RpcError';
- // see https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#example
- Object.setPrototypeOf(this, new.target.prototype);
- this.code = code;
- this.meta = meta !== null && meta !== void 0 ? meta : {};
- }
- toString() {
- const l = [this.name + ': ' + this.message];
- if (this.code) {
- l.push('');
- l.push('Code: ' + this.code);
+function serializeDateTypes(typeName, value, objectName) {
+ if (value !== undefined && value !== null) {
+ if (typeName.match(/^Date$/i) !== null) {
+ if (!(value instanceof Date ||
+ (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
+ throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`);
+ }
+ value =
+ value instanceof Date
+ ? value.toISOString().substring(0, 10)
+ : new Date(value).toISOString().substring(0, 10);
}
- if (this.serviceName && this.methodName) {
- l.push('Method: ' + this.serviceName + '/' + this.methodName);
+ else if (typeName.match(/^DateTime$/i) !== null) {
+ if (!(value instanceof Date ||
+ (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
+ throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`);
+ }
+ value = value instanceof Date ? value.toISOString() : new Date(value).toISOString();
}
- let m = Object.entries(this.meta);
- if (m.length) {
- l.push('');
- l.push('Meta:');
- for (let [k, v] of m) {
- l.push(` ${k}: ${v}`);
+ else if (typeName.match(/^DateTimeRfc1123$/i) !== null) {
+ if (!(value instanceof Date ||
+ (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
+ throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123 format.`);
+ }
+ value = value instanceof Date ? value.toUTCString() : new Date(value).toUTCString();
+ }
+ else if (typeName.match(/^UnixTime$/i) !== null) {
+ if (!(value instanceof Date ||
+ (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
+ throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123/ISO8601 format ` +
+ `for it to be serialized in UnixTime/Epoch format.`);
+ }
+ value = dateToUnixTime(value);
+ }
+ else if (typeName.match(/^TimeSpan$/i) !== null) {
+ if (!isDuration(value)) {
+ throw new Error(`${objectName} must be a string in ISO 8601 format. Instead was "${value}".`);
}
}
- return l.join('\n');
}
+ return value;
}
-exports.RpcError = RpcError;
-
-
-/***/ }),
-
-/***/ 2849:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.stackDuplexStreamingInterceptors = exports.stackClientStreamingInterceptors = exports.stackServerStreamingInterceptors = exports.stackUnaryInterceptors = exports.stackIntercept = void 0;
-const runtime_1 = __nccwpck_require__(8886);
-/**
- * Creates a "stack" of of all interceptors specified in the given `RpcOptions`.
- * Used by generated client implementations.
- * @internal
- */
-function stackIntercept(kind, transport, method, options, input) {
- var _a, _b, _c, _d;
- if (kind == "unary") {
- let tail = (mtd, inp, opt) => transport.unary(mtd, inp, opt);
- for (const curr of ((_a = options.interceptors) !== null && _a !== void 0 ? _a : []).filter(i => i.interceptUnary).reverse()) {
- const next = tail;
- tail = (mtd, inp, opt) => curr.interceptUnary(next, mtd, inp, opt);
- }
- return tail(method, input, options);
+function serializeSequenceType(serializer, mapper, object, objectName, isXml, options) {
+ if (!Array.isArray(object)) {
+ throw new Error(`${objectName} must be of type Array.`);
}
- if (kind == "serverStreaming") {
- let tail = (mtd, inp, opt) => transport.serverStreaming(mtd, inp, opt);
- for (const curr of ((_b = options.interceptors) !== null && _b !== void 0 ? _b : []).filter(i => i.interceptServerStreaming).reverse()) {
- const next = tail;
- tail = (mtd, inp, opt) => curr.interceptServerStreaming(next, mtd, inp, opt);
- }
- return tail(method, input, options);
+ let elementType = mapper.type.element;
+ if (!elementType || typeof elementType !== "object") {
+ throw new Error(`element" metadata for an Array must be defined in the ` +
+ `mapper and it must of type "object" in ${objectName}.`);
}
- if (kind == "clientStreaming") {
- let tail = (mtd, opt) => transport.clientStreaming(mtd, opt);
- for (const curr of ((_c = options.interceptors) !== null && _c !== void 0 ? _c : []).filter(i => i.interceptClientStreaming).reverse()) {
- const next = tail;
- tail = (mtd, opt) => curr.interceptClientStreaming(next, mtd, opt);
- }
- return tail(method, options);
+ // Quirk: Composite mappers referenced by `element` might
+ // not have *all* properties declared (like uberParent),
+ // so let's try to look up the full definition by name.
+ if (elementType.type.name === "Composite" && elementType.type.className) {
+ elementType = serializer.modelMappers[elementType.type.className] ?? elementType;
}
- if (kind == "duplex") {
- let tail = (mtd, opt) => transport.duplex(mtd, opt);
- for (const curr of ((_d = options.interceptors) !== null && _d !== void 0 ? _d : []).filter(i => i.interceptDuplex).reverse()) {
- const next = tail;
- tail = (mtd, opt) => curr.interceptDuplex(next, mtd, opt);
+ const tempArray = [];
+ for (let i = 0; i < object.length; i++) {
+ const serializedValue = serializer.serialize(elementType, object[i], objectName, options);
+ if (isXml && elementType.xmlNamespace) {
+ const xmlnsKey = elementType.xmlNamespacePrefix
+ ? `xmlns:${elementType.xmlNamespacePrefix}`
+ : "xmlns";
+ if (elementType.type.name === "Composite") {
+ tempArray[i] = { ...serializedValue };
+ tempArray[i][XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace };
+ }
+ else {
+ tempArray[i] = {};
+ tempArray[i][options.xml.xmlCharKey] = serializedValue;
+ tempArray[i][XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace };
+ }
+ }
+ else {
+ tempArray[i] = serializedValue;
}
- return tail(method, options);
}
- runtime_1.assertNever(kind);
-}
-exports.stackIntercept = stackIntercept;
-/**
- * @deprecated replaced by `stackIntercept()`, still here to support older generated code
- */
-function stackUnaryInterceptors(transport, method, input, options) {
- return stackIntercept("unary", transport, method, options, input);
+ return tempArray;
}
-exports.stackUnaryInterceptors = stackUnaryInterceptors;
-/**
- * @deprecated replaced by `stackIntercept()`, still here to support older generated code
- */
-function stackServerStreamingInterceptors(transport, method, input, options) {
- return stackIntercept("serverStreaming", transport, method, options, input);
+function serializeDictionaryType(serializer, mapper, object, objectName, isXml, options) {
+ if (typeof object !== "object") {
+ throw new Error(`${objectName} must be of type object.`);
+ }
+ const valueType = mapper.type.value;
+ if (!valueType || typeof valueType !== "object") {
+ throw new Error(`"value" metadata for a Dictionary must be defined in the ` +
+ `mapper and it must of type "object" in ${objectName}.`);
+ }
+ const tempDictionary = {};
+ for (const key of Object.keys(object)) {
+ const serializedValue = serializer.serialize(valueType, object[key], objectName, options);
+ // If the element needs an XML namespace we need to add it within the $ property
+ tempDictionary[key] = getXmlObjectValue(valueType, serializedValue, isXml, options);
+ }
+ // Add the namespace to the root element if needed
+ if (isXml && mapper.xmlNamespace) {
+ const xmlnsKey = mapper.xmlNamespacePrefix ? `xmlns:${mapper.xmlNamespacePrefix}` : "xmlns";
+ const result = tempDictionary;
+ result[XML_ATTRKEY] = { [xmlnsKey]: mapper.xmlNamespace };
+ return result;
+ }
+ return tempDictionary;
}
-exports.stackServerStreamingInterceptors = stackServerStreamingInterceptors;
/**
- * @deprecated replaced by `stackIntercept()`, still here to support older generated code
+ * Resolves the additionalProperties property from a referenced mapper
+ * @param serializer - the serializer containing the entire set of mappers
+ * @param mapper - the composite mapper to resolve
+ * @param objectName - name of the object being serialized
*/
-function stackClientStreamingInterceptors(transport, method, options) {
- return stackIntercept("clientStreaming", transport, method, options);
+function resolveAdditionalProperties(serializer, mapper, objectName) {
+ const additionalProperties = mapper.type.additionalProperties;
+ if (!additionalProperties && mapper.type.className) {
+ const modelMapper = resolveReferencedMapper(serializer, mapper, objectName);
+ return modelMapper?.type.additionalProperties;
+ }
+ return additionalProperties;
}
-exports.stackClientStreamingInterceptors = stackClientStreamingInterceptors;
/**
- * @deprecated replaced by `stackIntercept()`, still here to support older generated code
+ * Finds the mapper referenced by className
+ * @param serializer - the serializer containing the entire set of mappers
+ * @param mapper - the composite mapper to resolve
+ * @param objectName - name of the object being serialized
*/
-function stackDuplexStreamingInterceptors(transport, method, options) {
- return stackIntercept("duplex", transport, method, options);
+function resolveReferencedMapper(serializer, mapper, objectName) {
+ const className = mapper.type.className;
+ if (!className) {
+ throw new Error(`Class name for model "${objectName}" is not provided in the mapper "${JSON.stringify(mapper, undefined, 2)}".`);
+ }
+ return serializer.modelMappers[className];
}
-exports.stackDuplexStreamingInterceptors = stackDuplexStreamingInterceptors;
-
-
-/***/ }),
-
-/***/ 8576:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.mergeRpcOptions = void 0;
-const runtime_1 = __nccwpck_require__(8886);
/**
- * Merges custom RPC options with defaults. Returns a new instance and keeps
- * the "defaults" and the "options" unmodified.
- *
- * Merges `RpcMetadata` "meta", overwriting values from "defaults" with
- * values from "options". Does not append values to existing entries.
- *
- * Merges "jsonOptions", including "jsonOptions.typeRegistry", by creating
- * a new array that contains types from "options.jsonOptions.typeRegistry"
- * first, then types from "defaults.jsonOptions.typeRegistry".
- *
- * Merges "binaryOptions".
- *
- * Merges "interceptors" by creating a new array that contains interceptors
- * from "defaults" first, then interceptors from "options".
- *
- * Works with objects that extend `RpcOptions`, but only if the added
- * properties are of type Date, primitive like string, boolean, or Array
- * of primitives. If you have other property types, you have to merge them
- * yourself.
+ * Resolves a composite mapper's modelProperties.
+ * @param serializer - the serializer containing the entire set of mappers
+ * @param mapper - the composite mapper to resolve
*/
-function mergeRpcOptions(defaults, options) {
- if (!options)
- return defaults;
- let o = {};
- copy(defaults, o);
- copy(options, o);
- for (let key of Object.keys(options)) {
- let val = options[key];
- switch (key) {
- case "jsonOptions":
- o.jsonOptions = runtime_1.mergeJsonOptions(defaults.jsonOptions, o.jsonOptions);
- break;
- case "binaryOptions":
- o.binaryOptions = runtime_1.mergeBinaryOptions(defaults.binaryOptions, o.binaryOptions);
- break;
- case "meta":
- o.meta = {};
- copy(defaults.meta, o.meta);
- copy(options.meta, o.meta);
- break;
- case "interceptors":
- o.interceptors = defaults.interceptors ? defaults.interceptors.concat(val) : val.concat();
- break;
+function resolveModelProperties(serializer, mapper, objectName) {
+ let modelProps = mapper.type.modelProperties;
+ if (!modelProps) {
+ const modelMapper = resolveReferencedMapper(serializer, mapper, objectName);
+ if (!modelMapper) {
+ throw new Error(`mapper() cannot be null or undefined for model "${mapper.type.className}".`);
+ }
+ modelProps = modelMapper?.type.modelProperties;
+ if (!modelProps) {
+ throw new Error(`modelProperties cannot be null or undefined in the ` +
+ `mapper "${JSON.stringify(modelMapper)}" of type "${mapper.type.className}" for object "${objectName}".`);
}
}
- return o;
-}
-exports.mergeRpcOptions = mergeRpcOptions;
-function copy(a, into) {
- if (!a)
- return;
- let c = into;
- for (let [k, v] of Object.entries(a)) {
- if (v instanceof Date)
- c[k] = new Date(v.getTime());
- else if (Array.isArray(v))
- c[k] = v.concat();
- else
- c[k] = v;
- }
+ return modelProps;
}
-
-
-/***/ }),
-
-/***/ 2726:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.RpcOutputStreamController = void 0;
-const deferred_1 = __nccwpck_require__(1409);
-const runtime_1 = __nccwpck_require__(8886);
-/**
- * A `RpcOutputStream` that you control.
- */
-class RpcOutputStreamController {
- constructor() {
- this._lis = {
- nxt: [],
- msg: [],
- err: [],
- cmp: [],
- };
- this._closed = false;
- // --- RpcOutputStream async iterator API
- // iterator state.
- // is undefined when no iterator has been acquired yet.
- this._itState = { q: [] };
- }
- // --- RpcOutputStream callback API
- onNext(callback) {
- return this.addLis(callback, this._lis.nxt);
- }
- onMessage(callback) {
- return this.addLis(callback, this._lis.msg);
- }
- onError(callback) {
- return this.addLis(callback, this._lis.err);
- }
- onComplete(callback) {
- return this.addLis(callback, this._lis.cmp);
+function serializeCompositeType(serializer, mapper, object, objectName, isXml, options) {
+ if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) {
+ mapper = getPolymorphicMapper(serializer, mapper, object, "clientName");
}
- addLis(callback, list) {
- list.push(callback);
- return () => {
- let i = list.indexOf(callback);
- if (i >= 0)
- list.splice(i, 1);
- };
- }
- // remove all listeners
- clearLis() {
- for (let l of Object.values(this._lis))
- l.splice(0, l.length);
- }
- // --- Controller API
- /**
- * Is this stream already closed by a completion or error?
- */
- get closed() {
- return this._closed !== false;
- }
- /**
- * Emit message, close with error, or close successfully, but only one
- * at a time.
- * Can be used to wrap a stream by using the other stream's `onNext`.
- */
- notifyNext(message, error, complete) {
- runtime_1.assert((message ? 1 : 0) + (error ? 1 : 0) + (complete ? 1 : 0) <= 1, 'only one emission at a time');
- if (message)
- this.notifyMessage(message);
- if (error)
- this.notifyError(error);
- if (complete)
- this.notifyComplete();
- }
- /**
- * Emits a new message. Throws if stream is closed.
- *
- * Triggers onNext and onMessage callbacks.
- */
- notifyMessage(message) {
- runtime_1.assert(!this.closed, 'stream is closed');
- this.pushIt({ value: message, done: false });
- this._lis.msg.forEach(l => l(message));
- this._lis.nxt.forEach(l => l(message, undefined, false));
- }
- /**
- * Closes the stream with an error. Throws if stream is closed.
- *
- * Triggers onNext and onError callbacks.
- */
- notifyError(error) {
- runtime_1.assert(!this.closed, 'stream is closed');
- this._closed = error;
- this.pushIt(error);
- this._lis.err.forEach(l => l(error));
- this._lis.nxt.forEach(l => l(undefined, error, false));
- this.clearLis();
- }
- /**
- * Closes the stream successfully. Throws if stream is closed.
- *
- * Triggers onNext and onComplete callbacks.
- */
- notifyComplete() {
- runtime_1.assert(!this.closed, 'stream is closed');
- this._closed = true;
- this.pushIt({ value: null, done: true });
- this._lis.cmp.forEach(l => l());
- this._lis.nxt.forEach(l => l(undefined, undefined, true));
- this.clearLis();
+ if (object !== undefined && object !== null) {
+ const payload = {};
+ const modelProps = resolveModelProperties(serializer, mapper, objectName);
+ for (const key of Object.keys(modelProps)) {
+ const propertyMapper = modelProps[key];
+ if (propertyMapper.readOnly) {
+ continue;
+ }
+ let propName;
+ let parentObject = payload;
+ if (serializer.isXML) {
+ if (propertyMapper.xmlIsWrapped) {
+ propName = propertyMapper.xmlName;
+ }
+ else {
+ propName = propertyMapper.xmlElementName || propertyMapper.xmlName;
+ }
+ }
+ else {
+ const paths = splitSerializeName(propertyMapper.serializedName);
+ propName = paths.pop();
+ for (const pathName of paths) {
+ const childObject = parentObject[pathName];
+ if ((childObject === undefined || childObject === null) &&
+ ((object[key] !== undefined && object[key] !== null) ||
+ propertyMapper.defaultValue !== undefined)) {
+ parentObject[pathName] = {};
+ }
+ parentObject = parentObject[pathName];
+ }
+ }
+ if (parentObject !== undefined && parentObject !== null) {
+ if (isXml && mapper.xmlNamespace) {
+ const xmlnsKey = mapper.xmlNamespacePrefix
+ ? `xmlns:${mapper.xmlNamespacePrefix}`
+ : "xmlns";
+ parentObject[XML_ATTRKEY] = {
+ ...parentObject[XML_ATTRKEY],
+ [xmlnsKey]: mapper.xmlNamespace,
+ };
+ }
+ const propertyObjectName = propertyMapper.serializedName !== ""
+ ? objectName + "." + propertyMapper.serializedName
+ : objectName;
+ let toSerialize = object[key];
+ const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper);
+ if (polymorphicDiscriminator &&
+ polymorphicDiscriminator.clientName === key &&
+ (toSerialize === undefined || toSerialize === null)) {
+ toSerialize = mapper.serializedName;
+ }
+ const serializedValue = serializer.serialize(propertyMapper, toSerialize, propertyObjectName, options);
+ if (serializedValue !== undefined && propName !== undefined && propName !== null) {
+ const value = getXmlObjectValue(propertyMapper, serializedValue, isXml, options);
+ if (isXml && propertyMapper.xmlIsAttribute) {
+ // XML_ATTRKEY, i.e., $ is the key attributes are kept under in xml2js.
+ // This keeps things simple while preventing name collision
+ // with names in user documents.
+ parentObject[XML_ATTRKEY] = parentObject[XML_ATTRKEY] || {};
+ parentObject[XML_ATTRKEY][propName] = serializedValue;
+ }
+ else if (isXml && propertyMapper.xmlIsWrapped) {
+ parentObject[propName] = { [propertyMapper.xmlElementName]: value };
+ }
+ else {
+ parentObject[propName] = value;
+ }
+ }
+ }
+ }
+ const additionalPropertiesMapper = resolveAdditionalProperties(serializer, mapper, objectName);
+ if (additionalPropertiesMapper) {
+ const propNames = Object.keys(modelProps);
+ for (const clientPropName in object) {
+ const isAdditionalProperty = propNames.every((pn) => pn !== clientPropName);
+ if (isAdditionalProperty) {
+ payload[clientPropName] = serializer.serialize(additionalPropertiesMapper, object[clientPropName], objectName + '["' + clientPropName + '"]', options);
+ }
+ }
+ }
+ return payload;
}
- /**
- * Creates an async iterator (that can be used with `for await {...}`)
- * to consume the stream.
- *
- * Some things to note:
- * - If an error occurs, the `for await` will throw it.
- * - If an error occurred before the `for await` was started, `for await`
- * will re-throw it.
- * - If the stream is already complete, the `for await` will be empty.
- * - If your `for await` consumes slower than the stream produces,
- * for example because you are relaying messages in a slow operation,
- * messages are queued.
- */
- [Symbol.asyncIterator]() {
- // if we are closed, we are definitely not receiving any more messages.
- // but we can't let the iterator get stuck. we want to either:
- // a) finish the new iterator immediately, because we are completed
- // b) reject the new iterator, because we errored
- if (this._closed === true)
- this.pushIt({ value: null, done: true });
- else if (this._closed !== false)
- this.pushIt(this._closed);
- // the async iterator
- return {
- next: () => {
- let state = this._itState;
- runtime_1.assert(state, "bad state"); // if we don't have a state here, code is broken
- // there should be no pending result.
- // did the consumer call next() before we resolved our previous result promise?
- runtime_1.assert(!state.p, "iterator contract broken");
- // did we produce faster than the iterator consumed?
- // return the oldest result from the queue.
- let first = state.q.shift();
- if (first)
- return ("value" in first) ? Promise.resolve(first) : Promise.reject(first);
- // we have no result ATM, but we promise one.
- // as soon as we have a result, we must resolve promise.
- state.p = new deferred_1.Deferred();
- return state.p.promise;
- },
- };
+ return object;
+}
+function getXmlObjectValue(propertyMapper, serializedValue, isXml, options) {
+ if (!isXml || !propertyMapper.xmlNamespace) {
+ return serializedValue;
}
- // "push" a new iterator result.
- // this either resolves a pending promise, or enqueues the result.
- pushIt(result) {
- let state = this._itState;
- // is the consumer waiting for us?
- if (state.p) {
- // yes, consumer is waiting for this promise.
- const p = state.p;
- runtime_1.assert(p.state == deferred_1.DeferredState.PENDING, "iterator contract broken");
- // resolve the promise
- ("value" in result) ? p.resolve(result) : p.reject(result);
- // must cleanup, otherwise iterator.next() would pick it up again.
- delete state.p;
+ const xmlnsKey = propertyMapper.xmlNamespacePrefix
+ ? `xmlns:${propertyMapper.xmlNamespacePrefix}`
+ : "xmlns";
+ const xmlNamespace = { [xmlnsKey]: propertyMapper.xmlNamespace };
+ if (["Composite"].includes(propertyMapper.type.name)) {
+ if (serializedValue[XML_ATTRKEY]) {
+ return serializedValue;
}
else {
- // we are producing faster than the iterator consumes.
- // push result onto queue.
- state.q.push(result);
+ const result = { ...serializedValue };
+ result[XML_ATTRKEY] = xmlNamespace;
+ return result;
}
}
+ const result = {};
+ result[options.xml.xmlCharKey] = serializedValue;
+ result[XML_ATTRKEY] = xmlNamespace;
+ return result;
}
-exports.RpcOutputStreamController = RpcOutputStreamController;
-
-
-/***/ }),
-
-/***/ 3352:
-/***/ ((__unused_webpack_module, exports) => {
-
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.ServerCallContextController = void 0;
-class ServerCallContextController {
- constructor(method, headers, deadline, sendResponseHeadersFn, defaultStatus = { code: 'OK', detail: '' }) {
- this._cancelled = false;
- this._listeners = [];
- this.method = method;
- this.headers = headers;
- this.deadline = deadline;
- this.trailers = {};
- this._sendRH = sendResponseHeadersFn;
- this.status = defaultStatus;
+function isSpecialXmlProperty(propertyName, options) {
+ return [XML_ATTRKEY, options.xml.xmlCharKey].includes(propertyName);
+}
+function deserializeCompositeType(serializer, mapper, responseBody, objectName, options) {
+ const xmlCharKey = options.xml.xmlCharKey ?? XML_CHARKEY;
+ if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) {
+ mapper = getPolymorphicMapper(serializer, mapper, responseBody, "serializedName");
}
- /**
- * Set the call cancelled.
- *
- * Invokes all callbacks registered with onCancel() and
- * sets `cancelled = true`.
- */
- notifyCancelled() {
- if (!this._cancelled) {
- this._cancelled = true;
- for (let l of this._listeners) {
- l();
+ const modelProps = resolveModelProperties(serializer, mapper, objectName);
+ let instance = {};
+ const handledPropertyNames = [];
+ for (const key of Object.keys(modelProps)) {
+ const propertyMapper = modelProps[key];
+ const paths = splitSerializeName(modelProps[key].serializedName);
+ handledPropertyNames.push(paths[0]);
+ const { serializedName, xmlName, xmlElementName } = propertyMapper;
+ let propertyObjectName = objectName;
+ if (serializedName !== "" && serializedName !== undefined) {
+ propertyObjectName = objectName + "." + serializedName;
+ }
+ const headerCollectionPrefix = propertyMapper.headerCollectionPrefix;
+ if (headerCollectionPrefix) {
+ const dictionary = {};
+ for (const headerKey of Object.keys(responseBody)) {
+ if (headerKey.startsWith(headerCollectionPrefix)) {
+ dictionary[headerKey.substring(headerCollectionPrefix.length)] = serializer.deserialize(propertyMapper.type.value, responseBody[headerKey], propertyObjectName, options);
+ }
+ handledPropertyNames.push(headerKey);
+ }
+ instance[key] = dictionary;
+ }
+ else if (serializer.isXML) {
+ if (propertyMapper.xmlIsAttribute && responseBody[XML_ATTRKEY]) {
+ instance[key] = serializer.deserialize(propertyMapper, responseBody[XML_ATTRKEY][xmlName], propertyObjectName, options);
+ }
+ else if (propertyMapper.xmlIsMsText) {
+ if (responseBody[xmlCharKey] !== undefined) {
+ instance[key] = responseBody[xmlCharKey];
+ }
+ else if (typeof responseBody === "string") {
+ // The special case where xml parser parses "content" into JSON of
+ // `{ name: "content"}` instead of `{ name: { "_": "content" }}`
+ instance[key] = responseBody;
+ }
+ }
+ else {
+ const propertyName = xmlElementName || xmlName || serializedName;
+ if (propertyMapper.xmlIsWrapped) {
+ /* a list of wrapped by
+ For the xml example below
+
+ ...
+ ...
+
+ the responseBody has
+ {
+ Cors: {
+ CorsRule: [{...}, {...}]
+ }
+ }
+ xmlName is "Cors" and xmlElementName is"CorsRule".
+ */
+ const wrapped = responseBody[xmlName];
+ const elementList = wrapped?.[xmlElementName] ?? [];
+ instance[key] = serializer.deserialize(propertyMapper, elementList, propertyObjectName, options);
+ handledPropertyNames.push(xmlName);
+ }
+ else {
+ const property = responseBody[propertyName];
+ instance[key] = serializer.deserialize(propertyMapper, property, propertyObjectName, options);
+ handledPropertyNames.push(propertyName);
+ }
+ }
+ }
+ else {
+ // deserialize the property if it is present in the provided responseBody instance
+ let propertyInstance;
+ let res = responseBody;
+ // traversing the object step by step.
+ let steps = 0;
+ for (const item of paths) {
+ if (!res)
+ break;
+ steps++;
+ res = res[item];
+ }
+ // only accept null when reaching the last position of object otherwise it would be undefined
+ if (res === null && steps < paths.length) {
+ res = undefined;
+ }
+ propertyInstance = res;
+ const polymorphicDiscriminator = mapper.type.polymorphicDiscriminator;
+ // checking that the model property name (key)(ex: "fishtype") and the
+ // clientName of the polymorphicDiscriminator {metadata} (ex: "fishtype")
+ // instead of the serializedName of the polymorphicDiscriminator (ex: "fish.type")
+ // is a better approach. The generator is not consistent with escaping '\.' in the
+ // serializedName of the property (ex: "fish\.type") that is marked as polymorphic discriminator
+ // and the serializedName of the metadata polymorphicDiscriminator (ex: "fish.type"). However,
+ // the clientName transformation of the polymorphicDiscriminator (ex: "fishtype") and
+ // the transformation of model property name (ex: "fishtype") is done consistently.
+ // Hence, it is a safer bet to rely on the clientName of the polymorphicDiscriminator.
+ if (polymorphicDiscriminator &&
+ key === polymorphicDiscriminator.clientName &&
+ (propertyInstance === undefined || propertyInstance === null)) {
+ propertyInstance = mapper.serializedName;
+ }
+ let serializedValue;
+ // paging
+ if (Array.isArray(responseBody[key]) && modelProps[key].serializedName === "") {
+ propertyInstance = responseBody[key];
+ const arrayInstance = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options);
+ // Copy over any properties that have already been added into the instance, where they do
+ // not exist on the newly de-serialized array
+ for (const [k, v] of Object.entries(instance)) {
+ if (!Object.prototype.hasOwnProperty.call(arrayInstance, k)) {
+ arrayInstance[k] = v;
+ }
+ }
+ instance = arrayInstance;
+ }
+ else if (propertyInstance !== undefined || propertyMapper.defaultValue !== undefined) {
+ serializedValue = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options);
+ instance[key] = serializedValue;
}
}
}
- /**
- * Send response headers.
- */
- sendResponseHeaders(data) {
- this._sendRH(data);
- }
- /**
- * Is the call cancelled?
- *
- * When the client closes the connection before the server
- * is done, the call is cancelled.
- *
- * If you want to cancel a request on the server, throw a
- * RpcError with the CANCELLED status code.
- */
- get cancelled() {
- return this._cancelled;
- }
- /**
- * Add a callback for cancellation.
- */
- onCancel(callback) {
- const l = this._listeners;
- l.push(callback);
- return () => {
- let i = l.indexOf(callback);
- if (i >= 0)
- l.splice(i, 1);
+ const additionalPropertiesMapper = mapper.type.additionalProperties;
+ if (additionalPropertiesMapper) {
+ const isAdditionalProperty = (responsePropName) => {
+ for (const clientPropName in modelProps) {
+ const paths = splitSerializeName(modelProps[clientPropName].serializedName);
+ if (paths[0] === responsePropName) {
+ return false;
+ }
+ }
+ return true;
};
+ for (const responsePropName in responseBody) {
+ if (isAdditionalProperty(responsePropName)) {
+ instance[responsePropName] = serializer.deserialize(additionalPropertiesMapper, responseBody[responsePropName], objectName + '["' + responsePropName + '"]', options);
+ }
+ }
}
-}
-exports.ServerCallContextController = ServerCallContextController;
-
-
-/***/ }),
-
-/***/ 6173:
-/***/ (function(__unused_webpack_module, exports) {
-
-
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.ServerStreamingCall = void 0;
-/**
- * A server streaming RPC call. The client provides exactly one input message
- * but the server may respond with 0, 1, or more messages.
- */
-class ServerStreamingCall {
- constructor(method, requestHeaders, request, headers, response, status, trailers) {
- this.method = method;
- this.requestHeaders = requestHeaders;
- this.request = request;
- this.headers = headers;
- this.responses = response;
- this.status = status;
- this.trailers = trailers;
+ else if (responseBody && !options.ignoreUnknownProperties) {
+ for (const key of Object.keys(responseBody)) {
+ if (instance[key] === undefined &&
+ !handledPropertyNames.includes(key) &&
+ !isSpecialXmlProperty(key, options)) {
+ instance[key] = responseBody[key];
+ }
+ }
}
- /**
- * Instead of awaiting the response status and trailers, you can
- * just as well await this call itself to receive the server outcome.
- * You should first setup some listeners to the `request` to
- * see the actual messages the server replied with.
- */
- then(onfulfilled, onrejected) {
- return this.promiseFinished().then(value => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, reason => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason));
+ return instance;
+}
+function deserializeDictionaryType(serializer, mapper, responseBody, objectName, options) {
+ /* jshint validthis: true */
+ const value = mapper.type.value;
+ if (!value || typeof value !== "object") {
+ throw new Error(`"value" metadata for a Dictionary must be defined in the ` +
+ `mapper and it must of type "object" in ${objectName}`);
}
- promiseFinished() {
- return __awaiter(this, void 0, void 0, function* () {
- let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]);
- return {
- method: this.method,
- requestHeaders: this.requestHeaders,
- request: this.request,
- headers,
- status,
- trailers,
- };
- });
+ if (responseBody) {
+ const tempDictionary = {};
+ for (const key of Object.keys(responseBody)) {
+ tempDictionary[key] = serializer.deserialize(value, responseBody[key], objectName, options);
+ }
+ return tempDictionary;
}
+ return responseBody;
}
-exports.ServerStreamingCall = ServerStreamingCall;
-
-
-/***/ }),
-
-/***/ 6892:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.ServiceType = void 0;
-const reflection_info_1 = __nccwpck_require__(2496);
-class ServiceType {
- constructor(typeName, methods, options) {
- this.typeName = typeName;
- this.methods = methods.map(i => reflection_info_1.normalizeMethodInfo(i, this));
- this.options = options !== null && options !== void 0 ? options : {};
- }
-}
-exports.ServiceType = ServiceType;
-
-
-/***/ }),
-
-/***/ 9122:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
-
-
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.TestTransport = void 0;
-const rpc_error_1 = __nccwpck_require__(8636);
-const runtime_1 = __nccwpck_require__(8886);
-const rpc_output_stream_1 = __nccwpck_require__(2726);
-const rpc_options_1 = __nccwpck_require__(8576);
-const unary_call_1 = __nccwpck_require__(9288);
-const server_streaming_call_1 = __nccwpck_require__(6173);
-const client_streaming_call_1 = __nccwpck_require__(7889);
-const duplex_streaming_call_1 = __nccwpck_require__(6826);
-/**
- * Transport for testing.
- */
-class TestTransport {
- /**
- * Initialize with mock data. Omitted fields have default value.
- */
- constructor(data) {
- /**
- * Suppress warning / error about uncaught rejections of
- * "status" and "trailers".
- */
- this.suppressUncaughtRejections = true;
- this.headerDelay = 10;
- this.responseDelay = 50;
- this.betweenResponseDelay = 10;
- this.afterResponseDelay = 10;
- this.data = data !== null && data !== void 0 ? data : {};
+function deserializeSequenceType(serializer, mapper, responseBody, objectName, options) {
+ let element = mapper.type.element;
+ if (!element || typeof element !== "object") {
+ throw new Error(`element" metadata for an Array must be defined in the ` +
+ `mapper and it must of type "object" in ${objectName}`);
}
- /**
- * Sent message(s) during the last operation.
- */
- get sentMessages() {
- if (this.lastInput instanceof TestInputStream) {
- return this.lastInput.sent;
- }
- else if (typeof this.lastInput == "object") {
- return [this.lastInput.single];
+ if (responseBody) {
+ if (!Array.isArray(responseBody)) {
+ // xml2js will interpret a single element array as just the element, so force it to be an array
+ responseBody = [responseBody];
}
- return [];
- }
- /**
- * Sending message(s) completed?
- */
- get sendComplete() {
- if (this.lastInput instanceof TestInputStream) {
- return this.lastInput.completed;
+ // Quirk: Composite mappers referenced by `element` might
+ // not have *all* properties declared (like uberParent),
+ // so let's try to look up the full definition by name.
+ if (element.type.name === "Composite" && element.type.className) {
+ element = serializer.modelMappers[element.type.className] ?? element;
}
- else if (typeof this.lastInput == "object") {
- return true;
+ const tempArray = [];
+ for (let i = 0; i < responseBody.length; i++) {
+ tempArray[i] = serializer.deserialize(element, responseBody[i], `${objectName}[${i}]`, options);
}
- return false;
- }
- // Creates a promise for response headers from the mock data.
- promiseHeaders() {
- var _a;
- const headers = (_a = this.data.headers) !== null && _a !== void 0 ? _a : TestTransport.defaultHeaders;
- return headers instanceof rpc_error_1.RpcError
- ? Promise.reject(headers)
- : Promise.resolve(headers);
+ return tempArray;
}
- // Creates a promise for a single, valid, message from the mock data.
- promiseSingleResponse(method) {
- if (this.data.response instanceof rpc_error_1.RpcError) {
- return Promise.reject(this.data.response);
- }
- let r;
- if (Array.isArray(this.data.response)) {
- runtime_1.assert(this.data.response.length > 0);
- r = this.data.response[0];
- }
- else if (this.data.response !== undefined) {
- r = this.data.response;
+ return responseBody;
+}
+function getIndexDiscriminator(discriminators, discriminatorValue, typeName) {
+ const typeNamesToCheck = [typeName];
+ while (typeNamesToCheck.length) {
+ const currentName = typeNamesToCheck.shift();
+ const indexDiscriminator = discriminatorValue === currentName
+ ? discriminatorValue
+ : currentName + "." + discriminatorValue;
+ if (Object.prototype.hasOwnProperty.call(discriminators, indexDiscriminator)) {
+ return discriminators[indexDiscriminator];
}
else {
- r = method.O.create();
+ for (const [name, mapper] of Object.entries(discriminators)) {
+ if (name.startsWith(currentName + ".") &&
+ mapper.type.uberParent === currentName &&
+ mapper.type.className) {
+ typeNamesToCheck.push(mapper.type.className);
+ }
+ }
}
- runtime_1.assert(method.O.is(r));
- return Promise.resolve(r);
}
- /**
- * Pushes response messages from the mock data to the output stream.
- * If an error response, status or trailers are mocked, the stream is
- * closed with the respective error.
- * Otherwise, stream is completed successfully.
- *
- * The returned promise resolves when the stream is closed. It should
- * not reject. If it does, code is broken.
- */
- streamResponses(method, stream, abort) {
- return __awaiter(this, void 0, void 0, function* () {
- // normalize "data.response" into an array of valid output messages
- const messages = [];
- if (this.data.response === undefined) {
- messages.push(method.O.create());
+ return undefined;
+}
+function getPolymorphicMapper(serializer, mapper, object, polymorphicPropertyName) {
+ const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper);
+ if (polymorphicDiscriminator) {
+ let discriminatorName = polymorphicDiscriminator[polymorphicPropertyName];
+ if (discriminatorName) {
+ // The serializedName might have \\, which we just want to ignore
+ if (polymorphicPropertyName === "serializedName") {
+ discriminatorName = discriminatorName.replace(/\\/gi, "");
}
- else if (Array.isArray(this.data.response)) {
- for (let msg of this.data.response) {
- runtime_1.assert(method.O.is(msg));
- messages.push(msg);
+ const discriminatorValue = object[discriminatorName];
+ const typeName = mapper.type.uberParent ?? mapper.type.className;
+ if (typeof discriminatorValue === "string" && typeName) {
+ const polymorphicMapper = getIndexDiscriminator(serializer.modelMappers.discriminators, discriminatorValue, typeName);
+ if (polymorphicMapper) {
+ mapper = polymorphicMapper;
}
}
- else if (!(this.data.response instanceof rpc_error_1.RpcError)) {
- runtime_1.assert(method.O.is(this.data.response));
- messages.push(this.data.response);
- }
- // start the stream with an initial delay.
- // if the request is cancelled, notify() error and exit.
- try {
- yield delay(this.responseDelay, abort)(undefined);
- }
- catch (error) {
- stream.notifyError(error);
- return;
- }
- // if error response was mocked, notify() error (stream is now closed with error) and exit.
- if (this.data.response instanceof rpc_error_1.RpcError) {
- stream.notifyError(this.data.response);
- return;
+ }
+ }
+ return mapper;
+}
+function getPolymorphicDiscriminatorRecursively(serializer, mapper) {
+ return (mapper.type.polymorphicDiscriminator ||
+ getPolymorphicDiscriminatorSafely(serializer, mapper.type.uberParent) ||
+ getPolymorphicDiscriminatorSafely(serializer, mapper.type.className));
+}
+function getPolymorphicDiscriminatorSafely(serializer, typeName) {
+ return (typeName &&
+ serializer.modelMappers[typeName] &&
+ serializer.modelMappers[typeName].type.polymorphicDiscriminator);
+}
+/**
+ * Known types of Mappers
+ */
+const MapperTypeNames = {
+ Base64Url: "Base64Url",
+ Boolean: "Boolean",
+ ByteArray: "ByteArray",
+ Composite: "Composite",
+ Date: "Date",
+ DateTime: "DateTime",
+ DateTimeRfc1123: "DateTimeRfc1123",
+ Dictionary: "Dictionary",
+ Enum: "Enum",
+ Number: "Number",
+ Object: "Object",
+ Sequence: "Sequence",
+ String: "String",
+ Stream: "Stream",
+ TimeSpan: "TimeSpan",
+ UnixTime: "UnixTime",
+};
+//# sourceMappingURL=serializer.js.map
+// EXTERNAL MODULE: ./node_modules/@azure/core-client/dist/commonjs/state.js
+var dist_commonjs_state = __nccwpck_require__(3345);
+;// CONCATENATED MODULE: ./node_modules/@azure/core-client/dist/esm/state.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+// @ts-expect-error The recommended approach to sharing module state between ESM and CJS.
+// See https://github.com/isaacs/tshy/blob/main/README.md#module-local-state for additional information.
+
+/**
+ * Defines the shared state between CJS and ESM by re-exporting the CJS state.
+ */
+const esm_state_state = dist_commonjs_state/* state */.w;
+//# sourceMappingURL=state.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-client/dist/esm/operationHelpers.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+
+/**
+ * @internal
+ * Retrieves the value to use for a given operation argument
+ * @param operationArguments - The arguments passed from the generated client
+ * @param parameter - The parameter description
+ * @param fallbackObject - If something isn't found in the arguments bag, look here.
+ * Generally used to look at the service client properties.
+ */
+function getOperationArgumentValueFromParameter(operationArguments, parameter, fallbackObject) {
+ let parameterPath = parameter.parameterPath;
+ const parameterMapper = parameter.mapper;
+ let value;
+ if (typeof parameterPath === "string") {
+ parameterPath = [parameterPath];
+ }
+ if (Array.isArray(parameterPath)) {
+ if (parameterPath.length > 0) {
+ if (parameterMapper.isConstant) {
+ value = parameterMapper.defaultValue;
}
- // regular response messages were mocked. notify() them.
- for (let msg of messages) {
- stream.notifyMessage(msg);
- // add a short delay between responses
- // if the request is cancelled, notify() error and exit.
- try {
- yield delay(this.betweenResponseDelay, abort)(undefined);
+ else {
+ let propertySearchResult = getPropertyFromParameterPath(operationArguments, parameterPath);
+ if (!propertySearchResult.propertyFound && fallbackObject) {
+ propertySearchResult = getPropertyFromParameterPath(fallbackObject, parameterPath);
}
- catch (error) {
- stream.notifyError(error);
- return;
+ let useDefaultValue = false;
+ if (!propertySearchResult.propertyFound) {
+ useDefaultValue =
+ parameterMapper.required ||
+ (parameterPath[0] === "options" && parameterPath.length === 2);
}
+ value = useDefaultValue ? parameterMapper.defaultValue : propertySearchResult.propertyValue;
}
- // error status was mocked, notify() error (stream is now closed with error) and exit.
- if (this.data.status instanceof rpc_error_1.RpcError) {
- stream.notifyError(this.data.status);
- return;
- }
- // error trailers were mocked, notify() error (stream is now closed with error) and exit.
- if (this.data.trailers instanceof rpc_error_1.RpcError) {
- stream.notifyError(this.data.trailers);
- return;
- }
- // stream completed successfully
- stream.notifyComplete();
- });
- }
- // Creates a promise for response status from the mock data.
- promiseStatus() {
- var _a;
- const status = (_a = this.data.status) !== null && _a !== void 0 ? _a : TestTransport.defaultStatus;
- return status instanceof rpc_error_1.RpcError
- ? Promise.reject(status)
- : Promise.resolve(status);
- }
- // Creates a promise for response trailers from the mock data.
- promiseTrailers() {
- var _a;
- const trailers = (_a = this.data.trailers) !== null && _a !== void 0 ? _a : TestTransport.defaultTrailers;
- return trailers instanceof rpc_error_1.RpcError
- ? Promise.reject(trailers)
- : Promise.resolve(trailers);
+ }
}
- maybeSuppressUncaught(...promise) {
- if (this.suppressUncaughtRejections) {
- for (let p of promise) {
- p.catch(() => {
- });
+ else {
+ if (parameterMapper.required) {
+ value = {};
+ }
+ for (const propertyName in parameterPath) {
+ const propertyMapper = parameterMapper.type.modelProperties[propertyName];
+ const propertyPath = parameterPath[propertyName];
+ const propertyValue = getOperationArgumentValueFromParameter(operationArguments, {
+ parameterPath: propertyPath,
+ mapper: propertyMapper,
+ }, fallbackObject);
+ if (propertyValue !== undefined) {
+ if (!value) {
+ value = {};
+ }
+ value[propertyName] = propertyValue;
}
}
}
- mergeOptions(options) {
- return rpc_options_1.mergeRpcOptions({}, options);
- }
- unary(method, input, options) {
- var _a;
- const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders()
- .then(delay(this.headerDelay, options.abort)), responsePromise = headersPromise
- .catch(_ => {
- })
- .then(delay(this.responseDelay, options.abort))
- .then(_ => this.promiseSingleResponse(method)), statusPromise = responsePromise
- .catch(_ => {
- })
- .then(delay(this.afterResponseDelay, options.abort))
- .then(_ => this.promiseStatus()), trailersPromise = responsePromise
- .catch(_ => {
- })
- .then(delay(this.afterResponseDelay, options.abort))
- .then(_ => this.promiseTrailers());
- this.maybeSuppressUncaught(statusPromise, trailersPromise);
- this.lastInput = { single: input };
- return new unary_call_1.UnaryCall(method, requestHeaders, input, headersPromise, responsePromise, statusPromise, trailersPromise);
- }
- serverStreaming(method, input, options) {
- var _a;
- const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders()
- .then(delay(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise
- .then(delay(this.responseDelay, options.abort))
- .catch(() => {
- })
- .then(() => this.streamResponses(method, outputStream, options.abort))
- .then(delay(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise
- .then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise
- .then(() => this.promiseTrailers());
- this.maybeSuppressUncaught(statusPromise, trailersPromise);
- this.lastInput = { single: input };
- return new server_streaming_call_1.ServerStreamingCall(method, requestHeaders, input, headersPromise, outputStream, statusPromise, trailersPromise);
- }
- clientStreaming(method, options) {
- var _a;
- const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders()
- .then(delay(this.headerDelay, options.abort)), responsePromise = headersPromise
- .catch(_ => {
- })
- .then(delay(this.responseDelay, options.abort))
- .then(_ => this.promiseSingleResponse(method)), statusPromise = responsePromise
- .catch(_ => {
- })
- .then(delay(this.afterResponseDelay, options.abort))
- .then(_ => this.promiseStatus()), trailersPromise = responsePromise
- .catch(_ => {
- })
- .then(delay(this.afterResponseDelay, options.abort))
- .then(_ => this.promiseTrailers());
- this.maybeSuppressUncaught(statusPromise, trailersPromise);
- this.lastInput = new TestInputStream(this.data, options.abort);
- return new client_streaming_call_1.ClientStreamingCall(method, requestHeaders, this.lastInput, headersPromise, responsePromise, statusPromise, trailersPromise);
- }
- duplex(method, options) {
- var _a;
- const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders()
- .then(delay(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise
- .then(delay(this.responseDelay, options.abort))
- .catch(() => {
- })
- .then(() => this.streamResponses(method, outputStream, options.abort))
- .then(delay(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise
- .then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise
- .then(() => this.promiseTrailers());
- this.maybeSuppressUncaught(statusPromise, trailersPromise);
- this.lastInput = new TestInputStream(this.data, options.abort);
- return new duplex_streaming_call_1.DuplexStreamingCall(method, requestHeaders, this.lastInput, headersPromise, outputStream, statusPromise, trailersPromise);
- }
+ return value;
}
-exports.TestTransport = TestTransport;
-TestTransport.defaultHeaders = {
- responseHeader: "test"
-};
-TestTransport.defaultStatus = {
- code: "OK", detail: "all good"
-};
-TestTransport.defaultTrailers = {
- responseTrailer: "test"
-};
-function delay(ms, abort) {
- return (v) => new Promise((resolve, reject) => {
- if (abort === null || abort === void 0 ? void 0 : abort.aborted) {
- reject(new rpc_error_1.RpcError("user cancel", "CANCELLED"));
+function getPropertyFromParameterPath(parent, parameterPath) {
+ const result = { propertyFound: false };
+ let i = 0;
+ for (; i < parameterPath.length; ++i) {
+ const parameterPathPart = parameterPath[i];
+ // Make sure to check inherited properties too, so don't use hasOwnProperty().
+ if (parent && parameterPathPart in parent) {
+ parent = parent[parameterPathPart];
}
else {
- const id = setTimeout(() => resolve(v), ms);
- if (abort) {
- abort.addEventListener("abort", ev => {
- clearTimeout(id);
- reject(new rpc_error_1.RpcError("user cancel", "CANCELLED"));
- });
- }
+ break;
}
- });
-}
-class TestInputStream {
- constructor(data, abort) {
- this._completed = false;
- this._sent = [];
- this.data = data;
- this.abort = abort;
- }
- get sent() {
- return this._sent;
}
- get completed() {
- return this._completed;
+ if (i === parameterPath.length) {
+ result.propertyValue = parent;
+ result.propertyFound = true;
}
- send(message) {
- if (this.data.inputMessage instanceof rpc_error_1.RpcError) {
- return Promise.reject(this.data.inputMessage);
- }
- const delayMs = this.data.inputMessage === undefined
- ? 10
- : this.data.inputMessage;
- return Promise.resolve(undefined)
- .then(() => {
- this._sent.push(message);
- })
- .then(delay(delayMs, this.abort));
+ return result;
+}
+const originalRequestSymbol = Symbol.for("@azure/core-client original request");
+function hasOriginalRequest(request) {
+ return originalRequestSymbol in request;
+}
+function getOperationRequestInfo(request) {
+ if (hasOriginalRequest(request)) {
+ return getOperationRequestInfo(request[originalRequestSymbol]);
}
- complete() {
- if (this.data.inputComplete instanceof rpc_error_1.RpcError) {
- return Promise.reject(this.data.inputComplete);
- }
- const delayMs = this.data.inputComplete === undefined
- ? 10
- : this.data.inputComplete;
- return Promise.resolve(undefined)
- .then(() => {
- this._completed = true;
- })
- .then(delay(delayMs, this.abort));
+ let info = esm_state_state.operationRequestMap.get(request);
+ if (!info) {
+ info = {};
+ esm_state_state.operationRequestMap.set(request, info);
}
+ return info;
}
+//# sourceMappingURL=operationHelpers.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-client/dist/esm/deserializationPolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
-/***/ }),
-
-/***/ 9288:
-/***/ (function(__unused_webpack_module, exports) {
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.UnaryCall = void 0;
+const defaultJsonContentTypes = ["application/json", "text/json"];
+const defaultXmlContentTypes = ["application/xml", "application/atom+xml"];
/**
- * A unary RPC call. Unary means there is exactly one input message and
- * exactly one output message unless an error occurred.
+ * The programmatic identifier of the deserializationPolicy.
*/
-class UnaryCall {
- constructor(method, requestHeaders, request, headers, response, status, trailers) {
- this.method = method;
- this.requestHeaders = requestHeaders;
- this.request = request;
- this.headers = headers;
- this.response = response;
- this.status = status;
- this.trailers = trailers;
+const deserializationPolicyName = "deserializationPolicy";
+/**
+ * This policy handles parsing out responses according to OperationSpecs on the request.
+ */
+function deserializationPolicy(options = {}) {
+ const jsonContentTypes = options.expectedContentTypes?.json ?? defaultJsonContentTypes;
+ const xmlContentTypes = options.expectedContentTypes?.xml ?? defaultXmlContentTypes;
+ const parseXML = options.parseXML;
+ const serializerOptions = options.serializerOptions;
+ const updatedOptions = {
+ xml: {
+ rootName: serializerOptions?.xml.rootName ?? "",
+ includeRoot: serializerOptions?.xml.includeRoot ?? false,
+ xmlCharKey: serializerOptions?.xml.xmlCharKey ?? XML_CHARKEY,
+ },
+ };
+ return {
+ name: deserializationPolicyName,
+ async sendRequest(request, next) {
+ const response = await next(request);
+ return deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, updatedOptions, parseXML);
+ },
+ };
+}
+function getOperationResponseMap(parsedResponse) {
+ let result;
+ const request = parsedResponse.request;
+ const operationInfo = getOperationRequestInfo(request);
+ const operationSpec = operationInfo?.operationSpec;
+ if (operationSpec) {
+ if (!operationInfo?.operationResponseGetter) {
+ result = operationSpec.responses[parsedResponse.status];
+ }
+ else {
+ result = operationInfo?.operationResponseGetter(operationSpec, parsedResponse);
+ }
}
- /**
- * If you are only interested in the final outcome of this call,
- * you can await it to receive a `FinishedUnaryCall`.
- */
- then(onfulfilled, onrejected) {
- return this.promiseFinished().then(value => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, reason => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason));
+ return result;
+}
+function shouldDeserializeResponse(parsedResponse) {
+ const request = parsedResponse.request;
+ const operationInfo = getOperationRequestInfo(request);
+ const shouldDeserialize = operationInfo?.shouldDeserialize;
+ let result;
+ if (shouldDeserialize === undefined) {
+ result = true;
}
- promiseFinished() {
- return __awaiter(this, void 0, void 0, function* () {
- let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]);
- return {
- method: this.method,
- requestHeaders: this.requestHeaders,
- request: this.request,
- headers,
- response,
- status,
- trailers
- };
- });
+ else if (typeof shouldDeserialize === "boolean") {
+ result = shouldDeserialize;
}
-}
-exports.UnaryCall = UnaryCall;
-
-
-/***/ }),
-
-/***/ 8602:
-/***/ ((__unused_webpack_module, exports) => {
-
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.assertFloat32 = exports.assertUInt32 = exports.assertInt32 = exports.assertNever = exports.assert = void 0;
-/**
- * assert that condition is true or throw error (with message)
- */
-function assert(condition, msg) {
- if (!condition) {
- throw new Error(msg);
+ else {
+ result = shouldDeserialize(parsedResponse);
}
+ return result;
}
-exports.assert = assert;
-/**
- * assert that value cannot exist = type `never`. throw runtime error if it does.
- */
-function assertNever(value, msg) {
- throw new Error(msg !== null && msg !== void 0 ? msg : 'Unexpected object: ' + value);
+async function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, options, parseXML) {
+ const parsedResponse = await parse(jsonContentTypes, xmlContentTypes, response, options, parseXML);
+ if (!shouldDeserializeResponse(parsedResponse)) {
+ return parsedResponse;
+ }
+ const operationInfo = getOperationRequestInfo(parsedResponse.request);
+ const operationSpec = operationInfo?.operationSpec;
+ if (!operationSpec || !operationSpec.responses) {
+ return parsedResponse;
+ }
+ const responseSpec = getOperationResponseMap(parsedResponse);
+ const { error, shouldReturnResponse } = handleErrorResponse(parsedResponse, operationSpec, responseSpec, options);
+ if (error) {
+ throw error;
+ }
+ else if (shouldReturnResponse) {
+ return parsedResponse;
+ }
+ // An operation response spec does exist for current status code, so
+ // use it to deserialize the response.
+ if (responseSpec) {
+ if (responseSpec.bodyMapper) {
+ let valueToDeserialize = parsedResponse.parsedBody;
+ if (operationSpec.isXML && responseSpec.bodyMapper.type.name === MapperTypeNames.Sequence) {
+ valueToDeserialize =
+ typeof valueToDeserialize === "object"
+ ? valueToDeserialize[responseSpec.bodyMapper.xmlElementName]
+ : [];
+ }
+ try {
+ parsedResponse.parsedBody = operationSpec.serializer.deserialize(responseSpec.bodyMapper, valueToDeserialize, "operationRes.parsedBody", options);
+ }
+ catch (deserializeError) {
+ const restError = new esm_restError_RestError(`Error ${deserializeError} occurred in deserializing the responseBody - ${parsedResponse.bodyAsText}`, {
+ statusCode: parsedResponse.status,
+ request: parsedResponse.request,
+ response: parsedResponse,
+ });
+ throw restError;
+ }
+ }
+ else if (operationSpec.httpMethod === "HEAD") {
+ // head methods never have a body, but we return a boolean to indicate presence/absence of the resource
+ parsedResponse.parsedBody = response.status >= 200 && response.status < 300;
+ }
+ if (responseSpec.headersMapper) {
+ parsedResponse.parsedHeaders = operationSpec.serializer.deserialize(responseSpec.headersMapper, parsedResponse.headers.toJSON(), "operationRes.parsedHeaders", { xml: {}, ignoreUnknownProperties: true });
+ }
+ }
+ return parsedResponse;
}
-exports.assertNever = assertNever;
-const FLOAT32_MAX = 3.4028234663852886e+38, FLOAT32_MIN = -3.4028234663852886e+38, UINT32_MAX = 0xFFFFFFFF, INT32_MAX = 0X7FFFFFFF, INT32_MIN = -0X80000000;
-function assertInt32(arg) {
- if (typeof arg !== "number")
- throw new Error('invalid int 32: ' + typeof arg);
- if (!Number.isInteger(arg) || arg > INT32_MAX || arg < INT32_MIN)
- throw new Error('invalid int 32: ' + arg);
+function isOperationSpecEmpty(operationSpec) {
+ const expectedStatusCodes = Object.keys(operationSpec.responses);
+ return (expectedStatusCodes.length === 0 ||
+ (expectedStatusCodes.length === 1 && expectedStatusCodes[0] === "default"));
}
-exports.assertInt32 = assertInt32;
-function assertUInt32(arg) {
- if (typeof arg !== "number")
- throw new Error('invalid uint 32: ' + typeof arg);
- if (!Number.isInteger(arg) || arg > UINT32_MAX || arg < 0)
- throw new Error('invalid uint 32: ' + arg);
+function handleErrorResponse(parsedResponse, operationSpec, responseSpec, options) {
+ const isSuccessByStatus = 200 <= parsedResponse.status && parsedResponse.status < 300;
+ const isExpectedStatusCode = isOperationSpecEmpty(operationSpec)
+ ? isSuccessByStatus
+ : !!responseSpec;
+ if (isExpectedStatusCode) {
+ if (responseSpec) {
+ if (!responseSpec.isError) {
+ return { error: null, shouldReturnResponse: false };
+ }
+ }
+ else {
+ return { error: null, shouldReturnResponse: false };
+ }
+ }
+ const errorResponseSpec = responseSpec ?? operationSpec.responses.default;
+ const initialErrorMessage = parsedResponse.request.streamResponseStatusCodes?.has(parsedResponse.status)
+ ? `Unexpected status code: ${parsedResponse.status}`
+ : parsedResponse.bodyAsText;
+ const error = new esm_restError_RestError(initialErrorMessage, {
+ statusCode: parsedResponse.status,
+ request: parsedResponse.request,
+ response: parsedResponse,
+ });
+ // If the item failed but there's no error spec or default spec to deserialize the error,
+ // and the parsed body doesn't look like an error object,
+ // we should fail so we just throw the parsed response
+ if (!errorResponseSpec &&
+ !(parsedResponse.parsedBody?.error?.code && parsedResponse.parsedBody?.error?.message)) {
+ throw error;
+ }
+ const defaultBodyMapper = errorResponseSpec?.bodyMapper;
+ const defaultHeadersMapper = errorResponseSpec?.headersMapper;
+ try {
+ // If error response has a body, try to deserialize it using default body mapper.
+ // Then try to extract error code & message from it
+ if (parsedResponse.parsedBody) {
+ const parsedBody = parsedResponse.parsedBody;
+ let deserializedError;
+ if (defaultBodyMapper) {
+ let valueToDeserialize = parsedBody;
+ if (operationSpec.isXML && defaultBodyMapper.type.name === MapperTypeNames.Sequence) {
+ valueToDeserialize = [];
+ const elementName = defaultBodyMapper.xmlElementName;
+ if (typeof parsedBody === "object" && elementName) {
+ valueToDeserialize = parsedBody[elementName];
+ }
+ }
+ deserializedError = operationSpec.serializer.deserialize(defaultBodyMapper, valueToDeserialize, "error.response.parsedBody", options);
+ }
+ const internalError = parsedBody.error || deserializedError || parsedBody;
+ error.code = internalError.code;
+ if (internalError.message) {
+ error.message = internalError.message;
+ }
+ if (defaultBodyMapper) {
+ error.response.parsedBody = deserializedError;
+ }
+ }
+ // If error response has headers, try to deserialize it using default header mapper
+ if (parsedResponse.headers && defaultHeadersMapper) {
+ error.response.parsedHeaders =
+ operationSpec.serializer.deserialize(defaultHeadersMapper, parsedResponse.headers.toJSON(), "operationRes.parsedHeaders");
+ }
+ }
+ catch (defaultError) {
+ error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody - "${parsedResponse.bodyAsText}" for the default response.`;
+ }
+ return { error, shouldReturnResponse: false };
}
-exports.assertUInt32 = assertUInt32;
-function assertFloat32(arg) {
- if (typeof arg !== "number")
- throw new Error('invalid float 32: ' + typeof arg);
- if (!Number.isFinite(arg))
- return;
- if (arg > FLOAT32_MAX || arg < FLOAT32_MIN)
- throw new Error('invalid float 32: ' + arg);
+async function parse(jsonContentTypes, xmlContentTypes, operationResponse, opts, parseXML) {
+ if (!operationResponse.request.streamResponseStatusCodes?.has(operationResponse.status) &&
+ operationResponse.bodyAsText) {
+ const text = operationResponse.bodyAsText;
+ const contentType = operationResponse.headers.get("Content-Type") || "";
+ const contentComponents = !contentType
+ ? []
+ : contentType.split(";").map((component) => component.toLowerCase());
+ try {
+ if (contentComponents.length === 0 ||
+ contentComponents.some((component) => jsonContentTypes.indexOf(component) !== -1)) {
+ operationResponse.parsedBody = JSON.parse(text);
+ return operationResponse;
+ }
+ else if (contentComponents.some((component) => xmlContentTypes.indexOf(component) !== -1)) {
+ if (!parseXML) {
+ throw new Error("Parsing XML not supported.");
+ }
+ const body = await parseXML(text, opts.xml);
+ operationResponse.parsedBody = body;
+ return operationResponse;
+ }
+ }
+ catch (err) {
+ const msg = `Error "${err}" occurred while parsing the response body - ${operationResponse.bodyAsText}.`;
+ const errCode = err.code || esm_restError_RestError.PARSE_ERROR;
+ const e = new esm_restError_RestError(msg, {
+ code: errCode,
+ statusCode: operationResponse.status,
+ request: operationResponse.request,
+ response: operationResponse,
+ });
+ throw e;
+ }
+ }
+ return operationResponse;
}
-exports.assertFloat32 = assertFloat32;
-
-
-/***/ }),
-
-/***/ 6335:
-/***/ ((__unused_webpack_module, exports) => {
-
+//# sourceMappingURL=deserializationPolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-client/dist/esm/interfaceHelpers.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.base64encode = exports.base64decode = void 0;
-// lookup table from base64 character to byte
-let encTable = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
-// lookup table from base64 character *code* to byte because lookup by number is fast
-let decTable = [];
-for (let i = 0; i < encTable.length; i++)
- decTable[encTable[i].charCodeAt(0)] = i;
-// support base64url variants
-decTable["-".charCodeAt(0)] = encTable.indexOf("+");
-decTable["_".charCodeAt(0)] = encTable.indexOf("/");
/**
- * Decodes a base64 string to a byte array.
- *
- * - ignores white-space, including line breaks and tabs
- * - allows inner padding (can decode concatenated base64 strings)
- * - does not require padding
- * - understands base64url encoding:
- * "-" instead of "+",
- * "_" instead of "/",
- * no padding
+ * Gets the list of status codes for streaming responses.
+ * @internal
*/
-function base64decode(base64Str) {
- // estimate byte size, not accounting for inner padding and whitespace
- let es = base64Str.length * 3 / 4;
- // if (es % 3 !== 0)
- // throw new Error('invalid base64 string');
- if (base64Str[base64Str.length - 2] == '=')
- es -= 2;
- else if (base64Str[base64Str.length - 1] == '=')
- es -= 1;
- let bytes = new Uint8Array(es), bytePos = 0, // position in byte array
- groupPos = 0, // position in base64 group
- b, // current byte
- p = 0 // previous byte
- ;
- for (let i = 0; i < base64Str.length; i++) {
- b = decTable[base64Str.charCodeAt(i)];
- if (b === undefined) {
- // noinspection FallThroughInSwitchStatementJS
- switch (base64Str[i]) {
- case '=':
- groupPos = 0; // reset state when padding found
- case '\n':
- case '\r':
- case '\t':
- case ' ':
- continue; // skip white-space, and padding
- default:
- throw Error(`invalid base64 string.`);
- }
- }
- switch (groupPos) {
- case 0:
- p = b;
- groupPos = 1;
- break;
- case 1:
- bytes[bytePos++] = p << 2 | (b & 48) >> 4;
- p = b;
- groupPos = 2;
- break;
- case 2:
- bytes[bytePos++] = (p & 15) << 4 | (b & 60) >> 2;
- p = b;
- groupPos = 3;
- break;
- case 3:
- bytes[bytePos++] = (p & 3) << 6 | b;
- groupPos = 0;
- break;
+function getStreamingResponseStatusCodes(operationSpec) {
+ const result = new Set();
+ for (const statusCode in operationSpec.responses) {
+ const operationResponse = operationSpec.responses[statusCode];
+ if (operationResponse.bodyMapper &&
+ operationResponse.bodyMapper.type.name === MapperTypeNames.Stream) {
+ result.add(Number(statusCode));
}
}
- if (groupPos == 1)
- throw Error(`invalid base64 string.`);
- return bytes.subarray(0, bytePos);
+ return result;
}
-exports.base64decode = base64decode;
/**
- * Encodes a byte array to a base64 string.
- * Adds padding at the end.
- * Does not insert newlines.
+ * Get the path to this parameter's value as a dotted string (a.b.c).
+ * @param parameter - The parameter to get the path string for.
+ * @returns The path to this parameter's value as a dotted string.
+ * @internal
*/
-function base64encode(bytes) {
- let base64 = '', groupPos = 0, // position in base64 group
- b, // current byte
- p = 0; // carry over from previous byte
- for (let i = 0; i < bytes.length; i++) {
- b = bytes[i];
- switch (groupPos) {
- case 0:
- base64 += encTable[b >> 2];
- p = (b & 3) << 4;
- groupPos = 1;
- break;
- case 1:
- base64 += encTable[p | b >> 4];
- p = (b & 15) << 2;
- groupPos = 2;
- break;
- case 2:
- base64 += encTable[p | b >> 6];
- base64 += encTable[b & 63];
- groupPos = 0;
- break;
- }
+function getPathStringFromParameter(parameter) {
+ const { parameterPath, mapper } = parameter;
+ let result;
+ if (typeof parameterPath === "string") {
+ result = parameterPath;
}
- // padding required?
- if (groupPos) {
- base64 += encTable[p];
- base64 += '=';
- if (groupPos == 1)
- base64 += '=';
+ else if (Array.isArray(parameterPath)) {
+ result = parameterPath.join(".");
}
- return base64;
+ else {
+ result = mapper.serializedName;
+ }
+ return result;
}
-exports.base64encode = base64encode;
-
+//# sourceMappingURL=interfaceHelpers.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-client/dist/esm/serializationPolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
-/***/ }),
-/***/ 4816:
-/***/ ((__unused_webpack_module, exports) => {
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.WireType = exports.mergeBinaryOptions = exports.UnknownFieldHandler = void 0;
/**
- * This handler implements the default behaviour for unknown fields.
- * When reading data, unknown fields are stored on the message, in a
- * symbol property.
- * When writing data, the symbol property is queried and unknown fields
- * are serialized into the output again.
+ * The programmatic identifier of the serializationPolicy.
*/
-var UnknownFieldHandler;
-(function (UnknownFieldHandler) {
- /**
- * The symbol used to store unknown fields for a message.
- * The property must conform to `UnknownFieldContainer`.
- */
- UnknownFieldHandler.symbol = Symbol.for("protobuf-ts/unknown");
- /**
- * Store an unknown field during binary read directly on the message.
- * This method is compatible with `BinaryReadOptions.readUnknownField`.
- */
- UnknownFieldHandler.onRead = (typeName, message, fieldNo, wireType, data) => {
- let container = is(message) ? message[UnknownFieldHandler.symbol] : message[UnknownFieldHandler.symbol] = [];
- container.push({ no: fieldNo, wireType, data });
- };
- /**
- * Write unknown fields stored for the message to the writer.
- * This method is compatible with `BinaryWriteOptions.writeUnknownFields`.
- */
- UnknownFieldHandler.onWrite = (typeName, message, writer) => {
- for (let { no, wireType, data } of UnknownFieldHandler.list(message))
- writer.tag(no, wireType).raw(data);
- };
- /**
- * List unknown fields stored for the message.
- * Note that there may be multiples fields with the same number.
- */
- UnknownFieldHandler.list = (message, fieldNo) => {
- if (is(message)) {
- let all = message[UnknownFieldHandler.symbol];
- return fieldNo ? all.filter(uf => uf.no == fieldNo) : all;
- }
- return [];
- };
- /**
- * Returns the last unknown field by field number.
- */
- UnknownFieldHandler.last = (message, fieldNo) => UnknownFieldHandler.list(message, fieldNo).slice(-1)[0];
- const is = (message) => message && Array.isArray(message[UnknownFieldHandler.symbol]);
-})(UnknownFieldHandler = exports.UnknownFieldHandler || (exports.UnknownFieldHandler = {}));
+const serializationPolicyName = "serializationPolicy";
/**
- * Merges binary write or read options. Later values override earlier values.
+ * This policy handles assembling the request body and headers using
+ * an OperationSpec and OperationArguments on the request.
*/
-function mergeBinaryOptions(a, b) {
- return Object.assign(Object.assign({}, a), b);
+function serializationPolicy(options = {}) {
+ const stringifyXML = options.stringifyXML;
+ return {
+ name: serializationPolicyName,
+ async sendRequest(request, next) {
+ const operationInfo = getOperationRequestInfo(request);
+ const operationSpec = operationInfo?.operationSpec;
+ const operationArguments = operationInfo?.operationArguments;
+ if (operationSpec && operationArguments) {
+ serializeHeaders(request, operationArguments, operationSpec);
+ serializeRequestBody(request, operationArguments, operationSpec, stringifyXML);
+ }
+ return next(request);
+ },
+ };
}
-exports.mergeBinaryOptions = mergeBinaryOptions;
/**
- * Protobuf binary format wire types.
- *
- * A wire type provides just enough information to find the length of the
- * following value.
- *
- * See https://developers.google.com/protocol-buffers/docs/encoding#structure
+ * @internal
*/
-var WireType;
-(function (WireType) {
- /**
- * Used for int32, int64, uint32, uint64, sint32, sint64, bool, enum
- */
- WireType[WireType["Varint"] = 0] = "Varint";
- /**
- * Used for fixed64, sfixed64, double.
- * Always 8 bytes with little-endian byte order.
- */
- WireType[WireType["Bit64"] = 1] = "Bit64";
- /**
- * Used for string, bytes, embedded messages, packed repeated fields
- *
- * Only repeated numeric types (types which use the varint, 32-bit,
- * or 64-bit wire types) can be packed. In proto3, such fields are
- * packed by default.
- */
- WireType[WireType["LengthDelimited"] = 2] = "LengthDelimited";
- /**
- * Used for groups
- * @deprecated
- */
- WireType[WireType["StartGroup"] = 3] = "StartGroup";
- /**
- * Used for groups
- * @deprecated
- */
- WireType[WireType["EndGroup"] = 4] = "EndGroup";
- /**
- * Used for fixed32, sfixed32, float.
- * Always 4 bytes with little-endian byte order.
- */
- WireType[WireType["Bit32"] = 5] = "Bit32";
-})(WireType = exports.WireType || (exports.WireType = {}));
-
-
-/***/ }),
-
-/***/ 2889:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.BinaryReader = exports.binaryReadOptions = void 0;
-const binary_format_contract_1 = __nccwpck_require__(4816);
-const pb_long_1 = __nccwpck_require__(1753);
-const goog_varint_1 = __nccwpck_require__(3223);
-const defaultsRead = {
- readUnknownField: true,
- readerFactory: bytes => new BinaryReader(bytes),
-};
-/**
- * Make options for reading binary data form partial options.
- */
-function binaryReadOptions(options) {
- return options ? Object.assign(Object.assign({}, defaultsRead), options) : defaultsRead;
-}
-exports.binaryReadOptions = binaryReadOptions;
-class BinaryReader {
- constructor(buf, textDecoder) {
- this.varint64 = goog_varint_1.varint64read; // dirty cast for `this`
- /**
- * Read a `uint32` field, an unsigned 32 bit varint.
- */
- this.uint32 = goog_varint_1.varint32read; // dirty cast for `this` and access to protected `buf`
- this.buf = buf;
- this.len = buf.length;
- this.pos = 0;
- this.view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
- this.textDecoder = textDecoder !== null && textDecoder !== void 0 ? textDecoder : new TextDecoder("utf-8", {
- fatal: true,
- ignoreBOM: true,
- });
- }
- /**
- * Reads a tag - field number and wire type.
- */
- tag() {
- let tag = this.uint32(), fieldNo = tag >>> 3, wireType = tag & 7;
- if (fieldNo <= 0 || wireType < 0 || wireType > 5)
- throw new Error("illegal tag: field no " + fieldNo + " wire type " + wireType);
- return [fieldNo, wireType];
- }
- /**
- * Skip one element on the wire and return the skipped data.
- * Supports WireType.StartGroup since v2.0.0-alpha.23.
- */
- skip(wireType) {
- let start = this.pos;
- // noinspection FallThroughInSwitchStatementJS
- switch (wireType) {
- case binary_format_contract_1.WireType.Varint:
- while (this.buf[this.pos++] & 0x80) {
- // ignore
+function serializeHeaders(request, operationArguments, operationSpec) {
+ if (operationSpec.headerParameters) {
+ for (const headerParameter of operationSpec.headerParameters) {
+ let headerValue = getOperationArgumentValueFromParameter(operationArguments, headerParameter);
+ if ((headerValue !== null && headerValue !== undefined) || headerParameter.mapper.required) {
+ headerValue = operationSpec.serializer.serialize(headerParameter.mapper, headerValue, getPathStringFromParameter(headerParameter));
+ const headerCollectionPrefix = headerParameter.mapper
+ .headerCollectionPrefix;
+ if (headerCollectionPrefix) {
+ for (const key of Object.keys(headerValue)) {
+ request.headers.set(headerCollectionPrefix + key, headerValue[key]);
+ }
}
- break;
- case binary_format_contract_1.WireType.Bit64:
- this.pos += 4;
- case binary_format_contract_1.WireType.Bit32:
- this.pos += 4;
- break;
- case binary_format_contract_1.WireType.LengthDelimited:
- let len = this.uint32();
- this.pos += len;
- break;
- case binary_format_contract_1.WireType.StartGroup:
- // From descriptor.proto: Group type is deprecated, not supported in proto3.
- // But we must still be able to parse and treat as unknown.
- let t;
- while ((t = this.tag()[1]) !== binary_format_contract_1.WireType.EndGroup) {
- this.skip(t);
+ else {
+ request.headers.set(headerParameter.mapper.serializedName || getPathStringFromParameter(headerParameter), headerValue);
}
- break;
- default:
- throw new Error("cant skip wire type " + wireType);
+ }
}
- this.assertBounds();
- return this.buf.subarray(start, this.pos);
- }
- /**
- * Throws error if position in byte array is out of range.
- */
- assertBounds() {
- if (this.pos > this.len)
- throw new RangeError("premature EOF");
}
- /**
- * Read a `int32` field, a signed 32 bit varint.
- */
- int32() {
- return this.uint32() | 0;
- }
- /**
- * Read a `sint32` field, a signed, zigzag-encoded 32-bit varint.
- */
- sint32() {
- let zze = this.uint32();
- // decode zigzag
- return (zze >>> 1) ^ -(zze & 1);
- }
- /**
- * Read a `int64` field, a signed 64-bit varint.
- */
- int64() {
- return new pb_long_1.PbLong(...this.varint64());
- }
- /**
- * Read a `uint64` field, an unsigned 64-bit varint.
- */
- uint64() {
- return new pb_long_1.PbULong(...this.varint64());
- }
- /**
- * Read a `sint64` field, a signed, zig-zag-encoded 64-bit varint.
- */
- sint64() {
- let [lo, hi] = this.varint64();
- // decode zig zag
- let s = -(lo & 1);
- lo = ((lo >>> 1 | (hi & 1) << 31) ^ s);
- hi = (hi >>> 1 ^ s);
- return new pb_long_1.PbLong(lo, hi);
- }
- /**
- * Read a `bool` field, a variant.
- */
- bool() {
- let [lo, hi] = this.varint64();
- return lo !== 0 || hi !== 0;
- }
- /**
- * Read a `fixed32` field, an unsigned, fixed-length 32-bit integer.
- */
- fixed32() {
- return this.view.getUint32((this.pos += 4) - 4, true);
- }
- /**
- * Read a `sfixed32` field, a signed, fixed-length 32-bit integer.
- */
- sfixed32() {
- return this.view.getInt32((this.pos += 4) - 4, true);
- }
- /**
- * Read a `fixed64` field, an unsigned, fixed-length 64 bit integer.
- */
- fixed64() {
- return new pb_long_1.PbULong(this.sfixed32(), this.sfixed32());
+ const customHeaders = operationArguments.options?.requestOptions?.customHeaders;
+ if (customHeaders) {
+ for (const customHeaderName of Object.keys(customHeaders)) {
+ request.headers.set(customHeaderName, customHeaders[customHeaderName]);
+ }
}
- /**
- * Read a `fixed64` field, a signed, fixed-length 64-bit integer.
- */
- sfixed64() {
- return new pb_long_1.PbLong(this.sfixed32(), this.sfixed32());
+}
+/**
+ * @internal
+ */
+function serializeRequestBody(request, operationArguments, operationSpec, stringifyXML = function () {
+ throw new Error("XML serialization unsupported!");
+}) {
+ const serializerOptions = operationArguments.options?.serializerOptions;
+ const updatedOptions = {
+ xml: {
+ rootName: serializerOptions?.xml.rootName ?? "",
+ includeRoot: serializerOptions?.xml.includeRoot ?? false,
+ xmlCharKey: serializerOptions?.xml.xmlCharKey ?? XML_CHARKEY,
+ },
+ };
+ const xmlCharKey = updatedOptions.xml.xmlCharKey;
+ if (operationSpec.requestBody && operationSpec.requestBody.mapper) {
+ request.body = getOperationArgumentValueFromParameter(operationArguments, operationSpec.requestBody);
+ const bodyMapper = operationSpec.requestBody.mapper;
+ const { required, serializedName, xmlName, xmlElementName, xmlNamespace, xmlNamespacePrefix, nullable, } = bodyMapper;
+ const typeName = bodyMapper.type.name;
+ try {
+ if ((request.body !== undefined && request.body !== null) ||
+ (nullable && request.body === null) ||
+ required) {
+ const requestBodyParameterPathString = getPathStringFromParameter(operationSpec.requestBody);
+ request.body = operationSpec.serializer.serialize(bodyMapper, request.body, requestBodyParameterPathString, updatedOptions);
+ const isStream = typeName === MapperTypeNames.Stream;
+ if (operationSpec.isXML) {
+ const xmlnsKey = xmlNamespacePrefix ? `xmlns:${xmlNamespacePrefix}` : "xmlns";
+ const value = getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, request.body, updatedOptions);
+ if (typeName === MapperTypeNames.Sequence) {
+ request.body = stringifyXML(prepareXMLRootList(value, xmlElementName || xmlName || serializedName, xmlnsKey, xmlNamespace), { rootName: xmlName || serializedName, xmlCharKey });
+ }
+ else if (!isStream) {
+ request.body = stringifyXML(value, {
+ rootName: xmlName || serializedName,
+ xmlCharKey,
+ });
+ }
+ }
+ else if (typeName === MapperTypeNames.String &&
+ (operationSpec.contentType?.match("text/plain") || operationSpec.mediaType === "text")) {
+ // the String serializer has validated that request body is a string
+ // so just send the string.
+ return;
+ }
+ else if (!isStream) {
+ request.body = JSON.stringify(request.body);
+ }
+ }
+ }
+ catch (error) {
+ throw new Error(`Error "${error.message}" occurred in serializing the payload - ${JSON.stringify(serializedName, undefined, " ")}.`);
+ }
}
- /**
- * Read a `float` field, 32-bit floating point number.
- */
- float() {
- return this.view.getFloat32((this.pos += 4) - 4, true);
+ else if (operationSpec.formDataParameters && operationSpec.formDataParameters.length > 0) {
+ request.formData = {};
+ for (const formDataParameter of operationSpec.formDataParameters) {
+ const formDataParameterValue = getOperationArgumentValueFromParameter(operationArguments, formDataParameter);
+ if (formDataParameterValue !== undefined && formDataParameterValue !== null) {
+ const formDataParameterPropertyName = formDataParameter.mapper.serializedName || getPathStringFromParameter(formDataParameter);
+ request.formData[formDataParameterPropertyName] = operationSpec.serializer.serialize(formDataParameter.mapper, formDataParameterValue, getPathStringFromParameter(formDataParameter), updatedOptions);
+ }
+ }
}
- /**
- * Read a `double` field, a 64-bit floating point number.
- */
- double() {
- return this.view.getFloat64((this.pos += 8) - 8, true);
+}
+/**
+ * Adds an xml namespace to the xml serialized object if needed, otherwise it just returns the value itself
+ */
+function getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, serializedValue, options) {
+ // Composite and Sequence schemas already got their root namespace set during serialization
+ // We just need to add xmlns to the other schema types
+ if (xmlNamespace && !["Composite", "Sequence", "Dictionary"].includes(typeName)) {
+ const result = {};
+ result[options.xml.xmlCharKey] = serializedValue;
+ result[XML_ATTRKEY] = { [xmlnsKey]: xmlNamespace };
+ return result;
}
- /**
- * Read a `bytes` field, length-delimited arbitrary data.
- */
- bytes() {
- let len = this.uint32();
- let start = this.pos;
- this.pos += len;
- this.assertBounds();
- return this.buf.subarray(start, start + len);
+ return serializedValue;
+}
+function prepareXMLRootList(obj, elementName, xmlNamespaceKey, xmlNamespace) {
+ if (!Array.isArray(obj)) {
+ obj = [obj];
}
- /**
- * Read a `string` field, length-delimited data converted to UTF-8 text.
- */
- string() {
- return this.textDecoder.decode(this.bytes());
+ if (!xmlNamespaceKey || !xmlNamespace) {
+ return { [elementName]: obj };
}
+ const result = { [elementName]: obj };
+ result[XML_ATTRKEY] = { [xmlNamespaceKey]: xmlNamespace };
+ return result;
}
-exports.BinaryReader = BinaryReader;
-
-
-/***/ }),
+//# sourceMappingURL=serializationPolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-client/dist/esm/pipeline.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
-/***/ 3957:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.BinaryWriter = exports.binaryWriteOptions = void 0;
-const pb_long_1 = __nccwpck_require__(1753);
-const goog_varint_1 = __nccwpck_require__(3223);
-const assert_1 = __nccwpck_require__(8602);
-const defaultsWrite = {
- writeUnknownFields: true,
- writerFactory: () => new BinaryWriter(),
-};
/**
- * Make options for writing binary data form partial options.
+ * Creates a new Pipeline for use with a Service Client.
+ * Adds in deserializationPolicy by default.
+ * Also adds in bearerTokenAuthenticationPolicy if passed a TokenCredential.
+ * @param options - Options to customize the created pipeline.
*/
-function binaryWriteOptions(options) {
- return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite;
+function createClientPipeline(options = {}) {
+ const pipeline = esm_createPipelineFromOptions_createPipelineFromOptions(options ?? {});
+ if (options.credentialOptions) {
+ pipeline.addPolicy(bearerTokenAuthenticationPolicy({
+ credential: options.credentialOptions.credential,
+ scopes: options.credentialOptions.credentialScopes,
+ }));
+ }
+ pipeline.addPolicy(serializationPolicy(options.serializationOptions), { phase: "Serialize" });
+ pipeline.addPolicy(deserializationPolicy(options.deserializationOptions), {
+ phase: "Deserialize",
+ });
+ return pipeline;
}
-exports.binaryWriteOptions = binaryWriteOptions;
-class BinaryWriter {
- constructor(textEncoder) {
- /**
- * Previous fork states.
- */
- this.stack = [];
- this.textEncoder = textEncoder !== null && textEncoder !== void 0 ? textEncoder : new TextEncoder();
- this.chunks = [];
- this.buf = [];
+//# sourceMappingURL=pipeline.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-client/dist/esm/httpClientCache.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+
+let httpClientCache_cachedHttpClient;
+function getCachedDefaultHttpClient() {
+ if (!httpClientCache_cachedHttpClient) {
+ httpClientCache_cachedHttpClient = esm_defaultHttpClient_createDefaultHttpClient();
}
- /**
- * Return all bytes written and reset this writer.
- */
- finish() {
- this.chunks.push(new Uint8Array(this.buf)); // flush the buffer
- let len = 0;
- for (let i = 0; i < this.chunks.length; i++)
- len += this.chunks[i].length;
- let bytes = new Uint8Array(len);
- let offset = 0;
- for (let i = 0; i < this.chunks.length; i++) {
- bytes.set(this.chunks[i], offset);
- offset += this.chunks[i].length;
+ return httpClientCache_cachedHttpClient;
+}
+//# sourceMappingURL=httpClientCache.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-client/dist/esm/urlHelpers.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+
+
+const CollectionFormatToDelimiterMap = {
+ CSV: ",",
+ SSV: " ",
+ Multi: "Multi",
+ TSV: "\t",
+ Pipes: "|",
+};
+function getRequestUrl(baseUri, operationSpec, operationArguments, fallbackObject) {
+ const urlReplacements = calculateUrlReplacements(operationSpec, operationArguments, fallbackObject);
+ let isAbsolutePath = false;
+ let requestUrl = replaceAll(baseUri, urlReplacements);
+ if (operationSpec.path) {
+ let path = replaceAll(operationSpec.path, urlReplacements);
+ // QUIRK: sometimes we get a path component like /{nextLink}
+ // which may be a fully formed URL with a leading /. In that case, we should
+ // remove the leading /
+ if (operationSpec.path === "/{nextLink}" && path.startsWith("/")) {
+ path = path.substring(1);
+ }
+ // QUIRK: sometimes we get a path component like {nextLink}
+ // which may be a fully formed URL. In that case, we should
+ // ignore the baseUri.
+ if (isAbsoluteUrl(path)) {
+ requestUrl = path;
+ isAbsolutePath = true;
+ }
+ else {
+ requestUrl = appendPath(requestUrl, path);
}
- this.chunks = [];
- return bytes;
}
+ const { queryParams, sequenceParams } = calculateQueryParameters(operationSpec, operationArguments, fallbackObject);
/**
- * Start a new fork for length-delimited data like a message
- * or a packed repeated field.
- *
- * Must be joined later with `join()`.
+ * Notice that this call sets the `noOverwrite` parameter to true if the `requestUrl`
+ * is an absolute path. This ensures that existing query parameter values in `requestUrl`
+ * do not get overwritten. On the other hand when `requestUrl` is not absolute path, it
+ * is still being built so there is nothing to overwrite.
*/
- fork() {
- this.stack.push({ chunks: this.chunks, buf: this.buf });
- this.chunks = [];
- this.buf = [];
- return this;
+ requestUrl = appendQueryParams(requestUrl, queryParams, sequenceParams, isAbsolutePath);
+ return requestUrl;
+}
+function replaceAll(input, replacements) {
+ let result = input;
+ for (const [searchValue, replaceValue] of replacements) {
+ result = result.split(searchValue).join(replaceValue);
}
- /**
- * Join the last fork. Write its length and bytes, then
- * return to the previous state.
- */
- join() {
- // get chunk of fork
- let chunk = this.finish();
- // restore previous state
- let prev = this.stack.pop();
- if (!prev)
- throw new Error('invalid state, fork stack empty');
- this.chunks = prev.chunks;
- this.buf = prev.buf;
- // write length of chunk as varint
- this.uint32(chunk.byteLength);
- return this.raw(chunk);
+ return result;
+}
+function calculateUrlReplacements(operationSpec, operationArguments, fallbackObject) {
+ const result = new Map();
+ if (operationSpec.urlParameters?.length) {
+ for (const urlParameter of operationSpec.urlParameters) {
+ let urlParameterValue = getOperationArgumentValueFromParameter(operationArguments, urlParameter, fallbackObject);
+ const parameterPathString = getPathStringFromParameter(urlParameter);
+ urlParameterValue = operationSpec.serializer.serialize(urlParameter.mapper, urlParameterValue, parameterPathString);
+ if (!urlParameter.skipEncoding) {
+ urlParameterValue = encodeURIComponent(urlParameterValue);
+ }
+ result.set(`{${urlParameter.mapper.serializedName || parameterPathString}}`, urlParameterValue);
+ }
}
- /**
- * Writes a tag (field number and wire type).
- *
- * Equivalent to `uint32( (fieldNo << 3 | type) >>> 0 )`.
- *
- * Generated code should compute the tag ahead of time and call `uint32()`.
- */
- tag(fieldNo, type) {
- return this.uint32((fieldNo << 3 | type) >>> 0);
+ return result;
+}
+function isAbsoluteUrl(url) {
+ return url.includes("://");
+}
+function appendPath(url, pathToAppend) {
+ if (!pathToAppend) {
+ return url;
}
- /**
- * Write a chunk of raw bytes.
- */
- raw(chunk) {
- if (this.buf.length) {
- this.chunks.push(new Uint8Array(this.buf));
- this.buf = [];
+ const parsedUrl = new URL(url);
+ let newPath = parsedUrl.pathname;
+ if (!newPath.endsWith("/")) {
+ newPath = `${newPath}/`;
+ }
+ if (pathToAppend.startsWith("/")) {
+ pathToAppend = pathToAppend.substring(1);
+ }
+ const searchStart = pathToAppend.indexOf("?");
+ if (searchStart !== -1) {
+ const path = pathToAppend.substring(0, searchStart);
+ const search = pathToAppend.substring(searchStart + 1);
+ newPath = newPath + path;
+ if (search) {
+ parsedUrl.search = parsedUrl.search ? `${parsedUrl.search}&${search}` : search;
}
- this.chunks.push(chunk);
- return this;
}
- /**
- * Write a `uint32` value, an unsigned 32 bit varint.
- */
- uint32(value) {
- assert_1.assertUInt32(value);
- // write value as varint 32, inlined for speed
- while (value > 0x7f) {
- this.buf.push((value & 0x7f) | 0x80);
- value = value >>> 7;
+ else {
+ newPath = newPath + pathToAppend;
+ }
+ parsedUrl.pathname = newPath;
+ return parsedUrl.toString();
+}
+function calculateQueryParameters(operationSpec, operationArguments, fallbackObject) {
+ const result = new Map();
+ const sequenceParams = new Set();
+ if (operationSpec.queryParameters?.length) {
+ for (const queryParameter of operationSpec.queryParameters) {
+ if (queryParameter.mapper.type.name === "Sequence" && queryParameter.mapper.serializedName) {
+ sequenceParams.add(queryParameter.mapper.serializedName);
+ }
+ let queryParameterValue = getOperationArgumentValueFromParameter(operationArguments, queryParameter, fallbackObject);
+ if ((queryParameterValue !== undefined && queryParameterValue !== null) ||
+ queryParameter.mapper.required) {
+ queryParameterValue = operationSpec.serializer.serialize(queryParameter.mapper, queryParameterValue, getPathStringFromParameter(queryParameter));
+ const delimiter = queryParameter.collectionFormat
+ ? CollectionFormatToDelimiterMap[queryParameter.collectionFormat]
+ : "";
+ if (Array.isArray(queryParameterValue)) {
+ // replace null and undefined
+ queryParameterValue = queryParameterValue.map((item) => {
+ if (item === null || item === undefined) {
+ return "";
+ }
+ return item;
+ });
+ }
+ if (queryParameter.collectionFormat === "Multi" && queryParameterValue.length === 0) {
+ continue;
+ }
+ else if (Array.isArray(queryParameterValue) &&
+ (queryParameter.collectionFormat === "SSV" || queryParameter.collectionFormat === "TSV")) {
+ queryParameterValue = queryParameterValue.join(delimiter);
+ }
+ if (!queryParameter.skipEncoding) {
+ if (Array.isArray(queryParameterValue)) {
+ queryParameterValue = queryParameterValue.map((item) => {
+ return encodeURIComponent(item);
+ });
+ }
+ else {
+ queryParameterValue = encodeURIComponent(queryParameterValue);
+ }
+ }
+ // Join pipes and CSV *after* encoding, or the server will be upset.
+ if (Array.isArray(queryParameterValue) &&
+ (queryParameter.collectionFormat === "CSV" || queryParameter.collectionFormat === "Pipes")) {
+ queryParameterValue = queryParameterValue.join(delimiter);
+ }
+ result.set(queryParameter.mapper.serializedName || getPathStringFromParameter(queryParameter), queryParameterValue);
+ }
}
- this.buf.push(value);
- return this;
}
- /**
- * Write a `int32` value, a signed 32 bit varint.
- */
- int32(value) {
- assert_1.assertInt32(value);
- goog_varint_1.varint32write(value, this.buf);
- return this;
+ return {
+ queryParams: result,
+ sequenceParams,
+ };
+}
+function simpleParseQueryParams(queryString) {
+ const result = new Map();
+ if (!queryString || queryString[0] !== "?") {
+ return result;
}
- /**
- * Write a `bool` value, a variant.
- */
- bool(value) {
- this.buf.push(value ? 1 : 0);
- return this;
+ // remove the leading ?
+ queryString = queryString.slice(1);
+ const pairs = queryString.split("&");
+ for (const pair of pairs) {
+ const [name, value] = pair.split("=", 2);
+ const existingValue = result.get(name);
+ if (existingValue) {
+ if (Array.isArray(existingValue)) {
+ existingValue.push(value);
+ }
+ else {
+ result.set(name, [existingValue, value]);
+ }
+ }
+ else {
+ result.set(name, value);
+ }
}
- /**
- * Write a `bytes` value, length-delimited arbitrary data.
- */
- bytes(value) {
- this.uint32(value.byteLength); // write length of chunk as varint
- return this.raw(value);
+ return result;
+}
+/** @internal */
+function appendQueryParams(url, queryParams, sequenceParams, noOverwrite = false) {
+ if (queryParams.size === 0) {
+ return url;
}
- /**
- * Write a `string` value, length-delimited data converted to UTF-8 text.
- */
- string(value) {
- let chunk = this.textEncoder.encode(value);
- this.uint32(chunk.byteLength); // write length of chunk as varint
- return this.raw(chunk);
+ const parsedUrl = new URL(url);
+ // QUIRK: parsedUrl.searchParams will have their name/value pairs decoded, which
+ // can change their meaning to the server, such as in the case of a SAS signature.
+ // To avoid accidentally un-encoding a query param, we parse the key/values ourselves
+ const combinedParams = simpleParseQueryParams(parsedUrl.search);
+ for (const [name, value] of queryParams) {
+ const existingValue = combinedParams.get(name);
+ if (Array.isArray(existingValue)) {
+ if (Array.isArray(value)) {
+ existingValue.push(...value);
+ const valueSet = new Set(existingValue);
+ combinedParams.set(name, Array.from(valueSet));
+ }
+ else {
+ existingValue.push(value);
+ }
+ }
+ else if (existingValue) {
+ if (Array.isArray(value)) {
+ value.unshift(existingValue);
+ }
+ else if (sequenceParams.has(name)) {
+ combinedParams.set(name, [existingValue, value]);
+ }
+ if (!noOverwrite) {
+ combinedParams.set(name, value);
+ }
+ }
+ else {
+ combinedParams.set(name, value);
+ }
}
- /**
- * Write a `float` value, 32-bit floating point number.
- */
- float(value) {
- assert_1.assertFloat32(value);
- let chunk = new Uint8Array(4);
- new DataView(chunk.buffer).setFloat32(0, value, true);
- return this.raw(chunk);
+ const searchPieces = [];
+ for (const [name, value] of combinedParams) {
+ if (typeof value === "string") {
+ searchPieces.push(`${name}=${value}`);
+ }
+ else if (Array.isArray(value)) {
+ // QUIRK: If we get an array of values, include multiple key/value pairs
+ for (const subValue of value) {
+ searchPieces.push(`${name}=${subValue}`);
+ }
+ }
+ else {
+ searchPieces.push(`${name}=${value}`);
+ }
}
+ // QUIRK: we have to set search manually as searchParams will encode comma when it shouldn't.
+ parsedUrl.search = searchPieces.length ? `?${searchPieces.join("&")}` : "";
+ return parsedUrl.toString();
+}
+//# sourceMappingURL=urlHelpers.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-client/dist/esm/log.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+
+const dist_esm_log_logger = esm_createClientLogger("core-client");
+//# sourceMappingURL=log.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-client/dist/esm/serviceClient.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+
+
+
+
+
+
+
+
+/**
+ * Initializes a new instance of the ServiceClient.
+ */
+class ServiceClient {
/**
- * Write a `double` value, a 64-bit floating point number.
+ * If specified, this is the base URI that requests will be made against for this ServiceClient.
+ * If it is not specified, then all OperationSpecs must contain a baseUrl property.
*/
- double(value) {
- let chunk = new Uint8Array(8);
- new DataView(chunk.buffer).setFloat64(0, value, true);
- return this.raw(chunk);
- }
+ _endpoint;
/**
- * Write a `fixed32` value, an unsigned, fixed-length 32-bit integer.
+ * The default request content type for the service.
+ * Used if no requestContentType is present on an OperationSpec.
*/
- fixed32(value) {
- assert_1.assertUInt32(value);
- let chunk = new Uint8Array(4);
- new DataView(chunk.buffer).setUint32(0, value, true);
- return this.raw(chunk);
- }
+ _requestContentType;
/**
- * Write a `sfixed32` value, a signed, fixed-length 32-bit integer.
+ * Set to true if the request is sent over HTTP instead of HTTPS
*/
- sfixed32(value) {
- assert_1.assertInt32(value);
- let chunk = new Uint8Array(4);
- new DataView(chunk.buffer).setInt32(0, value, true);
- return this.raw(chunk);
- }
+ _allowInsecureConnection;
/**
- * Write a `sint32` value, a signed, zigzag-encoded 32-bit varint.
+ * The HTTP client that will be used to send requests.
*/
- sint32(value) {
- assert_1.assertInt32(value);
- // zigzag encode
- value = ((value << 1) ^ (value >> 31)) >>> 0;
- goog_varint_1.varint32write(value, this.buf);
- return this;
- }
+ _httpClient;
/**
- * Write a `fixed64` value, a signed, fixed-length 64-bit integer.
+ * The pipeline used by this client to make requests
*/
- sfixed64(value) {
- let chunk = new Uint8Array(8);
- let view = new DataView(chunk.buffer);
- let long = pb_long_1.PbLong.from(value);
- view.setInt32(0, long.lo, true);
- view.setInt32(4, long.hi, true);
- return this.raw(chunk);
- }
+ pipeline;
/**
- * Write a `fixed64` value, an unsigned, fixed-length 64 bit integer.
+ * The ServiceClient constructor
+ * @param options - The service client options that govern the behavior of the client.
*/
- fixed64(value) {
- let chunk = new Uint8Array(8);
- let view = new DataView(chunk.buffer);
- let long = pb_long_1.PbULong.from(value);
- view.setInt32(0, long.lo, true);
- view.setInt32(4, long.hi, true);
- return this.raw(chunk);
+ constructor(options = {}) {
+ this._requestContentType = options.requestContentType;
+ this._endpoint = options.endpoint ?? options.baseUri;
+ if (options.baseUri) {
+ dist_esm_log_logger.warning("The baseUri option for SDK Clients has been deprecated, please use endpoint instead.");
+ }
+ this._allowInsecureConnection = options.allowInsecureConnection;
+ this._httpClient = options.httpClient || getCachedDefaultHttpClient();
+ this.pipeline = options.pipeline || serviceClient_createDefaultPipeline(options);
+ if (options.additionalPolicies?.length) {
+ for (const { policy, position } of options.additionalPolicies) {
+ // Sign happens after Retry and is commonly needed to occur
+ // before policies that intercept post-retry.
+ const afterPhase = position === "perRetry" ? "Sign" : undefined;
+ this.pipeline.addPolicy(policy, {
+ afterPhase,
+ });
+ }
+ }
}
/**
- * Write a `int64` value, a signed 64-bit varint.
+ * Send the provided httpRequest.
*/
- int64(value) {
- let long = pb_long_1.PbLong.from(value);
- goog_varint_1.varint64write(long.lo, long.hi, this.buf);
- return this;
+ async sendRequest(request) {
+ return this.pipeline.sendRequest(this._httpClient, request);
}
/**
- * Write a `sint64` value, a signed, zig-zag-encoded 64-bit varint.
+ * Send an HTTP request that is populated using the provided OperationSpec.
+ * @typeParam T - The typed result of the request, based on the OperationSpec.
+ * @param operationArguments - The arguments that the HTTP request's templated values will be populated from.
+ * @param operationSpec - The OperationSpec to use to populate the httpRequest.
*/
- sint64(value) {
- let long = pb_long_1.PbLong.from(value),
- // zigzag encode
- sign = long.hi >> 31, lo = (long.lo << 1) ^ sign, hi = ((long.hi << 1) | (long.lo >>> 31)) ^ sign;
- goog_varint_1.varint64write(lo, hi, this.buf);
- return this;
+ async sendOperationRequest(operationArguments, operationSpec) {
+ const endpoint = operationSpec.baseUrl || this._endpoint;
+ if (!endpoint) {
+ throw new Error("If operationSpec.baseUrl is not specified, then the ServiceClient must have a endpoint string property that contains the base URL to use.");
+ }
+ // Templatized URLs sometimes reference properties on the ServiceClient child class,
+ // so we have to pass `this` below in order to search these properties if they're
+ // not part of OperationArguments
+ const url = getRequestUrl(endpoint, operationSpec, operationArguments, this);
+ const request = esm_pipelineRequest_createPipelineRequest({
+ url,
+ });
+ request.method = operationSpec.httpMethod;
+ const operationInfo = getOperationRequestInfo(request);
+ operationInfo.operationSpec = operationSpec;
+ operationInfo.operationArguments = operationArguments;
+ const contentType = operationSpec.contentType || this._requestContentType;
+ if (contentType && operationSpec.requestBody) {
+ request.headers.set("Content-Type", contentType);
+ }
+ const options = operationArguments.options;
+ if (options) {
+ const requestOptions = options.requestOptions;
+ if (requestOptions) {
+ if (requestOptions.timeout) {
+ request.timeout = requestOptions.timeout;
+ }
+ if (requestOptions.onUploadProgress) {
+ request.onUploadProgress = requestOptions.onUploadProgress;
+ }
+ if (requestOptions.onDownloadProgress) {
+ request.onDownloadProgress = requestOptions.onDownloadProgress;
+ }
+ if (requestOptions.shouldDeserialize !== undefined) {
+ operationInfo.shouldDeserialize = requestOptions.shouldDeserialize;
+ }
+ if (requestOptions.allowInsecureConnection) {
+ request.allowInsecureConnection = true;
+ }
+ }
+ if (options.abortSignal) {
+ request.abortSignal = options.abortSignal;
+ }
+ if (options.tracingOptions) {
+ request.tracingOptions = options.tracingOptions;
+ }
+ }
+ if (this._allowInsecureConnection) {
+ request.allowInsecureConnection = true;
+ }
+ if (request.streamResponseStatusCodes === undefined) {
+ request.streamResponseStatusCodes = getStreamingResponseStatusCodes(operationSpec);
+ }
+ try {
+ const rawResponse = await this.sendRequest(request);
+ const flatResponse = flattenResponse(rawResponse, operationSpec.responses[rawResponse.status]);
+ if (options?.onResponse) {
+ options.onResponse(rawResponse, flatResponse);
+ }
+ return flatResponse;
+ }
+ catch (error) {
+ if (typeof error === "object" && error?.response) {
+ const rawResponse = error.response;
+ const flatResponse = flattenResponse(rawResponse, operationSpec.responses[error.statusCode] || operationSpec.responses["default"]);
+ error.details = flatResponse;
+ if (options?.onResponse) {
+ options.onResponse(rawResponse, flatResponse, error);
+ }
+ }
+ throw error;
+ }
}
- /**
- * Write a `uint64` value, an unsigned 64-bit varint.
- */
- uint64(value) {
- let long = pb_long_1.PbULong.from(value);
- goog_varint_1.varint64write(long.lo, long.hi, this.buf);
- return this;
+}
+function serviceClient_createDefaultPipeline(options) {
+ const credentialScopes = getCredentialScopes(options);
+ const credentialOptions = options.credential && credentialScopes
+ ? { credentialScopes, credential: options.credential }
+ : undefined;
+ return createClientPipeline({
+ ...options,
+ credentialOptions,
+ });
+}
+function getCredentialScopes(options) {
+ if (options.credentialScopes) {
+ return options.credentialScopes;
+ }
+ if (options.endpoint) {
+ return `${options.endpoint}/.default`;
+ }
+ if (options.baseUri) {
+ return `${options.baseUri}/.default`;
}
+ if (options.credential && !options.credentialScopes) {
+ throw new Error(`When using credentials, the ServiceClientOptions must contain either a endpoint or a credentialScopes. Unable to create a bearerTokenAuthenticationPolicy`);
+ }
+ return undefined;
}
-exports.BinaryWriter = BinaryWriter;
-
-
-/***/ }),
-
-/***/ 257:
-/***/ ((__unused_webpack_module, exports) => {
+//# sourceMappingURL=serviceClient.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-client/dist/esm/authorizeRequestOnClaimChallenge.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.listEnumNumbers = exports.listEnumNames = exports.listEnumValues = exports.isEnumObject = void 0;
/**
- * Is this a lookup object generated by Typescript, for a Typescript enum
- * generated by protobuf-ts?
+ * Converts: `Bearer a="b", c="d", Bearer d="e", f="g"`.
+ * Into: `[ { a: 'b', c: 'd' }, { d: 'e', f: 'g' } ]`.
*
- * - No `const enum` (enum must not be inlined, we need reverse mapping).
- * - No string enum (we need int32 for protobuf).
- * - Must have a value for 0 (otherwise, we would need to support custom default values).
+ * @internal
*/
-function isEnumObject(arg) {
- if (typeof arg != 'object' || arg === null) {
+function parseCAEChallenge(challenges) {
+ const bearerChallenges = `, ${challenges.trim()}`.split(", Bearer ").filter((x) => x);
+ return bearerChallenges.map((challenge) => {
+ const challengeParts = `${challenge.trim()}, `.split('", ').filter((x) => x);
+ const keyValuePairs = challengeParts.map((keyValue) => (([key, value]) => ({ [key]: value }))(keyValue.trim().split('="')));
+ // Key-value pairs to plain object:
+ return keyValuePairs.reduce((a, b) => ({ ...a, ...b }), {});
+ });
+}
+/**
+ * This function can be used as a callback for the `bearerTokenAuthenticationPolicy` of `@azure/core-rest-pipeline`, to support CAE challenges:
+ * [Continuous Access Evaluation](https://learn.microsoft.com/azure/active-directory/conditional-access/concept-continuous-access-evaluation).
+ *
+ * Call the `bearerTokenAuthenticationPolicy` with the following options:
+ *
+ * ```ts snippet:AuthorizeRequestOnClaimChallenge
+ * import { bearerTokenAuthenticationPolicy } from "@azure/core-rest-pipeline";
+ * import { authorizeRequestOnClaimChallenge } from "@azure/core-client";
+ *
+ * const policy = bearerTokenAuthenticationPolicy({
+ * challengeCallbacks: {
+ * authorizeRequestOnChallenge: authorizeRequestOnClaimChallenge,
+ * },
+ * scopes: ["https://service/.default"],
+ * });
+ * ```
+ *
+ * Once provided, the `bearerTokenAuthenticationPolicy` policy will internally handle Continuous Access Evaluation (CAE) challenges.
+ * When it can't complete a challenge it will return the 401 (unauthorized) response from ARM.
+ *
+ * Example challenge with claims:
+ *
+ * ```
+ * Bearer authorization_uri="https://login.windows-ppe.net/", error="invalid_token",
+ * error_description="User session has been revoked",
+ * claims="eyJhY2Nlc3NfdG9rZW4iOnsibmJmIjp7ImVzc2VudGlhbCI6dHJ1ZSwgInZhbHVlIjoiMTYwMzc0MjgwMCJ9fX0="
+ * ```
+ */
+async function authorizeRequestOnClaimChallenge(onChallengeOptions) {
+ const { scopes, response } = onChallengeOptions;
+ const logger = onChallengeOptions.logger || coreClientLogger;
+ const challenge = response.headers.get("WWW-Authenticate");
+ if (!challenge) {
+ logger.info(`The WWW-Authenticate header was missing. Failed to perform the Continuous Access Evaluation authentication flow.`);
return false;
}
- if (!arg.hasOwnProperty(0)) {
+ const challenges = parseCAEChallenge(challenge) || [];
+ const parsedChallenge = challenges.find((x) => x.claims);
+ if (!parsedChallenge) {
+ logger.info(`The WWW-Authenticate header was missing the necessary "claims" to perform the Continuous Access Evaluation authentication flow.`);
return false;
}
- for (let k of Object.keys(arg)) {
- let num = parseInt(k);
- if (!Number.isNaN(num)) {
- // is there a name for the number?
- let nam = arg[num];
- if (nam === undefined)
- return false;
- // does the name resolve back to the number?
- if (arg[nam] !== num)
- return false;
- }
- else {
- // is there a number for the name?
- let num = arg[k];
- if (num === undefined)
- return false;
- // is it a string enum?
- if (typeof num !== 'number')
- return false;
- // do we know the number?
- if (arg[num] === undefined)
- return false;
- }
+ const accessToken = await onChallengeOptions.getAccessToken(parsedChallenge.scope ? [parsedChallenge.scope] : scopes, {
+ claims: decodeStringToString(parsedChallenge.claims),
+ });
+ if (!accessToken) {
+ return false;
}
+ onChallengeOptions.request.headers.set("Authorization", `${accessToken.tokenType ?? "Bearer"} ${accessToken.token}`);
return true;
}
-exports.isEnumObject = isEnumObject;
+//# sourceMappingURL=authorizeRequestOnClaimChallenge.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-client/dist/esm/authorizeRequestOnTenantChallenge.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
/**
- * Lists all values of a Typescript enum, as an array of objects with a "name"
- * property and a "number" property.
- *
- * Note that it is possible that a number appears more than once, because it is
- * possible to have aliases in an enum.
- *
- * Throws if the enum does not adhere to the rules of enums generated by
- * protobuf-ts. See `isEnumObject()`.
- */
-function listEnumValues(enumObject) {
- if (!isEnumObject(enumObject))
- throw new Error("not a typescript enum object");
- let values = [];
- for (let [name, number] of Object.entries(enumObject))
- if (typeof number == "number")
- values.push({ name, number });
- return values;
-}
-exports.listEnumValues = listEnumValues;
-/**
- * Lists the names of a Typescript enum.
- *
- * Throws if the enum does not adhere to the rules of enums generated by
- * protobuf-ts. See `isEnumObject()`.
- */
-function listEnumNames(enumObject) {
- return listEnumValues(enumObject).map(val => val.name);
-}
-exports.listEnumNames = listEnumNames;
-/**
- * Lists the numbers of a Typescript enum.
- *
- * Throws if the enum does not adhere to the rules of enums generated by
- * protobuf-ts. See `isEnumObject()`.
+ * A set of constants used internally when processing requests.
*/
-function listEnumNumbers(enumObject) {
- return listEnumValues(enumObject)
- .map(val => val.number)
- .filter((num, index, arr) => arr.indexOf(num) == index);
+const Constants = {
+ DefaultScope: "/.default",
+ /**
+ * Defines constants for use with HTTP headers.
+ */
+ HeaderConstants: {
+ /**
+ * The Authorization header.
+ */
+ AUTHORIZATION: "authorization",
+ },
+};
+function isUuid(text) {
+ return /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/.test(text);
}
-exports.listEnumNumbers = listEnumNumbers;
-
-
-/***/ }),
-
-/***/ 3223:
-/***/ ((__unused_webpack_module, exports) => {
-
-
-// Copyright 2008 Google Inc. All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-// Code generated by the Protocol Buffer compiler is owned by the owner
-// of the input file used when generating it. This code is not
-// standalone and requires a support library to be linked with it. This
-// support library is itself covered by the above license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.varint32read = exports.varint32write = exports.int64toString = exports.int64fromString = exports.varint64write = exports.varint64read = void 0;
/**
- * Read a 64 bit varint as two JS numbers.
- *
- * Returns tuple:
- * [0]: low bits
- * [0]: high bits
- *
- * Copyright 2008 Google Inc. All rights reserved.
- *
- * See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/buffer_decoder.js#L175
- */
-function varint64read() {
- let lowBits = 0;
- let highBits = 0;
- for (let shift = 0; shift < 28; shift += 7) {
- let b = this.buf[this.pos++];
- lowBits |= (b & 0x7F) << shift;
- if ((b & 0x80) == 0) {
- this.assertBounds();
- return [lowBits, highBits];
+ * Defines a callback to handle auth challenge for Storage APIs.
+ * This implements the bearer challenge process described here: https://learn.microsoft.com/rest/api/storageservices/authorize-with-azure-active-directory#bearer-challenge
+ * Handling has specific features for storage that departs to the general AAD challenge docs.
+ **/
+const authorizeRequestOnTenantChallenge = async (challengeOptions) => {
+ const requestOptions = requestToOptions(challengeOptions.request);
+ const challenge = getChallenge(challengeOptions.response);
+ if (challenge) {
+ const challengeInfo = parseChallenge(challenge);
+ const challengeScopes = buildScopes(challengeOptions, challengeInfo);
+ const tenantId = extractTenantId(challengeInfo);
+ if (!tenantId) {
+ return false;
}
- }
- let middleByte = this.buf[this.pos++];
- // last four bits of the first 32 bit number
- lowBits |= (middleByte & 0x0F) << 28;
- // 3 upper bits are part of the next 32 bit number
- highBits = (middleByte & 0x70) >> 4;
- if ((middleByte & 0x80) == 0) {
- this.assertBounds();
- return [lowBits, highBits];
- }
- for (let shift = 3; shift <= 31; shift += 7) {
- let b = this.buf[this.pos++];
- highBits |= (b & 0x7F) << shift;
- if ((b & 0x80) == 0) {
- this.assertBounds();
- return [lowBits, highBits];
+ const accessToken = await challengeOptions.getAccessToken(challengeScopes, {
+ ...requestOptions,
+ tenantId,
+ });
+ if (!accessToken) {
+ return false;
}
+ challengeOptions.request.headers.set(Constants.HeaderConstants.AUTHORIZATION, `${accessToken.tokenType ?? "Bearer"} ${accessToken.token}`);
+ return true;
}
- throw new Error('invalid varint');
-}
-exports.varint64read = varint64read;
+ return false;
+};
/**
- * Write a 64 bit varint, given as two JS numbers, to the given bytes array.
- *
- * Copyright 2008 Google Inc. All rights reserved.
- *
- * See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/writer.js#L344
+ * Extracts the tenant id from the challenge information
+ * The tenant id is contained in the authorization_uri as the first
+ * path part.
*/
-function varint64write(lo, hi, bytes) {
- for (let i = 0; i < 28; i = i + 7) {
- const shift = lo >>> i;
- const hasNext = !((shift >>> 7) == 0 && hi == 0);
- const byte = (hasNext ? shift | 0x80 : shift) & 0xFF;
- bytes.push(byte);
- if (!hasNext) {
- return;
- }
- }
- const splitBits = ((lo >>> 28) & 0x0F) | ((hi & 0x07) << 4);
- const hasMoreBits = !((hi >> 3) == 0);
- bytes.push((hasMoreBits ? splitBits | 0x80 : splitBits) & 0xFF);
- if (!hasMoreBits) {
- return;
- }
- for (let i = 3; i < 31; i = i + 7) {
- const shift = hi >>> i;
- const hasNext = !((shift >>> 7) == 0);
- const byte = (hasNext ? shift | 0x80 : shift) & 0xFF;
- bytes.push(byte);
- if (!hasNext) {
- return;
- }
+function extractTenantId(challengeInfo) {
+ const parsedAuthUri = new URL(challengeInfo.authorization_uri);
+ const pathSegments = parsedAuthUri.pathname.split("/");
+ const tenantId = pathSegments[1];
+ if (tenantId && isUuid(tenantId)) {
+ return tenantId;
}
- bytes.push((hi >>> 31) & 0x01);
+ return undefined;
}
-exports.varint64write = varint64write;
-// constants for binary math
-const TWO_PWR_32_DBL = (1 << 16) * (1 << 16);
/**
- * Parse decimal string of 64 bit integer value as two JS numbers.
- *
- * Returns tuple:
- * [0]: minus sign?
- * [1]: low bits
- * [2]: high bits
- *
- * Copyright 2008 Google Inc.
+ * Builds the authentication scopes based on the information that comes in the
+ * challenge information. Scopes url is present in the resource_id, if it is empty
+ * we keep using the original scopes.
*/
-function int64fromString(dec) {
- // Check for minus sign.
- let minus = dec[0] == '-';
- if (minus)
- dec = dec.slice(1);
- // Work 6 decimal digits at a time, acting like we're converting base 1e6
- // digits to binary. This is safe to do with floating point math because
- // Number.isSafeInteger(ALL_32_BITS * 1e6) == true.
- const base = 1e6;
- let lowBits = 0;
- let highBits = 0;
- function add1e6digit(begin, end) {
- // Note: Number('') is 0.
- const digit1e6 = Number(dec.slice(begin, end));
- highBits *= base;
- lowBits = lowBits * base + digit1e6;
- // Carry bits from lowBits to highBits
- if (lowBits >= TWO_PWR_32_DBL) {
- highBits = highBits + ((lowBits / TWO_PWR_32_DBL) | 0);
- lowBits = lowBits % TWO_PWR_32_DBL;
- }
+function buildScopes(challengeOptions, challengeInfo) {
+ if (!challengeInfo.resource_id) {
+ return challengeOptions.scopes;
}
- add1e6digit(-24, -18);
- add1e6digit(-18, -12);
- add1e6digit(-12, -6);
- add1e6digit(-6);
- return [minus, lowBits, highBits];
+ const challengeScopes = new URL(challengeInfo.resource_id);
+ challengeScopes.pathname = Constants.DefaultScope;
+ let scope = challengeScopes.toString();
+ if (scope === "https://disk.azure.com/.default") {
+ // the extra slash is required by the service
+ scope = "https://disk.azure.com//.default";
+ }
+ return [scope];
}
-exports.int64fromString = int64fromString;
/**
- * Format 64 bit integer value (as two JS numbers) to decimal string.
- *
- * Copyright 2008 Google Inc.
+ * We will retrieve the challenge only if the response status code was 401,
+ * and if the response contained the header "WWW-Authenticate" with a non-empty value.
*/
-function int64toString(bitsLow, bitsHigh) {
- // Skip the expensive conversion if the number is small enough to use the
- // built-in conversions.
- if ((bitsHigh >>> 0) <= 0x1FFFFF) {
- return '' + (TWO_PWR_32_DBL * bitsHigh + (bitsLow >>> 0));
- }
- // What this code is doing is essentially converting the input number from
- // base-2 to base-1e7, which allows us to represent the 64-bit range with
- // only 3 (very large) digits. Those digits are then trivial to convert to
- // a base-10 string.
- // The magic numbers used here are -
- // 2^24 = 16777216 = (1,6777216) in base-1e7.
- // 2^48 = 281474976710656 = (2,8147497,6710656) in base-1e7.
- // Split 32:32 representation into 16:24:24 representation so our
- // intermediate digits don't overflow.
- let low = bitsLow & 0xFFFFFF;
- let mid = (((bitsLow >>> 24) | (bitsHigh << 8)) >>> 0) & 0xFFFFFF;
- let high = (bitsHigh >> 16) & 0xFFFF;
- // Assemble our three base-1e7 digits, ignoring carries. The maximum
- // value in a digit at this step is representable as a 48-bit integer, which
- // can be stored in a 64-bit floating point number.
- let digitA = low + (mid * 6777216) + (high * 6710656);
- let digitB = mid + (high * 8147497);
- let digitC = (high * 2);
- // Apply carries from A to B and from B to C.
- let base = 10000000;
- if (digitA >= base) {
- digitB += Math.floor(digitA / base);
- digitA %= base;
- }
- if (digitB >= base) {
- digitC += Math.floor(digitB / base);
- digitB %= base;
- }
- // Convert base-1e7 digits to base-10, with optional leading zeroes.
- function decimalFrom1e7(digit1e7, needLeadingZeros) {
- let partial = digit1e7 ? String(digit1e7) : '';
- if (needLeadingZeros) {
- return '0000000'.slice(partial.length) + partial;
- }
- return partial;
+function getChallenge(response) {
+ const challenge = response.headers.get("WWW-Authenticate");
+ if (response.status === 401 && challenge) {
+ return challenge;
}
- return decimalFrom1e7(digitC, /*needLeadingZeros=*/ 0) +
- decimalFrom1e7(digitB, /*needLeadingZeros=*/ digitC) +
- // If the final 1e7 digit didn't need leading zeros, we would have
- // returned via the trivial code path at the top.
- decimalFrom1e7(digitA, /*needLeadingZeros=*/ 1);
+ return;
}
-exports.int64toString = int64toString;
/**
- * Write a 32 bit varint, signed or unsigned. Same as `varint64write(0, value, bytes)`
- *
- * Copyright 2008 Google Inc. All rights reserved.
+ * Converts: `Bearer a="b" c="d"`.
+ * Into: `[ { a: 'b', c: 'd' }]`.
*
- * See https://github.com/protocolbuffers/protobuf/blob/1b18833f4f2a2f681f4e4a25cdf3b0a43115ec26/js/binary/encoder.js#L144
+ * @internal
*/
-function varint32write(value, bytes) {
- if (value >= 0) {
- // write value as varint 32
- while (value > 0x7f) {
- bytes.push((value & 0x7f) | 0x80);
- value = value >>> 7;
- }
- bytes.push(value);
- }
- else {
- for (let i = 0; i < 9; i++) {
- bytes.push(value & 127 | 128);
- value = value >> 7;
- }
- bytes.push(1);
- }
+function parseChallenge(challenge) {
+ const bearerChallenge = challenge.slice("Bearer ".length);
+ const challengeParts = `${bearerChallenge.trim()} `.split(" ").filter((x) => x);
+ const keyValuePairs = challengeParts.map((keyValue) => (([key, value]) => ({ [key]: value }))(keyValue.trim().split("=")));
+ // Key-value pairs to plain object:
+ return keyValuePairs.reduce((a, b) => ({ ...a, ...b }), {});
}
-exports.varint32write = varint32write;
/**
- * Read an unsigned 32 bit varint.
- *
- * See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/buffer_decoder.js#L220
+ * Extracts the options form a Pipeline Request for later re-use
*/
-function varint32read() {
- let b = this.buf[this.pos++];
- let result = b & 0x7F;
- if ((b & 0x80) == 0) {
- this.assertBounds();
- return result;
- }
- b = this.buf[this.pos++];
- result |= (b & 0x7F) << 7;
- if ((b & 0x80) == 0) {
- this.assertBounds();
- return result;
- }
- b = this.buf[this.pos++];
- result |= (b & 0x7F) << 14;
- if ((b & 0x80) == 0) {
- this.assertBounds();
- return result;
- }
- b = this.buf[this.pos++];
- result |= (b & 0x7F) << 21;
- if ((b & 0x80) == 0) {
- this.assertBounds();
- return result;
- }
- // Extract only last 4 bits
- b = this.buf[this.pos++];
- result |= (b & 0x0F) << 28;
- for (let readBytes = 5; ((b & 0x80) !== 0) && readBytes < 10; readBytes++)
- b = this.buf[this.pos++];
- if ((b & 0x80) != 0)
- throw new Error('invalid varint');
- this.assertBounds();
- // Result can have 32 bits, convert it to unsigned
- return result >>> 0;
+function requestToOptions(request) {
+ return {
+ abortSignal: request.abortSignal,
+ requestOptions: {
+ timeout: request.timeout,
+ },
+ tracingOptions: request.tracingOptions,
+ };
}
-exports.varint32read = varint32read;
-
+//# sourceMappingURL=authorizeRequestOnTenantChallenge.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-client/dist/esm/index.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
-/***/ }),
-/***/ 8886:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-// Public API of the protobuf-ts runtime.
-// Note: we do not use `export * from ...` to help tree shakers,
-// webpack verbose output hints that this should be useful
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-// Convenience JSON typings and corresponding type guards
-var json_typings_1 = __nccwpck_require__(9999);
-Object.defineProperty(exports, "typeofJsonValue", ({ enumerable: true, get: function () { return json_typings_1.typeofJsonValue; } }));
-Object.defineProperty(exports, "isJsonObject", ({ enumerable: true, get: function () { return json_typings_1.isJsonObject; } }));
-// Base 64 encoding
-var base64_1 = __nccwpck_require__(6335);
-Object.defineProperty(exports, "base64decode", ({ enumerable: true, get: function () { return base64_1.base64decode; } }));
-Object.defineProperty(exports, "base64encode", ({ enumerable: true, get: function () { return base64_1.base64encode; } }));
-// UTF8 encoding
-var protobufjs_utf8_1 = __nccwpck_require__(8950);
-Object.defineProperty(exports, "utf8read", ({ enumerable: true, get: function () { return protobufjs_utf8_1.utf8read; } }));
-// Binary format contracts, options for reading and writing, for example
-var binary_format_contract_1 = __nccwpck_require__(4816);
-Object.defineProperty(exports, "WireType", ({ enumerable: true, get: function () { return binary_format_contract_1.WireType; } }));
-Object.defineProperty(exports, "mergeBinaryOptions", ({ enumerable: true, get: function () { return binary_format_contract_1.mergeBinaryOptions; } }));
-Object.defineProperty(exports, "UnknownFieldHandler", ({ enumerable: true, get: function () { return binary_format_contract_1.UnknownFieldHandler; } }));
-// Standard IBinaryReader implementation
-var binary_reader_1 = __nccwpck_require__(2889);
-Object.defineProperty(exports, "BinaryReader", ({ enumerable: true, get: function () { return binary_reader_1.BinaryReader; } }));
-Object.defineProperty(exports, "binaryReadOptions", ({ enumerable: true, get: function () { return binary_reader_1.binaryReadOptions; } }));
-// Standard IBinaryWriter implementation
-var binary_writer_1 = __nccwpck_require__(3957);
-Object.defineProperty(exports, "BinaryWriter", ({ enumerable: true, get: function () { return binary_writer_1.BinaryWriter; } }));
-Object.defineProperty(exports, "binaryWriteOptions", ({ enumerable: true, get: function () { return binary_writer_1.binaryWriteOptions; } }));
-// Int64 and UInt64 implementations required for the binary format
-var pb_long_1 = __nccwpck_require__(1753);
-Object.defineProperty(exports, "PbLong", ({ enumerable: true, get: function () { return pb_long_1.PbLong; } }));
-Object.defineProperty(exports, "PbULong", ({ enumerable: true, get: function () { return pb_long_1.PbULong; } }));
-// JSON format contracts, options for reading and writing, for example
-var json_format_contract_1 = __nccwpck_require__(9367);
-Object.defineProperty(exports, "jsonReadOptions", ({ enumerable: true, get: function () { return json_format_contract_1.jsonReadOptions; } }));
-Object.defineProperty(exports, "jsonWriteOptions", ({ enumerable: true, get: function () { return json_format_contract_1.jsonWriteOptions; } }));
-Object.defineProperty(exports, "mergeJsonOptions", ({ enumerable: true, get: function () { return json_format_contract_1.mergeJsonOptions; } }));
-// Message type contract
-var message_type_contract_1 = __nccwpck_require__(3785);
-Object.defineProperty(exports, "MESSAGE_TYPE", ({ enumerable: true, get: function () { return message_type_contract_1.MESSAGE_TYPE; } }));
-// Message type implementation via reflection
-var message_type_1 = __nccwpck_require__(5106);
-Object.defineProperty(exports, "MessageType", ({ enumerable: true, get: function () { return message_type_1.MessageType; } }));
-// Reflection info, generated by the plugin, exposed to the user, used by reflection ops
-var reflection_info_1 = __nccwpck_require__(7910);
-Object.defineProperty(exports, "ScalarType", ({ enumerable: true, get: function () { return reflection_info_1.ScalarType; } }));
-Object.defineProperty(exports, "LongType", ({ enumerable: true, get: function () { return reflection_info_1.LongType; } }));
-Object.defineProperty(exports, "RepeatType", ({ enumerable: true, get: function () { return reflection_info_1.RepeatType; } }));
-Object.defineProperty(exports, "normalizeFieldInfo", ({ enumerable: true, get: function () { return reflection_info_1.normalizeFieldInfo; } }));
-Object.defineProperty(exports, "readFieldOptions", ({ enumerable: true, get: function () { return reflection_info_1.readFieldOptions; } }));
-Object.defineProperty(exports, "readFieldOption", ({ enumerable: true, get: function () { return reflection_info_1.readFieldOption; } }));
-Object.defineProperty(exports, "readMessageOption", ({ enumerable: true, get: function () { return reflection_info_1.readMessageOption; } }));
-// Message operations via reflection
-var reflection_type_check_1 = __nccwpck_require__(5167);
-Object.defineProperty(exports, "ReflectionTypeCheck", ({ enumerable: true, get: function () { return reflection_type_check_1.ReflectionTypeCheck; } }));
-var reflection_create_1 = __nccwpck_require__(5726);
-Object.defineProperty(exports, "reflectionCreate", ({ enumerable: true, get: function () { return reflection_create_1.reflectionCreate; } }));
-var reflection_scalar_default_1 = __nccwpck_require__(9526);
-Object.defineProperty(exports, "reflectionScalarDefault", ({ enumerable: true, get: function () { return reflection_scalar_default_1.reflectionScalarDefault; } }));
-var reflection_merge_partial_1 = __nccwpck_require__(8044);
-Object.defineProperty(exports, "reflectionMergePartial", ({ enumerable: true, get: function () { return reflection_merge_partial_1.reflectionMergePartial; } }));
-var reflection_equals_1 = __nccwpck_require__(4827);
-Object.defineProperty(exports, "reflectionEquals", ({ enumerable: true, get: function () { return reflection_equals_1.reflectionEquals; } }));
-var reflection_binary_reader_1 = __nccwpck_require__(9611);
-Object.defineProperty(exports, "ReflectionBinaryReader", ({ enumerable: true, get: function () { return reflection_binary_reader_1.ReflectionBinaryReader; } }));
-var reflection_binary_writer_1 = __nccwpck_require__(6907);
-Object.defineProperty(exports, "ReflectionBinaryWriter", ({ enumerable: true, get: function () { return reflection_binary_writer_1.ReflectionBinaryWriter; } }));
-var reflection_json_reader_1 = __nccwpck_require__(6790);
-Object.defineProperty(exports, "ReflectionJsonReader", ({ enumerable: true, get: function () { return reflection_json_reader_1.ReflectionJsonReader; } }));
-var reflection_json_writer_1 = __nccwpck_require__(1094);
-Object.defineProperty(exports, "ReflectionJsonWriter", ({ enumerable: true, get: function () { return reflection_json_writer_1.ReflectionJsonWriter; } }));
-var reflection_contains_message_type_1 = __nccwpck_require__(9946);
-Object.defineProperty(exports, "containsMessageType", ({ enumerable: true, get: function () { return reflection_contains_message_type_1.containsMessageType; } }));
-// Oneof helpers
-var oneof_1 = __nccwpck_require__(8063);
-Object.defineProperty(exports, "isOneofGroup", ({ enumerable: true, get: function () { return oneof_1.isOneofGroup; } }));
-Object.defineProperty(exports, "setOneofValue", ({ enumerable: true, get: function () { return oneof_1.setOneofValue; } }));
-Object.defineProperty(exports, "getOneofValue", ({ enumerable: true, get: function () { return oneof_1.getOneofValue; } }));
-Object.defineProperty(exports, "clearOneofValue", ({ enumerable: true, get: function () { return oneof_1.clearOneofValue; } }));
-Object.defineProperty(exports, "getSelectedOneofValue", ({ enumerable: true, get: function () { return oneof_1.getSelectedOneofValue; } }));
-// Enum object type guard and reflection util, may be interesting to the user.
-var enum_object_1 = __nccwpck_require__(257);
-Object.defineProperty(exports, "listEnumValues", ({ enumerable: true, get: function () { return enum_object_1.listEnumValues; } }));
-Object.defineProperty(exports, "listEnumNames", ({ enumerable: true, get: function () { return enum_object_1.listEnumNames; } }));
-Object.defineProperty(exports, "listEnumNumbers", ({ enumerable: true, get: function () { return enum_object_1.listEnumNumbers; } }));
-Object.defineProperty(exports, "isEnumObject", ({ enumerable: true, get: function () { return enum_object_1.isEnumObject; } }));
-// lowerCamelCase() is exported for plugin, rpc-runtime and other rpc packages
-var lower_camel_case_1 = __nccwpck_require__(4073);
-Object.defineProperty(exports, "lowerCamelCase", ({ enumerable: true, get: function () { return lower_camel_case_1.lowerCamelCase; } }));
-// assertion functions are exported for plugin, may also be useful to user
-var assert_1 = __nccwpck_require__(8602);
-Object.defineProperty(exports, "assert", ({ enumerable: true, get: function () { return assert_1.assert; } }));
-Object.defineProperty(exports, "assertNever", ({ enumerable: true, get: function () { return assert_1.assertNever; } }));
-Object.defineProperty(exports, "assertInt32", ({ enumerable: true, get: function () { return assert_1.assertInt32; } }));
-Object.defineProperty(exports, "assertUInt32", ({ enumerable: true, get: function () { return assert_1.assertUInt32; } }));
-Object.defineProperty(exports, "assertFloat32", ({ enumerable: true, get: function () { return assert_1.assertFloat32; } }));
-/***/ }),
-/***/ 9367:
-/***/ ((__unused_webpack_module, exports) => {
+//# sourceMappingURL=index.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-http-compat/dist/esm/util.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.mergeJsonOptions = exports.jsonWriteOptions = exports.jsonReadOptions = void 0;
-const defaultsWrite = {
- emitDefaultValues: false,
- enumAsInteger: false,
- useProtoFieldName: false,
- prettySpaces: 0,
-}, defaultsRead = {
- ignoreUnknownFields: false,
-};
-/**
- * Make options for reading JSON data from partial options.
- */
-function jsonReadOptions(options) {
- return options ? Object.assign(Object.assign({}, defaultsRead), options) : defaultsRead;
-}
-exports.jsonReadOptions = jsonReadOptions;
-/**
- * Make options for writing JSON data from partial options.
- */
-function jsonWriteOptions(options) {
- return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite;
-}
-exports.jsonWriteOptions = jsonWriteOptions;
-/**
- * Merges JSON write or read options. Later values override earlier values. Type registries are merged.
- */
-function mergeJsonOptions(a, b) {
- var _a, _b;
- let c = Object.assign(Object.assign({}, a), b);
- c.typeRegistry = [...((_a = a === null || a === void 0 ? void 0 : a.typeRegistry) !== null && _a !== void 0 ? _a : []), ...((_b = b === null || b === void 0 ? void 0 : b.typeRegistry) !== null && _b !== void 0 ? _b : [])];
- return c;
+// We use a custom symbol to cache a reference to the original request without
+// exposing it on the public interface.
+const util_originalRequestSymbol = Symbol("Original PipelineRequest");
+// Symbol.for() will return the same symbol if it's already been created
+// This particular one is used in core-client to handle the case of when a request is
+// cloned but we need to retrieve the OperationSpec and OperationArguments from the
+// original request.
+const originalClientRequestSymbol = Symbol.for("@azure/core-client original request");
+function toPipelineRequest(webResource, options = {}) {
+ const compatWebResource = webResource;
+ const request = compatWebResource[util_originalRequestSymbol];
+ const headers = esm_httpHeaders_createHttpHeaders(webResource.headers.toJson({ preserveCase: true }));
+ if (request) {
+ request.headers = headers;
+ return request;
+ }
+ else {
+ const newRequest = esm_pipelineRequest_createPipelineRequest({
+ url: webResource.url,
+ method: webResource.method,
+ headers,
+ withCredentials: webResource.withCredentials,
+ timeout: webResource.timeout,
+ requestId: webResource.requestId,
+ abortSignal: webResource.abortSignal,
+ body: webResource.body,
+ formData: webResource.formData,
+ disableKeepAlive: !!webResource.keepAlive,
+ onDownloadProgress: webResource.onDownloadProgress,
+ onUploadProgress: webResource.onUploadProgress,
+ proxySettings: webResource.proxySettings,
+ streamResponseStatusCodes: webResource.streamResponseStatusCodes,
+ agent: webResource.agent,
+ requestOverrides: webResource.requestOverrides,
+ });
+ if (options.originalRequest) {
+ newRequest[originalClientRequestSymbol] =
+ options.originalRequest;
+ }
+ return newRequest;
+ }
}
-exports.mergeJsonOptions = mergeJsonOptions;
-
-
-/***/ }),
-
-/***/ 9999:
-/***/ ((__unused_webpack_module, exports) => {
-
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.isJsonObject = exports.typeofJsonValue = void 0;
-/**
- * Get the type of a JSON value.
- * Distinguishes between array, null and object.
- */
-function typeofJsonValue(value) {
- let t = typeof value;
- if (t == "object") {
- if (Array.isArray(value))
- return "array";
- if (value === null)
- return "null";
+function toWebResourceLike(request, options) {
+ const originalRequest = options?.originalRequest ?? request;
+ const webResource = {
+ url: request.url,
+ method: request.method,
+ headers: toHttpHeadersLike(request.headers),
+ withCredentials: request.withCredentials,
+ timeout: request.timeout,
+ requestId: request.headers.get("x-ms-client-request-id") || request.requestId,
+ abortSignal: request.abortSignal,
+ body: request.body,
+ formData: request.formData,
+ keepAlive: !!request.disableKeepAlive,
+ onDownloadProgress: request.onDownloadProgress,
+ onUploadProgress: request.onUploadProgress,
+ proxySettings: request.proxySettings,
+ streamResponseStatusCodes: request.streamResponseStatusCodes,
+ agent: request.agent,
+ requestOverrides: request.requestOverrides,
+ clone() {
+ throw new Error("Cannot clone a non-proxied WebResourceLike");
+ },
+ prepare() {
+ throw new Error("WebResourceLike.prepare() is not supported by @azure/core-http-compat");
+ },
+ validateRequestProperties() {
+ /** do nothing */
+ },
+ };
+ if (options?.createProxy) {
+ return new Proxy(webResource, {
+ get(target, prop, receiver) {
+ if (prop === util_originalRequestSymbol) {
+ return request;
+ }
+ else if (prop === "clone") {
+ return () => {
+ return toWebResourceLike(toPipelineRequest(webResource, { originalRequest }), {
+ createProxy: true,
+ originalRequest,
+ });
+ };
+ }
+ return Reflect.get(target, prop, receiver);
+ },
+ set(target, prop, value, receiver) {
+ if (prop === "keepAlive") {
+ request.disableKeepAlive = !value;
+ }
+ const passThroughProps = [
+ "url",
+ "method",
+ "withCredentials",
+ "timeout",
+ "requestId",
+ "abortSignal",
+ "body",
+ "formData",
+ "onDownloadProgress",
+ "onUploadProgress",
+ "proxySettings",
+ "streamResponseStatusCodes",
+ "agent",
+ "requestOverrides",
+ ];
+ if (typeof prop === "string" && passThroughProps.includes(prop)) {
+ request[prop] = value;
+ }
+ return Reflect.set(target, prop, value, receiver);
+ },
+ });
+ }
+ else {
+ return webResource;
}
- return t;
}
-exports.typeofJsonValue = typeofJsonValue;
/**
- * Is this a JSON object (instead of an array or null)?
+ * Converts HttpHeaders from core-rest-pipeline to look like
+ * HttpHeaders from core-http.
+ * @param headers - HttpHeaders from core-rest-pipeline
+ * @returns HttpHeaders as they looked in core-http
*/
-function isJsonObject(value) {
- return value !== null && typeof value == "object" && !Array.isArray(value);
+function toHttpHeadersLike(headers) {
+ return new HttpHeaders(headers.toJSON({ preserveCase: true }));
}
-exports.isJsonObject = isJsonObject;
-
-
-/***/ }),
-
-/***/ 4073:
-/***/ ((__unused_webpack_module, exports) => {
-
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.lowerCamelCase = void 0;
/**
- * Converts snake_case to lowerCamelCase.
- *
- * Should behave like protoc:
- * https://github.com/protocolbuffers/protobuf/blob/e8ae137c96444ea313485ed1118c5e43b2099cf1/src/google/protobuf/compiler/java/java_helpers.cc#L118
+ * A collection of HttpHeaders that can be sent with a HTTP request.
*/
-function lowerCamelCase(snakeCase) {
- let capNext = false;
- const sb = [];
- for (let i = 0; i < snakeCase.length; i++) {
- let next = snakeCase.charAt(i);
- if (next == '_') {
- capNext = true;
- }
- else if (/\d/.test(next)) {
- sb.push(next);
- capNext = true;
- }
- else if (capNext) {
- sb.push(next.toUpperCase());
- capNext = false;
- }
- else if (i == 0) {
- sb.push(next.toLowerCase());
- }
- else {
- sb.push(next);
- }
- }
- return sb.join('');
+function getHeaderKey(headerName) {
+ return headerName.toLowerCase();
}
-exports.lowerCamelCase = lowerCamelCase;
-
-
-/***/ }),
-
-/***/ 3785:
-/***/ ((__unused_webpack_module, exports) => {
-
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.MESSAGE_TYPE = void 0;
-/**
- * The symbol used as a key on message objects to store the message type.
- *
- * Note that this is an experimental feature - it is here to stay, but
- * implementation details may change without notice.
- */
-exports.MESSAGE_TYPE = Symbol.for("protobuf-ts/message-type");
-
-
-/***/ }),
-
-/***/ 5106:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.MessageType = void 0;
-const message_type_contract_1 = __nccwpck_require__(3785);
-const reflection_info_1 = __nccwpck_require__(7910);
-const reflection_type_check_1 = __nccwpck_require__(5167);
-const reflection_json_reader_1 = __nccwpck_require__(6790);
-const reflection_json_writer_1 = __nccwpck_require__(1094);
-const reflection_binary_reader_1 = __nccwpck_require__(9611);
-const reflection_binary_writer_1 = __nccwpck_require__(6907);
-const reflection_create_1 = __nccwpck_require__(5726);
-const reflection_merge_partial_1 = __nccwpck_require__(8044);
-const json_typings_1 = __nccwpck_require__(9999);
-const json_format_contract_1 = __nccwpck_require__(9367);
-const reflection_equals_1 = __nccwpck_require__(4827);
-const binary_writer_1 = __nccwpck_require__(3957);
-const binary_reader_1 = __nccwpck_require__(2889);
-const baseDescriptors = Object.getOwnPropertyDescriptors(Object.getPrototypeOf({}));
-const messageTypeDescriptor = baseDescriptors[message_type_contract_1.MESSAGE_TYPE] = {};
/**
- * This standard message type provides reflection-based
- * operations to work with a message.
+ * A collection of HTTP header key/value pairs.
*/
-class MessageType {
- constructor(name, fields, options) {
- this.defaultCheckDepth = 16;
- this.typeName = name;
- this.fields = fields.map(reflection_info_1.normalizeFieldInfo);
- this.options = options !== null && options !== void 0 ? options : {};
- messageTypeDescriptor.value = this;
- this.messagePrototype = Object.create(null, baseDescriptors);
- this.refTypeCheck = new reflection_type_check_1.ReflectionTypeCheck(this);
- this.refJsonReader = new reflection_json_reader_1.ReflectionJsonReader(this);
- this.refJsonWriter = new reflection_json_writer_1.ReflectionJsonWriter(this);
- this.refBinReader = new reflection_binary_reader_1.ReflectionBinaryReader(this);
- this.refBinWriter = new reflection_binary_writer_1.ReflectionBinaryWriter(this);
- }
- create(value) {
- let message = reflection_create_1.reflectionCreate(this);
- if (value !== undefined) {
- reflection_merge_partial_1.reflectionMergePartial(this, message, value);
+class HttpHeaders {
+ _headersMap;
+ constructor(rawHeaders) {
+ this._headersMap = {};
+ if (rawHeaders) {
+ for (const headerName in rawHeaders) {
+ this.set(headerName, rawHeaders[headerName]);
+ }
}
- return message;
- }
- /**
- * Clone the message.
- *
- * Unknown fields are discarded.
- */
- clone(message) {
- let copy = this.create();
- reflection_merge_partial_1.reflectionMergePartial(this, copy, message);
- return copy;
- }
- /**
- * Determines whether two message of the same type have the same field values.
- * Checks for deep equality, traversing repeated fields, oneof groups, maps
- * and messages recursively.
- * Will also return true if both messages are `undefined`.
- */
- equals(a, b) {
- return reflection_equals_1.reflectionEquals(this, a, b);
- }
- /**
- * Is the given value assignable to our message type
- * and contains no [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)?
- */
- is(arg, depth = this.defaultCheckDepth) {
- return this.refTypeCheck.is(arg, depth, false);
- }
- /**
- * Is the given value assignable to our message type,
- * regardless of [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)?
- */
- isAssignable(arg, depth = this.defaultCheckDepth) {
- return this.refTypeCheck.is(arg, depth, true);
}
/**
- * Copy partial data into the target message.
+ * Set a header in this collection with the provided name and value. The name is
+ * case-insensitive.
+ * @param headerName - The name of the header to set. This value is case-insensitive.
+ * @param headerValue - The value of the header to set.
*/
- mergePartial(target, source) {
- reflection_merge_partial_1.reflectionMergePartial(this, target, source);
+ set(headerName, headerValue) {
+ this._headersMap[getHeaderKey(headerName)] = {
+ name: headerName,
+ value: headerValue.toString(),
+ };
}
/**
- * Create a new message from binary format.
+ * Get the header value for the provided header name, or undefined if no header exists in this
+ * collection with the provided name.
+ * @param headerName - The name of the header.
*/
- fromBinary(data, options) {
- let opt = binary_reader_1.binaryReadOptions(options);
- return this.internalBinaryRead(opt.readerFactory(data), data.byteLength, opt);
+ get(headerName) {
+ const header = this._headersMap[getHeaderKey(headerName)];
+ return !header ? undefined : header.value;
}
/**
- * Read a new message from a JSON value.
+ * Get whether or not this header collection contains a header entry for the provided header name.
*/
- fromJson(json, options) {
- return this.internalJsonRead(json, json_format_contract_1.jsonReadOptions(options));
+ contains(headerName) {
+ return !!this._headersMap[getHeaderKey(headerName)];
}
/**
- * Read a new message from a JSON string.
- * This is equivalent to `T.fromJson(JSON.parse(json))`.
+ * Remove the header with the provided headerName. Return whether or not the header existed and
+ * was removed.
+ * @param headerName - The name of the header to remove.
*/
- fromJsonString(json, options) {
- let value = JSON.parse(json);
- return this.fromJson(value, options);
+ remove(headerName) {
+ const result = this.contains(headerName);
+ delete this._headersMap[getHeaderKey(headerName)];
+ return result;
}
/**
- * Write the message to canonical JSON value.
+ * Get the headers that are contained this collection as an object.
*/
- toJson(message, options) {
- return this.internalJsonWrite(message, json_format_contract_1.jsonWriteOptions(options));
+ rawHeaders() {
+ return this.toJson({ preserveCase: true });
}
/**
- * Convert the message to canonical JSON string.
- * This is equivalent to `JSON.stringify(T.toJson(t))`
+ * Get the headers that are contained in this collection as an array.
*/
- toJsonString(message, options) {
- var _a;
- let value = this.toJson(message, options);
- return JSON.stringify(value, null, (_a = options === null || options === void 0 ? void 0 : options.prettySpaces) !== null && _a !== void 0 ? _a : 0);
+ headersArray() {
+ const headers = [];
+ for (const headerKey in this._headersMap) {
+ headers.push(this._headersMap[headerKey]);
+ }
+ return headers;
}
/**
- * Write the message to binary format.
+ * Get the header names that are contained in this collection.
*/
- toBinary(message, options) {
- let opt = binary_writer_1.binaryWriteOptions(options);
- return this.internalBinaryWrite(message, opt.writerFactory(), opt).finish();
+ headerNames() {
+ const headerNames = [];
+ const headers = this.headersArray();
+ for (let i = 0; i < headers.length; ++i) {
+ headerNames.push(headers[i].name);
+ }
+ return headerNames;
}
/**
- * This is an internal method. If you just want to read a message from
- * JSON, use `fromJson()` or `fromJsonString()`.
- *
- * Reads JSON value and merges the fields into the target
- * according to protobuf rules. If the target is omitted,
- * a new instance is created first.
+ * Get the header values that are contained in this collection.
*/
- internalJsonRead(json, options, target) {
- if (json !== null && typeof json == "object" && !Array.isArray(json)) {
- let message = target !== null && target !== void 0 ? target : this.create();
- this.refJsonReader.read(json, message, options);
- return message;
+ headerValues() {
+ const headerValues = [];
+ const headers = this.headersArray();
+ for (let i = 0; i < headers.length; ++i) {
+ headerValues.push(headers[i].value);
}
- throw new Error(`Unable to parse message ${this.typeName} from JSON ${json_typings_1.typeofJsonValue(json)}.`);
+ return headerValues;
}
/**
- * This is an internal method. If you just want to write a message
- * to JSON, use `toJson()` or `toJsonString().
- *
- * Writes JSON value and returns it.
+ * Get the JSON object representation of this HTTP header collection.
*/
- internalJsonWrite(message, options) {
- return this.refJsonWriter.write(message, options);
+ toJson(options = {}) {
+ const result = {};
+ if (options.preserveCase) {
+ for (const headerKey in this._headersMap) {
+ const header = this._headersMap[headerKey];
+ result[header.name] = header.value;
+ }
+ }
+ else {
+ for (const headerKey in this._headersMap) {
+ const header = this._headersMap[headerKey];
+ result[getHeaderKey(header.name)] = header.value;
+ }
+ }
+ return result;
}
/**
- * This is an internal method. If you just want to write a message
- * in binary format, use `toBinary()`.
- *
- * Serializes the message in binary format and appends it to the given
- * writer. Returns passed writer.
+ * Get the string representation of this HTTP header collection.
*/
- internalBinaryWrite(message, writer, options) {
- this.refBinWriter.write(message, writer, options);
- return writer;
+ toString() {
+ return JSON.stringify(this.toJson({ preserveCase: true }));
}
/**
- * This is an internal method. If you just want to read a message from
- * binary data, use `fromBinary()`.
- *
- * Reads data from binary format and merges the fields into
- * the target according to protobuf rules. If the target is
- * omitted, a new instance is created first.
+ * Create a deep clone/copy of this HttpHeaders collection.
*/
- internalBinaryRead(reader, length, options, target) {
- let message = target !== null && target !== void 0 ? target : this.create();
- this.refBinReader.read(reader, message, options, length);
- return message;
+ clone() {
+ const resultPreservingCasing = {};
+ for (const headerKey in this._headersMap) {
+ const header = this._headersMap[headerKey];
+ resultPreservingCasing[header.name] = header.value;
+ }
+ return new HttpHeaders(resultPreservingCasing);
}
}
-exports.MessageType = MessageType;
-
-
-/***/ }),
-
-/***/ 8063:
-/***/ ((__unused_webpack_module, exports) => {
+//# sourceMappingURL=util.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-http-compat/dist/esm/response.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.getSelectedOneofValue = exports.clearOneofValue = exports.setUnknownOneofValue = exports.setOneofValue = exports.getOneofValue = exports.isOneofGroup = void 0;
-/**
- * Is the given value a valid oneof group?
- *
- * We represent protobuf `oneof` as algebraic data types (ADT) in generated
- * code. But when working with messages of unknown type, the ADT does not
- * help us.
- *
- * This type guard checks if the given object adheres to the ADT rules, which
- * are as follows:
- *
- * 1) Must be an object.
- *
- * 2) Must have a "oneofKind" discriminator property.
- *
- * 3) If "oneofKind" is `undefined`, no member field is selected. The object
- * must not have any other properties.
- *
- * 4) If "oneofKind" is a `string`, the member field with this name is
- * selected.
- *
- * 5) If a member field is selected, the object must have a second property
- * with this name. The property must not be `undefined`.
- *
- * 6) No extra properties are allowed. The object has either one property
- * (no selection) or two properties (selection).
- *
- */
-function isOneofGroup(any) {
- if (typeof any != 'object' || any === null || !any.hasOwnProperty('oneofKind')) {
- return false;
- }
- switch (typeof any.oneofKind) {
- case "string":
- if (any[any.oneofKind] === undefined)
- return false;
- return Object.keys(any).length == 2;
- case "undefined":
- return Object.keys(any).length == 1;
- default:
- return false;
- }
-}
-exports.isOneofGroup = isOneofGroup;
+const originalResponse = Symbol("Original FullOperationResponse");
/**
- * Returns the value of the given field in a oneof group.
+ * A helper to convert response objects from the new pipeline back to the old one.
+ * @param response - A response object from core-client.
+ * @returns A response compatible with `HttpOperationResponse` from core-http.
*/
-function getOneofValue(oneof, kind) {
- return oneof[kind];
-}
-exports.getOneofValue = getOneofValue;
-function setOneofValue(oneof, kind, value) {
- if (oneof.oneofKind !== undefined) {
- delete oneof[oneof.oneofKind];
- }
- oneof.oneofKind = kind;
- if (value !== undefined) {
- oneof[kind] = value;
- }
-}
-exports.setOneofValue = setOneofValue;
-function setUnknownOneofValue(oneof, kind, value) {
- if (oneof.oneofKind !== undefined) {
- delete oneof[oneof.oneofKind];
+function toCompatResponse(response, options) {
+ let request = toWebResourceLike(response.request);
+ let headers = toHttpHeadersLike(response.headers);
+ if (options?.createProxy) {
+ return new Proxy(response, {
+ get(target, prop, receiver) {
+ if (prop === "headers") {
+ return headers;
+ }
+ else if (prop === "request") {
+ return request;
+ }
+ else if (prop === originalResponse) {
+ return response;
+ }
+ return Reflect.get(target, prop, receiver);
+ },
+ set(target, prop, value, receiver) {
+ if (prop === "headers") {
+ headers = value;
+ }
+ else if (prop === "request") {
+ request = value;
+ }
+ return Reflect.set(target, prop, value, receiver);
+ },
+ });
}
- oneof.oneofKind = kind;
- if (value !== undefined && kind !== undefined) {
- oneof[kind] = value;
+ else {
+ return {
+ ...response,
+ request,
+ headers,
+ };
}
}
-exports.setUnknownOneofValue = setUnknownOneofValue;
/**
- * Removes the selected field in a oneof group.
- *
- * Note that the recommended way to modify a oneof group is to set
- * a new object:
- *
- * ```ts
- * message.result = { oneofKind: undefined };
- * ```
+ * A helper to convert back to a PipelineResponse
+ * @param compatResponse - A response compatible with `HttpOperationResponse` from core-http.
*/
-function clearOneofValue(oneof) {
- if (oneof.oneofKind !== undefined) {
- delete oneof[oneof.oneofKind];
+function response_toPipelineResponse(compatResponse) {
+ const extendedCompatResponse = compatResponse;
+ const response = extendedCompatResponse[originalResponse];
+ const headers = esm_httpHeaders_createHttpHeaders(compatResponse.headers.toJson({ preserveCase: true }));
+ if (response) {
+ response.headers = headers;
+ return response;
}
- oneof.oneofKind = undefined;
-}
-exports.clearOneofValue = clearOneofValue;
-/**
- * Returns the selected value of the given oneof group.
- *
- * Not that the recommended way to access a oneof group is to check
- * the "oneofKind" property and let TypeScript narrow down the union
- * type for you:
- *
- * ```ts
- * if (message.result.oneofKind === "error") {
- * message.result.error; // string
- * }
- * ```
- *
- * In the rare case you just need the value, and do not care about
- * which protobuf field is selected, you can use this function
- * for convenience.
- */
-function getSelectedOneofValue(oneof) {
- if (oneof.oneofKind === undefined) {
- return undefined;
+ else {
+ return {
+ ...compatResponse,
+ headers,
+ request: toPipelineRequest(compatResponse.request),
+ };
}
- return oneof[oneof.oneofKind];
}
-exports.getSelectedOneofValue = getSelectedOneofValue;
-
+//# sourceMappingURL=response.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-http-compat/dist/esm/extendedClient.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
-/***/ }),
-/***/ 1753:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.PbLong = exports.PbULong = exports.detectBi = void 0;
-const goog_varint_1 = __nccwpck_require__(3223);
-let BI;
-function detectBi() {
- const dv = new DataView(new ArrayBuffer(8));
- const ok = globalThis.BigInt !== undefined
- && typeof dv.getBigInt64 === "function"
- && typeof dv.getBigUint64 === "function"
- && typeof dv.setBigInt64 === "function"
- && typeof dv.setBigUint64 === "function";
- BI = ok ? {
- MIN: BigInt("-9223372036854775808"),
- MAX: BigInt("9223372036854775807"),
- UMIN: BigInt("0"),
- UMAX: BigInt("18446744073709551615"),
- C: BigInt,
- V: dv,
- } : undefined;
-}
-exports.detectBi = detectBi;
-detectBi();
-function assertBi(bi) {
- if (!bi)
- throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support");
-}
-// used to validate from(string) input (when bigint is unavailable)
-const RE_DECIMAL_STR = /^-?[0-9]+$/;
-// constants for binary math
-const TWO_PWR_32_DBL = 0x100000000;
-const HALF_2_PWR_32 = 0x080000000;
-// base class for PbLong and PbULong provides shared code
-class SharedPbLong {
- /**
- * Create a new instance with the given bits.
- */
- constructor(lo, hi) {
- this.lo = lo | 0;
- this.hi = hi | 0;
- }
- /**
- * Is this instance equal to 0?
- */
- isZero() {
- return this.lo == 0 && this.hi == 0;
+/**
+ * Client to provide compatability between core V1 & V2.
+ */
+class ExtendedServiceClient extends ServiceClient {
+ constructor(options) {
+ super(options);
+ if (options.keepAliveOptions?.enable === false &&
+ !pipelineContainsDisableKeepAlivePolicy(this.pipeline)) {
+ this.pipeline.addPolicy(createDisableKeepAlivePolicy());
+ }
+ if (options.redirectOptions?.handleRedirects === false) {
+ this.pipeline.removePolicy({
+ name: redirectPolicy_redirectPolicyName,
+ });
+ }
}
/**
- * Convert to a native number.
+ * Compatible send operation request function.
+ *
+ * @param operationArguments - Operation arguments
+ * @param operationSpec - Operation Spec
+ * @returns
*/
- toNumber() {
- let result = this.hi * TWO_PWR_32_DBL + (this.lo >>> 0);
- if (!Number.isSafeInteger(result))
- throw new Error("cannot convert to safe number");
+ async sendOperationRequest(operationArguments, operationSpec) {
+ const userProvidedCallBack = operationArguments?.options?.onResponse;
+ let lastResponse;
+ function onResponse(rawResponse, flatResponse, error) {
+ lastResponse = rawResponse;
+ if (userProvidedCallBack) {
+ userProvidedCallBack(rawResponse, flatResponse, error);
+ }
+ }
+ operationArguments.options = {
+ ...operationArguments.options,
+ onResponse,
+ };
+ const result = await super.sendOperationRequest(operationArguments, operationSpec);
+ if (lastResponse) {
+ Object.defineProperty(result, "_response", {
+ value: toCompatResponse(lastResponse),
+ });
+ }
return result;
}
}
+//# sourceMappingURL=extendedClient.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-http-compat/dist/esm/policies/requestPolicyFactoryPolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+
+
/**
- * 64-bit unsigned integer as two 32-bit values.
- * Converts between `string`, `number` and `bigint` representations.
+ * An enum for compatibility with RequestPolicy
*/
-class PbULong extends SharedPbLong {
- /**
- * Create instance from a `string`, `number` or `bigint`.
- */
- static from(value) {
- if (BI)
- // noinspection FallThroughInSwitchStatementJS
- switch (typeof value) {
- case "string":
- if (value == "0")
- return this.ZERO;
- if (value == "")
- throw new Error('string is no integer');
- value = BI.C(value);
- case "number":
- if (value === 0)
- return this.ZERO;
- value = BI.C(value);
- case "bigint":
- if (!value)
- return this.ZERO;
- if (value < BI.UMIN)
- throw new Error('signed value for ulong');
- if (value > BI.UMAX)
- throw new Error('ulong too large');
- BI.V.setBigUint64(0, value, true);
- return new PbULong(BI.V.getInt32(0, true), BI.V.getInt32(4, true));
- }
- else
- switch (typeof value) {
- case "string":
- if (value == "0")
- return this.ZERO;
- value = value.trim();
- if (!RE_DECIMAL_STR.test(value))
- throw new Error('string is no integer');
- let [minus, lo, hi] = goog_varint_1.int64fromString(value);
- if (minus)
- throw new Error('signed value for ulong');
- return new PbULong(lo, hi);
- case "number":
- if (value == 0)
- return this.ZERO;
- if (!Number.isSafeInteger(value))
- throw new Error('number is no integer');
- if (value < 0)
- throw new Error('signed value for ulong');
- return new PbULong(value, value / TWO_PWR_32_DBL);
- }
- throw new Error('unknown value ' + typeof value);
- }
- /**
- * Convert to decimal string.
- */
- toString() {
- return BI ? this.toBigInt().toString() : goog_varint_1.int64toString(this.lo, this.hi);
- }
- /**
- * Convert to native bigint.
- */
- toBigInt() {
- assertBi(BI);
- BI.V.setInt32(0, this.lo, true);
- BI.V.setInt32(4, this.hi, true);
- return BI.V.getBigUint64(0, true);
- }
-}
-exports.PbULong = PbULong;
+var HttpPipelineLogLevel;
+(function (HttpPipelineLogLevel) {
+ HttpPipelineLogLevel[HttpPipelineLogLevel["ERROR"] = 1] = "ERROR";
+ HttpPipelineLogLevel[HttpPipelineLogLevel["INFO"] = 3] = "INFO";
+ HttpPipelineLogLevel[HttpPipelineLogLevel["OFF"] = 0] = "OFF";
+ HttpPipelineLogLevel[HttpPipelineLogLevel["WARNING"] = 2] = "WARNING";
+})(HttpPipelineLogLevel || (HttpPipelineLogLevel = {}));
+const mockRequestPolicyOptions = {
+ log(_logLevel, _message) {
+ /* do nothing */
+ },
+ shouldLog(_logLevel) {
+ return false;
+ },
+};
/**
- * ulong 0 singleton.
+ * The name of the RequestPolicyFactoryPolicy
*/
-PbULong.ZERO = new PbULong(0, 0);
+const requestPolicyFactoryPolicyName = "RequestPolicyFactoryPolicy";
/**
- * 64-bit signed integer as two 32-bit values.
- * Converts between `string`, `number` and `bigint` representations.
+ * A policy that wraps policies written for core-http.
+ * @param factories - An array of `RequestPolicyFactory` objects from a core-http pipeline
*/
-class PbLong extends SharedPbLong {
- /**
- * Create instance from a `string`, `number` or `bigint`.
- */
- static from(value) {
- if (BI)
- // noinspection FallThroughInSwitchStatementJS
- switch (typeof value) {
- case "string":
- if (value == "0")
- return this.ZERO;
- if (value == "")
- throw new Error('string is no integer');
- value = BI.C(value);
- case "number":
- if (value === 0)
- return this.ZERO;
- value = BI.C(value);
- case "bigint":
- if (!value)
- return this.ZERO;
- if (value < BI.MIN)
- throw new Error('signed long too small');
- if (value > BI.MAX)
- throw new Error('signed long too large');
- BI.V.setBigInt64(0, value, true);
- return new PbLong(BI.V.getInt32(0, true), BI.V.getInt32(4, true));
- }
- else
- switch (typeof value) {
- case "string":
- if (value == "0")
- return this.ZERO;
- value = value.trim();
- if (!RE_DECIMAL_STR.test(value))
- throw new Error('string is no integer');
- let [minus, lo, hi] = goog_varint_1.int64fromString(value);
- if (minus) {
- if (hi > HALF_2_PWR_32 || (hi == HALF_2_PWR_32 && lo != 0))
- throw new Error('signed long too small');
- }
- else if (hi >= HALF_2_PWR_32)
- throw new Error('signed long too large');
- let pbl = new PbLong(lo, hi);
- return minus ? pbl.negate() : pbl;
- case "number":
- if (value == 0)
- return this.ZERO;
- if (!Number.isSafeInteger(value))
- throw new Error('number is no integer');
- return value > 0
- ? new PbLong(value, value / TWO_PWR_32_DBL)
- : new PbLong(-value, -value / TWO_PWR_32_DBL).negate();
+function createRequestPolicyFactoryPolicy(factories) {
+ const orderedFactories = factories.slice().reverse();
+ return {
+ name: requestPolicyFactoryPolicyName,
+ async sendRequest(request, next) {
+ let httpPipeline = {
+ async sendRequest(httpRequest) {
+ const response = await next(toPipelineRequest(httpRequest));
+ return toCompatResponse(response, { createProxy: true });
+ },
+ };
+ for (const factory of orderedFactories) {
+ httpPipeline = factory.create(httpPipeline, mockRequestPolicyOptions);
}
- throw new Error('unknown value ' + typeof value);
- }
- /**
- * Do we have a minus sign?
- */
- isNegative() {
- return (this.hi & HALF_2_PWR_32) !== 0;
- }
- /**
- * Negate two's complement.
- * Invert all the bits and add one to the result.
- */
- negate() {
- let hi = ~this.hi, lo = this.lo;
- if (lo)
- lo = ~lo + 1;
- else
- hi += 1;
- return new PbLong(lo, hi);
- }
- /**
- * Convert to decimal string.
- */
- toString() {
- if (BI)
- return this.toBigInt().toString();
- if (this.isNegative()) {
- let n = this.negate();
- return '-' + goog_varint_1.int64toString(n.lo, n.hi);
- }
- return goog_varint_1.int64toString(this.lo, this.hi);
- }
- /**
- * Convert to native bigint.
- */
- toBigInt() {
- assertBi(BI);
- BI.V.setInt32(0, this.lo, true);
- BI.V.setInt32(4, this.hi, true);
- return BI.V.getBigInt64(0, true);
- }
+ const webResourceLike = toWebResourceLike(request, { createProxy: true });
+ const response = await httpPipeline.sendRequest(webResourceLike);
+ return response_toPipelineResponse(response);
+ },
+ };
}
-exports.PbLong = PbLong;
+//# sourceMappingURL=requestPolicyFactoryPolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-http-compat/dist/esm/httpClientAdapter.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+
+
/**
- * long 0 singleton.
+ * Converts a RequestPolicy based HttpClient to a PipelineRequest based HttpClient.
+ * @param requestPolicyClient - A HttpClient compatible with core-http
+ * @returns A HttpClient compatible with core-rest-pipeline
+ */
+function convertHttpClient(requestPolicyClient) {
+ return {
+ sendRequest: async (request) => {
+ const response = await requestPolicyClient.sendRequest(toWebResourceLike(request, { createProxy: true }));
+ return response_toPipelineResponse(response);
+ },
+ };
+}
+//# sourceMappingURL=httpClientAdapter.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-http-compat/dist/esm/index.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+/**
+ * A Shim Library that provides compatibility between Core V1 & V2 Packages.
+ *
+ * @packageDocumentation
*/
-PbLong.ZERO = new PbLong(0, 0);
-/***/ }),
-/***/ 8950:
-/***/ ((__unused_webpack_module, exports) => {
-// Copyright (c) 2016, Daniel Wirtz All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above copyright
-// notice, this list of conditions and the following disclaimer in the
-// documentation and/or other materials provided with the distribution.
-// * Neither the name of its author, nor the names of its contributors
-// may be used to endorse or promote products derived from this software
-// without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.utf8read = void 0;
-const fromCharCodes = (chunk) => String.fromCharCode.apply(String, chunk);
+
+//# sourceMappingURL=index.js.map
+;// CONCATENATED MODULE: ./node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js
+const EOL = "\n";
+
/**
- * @deprecated This function will no longer be exported with the next major
- * release, since protobuf-ts has switch to TextDecoder API. If you need this
- * function, please migrate to @protobufjs/utf8. For context, see
- * https://github.com/timostamm/protobuf-ts/issues/184
- *
- * Reads UTF8 bytes as a string.
- *
- * See [protobufjs / utf8](https://github.com/protobufjs/protobuf.js/blob/9893e35b854621cce64af4bf6be2cff4fb892796/lib/utf8/index.js#L40)
- *
- * Copyright (c) 2016, Daniel Wirtz
+ *
+ * @param {array} jArray
+ * @param {any} options
+ * @returns
*/
-function utf8read(bytes) {
- if (bytes.length < 1)
- return "";
- let pos = 0, // position in bytes
- parts = [], chunk = [], i = 0, // char offset
- t; // temporary
- let len = bytes.length;
- while (pos < len) {
- t = bytes[pos++];
- if (t < 128)
- chunk[i++] = t;
- else if (t > 191 && t < 224)
- chunk[i++] = (t & 31) << 6 | bytes[pos++] & 63;
- else if (t > 239 && t < 365) {
- t = ((t & 7) << 18 | (bytes[pos++] & 63) << 12 | (bytes[pos++] & 63) << 6 | bytes[pos++] & 63) - 0x10000;
- chunk[i++] = 0xD800 + (t >> 10);
- chunk[i++] = 0xDC00 + (t & 1023);
- }
- else
- chunk[i++] = (t & 15) << 12 | (bytes[pos++] & 63) << 6 | bytes[pos++] & 63;
- if (i > 8191) {
- parts.push(fromCharCodes(chunk));
- i = 0;
- }
- }
- if (parts.length) {
- if (i)
- parts.push(fromCharCodes(chunk.slice(0, i)));
- return parts.join("");
+function toXml(jArray, options) {
+ let indentation = "";
+ if (options.format && options.indentBy.length > 0) {
+ indentation = EOL;
}
- return fromCharCodes(chunk.slice(0, i));
+ return arrToStr(jArray, options, "", indentation);
}
-exports.utf8read = utf8read;
+function arrToStr(arr, options, jPath, indentation) {
+ let xmlStr = "";
+ let isPreviousElementTag = false;
-/***/ }),
-
-/***/ 9611:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ for (let i = 0; i < arr.length; i++) {
+ const tagObj = arr[i];
+ const tagName = propName(tagObj);
+ if(tagName === undefined) continue;
+ let newJPath = "";
+ if (jPath.length === 0) newJPath = tagName
+ else newJPath = `${jPath}.${tagName}`;
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.ReflectionBinaryReader = void 0;
-const binary_format_contract_1 = __nccwpck_require__(4816);
-const reflection_info_1 = __nccwpck_require__(7910);
-const reflection_long_convert_1 = __nccwpck_require__(3402);
-const reflection_scalar_default_1 = __nccwpck_require__(9526);
-/**
- * Reads proto3 messages in binary format using reflection information.
- *
- * https://developers.google.com/protocol-buffers/docs/encoding
- */
-class ReflectionBinaryReader {
- constructor(info) {
- this.info = info;
- }
- prepare() {
- var _a;
- if (!this.fieldNoToField) {
- const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : [];
- this.fieldNoToField = new Map(fieldsInput.map(field => [field.no, field]));
- }
- }
- /**
- * Reads a message from binary format into the target message.
- *
- * Repeated fields are appended. Map entries are added, overwriting
- * existing keys.
- *
- * If a message field is already present, it will be merged with the
- * new data.
- */
- read(reader, message, options, length) {
- this.prepare();
- const end = length === undefined ? reader.len : reader.pos + length;
- while (reader.pos < end) {
- // read the tag and find the field
- const [fieldNo, wireType] = reader.tag(), field = this.fieldNoToField.get(fieldNo);
- if (!field) {
- let u = options.readUnknownField;
- if (u == "throw")
- throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.info.typeName}`);
- let d = reader.skip(wireType);
- if (u !== false)
- (u === true ? binary_format_contract_1.UnknownFieldHandler.onRead : u)(this.info.typeName, message, fieldNo, wireType, d);
- continue;
+ if (tagName === options.textNodeName) {
+ let tagText = tagObj[tagName];
+ if (!isStopNode(newJPath, options)) {
+ tagText = options.tagValueProcessor(tagName, tagText);
+ tagText = replaceEntitiesValue(tagText, options);
}
- // target object for the field we are reading
- let target = message, repeated = field.repeat, localName = field.localName;
- // if field is member of oneof ADT, use ADT as target
- if (field.oneof) {
- target = target[field.oneof];
- // if other oneof member selected, set new ADT
- if (target.oneofKind !== localName)
- target = message[field.oneof] = {
- oneofKind: localName
- };
+ if (isPreviousElementTag) {
+ xmlStr += indentation;
}
- // we have handled oneof above, we just have read the value into `target[localName]`
- switch (field.kind) {
- case "scalar":
- case "enum":
- let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T;
- let L = field.kind == "scalar" ? field.L : undefined;
- if (repeated) {
- let arr = target[localName]; // safe to assume presence of array, oneof cannot contain repeated values
- if (wireType == binary_format_contract_1.WireType.LengthDelimited && T != reflection_info_1.ScalarType.STRING && T != reflection_info_1.ScalarType.BYTES) {
- let e = reader.uint32() + reader.pos;
- while (reader.pos < e)
- arr.push(this.scalar(reader, T, L));
- }
- else
- arr.push(this.scalar(reader, T, L));
- }
- else
- target[localName] = this.scalar(reader, T, L);
- break;
- case "message":
- if (repeated) {
- let arr = target[localName]; // safe to assume presence of array, oneof cannot contain repeated values
- let msg = field.T().internalBinaryRead(reader, reader.uint32(), options);
- arr.push(msg);
- }
- else
- target[localName] = field.T().internalBinaryRead(reader, reader.uint32(), options, target[localName]);
- break;
- case "map":
- let [mapKey, mapVal] = this.mapEntry(field, reader, options);
- // safe to assume presence of map object, oneof cannot contain repeated values
- target[localName][mapKey] = mapVal;
- break;
+ xmlStr += tagText;
+ isPreviousElementTag = false;
+ continue;
+ } else if (tagName === options.cdataPropName) {
+ if (isPreviousElementTag) {
+ xmlStr += indentation;
+ }
+ xmlStr += ``;
+ isPreviousElementTag = false;
+ continue;
+ } else if (tagName === options.commentPropName) {
+ xmlStr += indentation + ``;
+ isPreviousElementTag = true;
+ continue;
+ } else if (tagName[0] === "?") {
+ const attStr = attr_to_str(tagObj[":@"], options);
+ const tempInd = tagName === "?xml" ? "" : indentation;
+ let piTextNodeName = tagObj[tagName][0][options.textNodeName];
+ piTextNodeName = piTextNodeName.length !== 0 ? " " + piTextNodeName : ""; //remove extra spacing
+ xmlStr += tempInd + `<${tagName}${piTextNodeName}${attStr}?>`;
+ isPreviousElementTag = true;
+ continue;
+ }
+ let newIdentation = indentation;
+ if (newIdentation !== "") {
+ newIdentation += options.indentBy;
+ }
+ const attStr = attr_to_str(tagObj[":@"], options);
+ const tagStart = indentation + `<${tagName}${attStr}`;
+ const tagValue = arrToStr(tagObj[tagName], options, newJPath, newIdentation);
+ if (options.unpairedTags.indexOf(tagName) !== -1) {
+ if (options.suppressUnpairedNode) xmlStr += tagStart + ">";
+ else xmlStr += tagStart + "/>";
+ } else if ((!tagValue || tagValue.length === 0) && options.suppressEmptyNode) {
+ xmlStr += tagStart + "/>";
+ } else if (tagValue && tagValue.endsWith(">")) {
+ xmlStr += tagStart + `>${tagValue}${indentation}${tagName}>`;
+ } else {
+ xmlStr += tagStart + ">";
+ if (tagValue && indentation !== "" && (tagValue.includes("/>") || tagValue.includes(""))) {
+ xmlStr += indentation + options.indentBy + tagValue + indentation;
+ } else {
+ xmlStr += tagValue;
}
+ xmlStr += `${tagName}>`;
}
+ isPreviousElementTag = true;
}
- /**
- * Read a map field, expecting key field = 1, value field = 2
- */
- mapEntry(field, reader, options) {
- let length = reader.uint32();
- let end = reader.pos + length;
- let key = undefined; // javascript only allows number or string for object properties
- let val = undefined;
- while (reader.pos < end) {
- let [fieldNo, wireType] = reader.tag();
- switch (fieldNo) {
- case 1:
- if (field.K == reflection_info_1.ScalarType.BOOL)
- key = reader.bool().toString();
- else
- // long types are read as string, number types are okay as number
- key = this.scalar(reader, field.K, reflection_info_1.LongType.STRING);
- break;
- case 2:
- switch (field.V.kind) {
- case "scalar":
- val = this.scalar(reader, field.V.T, field.V.L);
- break;
- case "enum":
- val = reader.int32();
- break;
- case "message":
- val = field.V.T().internalBinaryRead(reader, reader.uint32(), options);
- break;
- }
- break;
- default:
- throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) in map entry for ${this.info.typeName}#${field.name}`);
+
+ return xmlStr;
+}
+
+function propName(obj) {
+ const keys = Object.keys(obj);
+ for (let i = 0; i < keys.length; i++) {
+ const key = keys[i];
+ if(!obj.hasOwnProperty(key)) continue;
+ if (key !== ":@") return key;
+ }
+}
+
+function attr_to_str(attrMap, options) {
+ let attrStr = "";
+ if (attrMap && !options.ignoreAttributes) {
+ for (let attr in attrMap) {
+ if(!attrMap.hasOwnProperty(attr)) continue;
+ let attrVal = options.attributeValueProcessor(attr, attrMap[attr]);
+ attrVal = replaceEntitiesValue(attrVal, options);
+ if (attrVal === true && options.suppressBooleanAttributes) {
+ attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}`;
+ } else {
+ attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}="${attrVal}"`;
}
}
- if (key === undefined) {
- let keyRaw = reflection_scalar_default_1.reflectionScalarDefault(field.K);
- key = field.K == reflection_info_1.ScalarType.BOOL ? keyRaw.toString() : keyRaw;
+ }
+ return attrStr;
+}
+
+function isStopNode(jPath, options) {
+ jPath = jPath.substr(0, jPath.length - options.textNodeName.length - 1);
+ let tagName = jPath.substr(jPath.lastIndexOf(".") + 1);
+ for (let index in options.stopNodes) {
+ if (options.stopNodes[index] === jPath || options.stopNodes[index] === "*." + tagName) return true;
+ }
+ return false;
+}
+
+function replaceEntitiesValue(textValue, options) {
+ if (textValue && textValue.length > 0 && options.processEntities) {
+ for (let i = 0; i < options.entities.length; i++) {
+ const entity = options.entities[i];
+ textValue = textValue.replace(entity.regex, entity.val);
}
- if (val === undefined)
- switch (field.V.kind) {
- case "scalar":
- val = reflection_scalar_default_1.reflectionScalarDefault(field.V.T, field.V.L);
- break;
- case "enum":
- val = 0;
- break;
- case "message":
- val = field.V.T().create();
- break;
- }
- return [key, val];
}
- scalar(reader, type, longType) {
- switch (type) {
- case reflection_info_1.ScalarType.INT32:
- return reader.int32();
- case reflection_info_1.ScalarType.STRING:
- return reader.string();
- case reflection_info_1.ScalarType.BOOL:
- return reader.bool();
- case reflection_info_1.ScalarType.DOUBLE:
- return reader.double();
- case reflection_info_1.ScalarType.FLOAT:
- return reader.float();
- case reflection_info_1.ScalarType.INT64:
- return reflection_long_convert_1.reflectionLongConvert(reader.int64(), longType);
- case reflection_info_1.ScalarType.UINT64:
- return reflection_long_convert_1.reflectionLongConvert(reader.uint64(), longType);
- case reflection_info_1.ScalarType.FIXED64:
- return reflection_long_convert_1.reflectionLongConvert(reader.fixed64(), longType);
- case reflection_info_1.ScalarType.FIXED32:
- return reader.fixed32();
- case reflection_info_1.ScalarType.BYTES:
- return reader.bytes();
- case reflection_info_1.ScalarType.UINT32:
- return reader.uint32();
- case reflection_info_1.ScalarType.SFIXED32:
- return reader.sfixed32();
- case reflection_info_1.ScalarType.SFIXED64:
- return reflection_long_convert_1.reflectionLongConvert(reader.sfixed64(), longType);
- case reflection_info_1.ScalarType.SINT32:
- return reader.sint32();
- case reflection_info_1.ScalarType.SINT64:
- return reflection_long_convert_1.reflectionLongConvert(reader.sint64(), longType);
+ return textValue;
+}
+
+;// CONCATENATED MODULE: ./node_modules/fast-xml-parser/src/ignoreAttributes.js
+function getIgnoreAttributesFn(ignoreAttributes) {
+ if (typeof ignoreAttributes === 'function') {
+ return ignoreAttributes
+ }
+ if (Array.isArray(ignoreAttributes)) {
+ return (attrName) => {
+ for (const pattern of ignoreAttributes) {
+ if (typeof pattern === 'string' && attrName === pattern) {
+ return true
+ }
+ if (pattern instanceof RegExp && pattern.test(attrName)) {
+ return true
+ }
+ }
}
}
+ return () => false
}
-exports.ReflectionBinaryReader = ReflectionBinaryReader;
+;// CONCATENATED MODULE: ./node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js
+//parse Empty Node as self closing node
-/***/ }),
-/***/ 6907:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+const defaultOptions = {
+ attributeNamePrefix: '@_',
+ attributesGroupName: false,
+ textNodeName: '#text',
+ ignoreAttributes: true,
+ cdataPropName: false,
+ format: false,
+ indentBy: ' ',
+ suppressEmptyNode: false,
+ suppressUnpairedNode: true,
+ suppressBooleanAttributes: true,
+ tagValueProcessor: function(key, a) {
+ return a;
+ },
+ attributeValueProcessor: function(attrName, a) {
+ return a;
+ },
+ preserveOrder: false,
+ commentPropName: false,
+ unpairedTags: [],
+ entities: [
+ { regex: new RegExp("&", "g"), val: "&" },//it must be on top
+ { regex: new RegExp(">", "g"), val: ">" },
+ { regex: new RegExp("<", "g"), val: "<" },
+ { regex: new RegExp("\'", "g"), val: "'" },
+ { regex: new RegExp("\"", "g"), val: """ }
+ ],
+ processEntities: true,
+ stopNodes: [],
+ // transformTagName: false,
+ // transformAttributeName: false,
+ oneListGroup: false
+};
+
+function Builder(options) {
+ this.options = Object.assign({}, defaultOptions, options);
+ if (this.options.ignoreAttributes === true || this.options.attributesGroupName) {
+ this.isAttribute = function(/*a*/) {
+ return false;
+ };
+ } else {
+ this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes)
+ this.attrPrefixLen = this.options.attributeNamePrefix.length;
+ this.isAttribute = isAttribute;
+ }
+
+ this.processTextOrObjNode = processTextOrObjNode
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.ReflectionBinaryWriter = void 0;
-const binary_format_contract_1 = __nccwpck_require__(4816);
-const reflection_info_1 = __nccwpck_require__(7910);
-const assert_1 = __nccwpck_require__(8602);
-const pb_long_1 = __nccwpck_require__(1753);
-/**
- * Writes proto3 messages in binary format using reflection information.
- *
- * https://developers.google.com/protocol-buffers/docs/encoding
- */
-class ReflectionBinaryWriter {
- constructor(info) {
- this.info = info;
+ if (this.options.format) {
+ this.indentate = indentate;
+ this.tagEndChar = '>\n';
+ this.newLine = '\n';
+ } else {
+ this.indentate = function() {
+ return '';
+ };
+ this.tagEndChar = '>';
+ this.newLine = '';
+ }
+}
+
+Builder.prototype.build = function(jObj) {
+ if(this.options.preserveOrder){
+ return toXml(jObj, this.options);
+ }else {
+ if(Array.isArray(jObj) && this.options.arrayNodeName && this.options.arrayNodeName.length > 1){
+ jObj = {
+ [this.options.arrayNodeName] : jObj
+ }
}
- prepare() {
- if (!this.fields) {
- const fieldsInput = this.info.fields ? this.info.fields.concat() : [];
- this.fields = fieldsInput.sort((a, b) => a.no - b.no);
+ return this.j2x(jObj, 0, []).val;
+ }
+};
+
+Builder.prototype.j2x = function(jObj, level, ajPath) {
+ let attrStr = '';
+ let val = '';
+ const jPath = ajPath.join('.')
+ for (let key in jObj) {
+ if(!Object.prototype.hasOwnProperty.call(jObj, key)) continue;
+ if (typeof jObj[key] === 'undefined') {
+ // supress undefined node only if it is not an attribute
+ if (this.isAttribute(key)) {
+ val += '';
+ }
+ } else if (jObj[key] === null) {
+ // null attribute should be ignored by the attribute list, but should not cause the tag closing
+ if (this.isAttribute(key)) {
+ val += '';
+ } else if (key === this.options.cdataPropName) {
+ val += '';
+ } else if (key[0] === '?') {
+ val += this.indentate(level) + '<' + key + '?' + this.tagEndChar;
+ } else {
+ val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;
+ }
+ // val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;
+ } else if (jObj[key] instanceof Date) {
+ val += this.buildTextValNode(jObj[key], key, '', level);
+ } else if (typeof jObj[key] !== 'object') {
+ //premitive type
+ const attr = this.isAttribute(key);
+ if (attr && !this.ignoreAttributesFn(attr, jPath)) {
+ attrStr += this.buildAttrPairStr(attr, '' + jObj[key]);
+ } else if (!attr) {
+ //tag value
+ if (key === this.options.textNodeName) {
+ let newval = this.options.tagValueProcessor(key, '' + jObj[key]);
+ val += this.replaceEntitiesValue(newval);
+ } else {
+ val += this.buildTextValNode(jObj[key], key, '', level);
}
- }
- /**
- * Writes the message to binary format.
- */
- write(message, writer, options) {
- this.prepare();
- for (const field of this.fields) {
- let value, // this will be our field value, whether it is member of a oneof or not
- emitDefault, // whether we emit the default value (only true for oneof members)
- repeated = field.repeat, localName = field.localName;
- // handle oneof ADT
- if (field.oneof) {
- const group = message[field.oneof];
- if (group.oneofKind !== localName)
- continue; // if field is not selected, skip
- value = group[localName];
- emitDefault = true;
- }
- else {
- value = message[localName];
- emitDefault = false;
+ }
+ } else if (Array.isArray(jObj[key])) {
+ //repeated nodes
+ const arrLen = jObj[key].length;
+ let listTagVal = "";
+ let listTagAttr = "";
+ for (let j = 0; j < arrLen; j++) {
+ const item = jObj[key][j];
+ if (typeof item === 'undefined') {
+ // supress undefined node
+ } else if (item === null) {
+ if(key[0] === "?") val += this.indentate(level) + '<' + key + '?' + this.tagEndChar;
+ else val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;
+ // val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;
+ } else if (typeof item === 'object') {
+ if(this.options.oneListGroup){
+ const result = this.j2x(item, level + 1, ajPath.concat(key));
+ listTagVal += result.val;
+ if (this.options.attributesGroupName && item.hasOwnProperty(this.options.attributesGroupName)) {
+ listTagAttr += result.attrStr
}
- // we have handled oneof above. we just have to honor `emitDefault`.
- switch (field.kind) {
- case "scalar":
- case "enum":
- let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T;
- if (repeated) {
- assert_1.assert(Array.isArray(value));
- if (repeated == reflection_info_1.RepeatType.PACKED)
- this.packed(writer, T, field.no, value);
- else
- for (const item of value)
- this.scalar(writer, T, field.no, item, true);
- }
- else if (value === undefined)
- assert_1.assert(field.opt);
- else
- this.scalar(writer, T, field.no, value, emitDefault || field.opt);
- break;
- case "message":
- if (repeated) {
- assert_1.assert(Array.isArray(value));
- for (const item of value)
- this.message(writer, options, field.T(), field.no, item);
- }
- else {
- this.message(writer, options, field.T(), field.no, value);
- }
- break;
- case "map":
- assert_1.assert(typeof value == 'object' && value !== null);
- for (const [key, val] of Object.entries(value))
- this.mapEntry(writer, options, field, key, val);
- break;
- }
- }
- let u = options.writeUnknownFields;
- if (u !== false)
- (u === true ? binary_format_contract_1.UnknownFieldHandler.onWrite : u)(this.info.typeName, message, writer);
- }
- mapEntry(writer, options, field, key, value) {
- writer.tag(field.no, binary_format_contract_1.WireType.LengthDelimited);
- writer.fork();
- // javascript only allows number or string for object properties
- // we convert from our representation to the protobuf type
- let keyValue = key;
- switch (field.K) {
- case reflection_info_1.ScalarType.INT32:
- case reflection_info_1.ScalarType.FIXED32:
- case reflection_info_1.ScalarType.UINT32:
- case reflection_info_1.ScalarType.SFIXED32:
- case reflection_info_1.ScalarType.SINT32:
- keyValue = Number.parseInt(key);
- break;
- case reflection_info_1.ScalarType.BOOL:
- assert_1.assert(key == 'true' || key == 'false');
- keyValue = key == 'true';
- break;
+ }else{
+ listTagVal += this.processTextOrObjNode(item, key, level, ajPath)
+ }
+ } else {
+ if (this.options.oneListGroup) {
+ let textValue = this.options.tagValueProcessor(key, item);
+ textValue = this.replaceEntitiesValue(textValue);
+ listTagVal += textValue;
+ } else {
+ listTagVal += this.buildTextValNode(item, key, '', level);
+ }
}
- // write key, expecting key field number = 1
- this.scalar(writer, field.K, 1, keyValue, true);
- // write value, expecting value field number = 2
- switch (field.V.kind) {
- case 'scalar':
- this.scalar(writer, field.V.T, 2, value, true);
- break;
- case 'enum':
- this.scalar(writer, reflection_info_1.ScalarType.INT32, 2, value, true);
- break;
- case 'message':
- this.message(writer, options, field.V.T(), 2, value);
- break;
+ }
+ if(this.options.oneListGroup){
+ listTagVal = this.buildObjectNode(listTagVal, key, listTagAttr, level);
+ }
+ val += listTagVal;
+ } else {
+ //nested node
+ if (this.options.attributesGroupName && key === this.options.attributesGroupName) {
+ const Ks = Object.keys(jObj[key]);
+ const L = Ks.length;
+ for (let j = 0; j < L; j++) {
+ attrStr += this.buildAttrPairStr(Ks[j], '' + jObj[key][Ks[j]]);
}
- writer.join();
- }
- message(writer, options, handler, fieldNo, value) {
- if (value === undefined)
- return;
- handler.internalBinaryWrite(value, writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited).fork(), options);
- writer.join();
+ } else {
+ val += this.processTextOrObjNode(jObj[key], key, level, ajPath)
+ }
}
- /**
- * Write a single scalar value.
- */
- scalar(writer, type, fieldNo, value, emitDefault) {
- let [wireType, method, isDefault] = this.scalarInfo(type, value);
- if (!isDefault || emitDefault) {
- writer.tag(fieldNo, wireType);
- writer[method](value);
- }
+ }
+ return {attrStr: attrStr, val: val};
+};
+
+Builder.prototype.buildAttrPairStr = function(attrName, val){
+ val = this.options.attributeValueProcessor(attrName, '' + val);
+ val = this.replaceEntitiesValue(val);
+ if (this.options.suppressBooleanAttributes && val === "true") {
+ return ' ' + attrName;
+ } else return ' ' + attrName + '="' + val + '"';
+}
+
+function processTextOrObjNode (object, key, level, ajPath) {
+ const result = this.j2x(object, level + 1, ajPath.concat(key));
+ if (object[this.options.textNodeName] !== undefined && Object.keys(object).length === 1) {
+ return this.buildTextValNode(object[this.options.textNodeName], key, result.attrStr, level);
+ } else {
+ return this.buildObjectNode(result.val, key, result.attrStr, level);
+ }
+}
+
+Builder.prototype.buildObjectNode = function(val, key, attrStr, level) {
+ if(val === ""){
+ if(key[0] === "?") return this.indentate(level) + '<' + key + attrStr+ '?' + this.tagEndChar;
+ else {
+ return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar;
}
- /**
- * Write an array of scalar values in packed format.
- */
- packed(writer, type, fieldNo, value) {
- if (!value.length)
- return;
- assert_1.assert(type !== reflection_info_1.ScalarType.BYTES && type !== reflection_info_1.ScalarType.STRING);
- // write tag
- writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited);
- // begin length-delimited
- writer.fork();
- // write values without tags
- let [, method,] = this.scalarInfo(type);
- for (let i = 0; i < value.length; i++)
- writer[method](value[i]);
- // end length delimited
- writer.join();
+ }else{
+
+ let tagEndExp = '' + key + this.tagEndChar;
+ let piClosingChar = "";
+
+ if(key[0] === "?") {
+ piClosingChar = "?";
+ tagEndExp = "";
}
- /**
- * Get information for writing a scalar value.
- *
- * Returns tuple:
- * [0]: appropriate WireType
- * [1]: name of the appropriate method of IBinaryWriter
- * [2]: whether the given value is a default value
- *
- * If argument `value` is omitted, [2] is always false.
- */
- scalarInfo(type, value) {
- let t = binary_format_contract_1.WireType.Varint;
- let m;
- let i = value === undefined;
- let d = value === 0;
- switch (type) {
- case reflection_info_1.ScalarType.INT32:
- m = "int32";
- break;
- case reflection_info_1.ScalarType.STRING:
- d = i || !value.length;
- t = binary_format_contract_1.WireType.LengthDelimited;
- m = "string";
- break;
- case reflection_info_1.ScalarType.BOOL:
- d = value === false;
- m = "bool";
- break;
- case reflection_info_1.ScalarType.UINT32:
- m = "uint32";
- break;
- case reflection_info_1.ScalarType.DOUBLE:
- t = binary_format_contract_1.WireType.Bit64;
- m = "double";
- break;
- case reflection_info_1.ScalarType.FLOAT:
- t = binary_format_contract_1.WireType.Bit32;
- m = "float";
- break;
- case reflection_info_1.ScalarType.INT64:
- d = i || pb_long_1.PbLong.from(value).isZero();
- m = "int64";
- break;
- case reflection_info_1.ScalarType.UINT64:
- d = i || pb_long_1.PbULong.from(value).isZero();
- m = "uint64";
- break;
- case reflection_info_1.ScalarType.FIXED64:
- d = i || pb_long_1.PbULong.from(value).isZero();
- t = binary_format_contract_1.WireType.Bit64;
- m = "fixed64";
- break;
- case reflection_info_1.ScalarType.BYTES:
- d = i || !value.byteLength;
- t = binary_format_contract_1.WireType.LengthDelimited;
- m = "bytes";
- break;
- case reflection_info_1.ScalarType.FIXED32:
- t = binary_format_contract_1.WireType.Bit32;
- m = "fixed32";
- break;
- case reflection_info_1.ScalarType.SFIXED32:
- t = binary_format_contract_1.WireType.Bit32;
- m = "sfixed32";
- break;
- case reflection_info_1.ScalarType.SFIXED64:
- d = i || pb_long_1.PbLong.from(value).isZero();
- t = binary_format_contract_1.WireType.Bit64;
- m = "sfixed64";
- break;
- case reflection_info_1.ScalarType.SINT32:
- m = "sint32";
- break;
- case reflection_info_1.ScalarType.SINT64:
- d = i || pb_long_1.PbLong.from(value).isZero();
- m = "sint64";
- break;
- }
- return [t, m, i || d];
+
+ // attrStr is an empty string in case the attribute came as undefined or null
+ if ((attrStr || attrStr === '') && val.indexOf('<') === -1) {
+ return ( this.indentate(level) + '<' + key + attrStr + piClosingChar + '>' + val + tagEndExp );
+ } else if (this.options.commentPropName !== false && key === this.options.commentPropName && piClosingChar.length === 0) {
+ return this.indentate(level) + `` + this.newLine;
+ }else {
+ return (
+ this.indentate(level) + '<' + key + attrStr + piClosingChar + this.tagEndChar +
+ val +
+ this.indentate(level) + tagEndExp );
}
+ }
}
-exports.ReflectionBinaryWriter = ReflectionBinaryWriter;
+Builder.prototype.closeTag = function(key){
+ let closeTag = "";
+ if(this.options.unpairedTags.indexOf(key) !== -1){ //unpaired
+ if(!this.options.suppressUnpairedNode) closeTag = "/"
+ }else if(this.options.suppressEmptyNode){ //empty
+ closeTag = "/";
+ }else{
+ closeTag = `>${key}`
+ }
+ return closeTag;
+}
-/***/ }),
+function buildEmptyObjNode(val, key, attrStr, level) {
+ if (val !== '') {
+ return this.buildObjectNode(val, key, attrStr, level);
+ } else {
+ if(key[0] === "?") return this.indentate(level) + '<' + key + attrStr+ '?' + this.tagEndChar;
+ else {
+ return this.indentate(level) + '<' + key + attrStr + '/' + this.tagEndChar;
+ // return this.buildTagStr(level,key, attrStr);
+ }
+ }
+}
-/***/ 9946:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+Builder.prototype.buildTextValNode = function(val, key, attrStr, level) {
+ if (this.options.cdataPropName !== false && key === this.options.cdataPropName) {
+ return this.indentate(level) + `` + this.newLine;
+ }else if (this.options.commentPropName !== false && key === this.options.commentPropName) {
+ return this.indentate(level) + `` + this.newLine;
+ }else if(key[0] === "?") {//PI tag
+ return this.indentate(level) + '<' + key + attrStr+ '?' + this.tagEndChar;
+ }else{
+ let textValue = this.options.tagValueProcessor(key, val);
+ textValue = this.replaceEntitiesValue(textValue);
+
+ if( textValue === ''){
+ return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar;
+ }else{
+ return this.indentate(level) + '<' + key + attrStr + '>' +
+ textValue +
+ '' + key + this.tagEndChar;
+ }
+ }
+}
+Builder.prototype.replaceEntitiesValue = function(textValue){
+ if(textValue && textValue.length > 0 && this.options.processEntities){
+ for (let i=0; i {
+;// CONCATENATED MODULE: ./node_modules/fast-xml-parser/src/util.js
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.reflectionCreate = void 0;
-const reflection_scalar_default_1 = __nccwpck_require__(9526);
-const message_type_contract_1 = __nccwpck_require__(3785);
-/**
- * Creates an instance of the generic message, using the field
- * information.
- */
-function reflectionCreate(type) {
- /**
- * This ternary can be removed in the next major version.
- * The `Object.create()` code path utilizes a new `messagePrototype`
- * property on the `IMessageType` which has this same `MESSAGE_TYPE`
- * non-enumerable property on it. Doing it this way means that we only
- * pay the cost of `Object.defineProperty()` once per `IMessageType`
- * class of once per "instance". The falsy code path is only provided
- * for backwards compatibility in cases where the runtime library is
- * updated without also updating the generated code.
- */
- const msg = type.messagePrototype
- ? Object.create(type.messagePrototype)
- : Object.defineProperty({}, message_type_contract_1.MESSAGE_TYPE, { value: type });
- for (let field of type.fields) {
- let name = field.localName;
- if (field.opt)
- continue;
- if (field.oneof)
- msg[field.oneof] = { oneofKind: undefined };
- else if (field.repeat)
- msg[name] = [];
- else
- switch (field.kind) {
- case "scalar":
- msg[name] = reflection_scalar_default_1.reflectionScalarDefault(field.T, field.L);
- break;
- case "enum":
- // we require 0 to be default value for all enums
- msg[name] = 0;
- break;
- case "map":
- msg[name] = {};
- break;
- }
+const nameStartChar = ':A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD';
+const nameChar = nameStartChar + '\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040';
+const nameRegexp = '[' + nameStartChar + '][' + nameChar + ']*';
+const regexName = new RegExp('^' + nameRegexp + '$');
+
+function getAllMatches(string, regex) {
+ const matches = [];
+ let match = regex.exec(string);
+ while (match) {
+ const allmatches = [];
+ allmatches.startIndex = regex.lastIndex - match[0].length;
+ const len = match.length;
+ for (let index = 0; index < len; index++) {
+ allmatches.push(match[index]);
}
- return msg;
+ matches.push(allmatches);
+ match = regex.exec(string);
+ }
+ return matches;
}
-exports.reflectionCreate = reflectionCreate;
-
-/***/ }),
+const isName = function(string) {
+ const match = regexName.exec(string);
+ return !(match === null || typeof match === 'undefined');
+}
-/***/ 4827:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+function isExist(v) {
+ return typeof v !== 'undefined';
+}
+function isEmptyObject(obj) {
+ return Object.keys(obj).length === 0;
+}
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.reflectionEquals = void 0;
-const reflection_info_1 = __nccwpck_require__(7910);
/**
- * Determines whether two message of the same type have the same field values.
- * Checks for deep equality, traversing repeated fields, oneof groups, maps
- * and messages recursively.
- * Will also return true if both messages are `undefined`.
+ * Copy all the properties of a into b.
+ * @param {*} target
+ * @param {*} a
*/
-function reflectionEquals(info, a, b) {
- if (a === b)
- return true;
- if (!a || !b)
- return false;
- for (let field of info.fields) {
- let localName = field.localName;
- let val_a = field.oneof ? a[field.oneof][localName] : a[localName];
- let val_b = field.oneof ? b[field.oneof][localName] : b[localName];
- switch (field.kind) {
- case "enum":
- case "scalar":
- let t = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T;
- if (!(field.repeat
- ? repeatedPrimitiveEq(t, val_a, val_b)
- : primitiveEq(t, val_a, val_b)))
- return false;
- break;
- case "map":
- if (!(field.V.kind == "message"
- ? repeatedMsgEq(field.V.T(), objectValues(val_a), objectValues(val_b))
- : repeatedPrimitiveEq(field.V.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.V.T, objectValues(val_a), objectValues(val_b))))
- return false;
- break;
- case "message":
- let T = field.T();
- if (!(field.repeat
- ? repeatedMsgEq(T, val_a, val_b)
- : T.equals(val_a, val_b)))
- return false;
- break;
- }
+function merge(target, a, arrayMode) {
+ if (a) {
+ const keys = Object.keys(a); // will return an array of own properties
+ const len = keys.length; //don't make it inline
+ for (let i = 0; i < len; i++) {
+ if (arrayMode === 'strict') {
+ target[keys[i]] = [ a[keys[i]] ];
+ } else {
+ target[keys[i]] = a[keys[i]];
+ }
}
- return true;
-}
-exports.reflectionEquals = reflectionEquals;
-const objectValues = Object.values;
-function primitiveEq(type, a, b) {
- if (a === b)
- return true;
- if (type !== reflection_info_1.ScalarType.BYTES)
- return false;
- let ba = a;
- let bb = b;
- if (ba.length !== bb.length)
- return false;
- for (let i = 0; i < ba.length; i++)
- if (ba[i] != bb[i])
- return false;
- return true;
-}
-function repeatedPrimitiveEq(type, a, b) {
- if (a.length !== b.length)
- return false;
- for (let i = 0; i < a.length; i++)
- if (!primitiveEq(type, a[i], b[i]))
- return false;
- return true;
+ }
}
-function repeatedMsgEq(type, a, b) {
- if (a.length !== b.length)
- return false;
- for (let i = 0; i < a.length; i++)
- if (!type.equals(a[i], b[i]))
- return false;
- return true;
+/* exports.merge =function (b,a){
+ return Object.assign(b,a);
+} */
+
+function getValue(v) {
+ if (exports.isExist(v)) {
+ return v;
+ } else {
+ return '';
+ }
}
+// const fakeCall = function(a) {return a;};
+// const fakeCallNoReturn = function() {};
+;// CONCATENATED MODULE: ./node_modules/fast-xml-parser/src/validator.js
-/***/ }),
-/***/ 7910:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.readMessageOption = exports.readFieldOption = exports.readFieldOptions = exports.normalizeFieldInfo = exports.RepeatType = exports.LongType = exports.ScalarType = void 0;
-const lower_camel_case_1 = __nccwpck_require__(4073);
-/**
- * Scalar value types. This is a subset of field types declared by protobuf
- * enum google.protobuf.FieldDescriptorProto.Type The types GROUP and MESSAGE
- * are omitted, but the numerical values are identical.
- */
-var ScalarType;
-(function (ScalarType) {
- // 0 is reserved for errors.
- // Order is weird for historical reasons.
- ScalarType[ScalarType["DOUBLE"] = 1] = "DOUBLE";
- ScalarType[ScalarType["FLOAT"] = 2] = "FLOAT";
- // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if
- // negative values are likely.
- ScalarType[ScalarType["INT64"] = 3] = "INT64";
- ScalarType[ScalarType["UINT64"] = 4] = "UINT64";
- // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if
- // negative values are likely.
- ScalarType[ScalarType["INT32"] = 5] = "INT32";
- ScalarType[ScalarType["FIXED64"] = 6] = "FIXED64";
- ScalarType[ScalarType["FIXED32"] = 7] = "FIXED32";
- ScalarType[ScalarType["BOOL"] = 8] = "BOOL";
- ScalarType[ScalarType["STRING"] = 9] = "STRING";
- // Tag-delimited aggregate.
- // Group type is deprecated and not supported in proto3. However, Proto3
- // implementations should still be able to parse the group wire format and
- // treat group fields as unknown fields.
- // TYPE_GROUP = 10,
- // TYPE_MESSAGE = 11, // Length-delimited aggregate.
- // New in version 2.
- ScalarType[ScalarType["BYTES"] = 12] = "BYTES";
- ScalarType[ScalarType["UINT32"] = 13] = "UINT32";
- // TYPE_ENUM = 14,
- ScalarType[ScalarType["SFIXED32"] = 15] = "SFIXED32";
- ScalarType[ScalarType["SFIXED64"] = 16] = "SFIXED64";
- ScalarType[ScalarType["SINT32"] = 17] = "SINT32";
- ScalarType[ScalarType["SINT64"] = 18] = "SINT64";
-})(ScalarType = exports.ScalarType || (exports.ScalarType = {}));
-/**
- * JavaScript representation of 64 bit integral types. Equivalent to the
- * field option "jstype".
- *
- * By default, protobuf-ts represents 64 bit types as `bigint`.
- *
- * You can change the default behaviour by enabling the plugin parameter
- * `long_type_string`, which will represent 64 bit types as `string`.
- *
- * Alternatively, you can change the behaviour for individual fields
- * with the field option "jstype":
- *
- * ```protobuf
- * uint64 my_field = 1 [jstype = JS_STRING];
- * uint64 other_field = 2 [jstype = JS_NUMBER];
- * ```
- */
-var LongType;
-(function (LongType) {
- /**
- * Use JavaScript `bigint`.
- *
- * Field option `[jstype = JS_NORMAL]`.
- */
- LongType[LongType["BIGINT"] = 0] = "BIGINT";
- /**
- * Use JavaScript `string`.
- *
- * Field option `[jstype = JS_STRING]`.
- */
- LongType[LongType["STRING"] = 1] = "STRING";
- /**
- * Use JavaScript `number`.
- *
- * Large values will loose precision.
- *
- * Field option `[jstype = JS_NUMBER]`.
- */
- LongType[LongType["NUMBER"] = 2] = "NUMBER";
-})(LongType = exports.LongType || (exports.LongType = {}));
-/**
- * Protobuf 2.1.0 introduced packed repeated fields.
- * Setting the field option `[packed = true]` enables packing.
- *
- * In proto3, all repeated fields are packed by default.
- * Setting the field option `[packed = false]` disables packing.
- *
- * Packed repeated fields are encoded with a single tag,
- * then a length-delimiter, then the element values.
- *
- * Unpacked repeated fields are encoded with a tag and
- * value for each element.
- *
- * `bytes` and `string` cannot be packed.
- */
-var RepeatType;
-(function (RepeatType) {
- /**
- * The field is not repeated.
- */
- RepeatType[RepeatType["NO"] = 0] = "NO";
- /**
- * The field is repeated and should be packed.
- * Invalid for `bytes` and `string`, they cannot be packed.
- */
- RepeatType[RepeatType["PACKED"] = 1] = "PACKED";
- /**
- * The field is repeated but should not be packed.
- * The only valid repeat type for repeated `bytes` and `string`.
- */
- RepeatType[RepeatType["UNPACKED"] = 2] = "UNPACKED";
-})(RepeatType = exports.RepeatType || (exports.RepeatType = {}));
-/**
- * Turns PartialFieldInfo into FieldInfo.
- */
-function normalizeFieldInfo(field) {
- var _a, _b, _c, _d;
- field.localName = (_a = field.localName) !== null && _a !== void 0 ? _a : lower_camel_case_1.lowerCamelCase(field.name);
- field.jsonName = (_b = field.jsonName) !== null && _b !== void 0 ? _b : lower_camel_case_1.lowerCamelCase(field.name);
- field.repeat = (_c = field.repeat) !== null && _c !== void 0 ? _c : RepeatType.NO;
- field.opt = (_d = field.opt) !== null && _d !== void 0 ? _d : (field.repeat ? false : field.oneof ? false : field.kind == "message");
- return field;
+const validator_defaultOptions = {
+ allowBooleanAttributes: false, //A tag can have attributes without any value
+ unpairedTags: []
+};
+
+//const tagsPattern = new RegExp("<\\/?([\\w:\\-_\.]+)\\s*\/?>","g");
+function validate(xmlData, options) {
+ options = Object.assign({}, validator_defaultOptions, options);
+
+ //xmlData = xmlData.replace(/(\r\n|\n|\r)/gm,"");//make it single line
+ //xmlData = xmlData.replace(/(^\s*<\?xml.*?\?>)/g,"");//Remove XML starting tag
+ //xmlData = xmlData.replace(/()/g,"");//Remove DOCTYPE
+ const tags = [];
+ let tagFound = false;
+
+ //indicates that the root tag has been closed (aka. depth 0 has been reached)
+ let reachedRoot = false;
+
+ if (xmlData[0] === '\ufeff') {
+ // check for byte order mark (BOM)
+ xmlData = xmlData.substr(1);
+ }
+
+ for (let i = 0; i < xmlData.length; i++) {
+
+ if (xmlData[i] === '<' && xmlData[i+1] === '?') {
+ i+=2;
+ i = readPI(xmlData,i);
+ if (i.err) return i;
+ }else if (xmlData[i] === '<') {
+ //starting of tag
+ //read until you reach to '>' avoiding any '>' in attribute value
+ let tagStartPos = i;
+ i++;
+
+ if (xmlData[i] === '!') {
+ i = readCommentAndCDATA(xmlData, i);
+ continue;
+ } else {
+ let closingTag = false;
+ if (xmlData[i] === '/') {
+ //closing tag
+ closingTag = true;
+ i++;
+ }
+ //read tagname
+ let tagName = '';
+ for (; i < xmlData.length &&
+ xmlData[i] !== '>' &&
+ xmlData[i] !== ' ' &&
+ xmlData[i] !== '\t' &&
+ xmlData[i] !== '\n' &&
+ xmlData[i] !== '\r'; i++
+ ) {
+ tagName += xmlData[i];
+ }
+ tagName = tagName.trim();
+ //console.log(tagName);
+
+ if (tagName[tagName.length - 1] === '/') {
+ //self closing tag without attributes
+ tagName = tagName.substring(0, tagName.length - 1);
+ //continue;
+ i--;
+ }
+ if (!validateTagName(tagName)) {
+ let msg;
+ if (tagName.trim().length === 0) {
+ msg = "Invalid space after '<'.";
+ } else {
+ msg = "Tag '"+tagName+"' is an invalid name.";
+ }
+ return getErrorObject('InvalidTag', msg, getLineNumberForPosition(xmlData, i));
+ }
+
+ const result = readAttributeStr(xmlData, i);
+ if (result === false) {
+ return getErrorObject('InvalidAttr', "Attributes for '"+tagName+"' have open quote.", getLineNumberForPosition(xmlData, i));
+ }
+ let attrStr = result.value;
+ i = result.index;
+
+ if (attrStr[attrStr.length - 1] === '/') {
+ //self closing tag
+ const attrStrStart = i - attrStr.length;
+ attrStr = attrStr.substring(0, attrStr.length - 1);
+ const isValid = validateAttributeString(attrStr, options);
+ if (isValid === true) {
+ tagFound = true;
+ //continue; //text may presents after self closing tag
+ } else {
+ //the result from the nested function returns the position of the error within the attribute
+ //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute
+ //this gives us the absolute index in the entire xml, which we can use to find the line at last
+ return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid.err.line));
+ }
+ } else if (closingTag) {
+ if (!result.tagClosed) {
+ return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' doesn't have proper closing.", getLineNumberForPosition(xmlData, i));
+ } else if (attrStr.trim().length > 0) {
+ return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' can't have attributes or invalid starting.", getLineNumberForPosition(xmlData, tagStartPos));
+ } else if (tags.length === 0) {
+ return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' has not been opened.", getLineNumberForPosition(xmlData, tagStartPos));
+ } else {
+ const otg = tags.pop();
+ if (tagName !== otg.tagName) {
+ let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos);
+ return getErrorObject('InvalidTag',
+ "Expected closing tag '"+otg.tagName+"' (opened in line "+openPos.line+", col "+openPos.col+") instead of closing tag '"+tagName+"'.",
+ getLineNumberForPosition(xmlData, tagStartPos));
+ }
+
+ //when there are no more tags, we reached the root level.
+ if (tags.length == 0) {
+ reachedRoot = true;
+ }
+ }
+ } else {
+ const isValid = validateAttributeString(attrStr, options);
+ if (isValid !== true) {
+ //the result from the nested function returns the position of the error within the attribute
+ //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute
+ //this gives us the absolute index in the entire xml, which we can use to find the line at last
+ return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, i - attrStr.length + isValid.err.line));
+ }
+
+ //if the root level has been reached before ...
+ if (reachedRoot === true) {
+ return getErrorObject('InvalidXml', 'Multiple possible root nodes found.', getLineNumberForPosition(xmlData, i));
+ } else if(options.unpairedTags.indexOf(tagName) !== -1){
+ //don't push into stack
+ } else {
+ tags.push({tagName, tagStartPos});
+ }
+ tagFound = true;
+ }
+
+ //skip tag text value
+ //It may include comments and CDATA value
+ for (i++; i < xmlData.length; i++) {
+ if (xmlData[i] === '<') {
+ if (xmlData[i + 1] === '!') {
+ //comment or CADATA
+ i++;
+ i = readCommentAndCDATA(xmlData, i);
+ continue;
+ } else if (xmlData[i+1] === '?') {
+ i = readPI(xmlData, ++i);
+ if (i.err) return i;
+ } else{
+ break;
+ }
+ } else if (xmlData[i] === '&') {
+ const afterAmp = validateAmpersand(xmlData, i);
+ if (afterAmp == -1)
+ return getErrorObject('InvalidChar', "char '&' is not expected.", getLineNumberForPosition(xmlData, i));
+ i = afterAmp;
+ }else{
+ if (reachedRoot === true && !isWhiteSpace(xmlData[i])) {
+ return getErrorObject('InvalidXml', "Extra text at the end", getLineNumberForPosition(xmlData, i));
+ }
+ }
+ } //end of reading tag text value
+ if (xmlData[i] === '<') {
+ i--;
+ }
+ }
+ } else {
+ if ( isWhiteSpace(xmlData[i])) {
+ continue;
+ }
+ return getErrorObject('InvalidChar', "char '"+xmlData[i]+"' is not expected.", getLineNumberForPosition(xmlData, i));
+ }
+ }
+
+ if (!tagFound) {
+ return getErrorObject('InvalidXml', 'Start tag expected.', 1);
+ }else if (tags.length == 1) {
+ return getErrorObject('InvalidTag', "Unclosed tag '"+tags[0].tagName+"'.", getLineNumberForPosition(xmlData, tags[0].tagStartPos));
+ }else if (tags.length > 0) {
+ return getErrorObject('InvalidXml', "Invalid '"+
+ JSON.stringify(tags.map(t => t.tagName), null, 4).replace(/\r?\n/g, '')+
+ "' found.", {line: 1, col: 1});
+ }
+
+ return true;
+};
+
+function isWhiteSpace(char){
+ return char === ' ' || char === '\t' || char === '\n' || char === '\r';
}
-exports.normalizeFieldInfo = normalizeFieldInfo;
/**
- * Read custom field options from a generated message type.
- *
- * @deprecated use readFieldOption()
+ * Read Processing insstructions and skip
+ * @param {*} xmlData
+ * @param {*} i
*/
-function readFieldOptions(messageType, fieldName, extensionName, extensionType) {
- var _a;
- const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options;
- return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : undefined;
+function readPI(xmlData, i) {
+ const start = i;
+ for (; i < xmlData.length; i++) {
+ if (xmlData[i] == '?' || xmlData[i] == ' ') {
+ //tagname
+ const tagname = xmlData.substr(start, i - start);
+ if (i > 5 && tagname === 'xml') {
+ return getErrorObject('InvalidXml', 'XML declaration allowed only at the start of the document.', getLineNumberForPosition(xmlData, i));
+ } else if (xmlData[i] == '?' && xmlData[i + 1] == '>') {
+ //check if valid attribut string
+ i++;
+ break;
+ } else {
+ continue;
+ }
+ }
+ }
+ return i;
}
-exports.readFieldOptions = readFieldOptions;
-function readFieldOption(messageType, fieldName, extensionName, extensionType) {
- var _a;
- const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options;
- if (!options) {
- return undefined;
+
+function readCommentAndCDATA(xmlData, i) {
+ if (xmlData.length > i + 5 && xmlData[i + 1] === '-' && xmlData[i + 2] === '-') {
+ //comment
+ for (i += 3; i < xmlData.length; i++) {
+ if (xmlData[i] === '-' && xmlData[i + 1] === '-' && xmlData[i + 2] === '>') {
+ i += 2;
+ break;
+ }
}
- const optionVal = options[extensionName];
- if (optionVal === undefined) {
- return optionVal;
+ } else if (
+ xmlData.length > i + 8 &&
+ xmlData[i + 1] === 'D' &&
+ xmlData[i + 2] === 'O' &&
+ xmlData[i + 3] === 'C' &&
+ xmlData[i + 4] === 'T' &&
+ xmlData[i + 5] === 'Y' &&
+ xmlData[i + 6] === 'P' &&
+ xmlData[i + 7] === 'E'
+ ) {
+ let angleBracketsCount = 1;
+ for (i += 8; i < xmlData.length; i++) {
+ if (xmlData[i] === '<') {
+ angleBracketsCount++;
+ } else if (xmlData[i] === '>') {
+ angleBracketsCount--;
+ if (angleBracketsCount === 0) {
+ break;
+ }
+ }
}
- return extensionType ? extensionType.fromJson(optionVal) : optionVal;
-}
-exports.readFieldOption = readFieldOption;
-function readMessageOption(messageType, extensionName, extensionType) {
- const options = messageType.options;
- const optionVal = options[extensionName];
- if (optionVal === undefined) {
- return optionVal;
+ } else if (
+ xmlData.length > i + 9 &&
+ xmlData[i + 1] === '[' &&
+ xmlData[i + 2] === 'C' &&
+ xmlData[i + 3] === 'D' &&
+ xmlData[i + 4] === 'A' &&
+ xmlData[i + 5] === 'T' &&
+ xmlData[i + 6] === 'A' &&
+ xmlData[i + 7] === '['
+ ) {
+ for (i += 8; i < xmlData.length; i++) {
+ if (xmlData[i] === ']' && xmlData[i + 1] === ']' && xmlData[i + 2] === '>') {
+ i += 2;
+ break;
+ }
}
- return extensionType ? extensionType.fromJson(optionVal) : optionVal;
-}
-exports.readMessageOption = readMessageOption;
+ }
+ return i;
+}
-/***/ }),
+const doubleQuote = '"';
+const singleQuote = "'";
-/***/ 6790:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/**
+ * Keep reading xmlData until '<' is found outside the attribute value.
+ * @param {string} xmlData
+ * @param {number} i
+ */
+function readAttributeStr(xmlData, i) {
+ let attrStr = '';
+ let startChar = '';
+ let tagClosed = false;
+ for (; i < xmlData.length; i++) {
+ if (xmlData[i] === doubleQuote || xmlData[i] === singleQuote) {
+ if (startChar === '') {
+ startChar = xmlData[i];
+ } else if (startChar !== xmlData[i]) {
+ //if vaue is enclosed with double quote then single quotes are allowed inside the value and vice versa
+ } else {
+ startChar = '';
+ }
+ } else if (xmlData[i] === '>') {
+ if (startChar === '') {
+ tagClosed = true;
+ break;
+ }
+ }
+ attrStr += xmlData[i];
+ }
+ if (startChar !== '') {
+ return false;
+ }
+ return {
+ value: attrStr,
+ index: i,
+ tagClosed: tagClosed
+ };
+}
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.ReflectionJsonReader = void 0;
-const json_typings_1 = __nccwpck_require__(9999);
-const base64_1 = __nccwpck_require__(6335);
-const reflection_info_1 = __nccwpck_require__(7910);
-const pb_long_1 = __nccwpck_require__(1753);
-const assert_1 = __nccwpck_require__(8602);
-const reflection_long_convert_1 = __nccwpck_require__(3402);
/**
- * Reads proto3 messages in canonical JSON format using reflection information.
- *
- * https://developers.google.com/protocol-buffers/docs/proto3#json
+ * Select all the attributes whether valid or invalid.
*/
-class ReflectionJsonReader {
- constructor(info) {
- this.info = info;
+const validAttrStrRegxp = new RegExp('(\\s*)([^\\s=]+)(\\s*=)?(\\s*([\'"])(([\\s\\S])*?)\\5)?', 'g');
+
+//attr, ="sd", a="amit's", a="sd"b="saf", ab cd=""
+
+function validateAttributeString(attrStr, options) {
+ //console.log("start:"+attrStr+":end");
+
+ //if(attrStr.trim().length === 0) return true; //empty string
+
+ const matches = getAllMatches(attrStr, validAttrStrRegxp);
+ const attrNames = {};
+
+ for (let i = 0; i < matches.length; i++) {
+ if (matches[i][1].length === 0) {
+ //nospace before attribute name: a="sd"b="saf"
+ return getErrorObject('InvalidAttr', "Attribute '"+matches[i][2]+"' has no space in starting.", getPositionFromMatch(matches[i]))
+ } else if (matches[i][3] !== undefined && matches[i][4] === undefined) {
+ return getErrorObject('InvalidAttr', "Attribute '"+matches[i][2]+"' is without value.", getPositionFromMatch(matches[i]));
+ } else if (matches[i][3] === undefined && !options.allowBooleanAttributes) {
+ //independent attribute: ab
+ return getErrorObject('InvalidAttr', "boolean attribute '"+matches[i][2]+"' is not allowed.", getPositionFromMatch(matches[i]));
}
- prepare() {
- var _a;
- if (this.fMap === undefined) {
- this.fMap = {};
- const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : [];
- for (const field of fieldsInput) {
- this.fMap[field.name] = field;
- this.fMap[field.jsonName] = field;
- this.fMap[field.localName] = field;
- }
- }
+ /* else if(matches[i][6] === undefined){//attribute without value: ab=
+ return { err: { code:"InvalidAttr",msg:"attribute " + matches[i][2] + " has no value assigned."}};
+ } */
+ const attrName = matches[i][2];
+ if (!validateAttrName(attrName)) {
+ return getErrorObject('InvalidAttr', "Attribute '"+attrName+"' is an invalid name.", getPositionFromMatch(matches[i]));
}
- // Cannot parse JSON for #.
- assert(condition, fieldName, jsonValue) {
- if (!condition) {
- let what = json_typings_1.typeofJsonValue(jsonValue);
- if (what == "number" || what == "boolean")
- what = jsonValue.toString();
- throw new Error(`Cannot parse JSON ${what} for ${this.info.typeName}#${fieldName}`);
- }
+ if (!attrNames.hasOwnProperty(attrName)) {
+ //check for duplicate attribute.
+ attrNames[attrName] = 1;
+ } else {
+ return getErrorObject('InvalidAttr', "Attribute '"+attrName+"' is repeated.", getPositionFromMatch(matches[i]));
}
- /**
- * Reads a message from canonical JSON format into the target message.
- *
- * Repeated fields are appended. Map entries are added, overwriting
- * existing keys.
- *
- * If a message field is already present, it will be merged with the
- * new data.
- */
- read(input, message, options) {
- this.prepare();
- const oneofsHandled = [];
- for (const [jsonKey, jsonValue] of Object.entries(input)) {
- const field = this.fMap[jsonKey];
- if (!field) {
- if (!options.ignoreUnknownFields)
- throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${jsonKey}`);
- continue;
- }
- const localName = field.localName;
- // handle oneof ADT
- let target; // this will be the target for the field value, whether it is member of a oneof or not
- if (field.oneof) {
- if (jsonValue === null && (field.kind !== 'enum' || field.T()[0] !== 'google.protobuf.NullValue')) {
- continue;
- }
- // since json objects are unordered by specification, it is not possible to take the last of multiple oneofs
- if (oneofsHandled.includes(field.oneof))
- throw new Error(`Multiple members of the oneof group "${field.oneof}" of ${this.info.typeName} are present in JSON.`);
- oneofsHandled.push(field.oneof);
- target = message[field.oneof] = {
- oneofKind: localName
- };
- }
- else {
- target = message;
- }
- // we have handled oneof above. we just have read the value into `target`.
- if (field.kind == 'map') {
- if (jsonValue === null) {
- continue;
- }
- // check input
- this.assert(json_typings_1.isJsonObject(jsonValue), field.name, jsonValue);
- // our target to put map entries into
- const fieldObj = target[localName];
- // read entries
- for (const [jsonObjKey, jsonObjValue] of Object.entries(jsonValue)) {
- this.assert(jsonObjValue !== null, field.name + " map value", null);
- // read value
- let val;
- switch (field.V.kind) {
- case "message":
- val = field.V.T().internalJsonRead(jsonObjValue, options);
- break;
- case "enum":
- val = this.enum(field.V.T(), jsonObjValue, field.name, options.ignoreUnknownFields);
- if (val === false)
- continue;
- break;
- case "scalar":
- val = this.scalar(jsonObjValue, field.V.T, field.V.L, field.name);
- break;
- }
- this.assert(val !== undefined, field.name + " map value", jsonObjValue);
- // read key
- let key = jsonObjKey;
- if (field.K == reflection_info_1.ScalarType.BOOL)
- key = key == "true" ? true : key == "false" ? false : key;
- key = this.scalar(key, field.K, reflection_info_1.LongType.STRING, field.name).toString();
- fieldObj[key] = val;
- }
- }
- else if (field.repeat) {
- if (jsonValue === null)
- continue;
- // check input
- this.assert(Array.isArray(jsonValue), field.name, jsonValue);
- // our target to put array entries into
- const fieldArr = target[localName];
- // read array entries
- for (const jsonItem of jsonValue) {
- this.assert(jsonItem !== null, field.name, null);
- let val;
- switch (field.kind) {
- case "message":
- val = field.T().internalJsonRead(jsonItem, options);
- break;
- case "enum":
- val = this.enum(field.T(), jsonItem, field.name, options.ignoreUnknownFields);
- if (val === false)
- continue;
- break;
- case "scalar":
- val = this.scalar(jsonItem, field.T, field.L, field.name);
- break;
- }
- this.assert(val !== undefined, field.name, jsonValue);
- fieldArr.push(val);
- }
- }
- else {
- switch (field.kind) {
- case "message":
- if (jsonValue === null && field.T().typeName != 'google.protobuf.Value') {
- this.assert(field.oneof === undefined, field.name + " (oneof member)", null);
- continue;
- }
- target[localName] = field.T().internalJsonRead(jsonValue, options, target[localName]);
- break;
- case "enum":
- if (jsonValue === null)
- continue;
- let val = this.enum(field.T(), jsonValue, field.name, options.ignoreUnknownFields);
- if (val === false)
- continue;
- target[localName] = val;
- break;
- case "scalar":
- if (jsonValue === null)
- continue;
- target[localName] = this.scalar(jsonValue, field.T, field.L, field.name);
- break;
- }
- }
- }
+ }
+
+ return true;
+}
+
+function validateNumberAmpersand(xmlData, i) {
+ let re = /\d/;
+ if (xmlData[i] === 'x') {
+ i++;
+ re = /[\da-fA-F]/;
+ }
+ for (; i < xmlData.length; i++) {
+ if (xmlData[i] === ';')
+ return i;
+ if (!xmlData[i].match(re))
+ break;
+ }
+ return -1;
+}
+
+function validateAmpersand(xmlData, i) {
+ // https://www.w3.org/TR/xml/#dt-charref
+ i++;
+ if (xmlData[i] === ';')
+ return -1;
+ if (xmlData[i] === '#') {
+ i++;
+ return validateNumberAmpersand(xmlData, i);
+ }
+ let count = 0;
+ for (; i < xmlData.length; i++, count++) {
+ if (xmlData[i].match(/\w/) && count < 20)
+ continue;
+ if (xmlData[i] === ';')
+ break;
+ return -1;
+ }
+ return i;
+}
+
+function getErrorObject(code, message, lineNumber) {
+ return {
+ err: {
+ code: code,
+ msg: message,
+ line: lineNumber.line || lineNumber,
+ col: lineNumber.col,
+ },
+ };
+}
+
+function validateAttrName(attrName) {
+ return isName(attrName);
+}
+
+// const startsWithXML = /^xml/i;
+
+function validateTagName(tagname) {
+ return isName(tagname) /* && !tagname.match(startsWithXML) */;
+}
+
+//this function returns the line number for the character at the given index
+function getLineNumberForPosition(xmlData, index) {
+ const lines = xmlData.substring(0, index).split(/\r?\n/);
+ return {
+ line: lines.length,
+
+ // column number is last line's length + 1, because column numbering starts at 1:
+ col: lines[lines.length - 1].length + 1
+ };
+}
+
+//this function returns the position of the first character of match within attrStr
+function getPositionFromMatch(match) {
+ return match.startIndex + match[1].length;
+}
+
+;// CONCATENATED MODULE: ./node_modules/fast-xml-parser/src/fxp.js
+
+
+
+
+
+
+const XMLValidator = {
+ validate: validate
+}
+
+;// CONCATENATED MODULE: ./node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js
+
+const OptionsBuilder_defaultOptions = {
+ preserveOrder: false,
+ attributeNamePrefix: '@_',
+ attributesGroupName: false,
+ textNodeName: '#text',
+ ignoreAttributes: true,
+ removeNSPrefix: false, // remove NS from tag name or attribute name if true
+ allowBooleanAttributes: false, //a tag can have attributes without any value
+ //ignoreRootElement : false,
+ parseTagValue: true,
+ parseAttributeValue: false,
+ trimValues: true, //Trim string values of tag and attributes
+ cdataPropName: false,
+ numberParseOptions: {
+ hex: true,
+ leadingZeros: true,
+ eNotation: true
+ },
+ tagValueProcessor: function(tagName, val) {
+ return val;
+ },
+ attributeValueProcessor: function(attrName, val) {
+ return val;
+ },
+ stopNodes: [], //nested tags will not be parsed even for errors
+ alwaysCreateTextNode: false,
+ isArray: () => false,
+ commentPropName: false,
+ unpairedTags: [],
+ processEntities: true,
+ htmlEntities: false,
+ ignoreDeclaration: false,
+ ignorePiTags: false,
+ transformTagName: false,
+ transformAttributeName: false,
+ updateTag: function(tagName, jPath, attrs){
+ return tagName
+ },
+ // skipEmptyListItem: false
+ captureMetaData: false,
+};
+
+const buildOptions = function(options) {
+ return Object.assign({}, OptionsBuilder_defaultOptions, options);
+};
+
+;// CONCATENATED MODULE: ./node_modules/fast-xml-parser/src/xmlparser/xmlNode.js
+
+
+let METADATA_SYMBOL;
+
+if (typeof Symbol !== "function") {
+ METADATA_SYMBOL = "@@xmlMetadata";
+} else {
+ METADATA_SYMBOL = Symbol("XML Node Metadata");
+}
+
+class XmlNode{
+ constructor(tagname) {
+ this.tagname = tagname;
+ this.child = []; //nested tags, text, cdata, comments in order
+ this[":@"] = {}; //attributes map
+ }
+ add(key,val){
+ // this.child.push( {name : key, val: val, isCdata: isCdata });
+ if(key === "__proto__") key = "#__proto__";
+ this.child.push( {[key]: val });
+ }
+ addChild(node, startIndex) {
+ if(node.tagname === "__proto__") node.tagname = "#__proto__";
+ if(node[":@"] && Object.keys(node[":@"]).length > 0){
+ this.child.push( { [node.tagname]: node.child, [":@"]: node[":@"] });
+ }else{
+ this.child.push( { [node.tagname]: node.child });
}
- /**
- * Returns `false` for unrecognized string representations.
- *
- * google.protobuf.NullValue accepts only JSON `null` (or the old `"NULL_VALUE"`).
- */
- enum(type, json, fieldName, ignoreUnknownFields) {
- if (type[0] == 'google.protobuf.NullValue')
- assert_1.assert(json === null || json === "NULL_VALUE", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type[0]} only accepts null.`);
- if (json === null)
- // we require 0 to be default value for all enums
- return 0;
- switch (typeof json) {
- case "number":
- assert_1.assert(Number.isInteger(json), `Unable to parse field ${this.info.typeName}#${fieldName}, enum can only be integral number, got ${json}.`);
- return json;
- case "string":
- let localEnumName = json;
- if (type[2] && json.substring(0, type[2].length) === type[2])
- // lookup without the shared prefix
- localEnumName = json.substring(type[2].length);
- let enumNumber = type[1][localEnumName];
- if (typeof enumNumber === 'undefined' && ignoreUnknownFields) {
- return false;
- }
- assert_1.assert(typeof enumNumber == "number", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type[0]} has no value for "${json}".`);
- return enumNumber;
- }
- assert_1.assert(false, `Unable to parse field ${this.info.typeName}#${fieldName}, cannot parse enum value from ${typeof json}".`);
+ // if requested, add the startIndex
+ if (startIndex !== undefined) {
+ // Note: for now we just overwrite the metadata. If we had more complex metadata,
+ // we might need to do an object append here: metadata = { ...metadata, startIndex }
+ this.child[this.child.length - 1][METADATA_SYMBOL] = { startIndex };
}
- scalar(json, type, longType, fieldName) {
- let e;
- try {
- switch (type) {
- // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity".
- // Either numbers or strings are accepted. Exponent notation is also accepted.
- case reflection_info_1.ScalarType.DOUBLE:
- case reflection_info_1.ScalarType.FLOAT:
- if (json === null)
- return .0;
- if (json === "NaN")
- return Number.NaN;
- if (json === "Infinity")
- return Number.POSITIVE_INFINITY;
- if (json === "-Infinity")
- return Number.NEGATIVE_INFINITY;
- if (json === "") {
- e = "empty string";
- break;
- }
- if (typeof json == "string" && json.trim().length !== json.length) {
- e = "extra whitespace";
- break;
- }
- if (typeof json != "string" && typeof json != "number") {
- break;
- }
- let float = Number(json);
- if (Number.isNaN(float)) {
- e = "not a number";
- break;
- }
- if (!Number.isFinite(float)) {
- // infinity and -infinity are handled by string representation above, so this is an error
- e = "too large or small";
- break;
- }
- if (type == reflection_info_1.ScalarType.FLOAT)
- assert_1.assertFloat32(float);
- return float;
- // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted.
- case reflection_info_1.ScalarType.INT32:
- case reflection_info_1.ScalarType.FIXED32:
- case reflection_info_1.ScalarType.SFIXED32:
- case reflection_info_1.ScalarType.SINT32:
- case reflection_info_1.ScalarType.UINT32:
- if (json === null)
- return 0;
- let int32;
- if (typeof json == "number")
- int32 = json;
- else if (json === "")
- e = "empty string";
- else if (typeof json == "string") {
- if (json.trim().length !== json.length)
- e = "extra whitespace";
- else
- int32 = Number(json);
- }
- if (int32 === undefined)
- break;
- if (type == reflection_info_1.ScalarType.UINT32)
- assert_1.assertUInt32(int32);
- else
- assert_1.assertInt32(int32);
- return int32;
- // int64, fixed64, uint64: JSON value will be a decimal string. Either numbers or strings are accepted.
- case reflection_info_1.ScalarType.INT64:
- case reflection_info_1.ScalarType.SFIXED64:
- case reflection_info_1.ScalarType.SINT64:
- if (json === null)
- return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType);
- if (typeof json != "number" && typeof json != "string")
- break;
- return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.from(json), longType);
- case reflection_info_1.ScalarType.FIXED64:
- case reflection_info_1.ScalarType.UINT64:
- if (json === null)
- return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType);
- if (typeof json != "number" && typeof json != "string")
- break;
- return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.from(json), longType);
- // bool:
- case reflection_info_1.ScalarType.BOOL:
- if (json === null)
- return false;
- if (typeof json !== "boolean")
- break;
- return json;
- // string:
- case reflection_info_1.ScalarType.STRING:
- if (json === null)
- return "";
- if (typeof json !== "string") {
- e = "extra whitespace";
- break;
+ }
+ /** symbol used for metadata */
+ static getMetaDataSymbol() {
+ return METADATA_SYMBOL;
+ }
+}
+
+;// CONCATENATED MODULE: ./node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js
+
+
+class DocTypeReader{
+ constructor(processEntities){
+ this.suppressValidationErr = !processEntities;
+ }
+
+ readDocType(xmlData, i){
+
+ const entities = {};
+ if( xmlData[i + 3] === 'O' &&
+ xmlData[i + 4] === 'C' &&
+ xmlData[i + 5] === 'T' &&
+ xmlData[i + 6] === 'Y' &&
+ xmlData[i + 7] === 'P' &&
+ xmlData[i + 8] === 'E')
+ {
+ i = i+9;
+ let angleBracketsCount = 1;
+ let hasBody = false, comment = false;
+ let exp = "";
+ for(;i') { //Read tag content
+ if(comment){
+ if( xmlData[i - 1] === "-" && xmlData[i - 2] === "-"){
+ comment = false;
+ angleBracketsCount--;
+ }
+ }else{
+ angleBracketsCount--;
}
- catch (e) {
- e = "invalid UTF8";
- break;
+ if (angleBracketsCount === 0) {
+ break;
}
- return json;
- // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings.
- // Either standard or URL-safe base64 encoding with/without paddings are accepted.
- case reflection_info_1.ScalarType.BYTES:
- if (json === null || json === "")
- return new Uint8Array(0);
- if (typeof json !== 'string')
- break;
- return base64_1.base64decode(json);
+ }else if( xmlData[i] === '['){
+ hasBody = true;
+ }else{
+ exp += xmlData[i];
+ }
}
+ if(angleBracketsCount !== 0){
+ throw new Error(`Unclosed DOCTYPE`);
+ }
+ }else{
+ throw new Error(`Invalid Tag instead of DOCTYPE`);
}
- catch (error) {
- e = error.message;
- }
- this.assert(false, fieldName + (e ? " - " + e : ""), json);
+ return {entities, i};
}
-}
-exports.ReflectionJsonReader = ReflectionJsonReader;
+ readEntityExp(xmlData, i) {
+ //External entities are not supported
+ //
+ //Parameter entities are not supported
+ //
-/***/ }),
+ //Internal entities are supported
+ //
-/***/ 1094:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ // Skip leading whitespace after 0)
- jsonValue = jsonObj;
+
+ readNotationExp(xmlData, i) {
+ // Skip leading whitespace after 0 || options.emitDefaultValues)
- jsonValue = jsonArr;
+ !this.suppressValidationErr && validateEntityName(notationName);
+
+ // Skip whitespace after notation name
+ i = skipWhitespace(xmlData, i);
+
+ // Check identifier type (SYSTEM or PUBLIC)
+ const identifierType = xmlData.substring(i, i + 6).toUpperCase();
+ if (!this.suppressValidationErr && identifierType !== "SYSTEM" && identifierType !== "PUBLIC") {
+ throw new Error(`Expected SYSTEM or PUBLIC, found "${identifierType}"`);
}
- else {
- switch (field.kind) {
- case "scalar":
- jsonValue = this.scalar(field.T, value, field.name, field.opt, options.emitDefaultValues);
- break;
- case "enum":
- jsonValue = this.enum(field.T(), value, field.name, field.opt, options.emitDefaultValues, options.enumAsInteger);
- break;
- case "message":
- jsonValue = this.message(field.T(), value, field.name, options);
- break;
+ i += identifierType.length;
+
+ // Skip whitespace after identifier type
+ i = skipWhitespace(xmlData, i);
+
+ // Read public identifier (if PUBLIC)
+ let publicIdentifier = null;
+ let systemIdentifier = null;
+
+ if (identifierType === "PUBLIC") {
+ [i, publicIdentifier ] = this.readIdentifierVal(xmlData, i, "publicIdentifier");
+
+ // Skip whitespace after public identifier
+ i = skipWhitespace(xmlData, i);
+
+ // Optionally read system identifier
+ if (xmlData[i] === '"' || xmlData[i] === "'") {
+ [i, systemIdentifier ] = this.readIdentifierVal(xmlData, i,"systemIdentifier");
+ }
+ } else if (identifierType === "SYSTEM") {
+ // Read system identifier (mandatory for SYSTEM)
+ [i, systemIdentifier ] = this.readIdentifierVal(xmlData, i, "systemIdentifier");
+
+ if (!this.suppressValidationErr && !systemIdentifier) {
+ throw new Error("Missing mandatory system identifier for SYSTEM notation");
}
}
- return jsonValue;
+
+ return {notationName, publicIdentifier, systemIdentifier, index: --i};
}
- /**
- * Returns `null` as the default for google.protobuf.NullValue.
- */
- enum(type, value, fieldName, optional, emitDefaultValues, enumAsInteger) {
- if (type[0] == 'google.protobuf.NullValue')
- return !emitDefaultValues && !optional ? undefined : null;
- if (value === undefined) {
- assert_1.assert(optional);
- return undefined;
+
+ readIdentifierVal(xmlData, i, type) {
+ let identifierVal = "";
+ const startChar = xmlData[i];
+ if (startChar !== '"' && startChar !== "'") {
+ throw new Error(`Expected quoted string, found "${startChar}"`);
}
- if (value === 0 && !emitDefaultValues && !optional)
- // we require 0 to be default value for all enums
- return undefined;
- assert_1.assert(typeof value == 'number');
- assert_1.assert(Number.isInteger(value));
- if (enumAsInteger || !type[1].hasOwnProperty(value))
- // if we don't now the enum value, just return the number
- return value;
- if (type[2])
- // restore the dropped prefix
- return type[2] + type[1][value];
- return type[1][value];
- }
- message(type, value, fieldName, options) {
- if (value === undefined)
- return options.emitDefaultValues ? null : undefined;
- return type.internalJsonWrite(value, options);
- }
- scalar(type, value, fieldName, optional, emitDefaultValues) {
- if (value === undefined) {
- assert_1.assert(optional);
- return undefined;
+ i++;
+
+ while (i < xmlData.length && xmlData[i] !== startChar) {
+ identifierVal += xmlData[i];
+ i++;
}
- const ed = emitDefaultValues || optional;
- // noinspection FallThroughInSwitchStatementJS
- switch (type) {
- // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted.
- case reflection_info_1.ScalarType.INT32:
- case reflection_info_1.ScalarType.SFIXED32:
- case reflection_info_1.ScalarType.SINT32:
- if (value === 0)
- return ed ? 0 : undefined;
- assert_1.assertInt32(value);
- return value;
- case reflection_info_1.ScalarType.FIXED32:
- case reflection_info_1.ScalarType.UINT32:
- if (value === 0)
- return ed ? 0 : undefined;
- assert_1.assertUInt32(value);
- return value;
- // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity".
- // Either numbers or strings are accepted. Exponent notation is also accepted.
- case reflection_info_1.ScalarType.FLOAT:
- assert_1.assertFloat32(value);
- case reflection_info_1.ScalarType.DOUBLE:
- if (value === 0)
- return ed ? 0 : undefined;
- assert_1.assert(typeof value == 'number');
- if (Number.isNaN(value))
- return 'NaN';
- if (value === Number.POSITIVE_INFINITY)
- return 'Infinity';
- if (value === Number.NEGATIVE_INFINITY)
- return '-Infinity';
- return value;
- // string:
- case reflection_info_1.ScalarType.STRING:
- if (value === "")
- return ed ? '' : undefined;
- assert_1.assert(typeof value == 'string');
- return value;
- // bool:
- case reflection_info_1.ScalarType.BOOL:
- if (value === false)
- return ed ? false : undefined;
- assert_1.assert(typeof value == 'boolean');
- return value;
- // JSON value will be a decimal string. Either numbers or strings are accepted.
- case reflection_info_1.ScalarType.UINT64:
- case reflection_info_1.ScalarType.FIXED64:
- assert_1.assert(typeof value == 'number' || typeof value == 'string' || typeof value == 'bigint');
- let ulong = pb_long_1.PbULong.from(value);
- if (ulong.isZero() && !ed)
- return undefined;
- return ulong.toString();
- // JSON value will be a decimal string. Either numbers or strings are accepted.
- case reflection_info_1.ScalarType.INT64:
- case reflection_info_1.ScalarType.SFIXED64:
- case reflection_info_1.ScalarType.SINT64:
- assert_1.assert(typeof value == 'number' || typeof value == 'string' || typeof value == 'bigint');
- let long = pb_long_1.PbLong.from(value);
- if (long.isZero() && !ed)
- return undefined;
- return long.toString();
- // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings.
- // Either standard or URL-safe base64 encoding with/without paddings are accepted.
- case reflection_info_1.ScalarType.BYTES:
- assert_1.assert(value instanceof Uint8Array);
- if (!value.byteLength)
- return ed ? "" : undefined;
- return base64_1.base64encode(value);
+
+ if (xmlData[i] !== startChar) {
+ throw new Error(`Unterminated ${type} value`);
}
+ i++;
+ return [i, identifierVal];
}
-}
-exports.ReflectionJsonWriter = ReflectionJsonWriter;
+ readElementExp(xmlData, i) {
+ //
+ //
+ //
+ //
+ //
+
+ // Skip leading whitespace after {
+ // Validate element name
+ if (!this.suppressValidationErr && !isName(elementName)) {
+ throw new Error(`Invalid element name: "${elementName}"`);
+ }
+
+ // Skip whitespace after element name
+ i = skipWhitespace(xmlData, i);
+ let contentModel = "";
+ // Expect '(' to start content model
+ if(xmlData[i] === "E" && hasSeq(xmlData, "MPTY",i)) i+=4;
+ else if(xmlData[i] === "A" && hasSeq(xmlData, "NY",i)) i+=2;
+ else if (xmlData[i] === "(") {
+ i++; // Move past '('
+ // Read content model
+ while (i < xmlData.length && xmlData[i] !== ")") {
+ contentModel += xmlData[i];
+ i++;
+ }
+ if (xmlData[i] !== ")") {
+ throw new Error("Unterminated content model");
+ }
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.reflectionLongConvert = void 0;
-const reflection_info_1 = __nccwpck_require__(7910);
-/**
- * Utility method to convert a PbLong or PbUlong to a JavaScript
- * representation during runtime.
- *
- * Works with generated field information, `undefined` is equivalent
- * to `STRING`.
- */
-function reflectionLongConvert(long, type) {
- switch (type) {
- case reflection_info_1.LongType.BIGINT:
- return long.toBigInt();
- case reflection_info_1.LongType.NUMBER:
- return long.toNumber();
- default:
- // case undefined:
- // case LongType.STRING:
- return long.toString();
+ }else if(!this.suppressValidationErr){
+ throw new Error(`Invalid Element Expression, found "${xmlData[i]}"`);
+ }
+
+ return {
+ elementName,
+ contentModel: contentModel.trim(),
+ index: i
+ };
}
-}
-exports.reflectionLongConvert = reflectionLongConvert;
+ readAttlistExp(xmlData, i) {
+ // Skip leading whitespace after {
+ // Validate element name
+ validateEntityName(elementName)
+ // Skip whitespace after element name
+ i = skipWhitespace(xmlData, i);
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.reflectionMergePartial = void 0;
-/**
- * Copy partial data into the target message.
- *
- * If a singular scalar or enum field is present in the source, it
- * replaces the field in the target.
- *
- * If a singular message field is present in the source, it is merged
- * with the target field by calling mergePartial() of the responsible
- * message type.
- *
- * If a repeated field is present in the source, its values replace
- * all values in the target array, removing extraneous values.
- * Repeated message fields are copied, not merged.
- *
- * If a map field is present in the source, entries are added to the
- * target map, replacing entries with the same key. Entries that only
- * exist in the target remain. Entries with message values are copied,
- * not merged.
- *
- * Note that this function differs from protobuf merge semantics,
- * which appends repeated fields.
- */
-function reflectionMergePartial(info, target, source) {
- let fieldValue, // the field value we are working with
- input = source, output; // where we want our field value to go
- for (let field of info.fields) {
- let name = field.localName;
- if (field.oneof) {
- const group = input[field.oneof]; // this is the oneof`s group in the source
- if ((group === null || group === void 0 ? void 0 : group.oneofKind) == undefined) { // the user is free to omit
- continue; // we skip this field, and all other members too
- }
- fieldValue = group[name]; // our value comes from the the oneof group of the source
- output = target[field.oneof]; // and our output is the oneof group of the target
- output.oneofKind = group.oneofKind; // always update discriminator
- if (fieldValue == undefined) {
- delete output[name]; // remove any existing value
- continue; // skip further work on field
- }
- }
- else {
- fieldValue = input[name]; // we are using the source directly
- output = target; // we want our field value to go directly into the target
- if (fieldValue == undefined) {
- continue; // skip further work on field, existing value is used as is
- }
+ // Read attribute name
+ let attributeName = "";
+ while (i < xmlData.length && !/\s/.test(xmlData[i])) {
+ attributeName += xmlData[i];
+ i++;
}
- if (field.repeat)
- output[name].length = fieldValue.length; // resize target array to match source array
- // now we just work with `fieldValue` and `output` to merge the value
- switch (field.kind) {
- case "scalar":
- case "enum":
- if (field.repeat)
- for (let i = 0; i < fieldValue.length; i++)
- output[name][i] = fieldValue[i]; // not a reference type
- else
- output[name] = fieldValue; // not a reference type
- break;
- case "message":
- let T = field.T();
- if (field.repeat)
- for (let i = 0; i < fieldValue.length; i++)
- output[name][i] = T.create(fieldValue[i]);
- else if (output[name] === undefined)
- output[name] = T.create(fieldValue); // nothing to merge with
- else
- T.mergePartial(output[name], fieldValue);
- break;
- case "map":
- // Map and repeated fields are simply overwritten, not appended or merged
- switch (field.V.kind) {
- case "scalar":
- case "enum":
- Object.assign(output[name], fieldValue); // elements are not reference types
- break;
- case "message":
- let T = field.V.T();
- for (let k of Object.keys(fieldValue))
- output[name][k] = T.create(fieldValue[k]);
- break;
- }
- break;
+
+ // Validate attribute name
+ if (!validateEntityName(attributeName)) {
+ throw new Error(`Invalid attribute name: "${attributeName}"`);
}
- }
-}
-exports.reflectionMergePartial = reflectionMergePartial;
+ // Skip whitespace after attribute name
+ i = skipWhitespace(xmlData, i);
-/***/ }),
+ // Read attribute type
+ let attributeType = "";
+ if (xmlData.substring(i, i + 8).toUpperCase() === "NOTATION") {
+ attributeType = "NOTATION";
+ i += 8; // Move past "NOTATION"
-/***/ 9526:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ // Skip whitespace after "NOTATION"
+ i = skipWhitespace(xmlData, i);
+ // Expect '(' to start the list of notations
+ if (xmlData[i] !== "(") {
+ throw new Error(`Expected '(', found "${xmlData[i]}"`);
+ }
+ i++; // Move past '('
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.reflectionScalarDefault = void 0;
-const reflection_info_1 = __nccwpck_require__(7910);
-const reflection_long_convert_1 = __nccwpck_require__(3402);
-const pb_long_1 = __nccwpck_require__(1753);
-/**
- * Creates the default value for a scalar type.
- */
-function reflectionScalarDefault(type, longType = reflection_info_1.LongType.STRING) {
- switch (type) {
- case reflection_info_1.ScalarType.BOOL:
- return false;
- case reflection_info_1.ScalarType.UINT64:
- case reflection_info_1.ScalarType.FIXED64:
- return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType);
- case reflection_info_1.ScalarType.INT64:
- case reflection_info_1.ScalarType.SFIXED64:
- case reflection_info_1.ScalarType.SINT64:
- return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType);
- case reflection_info_1.ScalarType.DOUBLE:
- case reflection_info_1.ScalarType.FLOAT:
- return 0.0;
- case reflection_info_1.ScalarType.BYTES:
- return new Uint8Array(0);
- case reflection_info_1.ScalarType.STRING:
- return "";
- default:
- // case ScalarType.INT32:
- // case ScalarType.UINT32:
- // case ScalarType.SINT32:
- // case ScalarType.FIXED32:
- // case ScalarType.SFIXED32:
- return 0;
- }
-}
-exports.reflectionScalarDefault = reflectionScalarDefault;
+ // Read the list of allowed notations
+ let allowedNotations = [];
+ while (i < xmlData.length && xmlData[i] !== ")") {
+ let notation = "";
+ while (i < xmlData.length && xmlData[i] !== "|" && xmlData[i] !== ")") {
+ notation += xmlData[i];
+ i++;
+ }
+ // Validate notation name
+ notation = notation.trim();
+ if (!validateEntityName(notation)) {
+ throw new Error(`Invalid notation name: "${notation}"`);
+ }
-/***/ }),
+ allowedNotations.push(notation);
-/***/ 5167:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ // Skip '|' separator or exit loop
+ if (xmlData[i] === "|") {
+ i++; // Move past '|'
+ i = skipWhitespace(xmlData, i); // Skip optional whitespace after '|'
+ }
+ }
+ if (xmlData[i] !== ")") {
+ throw new Error("Unterminated list of notations");
+ }
+ i++; // Move past ')'
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.ReflectionTypeCheck = void 0;
-const reflection_info_1 = __nccwpck_require__(7910);
-const oneof_1 = __nccwpck_require__(8063);
-// noinspection JSMethodCanBeStatic
-class ReflectionTypeCheck {
- constructor(info) {
- var _a;
- this.fields = (_a = info.fields) !== null && _a !== void 0 ? _a : [];
- }
- prepare() {
- if (this.data)
- return;
- const req = [], known = [], oneofs = [];
- for (let field of this.fields) {
- if (field.oneof) {
- if (!oneofs.includes(field.oneof)) {
- oneofs.push(field.oneof);
- req.push(field.oneof);
- known.push(field.oneof);
- }
+ // Store the allowed notations as part of the attribute type
+ attributeType += " (" + allowedNotations.join("|") + ")";
+ } else {
+ // Handle simple types (e.g., CDATA, ID, IDREF, etc.)
+ while (i < xmlData.length && !/\s/.test(xmlData[i])) {
+ attributeType += xmlData[i];
+ i++;
}
- else {
- known.push(field.localName);
- switch (field.kind) {
- case "scalar":
- case "enum":
- if (!field.opt || field.repeat)
- req.push(field.localName);
- break;
- case "message":
- if (field.repeat)
- req.push(field.localName);
- break;
- case "map":
- req.push(field.localName);
- break;
- }
+
+ // Validate simple attribute type
+ const validTypes = ["CDATA", "ID", "IDREF", "IDREFS", "ENTITY", "ENTITIES", "NMTOKEN", "NMTOKENS"];
+ if (!this.suppressValidationErr && !validTypes.includes(attributeType.toUpperCase())) {
+ throw new Error(`Invalid attribute type: "${attributeType}"`);
}
}
- this.data = { req, known, oneofs: Object.values(oneofs) };
- }
- /**
- * Is the argument a valid message as specified by the
- * reflection information?
- *
- * Checks all field types recursively. The `depth`
- * specifies how deep into the structure the check will be.
- *
- * With a depth of 0, only the presence of fields
- * is checked.
- *
- * With a depth of 1 or more, the field types are checked.
- *
- * With a depth of 2 or more, the members of map, repeated
- * and message fields are checked.
- *
- * Message fields will be checked recursively with depth - 1.
- *
- * The number of map entries / repeated values being checked
- * is < depth.
- */
- is(message, depth, allowExcessProperties = false) {
- if (depth < 0)
- return true;
- if (message === null || message === undefined || typeof message != 'object')
- return false;
- this.prepare();
- let keys = Object.keys(message), data = this.data;
- // if a required field is missing in arg, this cannot be a T
- if (keys.length < data.req.length || data.req.some(n => !keys.includes(n)))
- return false;
- if (!allowExcessProperties) {
- // if the arg contains a key we dont know, this is not a literal T
- if (keys.some(k => !data.known.includes(k)))
- return false;
- }
- // "With a depth of 0, only the presence and absence of fields is checked."
- // "With a depth of 1 or more, the field types are checked."
- if (depth < 1) {
- return true;
- }
- // check oneof group
- for (const name of data.oneofs) {
- const group = message[name];
- if (!oneof_1.isOneofGroup(group))
- return false;
- if (group.oneofKind === undefined)
- continue;
- const field = this.fields.find(f => f.localName === group.oneofKind);
- if (!field)
- return false; // we found no field, but have a kind, something is wrong
- if (!this.field(group[group.oneofKind], field, allowExcessProperties, depth))
- return false;
- }
- // check types
- for (const field of this.fields) {
- if (field.oneof !== undefined)
- continue;
- if (!this.field(message[field.localName], field, allowExcessProperties, depth))
- return false;
- }
- return true;
- }
- field(arg, field, allowExcessProperties, depth) {
- let repeated = field.repeat;
- switch (field.kind) {
- case "scalar":
- if (arg === undefined)
- return field.opt;
- if (repeated)
- return this.scalars(arg, field.T, depth, field.L);
- return this.scalar(arg, field.T, field.L);
- case "enum":
- if (arg === undefined)
- return field.opt;
- if (repeated)
- return this.scalars(arg, reflection_info_1.ScalarType.INT32, depth);
- return this.scalar(arg, reflection_info_1.ScalarType.INT32);
- case "message":
- if (arg === undefined)
- return true;
- if (repeated)
- return this.messages(arg, field.T(), allowExcessProperties, depth);
- return this.message(arg, field.T(), allowExcessProperties, depth);
- case "map":
- if (typeof arg != 'object' || arg === null)
- return false;
- if (depth < 2)
- return true;
- if (!this.mapKeys(arg, field.K, depth))
- return false;
- switch (field.V.kind) {
- case "scalar":
- return this.scalars(Object.values(arg), field.V.T, depth, field.V.L);
- case "enum":
- return this.scalars(Object.values(arg), reflection_info_1.ScalarType.INT32, depth);
- case "message":
- return this.messages(Object.values(arg), field.V.T(), allowExcessProperties, depth);
- }
- break;
- }
- return true;
- }
- message(arg, type, allowExcessProperties, depth) {
- if (allowExcessProperties) {
- return type.isAssignable(arg, depth);
- }
- return type.is(arg, depth);
- }
- messages(arg, type, allowExcessProperties, depth) {
- if (!Array.isArray(arg))
- return false;
- if (depth < 2)
- return true;
- if (allowExcessProperties) {
- for (let i = 0; i < arg.length && i < depth; i++)
- if (!type.isAssignable(arg[i], depth - 1))
- return false;
- }
- else {
- for (let i = 0; i < arg.length && i < depth; i++)
- if (!type.is(arg[i], depth - 1))
- return false;
- }
- return true;
- }
- scalar(arg, type, longType) {
- let argType = typeof arg;
- switch (type) {
- case reflection_info_1.ScalarType.UINT64:
- case reflection_info_1.ScalarType.FIXED64:
- case reflection_info_1.ScalarType.INT64:
- case reflection_info_1.ScalarType.SFIXED64:
- case reflection_info_1.ScalarType.SINT64:
- switch (longType) {
- case reflection_info_1.LongType.BIGINT:
- return argType == "bigint";
- case reflection_info_1.LongType.NUMBER:
- return argType == "number" && !isNaN(arg);
- default:
- return argType == "string";
- }
- case reflection_info_1.ScalarType.BOOL:
- return argType == 'boolean';
- case reflection_info_1.ScalarType.STRING:
- return argType == 'string';
- case reflection_info_1.ScalarType.BYTES:
- return arg instanceof Uint8Array;
- case reflection_info_1.ScalarType.DOUBLE:
- case reflection_info_1.ScalarType.FLOAT:
- return argType == 'number' && !isNaN(arg);
- default:
- // case ScalarType.UINT32:
- // case ScalarType.FIXED32:
- // case ScalarType.INT32:
- // case ScalarType.SINT32:
- // case ScalarType.SFIXED32:
- return argType == 'number' && Number.isInteger(arg);
+
+ // Skip whitespace after attribute type
+ i = skipWhitespace(xmlData, i);
+
+ // Read default value
+ let defaultValue = "";
+ if (xmlData.substring(i, i + 8).toUpperCase() === "#REQUIRED") {
+ defaultValue = "#REQUIRED";
+ i += 8;
+ } else if (xmlData.substring(i, i + 7).toUpperCase() === "#IMPLIED") {
+ defaultValue = "#IMPLIED";
+ i += 7;
+ } else {
+ [i, defaultValue] = this.readIdentifierVal(xmlData, i, "ATTLIST");
}
- }
- scalars(arg, type, depth, longType) {
- if (!Array.isArray(arg))
- return false;
- if (depth < 2)
- return true;
- if (Array.isArray(arg))
- for (let i = 0; i < arg.length && i < depth; i++)
- if (!this.scalar(arg[i], type, longType))
- return false;
- return true;
- }
- mapKeys(map, type, depth) {
- let keys = Object.keys(map);
- switch (type) {
- case reflection_info_1.ScalarType.INT32:
- case reflection_info_1.ScalarType.FIXED32:
- case reflection_info_1.ScalarType.SFIXED32:
- case reflection_info_1.ScalarType.SINT32:
- case reflection_info_1.ScalarType.UINT32:
- return this.scalars(keys.slice(0, depth).map(k => parseInt(k)), type, depth);
- case reflection_info_1.ScalarType.BOOL:
- return this.scalars(keys.slice(0, depth).map(k => k == 'true' ? true : k == 'false' ? false : k), type, depth);
- default:
- return this.scalars(keys, type, depth, reflection_info_1.LongType.STRING);
+
+ return {
+ elementName,
+ attributeName,
+ attributeType,
+ defaultValue,
+ index: i
}
}
}
-exports.ReflectionTypeCheck = ReflectionTypeCheck;
-/***/ }),
-/***/ 5183:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+const skipWhitespace = (data, index) => {
+ while (index < data.length && /\s/.test(data[index])) {
+ index++;
+ }
+ return index;
+};
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- var desc = Object.getOwnPropertyDescriptor(m, k);
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() { return m[k]; } };
+
+function hasSeq(data, seq,i){
+ for(let j=0;j [ , '+', '00', '.123', ..
+ if(match){
+ const sign = match[1] || "";
+ const leadingZeros = match[2];
+ let numTrimmedByZeros = trimZeros(match[3]); //complete num without leading zeros
+ const decimalAdjacentToLeadingZeros = sign ? // 0., -00., 000.
+ str[leadingZeros.length+1] === "."
+ : str[leadingZeros.length] === ".";
+
+ //trim ending zeros for floating number
+ if(!options.leadingZeros //leading zeros are not allowed
+ && (leadingZeros.length > 1
+ || (leadingZeros.length === 1 && !decimalAdjacentToLeadingZeros))){
+ // 00, 00.3, +03.24, 03, 03.24
+ return str;
+ }
+ else{//no leading zeros or leading zeros are allowed
+ const num = Number(trimmedStr);
+ const parsedStr = String(num);
+
+ if( num === 0) return num;
+ if(parsedStr.search(/[eE]/) !== -1){ //given number is long and parsed to eNotation
+ if(options.eNotation) return num;
+ else return str;
+ }else if(trimmedStr.indexOf(".") !== -1){ //floating number
+ if(parsedStr === "0") return num; //0.0
+ else if(parsedStr === numTrimmedByZeros) return num; //0.456. 0.79000
+ else if( parsedStr === `${sign}${numTrimmedByZeros}`) return num;
+ else return str;
+ }
+
+ let n = leadingZeros? numTrimmedByZeros : trimmedStr;
+ if(leadingZeros){
+ // -009 => -9
+ return (n === parsedStr) || (sign+n === parsedStr) ? num : str
+ }else {
+ // +9
+ return (n === parsedStr) || (n === sign+parsedStr) ? num : str
+ }
+ }
+ }else{ //non-numeric string
+ return str;
+ }
}
- return Buffer.concat(chunks, length);
}
-exports.toBuffer = toBuffer;
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-async function json(stream) {
- const buf = await toBuffer(stream);
- const str = buf.toString('utf8');
- try {
- return JSON.parse(str);
+
+const eNotationRegx = /^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;
+function resolveEnotation(str,trimmedStr,options){
+ if(!options.eNotation) return str;
+ const notation = trimmedStr.match(eNotationRegx);
+ if(notation){
+ let sign = notation[1] || "";
+ const eChar = notation[3].indexOf("e") === -1 ? "E" : "e";
+ const leadingZeros = notation[2];
+ const eAdjacentToLeadingZeros = sign ? // 0E.
+ str[leadingZeros.length+1] === eChar
+ : str[leadingZeros.length] === eChar;
+
+ if(leadingZeros.length > 1 && eAdjacentToLeadingZeros) return str;
+ else if(leadingZeros.length === 1
+ && (notation[3].startsWith(`.${eChar}`) || notation[3][0] === eChar)){
+ return Number(trimmedStr);
+ }else if(options.leadingZeros && !eAdjacentToLeadingZeros){ //accept with leading zeros
+ //remove leading 0s
+ trimmedStr = (notation[1] || "") + notation[3];
+ return Number(trimmedStr);
+ }else return str;
+ }else{
+ return str;
}
- catch (_err) {
- const err = _err;
- err.message += ` (input: ${str})`;
- throw err;
+}
+
+/**
+ *
+ * @param {string} numStr without leading zeros
+ * @returns
+ */
+function trimZeros(numStr){
+ if(numStr && numStr.indexOf(".") !== -1){//float
+ numStr = numStr.replace(/0+$/, ""); //remove ending zeros
+ if(numStr === ".") numStr = "0";
+ else if(numStr[0] === ".") numStr = "0"+numStr;
+ else if(numStr[numStr.length-1] === ".") numStr = numStr.substring(0,numStr.length-1);
+ return numStr;
}
+ return numStr;
}
-exports.json = json;
-function req(url, opts = {}) {
- const href = typeof url === 'string' ? url : url.href;
- const req = (href.startsWith('https:') ? https : http).request(url, opts);
- const promise = new Promise((resolve, reject) => {
- req
- .once('response', resolve)
- .once('error', reject)
- .end();
- });
- req.then = promise.then.bind(promise);
- return req;
+
+function parse_int(numStr, base){
+ //polyfill
+ if(parseInt) return parseInt(numStr, base);
+ else if(Number.parseInt) return Number.parseInt(numStr, base);
+ else if(window && window.parseInt) return window.parseInt(numStr, base);
+ else throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")
}
-exports.req = req;
-//# sourceMappingURL=helpers.js.map
+;// CONCATENATED MODULE: ./node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js
-/***/ }),
+///@ts-check
-/***/ 8894:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- var desc = Object.getOwnPropertyDescriptor(m, k);
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() { return m[k]; } };
- }
- Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-var __exportStar = (this && this.__exportStar) || function(m, exports) {
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.Agent = void 0;
-const net = __importStar(__nccwpck_require__(9278));
-const http = __importStar(__nccwpck_require__(8611));
-const https_1 = __nccwpck_require__(5692);
-__exportStar(__nccwpck_require__(5183), exports);
-const INTERNAL = Symbol('AgentBaseInternalState');
-class Agent extends http.Agent {
- constructor(opts) {
- super(opts);
- this[INTERNAL] = {};
- }
- /**
- * Determine whether this is an `http` or `https` request.
- */
- isSecureEndpoint(options) {
- if (options) {
- // First check the `secureEndpoint` property explicitly, since this
- // means that a parent `Agent` is "passing through" to this instance.
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- if (typeof options.secureEndpoint === 'boolean') {
- return options.secureEndpoint;
- }
- // If no explicit `secure` endpoint, check if `protocol` property is
- // set. This will usually be the case since using a full string URL
- // or `URL` instance should be the most common usage.
- if (typeof options.protocol === 'string') {
- return options.protocol === 'https:';
- }
- }
- // Finally, if no `protocol` property was set, then fall back to
- // checking the stack trace of the current call stack, and try to
- // detect the "https" module.
- const { stack } = new Error();
- if (typeof stack !== 'string')
- return false;
- return stack
- .split('\n')
- .some((l) => l.indexOf('(https.js:') !== -1 ||
- l.indexOf('node:https:') !== -1);
- }
- // In order to support async signatures in `connect()` and Node's native
- // connection pooling in `http.Agent`, the array of sockets for each origin
- // has to be updated synchronously. This is so the length of the array is
- // accurate when `addRequest()` is next called. We achieve this by creating a
- // fake socket and adding it to `sockets[origin]` and incrementing
- // `totalSocketCount`.
- incrementSockets(name) {
- // If `maxSockets` and `maxTotalSockets` are both Infinity then there is no
- // need to create a fake socket because Node.js native connection pooling
- // will never be invoked.
- if (this.maxSockets === Infinity && this.maxTotalSockets === Infinity) {
- return null;
- }
- // All instances of `sockets` are expected TypeScript errors. The
- // alternative is to add it as a private property of this class but that
- // will break TypeScript subclassing.
- if (!this.sockets[name]) {
- // @ts-expect-error `sockets` is readonly in `@types/node`
- this.sockets[name] = [];
- }
- const fakeSocket = new net.Socket({ writable: false });
- this.sockets[name].push(fakeSocket);
- // @ts-expect-error `totalSocketCount` isn't defined in `@types/node`
- this.totalSocketCount++;
- return fakeSocket;
- }
- decrementSockets(name, socket) {
- if (!this.sockets[name] || socket === null) {
- return;
- }
- const sockets = this.sockets[name];
- const index = sockets.indexOf(socket);
- if (index !== -1) {
- sockets.splice(index, 1);
- // @ts-expect-error `totalSocketCount` isn't defined in `@types/node`
- this.totalSocketCount--;
- if (sockets.length === 0) {
- // @ts-expect-error `sockets` is readonly in `@types/node`
- delete this.sockets[name];
- }
- }
- }
- // In order to properly update the socket pool, we need to call `getName()` on
- // the core `https.Agent` if it is a secureEndpoint.
- getName(options) {
- const secureEndpoint = this.isSecureEndpoint(options);
- if (secureEndpoint) {
- // @ts-expect-error `getName()` isn't defined in `@types/node`
- return https_1.Agent.prototype.getName.call(this, options);
- }
- // @ts-expect-error `getName()` isn't defined in `@types/node`
- return super.getName(options);
- }
- createSocket(req, options, cb) {
- const connectOpts = {
- ...options,
- secureEndpoint: this.isSecureEndpoint(options),
- };
- const name = this.getName(connectOpts);
- const fakeSocket = this.incrementSockets(name);
- Promise.resolve()
- .then(() => this.connect(req, connectOpts))
- .then((socket) => {
- this.decrementSockets(name, fakeSocket);
- if (socket instanceof http.Agent) {
- try {
- // @ts-expect-error `addRequest()` isn't defined in `@types/node`
- return socket.addRequest(req, connectOpts);
- }
- catch (err) {
- return cb(err);
- }
- }
- this[INTERNAL].currentSocket = socket;
- // @ts-expect-error `createSocket()` isn't defined in `@types/node`
- super.createSocket(req, options, cb);
- }, (err) => {
- this.decrementSockets(name, fakeSocket);
- cb(err);
- });
- }
- createConnection() {
- const socket = this[INTERNAL].currentSocket;
- this[INTERNAL].currentSocket = undefined;
- if (!socket) {
- throw new Error('No socket was returned in the `connect()` function');
- }
- return socket;
- }
- get defaultPort() {
- return (this[INTERNAL].defaultPort ??
- (this.protocol === 'https:' ? 443 : 80));
- }
- set defaultPort(v) {
- if (this[INTERNAL]) {
- this[INTERNAL].defaultPort = v;
- }
- }
- get protocol() {
- return (this[INTERNAL].protocol ??
- (this.isSecureEndpoint() ? 'https:' : 'http:'));
- }
- set protocol(v) {
- if (this[INTERNAL]) {
- this[INTERNAL].protocol = v;
- }
- }
-}
-exports.Agent = Agent;
-//# sourceMappingURL=index.js.map
-/***/ }),
-/***/ 9380:
-/***/ ((module) => {
-module.exports = balanced;
-function balanced(a, b, str) {
- if (a instanceof RegExp) a = maybeMatch(a, str);
- if (b instanceof RegExp) b = maybeMatch(b, str);
+// const regx =
+// '<((!\\[CDATA\\[([\\s\\S]*?)(]]>))|((NAME:)?(NAME))([^>]*)>|((\\/)(NAME)\\s*>))([^<]*)'
+// .replace(/NAME/g, util.nameRegexp);
- var r = range(a, b, str);
+//const tagsRegx = new RegExp("<(\\/?[\\w:\\-\._]+)([^>]*)>(\\s*"+cdataRegx+")*([^<]+)?","g");
+//const tagsRegx = new RegExp("<(\\/?)((\\w*:)?([\\w:\\-\._]+))([^>]*)>([^<]*)("+cdataRegx+"([^<]*))*([^<]+)?","g");
- return r && {
- start: r[0],
- end: r[1],
- pre: str.slice(0, r[0]),
- body: str.slice(r[0] + a.length, r[1]),
- post: str.slice(r[1] + b.length)
- };
-}
+class OrderedObjParser{
+ constructor(options){
+ this.options = options;
+ this.currentNode = null;
+ this.tagsNodeStack = [];
+ this.docTypeEntities = {};
+ this.lastEntities = {
+ "apos" : { regex: /&(apos|#39|#x27);/g, val : "'"},
+ "gt" : { regex: /&(gt|#62|#x3E);/g, val : ">"},
+ "lt" : { regex: /&(lt|#60|#x3C);/g, val : "<"},
+ "quot" : { regex: /&(quot|#34|#x22);/g, val : "\""},
+ };
+ this.ampEntity = { regex: /&(amp|#38|#x26);/g, val : "&"};
+ this.htmlEntities = {
+ "space": { regex: /&(nbsp|#160);/g, val: " " },
+ // "lt" : { regex: /&(lt|#60);/g, val: "<" },
+ // "gt" : { regex: /&(gt|#62);/g, val: ">" },
+ // "amp" : { regex: /&(amp|#38);/g, val: "&" },
+ // "quot" : { regex: /&(quot|#34);/g, val: "\"" },
+ // "apos" : { regex: /&(apos|#39);/g, val: "'" },
+ "cent" : { regex: /&(cent|#162);/g, val: "¢" },
+ "pound" : { regex: /&(pound|#163);/g, val: "£" },
+ "yen" : { regex: /&(yen|#165);/g, val: "¥" },
+ "euro" : { regex: /&(euro|#8364);/g, val: "€" },
+ "copyright" : { regex: /&(copy|#169);/g, val: "©" },
+ "reg" : { regex: /&(reg|#174);/g, val: "®" },
+ "inr" : { regex: /&(inr|#8377);/g, val: "₹" },
+ "num_dec": { regex: /([0-9]{1,7});/g, val : (_, str) => String.fromCodePoint(Number.parseInt(str, 10)) },
+ "num_hex": { regex: /([0-9a-fA-F]{1,6});/g, val : (_, str) => String.fromCodePoint(Number.parseInt(str, 16)) },
+ };
+ this.addExternalEntities = addExternalEntities;
+ this.parseXml = parseXml;
+ this.parseTextData = parseTextData;
+ this.resolveNameSpace = resolveNameSpace;
+ this.buildAttributesMap = buildAttributesMap;
+ this.isItStopNode = isItStopNode;
+ this.replaceEntitiesValue = OrderedObjParser_replaceEntitiesValue;
+ this.readStopNodeData = readStopNodeData;
+ this.saveTextToParentTag = saveTextToParentTag;
+ this.addChild = addChild;
+ this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes)
-function maybeMatch(reg, str) {
- var m = str.match(reg);
- return m ? m[0] : null;
-}
+ if(this.options.stopNodes && this.options.stopNodes.length > 0){
+ this.stopNodesExact = new Set();
+ this.stopNodesWildcard = new Set();
+ for(let i = 0; i < this.options.stopNodes.length; i++){
+ const stopNodeExp = this.options.stopNodes[i];
+ if(typeof stopNodeExp !== 'string') continue;
+ if(stopNodeExp.startsWith("*.")){
+ this.stopNodesWildcard.add(stopNodeExp.substring(2));
+ }else{
+ this.stopNodesExact.add(stopNodeExp);
+ }
+ }
+ }
+ }
-balanced.range = range;
-function range(a, b, str) {
- var begs, beg, left, right, result;
- var ai = str.indexOf(a);
- var bi = str.indexOf(b, ai + 1);
- var i = ai;
+}
- if (ai >= 0 && bi > 0) {
- if(a===b) {
- return [ai, bi];
+function addExternalEntities(externalEntities){
+ const entKeys = Object.keys(externalEntities);
+ for (let i = 0; i < entKeys.length; i++) {
+ const ent = entKeys[i];
+ this.lastEntities[ent] = {
+ regex: new RegExp("&"+ent+";","g"),
+ val : externalEntities[ent]
}
- begs = [];
- left = str.length;
+ }
+}
- while (i >= 0 && !result) {
- if (i == ai) {
- begs.push(i);
- ai = str.indexOf(a, i + 1);
- } else if (begs.length == 1) {
- result = [ begs.pop(), bi ];
- } else {
- beg = begs.pop();
- if (beg < left) {
- left = beg;
- right = bi;
+/**
+ * @param {string} val
+ * @param {string} tagName
+ * @param {string} jPath
+ * @param {boolean} dontTrim
+ * @param {boolean} hasAttributes
+ * @param {boolean} isLeafNode
+ * @param {boolean} escapeEntities
+ */
+function parseTextData(val, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) {
+ if (val !== undefined) {
+ if (this.options.trimValues && !dontTrim) {
+ val = val.trim();
+ }
+ if(val.length > 0){
+ if(!escapeEntities) val = this.replaceEntitiesValue(val);
+
+ const newval = this.options.tagValueProcessor(tagName, val, jPath, hasAttributes, isLeafNode);
+ if(newval === null || newval === undefined){
+ //don't parse
+ return val;
+ }else if(typeof newval !== typeof val || newval !== val){
+ //overwrite
+ return newval;
+ }else if(this.options.trimValues){
+ return parseValue(val, this.options.parseTagValue, this.options.numberParseOptions);
+ }else{
+ const trimmedVal = val.trim();
+ if(trimmedVal === val){
+ return parseValue(val, this.options.parseTagValue, this.options.numberParseOptions);
+ }else{
+ return val;
}
-
- bi = str.indexOf(b, i + 1);
}
-
- i = ai < bi && ai >= 0 ? ai : bi;
}
+ }
+}
- if (begs.length) {
- result = [ left, right ];
+function resolveNameSpace(tagname) {
+ if (this.options.removeNSPrefix) {
+ const tags = tagname.split(':');
+ const prefix = tagname.charAt(0) === '/' ? '/' : '';
+ if (tags[0] === 'xmlns') {
+ return '';
+ }
+ if (tags.length === 2) {
+ tagname = prefix + tags[1];
}
}
-
- return result;
+ return tagname;
}
+//TODO: change regex to capture NS
+//const attrsRegx = new RegExp("([\\w\\-\\.\\:]+)\\s*=\\s*(['\"])((.|\n)*?)\\2","gm");
+const attrsRegx = new RegExp('([^\\s=]+)\\s*(=\\s*([\'"])([\\s\\S]*?)\\3)?', 'gm');
-/***/ }),
-
-/***/ 4691:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-var concatMap = __nccwpck_require__(7087);
-var balanced = __nccwpck_require__(9380);
-
-module.exports = expandTop;
-
-var escSlash = '\0SLASH'+Math.random()+'\0';
-var escOpen = '\0OPEN'+Math.random()+'\0';
-var escClose = '\0CLOSE'+Math.random()+'\0';
-var escComma = '\0COMMA'+Math.random()+'\0';
-var escPeriod = '\0PERIOD'+Math.random()+'\0';
+function buildAttributesMap(attrStr, jPath) {
+ if (this.options.ignoreAttributes !== true && typeof attrStr === 'string') {
+ // attrStr = attrStr.replace(/\r?\n/g, ' ');
+ //attrStr = attrStr || attrStr.trim();
-function numeric(str) {
- return parseInt(str, 10) == str
- ? parseInt(str, 10)
- : str.charCodeAt(0);
+ const matches = getAllMatches(attrStr, attrsRegx);
+ const len = matches.length; //don't make it inline
+ const attrs = {};
+ for (let i = 0; i < len; i++) {
+ const attrName = this.resolveNameSpace(matches[i][1]);
+ if (this.ignoreAttributesFn(attrName, jPath)) {
+ continue
+ }
+ let oldVal = matches[i][4];
+ let aName = this.options.attributeNamePrefix + attrName;
+ if (attrName.length) {
+ if (this.options.transformAttributeName) {
+ aName = this.options.transformAttributeName(aName);
+ }
+ if(aName === "__proto__") aName = "#__proto__";
+ if (oldVal !== undefined) {
+ if (this.options.trimValues) {
+ oldVal = oldVal.trim();
+ }
+ oldVal = this.replaceEntitiesValue(oldVal);
+ const newVal = this.options.attributeValueProcessor(attrName, oldVal, jPath);
+ if(newVal === null || newVal === undefined){
+ //don't parse
+ attrs[aName] = oldVal;
+ }else if(typeof newVal !== typeof oldVal || newVal !== oldVal){
+ //overwrite
+ attrs[aName] = newVal;
+ }else{
+ //parse
+ attrs[aName] = parseValue(
+ oldVal,
+ this.options.parseAttributeValue,
+ this.options.numberParseOptions
+ );
+ }
+ } else if (this.options.allowBooleanAttributes) {
+ attrs[aName] = true;
+ }
+ }
+ }
+ if (!Object.keys(attrs).length) {
+ return;
+ }
+ if (this.options.attributesGroupName) {
+ const attrCollection = {};
+ attrCollection[this.options.attributesGroupName] = attrs;
+ return attrCollection;
+ }
+ return attrs
+ }
}
-function escapeBraces(str) {
- return str.split('\\\\').join(escSlash)
- .split('\\{').join(escOpen)
- .split('\\}').join(escClose)
- .split('\\,').join(escComma)
- .split('\\.').join(escPeriod);
-}
+const parseXml = function(xmlData) {
+ xmlData = xmlData.replace(/\r\n?/g, "\n"); //TODO: remove this line
+ const xmlObj = new XmlNode('!xml');
+ let currentNode = xmlObj;
+ let textData = "";
+ let jPath = "";
+ const docTypeReader = new DocTypeReader(this.options.processEntities);
+ for(let i=0; i< xmlData.length; i++){//for each char in XML data
+ const ch = xmlData[i];
+ if(ch === '<'){
+ // const nextIndex = i+1;
+ // const _2ndChar = xmlData[nextIndex];
+ if( xmlData[i+1] === '/') {//Closing Tag
+ const closeIndex = findClosingIndex(xmlData, ">", i, "Closing Tag is not closed.")
+ let tagName = xmlData.substring(i+2,closeIndex).trim();
-function unescapeBraces(str) {
- return str.split(escSlash).join('\\')
- .split(escOpen).join('{')
- .split(escClose).join('}')
- .split(escComma).join(',')
- .split(escPeriod).join('.');
-}
+ if(this.options.removeNSPrefix){
+ const colonIndex = tagName.indexOf(":");
+ if(colonIndex !== -1){
+ tagName = tagName.substr(colonIndex+1);
+ }
+ }
+ if(this.options.transformTagName) {
+ tagName = this.options.transformTagName(tagName);
+ }
-// Basically just str.split(","), but handling cases
-// where we have nested braced sections, which should be
-// treated as individual members, like {a,{b,c},d}
-function parseCommaParts(str) {
- if (!str)
- return [''];
+ if(currentNode){
+ textData = this.saveTextToParentTag(textData, currentNode, jPath);
+ }
- var parts = [];
- var m = balanced('{', '}', str);
+ //check if last tag of nested tag was unpaired tag
+ const lastTagName = jPath.substring(jPath.lastIndexOf(".")+1);
+ if(tagName && this.options.unpairedTags.indexOf(tagName) !== -1 ){
+ throw new Error(`Unpaired tag can not be used as closing tag: ${tagName}>`);
+ }
+ let propIndex = 0
+ if(lastTagName && this.options.unpairedTags.indexOf(lastTagName) !== -1 ){
+ propIndex = jPath.lastIndexOf('.', jPath.lastIndexOf('.')-1)
+ this.tagsNodeStack.pop();
+ }else{
+ propIndex = jPath.lastIndexOf(".");
+ }
+ jPath = jPath.substring(0, propIndex);
- if (!m)
- return str.split(',');
+ currentNode = this.tagsNodeStack.pop();//avoid recursion, set the parent tag scope
+ textData = "";
+ i = closeIndex;
+ } else if( xmlData[i+1] === '?') {
- var pre = m.pre;
- var body = m.body;
- var post = m.post;
- var p = pre.split(',');
+ let tagData = readTagExp(xmlData,i, false, "?>");
+ if(!tagData) throw new Error("Pi Tag is not closed.");
- p[p.length-1] += '{' + body + '}';
- var postParts = parseCommaParts(post);
- if (post.length) {
- p[p.length-1] += postParts.shift();
- p.push.apply(p, postParts);
- }
+ textData = this.saveTextToParentTag(textData, currentNode, jPath);
+ if( (this.options.ignoreDeclaration && tagData.tagName === "?xml") || this.options.ignorePiTags){
+ //do nothing
+ }else{
+
+ const childNode = new XmlNode(tagData.tagName);
+ childNode.add(this.options.textNodeName, "");
+
+ if(tagData.tagName !== tagData.tagExp && tagData.attrExpPresent){
+ childNode[":@"] = this.buildAttributesMap(tagData.tagExp, jPath);
+ }
+ this.addChild(currentNode, childNode, jPath, i);
+ }
- parts.push.apply(parts, p);
- return parts;
-}
+ i = tagData.closeIndex + 1;
+ } else if(xmlData.substr(i + 1, 3) === '!--') {
+ const endIndex = findClosingIndex(xmlData, "-->", i+4, "Comment is not closed.")
+ if(this.options.commentPropName){
+ const comment = xmlData.substring(i + 4, endIndex - 2);
-function expandTop(str) {
- if (!str)
- return [];
+ textData = this.saveTextToParentTag(textData, currentNode, jPath);
- // I don't know why Bash 4.3 does this, but it does.
- // Anything starting with {} will have the first two bytes preserved
- // but *only* at the top level, so {},a}b will not expand to anything,
- // but a{},b}c will be expanded to [a}c,abc].
- // One could argue that this is a bug in Bash, but since the goal of
- // this module is to match Bash's rules, we escape a leading {}
- if (str.substr(0, 2) === '{}') {
- str = '\\{\\}' + str.substr(2);
- }
+ currentNode.add(this.options.commentPropName, [ { [this.options.textNodeName] : comment } ]);
+ }
+ i = endIndex;
+ } else if( xmlData.substr(i + 1, 2) === '!D') {
+ const result = docTypeReader.readDocType(xmlData, i);
+ this.docTypeEntities = result.entities;
+ i = result.i;
+ }else if(xmlData.substr(i + 1, 2) === '![') {
+ const closeIndex = findClosingIndex(xmlData, "]]>", i, "CDATA is not closed.") - 2;
+ const tagExp = xmlData.substring(i + 9,closeIndex);
- return expand(escapeBraces(str), true).map(unescapeBraces);
-}
+ textData = this.saveTextToParentTag(textData, currentNode, jPath);
-function identity(e) {
- return e;
-}
+ let val = this.parseTextData(tagExp, currentNode.tagname, jPath, true, false, true, true);
+ if(val == undefined) val = "";
-function embrace(str) {
- return '{' + str + '}';
-}
-function isPadded(el) {
- return /^-?0\d/.test(el);
-}
+ //cdata should be set even if it is 0 length string
+ if(this.options.cdataPropName){
+ currentNode.add(this.options.cdataPropName, [ { [this.options.textNodeName] : tagExp } ]);
+ }else{
+ currentNode.add(this.options.textNodeName, val);
+ }
+
+ i = closeIndex + 2;
+ }else {//Opening tag
+ let result = readTagExp(xmlData,i, this.options.removeNSPrefix);
+ let tagName= result.tagName;
+ const rawTagName = result.rawTagName;
+ let tagExp = result.tagExp;
+ let attrExpPresent = result.attrExpPresent;
+ let closeIndex = result.closeIndex;
-function lte(i, y) {
- return i <= y;
-}
-function gte(i, y) {
- return i >= y;
-}
+ if (this.options.transformTagName) {
+ //console.log(tagExp, tagName)
+ const newTagName = this.options.transformTagName(tagName);
+ if(tagExp === tagName) {
+ tagExp = newTagName
+ }
+ tagName = newTagName;
+ }
+
+ //save text as child node
+ if (currentNode && textData) {
+ if(currentNode.tagname !== '!xml'){
+ //when nested tag is found
+ textData = this.saveTextToParentTag(textData, currentNode, jPath, false);
+ }
+ }
-function expand(str, isTop) {
- var expansions = [];
+ //check if last tag was unpaired tag
+ const lastTag = currentNode;
+ if(lastTag && this.options.unpairedTags.indexOf(lastTag.tagname) !== -1 ){
+ currentNode = this.tagsNodeStack.pop();
+ jPath = jPath.substring(0, jPath.lastIndexOf("."));
+ }
+ if(tagName !== xmlObj.tagname){
+ jPath += jPath ? "." + tagName : tagName;
+ }
+ const startIndex = i;
+ if (this.isItStopNode(this.stopNodesExact, this.stopNodesWildcard, jPath, tagName)) {
+ let tagContent = "";
+ //self-closing tag
+ if(tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1){
+ if(tagName[tagName.length - 1] === "/"){ //remove trailing '/'
+ tagName = tagName.substr(0, tagName.length - 1);
+ jPath = jPath.substr(0, jPath.length - 1);
+ tagExp = tagName;
+ }else{
+ tagExp = tagExp.substr(0, tagExp.length - 1);
+ }
+ i = result.closeIndex;
+ }
+ //unpaired tag
+ else if(this.options.unpairedTags.indexOf(tagName) !== -1){
+
+ i = result.closeIndex;
+ }
+ //normal tag
+ else{
+ //read until closing tag is found
+ const result = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1);
+ if(!result) throw new Error(`Unexpected end of ${rawTagName}`);
+ i = result.i;
+ tagContent = result.tagContent;
+ }
- var m = balanced('{', '}', str);
- if (!m || /\$$/.test(m.pre)) return [str];
+ const childNode = new XmlNode(tagName);
- var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
- var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
- var isSequence = isNumericSequence || isAlphaSequence;
- var isOptions = m.body.indexOf(',') >= 0;
- if (!isSequence && !isOptions) {
- // {a},b}
- if (m.post.match(/,.*\}/)) {
- str = m.pre + '{' + m.body + escClose + m.post;
- return expand(str);
- }
- return [str];
- }
+ if(tagName !== tagExp && attrExpPresent){
+ childNode[":@"] = this.buildAttributesMap(tagExp, jPath
+ );
+ }
+ if(tagContent) {
+ tagContent = this.parseTextData(tagContent, tagName, jPath, true, attrExpPresent, true, true);
+ }
+
+ jPath = jPath.substr(0, jPath.lastIndexOf("."));
+ childNode.add(this.options.textNodeName, tagContent);
+
+ this.addChild(currentNode, childNode, jPath, startIndex);
+ }else{
+ //selfClosing tag
+ if(tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1){
+ if(tagName[tagName.length - 1] === "/"){ //remove trailing '/'
+ tagName = tagName.substr(0, tagName.length - 1);
+ jPath = jPath.substr(0, jPath.length - 1);
+ tagExp = tagName;
+ }else{
+ tagExp = tagExp.substr(0, tagExp.length - 1);
+ }
+
+ if(this.options.transformTagName) {
+ const newTagName = this.options.transformTagName(tagName);
+ if(tagExp === tagName) {
+ tagExp = newTagName
+ }
+ tagName = newTagName;
+ }
- var n;
- if (isSequence) {
- n = m.body.split(/\.\./);
- } else {
- n = parseCommaParts(m.body);
- if (n.length === 1) {
- // x{{a,b}}y ==> x{a}y x{b}y
- n = expand(n[0], false).map(embrace);
- if (n.length === 1) {
- var post = m.post.length
- ? expand(m.post, false)
- : [''];
- return post.map(function(p) {
- return m.pre + n[0] + p;
- });
+ const childNode = new XmlNode(tagName);
+ if(tagName !== tagExp && attrExpPresent){
+ childNode[":@"] = this.buildAttributesMap(tagExp, jPath);
+ }
+ this.addChild(currentNode, childNode, jPath, startIndex);
+ jPath = jPath.substr(0, jPath.lastIndexOf("."));
+ }
+ //opening tag
+ else{
+ const childNode = new XmlNode( tagName);
+ this.tagsNodeStack.push(currentNode);
+
+ if(tagName !== tagExp && attrExpPresent){
+ childNode[":@"] = this.buildAttributesMap(tagExp, jPath);
+ }
+ this.addChild(currentNode, childNode, jPath, startIndex);
+ currentNode = childNode;
+ }
+ textData = "";
+ i = closeIndex;
+ }
}
+ }else{
+ textData += xmlData[i];
}
}
+ return xmlObj.child;
+}
- // at this point, n is the parts, and we know it's not a comma set
- // with a single entry.
-
- // no need to expand pre, since it is guaranteed to be free of brace-sets
- var pre = m.pre;
- var post = m.post.length
- ? expand(m.post, false)
- : [''];
+function addChild(currentNode, childNode, jPath, startIndex){
+ // unset startIndex if not requested
+ if (!this.options.captureMetaData) startIndex = undefined;
+ const result = this.options.updateTag(childNode.tagname, jPath, childNode[":@"])
+ if(result === false){
+ //do nothing
+ } else if(typeof result === "string"){
+ childNode.tagname = result
+ currentNode.addChild(childNode, startIndex);
+ }else{
+ currentNode.addChild(childNode, startIndex);
+ }
+}
- var N;
+const OrderedObjParser_replaceEntitiesValue = function(val){
- if (isSequence) {
- var x = numeric(n[0]);
- var y = numeric(n[1]);
- var width = Math.max(n[0].length, n[1].length)
- var incr = n.length == 3
- ? Math.abs(numeric(n[2]))
- : 1;
- var test = lte;
- var reverse = y < x;
- if (reverse) {
- incr *= -1;
- test = gte;
+ if(this.options.processEntities){
+ for(let entityName in this.docTypeEntities){
+ const entity = this.docTypeEntities[entityName];
+ val = val.replace( entity.regx, entity.val);
}
- var pad = n.some(isPadded);
+ for(let entityName in this.lastEntities){
+ const entity = this.lastEntities[entityName];
+ val = val.replace( entity.regex, entity.val);
+ }
+ if(this.options.htmlEntities){
+ for(let entityName in this.htmlEntities){
+ const entity = this.htmlEntities[entityName];
+ val = val.replace( entity.regex, entity.val);
+ }
+ }
+ val = val.replace( this.ampEntity.regex, this.ampEntity.val);
+ }
+ return val;
+}
+function saveTextToParentTag(textData, currentNode, jPath, isLeafNode) {
+ if (textData) { //store previously collected data as textNode
+ if(isLeafNode === undefined) isLeafNode = currentNode.child.length === 0
+
+ textData = this.parseTextData(textData,
+ currentNode.tagname,
+ jPath,
+ false,
+ currentNode[":@"] ? Object.keys(currentNode[":@"]).length !== 0 : false,
+ isLeafNode);
- N = [];
+ if (textData !== undefined && textData !== "")
+ currentNode.add(this.options.textNodeName, textData);
+ textData = "";
+ }
+ return textData;
+}
- for (var i = x; test(i, y); i += incr) {
- var c;
- if (isAlphaSequence) {
- c = String.fromCharCode(i);
- if (c === '\\')
- c = '';
- } else {
- c = String(i);
- if (pad) {
- var need = width - c.length;
- if (need > 0) {
- var z = new Array(need + 1).join('0');
- if (i < 0)
- c = '-' + z + c.slice(1);
- else
- c = z + c;
+//TODO: use jPath to simplify the logic
+/**
+ * @param {Set} stopNodesExact
+ * @param {Set} stopNodesWildcard
+ * @param {string} jPath
+ * @param {string} currentTagName
+ */
+function isItStopNode(stopNodesExact, stopNodesWildcard, jPath, currentTagName){
+ if(stopNodesWildcard && stopNodesWildcard.has(currentTagName)) return true;
+ if(stopNodesExact && stopNodesExact.has(jPath)) return true;
+ return false;
+}
+
+/**
+ * Returns the tag Expression and where it is ending handling single-double quotes situation
+ * @param {string} xmlData
+ * @param {number} i starting index
+ * @returns
+ */
+function tagExpWithClosingIndex(xmlData, i, closingChar = ">"){
+ let attrBoundary;
+ let tagExp = "";
+ for (let index = i; index < xmlData.length; index++) {
+ let ch = xmlData[index];
+ if (attrBoundary) {
+ if (ch === attrBoundary) attrBoundary = "";//reset
+ } else if (ch === '"' || ch === "'") {
+ attrBoundary = ch;
+ } else if (ch === closingChar[0]) {
+ if(closingChar[1]){
+ if(xmlData[index + 1] === closingChar[1]){
+ return {
+ data: tagExp,
+ index: index
}
}
+ }else{
+ return {
+ data: tagExp,
+ index: index
+ }
}
- N.push(c);
+ } else if (ch === '\t') {
+ ch = " "
}
- } else {
- N = concatMap(n, function(el) { return expand(el, false) });
+ tagExp += ch;
}
+}
- for (var j = 0; j < N.length; j++) {
- for (var k = 0; k < post.length; k++) {
- var expansion = pre + N[j] + post[k];
- if (!isTop || isSequence || expansion)
- expansions.push(expansion);
- }
+function findClosingIndex(xmlData, str, i, errMsg){
+ const closingIndex = xmlData.indexOf(str, i);
+ if(closingIndex === -1){
+ throw new Error(errMsg)
+ }else{
+ return closingIndex + str.length - 1;
}
-
- return expansions;
}
+function readTagExp(xmlData,i, removeNSPrefix, closingChar = ">"){
+ const result = tagExpWithClosingIndex(xmlData, i+1, closingChar);
+ if(!result) return;
+ let tagExp = result.data;
+ const closeIndex = result.index;
+ const separatorIndex = tagExp.search(/\s/);
+ let tagName = tagExp;
+ let attrExpPresent = true;
+ if(separatorIndex !== -1){//separate tag name and attributes expression
+ tagName = tagExp.substring(0, separatorIndex);
+ tagExp = tagExp.substring(separatorIndex + 1).trimStart();
+ }
+ const rawTagName = tagName;
+ if(removeNSPrefix){
+ const colonIndex = tagName.indexOf(":");
+ if(colonIndex !== -1){
+ tagName = tagName.substr(colonIndex+1);
+ attrExpPresent = tagName !== result.data.substr(colonIndex + 1);
+ }
+ }
-/***/ }),
+ return {
+ tagName: tagName,
+ tagExp: tagExp,
+ closeIndex: closeIndex,
+ attrExpPresent: attrExpPresent,
+ rawTagName: rawTagName,
+ }
+}
+/**
+ * find paired tag for a stop node
+ * @param {string} xmlData
+ * @param {string} tagName
+ * @param {number} i
+ */
+function readStopNodeData(xmlData, tagName, i){
+ const startIndex = i;
+ // Starting at 1 since we already have an open tag
+ let openTagCount = 1;
-/***/ 7087:
-/***/ ((module) => {
+ for (; i < xmlData.length; i++) {
+ if( xmlData[i] === "<"){
+ if (xmlData[i+1] === "/") {//close tag
+ const closeIndex = findClosingIndex(xmlData, ">", i, `${tagName} is not closed`);
+ let closeTagName = xmlData.substring(i+2,closeIndex).trim();
+ if(closeTagName === tagName){
+ openTagCount--;
+ if (openTagCount === 0) {
+ return {
+ tagContent: xmlData.substring(startIndex, i),
+ i : closeIndex
+ }
+ }
+ }
+ i=closeIndex;
+ } else if(xmlData[i+1] === '?') {
+ const closeIndex = findClosingIndex(xmlData, "?>", i+1, "StopNode is not closed.")
+ i=closeIndex;
+ } else if(xmlData.substr(i + 1, 3) === '!--') {
+ const closeIndex = findClosingIndex(xmlData, "-->", i+3, "StopNode is not closed.")
+ i=closeIndex;
+ } else if(xmlData.substr(i + 1, 2) === '![') {
+ const closeIndex = findClosingIndex(xmlData, "]]>", i, "StopNode is not closed.") - 2;
+ i=closeIndex;
+ } else {
+ const tagData = readTagExp(xmlData, i, '>')
-module.exports = function (xs, fn) {
- var res = [];
- for (var i = 0; i < xs.length; i++) {
- var x = fn(xs[i], i);
- if (isArray(x)) res.push.apply(res, x);
- else res.push(x);
+ if (tagData) {
+ const openTagName = tagData && tagData.tagName;
+ if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length-1] !== "/") {
+ openTagCount++;
+ }
+ i=tagData.closeIndex;
+ }
+ }
+ }
+ }//end for loop
+}
+
+function parseValue(val, shouldParse, options) {
+ if (shouldParse && typeof val === 'string') {
+ //console.log(options)
+ const newval = val.trim();
+ if(newval === 'true' ) return true;
+ else if(newval === 'false' ) return false;
+ else return toNumber(val, options);
+ } else {
+ if (isExist(val)) {
+ return val;
+ } else {
+ return '';
}
- return res;
-};
+ }
+}
-var isArray = Array.isArray || function (xs) {
- return Object.prototype.toString.call(xs) === '[object Array]';
-};
+;// CONCATENATED MODULE: ./node_modules/fast-xml-parser/src/xmlparser/node2json.js
-/***/ }),
-/***/ 6110:
-/***/ ((module, exports, __nccwpck_require__) => {
-/* eslint-env browser */
+const node2json_METADATA_SYMBOL = XmlNode.getMetaDataSymbol();
/**
- * This is the web browser implementation of `debug()`.
+ *
+ * @param {array} node
+ * @param {any} options
+ * @returns
*/
-
-exports.formatArgs = formatArgs;
-exports.save = save;
-exports.load = load;
-exports.useColors = useColors;
-exports.storage = localstorage();
-exports.destroy = (() => {
- let warned = false;
-
- return () => {
- if (!warned) {
- warned = true;
- console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
- }
- };
-})();
+function prettify(node, options){
+ return compress( node, options);
+}
/**
- * Colors.
+ *
+ * @param {array} arr
+ * @param {object} options
+ * @param {string} jPath
+ * @returns object
*/
+function compress(arr, options, jPath){
+ let text;
+ const compressedObj = {};
+ for (let i = 0; i < arr.length; i++) {
+ const tagObj = arr[i];
+ const property = node2json_propName(tagObj);
+ let newJpath = "";
+ if(jPath === undefined) newJpath = property;
+ else newJpath = jPath + "." + property;
-exports.colors = [
- '#0000CC',
- '#0000FF',
- '#0033CC',
- '#0033FF',
- '#0066CC',
- '#0066FF',
- '#0099CC',
- '#0099FF',
- '#00CC00',
- '#00CC33',
- '#00CC66',
- '#00CC99',
- '#00CCCC',
- '#00CCFF',
- '#3300CC',
- '#3300FF',
- '#3333CC',
- '#3333FF',
- '#3366CC',
- '#3366FF',
- '#3399CC',
- '#3399FF',
- '#33CC00',
- '#33CC33',
- '#33CC66',
- '#33CC99',
- '#33CCCC',
- '#33CCFF',
- '#6600CC',
- '#6600FF',
- '#6633CC',
- '#6633FF',
- '#66CC00',
- '#66CC33',
- '#9900CC',
- '#9900FF',
- '#9933CC',
- '#9933FF',
- '#99CC00',
- '#99CC33',
- '#CC0000',
- '#CC0033',
- '#CC0066',
- '#CC0099',
- '#CC00CC',
- '#CC00FF',
- '#CC3300',
- '#CC3333',
- '#CC3366',
- '#CC3399',
- '#CC33CC',
- '#CC33FF',
- '#CC6600',
- '#CC6633',
- '#CC9900',
- '#CC9933',
- '#CCCC00',
- '#CCCC33',
- '#FF0000',
- '#FF0033',
- '#FF0066',
- '#FF0099',
- '#FF00CC',
- '#FF00FF',
- '#FF3300',
- '#FF3333',
- '#FF3366',
- '#FF3399',
- '#FF33CC',
- '#FF33FF',
- '#FF6600',
- '#FF6633',
- '#FF9900',
- '#FF9933',
- '#FFCC00',
- '#FFCC33'
-];
+ if(property === options.textNodeName){
+ if(text === undefined) text = tagObj[property];
+ else text += "" + tagObj[property];
+ }else if(property === undefined){
+ continue;
+ }else if(tagObj[property]){
+
+ let val = compress(tagObj[property], options, newJpath);
+ const isLeaf = isLeafTag(val, options);
+ if (tagObj[node2json_METADATA_SYMBOL] !== undefined) {
+ val[node2json_METADATA_SYMBOL] = tagObj[node2json_METADATA_SYMBOL]; // copy over metadata
+ }
-/**
- * Currently only WebKit-based Web Inspectors, Firefox >= v31,
- * and the Firebug extension (any Firefox version) are known
- * to support "%c" CSS customizations.
- *
- * TODO: add a `localStorage` variable to explicitly enable/disable colors
- */
+ if(tagObj[":@"]){
+ assignAttributes( val, tagObj[":@"], newJpath, options);
+ }else if(Object.keys(val).length === 1 && val[options.textNodeName] !== undefined && !options.alwaysCreateTextNode){
+ val = val[options.textNodeName];
+ }else if(Object.keys(val).length === 0){
+ if(options.alwaysCreateTextNode) val[options.textNodeName] = "";
+ else val = "";
+ }
-// eslint-disable-next-line complexity
-function useColors() {
- // NB: In an Electron preload script, document will be defined but not fully
- // initialized. Since we know we're in Chrome, we'll just detect this case
- // explicitly
- if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
- return true;
- }
+ if(compressedObj[property] !== undefined && compressedObj.hasOwnProperty(property)) {
+ if(!Array.isArray(compressedObj[property])) {
+ compressedObj[property] = [ compressedObj[property] ];
+ }
+ compressedObj[property].push(val);
+ }else{
+ //TODO: if a node is not an array, then check if it should be an array
+ //also determine if it is a leaf node
+ if (options.isArray(property, newJpath, isLeaf )) {
+ compressedObj[property] = [val];
+ }else{
+ compressedObj[property] = val;
+ }
+ }
+ }
+
+ }
+ // if(text && text.length > 0) compressedObj[options.textNodeName] = text;
+ if(typeof text === "string"){
+ if(text.length > 0) compressedObj[options.textNodeName] = text;
+ }else if(text !== undefined) compressedObj[options.textNodeName] = text;
+ return compressedObj;
+}
- // Internet Explorer and Edge do not support colors.
- if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
- return false;
- }
+function node2json_propName(obj){
+ const keys = Object.keys(obj);
+ for (let i = 0; i < keys.length; i++) {
+ const key = keys[i];
+ if(key !== ":@") return key;
+ }
+}
- let m;
+function assignAttributes(obj, attrMap, jpath, options){
+ if (attrMap) {
+ const keys = Object.keys(attrMap);
+ const len = keys.length; //don't make it inline
+ for (let i = 0; i < len; i++) {
+ const atrrName = keys[i];
+ if (options.isArray(atrrName, jpath + "." + atrrName, true, true)) {
+ obj[atrrName] = [ attrMap[atrrName] ];
+ } else {
+ obj[atrrName] = attrMap[atrrName];
+ }
+ }
+ }
+}
- // Is webkit? http://stackoverflow.com/a/16459606/376773
- // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
- // eslint-disable-next-line no-return-assign
- return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
- // Is firebug? http://stackoverflow.com/a/398120/376773
- (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
- // Is firefox >= v31?
- // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
- (typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31) ||
- // Double check webkit in userAgent just in case we are in a worker
- (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
+function isLeafTag(obj, options){
+ const { textNodeName } = options;
+ const propCount = Object.keys(obj).length;
+
+ if (propCount === 0) {
+ return true;
+ }
+
+ if (
+ propCount === 1 &&
+ (obj[textNodeName] || typeof obj[textNodeName] === "boolean" || obj[textNodeName] === 0)
+ ) {
+ return true;
+ }
+
+ return false;
}
-/**
- * Colorize log arguments if enabled.
- *
- * @api public
- */
+;// CONCATENATED MODULE: ./node_modules/fast-xml-parser/src/xmlparser/XMLParser.js
-function formatArgs(args) {
- args[0] = (this.useColors ? '%c' : '') +
- this.namespace +
- (this.useColors ? ' %c' : ' ') +
- args[0] +
- (this.useColors ? '%c ' : ' ') +
- '+' + module.exports.humanize(this.diff);
- if (!this.useColors) {
- return;
- }
- const c = 'color: ' + this.color;
- args.splice(1, 0, c, 'color: inherit');
- // The final "%c" is somewhat tricky, because there could be other
- // arguments passed either before or after the %c, so we need to
- // figure out the correct index to insert the CSS into
- let index = 0;
- let lastC = 0;
- args[0].replace(/%[a-zA-Z%]/g, match => {
- if (match === '%%') {
- return;
- }
- index++;
- if (match === '%c') {
- // We only are interested in the *last* %c
- // (the user may have provided their own)
- lastC = index;
- }
- });
- args.splice(lastC, 0, c);
+
+class XMLParser{
+
+ constructor(options){
+ this.externalEntities = {};
+ this.options = buildOptions(options);
+
+ }
+ /**
+ * Parse XML dats to JS object
+ * @param {string|Uint8Array} xmlData
+ * @param {boolean|Object} validationOption
+ */
+ parse(xmlData,validationOption){
+ if(typeof xmlData !== "string" && xmlData.toString){
+ xmlData = xmlData.toString();
+ }else if(typeof xmlData !== "string"){
+ throw new Error("XML data is accepted in String or Bytes[] form.")
+ }
+
+ if( validationOption){
+ if(validationOption === true) validationOption = {}; //validate with default options
+
+ const result = validate(xmlData, validationOption);
+ if (result !== true) {
+ throw Error( `${result.err.msg}:${result.err.line}:${result.err.col}` )
+ }
+ }
+ const orderedObjParser = new OrderedObjParser(this.options);
+ orderedObjParser.addExternalEntities(this.externalEntities);
+ const orderedResult = orderedObjParser.parseXml(xmlData);
+ if(this.options.preserveOrder || orderedResult === undefined) return orderedResult;
+ else return prettify(orderedResult, this.options);
+ }
+
+ /**
+ * Add Entity which is not by default supported by this library
+ * @param {string} key
+ * @param {string} value
+ */
+ addEntity(key, value){
+ if(value.indexOf("&") !== -1){
+ throw new Error("Entity value can't have '&'")
+ }else if(key.indexOf("&") !== -1 || key.indexOf(";") !== -1){
+ throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'")
+ }else if(value === "&"){
+ throw new Error("An entity with value '&' is not permitted");
+ }else{
+ this.externalEntities[key] = value;
+ }
+ }
+
+ /**
+ * Returns a Symbol that can be used to access the metadata
+ * property on a node.
+ *
+ * If Symbol is not available in the environment, an ordinary property is used
+ * and the name of the property is here returned.
+ *
+ * The XMLMetaData property is only present when `captureMetaData`
+ * is true in the options.
+ */
+ static getMetaDataSymbol() {
+ return XmlNode.getMetaDataSymbol();
+ }
}
+;// CONCATENATED MODULE: ./node_modules/@azure/core-xml/dist/esm/xml.common.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
/**
- * Invokes `console.debug()` when available.
- * No-op when `console.debug` is not a "function".
- * If `console.debug` is not available, falls back
- * to `console.log`.
- *
- * @api public
+ * Default key used to access the XML attributes.
*/
-exports.log = console.debug || console.log || (() => {});
+const xml_common_XML_ATTRKEY = "$";
+/**
+ * Default key used to access the XML value content.
+ */
+const xml_common_XML_CHARKEY = "_";
+//# sourceMappingURL=xml.common.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/core-xml/dist/esm/xml.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+
+function getCommonOptions(options) {
+ var _a;
+ return {
+ attributesGroupName: xml_common_XML_ATTRKEY,
+ textNodeName: (_a = options.xmlCharKey) !== null && _a !== void 0 ? _a : xml_common_XML_CHARKEY,
+ ignoreAttributes: false,
+ suppressBooleanAttributes: false,
+ };
+}
+function getSerializerOptions(options = {}) {
+ var _a, _b;
+ return Object.assign(Object.assign({}, getCommonOptions(options)), { attributeNamePrefix: "@_", format: true, suppressEmptyNode: true, indentBy: "", rootNodeName: (_a = options.rootName) !== null && _a !== void 0 ? _a : "root", cdataPropName: (_b = options.cdataPropName) !== null && _b !== void 0 ? _b : "__cdata" });
+}
+function getParserOptions(options = {}) {
+ return Object.assign(Object.assign({}, getCommonOptions(options)), { parseAttributeValue: false, parseTagValue: false, attributeNamePrefix: "", stopNodes: options.stopNodes, processEntities: true, trimValues: false });
+}
/**
- * Save `namespaces`.
- *
- * @param {String} namespaces
- * @api private
+ * Converts given JSON object to XML string
+ * @param obj - JSON object to be converted into XML string
+ * @param opts - Options that govern the XML building of given JSON object
+ * `rootName` indicates the name of the root element in the resulting XML
*/
-function save(namespaces) {
- try {
- if (namespaces) {
- exports.storage.setItem('debug', namespaces);
- } else {
- exports.storage.removeItem('debug');
- }
- } catch (error) {
- // Swallow
- // XXX (@Qix-) should we be logging these?
- }
+function stringifyXML(obj, opts = {}) {
+ const parserOptions = getSerializerOptions(opts);
+ const j2x = new Builder(parserOptions);
+ const node = { [parserOptions.rootNodeName]: obj };
+ const xmlData = j2x.build(node);
+ return `${xmlData}`.replace(/\n/g, "");
}
-
/**
- * Load `namespaces`.
- *
- * @return {String} returns the previously persisted debug modes
- * @api private
+ * Converts given XML string into JSON
+ * @param str - String containing the XML content to be parsed into JSON
+ * @param opts - Options that govern the parsing of given xml string
+ * `includeRoot` indicates whether the root element is to be included or not in the output
*/
-function load() {
- let r;
- try {
- r = exports.storage.getItem('debug') || exports.storage.getItem('DEBUG') ;
- } catch (error) {
- // Swallow
- // XXX (@Qix-) should we be logging these?
- }
-
- // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
- if (!r && typeof process !== 'undefined' && 'env' in process) {
- r = process.env.DEBUG;
- }
-
- return r;
+async function parseXML(str, opts = {}) {
+ if (!str) {
+ throw new Error("Document is empty");
+ }
+ const validation = XMLValidator.validate(str);
+ if (validation !== true) {
+ throw validation;
+ }
+ const parser = new XMLParser(getParserOptions(opts));
+ const parsedXml = parser.parse(str);
+ // Remove the node.
+ // This is a change in behavior on fxp v4. Issue #424
+ if (parsedXml["?xml"]) {
+ delete parsedXml["?xml"];
+ }
+ if (!opts.includeRoot) {
+ for (const key of Object.keys(parsedXml)) {
+ const value = parsedXml[key];
+ return typeof value === "object" ? Object.assign({}, value) : value;
+ }
+ }
+ return parsedXml;
}
+//# sourceMappingURL=xml.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/storage-blob/dist/esm/log.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
/**
- * Localstorage attempts to return the localstorage.
- *
- * This is necessary because safari throws
- * when a user disables cookies/localstorage
- * and you attempt to access it.
- *
- * @return {LocalStorage}
- * @api private
+ * The `@azure/logger` configuration for this package.
*/
+const storage_blob_dist_esm_log_logger = esm_createClientLogger("storage-blob");
+//# sourceMappingURL=log.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/BuffersStream.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
-function localstorage() {
- try {
- // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
- // The Browser also has localStorage in the global context.
- return localStorage;
- } catch (error) {
- // Swallow
- // XXX (@Qix-) should we be logging these?
- }
+/**
+ * This class generates a readable stream from the data in an array of buffers.
+ */
+class BuffersStream extends external_node_stream_.Readable {
+ buffers;
+ byteLength;
+ /**
+ * The offset of data to be read in the current buffer.
+ */
+ byteOffsetInCurrentBuffer;
+ /**
+ * The index of buffer to be read in the array of buffers.
+ */
+ bufferIndex;
+ /**
+ * The total length of data already read.
+ */
+ pushedBytesLength;
+ /**
+ * Creates an instance of BuffersStream that will emit the data
+ * contained in the array of buffers.
+ *
+ * @param buffers - Array of buffers containing the data
+ * @param byteLength - The total length of data contained in the buffers
+ */
+ constructor(buffers, byteLength, options) {
+ super(options);
+ this.buffers = buffers;
+ this.byteLength = byteLength;
+ this.byteOffsetInCurrentBuffer = 0;
+ this.bufferIndex = 0;
+ this.pushedBytesLength = 0;
+ // check byteLength is no larger than buffers[] total length
+ let buffersLength = 0;
+ for (const buf of this.buffers) {
+ buffersLength += buf.byteLength;
+ }
+ if (buffersLength < this.byteLength) {
+ throw new Error("Data size shouldn't be larger than the total length of buffers.");
+ }
+ }
+ /**
+ * Internal _read() that will be called when the stream wants to pull more data in.
+ *
+ * @param size - Optional. The size of data to be read
+ */
+ _read(size) {
+ if (this.pushedBytesLength >= this.byteLength) {
+ this.push(null);
+ }
+ if (!size) {
+ size = this.readableHighWaterMark;
+ }
+ const outBuffers = [];
+ let i = 0;
+ while (i < size && this.pushedBytesLength < this.byteLength) {
+ // The last buffer may be longer than the data it contains.
+ const remainingDataInAllBuffers = this.byteLength - this.pushedBytesLength;
+ const remainingCapacityInThisBuffer = this.buffers[this.bufferIndex].byteLength - this.byteOffsetInCurrentBuffer;
+ const remaining = Math.min(remainingCapacityInThisBuffer, remainingDataInAllBuffers);
+ if (remaining > size - i) {
+ // chunkSize = size - i
+ const end = this.byteOffsetInCurrentBuffer + size - i;
+ outBuffers.push(this.buffers[this.bufferIndex].slice(this.byteOffsetInCurrentBuffer, end));
+ this.pushedBytesLength += size - i;
+ this.byteOffsetInCurrentBuffer = end;
+ i = size;
+ break;
+ }
+ else {
+ // chunkSize = remaining
+ const end = this.byteOffsetInCurrentBuffer + remaining;
+ outBuffers.push(this.buffers[this.bufferIndex].slice(this.byteOffsetInCurrentBuffer, end));
+ if (remaining === remainingCapacityInThisBuffer) {
+ // this.buffers[this.bufferIndex] used up, shift to next one
+ this.byteOffsetInCurrentBuffer = 0;
+ this.bufferIndex++;
+ }
+ else {
+ this.byteOffsetInCurrentBuffer = end;
+ }
+ this.pushedBytesLength += remaining;
+ i += remaining;
+ }
+ }
+ if (outBuffers.length > 1) {
+ this.push(Buffer.concat(outBuffers));
+ }
+ else if (outBuffers.length === 1) {
+ this.push(outBuffers[0]);
+ }
+ }
}
+//# sourceMappingURL=BuffersStream.js.map
+// EXTERNAL MODULE: external "node:buffer"
+var external_node_buffer_ = __nccwpck_require__(4573);
+;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/PooledBuffer.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
-module.exports = __nccwpck_require__(897)(exports);
-
-const {formatters} = module.exports;
/**
- * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
+ * maxBufferLength is max size of each buffer in the pooled buffers.
*/
-
-formatters.j = function (v) {
- try {
- return JSON.stringify(v);
- } catch (error) {
- return '[UnexpectedJSONParseError]: ' + error.message;
- }
-};
-
-
-/***/ }),
-
-/***/ 897:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+const maxBufferLength = external_node_buffer_.constants.MAX_LENGTH;
+/**
+ * This class provides a buffer container which conceptually has no hard size limit.
+ * It accepts a capacity, an array of input buffers and the total length of input data.
+ * It will allocate an internal "buffer" of the capacity and fill the data in the input buffers
+ * into the internal "buffer" serially with respect to the total length.
+ * Then by calling PooledBuffer.getReadableStream(), you can get a readable stream
+ * assembled from all the data in the internal "buffer".
+ */
+class PooledBuffer {
+ /**
+ * Internal buffers used to keep the data.
+ * Each buffer has a length of the maxBufferLength except last one.
+ */
+ buffers = [];
+ /**
+ * The total size of internal buffers.
+ */
+ capacity;
+ /**
+ * The total size of data contained in internal buffers.
+ */
+ _size;
+ /**
+ * The size of the data contained in the pooled buffers.
+ */
+ get size() {
+ return this._size;
+ }
+ constructor(capacity, buffers, totalLength) {
+ this.capacity = capacity;
+ this._size = 0;
+ // allocate
+ const bufferNum = Math.ceil(capacity / maxBufferLength);
+ for (let i = 0; i < bufferNum; i++) {
+ let len = i === bufferNum - 1 ? capacity % maxBufferLength : maxBufferLength;
+ if (len === 0) {
+ len = maxBufferLength;
+ }
+ this.buffers.push(Buffer.allocUnsafe(len));
+ }
+ if (buffers) {
+ this.fill(buffers, totalLength);
+ }
+ }
+ /**
+ * Fill the internal buffers with data in the input buffers serially
+ * with respect to the total length and the total capacity of the internal buffers.
+ * Data copied will be shift out of the input buffers.
+ *
+ * @param buffers - Input buffers containing the data to be filled in the pooled buffer
+ * @param totalLength - Total length of the data to be filled in.
+ *
+ */
+ fill(buffers, totalLength) {
+ this._size = Math.min(this.capacity, totalLength);
+ let i = 0, j = 0, targetOffset = 0, sourceOffset = 0, totalCopiedNum = 0;
+ while (totalCopiedNum < this._size) {
+ const source = buffers[i];
+ const target = this.buffers[j];
+ const copiedNum = source.copy(target, targetOffset, sourceOffset);
+ totalCopiedNum += copiedNum;
+ sourceOffset += copiedNum;
+ targetOffset += copiedNum;
+ if (sourceOffset === source.length) {
+ i++;
+ sourceOffset = 0;
+ }
+ if (targetOffset === target.length) {
+ j++;
+ targetOffset = 0;
+ }
+ }
+ // clear copied from source buffers
+ buffers.splice(0, i);
+ if (buffers.length > 0) {
+ buffers[0] = buffers[0].slice(sourceOffset);
+ }
+ }
+ /**
+ * Get the readable stream assembled from all the data in the internal buffers.
+ *
+ */
+ getReadableStream() {
+ return new BuffersStream(this.buffers, this.size);
+ }
+}
+//# sourceMappingURL=PooledBuffer.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/BufferScheduler.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
/**
- * This is the common logic for both the Node.js and web browser
- * implementations of `debug()`.
+ * This class accepts a Node.js Readable stream as input, and keeps reading data
+ * from the stream into the internal buffer structure, until it reaches maxBuffers.
+ * Every available buffer will try to trigger outgoingHandler.
+ *
+ * The internal buffer structure includes an incoming buffer array, and a outgoing
+ * buffer array. The incoming buffer array includes the "empty" buffers can be filled
+ * with new incoming data. The outgoing array includes the filled buffers to be
+ * handled by outgoingHandler. Every above buffer size is defined by parameter bufferSize.
+ *
+ * NUM_OF_ALL_BUFFERS = BUFFERS_IN_INCOMING + BUFFERS_IN_OUTGOING + BUFFERS_UNDER_HANDLING
+ *
+ * NUM_OF_ALL_BUFFERS lesser than or equal to maxBuffers
+ *
+ * PERFORMANCE IMPROVEMENT TIPS:
+ * 1. Input stream highWaterMark is better to set a same value with bufferSize
+ * parameter, which will avoid Buffer.concat() operations.
+ * 2. concurrency should set a smaller value than maxBuffers, which is helpful to
+ * reduce the possibility when a outgoing handler waits for the stream data.
+ * in this situation, outgoing handlers are blocked.
+ * Outgoing queue shouldn't be empty.
*/
+class BufferScheduler {
+ /**
+ * Size of buffers in incoming and outgoing queues. This class will try to align
+ * data read from Readable stream into buffer chunks with bufferSize defined.
+ */
+ bufferSize;
+ /**
+ * How many buffers can be created or maintained.
+ */
+ maxBuffers;
+ /**
+ * A Node.js Readable stream.
+ */
+ readable;
+ /**
+ * OutgoingHandler is an async function triggered by BufferScheduler when there
+ * are available buffers in outgoing array.
+ */
+ outgoingHandler;
+ /**
+ * An internal event emitter.
+ */
+ emitter = new external_events_.EventEmitter();
+ /**
+ * Concurrency of executing outgoingHandlers. (0 lesser than concurrency lesser than or equal to maxBuffers)
+ */
+ concurrency;
+ /**
+ * An internal offset marker to track data offset in bytes of next outgoingHandler.
+ */
+ offset = 0;
+ /**
+ * An internal marker to track whether stream is end.
+ */
+ isStreamEnd = false;
+ /**
+ * An internal marker to track whether stream or outgoingHandler returns error.
+ */
+ isError = false;
+ /**
+ * How many handlers are executing.
+ */
+ executingOutgoingHandlers = 0;
+ /**
+ * Encoding of the input Readable stream which has string data type instead of Buffer.
+ */
+ encoding;
+ /**
+ * How many buffers have been allocated.
+ */
+ numBuffers = 0;
+ /**
+ * Because this class doesn't know how much data every time stream pops, which
+ * is defined by highWaterMarker of the stream. So BufferScheduler will cache
+ * data received from the stream, when data in unresolvedDataArray exceeds the
+ * blockSize defined, it will try to concat a blockSize of buffer, fill into available
+ * buffers from incoming and push to outgoing array.
+ */
+ unresolvedDataArray = [];
+ /**
+ * How much data consisted in unresolvedDataArray.
+ */
+ unresolvedLength = 0;
+ /**
+ * The array includes all the available buffers can be used to fill data from stream.
+ */
+ incoming = [];
+ /**
+ * The array (queue) includes all the buffers filled from stream data.
+ */
+ outgoing = [];
+ /**
+ * Creates an instance of BufferScheduler.
+ *
+ * @param readable - A Node.js Readable stream
+ * @param bufferSize - Buffer size of every maintained buffer
+ * @param maxBuffers - How many buffers can be allocated
+ * @param outgoingHandler - An async function scheduled to be
+ * triggered when a buffer fully filled
+ * with stream data
+ * @param concurrency - Concurrency of executing outgoingHandlers (>0)
+ * @param encoding - [Optional] Encoding of Readable stream when it's a string stream
+ */
+ constructor(readable, bufferSize, maxBuffers, outgoingHandler, concurrency, encoding) {
+ if (bufferSize <= 0) {
+ throw new RangeError(`bufferSize must be larger than 0, current is ${bufferSize}`);
+ }
+ if (maxBuffers <= 0) {
+ throw new RangeError(`maxBuffers must be larger than 0, current is ${maxBuffers}`);
+ }
+ if (concurrency <= 0) {
+ throw new RangeError(`concurrency must be larger than 0, current is ${concurrency}`);
+ }
+ this.bufferSize = bufferSize;
+ this.maxBuffers = maxBuffers;
+ this.readable = readable;
+ this.outgoingHandler = outgoingHandler;
+ this.concurrency = concurrency;
+ this.encoding = encoding;
+ }
+ /**
+ * Start the scheduler, will return error when stream of any of the outgoingHandlers
+ * returns error.
+ *
+ */
+ async do() {
+ return new Promise((resolve, reject) => {
+ this.readable.on("data", (data) => {
+ data = typeof data === "string" ? Buffer.from(data, this.encoding) : data;
+ this.appendUnresolvedData(data);
+ if (!this.resolveData()) {
+ this.readable.pause();
+ }
+ });
+ this.readable.on("error", (err) => {
+ this.emitter.emit("error", err);
+ });
+ this.readable.on("end", () => {
+ this.isStreamEnd = true;
+ this.emitter.emit("checkEnd");
+ });
+ this.emitter.on("error", (err) => {
+ this.isError = true;
+ this.readable.pause();
+ reject(err);
+ });
+ this.emitter.on("checkEnd", () => {
+ if (this.outgoing.length > 0) {
+ this.triggerOutgoingHandlers();
+ return;
+ }
+ if (this.isStreamEnd && this.executingOutgoingHandlers === 0) {
+ if (this.unresolvedLength > 0 && this.unresolvedLength < this.bufferSize) {
+ const buffer = this.shiftBufferFromUnresolvedDataArray();
+ this.outgoingHandler(() => buffer.getReadableStream(), buffer.size, this.offset)
+ .then(resolve)
+ .catch(reject);
+ }
+ else if (this.unresolvedLength >= this.bufferSize) {
+ return;
+ }
+ else {
+ resolve();
+ }
+ }
+ });
+ });
+ }
+ /**
+ * Insert a new data into unresolved array.
+ *
+ * @param data -
+ */
+ appendUnresolvedData(data) {
+ this.unresolvedDataArray.push(data);
+ this.unresolvedLength += data.length;
+ }
+ /**
+ * Try to shift a buffer with size in blockSize. The buffer returned may be less
+ * than blockSize when data in unresolvedDataArray is less than bufferSize.
+ *
+ */
+ shiftBufferFromUnresolvedDataArray(buffer) {
+ if (!buffer) {
+ buffer = new PooledBuffer(this.bufferSize, this.unresolvedDataArray, this.unresolvedLength);
+ }
+ else {
+ buffer.fill(this.unresolvedDataArray, this.unresolvedLength);
+ }
+ this.unresolvedLength -= buffer.size;
+ return buffer;
+ }
+ /**
+ * Resolve data in unresolvedDataArray. For every buffer with size in blockSize
+ * shifted, it will try to get (or allocate a buffer) from incoming, and fill it,
+ * then push it into outgoing to be handled by outgoing handler.
+ *
+ * Return false when available buffers in incoming are not enough, else true.
+ *
+ * @returns Return false when buffers in incoming are not enough, else true.
+ */
+ resolveData() {
+ while (this.unresolvedLength >= this.bufferSize) {
+ let buffer;
+ if (this.incoming.length > 0) {
+ buffer = this.incoming.shift();
+ this.shiftBufferFromUnresolvedDataArray(buffer);
+ }
+ else {
+ if (this.numBuffers < this.maxBuffers) {
+ buffer = this.shiftBufferFromUnresolvedDataArray();
+ this.numBuffers++;
+ }
+ else {
+ // No available buffer, wait for buffer returned
+ return false;
+ }
+ }
+ this.outgoing.push(buffer);
+ this.triggerOutgoingHandlers();
+ }
+ return true;
+ }
+ /**
+ * Try to trigger a outgoing handler for every buffer in outgoing. Stop when
+ * concurrency reaches.
+ */
+ async triggerOutgoingHandlers() {
+ let buffer;
+ do {
+ if (this.executingOutgoingHandlers >= this.concurrency) {
+ return;
+ }
+ buffer = this.outgoing.shift();
+ if (buffer) {
+ this.triggerOutgoingHandler(buffer);
+ }
+ } while (buffer);
+ }
+ /**
+ * Trigger a outgoing handler for a buffer shifted from outgoing.
+ *
+ * @param buffer -
+ */
+ async triggerOutgoingHandler(buffer) {
+ const bufferLength = buffer.size;
+ this.executingOutgoingHandlers++;
+ this.offset += bufferLength;
+ try {
+ await this.outgoingHandler(() => buffer.getReadableStream(), bufferLength, this.offset - bufferLength);
+ }
+ catch (err) {
+ this.emitter.emit("error", err);
+ return;
+ }
+ this.executingOutgoingHandlers--;
+ this.reuseBuffer(buffer);
+ this.emitter.emit("checkEnd");
+ }
+ /**
+ * Return buffer used by outgoing handler into incoming.
+ *
+ * @param buffer -
+ */
+ reuseBuffer(buffer) {
+ this.incoming.push(buffer);
+ if (!this.isError && this.resolveData() && !this.isStreamEnd) {
+ this.readable.resume();
+ }
+ }
+}
+//# sourceMappingURL=BufferScheduler.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/cache.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
-function setup(env) {
- createDebug.debug = createDebug;
- createDebug.default = createDebug;
- createDebug.coerce = coerce;
- createDebug.disable = disable;
- createDebug.enable = enable;
- createDebug.enabled = enabled;
- createDebug.humanize = __nccwpck_require__(744);
- createDebug.destroy = destroy;
+let _defaultHttpClient;
+function cache_getCachedDefaultHttpClient() {
+ if (!_defaultHttpClient) {
+ _defaultHttpClient = esm_defaultHttpClient_createDefaultHttpClient();
+ }
+ return _defaultHttpClient;
+}
+//# sourceMappingURL=cache.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/policies/RequestPolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+/**
+ * The base class from which all request policies derive.
+ */
+class BaseRequestPolicy {
+ _nextPolicy;
+ _options;
+ /**
+ * The main method to implement that manipulates a request/response.
+ */
+ constructor(
+ /**
+ * The next policy in the pipeline. Each policy is responsible for executing the next one if the request is to continue through the pipeline.
+ */
+ _nextPolicy,
+ /**
+ * The options that can be passed to a given request policy.
+ */
+ _options) {
+ this._nextPolicy = _nextPolicy;
+ this._options = _options;
+ }
+ /**
+ * Get whether or not a log with the provided log level should be logged.
+ * @param logLevel - The log level of the log that will be logged.
+ * @returns Whether or not a log with the provided log level should be logged.
+ */
+ shouldLog(logLevel) {
+ return this._options.shouldLog(logLevel);
+ }
+ /**
+ * Attempt to log the provided message to the provided logger. If no logger was provided or if
+ * the log level does not meat the logger's threshold, then nothing will be logged.
+ * @param logLevel - The log level of this log.
+ * @param message - The message of this log.
+ */
+ log(logLevel, message) {
+ this._options.log(logLevel, message);
+ }
+}
+//# sourceMappingURL=RequestPolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/utils/constants.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+const utils_constants_SDK_VERSION = "1.0.0";
+const constants_URLConstants = {
+ Parameters: {
+ FORCE_BROWSER_NO_CACHE: "_",
+ SIGNATURE: "sig",
+ SNAPSHOT: "snapshot",
+ VERSIONID: "versionid",
+ TIMEOUT: "timeout",
+ },
+};
+const constants_HeaderConstants = {
+ AUTHORIZATION: "Authorization",
+ AUTHORIZATION_SCHEME: "Bearer",
+ CONTENT_ENCODING: "Content-Encoding",
+ CONTENT_ID: "Content-ID",
+ CONTENT_LANGUAGE: "Content-Language",
+ CONTENT_LENGTH: "Content-Length",
+ CONTENT_MD5: "Content-Md5",
+ CONTENT_TRANSFER_ENCODING: "Content-Transfer-Encoding",
+ CONTENT_TYPE: "Content-Type",
+ COOKIE: "Cookie",
+ DATE: "date",
+ IF_MATCH: "if-match",
+ IF_MODIFIED_SINCE: "if-modified-since",
+ IF_NONE_MATCH: "if-none-match",
+ IF_UNMODIFIED_SINCE: "if-unmodified-since",
+ PREFIX_FOR_STORAGE: "x-ms-",
+ RANGE: "Range",
+ USER_AGENT: "User-Agent",
+ X_MS_CLIENT_REQUEST_ID: "x-ms-client-request-id",
+ X_MS_COPY_SOURCE: "x-ms-copy-source",
+ X_MS_DATE: "x-ms-date",
+ X_MS_ERROR_CODE: "x-ms-error-code",
+ X_MS_VERSION: "x-ms-version",
+ X_MS_CopySourceErrorCode: "x-ms-copy-source-error-code",
+};
+const constants_DevelopmentConnectionString = (/* unused pure expression or super */ null && (`DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;`));
+/// List of ports used for path style addressing.
+/// Path style addressing means that storage account is put in URI's Path segment in instead of in host.
+const constants_PathStylePorts = (/* unused pure expression or super */ null && ([
+ "10000",
+ "10001",
+ "10002",
+ "10003",
+ "10004",
+ "10100",
+ "10101",
+ "10102",
+ "10103",
+ "10104",
+ "11000",
+ "11001",
+ "11002",
+ "11003",
+ "11004",
+ "11100",
+ "11101",
+ "11102",
+ "11103",
+ "11104",
+]));
+//# sourceMappingURL=constants.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/utils/utils.common.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- Object.keys(env).forEach(key => {
- createDebug[key] = env[key];
- });
- /**
- * The currently active debug mode names, and names to skip.
- */
- createDebug.names = [];
- createDebug.skips = [];
-
- /**
- * Map of special "%n" handling functions, for the debug "format" argument.
- *
- * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
- */
- createDebug.formatters = {};
-
- /**
- * Selects a color for a debug namespace
- * @param {String} namespace The namespace string for the debug instance to be colored
- * @return {Number|String} An ANSI color code for the given namespace
- * @api private
- */
- function selectColor(namespace) {
- let hash = 0;
-
- for (let i = 0; i < namespace.length; i++) {
- hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
- hash |= 0; // Convert to 32bit integer
- }
-
- return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
- }
- createDebug.selectColor = selectColor;
-
- /**
- * Create a debugger with the given `namespace`.
- *
- * @param {String} namespace
- * @return {Function}
- * @api public
- */
- function createDebug(namespace) {
- let prevTime;
- let enableOverride = null;
- let namespacesCache;
- let enabledCache;
-
- function debug(...args) {
- // Disabled?
- if (!debug.enabled) {
- return;
- }
-
- const self = debug;
-
- // Set `diff` timestamp
- const curr = Number(new Date());
- const ms = curr - (prevTime || curr);
- self.diff = ms;
- self.prev = prevTime;
- self.curr = curr;
- prevTime = curr;
-
- args[0] = createDebug.coerce(args[0]);
-
- if (typeof args[0] !== 'string') {
- // Anything else let's inspect with %O
- args.unshift('%O');
- }
-
- // Apply any `formatters` transformations
- let index = 0;
- args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
- // If we encounter an escaped % then don't increase the array index
- if (match === '%%') {
- return '%';
- }
- index++;
- const formatter = createDebug.formatters[format];
- if (typeof formatter === 'function') {
- const val = args[index];
- match = formatter.call(self, val);
-
- // Now we need to remove `args[index]` since it's inlined in the `format`
- args.splice(index, 1);
- index--;
- }
- return match;
- });
-
- // Apply env-specific formatting (colors, etc.)
- createDebug.formatArgs.call(self, args);
-
- const logFn = self.log || createDebug.log;
- logFn.apply(self, args);
- }
-
- debug.namespace = namespace;
- debug.useColors = createDebug.useColors();
- debug.color = createDebug.selectColor(namespace);
- debug.extend = extend;
- debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
-
- Object.defineProperty(debug, 'enabled', {
- enumerable: true,
- configurable: false,
- get: () => {
- if (enableOverride !== null) {
- return enableOverride;
- }
- if (namespacesCache !== createDebug.namespaces) {
- namespacesCache = createDebug.namespaces;
- enabledCache = createDebug.enabled(namespace);
- }
-
- return enabledCache;
- },
- set: v => {
- enableOverride = v;
- }
- });
-
- // Env-specific initialization logic for debug instances
- if (typeof createDebug.init === 'function') {
- createDebug.init(debug);
- }
-
- return debug;
- }
-
- function extend(namespace, delimiter) {
- const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
- newDebug.log = this.log;
- return newDebug;
- }
-
- /**
- * Enables a debug mode by namespaces. This can include modes
- * separated by a colon and wildcards.
- *
- * @param {String} namespaces
- * @api public
- */
- function enable(namespaces) {
- createDebug.save(namespaces);
- createDebug.namespaces = namespaces;
-
- createDebug.names = [];
- createDebug.skips = [];
-
- const split = (typeof namespaces === 'string' ? namespaces : '')
- .trim()
- .replace(/\s+/g, ',')
- .split(',')
- .filter(Boolean);
-
- for (const ns of split) {
- if (ns[0] === '-') {
- createDebug.skips.push(ns.slice(1));
- } else {
- createDebug.names.push(ns);
- }
- }
- }
-
- /**
- * Checks if the given string matches a namespace template, honoring
- * asterisks as wildcards.
- *
- * @param {String} search
- * @param {String} template
- * @return {Boolean}
- */
- function matchesTemplate(search, template) {
- let searchIndex = 0;
- let templateIndex = 0;
- let starIndex = -1;
- let matchIndex = 0;
-
- while (searchIndex < search.length) {
- if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) {
- // Match character or proceed with wildcard
- if (template[templateIndex] === '*') {
- starIndex = templateIndex;
- matchIndex = searchIndex;
- templateIndex++; // Skip the '*'
- } else {
- searchIndex++;
- templateIndex++;
- }
- } else if (starIndex !== -1) { // eslint-disable-line no-negated-condition
- // Backtrack to the last '*' and try to match more characters
- templateIndex = starIndex + 1;
- matchIndex++;
- searchIndex = matchIndex;
- } else {
- return false; // No match
- }
- }
-
- // Handle trailing '*' in template
- while (templateIndex < template.length && template[templateIndex] === '*') {
- templateIndex++;
- }
-
- return templateIndex === template.length;
- }
-
- /**
- * Disable debug output.
- *
- * @return {String} namespaces
- * @api public
- */
- function disable() {
- const namespaces = [
- ...createDebug.names,
- ...createDebug.skips.map(namespace => '-' + namespace)
- ].join(',');
- createDebug.enable('');
- return namespaces;
- }
-
- /**
- * Returns true if the given mode name is enabled, false otherwise.
- *
- * @param {String} name
- * @return {Boolean}
- * @api public
- */
- function enabled(name) {
- for (const skip of createDebug.skips) {
- if (matchesTemplate(name, skip)) {
- return false;
- }
- }
-
- for (const ns of createDebug.names) {
- if (matchesTemplate(name, ns)) {
- return true;
- }
- }
-
- return false;
- }
-
- /**
- * Coerce `val`.
- *
- * @param {Mixed} val
- * @return {Mixed}
- * @api private
- */
- function coerce(val) {
- if (val instanceof Error) {
- return val.stack || val.message;
- }
- return val;
- }
-
- /**
- * XXX DO NOT USE. This is a temporary stub function.
- * XXX It WILL be removed in the next major release.
- */
- function destroy() {
- console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
- }
-
- createDebug.enable(createDebug.load());
-
- return createDebug;
+/**
+ * Reserved URL characters must be properly escaped for Storage services like Blob or File.
+ *
+ * ## URL encode and escape strategy for JS SDKs
+ *
+ * When customers pass a URL string into XxxClient classes constructor, the URL string may already be URL encoded or not.
+ * But before sending to Azure Storage server, the URL must be encoded. However, it's hard for a SDK to guess whether the URL
+ * string has been encoded or not. We have 2 potential strategies, and chose strategy two for the XxxClient constructors.
+ *
+ * ### Strategy One: Assume the customer URL string is not encoded, and always encode URL string in SDK.
+ *
+ * This is what legacy V2 SDK does, simple and works for most of the cases.
+ * - When customer URL string is "http://account.blob.core.windows.net/con/b:",
+ * SDK will encode it to "http://account.blob.core.windows.net/con/b%3A" and send to server. A blob named "b:" will be created.
+ * - When customer URL string is "http://account.blob.core.windows.net/con/b%3A",
+ * SDK will encode it to "http://account.blob.core.windows.net/con/b%253A" and send to server. A blob named "b%3A" will be created.
+ *
+ * But this strategy will make it not possible to create a blob with "?" in it's name. Because when customer URL string is
+ * "http://account.blob.core.windows.net/con/blob?name", the "?name" will be treated as URL paramter instead of blob name.
+ * If customer URL string is "http://account.blob.core.windows.net/con/blob%3Fname", a blob named "blob%3Fname" will be created.
+ * V2 SDK doesn't have this issue because it doesn't allow customer pass in a full URL, it accepts a separate blob name and encodeURIComponent for it.
+ * We cannot accept a SDK cannot create a blob name with "?". So we implement strategy two:
+ *
+ * ### Strategy Two: SDK doesn't assume the URL has been encoded or not. It will just escape the special characters.
+ *
+ * This is what V10 Blob Go SDK does. It accepts a URL type in Go, and call url.EscapedPath() to escape the special chars unescaped.
+ * - When customer URL string is "http://account.blob.core.windows.net/con/b:",
+ * SDK will escape ":" like "http://account.blob.core.windows.net/con/b%3A" and send to server. A blob named "b:" will be created.
+ * - When customer URL string is "http://account.blob.core.windows.net/con/b%3A",
+ * There is no special characters, so send "http://account.blob.core.windows.net/con/b%3A" to server. A blob named "b:" will be created.
+ * - When customer URL string is "http://account.blob.core.windows.net/con/b%253A",
+ * There is no special characters, so send "http://account.blob.core.windows.net/con/b%253A" to server. A blob named "b%3A" will be created.
+ *
+ * This strategy gives us flexibility to create with any special characters. But "%" will be treated as a special characters, if the URL string
+ * is not encoded, there shouldn't a "%" in the URL string, otherwise the URL is not a valid URL.
+ * If customer needs to create a blob with "%" in it's blob name, use "%25" instead of "%". Just like above 3rd sample.
+ * And following URL strings are invalid:
+ * - "http://account.blob.core.windows.net/con/b%"
+ * - "http://account.blob.core.windows.net/con/b%2"
+ * - "http://account.blob.core.windows.net/con/b%G"
+ *
+ * Another special character is "?", use "%2F" to represent a blob name with "?" in a URL string.
+ *
+ * ### Strategy for containerName, blobName or other specific XXXName parameters in methods such as `containerClient.getBlobClient(blobName)`
+ *
+ * We will apply strategy one, and call encodeURIComponent for these parameters like blobName. Because what customers passes in is a plain name instead of a URL.
+ *
+ * @see https://learn.microsoft.com/rest/api/storageservices/naming-and-referencing-containers--blobs--and-metadata
+ * @see https://learn.microsoft.com/rest/api/storageservices/naming-and-referencing-shares--directories--files--and-metadata
+ *
+ * @param url -
+ */
+function escapeURLPath(url) {
+ const urlParsed = new URL(url);
+ let path = urlParsed.pathname;
+ path = path || "/";
+ path = utils_common_escape(path);
+ urlParsed.pathname = path;
+ return urlParsed.toString();
+}
+function getProxyUriFromDevConnString(connectionString) {
+ // Development Connection String
+ // https://learn.microsoft.com/azure/storage/common/storage-configure-connection-string#connect-to-the-emulator-account-using-the-well-known-account-name-and-key
+ let proxyUri = "";
+ if (connectionString.search("DevelopmentStorageProxyUri=") !== -1) {
+ // CONNECTION_STRING=UseDevelopmentStorage=true;DevelopmentStorageProxyUri=http://myProxyUri
+ const matchCredentials = connectionString.split(";");
+ for (const element of matchCredentials) {
+ if (element.trim().startsWith("DevelopmentStorageProxyUri=")) {
+ proxyUri = element.trim().match("DevelopmentStorageProxyUri=(.*)")[1];
+ }
+ }
+ }
+ return proxyUri;
+}
+function getValueInConnString(connectionString, argument) {
+ const elements = connectionString.split(";");
+ for (const element of elements) {
+ if (element.trim().startsWith(argument)) {
+ return element.trim().match(argument + "=(.*)")[1];
+ }
+ }
+ return "";
}
-
-module.exports = setup;
-
-
-/***/ }),
-
-/***/ 2830:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
/**
- * Detect Electron renderer / nwjs process, which is node, but we should
- * treat as a browser.
+ * Extracts the parts of an Azure Storage account connection string.
+ *
+ * @param connectionString - Connection string.
+ * @returns String key value pairs of the storage account's url and credentials.
*/
-
-if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
- module.exports = __nccwpck_require__(6110);
-} else {
- module.exports = __nccwpck_require__(5108);
+function extractConnectionStringParts(connectionString) {
+ let proxyUri = "";
+ if (connectionString.startsWith("UseDevelopmentStorage=true")) {
+ // Development connection string
+ proxyUri = getProxyUriFromDevConnString(connectionString);
+ connectionString = DevelopmentConnectionString;
+ }
+ // Matching BlobEndpoint in the Account connection string
+ let blobEndpoint = getValueInConnString(connectionString, "BlobEndpoint");
+ // Slicing off '/' at the end if exists
+ // (The methods that use `extractConnectionStringParts` expect the url to not have `/` at the end)
+ blobEndpoint = blobEndpoint.endsWith("/") ? blobEndpoint.slice(0, -1) : blobEndpoint;
+ if (connectionString.search("DefaultEndpointsProtocol=") !== -1 &&
+ connectionString.search("AccountKey=") !== -1) {
+ // Account connection string
+ let defaultEndpointsProtocol = "";
+ let accountName = "";
+ let accountKey = Buffer.from("accountKey", "base64");
+ let endpointSuffix = "";
+ // Get account name and key
+ accountName = getValueInConnString(connectionString, "AccountName");
+ accountKey = Buffer.from(getValueInConnString(connectionString, "AccountKey"), "base64");
+ if (!blobEndpoint) {
+ // BlobEndpoint is not present in the Account connection string
+ // Can be obtained from `${defaultEndpointsProtocol}://${accountName}.blob.${endpointSuffix}`
+ defaultEndpointsProtocol = getValueInConnString(connectionString, "DefaultEndpointsProtocol");
+ const protocol = defaultEndpointsProtocol.toLowerCase();
+ if (protocol !== "https" && protocol !== "http") {
+ throw new Error("Invalid DefaultEndpointsProtocol in the provided Connection String. Expecting 'https' or 'http'");
+ }
+ endpointSuffix = getValueInConnString(connectionString, "EndpointSuffix");
+ if (!endpointSuffix) {
+ throw new Error("Invalid EndpointSuffix in the provided Connection String");
+ }
+ blobEndpoint = `${defaultEndpointsProtocol}://${accountName}.blob.${endpointSuffix}`;
+ }
+ if (!accountName) {
+ throw new Error("Invalid AccountName in the provided Connection String");
+ }
+ else if (accountKey.length === 0) {
+ throw new Error("Invalid AccountKey in the provided Connection String");
+ }
+ return {
+ kind: "AccountConnString",
+ url: blobEndpoint,
+ accountName,
+ accountKey,
+ proxyUri,
+ };
+ }
+ else {
+ // SAS connection string
+ let accountSas = getValueInConnString(connectionString, "SharedAccessSignature");
+ let accountName = getValueInConnString(connectionString, "AccountName");
+ // if accountName is empty, try to read it from BlobEndpoint
+ if (!accountName) {
+ accountName = getAccountNameFromUrl(blobEndpoint);
+ }
+ if (!blobEndpoint) {
+ throw new Error("Invalid BlobEndpoint in the provided SAS Connection String");
+ }
+ else if (!accountSas) {
+ throw new Error("Invalid SharedAccessSignature in the provided SAS Connection String");
+ }
+ // client constructors assume accountSas does *not* start with ?
+ if (accountSas.startsWith("?")) {
+ accountSas = accountSas.substring(1);
+ }
+ return { kind: "SASConnString", url: blobEndpoint, accountName, accountSas };
+ }
}
-
-
-/***/ }),
-
-/***/ 5108:
-/***/ ((module, exports, __nccwpck_require__) => {
-
/**
- * Module dependencies.
+ * Internal escape method implemented Strategy Two mentioned in escapeURL() description.
+ *
+ * @param text -
*/
-
-const tty = __nccwpck_require__(2018);
-const util = __nccwpck_require__(9023);
-
+function utils_common_escape(text) {
+ return encodeURIComponent(text)
+ .replace(/%2F/g, "/") // Don't escape for "/"
+ .replace(/'/g, "%27") // Escape for "'"
+ .replace(/\+/g, "%20")
+ .replace(/%25/g, "%"); // Revert encoded "%"
+}
/**
- * This is the Node.js implementation of `debug()`.
+ * Append a string to URL path. Will remove duplicated "/" in front of the string
+ * when URL path ends with a "/".
+ *
+ * @param url - Source URL string
+ * @param name - String to be appended to URL
+ * @returns An updated URL string
*/
-
-exports.init = init;
-exports.log = log;
-exports.formatArgs = formatArgs;
-exports.save = save;
-exports.load = load;
-exports.useColors = useColors;
-exports.destroy = util.deprecate(
- () => {},
- 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'
-);
-
+function appendToURLPath(url, name) {
+ const urlParsed = new URL(url);
+ let path = urlParsed.pathname;
+ path = path ? (path.endsWith("/") ? `${path}${name}` : `${path}/${name}`) : name;
+ urlParsed.pathname = path;
+ return urlParsed.toString();
+}
/**
- * Colors.
+ * Set URL parameter name and value. If name exists in URL parameters, old value
+ * will be replaced by name key. If not provide value, the parameter will be deleted.
+ *
+ * @param url - Source URL string
+ * @param name - Parameter name
+ * @param value - Parameter value
+ * @returns An updated URL string
*/
-
-exports.colors = [6, 2, 3, 4, 5, 1];
-
-try {
- // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
- // eslint-disable-next-line import/no-extraneous-dependencies
- const supportsColor = __nccwpck_require__(75);
-
- if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
- exports.colors = [
- 20,
- 21,
- 26,
- 27,
- 32,
- 33,
- 38,
- 39,
- 40,
- 41,
- 42,
- 43,
- 44,
- 45,
- 56,
- 57,
- 62,
- 63,
- 68,
- 69,
- 74,
- 75,
- 76,
- 77,
- 78,
- 79,
- 80,
- 81,
- 92,
- 93,
- 98,
- 99,
- 112,
- 113,
- 128,
- 129,
- 134,
- 135,
- 148,
- 149,
- 160,
- 161,
- 162,
- 163,
- 164,
- 165,
- 166,
- 167,
- 168,
- 169,
- 170,
- 171,
- 172,
- 173,
- 178,
- 179,
- 184,
- 185,
- 196,
- 197,
- 198,
- 199,
- 200,
- 201,
- 202,
- 203,
- 204,
- 205,
- 206,
- 207,
- 208,
- 209,
- 214,
- 215,
- 220,
- 221
- ];
- }
-} catch (error) {
- // Swallow - we only care if `supports-color` is available; it doesn't have to be.
+function setURLParameter(url, name, value) {
+ const urlParsed = new URL(url);
+ const encodedName = encodeURIComponent(name);
+ const encodedValue = value ? encodeURIComponent(value) : undefined;
+ // mutating searchParams will change the encoding, so we have to do this ourselves
+ const searchString = urlParsed.search === "" ? "?" : urlParsed.search;
+ const searchPieces = [];
+ for (const pair of searchString.slice(1).split("&")) {
+ if (pair) {
+ const [key] = pair.split("=", 2);
+ if (key !== encodedName) {
+ searchPieces.push(pair);
+ }
+ }
+ }
+ if (encodedValue) {
+ searchPieces.push(`${encodedName}=${encodedValue}`);
+ }
+ urlParsed.search = searchPieces.length ? `?${searchPieces.join("&")}` : "";
+ return urlParsed.toString();
}
-
/**
- * Build up the default `inspectOpts` object from the environment variables.
+ * Get URL parameter by name.
*
- * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
+ * @param url -
+ * @param name -
*/
-
-exports.inspectOpts = Object.keys(process.env).filter(key => {
- return /^debug_/i.test(key);
-}).reduce((obj, key) => {
- // Camel-case
- const prop = key
- .substring(6)
- .toLowerCase()
- .replace(/_([a-z])/g, (_, k) => {
- return k.toUpperCase();
- });
-
- // Coerce string value into JS value
- let val = process.env[key];
- if (/^(yes|on|true|enabled)$/i.test(val)) {
- val = true;
- } else if (/^(no|off|false|disabled)$/i.test(val)) {
- val = false;
- } else if (val === 'null') {
- val = null;
- } else {
- val = Number(val);
- }
-
- obj[prop] = val;
- return obj;
-}, {});
-
+function getURLParameter(url, name) {
+ const urlParsed = new URL(url);
+ return urlParsed.searchParams.get(name) ?? undefined;
+}
/**
- * Is stdout a TTY? Colored output is enabled when `true`.
+ * Set URL host.
+ *
+ * @param url - Source URL string
+ * @param host - New host string
+ * @returns An updated URL string
*/
-
-function useColors() {
- return 'colors' in exports.inspectOpts ?
- Boolean(exports.inspectOpts.colors) :
- tty.isatty(process.stderr.fd);
+function setURLHost(url, host) {
+ const urlParsed = new URL(url);
+ urlParsed.hostname = host;
+ return urlParsed.toString();
}
-
/**
- * Adds ANSI color escape codes if enabled.
+ * Get URL path from an URL string.
*
- * @api public
+ * @param url - Source URL string
*/
-
-function formatArgs(args) {
- const {namespace: name, useColors} = this;
-
- if (useColors) {
- const c = this.color;
- const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c);
- const prefix = ` ${colorCode};1m${name} \u001B[0m`;
-
- args[0] = prefix + args[0].split('\n').join('\n' + prefix);
- args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m');
- } else {
- args[0] = getDate() + name + ' ' + args[0];
- }
+function getURLPath(url) {
+ try {
+ const urlParsed = new URL(url);
+ return urlParsed.pathname;
+ }
+ catch (e) {
+ return undefined;
+ }
}
-
-function getDate() {
- if (exports.inspectOpts.hideDate) {
- return '';
- }
- return new Date().toISOString() + ' ';
+/**
+ * Get URL scheme from an URL string.
+ *
+ * @param url - Source URL string
+ */
+function getURLScheme(url) {
+ try {
+ const urlParsed = new URL(url);
+ return urlParsed.protocol.endsWith(":") ? urlParsed.protocol.slice(0, -1) : urlParsed.protocol;
+ }
+ catch (e) {
+ return undefined;
+ }
}
-
/**
- * Invokes `util.formatWithOptions()` with the specified arguments and writes to stderr.
+ * Get URL path and query from an URL string.
+ *
+ * @param url - Source URL string
*/
-
-function log(...args) {
- return process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...args) + '\n');
+function getURLPathAndQuery(url) {
+ const urlParsed = new URL(url);
+ const pathString = urlParsed.pathname;
+ if (!pathString) {
+ throw new RangeError("Invalid url without valid path.");
+ }
+ let queryString = urlParsed.search || "";
+ queryString = queryString.trim();
+ if (queryString !== "") {
+ queryString = queryString.startsWith("?") ? queryString : `?${queryString}`; // Ensure query string start with '?'
+ }
+ return `${pathString}${queryString}`;
}
-
/**
- * Save `namespaces`.
+ * Get URL query key value pairs from an URL string.
*
- * @param {String} namespaces
- * @api private
+ * @param url -
*/
-function save(namespaces) {
- if (namespaces) {
- process.env.DEBUG = namespaces;
- } else {
- // If you set a process.env field to null or undefined, it gets cast to the
- // string 'null' or 'undefined'. Just delete instead.
- delete process.env.DEBUG;
- }
+function getURLQueries(url) {
+ let queryString = new URL(url).search;
+ if (!queryString) {
+ return {};
+ }
+ queryString = queryString.trim();
+ queryString = queryString.startsWith("?") ? queryString.substring(1) : queryString;
+ let querySubStrings = queryString.split("&");
+ querySubStrings = querySubStrings.filter((value) => {
+ const indexOfEqual = value.indexOf("=");
+ const lastIndexOfEqual = value.lastIndexOf("=");
+ return (indexOfEqual > 0 && indexOfEqual === lastIndexOfEqual && lastIndexOfEqual < value.length - 1);
+ });
+ const queries = {};
+ for (const querySubString of querySubStrings) {
+ const splitResults = querySubString.split("=");
+ const key = splitResults[0];
+ const value = splitResults[1];
+ queries[key] = value;
+ }
+ return queries;
}
-
/**
- * Load `namespaces`.
+ * Append a string to URL query.
*
- * @return {String} returns the previously persisted debug modes
- * @api private
+ * @param url - Source URL string.
+ * @param queryParts - String to be appended to the URL query.
+ * @returns An updated URL string.
*/
-
-function load() {
- return process.env.DEBUG;
+function appendToURLQuery(url, queryParts) {
+ const urlParsed = new URL(url);
+ let query = urlParsed.search;
+ if (query) {
+ query += "&" + queryParts;
+ }
+ else {
+ query = queryParts;
+ }
+ urlParsed.search = query;
+ return urlParsed.toString();
}
-
/**
- * Init logic for `debug` instances.
+ * Rounds a date off to seconds.
*
- * Create a new `inspectOpts` object in case `useColors` is set
- * differently for a particular `debug` instance.
+ * @param date -
+ * @param withMilliseconds - If true, YYYY-MM-DDThh:mm:ss.fffffffZ will be returned;
+ * If false, YYYY-MM-DDThh:mm:ssZ will be returned.
+ * @returns Date string in ISO8061 format, with or without 7 milliseconds component
*/
-
-function init(debug) {
- debug.inspectOpts = {};
-
- const keys = Object.keys(exports.inspectOpts);
- for (let i = 0; i < keys.length; i++) {
- debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
- }
+function truncatedISO8061Date(date, withMilliseconds = true) {
+ // Date.toISOString() will return like "2018-10-29T06:34:36.139Z"
+ const dateString = date.toISOString();
+ return withMilliseconds
+ ? dateString.substring(0, dateString.length - 1) + "0000" + "Z"
+ : dateString.substring(0, dateString.length - 5) + "Z";
}
-
-module.exports = __nccwpck_require__(897)(exports);
-
-const {formatters} = module.exports;
-
/**
- * Map %o to `util.inspect()`, all on a single line.
+ * Base64 encode.
+ *
+ * @param content -
*/
-
-formatters.o = function (v) {
- this.inspectOpts.colors = this.useColors;
- return util.inspect(v, this.inspectOpts)
- .split('\n')
- .map(str => str.trim())
- .join(' ');
-};
-
+function base64encode(content) {
+ return !isNodeLike ? btoa(content) : Buffer.from(content).toString("base64");
+}
/**
- * Map %O to `util.inspect()`, allowing multiple lines if needed.
+ * Base64 decode.
+ *
+ * @param encodedString -
*/
-
-formatters.O = function (v) {
- this.inspectOpts.colors = this.useColors;
- return util.inspect(v, this.inspectOpts);
-};
-
-
-/***/ }),
-
-/***/ 1970:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
-
-
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- var desc = Object.getOwnPropertyDescriptor(m, k);
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() { return m[k]; } };
+function base64decode(encodedString) {
+ return !isNodeLike ? atob(encodedString) : Buffer.from(encodedString, "base64").toString();
+}
+/**
+ * Generate a 64 bytes base64 block ID string.
+ *
+ * @param blockIndex -
+ */
+function generateBlockID(blockIDPrefix, blockIndex) {
+ // To generate a 64 bytes base64 string, source string should be 48
+ const maxSourceStringLength = 48;
+ // A blob can have a maximum of 100,000 uncommitted blocks at any given time
+ const maxBlockIndexLength = 6;
+ const maxAllowedBlockIDPrefixLength = maxSourceStringLength - maxBlockIndexLength;
+ if (blockIDPrefix.length > maxAllowedBlockIDPrefixLength) {
+ blockIDPrefix = blockIDPrefix.slice(0, maxAllowedBlockIDPrefixLength);
}
- Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.HttpProxyAgent = void 0;
-const net = __importStar(__nccwpck_require__(9278));
-const tls = __importStar(__nccwpck_require__(4756));
-const debug_1 = __importDefault(__nccwpck_require__(2830));
-const events_1 = __nccwpck_require__(4434);
-const agent_base_1 = __nccwpck_require__(8894);
-const url_1 = __nccwpck_require__(7016);
-const debug = (0, debug_1.default)('http-proxy-agent');
+ const res = blockIDPrefix +
+ padStart(blockIndex.toString(), maxSourceStringLength - blockIDPrefix.length, "0");
+ return base64encode(res);
+}
/**
- * The `HttpProxyAgent` implements an HTTP Agent subclass that connects
- * to the specified "HTTP proxy server" in order to proxy HTTP requests.
+ * Delay specified time interval.
+ *
+ * @param timeInMs -
+ * @param aborter -
+ * @param abortError -
*/
-class HttpProxyAgent extends agent_base_1.Agent {
- constructor(proxy, opts) {
- super(opts);
- this.proxy = typeof proxy === 'string' ? new url_1.URL(proxy) : proxy;
- this.proxyHeaders = opts?.headers ?? {};
- debug('Creating new HttpProxyAgent instance: %o', this.proxy.href);
- // Trim off the brackets from IPv6 addresses
- const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, '');
- const port = this.proxy.port
- ? parseInt(this.proxy.port, 10)
- : this.proxy.protocol === 'https:'
- ? 443
- : 80;
- this.connectOpts = {
- ...(opts ? omit(opts, 'headers') : null),
- host,
- port,
+async function utils_common_delay(timeInMs, aborter, abortError) {
+ return new Promise((resolve, reject) => {
+ /* eslint-disable-next-line prefer-const */
+ let timeout;
+ const abortHandler = () => {
+ if (timeout !== undefined) {
+ clearTimeout(timeout);
+ }
+ reject(abortError);
+ };
+ const resolveHandler = () => {
+ if (aborter !== undefined) {
+ aborter.removeEventListener("abort", abortHandler);
+ }
+ resolve();
};
+ timeout = setTimeout(resolveHandler, timeInMs);
+ if (aborter !== undefined) {
+ aborter.addEventListener("abort", abortHandler);
+ }
+ });
+}
+/**
+ * String.prototype.padStart()
+ *
+ * @param currentString -
+ * @param targetLength -
+ * @param padString -
+ */
+function padStart(currentString, targetLength, padString = " ") {
+ // @ts-expect-error: TS doesn't know this code needs to run downlevel sometimes
+ if (String.prototype.padStart) {
+ return currentString.padStart(targetLength, padString);
}
- addRequest(req, opts) {
- req._header = null;
- this.setRequestProps(req, opts);
- // @ts-expect-error `addRequest()` isn't defined in `@types/node`
- super.addRequest(req, opts);
+ padString = padString || " ";
+ if (currentString.length > targetLength) {
+ return currentString;
}
- setRequestProps(req, opts) {
- const { proxy } = this;
- const protocol = opts.secureEndpoint ? 'https:' : 'http:';
- const hostname = req.getHeader('host') || 'localhost';
- const base = `${protocol}//${hostname}`;
- const url = new url_1.URL(req.path, base);
- if (opts.port !== 80) {
- url.port = String(opts.port);
+ else {
+ targetLength = targetLength - currentString.length;
+ if (targetLength > padString.length) {
+ padString += padString.repeat(targetLength / padString.length);
}
- // Change the `http.ClientRequest` instance's "path" field
- // to the absolute path of the URL that will be requested.
- req.path = String(url);
- // Inject the `Proxy-Authorization` header if necessary.
- const headers = typeof this.proxyHeaders === 'function'
- ? this.proxyHeaders()
- : { ...this.proxyHeaders };
- if (proxy.username || proxy.password) {
- const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;
- headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`;
+ return padString.slice(0, targetLength) + currentString;
+ }
+}
+function sanitizeURL(url) {
+ let safeURL = url;
+ if (getURLParameter(safeURL, URLConstants.Parameters.SIGNATURE)) {
+ safeURL = setURLParameter(safeURL, URLConstants.Parameters.SIGNATURE, "*****");
+ }
+ return safeURL;
+}
+function sanitizeHeaders(originalHeader) {
+ const headers = createHttpHeaders();
+ for (const [name, value] of originalHeader) {
+ if (name.toLowerCase() === HeaderConstants.AUTHORIZATION.toLowerCase()) {
+ headers.set(name, "*****");
}
- if (!headers['Proxy-Connection']) {
- headers['Proxy-Connection'] = this.keepAlive
- ? 'Keep-Alive'
- : 'close';
+ else if (name.toLowerCase() === HeaderConstants.X_MS_COPY_SOURCE) {
+ headers.set(name, sanitizeURL(value));
}
- for (const name of Object.keys(headers)) {
- const value = headers[name];
- if (value) {
- req.setHeader(name, value);
- }
+ else {
+ headers.set(name, value);
}
}
- async connect(req, opts) {
- req._header = null;
- if (!req.path.includes('://')) {
- this.setRequestProps(req, opts);
- }
- // At this point, the http ClientRequest's internal `_header` field
- // might have already been set. If this is the case then we'll need
- // to re-generate the string since we just changed the `req.path`.
- let first;
- let endOfHeaders;
- debug('Regenerating stored HTTP header string for request');
- req._implicitHeader();
- if (req.outputData && req.outputData.length > 0) {
- debug('Patching connection write() output buffer with updated header');
- first = req.outputData[0].data;
- endOfHeaders = first.indexOf('\r\n\r\n') + 4;
- req.outputData[0].data =
- req._header + first.substring(endOfHeaders);
- debug('Output buffer: %o', req.outputData[0].data);
+ return headers;
+}
+/**
+ * If two strings are equal when compared case insensitive.
+ *
+ * @param str1 -
+ * @param str2 -
+ */
+function iEqual(str1, str2) {
+ return str1.toLocaleLowerCase() === str2.toLocaleLowerCase();
+}
+/**
+ * Extracts account name from the url
+ * @param url - url to extract the account name from
+ * @returns with the account name
+ */
+function getAccountNameFromUrl(url) {
+ const parsedUrl = new URL(url);
+ let accountName;
+ try {
+ if (parsedUrl.hostname.split(".")[1] === "blob") {
+ // `${defaultEndpointsProtocol}://${accountName}.blob.${endpointSuffix}`;
+ accountName = parsedUrl.hostname.split(".")[0];
}
- // Create a socket connection to the proxy server.
- let socket;
- if (this.proxy.protocol === 'https:') {
- debug('Creating `tls.Socket`: %o', this.connectOpts);
- socket = tls.connect(this.connectOpts);
+ else if (isIpEndpointStyle(parsedUrl)) {
+ // IPv4/IPv6 address hosts... Example - http://192.0.0.10:10001/devstoreaccount1/
+ // Single word domain without a [dot] in the endpoint... Example - http://localhost:10001/devstoreaccount1/
+ // .getPath() -> /devstoreaccount1/
+ accountName = parsedUrl.pathname.split("/")[1];
}
else {
- debug('Creating `net.Socket`: %o', this.connectOpts);
- socket = net.connect(this.connectOpts);
+ // Custom domain case: "https://customdomain.com/containername/blob".
+ accountName = "";
}
- // Wait for the socket's `connect` event, so that this `callback()`
- // function throws instead of the `http` request machinery. This is
- // important for i.e. `PacProxyAgent` which determines a failed proxy
- // connection via the `callback()` function throwing.
- await (0, events_1.once)(socket, 'connect');
- return socket;
+ return accountName;
+ }
+ catch (error) {
+ throw new Error("Unable to extract accountName with provided information.");
}
}
-HttpProxyAgent.protocols = ['http', 'https'];
-exports.HttpProxyAgent = HttpProxyAgent;
-function omit(obj, ...keys) {
- const ret = {};
- let key;
- for (key in obj) {
- if (!keys.includes(key)) {
- ret[key] = obj[key];
- }
+function isIpEndpointStyle(parsedUrl) {
+ const host = parsedUrl.host;
+ // Case 1: Ipv6, use a broad regex to find out candidates whose host contains two ':'.
+ // Case 2: localhost(:port) or host.docker.internal, use broad regex to match port part.
+ // Case 3: Ipv4, use broad regex which just check if host contains Ipv4.
+ // For valid host please refer to https://man7.org/linux/man-pages/man7/hostname.7.html.
+ return (/^.*:.*:.*$|^(localhost|host.docker.internal)(:[0-9]+)?$|^(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])(\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])){3}(:[0-9]+)?$/.test(host) ||
+ (Boolean(parsedUrl.port) && PathStylePorts.includes(parsedUrl.port)));
+}
+/**
+ * Attach a TokenCredential to an object.
+ *
+ * @param thing -
+ * @param credential -
+ */
+function attachCredential(thing, credential) {
+ thing.credential = credential;
+ return thing;
+}
+function httpAuthorizationToString(httpAuthorization) {
+ return httpAuthorization ? httpAuthorization.scheme + " " + httpAuthorization.value : undefined;
+}
+/**
+ * Escape the blobName but keep path separator ('/').
+ */
+function EscapePath(blobName) {
+ const split = blobName.split("/");
+ for (let i = 0; i < split.length; i++) {
+ split[i] = encodeURIComponent(split[i]);
}
- return ret;
+ return split.join("/");
}
-//# sourceMappingURL=index.js.map
+/**
+ * A typesafe helper for ensuring that a given response object has
+ * the original _response attached.
+ * @param response - A response object from calling a client operation
+ * @returns The same object, but with known _response property
+ */
+function assertResponse(response) {
+ if (`_response` in response) {
+ return response;
+ }
+ throw new TypeError(`Unexpected response object ${response}`);
+}
+//# sourceMappingURL=utils.common.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/policies/StorageBrowserPolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
-/***/ }),
-/***/ 3669:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- var desc = Object.getOwnPropertyDescriptor(m, k);
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() { return m[k]; } };
- }
- Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.HttpsProxyAgent = void 0;
-const net = __importStar(__nccwpck_require__(9278));
-const tls = __importStar(__nccwpck_require__(4756));
-const assert_1 = __importDefault(__nccwpck_require__(2613));
-const debug_1 = __importDefault(__nccwpck_require__(2830));
-const agent_base_1 = __nccwpck_require__(8894);
-const url_1 = __nccwpck_require__(7016);
-const parse_proxy_response_1 = __nccwpck_require__(7943);
-const debug = (0, debug_1.default)('https-proxy-agent');
-const setServernameFromNonIpHost = (options) => {
- if (options.servername === undefined &&
- options.host &&
- !net.isIP(options.host)) {
- return {
- ...options,
- servername: options.host,
- };
- }
- return options;
-};
/**
- * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to
- * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests.
+ * StorageBrowserPolicy will handle differences between Node.js and browser runtime, including:
*
- * Outgoing HTTP requests are first tunneled through the proxy server using the
- * `CONNECT` HTTP request method to establish a connection to the proxy server,
- * and then the proxy server connects to the destination target and issues the
- * HTTP request from the proxy server.
+ * 1. Browsers cache GET/HEAD requests by adding conditional headers such as 'IF_MODIFIED_SINCE'.
+ * StorageBrowserPolicy is a policy used to add a timestamp query to GET/HEAD request URL
+ * thus avoid the browser cache.
*
- * `https:` requests have their socket connection upgraded to TLS once
- * the connection to the proxy server has been established.
+ * 2. Remove cookie header for security
+ *
+ * 3. Remove content-length header to avoid browsers warning
*/
-class HttpsProxyAgent extends agent_base_1.Agent {
- constructor(proxy, opts) {
- super(opts);
- this.options = { path: undefined };
- this.proxy = typeof proxy === 'string' ? new url_1.URL(proxy) : proxy;
- this.proxyHeaders = opts?.headers ?? {};
- debug('Creating new HttpsProxyAgent instance: %o', this.proxy.href);
- // Trim off the brackets from IPv6 addresses
- const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, '');
- const port = this.proxy.port
- ? parseInt(this.proxy.port, 10)
- : this.proxy.protocol === 'https:'
- ? 443
- : 80;
- this.connectOpts = {
- // Attempt to negotiate http/1.1 for proxy servers that support http/2
- ALPNProtocols: ['http/1.1'],
- ...(opts ? omit(opts, 'headers') : null),
- host,
- port,
- };
+class StorageBrowserPolicy extends BaseRequestPolicy {
+ /**
+ * Creates an instance of StorageBrowserPolicy.
+ * @param nextPolicy -
+ * @param options -
+ */
+ // The base class has a protected constructor. Adding a public one to enable constructing of this class.
+ /* eslint-disable-next-line @typescript-eslint/no-useless-constructor*/
+ constructor(nextPolicy, options) {
+ super(nextPolicy, options);
}
/**
- * Called when the node-core HTTP client library is creating a
- * new HTTP request.
+ * Sends out request.
+ *
+ * @param request -
*/
- async connect(req, opts) {
- const { proxy } = this;
- if (!opts.host) {
- throw new TypeError('No "host" provided');
- }
- // Create a socket connection to the proxy server.
- let socket;
- if (proxy.protocol === 'https:') {
- debug('Creating `tls.Socket`: %o', this.connectOpts);
- socket = tls.connect(setServernameFromNonIpHost(this.connectOpts));
- }
- else {
- debug('Creating `net.Socket`: %o', this.connectOpts);
- socket = net.connect(this.connectOpts);
- }
- const headers = typeof this.proxyHeaders === 'function'
- ? this.proxyHeaders()
- : { ...this.proxyHeaders };
- const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host;
- let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r\n`;
- // Inject the `Proxy-Authorization` header if necessary.
- if (proxy.username || proxy.password) {
- const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;
- headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`;
- }
- headers.Host = `${host}:${opts.port}`;
- if (!headers['Proxy-Connection']) {
- headers['Proxy-Connection'] = this.keepAlive
- ? 'Keep-Alive'
- : 'close';
- }
- for (const name of Object.keys(headers)) {
- payload += `${name}: ${headers[name]}\r\n`;
+ async sendRequest(request) {
+ if (esm_isNodeLike) {
+ return this._nextPolicy.sendRequest(request);
}
- const proxyResponsePromise = (0, parse_proxy_response_1.parseProxyResponse)(socket);
- socket.write(`${payload}\r\n`);
- const { connect, buffered } = await proxyResponsePromise;
- req.emit('proxyConnect', connect);
- this.emit('proxyConnect', connect, req);
- if (connect.statusCode === 200) {
- req.once('socket', resume);
- if (opts.secureEndpoint) {
- // The proxy is connecting to a TLS server, so upgrade
- // this socket connection to a TLS connection.
- debug('Upgrading socket connection to TLS');
- return tls.connect({
- ...omit(setServernameFromNonIpHost(opts), 'host', 'path', 'port'),
- socket,
- });
- }
- return socket;
+ if (request.method.toUpperCase() === "GET" || request.method.toUpperCase() === "HEAD") {
+ request.url = setURLParameter(request.url, constants_URLConstants.Parameters.FORCE_BROWSER_NO_CACHE, new Date().getTime().toString());
}
- // Some other status code that's not 200... need to re-play the HTTP
- // header "data" events onto the socket once the HTTP machinery is
- // attached so that the node core `http` can parse and handle the
- // error status code.
- // Close the original socket, and a new "fake" socket is returned
- // instead, so that the proxy doesn't get the HTTP request
- // written to it (which may contain `Authorization` headers or other
- // sensitive data).
- //
- // See: https://hackerone.com/reports/541502
- socket.destroy();
- const fakeSocket = new net.Socket({ writable: false });
- fakeSocket.readable = true;
- // Need to wait for the "socket" event to re-play the "data" events.
- req.once('socket', (s) => {
- debug('Replaying proxy buffer for failed request');
- (0, assert_1.default)(s.listenerCount('data') > 0);
- // Replay the "buffered" Buffer onto the fake `socket`, since at
- // this point the HTTP module machinery has been hooked up for
- // the user.
- s.push(buffered);
- s.push(null);
- });
- return fakeSocket;
+ request.headers.remove(constants_HeaderConstants.COOKIE);
+ // According to XHR standards, content-length should be fully controlled by browsers
+ request.headers.remove(constants_HeaderConstants.CONTENT_LENGTH);
+ return this._nextPolicy.sendRequest(request);
}
}
-HttpsProxyAgent.protocols = ['http', 'https'];
-exports.HttpsProxyAgent = HttpsProxyAgent;
-function resume(socket) {
- socket.resume();
-}
-function omit(obj, ...keys) {
- const ret = {};
- let key;
- for (key in obj) {
- if (!keys.includes(key)) {
- ret[key] = obj[key];
- }
+//# sourceMappingURL=StorageBrowserPolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/StorageBrowserPolicyFactory.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+
+
+/**
+ * StorageBrowserPolicyFactory is a factory class helping generating StorageBrowserPolicy objects.
+ */
+class StorageBrowserPolicyFactory {
+ /**
+ * Creates a StorageBrowserPolicyFactory object.
+ *
+ * @param nextPolicy -
+ * @param options -
+ */
+ create(nextPolicy, options) {
+ return new StorageBrowserPolicy(nextPolicy, options);
}
- return ret;
}
-//# sourceMappingURL=index.js.map
+//# sourceMappingURL=StorageBrowserPolicyFactory.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/policies/CredentialPolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
-/***/ }),
+/**
+ * Credential policy used to sign HTTP(S) requests before sending. This is an
+ * abstract class.
+ */
+class CredentialPolicy extends BaseRequestPolicy {
+ /**
+ * Sends out request.
+ *
+ * @param request -
+ */
+ sendRequest(request) {
+ return this._nextPolicy.sendRequest(this.signRequest(request));
+ }
+ /**
+ * Child classes must implement this method with request signing. This method
+ * will be executed in {@link sendRequest}.
+ *
+ * @param request -
+ */
+ signRequest(request) {
+ // Child classes must override this method with request signing. This method
+ // will be executed in sendRequest().
+ return request;
+ }
+}
+//# sourceMappingURL=CredentialPolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/policies/AnonymousCredentialPolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
-/***/ 7943:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+/**
+ * AnonymousCredentialPolicy is used with HTTP(S) requests that read public resources
+ * or for use with Shared Access Signatures (SAS).
+ */
+class AnonymousCredentialPolicy extends CredentialPolicy {
+ /**
+ * Creates an instance of AnonymousCredentialPolicy.
+ * @param nextPolicy -
+ * @param options -
+ */
+ // The base class has a protected constructor. Adding a public one to enable constructing of this class.
+ /* eslint-disable-next-line @typescript-eslint/no-useless-constructor*/
+ constructor(nextPolicy, options) {
+ super(nextPolicy, options);
+ }
+}
+//# sourceMappingURL=AnonymousCredentialPolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/credentials/Credential.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+/**
+ * Credential is an abstract class for Azure Storage HTTP requests signing. This
+ * class will host an credentialPolicyCreator factory which generates CredentialPolicy.
+ */
+class Credential {
+ /**
+ * Creates a RequestPolicy object.
+ *
+ * @param _nextPolicy -
+ * @param _options -
+ */
+ create(_nextPolicy, _options) {
+ throw new Error("Method should be implemented in children classes.");
+ }
+}
+//# sourceMappingURL=Credential.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/credentials/AnonymousCredential.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
-var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.parseProxyResponse = void 0;
-const debug_1 = __importDefault(__nccwpck_require__(2830));
-const debug = (0, debug_1.default)('https-proxy-agent:parse-proxy-response');
-function parseProxyResponse(socket) {
- return new Promise((resolve, reject) => {
- // we need to buffer any HTTP traffic that happens with the proxy before we get
- // the CONNECT response, so that if the response is anything other than an "200"
- // response code, then we can re-play the "data" events on the socket once the
- // HTTP parser is hooked up...
- let buffersLength = 0;
- const buffers = [];
- function read() {
- const b = socket.read();
- if (b)
- ondata(b);
- else
- socket.once('readable', read);
+/**
+ * AnonymousCredential provides a credentialPolicyCreator member used to create
+ * AnonymousCredentialPolicy objects. AnonymousCredentialPolicy is used with
+ * HTTP(S) requests that read public resources or for use with Shared Access
+ * Signatures (SAS).
+ */
+class AnonymousCredential extends Credential {
+ /**
+ * Creates an {@link AnonymousCredentialPolicy} object.
+ *
+ * @param nextPolicy -
+ * @param options -
+ */
+ create(nextPolicy, options) {
+ return new AnonymousCredentialPolicy(nextPolicy, options);
+ }
+}
+//# sourceMappingURL=AnonymousCredential.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/utils/SharedKeyComparator.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+/*
+ * We need to imitate .Net culture-aware sorting, which is used in storage service.
+ * Below tables contain sort-keys for en-US culture.
+ */
+const table_lv0 = new Uint32Array([
+ 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
+ 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x71c, 0x0, 0x71f, 0x721,
+ 0x723, 0x725, 0x0, 0x0, 0x0, 0x72d, 0x803, 0x0, 0x0, 0x733, 0x0, 0xd03, 0xd1a, 0xd1c, 0xd1e,
+ 0xd20, 0xd22, 0xd24, 0xd26, 0xd28, 0xd2a, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xe02, 0xe09, 0xe0a,
+ 0xe1a, 0xe21, 0xe23, 0xe25, 0xe2c, 0xe32, 0xe35, 0xe36, 0xe48, 0xe51, 0xe70, 0xe7c, 0xe7e, 0xe89,
+ 0xe8a, 0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0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
+ 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
+ 0x0, 0x8012, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8212, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
+ 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
+ 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
+ 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
+ 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
+]);
+function compareHeader(lhs, rhs) {
+ if (isLessThan(lhs, rhs))
+ return -1;
+ return 1;
+}
+function isLessThan(lhs, rhs) {
+ const tables = [table_lv0, table_lv2, table_lv4];
+ let curr_level = 0;
+ let i = 0;
+ let j = 0;
+ while (curr_level < tables.length) {
+ if (curr_level === tables.length - 1 && i !== j) {
+ return i > j;
}
- function cleanup() {
- socket.removeListener('end', onend);
- socket.removeListener('error', onerror);
- socket.removeListener('readable', read);
+ const weight1 = i < lhs.length ? tables[curr_level][lhs[i].charCodeAt(0)] : 0x1;
+ const weight2 = j < rhs.length ? tables[curr_level][rhs[j].charCodeAt(0)] : 0x1;
+ if (weight1 === 0x1 && weight2 === 0x1) {
+ i = 0;
+ j = 0;
+ ++curr_level;
}
- function onend() {
- cleanup();
- debug('onend');
- reject(new Error('Proxy connection ended before receiving CONNECT response'));
+ else if (weight1 === weight2) {
+ ++i;
+ ++j;
}
- function onerror(err) {
- cleanup();
- debug('onerror %o', err);
- reject(err);
+ else if (weight1 === 0) {
+ ++i;
}
- function ondata(b) {
- buffers.push(b);
- buffersLength += b.length;
- const buffered = Buffer.concat(buffers, buffersLength);
- const endOfHeaders = buffered.indexOf('\r\n\r\n');
- if (endOfHeaders === -1) {
- // keep buffering
- debug('have not received end of HTTP headers yet...');
- read();
- return;
- }
- const headerParts = buffered
- .slice(0, endOfHeaders)
- .toString('ascii')
- .split('\r\n');
- const firstLine = headerParts.shift();
- if (!firstLine) {
- socket.destroy();
- return reject(new Error('No header received from proxy CONNECT response'));
- }
- const firstLineParts = firstLine.split(' ');
- const statusCode = +firstLineParts[1];
- const statusText = firstLineParts.slice(2).join(' ');
- const headers = {};
- for (const header of headerParts) {
- if (!header)
- continue;
- const firstColon = header.indexOf(':');
- if (firstColon === -1) {
- socket.destroy();
- return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`));
- }
- const key = header.slice(0, firstColon).toLowerCase();
- const value = header.slice(firstColon + 1).trimStart();
- const current = headers[key];
- if (typeof current === 'string') {
- headers[key] = [current, value];
- }
- else if (Array.isArray(current)) {
- current.push(value);
- }
- else {
- headers[key] = value;
- }
- }
- debug('got proxy server response: %o %o', firstLine, headers);
- cleanup();
- resolve({
- connect: {
- statusCode,
- statusText,
- headers,
- },
- buffered,
- });
+ else if (weight2 === 0) {
+ ++j;
}
- socket.on('error', onerror);
- socket.on('end', onend);
- read();
- });
-}
-exports.parseProxyResponse = parseProxyResponse;
-//# sourceMappingURL=parse-proxy-response.js.map
-
-/***/ }),
-
-/***/ 3772:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-module.exports = minimatch
-minimatch.Minimatch = Minimatch
-
-var path = (function () { try { return __nccwpck_require__(6928) } catch (e) {}}()) || {
- sep: '/'
-}
-minimatch.sep = path.sep
-
-var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {}
-var expand = __nccwpck_require__(4691)
-
-var plTypes = {
- '!': { open: '(?:(?!(?:', close: '))[^/]*?)'},
- '?': { open: '(?:', close: ')?' },
- '+': { open: '(?:', close: ')+' },
- '*': { open: '(?:', close: ')*' },
- '@': { open: '(?:', close: ')' }
+ else {
+ return weight1 < weight2;
+ }
+ }
+ return false;
}
+//# sourceMappingURL=SharedKeyComparator.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/policies/StorageSharedKeyCredentialPolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
-// any single thing other than /
-// don't need to escape / when using new RegExp()
-var qmark = '[^/]'
-
-// * => any number of characters
-var star = qmark + '*?'
-
-// ** when dots are allowed. Anything goes, except .. and .
-// not (^ or / followed by one or two dots followed by $ or /),
-// followed by anything, any number of times.
-var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'
-
-// not a ^ or / followed by a dot,
-// followed by anything, any number of times.
-var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'
-
-// characters that need to be escaped in RegExp.
-var reSpecials = charSet('().*{}+?[]^$\\!')
-
-// "abc" -> { a:true, b:true, c:true }
-function charSet (s) {
- return s.split('').reduce(function (set, c) {
- set[c] = true
- return set
- }, {})
-}
-// normalizes slashes.
-var slashSplit = /\/+/
-minimatch.filter = filter
-function filter (pattern, options) {
- options = options || {}
- return function (p, i, list) {
- return minimatch(p, pattern, options)
- }
-}
-function ext (a, b) {
- b = b || {}
- var t = {}
- Object.keys(a).forEach(function (k) {
- t[k] = a[k]
- })
- Object.keys(b).forEach(function (k) {
- t[k] = b[k]
- })
- return t
+/**
+ * StorageSharedKeyCredentialPolicy is a policy used to sign HTTP request with a shared key.
+ */
+class StorageSharedKeyCredentialPolicy extends CredentialPolicy {
+ /**
+ * Reference to StorageSharedKeyCredential which generates StorageSharedKeyCredentialPolicy
+ */
+ factory;
+ /**
+ * Creates an instance of StorageSharedKeyCredentialPolicy.
+ * @param nextPolicy -
+ * @param options -
+ * @param factory -
+ */
+ constructor(nextPolicy, options, factory) {
+ super(nextPolicy, options);
+ this.factory = factory;
+ }
+ /**
+ * Signs request.
+ *
+ * @param request -
+ */
+ signRequest(request) {
+ request.headers.set(constants_HeaderConstants.X_MS_DATE, new Date().toUTCString());
+ if (request.body &&
+ (typeof request.body === "string" || request.body !== undefined) &&
+ request.body.length > 0) {
+ request.headers.set(constants_HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(request.body));
+ }
+ const stringToSign = [
+ request.method.toUpperCase(),
+ this.getHeaderValueToSign(request, constants_HeaderConstants.CONTENT_LANGUAGE),
+ this.getHeaderValueToSign(request, constants_HeaderConstants.CONTENT_ENCODING),
+ this.getHeaderValueToSign(request, constants_HeaderConstants.CONTENT_LENGTH),
+ this.getHeaderValueToSign(request, constants_HeaderConstants.CONTENT_MD5),
+ this.getHeaderValueToSign(request, constants_HeaderConstants.CONTENT_TYPE),
+ this.getHeaderValueToSign(request, constants_HeaderConstants.DATE),
+ this.getHeaderValueToSign(request, constants_HeaderConstants.IF_MODIFIED_SINCE),
+ this.getHeaderValueToSign(request, constants_HeaderConstants.IF_MATCH),
+ this.getHeaderValueToSign(request, constants_HeaderConstants.IF_NONE_MATCH),
+ this.getHeaderValueToSign(request, constants_HeaderConstants.IF_UNMODIFIED_SINCE),
+ this.getHeaderValueToSign(request, constants_HeaderConstants.RANGE),
+ ].join("\n") +
+ "\n" +
+ this.getCanonicalizedHeadersString(request) +
+ this.getCanonicalizedResourceString(request);
+ const signature = this.factory.computeHMACSHA256(stringToSign);
+ request.headers.set(constants_HeaderConstants.AUTHORIZATION, `SharedKey ${this.factory.accountName}:${signature}`);
+ // console.log(`[URL]:${request.url}`);
+ // console.log(`[HEADERS]:${request.headers.toString()}`);
+ // console.log(`[STRING TO SIGN]:${JSON.stringify(stringToSign)}`);
+ // console.log(`[KEY]: ${request.headers.get(HeaderConstants.AUTHORIZATION)}`);
+ return request;
+ }
+ /**
+ * Retrieve header value according to shared key sign rules.
+ * @see https://learn.microsoft.com/rest/api/storageservices/authenticate-with-shared-key
+ *
+ * @param request -
+ * @param headerName -
+ */
+ getHeaderValueToSign(request, headerName) {
+ const value = request.headers.get(headerName);
+ if (!value) {
+ return "";
+ }
+ // When using version 2015-02-21 or later, if Content-Length is zero, then
+ // set the Content-Length part of the StringToSign to an empty string.
+ // https://learn.microsoft.com/rest/api/storageservices/authenticate-with-shared-key
+ if (headerName === constants_HeaderConstants.CONTENT_LENGTH && value === "0") {
+ return "";
+ }
+ return value;
+ }
+ /**
+ * To construct the CanonicalizedHeaders portion of the signature string, follow these steps:
+ * 1. Retrieve all headers for the resource that begin with x-ms-, including the x-ms-date header.
+ * 2. Convert each HTTP header name to lowercase.
+ * 3. Sort the headers lexicographically by header name, in ascending order.
+ * Each header may appear only once in the string.
+ * 4. Replace any linear whitespace in the header value with a single space.
+ * 5. Trim any whitespace around the colon in the header.
+ * 6. Finally, append a new-line character to each canonicalized header in the resulting list.
+ * Construct the CanonicalizedHeaders string by concatenating all headers in this list into a single string.
+ *
+ * @param request -
+ */
+ getCanonicalizedHeadersString(request) {
+ let headersArray = request.headers.headersArray().filter((value) => {
+ return value.name.toLowerCase().startsWith(constants_HeaderConstants.PREFIX_FOR_STORAGE);
+ });
+ headersArray.sort((a, b) => {
+ return compareHeader(a.name.toLowerCase(), b.name.toLowerCase());
+ });
+ // Remove duplicate headers
+ headersArray = headersArray.filter((value, index, array) => {
+ if (index > 0 && value.name.toLowerCase() === array[index - 1].name.toLowerCase()) {
+ return false;
+ }
+ return true;
+ });
+ let canonicalizedHeadersStringToSign = "";
+ headersArray.forEach((header) => {
+ canonicalizedHeadersStringToSign += `${header.name
+ .toLowerCase()
+ .trimRight()}:${header.value.trimLeft()}\n`;
+ });
+ return canonicalizedHeadersStringToSign;
+ }
+ /**
+ * Retrieves the webResource canonicalized resource string.
+ *
+ * @param request -
+ */
+ getCanonicalizedResourceString(request) {
+ const path = getURLPath(request.url) || "/";
+ let canonicalizedResourceString = "";
+ canonicalizedResourceString += `/${this.factory.accountName}${path}`;
+ const queries = getURLQueries(request.url);
+ const lowercaseQueries = {};
+ if (queries) {
+ const queryKeys = [];
+ for (const key in queries) {
+ if (Object.prototype.hasOwnProperty.call(queries, key)) {
+ const lowercaseKey = key.toLowerCase();
+ lowercaseQueries[lowercaseKey] = queries[key];
+ queryKeys.push(lowercaseKey);
+ }
+ }
+ queryKeys.sort();
+ for (const key of queryKeys) {
+ canonicalizedResourceString += `\n${key}:${decodeURIComponent(lowercaseQueries[key])}`;
+ }
+ }
+ return canonicalizedResourceString;
+ }
}
+//# sourceMappingURL=StorageSharedKeyCredentialPolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/credentials/StorageSharedKeyCredential.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
-minimatch.defaults = function (def) {
- if (!def || typeof def !== 'object' || !Object.keys(def).length) {
- return minimatch
- }
-
- var orig = minimatch
-
- var m = function minimatch (p, pattern, options) {
- return orig(p, pattern, ext(def, options))
- }
-
- m.Minimatch = function Minimatch (pattern, options) {
- return new orig.Minimatch(pattern, ext(def, options))
- }
- m.Minimatch.defaults = function defaults (options) {
- return orig.defaults(ext(def, options)).Minimatch
- }
-
- m.filter = function filter (pattern, options) {
- return orig.filter(pattern, ext(def, options))
- }
-
- m.defaults = function defaults (options) {
- return orig.defaults(ext(def, options))
- }
-
- m.makeRe = function makeRe (pattern, options) {
- return orig.makeRe(pattern, ext(def, options))
- }
-
- m.braceExpand = function braceExpand (pattern, options) {
- return orig.braceExpand(pattern, ext(def, options))
- }
- m.match = function (list, pattern, options) {
- return orig.match(list, pattern, ext(def, options))
- }
- return m
+/**
+ * ONLY AVAILABLE IN NODE.JS RUNTIME.
+ *
+ * StorageSharedKeyCredential for account key authorization of Azure Storage service.
+ */
+class StorageSharedKeyCredential extends Credential {
+ /**
+ * Azure Storage account name; readonly.
+ */
+ accountName;
+ /**
+ * Azure Storage account key; readonly.
+ */
+ accountKey;
+ /**
+ * Creates an instance of StorageSharedKeyCredential.
+ * @param accountName -
+ * @param accountKey -
+ */
+ constructor(accountName, accountKey) {
+ super();
+ this.accountName = accountName;
+ this.accountKey = Buffer.from(accountKey, "base64");
+ }
+ /**
+ * Creates a StorageSharedKeyCredentialPolicy object.
+ *
+ * @param nextPolicy -
+ * @param options -
+ */
+ create(nextPolicy, options) {
+ return new StorageSharedKeyCredentialPolicy(nextPolicy, options, this);
+ }
+ /**
+ * Generates a hash signature for an HTTP request or for a SAS.
+ *
+ * @param stringToSign -
+ */
+ computeHMACSHA256(stringToSign) {
+ return (0,external_node_crypto_.createHmac)("sha256", this.accountKey).update(stringToSign, "utf8").digest("base64");
+ }
}
-
-Minimatch.defaults = function (def) {
- return minimatch.defaults(def).Minimatch
+//# sourceMappingURL=StorageSharedKeyCredential.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/node_modules/@azure/abort-controller/dist/esm/AbortError.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+/**
+ * This error is thrown when an asynchronous operation has been aborted.
+ * Check for this error by testing the `name` that the name property of the
+ * error matches `"AbortError"`.
+ *
+ * @example
+ * ```ts
+ * const controller = new AbortController();
+ * controller.abort();
+ * try {
+ * doAsyncWork(controller.signal)
+ * } catch (e) {
+ * if (e.name === 'AbortError') {
+ * // handle abort error here.
+ * }
+ * }
+ * ```
+ */
+class esm_AbortError_AbortError extends Error {
+ constructor(message) {
+ super(message);
+ this.name = "AbortError";
+ }
}
+//# sourceMappingURL=AbortError.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/node_modules/@azure/abort-controller/dist/esm/index.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
-function minimatch (p, pattern, options) {
- assertValidPattern(pattern)
-
- if (!options) options = {}
-
- // shortcut: comments match nothing.
- if (!options.nocomment && pattern.charAt(0) === '#') {
- return false
- }
-
- return new Minimatch(pattern, options).match(p)
-}
+//# sourceMappingURL=index.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/log.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
-function Minimatch (pattern, options) {
- if (!(this instanceof Minimatch)) {
- return new Minimatch(pattern, options)
- }
+/**
+ * The `@azure/logger` configuration for this package.
+ */
+const storage_common_dist_esm_log_logger = esm_createClientLogger("storage-common");
+//# sourceMappingURL=log.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/policies/StorageRetryPolicyType.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+/**
+ * RetryPolicy types.
+ */
+var StorageRetryPolicyType;
+(function (StorageRetryPolicyType) {
+ /**
+ * Exponential retry. Retry time delay grows exponentially.
+ */
+ StorageRetryPolicyType[StorageRetryPolicyType["EXPONENTIAL"] = 0] = "EXPONENTIAL";
+ /**
+ * Linear retry. Retry time delay grows linearly.
+ */
+ StorageRetryPolicyType[StorageRetryPolicyType["FIXED"] = 1] = "FIXED";
+})(StorageRetryPolicyType || (StorageRetryPolicyType = {}));
+//# sourceMappingURL=StorageRetryPolicyType.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/policies/StorageRetryPolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- assertValidPattern(pattern)
- if (!options) options = {}
- pattern = pattern.trim()
- // windows support: need to use /, not \
- if (!options.allowWindowsEscape && path.sep !== '/') {
- pattern = pattern.split(path.sep).join('/')
- }
- this.options = options
- this.set = []
- this.pattern = pattern
- this.regexp = null
- this.negate = false
- this.comment = false
- this.empty = false
- this.partial = !!options.partial
- // make the set of regexps etc.
- this.make()
+/**
+ * A factory method used to generated a RetryPolicy factory.
+ *
+ * @param retryOptions -
+ */
+function NewRetryPolicyFactory(retryOptions) {
+ return {
+ create: (nextPolicy, options) => {
+ return new StorageRetryPolicy(nextPolicy, options, retryOptions);
+ },
+ };
}
-
-Minimatch.prototype.debug = function () {}
-
-Minimatch.prototype.make = make
-function make () {
- var pattern = this.pattern
- var options = this.options
-
- // empty patterns and comments match nothing.
- if (!options.nocomment && pattern.charAt(0) === '#') {
- this.comment = true
- return
- }
- if (!pattern) {
- this.empty = true
- return
- }
-
- // step 1: figure out negation, etc.
- this.parseNegate()
-
- // step 2: expand braces
- var set = this.globSet = this.braceExpand()
-
- if (options.debug) this.debug = function debug() { console.error.apply(console, arguments) }
-
- this.debug(this.pattern, set)
-
- // step 3: now we have a set, so turn each one into a series of path-portion
- // matching patterns.
- // These will be regexps, except in the case of "**", which is
- // set to the GLOBSTAR object for globstar behavior,
- // and will not contain any / characters
- set = this.globParts = set.map(function (s) {
- return s.split(slashSplit)
- })
-
- this.debug(this.pattern, set)
-
- // glob --> regexps
- set = set.map(function (s, si, set) {
- return s.map(this.parse, this)
- }, this)
-
- this.debug(this.pattern, set)
-
- // filter out everything that didn't compile properly.
- set = set.filter(function (s) {
- return s.indexOf(false) === -1
- })
-
- this.debug(this.pattern, set)
-
- this.set = set
-}
-
-Minimatch.prototype.parseNegate = parseNegate
-function parseNegate () {
- var pattern = this.pattern
- var negate = false
- var options = this.options
- var negateOffset = 0
-
- if (options.nonegate) return
-
- for (var i = 0, l = pattern.length
- ; i < l && pattern.charAt(i) === '!'
- ; i++) {
- negate = !negate
- negateOffset++
- }
-
- if (negateOffset) this.pattern = pattern.substr(negateOffset)
- this.negate = negate
-}
-
-// Brace expansion:
-// a{b,c}d -> abd acd
-// a{b,}c -> abc ac
-// a{0..3}d -> a0d a1d a2d a3d
-// a{b,c{d,e}f}g -> abg acdfg acefg
-// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
-//
-// Invalid sets are not expanded.
-// a{2..}b -> a{2..}b
-// a{b}c -> a{b}c
-minimatch.braceExpand = function (pattern, options) {
- return braceExpand(pattern, options)
-}
-
-Minimatch.prototype.braceExpand = braceExpand
-
-function braceExpand (pattern, options) {
- if (!options) {
- if (this instanceof Minimatch) {
- options = this.options
- } else {
- options = {}
+// Default values of StorageRetryOptions
+const DEFAULT_RETRY_OPTIONS = {
+ maxRetryDelayInMs: 120 * 1000,
+ maxTries: 4,
+ retryDelayInMs: 4 * 1000,
+ retryPolicyType: StorageRetryPolicyType.EXPONENTIAL,
+ secondaryHost: "",
+ tryTimeoutInMs: undefined, // Use server side default timeout strategy
+};
+const RETRY_ABORT_ERROR = new esm_AbortError_AbortError("The operation was aborted.");
+/**
+ * Retry policy with exponential retry and linear retry implemented.
+ */
+class StorageRetryPolicy extends BaseRequestPolicy {
+ /**
+ * RetryOptions.
+ */
+ retryOptions;
+ /**
+ * Creates an instance of RetryPolicy.
+ *
+ * @param nextPolicy -
+ * @param options -
+ * @param retryOptions -
+ */
+ constructor(nextPolicy, options, retryOptions = DEFAULT_RETRY_OPTIONS) {
+ super(nextPolicy, options);
+ // Initialize retry options
+ this.retryOptions = {
+ retryPolicyType: retryOptions.retryPolicyType
+ ? retryOptions.retryPolicyType
+ : DEFAULT_RETRY_OPTIONS.retryPolicyType,
+ maxTries: retryOptions.maxTries && retryOptions.maxTries >= 1
+ ? Math.floor(retryOptions.maxTries)
+ : DEFAULT_RETRY_OPTIONS.maxTries,
+ tryTimeoutInMs: retryOptions.tryTimeoutInMs && retryOptions.tryTimeoutInMs >= 0
+ ? retryOptions.tryTimeoutInMs
+ : DEFAULT_RETRY_OPTIONS.tryTimeoutInMs,
+ retryDelayInMs: retryOptions.retryDelayInMs && retryOptions.retryDelayInMs >= 0
+ ? Math.min(retryOptions.retryDelayInMs, retryOptions.maxRetryDelayInMs
+ ? retryOptions.maxRetryDelayInMs
+ : DEFAULT_RETRY_OPTIONS.maxRetryDelayInMs)
+ : DEFAULT_RETRY_OPTIONS.retryDelayInMs,
+ maxRetryDelayInMs: retryOptions.maxRetryDelayInMs && retryOptions.maxRetryDelayInMs >= 0
+ ? retryOptions.maxRetryDelayInMs
+ : DEFAULT_RETRY_OPTIONS.maxRetryDelayInMs,
+ secondaryHost: retryOptions.secondaryHost
+ ? retryOptions.secondaryHost
+ : DEFAULT_RETRY_OPTIONS.secondaryHost,
+ };
+ }
+ /**
+ * Sends request.
+ *
+ * @param request -
+ */
+ async sendRequest(request) {
+ return this.attemptSendRequest(request, false, 1);
+ }
+ /**
+ * Decide and perform next retry. Won't mutate request parameter.
+ *
+ * @param request -
+ * @param secondaryHas404 - If attempt was against the secondary & it returned a StatusNotFound (404), then
+ * the resource was not found. This may be due to replication delay. So, in this
+ * case, we'll never try the secondary again for this operation.
+ * @param attempt - How many retries has been attempted to performed, starting from 1, which includes
+ * the attempt will be performed by this method call.
+ */
+ async attemptSendRequest(request, secondaryHas404, attempt) {
+ const newRequest = request.clone();
+ const isPrimaryRetry = secondaryHas404 ||
+ !this.retryOptions.secondaryHost ||
+ !(request.method === "GET" || request.method === "HEAD" || request.method === "OPTIONS") ||
+ attempt % 2 === 1;
+ if (!isPrimaryRetry) {
+ newRequest.url = setURLHost(newRequest.url, this.retryOptions.secondaryHost);
+ }
+ // Set the server-side timeout query parameter "timeout=[seconds]"
+ if (this.retryOptions.tryTimeoutInMs) {
+ newRequest.url = setURLParameter(newRequest.url, constants_URLConstants.Parameters.TIMEOUT, Math.floor(this.retryOptions.tryTimeoutInMs / 1000).toString());
+ }
+ let response;
+ try {
+ storage_common_dist_esm_log_logger.info(`RetryPolicy: =====> Try=${attempt} ${isPrimaryRetry ? "Primary" : "Secondary"}`);
+ response = await this._nextPolicy.sendRequest(newRequest);
+ if (!this.shouldRetry(isPrimaryRetry, attempt, response)) {
+ return response;
+ }
+ secondaryHas404 = secondaryHas404 || (!isPrimaryRetry && response.status === 404);
+ }
+ catch (err) {
+ storage_common_dist_esm_log_logger.error(`RetryPolicy: Caught error, message: ${err.message}, code: ${err.code}`);
+ if (!this.shouldRetry(isPrimaryRetry, attempt, response, err)) {
+ throw err;
+ }
+ }
+ await this.delay(isPrimaryRetry, attempt, request.abortSignal);
+ return this.attemptSendRequest(request, secondaryHas404, ++attempt);
+ }
+ /**
+ * Decide whether to retry according to last HTTP response and retry counters.
+ *
+ * @param isPrimaryRetry -
+ * @param attempt -
+ * @param response -
+ * @param err -
+ */
+ shouldRetry(isPrimaryRetry, attempt, response, err) {
+ if (attempt >= this.retryOptions.maxTries) {
+ storage_common_dist_esm_log_logger.info(`RetryPolicy: Attempt(s) ${attempt} >= maxTries ${this.retryOptions
+ .maxTries}, no further try.`);
+ return false;
+ }
+ // Handle network failures, you may need to customize the list when you implement
+ // your own http client
+ const retriableErrors = [
+ "ETIMEDOUT",
+ "ESOCKETTIMEDOUT",
+ "ECONNREFUSED",
+ "ECONNRESET",
+ "ENOENT",
+ "ENOTFOUND",
+ "TIMEOUT",
+ "EPIPE",
+ "REQUEST_SEND_ERROR", // For default xhr based http client provided in ms-rest-js
+ ];
+ if (err) {
+ for (const retriableError of retriableErrors) {
+ if (err.name.toUpperCase().includes(retriableError) ||
+ err.message.toUpperCase().includes(retriableError) ||
+ (err.code && err.code.toString().toUpperCase() === retriableError)) {
+ storage_common_dist_esm_log_logger.info(`RetryPolicy: Network error ${retriableError} found, will retry.`);
+ return true;
+ }
+ }
+ }
+ // If attempt was against the secondary & it returned a StatusNotFound (404), then
+ // the resource was not found. This may be due to replication delay. So, in this
+ // case, we'll never try the secondary again for this operation.
+ if (response || err) {
+ const statusCode = response ? response.status : err ? err.statusCode : 0;
+ if (!isPrimaryRetry && statusCode === 404) {
+ storage_common_dist_esm_log_logger.info(`RetryPolicy: Secondary access with 404, will retry.`);
+ return true;
+ }
+ // Server internal error or server timeout
+ if (statusCode === 503 || statusCode === 500) {
+ storage_common_dist_esm_log_logger.info(`RetryPolicy: Will retry for status code ${statusCode}.`);
+ return true;
+ }
+ }
+ if (response) {
+ // Retry select Copy Source Error Codes.
+ if (response?.status >= 400) {
+ const copySourceError = response.headers.get(constants_HeaderConstants.X_MS_CopySourceErrorCode);
+ if (copySourceError !== undefined) {
+ switch (copySourceError) {
+ case "InternalError":
+ case "OperationTimedOut":
+ case "ServerBusy":
+ return true;
+ }
+ }
+ }
+ }
+ if (err?.code === "PARSE_ERROR" && err?.message.startsWith(`Error "Error: Unclosed root tag`)) {
+ storage_common_dist_esm_log_logger.info("RetryPolicy: Incomplete XML response likely due to service timeout, will retry.");
+ return true;
+ }
+ return false;
+ }
+ /**
+ * Delay a calculated time between retries.
+ *
+ * @param isPrimaryRetry -
+ * @param attempt -
+ * @param abortSignal -
+ */
+ async delay(isPrimaryRetry, attempt, abortSignal) {
+ let delayTimeInMs = 0;
+ if (isPrimaryRetry) {
+ switch (this.retryOptions.retryPolicyType) {
+ case StorageRetryPolicyType.EXPONENTIAL:
+ delayTimeInMs = Math.min((Math.pow(2, attempt - 1) - 1) * this.retryOptions.retryDelayInMs, this.retryOptions.maxRetryDelayInMs);
+ break;
+ case StorageRetryPolicyType.FIXED:
+ delayTimeInMs = this.retryOptions.retryDelayInMs;
+ break;
+ }
+ }
+ else {
+ delayTimeInMs = Math.random() * 1000;
+ }
+ storage_common_dist_esm_log_logger.info(`RetryPolicy: Delay for ${delayTimeInMs}ms`);
+ return utils_common_delay(delayTimeInMs, abortSignal, RETRY_ABORT_ERROR);
}
- }
-
- pattern = typeof pattern === 'undefined'
- ? this.pattern : pattern
-
- assertValidPattern(pattern)
-
- // Thanks to Yeting Li for
- // improving this regexp to avoid a ReDOS vulnerability.
- if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
- // shortcut. no need to expand.
- return [pattern]
- }
-
- return expand(pattern)
-}
-
-var MAX_PATTERN_LENGTH = 1024 * 64
-var assertValidPattern = function (pattern) {
- if (typeof pattern !== 'string') {
- throw new TypeError('invalid pattern')
- }
-
- if (pattern.length > MAX_PATTERN_LENGTH) {
- throw new TypeError('pattern is too long')
- }
}
+//# sourceMappingURL=StorageRetryPolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/StorageRetryPolicyFactory.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
-// parse a component of the expanded set.
-// At this point, no pattern may contain "/" in it
-// so we're going to return a 2d array, where each entry is the full
-// pattern, split on '/', and then turned into a regular expression.
-// A regexp is made at the end which joins each array with an
-// escaped /, and another full one which joins each regexp with |.
-//
-// Following the lead of Bash 4.1, note that "**" only has special meaning
-// when it is the *only* thing in a path portion. Otherwise, any series
-// of * is equivalent to a single *. Globstar behavior is enabled by
-// default, and can be disabled by setting options.noglobstar.
-Minimatch.prototype.parse = parse
-var SUBPARSE = {}
-function parse (pattern, isSub) {
- assertValidPattern(pattern)
-
- var options = this.options
-
- // shortcuts
- if (pattern === '**') {
- if (!options.noglobstar)
- return GLOBSTAR
- else
- pattern = '*'
- }
- if (pattern === '') return ''
- var re = ''
- var hasMagic = !!options.nocase
- var escaping = false
- // ? => one single character
- var patternListStack = []
- var negativeLists = []
- var stateChar
- var inClass = false
- var reClassStart = -1
- var classStart = -1
- // . and .. never match anything that doesn't start with .,
- // even when options.dot is set.
- var patternStart = pattern.charAt(0) === '.' ? '' // anything
- // not (start or / followed by . or .. followed by / or end)
- : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))'
- : '(?!\\.)'
- var self = this
- function clearStateChar () {
- if (stateChar) {
- // we had some state-tracking character
- // that wasn't consumed by this pass.
- switch (stateChar) {
- case '*':
- re += star
- hasMagic = true
- break
- case '?':
- re += qmark
- hasMagic = true
- break
- default:
- re += '\\' + stateChar
- break
- }
- self.debug('clearStateChar %j %j', stateChar, re)
- stateChar = false
+/**
+ * StorageRetryPolicyFactory is a factory class helping generating {@link StorageRetryPolicy} objects.
+ */
+class StorageRetryPolicyFactory {
+ retryOptions;
+ /**
+ * Creates an instance of StorageRetryPolicyFactory.
+ * @param retryOptions -
+ */
+ constructor(retryOptions) {
+ this.retryOptions = retryOptions;
}
- }
-
- for (var i = 0, len = pattern.length, c
- ; (i < len) && (c = pattern.charAt(i))
- ; i++) {
- this.debug('%s\t%s %s %j', pattern, i, re, c)
-
- // skip over any that are escaped.
- if (escaping && reSpecials[c]) {
- re += '\\' + c
- escaping = false
- continue
+ /**
+ * Creates a StorageRetryPolicy object.
+ *
+ * @param nextPolicy -
+ * @param options -
+ */
+ create(nextPolicy, options) {
+ return new StorageRetryPolicy(nextPolicy, options, this.retryOptions);
}
+}
+//# sourceMappingURL=StorageRetryPolicyFactory.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/policies/StorageBrowserPolicyV2.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- switch (c) {
- /* istanbul ignore next */
- case '/': {
- // completely not allowed, even escaped.
- // Should already be path-split by now.
- return false
- }
- case '\\':
- clearStateChar()
- escaping = true
- continue
- // the various stateChar values
- // for the "extglob" stuff.
- case '?':
- case '*':
- case '+':
- case '@':
- case '!':
- this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c)
+/**
+ * The programmatic identifier of the StorageBrowserPolicy.
+ */
+const storageBrowserPolicyName = "storageBrowserPolicy";
+/**
+ * storageBrowserPolicy is a policy used to prevent browsers from caching requests
+ * and to remove cookies and explicit content-length headers.
+ */
+function storageBrowserPolicy() {
+ return {
+ name: storageBrowserPolicyName,
+ async sendRequest(request, next) {
+ if (esm_isNodeLike) {
+ return next(request);
+ }
+ if (request.method === "GET" || request.method === "HEAD") {
+ request.url = setURLParameter(request.url, constants_URLConstants.Parameters.FORCE_BROWSER_NO_CACHE, new Date().getTime().toString());
+ }
+ request.headers.delete(constants_HeaderConstants.COOKIE);
+ // According to XHR standards, content-length should be fully controlled by browsers
+ request.headers.delete(constants_HeaderConstants.CONTENT_LENGTH);
+ return next(request);
+ },
+ };
+}
+//# sourceMappingURL=StorageBrowserPolicyV2.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/policies/StorageCorrectContentLengthPolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- // all of those are literals inside a class, except that
- // the glob [!a] means [^a] in regexp
- if (inClass) {
- this.debug(' in class')
- if (c === '!' && i === classStart + 1) c = '^'
- re += c
- continue
+/**
+ * The programmatic identifier of the storageCorrectContentLengthPolicy.
+ */
+const storageCorrectContentLengthPolicyName = "StorageCorrectContentLengthPolicy";
+/**
+ * storageCorrectContentLengthPolicy to correctly set Content-Length header with request body length.
+ */
+function storageCorrectContentLengthPolicy() {
+ function correctContentLength(request) {
+ if (request.body &&
+ (typeof request.body === "string" || Buffer.isBuffer(request.body)) &&
+ request.body.length > 0) {
+ request.headers.set(constants_HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(request.body));
}
+ }
+ return {
+ name: storageCorrectContentLengthPolicyName,
+ async sendRequest(request, next) {
+ correctContentLength(request);
+ return next(request);
+ },
+ };
+}
+//# sourceMappingURL=StorageCorrectContentLengthPolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/policies/StorageRetryPolicyV2.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- // if we already have a stateChar, then it means
- // that there was something like ** or +? in there.
- // Handle the stateChar, then proceed with this one.
- self.debug('call clearStateChar %j', stateChar)
- clearStateChar()
- stateChar = c
- // if extglob is disabled, then +(asdf|foo) isn't a thing.
- // just clear the statechar *now*, rather than even diving into
- // the patternList stuff.
- if (options.noext) clearStateChar()
- continue
-
- case '(':
- if (inClass) {
- re += '('
- continue
- }
- if (!stateChar) {
- re += '\\('
- continue
- }
- patternListStack.push({
- type: stateChar,
- start: i - 1,
- reStart: re.length,
- open: plTypes[stateChar].open,
- close: plTypes[stateChar].close
- })
- // negation is (?:(?!js)[^/]*)
- re += stateChar === '!' ? '(?:(?!(?:' : '(?:'
- this.debug('plType %j %j', stateChar, re)
- stateChar = false
- continue
- case ')':
- if (inClass || !patternListStack.length) {
- re += '\\)'
- continue
- }
- clearStateChar()
- hasMagic = true
- var pl = patternListStack.pop()
- // negation is (?:(?!js)[^/]*)
- // The others are (?:)
- re += pl.close
- if (pl.type === '!') {
- negativeLists.push(pl)
- }
- pl.reEnd = re.length
- continue
- case '|':
- if (inClass || !patternListStack.length || escaping) {
- re += '\\|'
- escaping = false
- continue
- }
- clearStateChar()
- re += '|'
- continue
+/**
+ * Name of the {@link storageRetryPolicy}
+ */
+const storageRetryPolicyName = "storageRetryPolicy";
+// Default values of StorageRetryOptions
+const StorageRetryPolicyV2_DEFAULT_RETRY_OPTIONS = {
+ maxRetryDelayInMs: 120 * 1000,
+ maxTries: 4,
+ retryDelayInMs: 4 * 1000,
+ retryPolicyType: StorageRetryPolicyType.EXPONENTIAL,
+ secondaryHost: "",
+ tryTimeoutInMs: undefined, // Use server side default timeout strategy
+};
+const retriableErrors = [
+ "ETIMEDOUT",
+ "ESOCKETTIMEDOUT",
+ "ECONNREFUSED",
+ "ECONNRESET",
+ "ENOENT",
+ "ENOTFOUND",
+ "TIMEOUT",
+ "EPIPE",
+ "REQUEST_SEND_ERROR",
+];
+const StorageRetryPolicyV2_RETRY_ABORT_ERROR = new esm_AbortError_AbortError("The operation was aborted.");
+/**
+ * Retry policy with exponential retry and linear retry implemented.
+ */
+function storageRetryPolicy(options = {}) {
+ const retryPolicyType = options.retryPolicyType ?? StorageRetryPolicyV2_DEFAULT_RETRY_OPTIONS.retryPolicyType;
+ const maxTries = options.maxTries ?? StorageRetryPolicyV2_DEFAULT_RETRY_OPTIONS.maxTries;
+ const retryDelayInMs = options.retryDelayInMs ?? StorageRetryPolicyV2_DEFAULT_RETRY_OPTIONS.retryDelayInMs;
+ const maxRetryDelayInMs = options.maxRetryDelayInMs ?? StorageRetryPolicyV2_DEFAULT_RETRY_OPTIONS.maxRetryDelayInMs;
+ const secondaryHost = options.secondaryHost ?? StorageRetryPolicyV2_DEFAULT_RETRY_OPTIONS.secondaryHost;
+ const tryTimeoutInMs = options.tryTimeoutInMs ?? StorageRetryPolicyV2_DEFAULT_RETRY_OPTIONS.tryTimeoutInMs;
+ function shouldRetry({ isPrimaryRetry, attempt, response, error, }) {
+ if (attempt >= maxTries) {
+ storage_common_dist_esm_log_logger.info(`RetryPolicy: Attempt(s) ${attempt} >= maxTries ${maxTries}, no further try.`);
+ return false;
+ }
+ if (error) {
+ for (const retriableError of retriableErrors) {
+ if (error.name.toUpperCase().includes(retriableError) ||
+ error.message.toUpperCase().includes(retriableError) ||
+ (error.code && error.code.toString().toUpperCase() === retriableError)) {
+ storage_common_dist_esm_log_logger.info(`RetryPolicy: Network error ${retriableError} found, will retry.`);
+ return true;
+ }
+ }
+ if (error?.code === "PARSE_ERROR" &&
+ error?.message.startsWith(`Error "Error: Unclosed root tag`)) {
+ storage_common_dist_esm_log_logger.info("RetryPolicy: Incomplete XML response likely due to service timeout, will retry.");
+ return true;
+ }
+ }
+ // If attempt was against the secondary & it returned a StatusNotFound (404), then
+ // the resource was not found. This may be due to replication delay. So, in this
+ // case, we'll never try the secondary again for this operation.
+ if (response || error) {
+ const statusCode = response?.status ?? error?.statusCode ?? 0;
+ if (!isPrimaryRetry && statusCode === 404) {
+ storage_common_dist_esm_log_logger.info(`RetryPolicy: Secondary access with 404, will retry.`);
+ return true;
+ }
+ // Server internal error or server timeout
+ if (statusCode === 503 || statusCode === 500) {
+ storage_common_dist_esm_log_logger.info(`RetryPolicy: Will retry for status code ${statusCode}.`);
+ return true;
+ }
+ }
+ if (response) {
+ // Retry select Copy Source Error Codes.
+ if (response?.status >= 400) {
+ const copySourceError = response.headers.get(constants_HeaderConstants.X_MS_CopySourceErrorCode);
+ if (copySourceError !== undefined) {
+ switch (copySourceError) {
+ case "InternalError":
+ case "OperationTimedOut":
+ case "ServerBusy":
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+ }
+ function calculateDelay(isPrimaryRetry, attempt) {
+ let delayTimeInMs = 0;
+ if (isPrimaryRetry) {
+ switch (retryPolicyType) {
+ case StorageRetryPolicyType.EXPONENTIAL:
+ delayTimeInMs = Math.min((Math.pow(2, attempt - 1) - 1) * retryDelayInMs, maxRetryDelayInMs);
+ break;
+ case StorageRetryPolicyType.FIXED:
+ delayTimeInMs = retryDelayInMs;
+ break;
+ }
+ }
+ else {
+ delayTimeInMs = Math.random() * 1000;
+ }
+ storage_common_dist_esm_log_logger.info(`RetryPolicy: Delay for ${delayTimeInMs}ms`);
+ return delayTimeInMs;
+ }
+ return {
+ name: storageRetryPolicyName,
+ async sendRequest(request, next) {
+ // Set the server-side timeout query parameter "timeout=[seconds]"
+ if (tryTimeoutInMs) {
+ request.url = setURLParameter(request.url, constants_URLConstants.Parameters.TIMEOUT, String(Math.floor(tryTimeoutInMs / 1000)));
+ }
+ const primaryUrl = request.url;
+ const secondaryUrl = secondaryHost ? setURLHost(request.url, secondaryHost) : undefined;
+ let secondaryHas404 = false;
+ let attempt = 1;
+ let retryAgain = true;
+ let response;
+ let error;
+ while (retryAgain) {
+ const isPrimaryRetry = secondaryHas404 ||
+ !secondaryUrl ||
+ !["GET", "HEAD", "OPTIONS"].includes(request.method) ||
+ attempt % 2 === 1;
+ request.url = isPrimaryRetry ? primaryUrl : secondaryUrl;
+ response = undefined;
+ error = undefined;
+ try {
+ storage_common_dist_esm_log_logger.info(`RetryPolicy: =====> Try=${attempt} ${isPrimaryRetry ? "Primary" : "Secondary"}`);
+ response = await next(request);
+ secondaryHas404 = secondaryHas404 || (!isPrimaryRetry && response.status === 404);
+ }
+ catch (e) {
+ if (esm_restError_isRestError(e)) {
+ storage_common_dist_esm_log_logger.error(`RetryPolicy: Caught error, message: ${e.message}, code: ${e.code}`);
+ error = e;
+ }
+ else {
+ storage_common_dist_esm_log_logger.error(`RetryPolicy: Caught error, message: ${getErrorMessage(e)}`);
+ throw e;
+ }
+ }
+ retryAgain = shouldRetry({ isPrimaryRetry, attempt, response, error });
+ if (retryAgain) {
+ await utils_common_delay(calculateDelay(isPrimaryRetry, attempt), request.abortSignal, StorageRetryPolicyV2_RETRY_ABORT_ERROR);
+ }
+ attempt++;
+ }
+ if (response) {
+ return response;
+ }
+ throw error ?? new esm_restError_RestError("RetryPolicy failed without known error.");
+ },
+ };
+}
+//# sourceMappingURL=StorageRetryPolicyV2.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/policies/StorageSharedKeyCredentialPolicyV2.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- // these are mostly the same in regexp and glob
- case '[':
- // swallow any state-tracking char before the [
- clearStateChar()
- if (inClass) {
- re += '\\' + c
- continue
- }
- inClass = true
- classStart = i
- reClassStart = re.length
- re += c
- continue
- case ']':
- // a right bracket shall lose its special
- // meaning and represent itself in
- // a bracket expression if it occurs
- // first in the list. -- POSIX.2 2.8.3.2
- if (i === classStart + 1 || !inClass) {
- re += '\\' + c
- escaping = false
- continue
+/**
+ * The programmatic identifier of the storageSharedKeyCredentialPolicy.
+ */
+const storageSharedKeyCredentialPolicyName = "storageSharedKeyCredentialPolicy";
+/**
+ * storageSharedKeyCredentialPolicy handles signing requests using storage account keys.
+ */
+function storageSharedKeyCredentialPolicy(options) {
+ function signRequest(request) {
+ request.headers.set(constants_HeaderConstants.X_MS_DATE, new Date().toUTCString());
+ if (request.body &&
+ (typeof request.body === "string" || Buffer.isBuffer(request.body)) &&
+ request.body.length > 0) {
+ request.headers.set(constants_HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(request.body));
}
-
- // handle the case where we left a class open.
- // "[z-a]" is valid, equivalent to "\[z-a\]"
- // split where the last [ was, make sure we don't have
- // an invalid re. if so, re-walk the contents of the
- // would-be class to re-translate any characters that
- // were passed through as-is
- // TODO: It would probably be faster to determine this
- // without a try/catch and a new RegExp, but it's tricky
- // to do safely. For now, this is safe and works.
- var cs = pattern.substring(classStart + 1, i)
- try {
- RegExp('[' + cs + ']')
- } catch (er) {
- // not a valid class!
- var sp = this.parse(cs, SUBPARSE)
- re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]'
- hasMagic = hasMagic || sp[1]
- inClass = false
- continue
+ const stringToSign = [
+ request.method.toUpperCase(),
+ getHeaderValueToSign(request, constants_HeaderConstants.CONTENT_LANGUAGE),
+ getHeaderValueToSign(request, constants_HeaderConstants.CONTENT_ENCODING),
+ getHeaderValueToSign(request, constants_HeaderConstants.CONTENT_LENGTH),
+ getHeaderValueToSign(request, constants_HeaderConstants.CONTENT_MD5),
+ getHeaderValueToSign(request, constants_HeaderConstants.CONTENT_TYPE),
+ getHeaderValueToSign(request, constants_HeaderConstants.DATE),
+ getHeaderValueToSign(request, constants_HeaderConstants.IF_MODIFIED_SINCE),
+ getHeaderValueToSign(request, constants_HeaderConstants.IF_MATCH),
+ getHeaderValueToSign(request, constants_HeaderConstants.IF_NONE_MATCH),
+ getHeaderValueToSign(request, constants_HeaderConstants.IF_UNMODIFIED_SINCE),
+ getHeaderValueToSign(request, constants_HeaderConstants.RANGE),
+ ].join("\n") +
+ "\n" +
+ getCanonicalizedHeadersString(request) +
+ getCanonicalizedResourceString(request);
+ const signature = (0,external_node_crypto_.createHmac)("sha256", options.accountKey)
+ .update(stringToSign, "utf8")
+ .digest("base64");
+ request.headers.set(constants_HeaderConstants.AUTHORIZATION, `SharedKey ${options.accountName}:${signature}`);
+ // console.log(`[URL]:${request.url}`);
+ // console.log(`[HEADERS]:${request.headers.toString()}`);
+ // console.log(`[STRING TO SIGN]:${JSON.stringify(stringToSign)}`);
+ // console.log(`[KEY]: ${request.headers.get(HeaderConstants.AUTHORIZATION)}`);
+ }
+ /**
+ * Retrieve header value according to shared key sign rules.
+ * @see https://learn.microsoft.com/rest/api/storageservices/authenticate-with-shared-key
+ */
+ function getHeaderValueToSign(request, headerName) {
+ const value = request.headers.get(headerName);
+ if (!value) {
+ return "";
+ }
+ // When using version 2015-02-21 or later, if Content-Length is zero, then
+ // set the Content-Length part of the StringToSign to an empty string.
+ // https://learn.microsoft.com/rest/api/storageservices/authenticate-with-shared-key
+ if (headerName === constants_HeaderConstants.CONTENT_LENGTH && value === "0") {
+ return "";
}
+ return value;
+ }
+ /**
+ * To construct the CanonicalizedHeaders portion of the signature string, follow these steps:
+ * 1. Retrieve all headers for the resource that begin with x-ms-, including the x-ms-date header.
+ * 2. Convert each HTTP header name to lowercase.
+ * 3. Sort the headers lexicographically by header name, in ascending order.
+ * Each header may appear only once in the string.
+ * 4. Replace any linear whitespace in the header value with a single space.
+ * 5. Trim any whitespace around the colon in the header.
+ * 6. Finally, append a new-line character to each canonicalized header in the resulting list.
+ * Construct the CanonicalizedHeaders string by concatenating all headers in this list into a single string.
+ *
+ */
+ function getCanonicalizedHeadersString(request) {
+ let headersArray = [];
+ for (const [name, value] of request.headers) {
+ if (name.toLowerCase().startsWith(constants_HeaderConstants.PREFIX_FOR_STORAGE)) {
+ headersArray.push({ name, value });
+ }
+ }
+ headersArray.sort((a, b) => {
+ return compareHeader(a.name.toLowerCase(), b.name.toLowerCase());
+ });
+ // Remove duplicate headers
+ headersArray = headersArray.filter((value, index, array) => {
+ if (index > 0 && value.name.toLowerCase() === array[index - 1].name.toLowerCase()) {
+ return false;
+ }
+ return true;
+ });
+ let canonicalizedHeadersStringToSign = "";
+ headersArray.forEach((header) => {
+ canonicalizedHeadersStringToSign += `${header.name
+ .toLowerCase()
+ .trimRight()}:${header.value.trimLeft()}\n`;
+ });
+ return canonicalizedHeadersStringToSign;
+ }
+ function getCanonicalizedResourceString(request) {
+ const path = getURLPath(request.url) || "/";
+ let canonicalizedResourceString = "";
+ canonicalizedResourceString += `/${options.accountName}${path}`;
+ const queries = getURLQueries(request.url);
+ const lowercaseQueries = {};
+ if (queries) {
+ const queryKeys = [];
+ for (const key in queries) {
+ if (Object.prototype.hasOwnProperty.call(queries, key)) {
+ const lowercaseKey = key.toLowerCase();
+ lowercaseQueries[lowercaseKey] = queries[key];
+ queryKeys.push(lowercaseKey);
+ }
+ }
+ queryKeys.sort();
+ for (const key of queryKeys) {
+ canonicalizedResourceString += `\n${key}:${decodeURIComponent(lowercaseQueries[key])}`;
+ }
+ }
+ return canonicalizedResourceString;
+ }
+ return {
+ name: storageSharedKeyCredentialPolicyName,
+ async sendRequest(request, next) {
+ signRequest(request);
+ return next(request);
+ },
+ };
+}
+//# sourceMappingURL=StorageSharedKeyCredentialPolicyV2.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/policies/StorageRequestFailureDetailsParserPolicy.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+/**
+ * The programmatic identifier of the StorageRequestFailureDetailsParserPolicy.
+ */
+const storageRequestFailureDetailsParserPolicyName = "storageRequestFailureDetailsParserPolicy";
+/**
+ * StorageRequestFailureDetailsParserPolicy
+ */
+function storageRequestFailureDetailsParserPolicy() {
+ return {
+ name: storageRequestFailureDetailsParserPolicyName,
+ async sendRequest(request, next) {
+ try {
+ const response = await next(request);
+ return response;
+ }
+ catch (err) {
+ if (typeof err === "object" &&
+ err !== null &&
+ err.response &&
+ err.response.parsedBody) {
+ if (err.response.parsedBody.code === "InvalidHeaderValue" &&
+ err.response.parsedBody.HeaderName === "x-ms-version") {
+ err.message =
+ "The provided service version is not enabled on this storage account. Please see https://learn.microsoft.com/rest/api/storageservices/versioning-for-the-azure-storage-services for additional information.\n";
+ }
+ }
+ throw err;
+ }
+ },
+ };
+}
+//# sourceMappingURL=StorageRequestFailureDetailsParserPolicy.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/credentials/UserDelegationKeyCredential.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- // finish up the class.
- hasMagic = true
- inClass = false
- re += c
- continue
+/**
+ * ONLY AVAILABLE IN NODE.JS RUNTIME.
+ *
+ * UserDelegationKeyCredential is only used for generation of user delegation SAS.
+ * @see https://learn.microsoft.com/rest/api/storageservices/create-user-delegation-sas
+ */
+class UserDelegationKeyCredential {
+ /**
+ * Azure Storage account name; readonly.
+ */
+ accountName;
+ /**
+ * Azure Storage user delegation key; readonly.
+ */
+ userDelegationKey;
+ /**
+ * Key value in Buffer type.
+ */
+ key;
+ /**
+ * Creates an instance of UserDelegationKeyCredential.
+ * @param accountName -
+ * @param userDelegationKey -
+ */
+ constructor(accountName, userDelegationKey) {
+ this.accountName = accountName;
+ this.userDelegationKey = userDelegationKey;
+ this.key = Buffer.from(userDelegationKey.value, "base64");
+ }
+ /**
+ * Generates a hash signature for an HTTP request or for a SAS.
+ *
+ * @param stringToSign -
+ */
+ computeHMACSHA256(stringToSign) {
+ // console.log(`stringToSign: ${JSON.stringify(stringToSign)}`);
+ return (0,external_node_crypto_.createHmac)("sha256", this.key).update(stringToSign, "utf8").digest("base64");
+ }
+}
+//# sourceMappingURL=UserDelegationKeyCredential.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/index.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
- default:
- // swallow any state char that wasn't consumed
- clearStateChar()
- if (escaping) {
- // no need
- escaping = false
- } else if (reSpecials[c]
- && !(c === '^' && inClass)) {
- re += '\\'
- }
- re += c
- } // switch
- } // for
- // handle the case where we left a class open.
- // "[abc" is valid, equivalent to "\[abc"
- if (inClass) {
- // split where the last [ was, and escape it
- // this is a huge pita. We now have to re-walk
- // the contents of the would-be class to re-translate
- // any characters that were passed through as-is
- cs = pattern.substr(classStart + 1)
- sp = this.parse(cs, SUBPARSE)
- re = re.substr(0, reClassStart) + '\\[' + sp[0]
- hasMagic = hasMagic || sp[1]
- }
- // handle the case where we had a +( thing at the *end*
- // of the pattern.
- // each pattern list stack adds 3 chars, and we need to go through
- // and escape any | chars that were passed through as-is for the regexp.
- // Go through and escape them, taking care not to double-escape any
- // | chars that were already escaped.
- for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
- var tail = re.slice(pl.reStart + pl.open.length)
- this.debug('setting tail', re, pl)
- // maybe some even number of \, then maybe 1 \, followed by a |
- tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) {
- if (!$2) {
- // the | isn't already escaped, so escape it.
- $2 = '\\'
- }
- // need to escape all those slashes *again*, without escaping the
- // one that we need for escaping the | character. As it works out,
- // escaping an even number of slashes can be done by simply repeating
- // it exactly after itself. That's why this trick works.
- //
- // I am sorry that you have to see this.
- return $1 + $1 + $2 + '|'
- })
- this.debug('tail=%j\n %s', tail, tail, pl, re)
- var t = pl.type === '*' ? star
- : pl.type === '?' ? qmark
- : '\\' + pl.type
- hasMagic = true
- re = re.slice(0, pl.reStart) + t + '\\(' + tail
- }
- // handle trailing things that only matter at the very end.
- clearStateChar()
- if (escaping) {
- // trailing \\
- re += '\\\\'
- }
- // only need to apply the nodot start if the re starts with
- // something that could conceivably capture a dot
- var addPatternStart = false
- switch (re.charAt(0)) {
- case '[': case '.': case '(': addPatternStart = true
- }
- // Hack to work around lack of negative lookbehind in JS
- // A pattern like: *.!(x).!(y|z) needs to ensure that a name
- // like 'a.xyz.yz' doesn't match. So, the first negative
- // lookahead, has to look ALL the way ahead, to the end of
- // the pattern.
- for (var n = negativeLists.length - 1; n > -1; n--) {
- var nl = negativeLists[n]
- var nlBefore = re.slice(0, nl.reStart)
- var nlFirst = re.slice(nl.reStart, nl.reEnd - 8)
- var nlLast = re.slice(nl.reEnd - 8, nl.reEnd)
- var nlAfter = re.slice(nl.reEnd)
- nlLast += nlAfter
- // Handle nested stuff like *(*.js|!(*.json)), where open parens
- // mean that we should *not* include the ) in the bit that is considered
- // "after" the negated section.
- var openParensBefore = nlBefore.split('(').length - 1
- var cleanAfter = nlAfter
- for (i = 0; i < openParensBefore; i++) {
- cleanAfter = cleanAfter.replace(/\)[+*?]?/, '')
- }
- nlAfter = cleanAfter
- var dollar = ''
- if (nlAfter === '' && isSub !== SUBPARSE) {
- dollar = '$'
- }
- var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast
- re = newRe
- }
- // if the re is not "" at this point, then we need to make sure
- // it doesn't match against an empty path part.
- // Otherwise a/* will match a/, which it should not.
- if (re !== '' && hasMagic) {
- re = '(?=.)' + re
- }
-
- if (addPatternStart) {
- re = patternStart + re
- }
-
- // parsing just a piece of a larger pattern.
- if (isSub === SUBPARSE) {
- return [re, hasMagic]
- }
-
- // skip the regexp for non-magical patterns
- // unescape anything in it, though, so that it'll be
- // an exact match against a file etc.
- if (!hasMagic) {
- return globUnescape(pattern)
- }
-
- var flags = options.nocase ? 'i' : ''
- try {
- var regExp = new RegExp('^' + re + '$', flags)
- } catch (er) /* istanbul ignore next - should be impossible */ {
- // If it was an invalid regular expression, then it can't match
- // anything. This trick looks for a character after the end of
- // the string, which is of course impossible, except in multi-line
- // mode, but it's not a /m regex.
- return new RegExp('$.')
- }
- regExp._glob = pattern
- regExp._src = re
-
- return regExp
-}
+//# sourceMappingURL=index.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/storage-blob/dist/esm/utils/constants.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+const esm_utils_constants_SDK_VERSION = "12.31.0";
+const SERVICE_VERSION = "2026-02-06";
+const BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES = 256 * 1024 * 1024; // 256MB
+const BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES = 4000 * 1024 * 1024; // 4000MB
+const BLOCK_BLOB_MAX_BLOCKS = 50000;
+const DEFAULT_BLOCK_BUFFER_SIZE_BYTES = 8 * 1024 * 1024; // 8MB
+const DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES = 4 * 1024 * 1024; // 4MB
+const DEFAULT_MAX_DOWNLOAD_RETRY_REQUESTS = 5;
+const REQUEST_TIMEOUT = 100 * 1000; // In ms
+/**
+ * The OAuth scope to use with Azure Storage.
+ */
+const StorageOAuthScopes = "https://storage.azure.com/.default";
+const utils_constants_URLConstants = {
+ Parameters: {
+ FORCE_BROWSER_NO_CACHE: "_",
+ SIGNATURE: "sig",
+ SNAPSHOT: "snapshot",
+ VERSIONID: "versionid",
+ TIMEOUT: "timeout",
+ },
+};
+const HTTPURLConnection = {
+ HTTP_ACCEPTED: 202,
+ HTTP_CONFLICT: 409,
+ HTTP_NOT_FOUND: 404,
+ HTTP_PRECON_FAILED: 412,
+ HTTP_RANGE_NOT_SATISFIABLE: 416,
+};
+const utils_constants_HeaderConstants = {
+ AUTHORIZATION: "Authorization",
+ AUTHORIZATION_SCHEME: "Bearer",
+ CONTENT_ENCODING: "Content-Encoding",
+ CONTENT_ID: "Content-ID",
+ CONTENT_LANGUAGE: "Content-Language",
+ CONTENT_LENGTH: "Content-Length",
+ CONTENT_MD5: "Content-Md5",
+ CONTENT_TRANSFER_ENCODING: "Content-Transfer-Encoding",
+ CONTENT_TYPE: "Content-Type",
+ COOKIE: "Cookie",
+ DATE: "date",
+ IF_MATCH: "if-match",
+ IF_MODIFIED_SINCE: "if-modified-since",
+ IF_NONE_MATCH: "if-none-match",
+ IF_UNMODIFIED_SINCE: "if-unmodified-since",
+ PREFIX_FOR_STORAGE: "x-ms-",
+ RANGE: "Range",
+ USER_AGENT: "User-Agent",
+ X_MS_CLIENT_REQUEST_ID: "x-ms-client-request-id",
+ X_MS_COPY_SOURCE: "x-ms-copy-source",
+ X_MS_DATE: "x-ms-date",
+ X_MS_ERROR_CODE: "x-ms-error-code",
+ X_MS_VERSION: "x-ms-version",
+ X_MS_CopySourceErrorCode: "x-ms-copy-source-error-code",
+};
+const ETagNone = "";
+const ETagAny = "*";
+const SIZE_1_MB = 1 * 1024 * 1024;
+const BATCH_MAX_REQUEST = 256;
+const BATCH_MAX_PAYLOAD_IN_BYTES = 4 * SIZE_1_MB;
+const HTTP_LINE_ENDING = "\r\n";
+const HTTP_VERSION_1_1 = "HTTP/1.1";
+const EncryptionAlgorithmAES25 = "AES256";
+const utils_constants_DevelopmentConnectionString = `DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;`;
+const StorageBlobLoggingAllowedHeaderNames = [
+ "Access-Control-Allow-Origin",
+ "Cache-Control",
+ "Content-Length",
+ "Content-Type",
+ "Date",
+ "Request-Id",
+ "traceparent",
+ "Transfer-Encoding",
+ "User-Agent",
+ "x-ms-client-request-id",
+ "x-ms-date",
+ "x-ms-error-code",
+ "x-ms-request-id",
+ "x-ms-return-client-request-id",
+ "x-ms-version",
+ "Accept-Ranges",
+ "Content-Disposition",
+ "Content-Encoding",
+ "Content-Language",
+ "Content-MD5",
+ "Content-Range",
+ "ETag",
+ "Last-Modified",
+ "Server",
+ "Vary",
+ "x-ms-content-crc64",
+ "x-ms-copy-action",
+ "x-ms-copy-completion-time",
+ "x-ms-copy-id",
+ "x-ms-copy-progress",
+ "x-ms-copy-status",
+ "x-ms-has-immutability-policy",
+ "x-ms-has-legal-hold",
+ "x-ms-lease-state",
+ "x-ms-lease-status",
+ "x-ms-range",
+ "x-ms-request-server-encrypted",
+ "x-ms-server-encrypted",
+ "x-ms-snapshot",
+ "x-ms-source-range",
+ "If-Match",
+ "If-Modified-Since",
+ "If-None-Match",
+ "If-Unmodified-Since",
+ "x-ms-access-tier",
+ "x-ms-access-tier-change-time",
+ "x-ms-access-tier-inferred",
+ "x-ms-account-kind",
+ "x-ms-archive-status",
+ "x-ms-blob-append-offset",
+ "x-ms-blob-cache-control",
+ "x-ms-blob-committed-block-count",
+ "x-ms-blob-condition-appendpos",
+ "x-ms-blob-condition-maxsize",
+ "x-ms-blob-content-disposition",
+ "x-ms-blob-content-encoding",
+ "x-ms-blob-content-language",
+ "x-ms-blob-content-length",
+ "x-ms-blob-content-md5",
+ "x-ms-blob-content-type",
+ "x-ms-blob-public-access",
+ "x-ms-blob-sequence-number",
+ "x-ms-blob-type",
+ "x-ms-copy-destination-snapshot",
+ "x-ms-creation-time",
+ "x-ms-default-encryption-scope",
+ "x-ms-delete-snapshots",
+ "x-ms-delete-type-permanent",
+ "x-ms-deny-encryption-scope-override",
+ "x-ms-encryption-algorithm",
+ "x-ms-if-sequence-number-eq",
+ "x-ms-if-sequence-number-le",
+ "x-ms-if-sequence-number-lt",
+ "x-ms-incremental-copy",
+ "x-ms-lease-action",
+ "x-ms-lease-break-period",
+ "x-ms-lease-duration",
+ "x-ms-lease-id",
+ "x-ms-lease-time",
+ "x-ms-page-write",
+ "x-ms-proposed-lease-id",
+ "x-ms-range-get-content-md5",
+ "x-ms-rehydrate-priority",
+ "x-ms-sequence-number-action",
+ "x-ms-sku-name",
+ "x-ms-source-content-md5",
+ "x-ms-source-if-match",
+ "x-ms-source-if-modified-since",
+ "x-ms-source-if-none-match",
+ "x-ms-source-if-unmodified-since",
+ "x-ms-tag-count",
+ "x-ms-encryption-key-sha256",
+ "x-ms-copy-source-error-code",
+ "x-ms-copy-source-status-code",
+ "x-ms-if-tags",
+ "x-ms-source-if-tags",
+];
+const StorageBlobLoggingAllowedQueryParameters = [
+ "comp",
+ "maxresults",
+ "rscc",
+ "rscd",
+ "rsce",
+ "rscl",
+ "rsct",
+ "se",
+ "si",
+ "sip",
+ "sp",
+ "spr",
+ "sr",
+ "srt",
+ "ss",
+ "st",
+ "sv",
+ "include",
+ "marker",
+ "prefix",
+ "copyid",
+ "restype",
+ "blockid",
+ "blocklisttype",
+ "delimiter",
+ "prevsnapshot",
+ "ske",
+ "skoid",
+ "sks",
+ "skt",
+ "sktid",
+ "skv",
+ "snapshot",
+];
+const BlobUsesCustomerSpecifiedEncryptionMsg = "BlobUsesCustomerSpecifiedEncryption";
+const BlobDoesNotUseCustomerSpecifiedEncryption = "BlobDoesNotUseCustomerSpecifiedEncryption";
+/// List of ports used for path style addressing.
+/// Path style addressing means that storage account is put in URI's Path segment in instead of in host.
+const utils_constants_PathStylePorts = [
+ "10000",
+ "10001",
+ "10002",
+ "10003",
+ "10004",
+ "10100",
+ "10101",
+ "10102",
+ "10103",
+ "10104",
+ "11000",
+ "11001",
+ "11002",
+ "11003",
+ "11004",
+ "11100",
+ "11101",
+ "11102",
+ "11103",
+ "11104",
+];
+//# sourceMappingURL=constants.js.map
+;// CONCATENATED MODULE: ./node_modules/@azure/storage-blob/dist/esm/Pipeline.js
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
-minimatch.makeRe = function (pattern, options) {
- return new Minimatch(pattern, options || {}).makeRe()
-}
-Minimatch.prototype.makeRe = makeRe
-function makeRe () {
- if (this.regexp || this.regexp === false) return this.regexp
- // at this point, this.set is a 2d array of partial
- // pattern strings, or "**".
- //
- // It's better to use .match(). This function shouldn't
- // be used, really, but it's pretty convenient sometimes,
- // when you just want to work with a regex.
- var set = this.set
- if (!set.length) {
- this.regexp = false
- return this.regexp
- }
- var options = this.options
- var twoStar = options.noglobstar ? star
- : options.dot ? twoStarDot
- : twoStarNoDot
- var flags = options.nocase ? 'i' : ''
- var re = set.map(function (pattern) {
- return pattern.map(function (p) {
- return (p === GLOBSTAR) ? twoStar
- : (typeof p === 'string') ? regExpEscape(p)
- : p._src
- }).join('\\\/')
- }).join('|')
- // must match entire pattern
- // ending in a * or ** will make it less strict.
- re = '^(?:' + re + ')$'
- // can match anything, as long as it's not this.
- if (this.negate) re = '^(?!' + re + ').*$'
+// Export following interfaces and types for customers who want to implement their
+// own RequestPolicy or HTTPClient
- try {
- this.regexp = new RegExp(re, flags)
- } catch (ex) /* istanbul ignore next - should be impossible */ {
- this.regexp = false
- }
- return this.regexp
+/**
+ * A helper to decide if a given argument satisfies the Pipeline contract
+ * @param pipeline - An argument that may be a Pipeline
+ * @returns true when the argument satisfies the Pipeline contract
+ */
+function isPipelineLike(pipeline) {
+ if (!pipeline || typeof pipeline !== "object") {
+ return false;
+ }
+ const castPipeline = pipeline;
+ return (Array.isArray(castPipeline.factories) &&
+ typeof castPipeline.options === "object" &&
+ typeof castPipeline.toServiceClientOptions === "function");
}
-
-minimatch.match = function (list, pattern, options) {
- options = options || {}
- var mm = new Minimatch(pattern, options)
- list = list.filter(function (f) {
- return mm.match(f)
- })
- if (mm.options.nonull && !list.length) {
- list.push(pattern)
- }
- return list
+/**
+ * A Pipeline class containing HTTP request policies.
+ * You can create a default Pipeline by calling {@link newPipeline}.
+ * Or you can create a Pipeline with your own policies by the constructor of Pipeline.
+ *
+ * Refer to {@link newPipeline} and provided policies before implementing your
+ * customized Pipeline.
+ */
+class Pipeline {
+ /**
+ * A list of chained request policy factories.
+ */
+ factories;
+ /**
+ * Configures pipeline logger and HTTP client.
+ */
+ options;
+ /**
+ * Creates an instance of Pipeline. Customize HTTPClient by implementing IHttpClient interface.
+ *
+ * @param factories -
+ * @param options -
+ */
+ constructor(factories, options = {}) {
+ this.factories = factories;
+ this.options = options;
+ }
+ /**
+ * Transfer Pipeline object to ServiceClientOptions object which is required by
+ * ServiceClient constructor.
+ *
+ * @returns The ServiceClientOptions object from this Pipeline.
+ */
+ toServiceClientOptions() {
+ return {
+ httpClient: this.options.httpClient,
+ requestPolicyFactories: this.factories,
+ };
+ }
}
-
-Minimatch.prototype.match = function match (f, partial) {
- if (typeof partial === 'undefined') partial = this.partial
- this.debug('match', f, this.pattern)
- // short-circuit in the case of busted things.
- // comments, etc.
- if (this.comment) return false
- if (this.empty) return f === ''
-
- if (f === '/' && partial) return true
-
- var options = this.options
-
- // windows: need to use /, not \
- if (path.sep !== '/') {
- f = f.split(path.sep).join('/')
- }
-
- // treat the test path as a set of pathparts.
- f = f.split(slashSplit)
- this.debug(this.pattern, 'split', f)
-
- // just ONE of the pattern sets in this.set needs to match
- // in order for it to be valid. If negating, then just one
- // match means that we have failed.
- // Either way, return on the first hit.
-
- var set = this.set
- this.debug(this.pattern, 'set', set)
-
- // Find the basename of the path by looking for the last non-empty segment
- var filename
- var i
- for (i = f.length - 1; i >= 0; i--) {
- filename = f[i]
- if (filename) break
- }
-
- for (i = 0; i < set.length; i++) {
- var pattern = set[i]
- var file = f
- if (options.matchBase && pattern.length === 1) {
- file = [filename]
+/**
+ * Creates a new Pipeline object with Credential provided.
+ *
+ * @param credential - Such as AnonymousCredential, StorageSharedKeyCredential or any credential from the `@azure/identity` package to authenticate requests to the service. You can also provide an object that implements the TokenCredential interface. If not specified, AnonymousCredential is used.
+ * @param pipelineOptions - Optional. Options.
+ * @returns A new Pipeline object.
+ */
+function newPipeline(credential, pipelineOptions = {}) {
+ if (!credential) {
+ credential = new AnonymousCredential();
}
- var hit = this.matchOne(file, pattern, partial)
- if (hit) {
- if (options.flipNegate) return true
- return !this.negate
+ const pipeline = new Pipeline([], pipelineOptions);
+ pipeline._credential = credential;
+ return pipeline;
+}
+function processDownlevelPipeline(pipeline) {
+ const knownFactoryFunctions = [
+ isAnonymousCredential,
+ isStorageSharedKeyCredential,
+ isCoreHttpBearerTokenFactory,
+ isStorageBrowserPolicyFactory,
+ isStorageRetryPolicyFactory,
+ isStorageTelemetryPolicyFactory,
+ isCoreHttpPolicyFactory,
+ ];
+ if (pipeline.factories.length) {
+ const novelFactories = pipeline.factories.filter((factory) => {
+ return !knownFactoryFunctions.some((knownFactory) => knownFactory(factory));
+ });
+ if (novelFactories.length) {
+ const hasInjector = novelFactories.some((factory) => isInjectorPolicyFactory(factory));
+ // if there are any left over, wrap in a requestPolicyFactoryPolicy
+ return {
+ wrappedPolicies: createRequestPolicyFactoryPolicy(novelFactories),
+ afterRetry: hasInjector,
+ };
+ }
}
- }
-
- // didn't get any hits. this is success if it's a negative
- // pattern, failure otherwise.
- if (options.flipNegate) return false
- return this.negate
+ return undefined;
}
-
-// set partial to true to test if, for example,
-// "/a/b" matches the start of "/*/b/*/d"
-// Partial means, if you run out of file before you run
-// out of pattern, then that's fine, as long as all
-// the parts match.
-Minimatch.prototype.matchOne = function (file, pattern, partial) {
- var options = this.options
-
- this.debug('matchOne',
- { 'this': this, file: file, pattern: pattern })
-
- this.debug('matchOne', file.length, pattern.length)
-
- for (var fi = 0,
- pi = 0,
- fl = file.length,
- pl = pattern.length
- ; (fi < fl) && (pi < pl)
- ; fi++, pi++) {
- this.debug('matchOne loop')
- var p = pattern[pi]
- var f = file[fi]
-
- this.debug(pattern, p, f)
-
- // should be impossible.
- // some invalid regexp stuff in the set.
- /* istanbul ignore if */
- if (p === false) return false
-
- if (p === GLOBSTAR) {
- this.debug('GLOBSTAR', [pattern, p, f])
-
- // "**"
- // a/**/b/**/c would match the following:
- // a/b/x/y/z/c
- // a/x/y/z/b/c
- // a/b/x/b/x/c
- // a/b/c
- // To do this, take the rest of the pattern after
- // the **, and see if it would match the file remainder.
- // If so, return success.
- // If not, the ** "swallows" a segment, and try again.
- // This is recursively awful.
- //
- // a/**/b/**/c matching a/b/x/y/z/c
- // - a matches a
- // - doublestar
- // - matchOne(b/x/y/z/c, b/**/c)
- // - b matches b
- // - doublestar
- // - matchOne(x/y/z/c, c) -> no
- // - matchOne(y/z/c, c) -> no
- // - matchOne(z/c, c) -> no
- // - matchOne(c, c) yes, hit
- var fr = fi
- var pr = pi + 1
- if (pr === pl) {
- this.debug('** at the end')
- // a ** at the end will just swallow the rest.
- // We have found a match.
- // however, it will not swallow /.x, unless
- // options.dot is set.
- // . and .. are *never* matched by **, for explosively
- // exponential reasons.
- for (; fi < fl; fi++) {
- if (file[fi] === '.' || file[fi] === '..' ||
- (!options.dot && file[fi].charAt(0) === '.')) return false
+function getCoreClientOptions(pipeline) {
+ const { httpClient: v1Client, ...restOptions } = pipeline.options;
+ let httpClient = pipeline._coreHttpClient;
+ if (!httpClient) {
+ httpClient = v1Client ? convertHttpClient(v1Client) : cache_getCachedDefaultHttpClient();
+ pipeline._coreHttpClient = httpClient;
+ }
+ let corePipeline = pipeline._corePipeline;
+ if (!corePipeline) {
+ const packageDetails = `azsdk-js-azure-storage-blob/${esm_utils_constants_SDK_VERSION}`;
+ const userAgentPrefix = restOptions.userAgentOptions && restOptions.userAgentOptions.userAgentPrefix
+ ? `${restOptions.userAgentOptions.userAgentPrefix} ${packageDetails}`
+ : `${packageDetails}`;
+ corePipeline = createClientPipeline({
+ ...restOptions,
+ loggingOptions: {
+ additionalAllowedHeaderNames: StorageBlobLoggingAllowedHeaderNames,
+ additionalAllowedQueryParameters: StorageBlobLoggingAllowedQueryParameters,
+ logger: storage_blob_dist_esm_log_logger.info,
+ },
+ userAgentOptions: {
+ userAgentPrefix,
+ },
+ serializationOptions: {
+ stringifyXML: stringifyXML,
+ serializerOptions: {
+ xml: {
+ // Use customized XML char key of "#" so we can deserialize metadata
+ // with "_" key
+ xmlCharKey: "#",
+ },
+ },
+ },
+ deserializationOptions: {
+ parseXML: parseXML,
+ serializerOptions: {
+ xml: {
+ // Use customized XML char key of "#" so we can deserialize metadata
+ // with "_" key
+ xmlCharKey: "#",
+ },
+ },
+ },
+ });
+ corePipeline.removePolicy({ phase: "Retry" });
+ corePipeline.removePolicy({ name: decompressResponsePolicy_decompressResponsePolicyName });
+ corePipeline.addPolicy(storageCorrectContentLengthPolicy());
+ corePipeline.addPolicy(storageRetryPolicy(restOptions.retryOptions), { phase: "Retry" });
+ corePipeline.addPolicy(storageRequestFailureDetailsParserPolicy());
+ corePipeline.addPolicy(storageBrowserPolicy());
+ const downlevelResults = processDownlevelPipeline(pipeline);
+ if (downlevelResults) {
+ corePipeline.addPolicy(downlevelResults.wrappedPolicies, downlevelResults.afterRetry ? { afterPhase: "Retry" } : undefined);
}
- return true
- }
-
- // ok, let's see if we can swallow whatever we can.
- while (fr < fl) {
- var swallowee = file[fr]
-
- this.debug('\nglobstar while', file, fr, pattern, pr, swallowee)
-
- // XXX remove this slice. Just pass the start index.
- if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
- this.debug('globstar found match!', fr, fl, swallowee)
- // found a match.
- return true
- } else {
- // can't swallow "." or ".." ever.
- // can only swallow ".foo" when explicitly asked.
- if (swallowee === '.' || swallowee === '..' ||
- (!options.dot && swallowee.charAt(0) === '.')) {
- this.debug('dot detected!', file, fr, pattern, pr)
- break
- }
-
- // ** swallows a segment, and continue.
- this.debug('globstar swallow a segment, and continue')
- fr++
+ const credential = getCredentialFromPipeline(pipeline);
+ if (isTokenCredential(credential)) {
+ corePipeline.addPolicy(bearerTokenAuthenticationPolicy({
+ credential,
+ scopes: restOptions.audience ?? StorageOAuthScopes,
+ challengeCallbacks: { authorizeRequestOnChallenge: authorizeRequestOnTenantChallenge },
+ }), { phase: "Sign" });
}
- }
-
- // no match was found.
- // However, in partial mode, we can't say this is necessarily over.
- // If there's more *pattern* left, then
- /* istanbul ignore if */
- if (partial) {
- // ran out of file
- this.debug('\n>>> no match, partial?', file, fr, pattern, pr)
- if (fr === fl) return true
- }
- return false
+ else if (credential instanceof StorageSharedKeyCredential) {
+ corePipeline.addPolicy(storageSharedKeyCredentialPolicy({
+ accountName: credential.accountName,
+ accountKey: credential.accountKey,
+ }), { phase: "Sign" });
+ }
+ pipeline._corePipeline = corePipeline;
}
-
- // something other than **
- // non-magic patterns just have to match exactly
- // patterns with magic have been turned into regexps.
- var hit
- if (typeof p === 'string') {
- hit = f === p
- this.debug('string match', p, f, hit)
- } else {
- hit = f.match(p)
- this.debug('pattern match', p, f, hit)
+ return {
+ ...restOptions,
+ allowInsecureConnection: true,
+ httpClient,
+ pipeline: corePipeline,
+ };
+}
+function getCredentialFromPipeline(pipeline) {
+ // see if we squirreled one away on the type itself
+ if (pipeline._credential) {
+ return pipeline._credential;
}
-
- if (!hit) return false
- }
-
- // Note: ending in / means that we'll get a final ""
- // at the end of the pattern. This can only match a
- // corresponding "" at the end of the file.
- // If the file ends in /, then it can only match a
- // a pattern that ends in /, unless the pattern just
- // doesn't have any more for it. But, a/b/ should *not*
- // match "a/b/*", even though "" matches against the
- // [^/]*? pattern, except in partial mode, where it might
- // simply not be reached yet.
- // However, a/b/ should still satisfy a/*
-
- // now either we fell off the end of the pattern, or we're done.
- if (fi === fl && pi === pl) {
- // ran out of pattern and filename at the same time.
- // an exact hit!
- return true
- } else if (fi === fl) {
- // ran out of file, but still had pattern left.
- // this is ok if we're doing the match as part of
- // a glob fs traversal.
- return partial
- } else /* istanbul ignore else */ if (pi === pl) {
- // ran out of pattern, still have file left.
- // this is only acceptable if we're on the very last
- // empty segment of a file with a trailing slash.
- // a/* should match a/b/
- return (fi === fl - 1) && (file[fi] === '')
- }
-
- // should be unreachable.
- /* istanbul ignore next */
- throw new Error('wtf?')
+ // if it came from another package, loop over the factories and look for one like before
+ let credential = new AnonymousCredential();
+ for (const factory of pipeline.factories) {
+ if (isTokenCredential(factory.credential)) {
+ // Only works if the factory has been attached a "credential" property.
+ // We do that in newPipeline() when using TokenCredential.
+ credential = factory.credential;
+ }
+ else if (isStorageSharedKeyCredential(factory)) {
+ return factory;
+ }
+ }
+ return credential;
}
-
-// replace stuff like \* with *
-function globUnescape (s) {
- return s.replace(/\\(.)/g, '$1')
+function isStorageSharedKeyCredential(factory) {
+ if (factory instanceof StorageSharedKeyCredential) {
+ return true;
+ }
+ return factory.constructor.name === "StorageSharedKeyCredential";
}
-
-function regExpEscape (s) {
- return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
+function isAnonymousCredential(factory) {
+ if (factory instanceof AnonymousCredential) {
+ return true;
+ }
+ return factory.constructor.name === "AnonymousCredential";
}
-
-
-/***/ }),
-
-/***/ 744:
-/***/ ((module) => {
-
-/**
- * Helpers.
- */
-
-var s = 1000;
-var m = s * 60;
-var h = m * 60;
-var d = h * 24;
-var w = d * 7;
-var y = d * 365.25;
-
-/**
- * Parse or format the given `val`.
- *
- * Options:
- *
- * - `long` verbose formatting [false]
- *
- * @param {String|Number} val
- * @param {Object} [options]
- * @throws {Error} throw an error if val is not a non-empty string or a number
- * @return {String|Number}
- * @api public
- */
-
-module.exports = function (val, options) {
- options = options || {};
- var type = typeof val;
- if (type === 'string' && val.length > 0) {
- return parse(val);
- } else if (type === 'number' && isFinite(val)) {
- return options.long ? fmtLong(val) : fmtShort(val);
- }
- throw new Error(
- 'val is not a non-empty string or a valid number. val=' +
- JSON.stringify(val)
- );
-};
-
-/**
- * Parse the given `str` and return milliseconds.
- *
- * @param {String} str
- * @return {Number}
- * @api private
- */
-
-function parse(str) {
- str = String(str);
- if (str.length > 100) {
- return;
- }
- var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
- str
- );
- if (!match) {
- return;
- }
- var n = parseFloat(match[1]);
- var type = (match[2] || 'ms').toLowerCase();
- switch (type) {
- case 'years':
- case 'year':
- case 'yrs':
- case 'yr':
- case 'y':
- return n * y;
- case 'weeks':
- case 'week':
- case 'w':
- return n * w;
- case 'days':
- case 'day':
- case 'd':
- return n * d;
- case 'hours':
- case 'hour':
- case 'hrs':
- case 'hr':
- case 'h':
- return n * h;
- case 'minutes':
- case 'minute':
- case 'mins':
- case 'min':
- case 'm':
- return n * m;
- case 'seconds':
- case 'second':
- case 'secs':
- case 'sec':
- case 's':
- return n * s;
- case 'milliseconds':
- case 'millisecond':
- case 'msecs':
- case 'msec':
- case 'ms':
- return n;
- default:
- return undefined;
- }
+function isCoreHttpBearerTokenFactory(factory) {
+ return isTokenCredential(factory.credential);
}
-
-/**
- * Short format for `ms`.
- *
- * @param {Number} ms
- * @return {String}
- * @api private
- */
-
-function fmtShort(ms) {
- var msAbs = Math.abs(ms);
- if (msAbs >= d) {
- return Math.round(ms / d) + 'd';
- }
- if (msAbs >= h) {
- return Math.round(ms / h) + 'h';
- }
- if (msAbs >= m) {
- return Math.round(ms / m) + 'm';
- }
- if (msAbs >= s) {
- return Math.round(ms / s) + 's';
- }
- return ms + 'ms';
+function isStorageBrowserPolicyFactory(factory) {
+ if (factory instanceof StorageBrowserPolicyFactory) {
+ return true;
+ }
+ return factory.constructor.name === "StorageBrowserPolicyFactory";
}
-
-/**
- * Long format for `ms`.
- *
- * @param {Number} ms
- * @return {String}
- * @api private
- */
-
-function fmtLong(ms) {
- var msAbs = Math.abs(ms);
- if (msAbs >= d) {
- return plural(ms, msAbs, d, 'day');
- }
- if (msAbs >= h) {
- return plural(ms, msAbs, h, 'hour');
- }
- if (msAbs >= m) {
- return plural(ms, msAbs, m, 'minute');
- }
- if (msAbs >= s) {
- return plural(ms, msAbs, s, 'second');
- }
- return ms + ' ms';
+function isStorageRetryPolicyFactory(factory) {
+ if (factory instanceof StorageRetryPolicyFactory) {
+ return true;
+ }
+ return factory.constructor.name === "StorageRetryPolicyFactory";
}
-
-/**
- * Pluralization helper.
- */
-
-function plural(ms, msAbs, n, name) {
- var isPlural = msAbs >= n * 1.5;
- return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
+function isStorageTelemetryPolicyFactory(factory) {
+ return factory.constructor.name === "TelemetryPolicyFactory";
}
-
-
-/***/ }),
-
-/***/ 9379:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const ANY = Symbol('SemVer ANY')
-// hoisted class for cyclic dependency
-class Comparator {
- static get ANY () {
- return ANY
- }
-
- constructor (comp, options) {
- options = parseOptions(options)
-
- if (comp instanceof Comparator) {
- if (comp.loose === !!options.loose) {
- return comp
- } else {
- comp = comp.value
- }
- }
-
- comp = comp.trim().split(/\s+/).join(' ')
- debug('comparator', comp, options)
- this.options = options
- this.loose = !!options.loose
- this.parse(comp)
-
- if (this.semver === ANY) {
- this.value = ''
- } else {
- this.value = this.operator + this.semver.version
- }
-
- debug('comp', this)
- }
-
- parse (comp) {
- const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]
- const m = comp.match(r)
-
- if (!m) {
- throw new TypeError(`Invalid comparator: ${comp}`)
- }
-
- this.operator = m[1] !== undefined ? m[1] : ''
- if (this.operator === '=') {
- this.operator = ''
- }
-
- // if it literally is just '>' or '' then allow anything.
- if (!m[2]) {
- this.semver = ANY
- } else {
- this.semver = new SemVer(m[2], this.options.loose)
- }
- }
-
- toString () {
- return this.value
- }
-
- test (version) {
- debug('Comparator.test', version, this.options.loose)
-
- if (this.semver === ANY || version === ANY) {
- return true
- }
-
- if (typeof version === 'string') {
- try {
- version = new SemVer(version, this.options)
- } catch (er) {
- return false
- }
- }
-
- return cmp(version, this.operator, this.semver, this.options)
- }
-
- intersects (comp, options) {
- if (!(comp instanceof Comparator)) {
- throw new TypeError('a Comparator is required')
- }
-
- if (this.operator === '') {
- if (this.value === '') {
- return true
- }
- return new Range(comp.value, options).test(this.value)
- } else if (comp.operator === '') {
- if (comp.value === '') {
- return true
- }
- return new Range(this.value, options).test(comp.semver)
- }
-
- options = parseOptions(options)
-
- // Special cases where nothing can possibly be lower
- if (options.includePrerelease &&
- (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) {
- return false
- }
- if (!options.includePrerelease &&
- (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) {
- return false
- }
-
- // Same direction increasing (> or >=)
- if (this.operator.startsWith('>') && comp.operator.startsWith('>')) {
- return true
- }
- // Same direction decreasing (< or <=)
- if (this.operator.startsWith('<') && comp.operator.startsWith('<')) {
- return true
- }
- // same SemVer and both sides are inclusive (<= or >=)
- if (
- (this.semver.version === comp.semver.version) &&
- this.operator.includes('=') && comp.operator.includes('=')) {
- return true
- }
- // opposite directions less than
- if (cmp(this.semver, '<', comp.semver, options) &&
- this.operator.startsWith('>') && comp.operator.startsWith('<')) {
- return true
- }
- // opposite directions greater than
- if (cmp(this.semver, '>', comp.semver, options) &&
- this.operator.startsWith('<') && comp.operator.startsWith('>')) {
- return true
- }
- return false
- }
-}
-
-module.exports = Comparator
-
-const parseOptions = __nccwpck_require__(356)
-const { safeRe: re, t } = __nccwpck_require__(5471)
-const cmp = __nccwpck_require__(8646)
-const debug = __nccwpck_require__(1159)
-const SemVer = __nccwpck_require__(7163)
-const Range = __nccwpck_require__(6782)
-
-
-/***/ }),
-
-/***/ 6782:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const SPACE_CHARACTERS = /\s+/g
-
-// hoisted class for cyclic dependency
-class Range {
- constructor (range, options) {
- options = parseOptions(options)
-
- if (range instanceof Range) {
- if (
- range.loose === !!options.loose &&
- range.includePrerelease === !!options.includePrerelease
- ) {
- return range
- } else {
- return new Range(range.raw, options)
- }
- }
-
- if (range instanceof Comparator) {
- // just put it in the set and return
- this.raw = range.value
- this.set = [[range]]
- this.formatted = undefined
- return this
- }
-
- this.options = options
- this.loose = !!options.loose
- this.includePrerelease = !!options.includePrerelease
-
- // First reduce all whitespace as much as possible so we do not have to rely
- // on potentially slow regexes like \s*. This is then stored and used for
- // future error messages as well.
- this.raw = range.trim().replace(SPACE_CHARACTERS, ' ')
-
- // First, split on ||
- this.set = this.raw
- .split('||')
- // map the range to a 2d array of comparators
- .map(r => this.parseRange(r.trim()))
- // throw out any comparator lists that are empty
- // this generally means that it was not a valid range, which is allowed
- // in loose mode, but will still throw if the WHOLE range is invalid.
- .filter(c => c.length)
-
- if (!this.set.length) {
- throw new TypeError(`Invalid SemVer Range: ${this.raw}`)
- }
-
- // if we have any that are not the null set, throw out null sets.
- if (this.set.length > 1) {
- // keep the first one, in case they're all null sets
- const first = this.set[0]
- this.set = this.set.filter(c => !isNullSet(c[0]))
- if (this.set.length === 0) {
- this.set = [first]
- } else if (this.set.length > 1) {
- // if we have any that are *, then the range is just *
- for (const c of this.set) {
- if (c.length === 1 && isAny(c[0])) {
- this.set = [c]
- break
- }
- }
- }
- }
-
- this.formatted = undefined
- }
-
- get range () {
- if (this.formatted === undefined) {
- this.formatted = ''
- for (let i = 0; i < this.set.length; i++) {
- if (i > 0) {
- this.formatted += '||'
- }
- const comps = this.set[i]
- for (let k = 0; k < comps.length; k++) {
- if (k > 0) {
- this.formatted += ' '
- }
- this.formatted += comps[k].toString().trim()
- }
- }
- }
- return this.formatted
- }
-
- format () {
- return this.range
- }
-
- toString () {
- return this.range
- }
-
- parseRange (range) {
- // memoize range parsing for performance.
- // this is a very hot path, and fully deterministic.
- const memoOpts =
- (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) |
- (this.options.loose && FLAG_LOOSE)
- const memoKey = memoOpts + ':' + range
- const cached = cache.get(memoKey)
- if (cached) {
- return cached
- }
-
- const loose = this.options.loose
- // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
- const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]
- range = range.replace(hr, hyphenReplace(this.options.includePrerelease))
- debug('hyphen replace', range)
-
- // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
- range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace)
- debug('comparator trim', range)
-
- // `~ 1.2.3` => `~1.2.3`
- range = range.replace(re[t.TILDETRIM], tildeTrimReplace)
- debug('tilde trim', range)
-
- // `^ 1.2.3` => `^1.2.3`
- range = range.replace(re[t.CARETTRIM], caretTrimReplace)
- debug('caret trim', range)
-
- // At this point, the range is completely trimmed and
- // ready to be split into comparators.
-
- let rangeList = range
- .split(' ')
- .map(comp => parseComparator(comp, this.options))
- .join(' ')
- .split(/\s+/)
- // >=0.0.0 is equivalent to *
- .map(comp => replaceGTE0(comp, this.options))
-
- if (loose) {
- // in loose mode, throw out any that are not valid comparators
- rangeList = rangeList.filter(comp => {
- debug('loose invalid filter', comp, this.options)
- return !!comp.match(re[t.COMPARATORLOOSE])
- })
- }
- debug('range list', rangeList)
-
- // if any comparators are the null set, then replace with JUST null set
- // if more than one comparator, remove any * comparators
- // also, don't include the same comparator more than once
- const rangeMap = new Map()
- const comparators = rangeList.map(comp => new Comparator(comp, this.options))
- for (const comp of comparators) {
- if (isNullSet(comp)) {
- return [comp]
- }
- rangeMap.set(comp.value, comp)
- }
- if (rangeMap.size > 1 && rangeMap.has('')) {
- rangeMap.delete('')
- }
-
- const result = [...rangeMap.values()]
- cache.set(memoKey, result)
- return result
- }
-
- intersects (range, options) {
- if (!(range instanceof Range)) {
- throw new TypeError('a Range is required')
- }
-
- return this.set.some((thisComparators) => {
- return (
- isSatisfiable(thisComparators, options) &&
- range.set.some((rangeComparators) => {
- return (
- isSatisfiable(rangeComparators, options) &&
- thisComparators.every((thisComparator) => {
- return rangeComparators.every((rangeComparator) => {
- return thisComparator.intersects(rangeComparator, options)
- })
- })
- )
- })
- )
- })
- }
-
- // if ANY of the sets match ALL of its comparators, then pass
- test (version) {
- if (!version) {
- return false
- }
-
- if (typeof version === 'string') {
- try {
- version = new SemVer(version, this.options)
- } catch (er) {
- return false
- }
- }
-
- for (let i = 0; i < this.set.length; i++) {
- if (testSet(this.set[i], version, this.options)) {
- return true
- }
- }
- return false
- }
-}
-
-module.exports = Range
-
-const LRU = __nccwpck_require__(1383)
-const cache = new LRU()
-
-const parseOptions = __nccwpck_require__(356)
-const Comparator = __nccwpck_require__(9379)
-const debug = __nccwpck_require__(1159)
-const SemVer = __nccwpck_require__(7163)
-const {
- safeRe: re,
- t,
- comparatorTrimReplace,
- tildeTrimReplace,
- caretTrimReplace,
-} = __nccwpck_require__(5471)
-const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = __nccwpck_require__(5101)
-
-const isNullSet = c => c.value === '<0.0.0-0'
-const isAny = c => c.value === ''
-
-// take a set of comparators and determine whether there
-// exists a version which can satisfy it
-const isSatisfiable = (comparators, options) => {
- let result = true
- const remainingComparators = comparators.slice()
- let testComparator = remainingComparators.pop()
-
- while (result && remainingComparators.length) {
- result = remainingComparators.every((otherComparator) => {
- return testComparator.intersects(otherComparator, options)
- })
-
- testComparator = remainingComparators.pop()
- }
-
- return result
-}
-
-// comprised of xranges, tildes, stars, and gtlt's at this point.
-// already replaced the hyphen ranges
-// turn into a set of JUST comparators.
-const parseComparator = (comp, options) => {
- comp = comp.replace(re[t.BUILD], '')
- debug('comp', comp, options)
- comp = replaceCarets(comp, options)
- debug('caret', comp)
- comp = replaceTildes(comp, options)
- debug('tildes', comp)
- comp = replaceXRanges(comp, options)
- debug('xrange', comp)
- comp = replaceStars(comp, options)
- debug('stars', comp)
- return comp
-}
-
-const isX = id => !id || id.toLowerCase() === 'x' || id === '*'
-
-// ~, ~> --> * (any, kinda silly)
-// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0
-// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0
-// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0
-// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0
-// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0
-// ~0.0.1 --> >=0.0.1 <0.1.0-0
-const replaceTildes = (comp, options) => {
- return comp
- .trim()
- .split(/\s+/)
- .map((c) => replaceTilde(c, options))
- .join(' ')
-}
-
-const replaceTilde = (comp, options) => {
- const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]
- return comp.replace(r, (_, M, m, p, pr) => {
- debug('tilde', comp, _, M, m, p, pr)
- let ret
-
- if (isX(M)) {
- ret = ''
- } else if (isX(m)) {
- ret = `>=${M}.0.0 <${+M + 1}.0.0-0`
- } else if (isX(p)) {
- // ~1.2 == >=1.2.0 <1.3.0-0
- ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`
- } else if (pr) {
- debug('replaceTilde pr', pr)
- ret = `>=${M}.${m}.${p}-${pr
- } <${M}.${+m + 1}.0-0`
- } else {
- // ~1.2.3 == >=1.2.3 <1.3.0-0
- ret = `>=${M}.${m}.${p
- } <${M}.${+m + 1}.0-0`
- }
-
- debug('tilde return', ret)
- return ret
- })
-}
-
-// ^ --> * (any, kinda silly)
-// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0
-// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0
-// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0
-// ^1.2.3 --> >=1.2.3 <2.0.0-0
-// ^1.2.0 --> >=1.2.0 <2.0.0-0
-// ^0.0.1 --> >=0.0.1 <0.0.2-0
-// ^0.1.0 --> >=0.1.0 <0.2.0-0
-const replaceCarets = (comp, options) => {
- return comp
- .trim()
- .split(/\s+/)
- .map((c) => replaceCaret(c, options))
- .join(' ')
-}
-
-const replaceCaret = (comp, options) => {
- debug('caret', comp, options)
- const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]
- const z = options.includePrerelease ? '-0' : ''
- return comp.replace(r, (_, M, m, p, pr) => {
- debug('caret', comp, _, M, m, p, pr)
- let ret
-
- if (isX(M)) {
- ret = ''
- } else if (isX(m)) {
- ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`
- } else if (isX(p)) {
- if (M === '0') {
- ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`
- } else {
- ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`
- }
- } else if (pr) {
- debug('replaceCaret pr', pr)
- if (M === '0') {
- if (m === '0') {
- ret = `>=${M}.${m}.${p}-${pr
- } <${M}.${m}.${+p + 1}-0`
- } else {
- ret = `>=${M}.${m}.${p}-${pr
- } <${M}.${+m + 1}.0-0`
- }
- } else {
- ret = `>=${M}.${m}.${p}-${pr
- } <${+M + 1}.0.0-0`
- }
- } else {
- debug('no pr')
- if (M === '0') {
- if (m === '0') {
- ret = `>=${M}.${m}.${p
- }${z} <${M}.${m}.${+p + 1}-0`
- } else {
- ret = `>=${M}.${m}.${p
- }${z} <${M}.${+m + 1}.0-0`
- }
- } else {
- ret = `>=${M}.${m}.${p
- } <${+M + 1}.0.0-0`
- }
- }
-
- debug('caret return', ret)
- return ret
- })
+function isInjectorPolicyFactory(factory) {
+ return factory.constructor.name === "InjectorPolicyFactory";
}
-
-const replaceXRanges = (comp, options) => {
- debug('replaceXRanges', comp, options)
- return comp
- .split(/\s+/)
- .map((c) => replaceXRange(c, options))
- .join(' ')
-}
-
-const replaceXRange = (comp, options) => {
- comp = comp.trim()
- const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]
- return comp.replace(r, (ret, gtlt, M, m, p, pr) => {
- debug('xRange', comp, ret, gtlt, M, m, p, pr)
- const xM = isX(M)
- const xm = xM || isX(m)
- const xp = xm || isX(p)
- const anyX = xp
-
- if (gtlt === '=' && anyX) {
- gtlt = ''
- }
-
- // if we're including prereleases in the match, then we need
- // to fix this to -0, the lowest possible prerelease value
- pr = options.includePrerelease ? '-0' : ''
-
- if (xM) {
- if (gtlt === '>' || gtlt === '<') {
- // nothing is allowed
- ret = '<0.0.0-0'
- } else {
- // nothing is forbidden
- ret = '*'
- }
- } else if (gtlt && anyX) {
- // we know patch is an x, because we have any x at all.
- // replace X with 0
- if (xm) {
- m = 0
- }
- p = 0
-
- if (gtlt === '>') {
- // >1 => >=2.0.0
- // >1.2 => >=1.3.0
- gtlt = '>='
- if (xm) {
- M = +M + 1
- m = 0
- p = 0
- } else {
- m = +m + 1
- p = 0
- }
- } else if (gtlt === '<=') {
- // <=0.7.x is actually <0.8.0, since any 0.7.x should
- // pass. Similarly, <=7.x is actually <8.0.0, etc.
- gtlt = '<'
- if (xm) {
- M = +M + 1
- } else {
- m = +m + 1
- }
- }
-
- if (gtlt === '<') {
- pr = '-0'
- }
-
- ret = `${gtlt + M}.${m}.${p}${pr}`
- } else if (xm) {
- ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`
- } else if (xp) {
- ret = `>=${M}.${m}.0${pr
- } <${M}.${+m + 1}.0-0`
- }
-
- debug('xRange return', ret)
-
- return ret
- })
-}
-
-// Because * is AND-ed with everything else in the comparator,
-// and '' means "any version", just remove the *s entirely.
-const replaceStars = (comp, options) => {
- debug('replaceStars', comp, options)
- // Looseness is ignored here. star is always as loose as it gets!
- return comp
- .trim()
- .replace(re[t.STAR], '')
-}
-
-const replaceGTE0 = (comp, options) => {
- debug('replaceGTE0', comp, options)
- return comp
- .trim()
- .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')
-}
-
-// This function is passed to string.replace(re[t.HYPHENRANGE])
-// M, m, patch, prerelease, build
-// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
-// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do
-// 1.2 - 3.4 => >=1.2.0 <3.5.0-0
-// TODO build?
-const hyphenReplace = incPr => ($0,
- from, fM, fm, fp, fpr, fb,
- to, tM, tm, tp, tpr) => {
- if (isX(fM)) {
- from = ''
- } else if (isX(fm)) {
- from = `>=${fM}.0.0${incPr ? '-0' : ''}`
- } else if (isX(fp)) {
- from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`
- } else if (fpr) {
- from = `>=${from}`
- } else {
- from = `>=${from}${incPr ? '-0' : ''}`
- }
-
- if (isX(tM)) {
- to = ''
- } else if (isX(tm)) {
- to = `<${+tM + 1}.0.0-0`
- } else if (isX(tp)) {
- to = `<${tM}.${+tm + 1}.0-0`
- } else if (tpr) {
- to = `<=${tM}.${tm}.${tp}-${tpr}`
- } else if (incPr) {
- to = `<${tM}.${tm}.${+tp + 1}-0`
- } else {
- to = `<=${to}`
- }
-
- return `${from} ${to}`.trim()
-}
-
-const testSet = (set, version, options) => {
- for (let i = 0; i < set.length; i++) {
- if (!set[i].test(version)) {
- return false
- }
- }
-
- if (version.prerelease.length && !options.includePrerelease) {
- // Find the set of versions that are allowed to have prereleases
- // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
- // That should allow `1.2.3-pr.2` to pass.
- // However, `1.2.4-alpha.notready` should NOT be allowed,
- // even though it's within the range set by the comparators.
- for (let i = 0; i < set.length; i++) {
- debug(set[i].semver)
- if (set[i].semver === Comparator.ANY) {
- continue
- }
-
- if (set[i].semver.prerelease.length > 0) {
- const allowed = set[i].semver
- if (allowed.major === version.major &&
- allowed.minor === version.minor &&
- allowed.patch === version.patch) {
- return true
- }
- }
- }
-
- // Version has a -pre, but it's not one of the ones we like.
- return false
- }
-
- return true
-}
-
-
-/***/ }),
-
-/***/ 7163:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const debug = __nccwpck_require__(1159)
-const { MAX_LENGTH, MAX_SAFE_INTEGER } = __nccwpck_require__(5101)
-const { safeRe: re, t } = __nccwpck_require__(5471)
-
-const parseOptions = __nccwpck_require__(356)
-const { compareIdentifiers } = __nccwpck_require__(3348)
-class SemVer {
- constructor (version, options) {
- options = parseOptions(options)
-
- if (version instanceof SemVer) {
- if (version.loose === !!options.loose &&
- version.includePrerelease === !!options.includePrerelease) {
- return version
- } else {
- version = version.version
- }
- } else if (typeof version !== 'string') {
- throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`)
- }
-
- if (version.length > MAX_LENGTH) {
- throw new TypeError(
- `version is longer than ${MAX_LENGTH} characters`
- )
- }
-
- debug('SemVer', version, options)
- this.options = options
- this.loose = !!options.loose
- // this isn't actually relevant for versions, but keep it so that we
- // don't run into trouble passing this.options around.
- this.includePrerelease = !!options.includePrerelease
-
- const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL])
-
- if (!m) {
- throw new TypeError(`Invalid Version: ${version}`)
- }
-
- this.raw = version
-
- // these are actually numbers
- this.major = +m[1]
- this.minor = +m[2]
- this.patch = +m[3]
-
- if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
- throw new TypeError('Invalid major version')
- }
-
- if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
- throw new TypeError('Invalid minor version')
- }
-
- if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
- throw new TypeError('Invalid patch version')
- }
-
- // numberify any prerelease numeric ids
- if (!m[4]) {
- this.prerelease = []
- } else {
- this.prerelease = m[4].split('.').map((id) => {
- if (/^[0-9]+$/.test(id)) {
- const num = +id
- if (num >= 0 && num < MAX_SAFE_INTEGER) {
- return num
- }
- }
- return id
- })
- }
-
- this.build = m[5] ? m[5].split('.') : []
- this.format()
- }
-
- format () {
- this.version = `${this.major}.${this.minor}.${this.patch}`
- if (this.prerelease.length) {
- this.version += `-${this.prerelease.join('.')}`
- }
- return this.version
- }
-
- toString () {
- return this.version
- }
-
- compare (other) {
- debug('SemVer.compare', this.version, this.options, other)
- if (!(other instanceof SemVer)) {
- if (typeof other === 'string' && other === this.version) {
- return 0
- }
- other = new SemVer(other, this.options)
- }
-
- if (other.version === this.version) {
- return 0
- }
-
- return this.compareMain(other) || this.comparePre(other)
- }
-
- compareMain (other) {
- if (!(other instanceof SemVer)) {
- other = new SemVer(other, this.options)
- }
-
- if (this.major < other.major) {
- return -1
- }
- if (this.major > other.major) {
- return 1
- }
- if (this.minor < other.minor) {
- return -1
- }
- if (this.minor > other.minor) {
- return 1
- }
- if (this.patch < other.patch) {
- return -1
- }
- if (this.patch > other.patch) {
- return 1
- }
- return 0
- }
-
- comparePre (other) {
- if (!(other instanceof SemVer)) {
- other = new SemVer(other, this.options)
- }
-
- // NOT having a prerelease is > having one
- if (this.prerelease.length && !other.prerelease.length) {
- return -1
- } else if (!this.prerelease.length && other.prerelease.length) {
- return 1
- } else if (!this.prerelease.length && !other.prerelease.length) {
- return 0
- }
-
- let i = 0
- do {
- const a = this.prerelease[i]
- const b = other.prerelease[i]
- debug('prerelease compare', i, a, b)
- if (a === undefined && b === undefined) {
- return 0
- } else if (b === undefined) {
- return 1
- } else if (a === undefined) {
- return -1
- } else if (a === b) {
- continue
- } else {
- return compareIdentifiers(a, b)
- }
- } while (++i)
- }
-
- compareBuild (other) {
- if (!(other instanceof SemVer)) {
- other = new SemVer(other, this.options)
- }
-
- let i = 0
- do {
- const a = this.build[i]
- const b = other.build[i]
- debug('build compare', i, a, b)
- if (a === undefined && b === undefined) {
- return 0
- } else if (b === undefined) {
- return 1
- } else if (a === undefined) {
- return -1
- } else if (a === b) {
- continue
- } else {
- return compareIdentifiers(a, b)
- }
- } while (++i)
- }
-
- // preminor will bump the version up to the next minor release, and immediately
- // down to pre-release. premajor and prepatch work the same way.
- inc (release, identifier, identifierBase) {
- if (release.startsWith('pre')) {
- if (!identifier && identifierBase === false) {
- throw new Error('invalid increment argument: identifier is empty')
- }
- // Avoid an invalid semver results
- if (identifier) {
- const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE])
- if (!match || match[1] !== identifier) {
- throw new Error(`invalid identifier: ${identifier}`)
- }
- }
- }
-
- switch (release) {
- case 'premajor':
- this.prerelease.length = 0
- this.patch = 0
- this.minor = 0
- this.major++
- this.inc('pre', identifier, identifierBase)
- break
- case 'preminor':
- this.prerelease.length = 0
- this.patch = 0
- this.minor++
- this.inc('pre', identifier, identifierBase)
- break
- case 'prepatch':
- // If this is already a prerelease, it will bump to the next version
- // drop any prereleases that might already exist, since they are not
- // relevant at this point.
- this.prerelease.length = 0
- this.inc('patch', identifier, identifierBase)
- this.inc('pre', identifier, identifierBase)
- break
- // If the input is a non-prerelease version, this acts the same as
- // prepatch.
- case 'prerelease':
- if (this.prerelease.length === 0) {
- this.inc('patch', identifier, identifierBase)
- }
- this.inc('pre', identifier, identifierBase)
- break
- case 'release':
- if (this.prerelease.length === 0) {
- throw new Error(`version ${this.raw} is not a prerelease`)
- }
- this.prerelease.length = 0
- break
-
- case 'major':
- // If this is a pre-major version, bump up to the same major version.
- // Otherwise increment major.
- // 1.0.0-5 bumps to 1.0.0
- // 1.1.0 bumps to 2.0.0
- if (
- this.minor !== 0 ||
- this.patch !== 0 ||
- this.prerelease.length === 0
- ) {
- this.major++
- }
- this.minor = 0
- this.patch = 0
- this.prerelease = []
- break
- case 'minor':
- // If this is a pre-minor version, bump up to the same minor version.
- // Otherwise increment minor.
- // 1.2.0-5 bumps to 1.2.0
- // 1.2.1 bumps to 1.3.0
- if (this.patch !== 0 || this.prerelease.length === 0) {
- this.minor++
- }
- this.patch = 0
- this.prerelease = []
- break
- case 'patch':
- // If this is not a pre-release version, it will increment the patch.
- // If it is a pre-release it will bump up to the same patch version.
- // 1.2.0-5 patches to 1.2.0
- // 1.2.0 patches to 1.2.1
- if (this.prerelease.length === 0) {
- this.patch++
- }
- this.prerelease = []
- break
- // This probably shouldn't be used publicly.
- // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
- case 'pre': {
- const base = Number(identifierBase) ? 1 : 0
-
- if (this.prerelease.length === 0) {
- this.prerelease = [base]
- } else {
- let i = this.prerelease.length
- while (--i >= 0) {
- if (typeof this.prerelease[i] === 'number') {
- this.prerelease[i]++
- i = -2
- }
- }
- if (i === -1) {
- // didn't increment anything
- if (identifier === this.prerelease.join('.') && identifierBase === false) {
- throw new Error('invalid increment argument: identifier already exists')
- }
- this.prerelease.push(base)
- }
- }
- if (identifier) {
- // 1.2.0-beta.1 bumps to 1.2.0-beta.2,
- // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
- let prerelease = [identifier, base]
- if (identifierBase === false) {
- prerelease = [identifier]
- }
- if (compareIdentifiers(this.prerelease[0], identifier) === 0) {
- if (isNaN(this.prerelease[1])) {
- this.prerelease = prerelease
- }
- } else {
- this.prerelease = prerelease
- }
- }
- break
- }
- default:
- throw new Error(`invalid increment argument: ${release}`)
- }
- this.raw = this.format()
- if (this.build.length) {
- this.raw += `+${this.build.join('.')}`
- }
- return this
- }
-}
-
-module.exports = SemVer
-
-
-/***/ }),
-
-/***/ 1799:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const parse = __nccwpck_require__(6353)
-const clean = (version, options) => {
- const s = parse(version.trim().replace(/^[=v]+/, ''), options)
- return s ? s.version : null
-}
-module.exports = clean
-
-
-/***/ }),
-
-/***/ 8646:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const eq = __nccwpck_require__(5082)
-const neq = __nccwpck_require__(4974)
-const gt = __nccwpck_require__(6599)
-const gte = __nccwpck_require__(1236)
-const lt = __nccwpck_require__(3872)
-const lte = __nccwpck_require__(6717)
-
-const cmp = (a, op, b, loose) => {
- switch (op) {
- case '===':
- if (typeof a === 'object') {
- a = a.version
- }
- if (typeof b === 'object') {
- b = b.version
- }
- return a === b
-
- case '!==':
- if (typeof a === 'object') {
- a = a.version
- }
- if (typeof b === 'object') {
- b = b.version
- }
- return a !== b
-
- case '':
- case '=':
- case '==':
- return eq(a, b, loose)
-
- case '!=':
- return neq(a, b, loose)
-
- case '>':
- return gt(a, b, loose)
-
- case '>=':
- return gte(a, b, loose)
-
- case '<':
- return lt(a, b, loose)
-
- case '<=':
- return lte(a, b, loose)
-
- default:
- throw new TypeError(`Invalid operator: ${op}`)
- }
-}
-module.exports = cmp
-
-
-/***/ }),
-
-/***/ 5385:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const SemVer = __nccwpck_require__(7163)
-const parse = __nccwpck_require__(6353)
-const { safeRe: re, t } = __nccwpck_require__(5471)
-
-const coerce = (version, options) => {
- if (version instanceof SemVer) {
- return version
- }
-
- if (typeof version === 'number') {
- version = String(version)
- }
-
- if (typeof version !== 'string') {
- return null
- }
-
- options = options || {}
-
- let match = null
- if (!options.rtl) {
- match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE])
- } else {
- // Find the right-most coercible string that does not share
- // a terminus with a more left-ward coercible string.
- // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'
- // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4'
- //
- // Walk through the string checking with a /g regexp
- // Manually set the index so as to pick up overlapping matches.
- // Stop when we get a match that ends at the string end, since no
- // coercible string can be more right-ward without the same terminus.
- const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL]
- let next
- while ((next = coerceRtlRegex.exec(version)) &&
- (!match || match.index + match[0].length !== version.length)
- ) {
- if (!match ||
- next.index + next[0].length !== match.index + match[0].length) {
- match = next
- }
- coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length
- }
- // leave it in a clean state
- coerceRtlRegex.lastIndex = -1
- }
-
- if (match === null) {
- return null
- }
-
- const major = match[2]
- const minor = match[3] || '0'
- const patch = match[4] || '0'
- const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : ''
- const build = options.includePrerelease && match[6] ? `+${match[6]}` : ''
-
- return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options)
-}
-module.exports = coerce
-
-
-/***/ }),
-
-/***/ 7648:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const SemVer = __nccwpck_require__(7163)
-const compareBuild = (a, b, loose) => {
- const versionA = new SemVer(a, loose)
- const versionB = new SemVer(b, loose)
- return versionA.compare(versionB) || versionA.compareBuild(versionB)
-}
-module.exports = compareBuild
-
-
-/***/ }),
-
-/***/ 6874:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const compare = __nccwpck_require__(8469)
-const compareLoose = (a, b) => compare(a, b, true)
-module.exports = compareLoose
-
-
-/***/ }),
-
-/***/ 8469:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const SemVer = __nccwpck_require__(7163)
-const compare = (a, b, loose) =>
- new SemVer(a, loose).compare(new SemVer(b, loose))
-
-module.exports = compare
-
-
-/***/ }),
-
-/***/ 711:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const parse = __nccwpck_require__(6353)
-
-const diff = (version1, version2) => {
- const v1 = parse(version1, null, true)
- const v2 = parse(version2, null, true)
- const comparison = v1.compare(v2)
-
- if (comparison === 0) {
- return null
- }
-
- const v1Higher = comparison > 0
- const highVersion = v1Higher ? v1 : v2
- const lowVersion = v1Higher ? v2 : v1
- const highHasPre = !!highVersion.prerelease.length
- const lowHasPre = !!lowVersion.prerelease.length
-
- if (lowHasPre && !highHasPre) {
- // Going from prerelease -> no prerelease requires some special casing
-
- // If the low version has only a major, then it will always be a major
- // Some examples:
- // 1.0.0-1 -> 1.0.0
- // 1.0.0-1 -> 1.1.1
- // 1.0.0-1 -> 2.0.0
- if (!lowVersion.patch && !lowVersion.minor) {
- return 'major'
- }
-
- // If the main part has no difference
- if (lowVersion.compareMain(highVersion) === 0) {
- if (lowVersion.minor && !lowVersion.patch) {
- return 'minor'
- }
- return 'patch'
- }
- }
-
- // add the `pre` prefix if we are going to a prerelease version
- const prefix = highHasPre ? 'pre' : ''
-
- if (v1.major !== v2.major) {
- return prefix + 'major'
- }
-
- if (v1.minor !== v2.minor) {
- return prefix + 'minor'
- }
-
- if (v1.patch !== v2.patch) {
- return prefix + 'patch'
- }
-
- // high and low are prereleases
- return 'prerelease'
-}
-
-module.exports = diff
-
-
-/***/ }),
-
-/***/ 5082:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const compare = __nccwpck_require__(8469)
-const eq = (a, b, loose) => compare(a, b, loose) === 0
-module.exports = eq
-
-
-/***/ }),
-
-/***/ 6599:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const compare = __nccwpck_require__(8469)
-const gt = (a, b, loose) => compare(a, b, loose) > 0
-module.exports = gt
-
-
-/***/ }),
-
-/***/ 1236:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const compare = __nccwpck_require__(8469)
-const gte = (a, b, loose) => compare(a, b, loose) >= 0
-module.exports = gte
-
-
-/***/ }),
-
-/***/ 2338:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const SemVer = __nccwpck_require__(7163)
-
-const inc = (version, release, options, identifier, identifierBase) => {
- if (typeof (options) === 'string') {
- identifierBase = identifier
- identifier = options
- options = undefined
- }
-
- try {
- return new SemVer(
- version instanceof SemVer ? version.version : version,
- options
- ).inc(release, identifier, identifierBase).version
- } catch (er) {
- return null
- }
-}
-module.exports = inc
-
-
-/***/ }),
-
-/***/ 3872:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const compare = __nccwpck_require__(8469)
-const lt = (a, b, loose) => compare(a, b, loose) < 0
-module.exports = lt
-
-
-/***/ }),
-
-/***/ 6717:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const compare = __nccwpck_require__(8469)
-const lte = (a, b, loose) => compare(a, b, loose) <= 0
-module.exports = lte
-
-
-/***/ }),
-
-/***/ 8511:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const SemVer = __nccwpck_require__(7163)
-const major = (a, loose) => new SemVer(a, loose).major
-module.exports = major
-
-
-/***/ }),
-
-/***/ 2603:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const SemVer = __nccwpck_require__(7163)
-const minor = (a, loose) => new SemVer(a, loose).minor
-module.exports = minor
-
-
-/***/ }),
-
-/***/ 4974:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const compare = __nccwpck_require__(8469)
-const neq = (a, b, loose) => compare(a, b, loose) !== 0
-module.exports = neq
-
-
-/***/ }),
-
-/***/ 6353:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const SemVer = __nccwpck_require__(7163)
-const parse = (version, options, throwErrors = false) => {
- if (version instanceof SemVer) {
- return version
- }
- try {
- return new SemVer(version, options)
- } catch (er) {
- if (!throwErrors) {
- return null
- }
- throw er
- }
-}
-
-module.exports = parse
-
-
-/***/ }),
-
-/***/ 8756:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const SemVer = __nccwpck_require__(7163)
-const patch = (a, loose) => new SemVer(a, loose).patch
-module.exports = patch
-
-
-/***/ }),
-
-/***/ 5714:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const parse = __nccwpck_require__(6353)
-const prerelease = (version, options) => {
- const parsed = parse(version, options)
- return (parsed && parsed.prerelease.length) ? parsed.prerelease : null
-}
-module.exports = prerelease
-
-
-/***/ }),
-
-/***/ 2173:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const compare = __nccwpck_require__(8469)
-const rcompare = (a, b, loose) => compare(b, a, loose)
-module.exports = rcompare
-
-
-/***/ }),
-
-/***/ 7192:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const compareBuild = __nccwpck_require__(7648)
-const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose))
-module.exports = rsort
-
-
-/***/ }),
-
-/***/ 8011:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const Range = __nccwpck_require__(6782)
-const satisfies = (version, range, options) => {
- try {
- range = new Range(range, options)
- } catch (er) {
- return false
- }
- return range.test(version)
-}
-module.exports = satisfies
-
-
-/***/ }),
-
-/***/ 9872:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const compareBuild = __nccwpck_require__(7648)
-const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose))
-module.exports = sort
-
-
-/***/ }),
-
-/***/ 6399:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const parse = __nccwpck_require__(6353)
-const valid = (version, options) => {
- const v = parse(version, options)
- return v ? v.version : null
-}
-module.exports = valid
-
-
-/***/ }),
-
-/***/ 2088:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-// just pre-load all the stuff that index.js lazily exports
-const internalRe = __nccwpck_require__(5471)
-const constants = __nccwpck_require__(5101)
-const SemVer = __nccwpck_require__(7163)
-const identifiers = __nccwpck_require__(3348)
-const parse = __nccwpck_require__(6353)
-const valid = __nccwpck_require__(6399)
-const clean = __nccwpck_require__(1799)
-const inc = __nccwpck_require__(2338)
-const diff = __nccwpck_require__(711)
-const major = __nccwpck_require__(8511)
-const minor = __nccwpck_require__(2603)
-const patch = __nccwpck_require__(8756)
-const prerelease = __nccwpck_require__(5714)
-const compare = __nccwpck_require__(8469)
-const rcompare = __nccwpck_require__(2173)
-const compareLoose = __nccwpck_require__(6874)
-const compareBuild = __nccwpck_require__(7648)
-const sort = __nccwpck_require__(9872)
-const rsort = __nccwpck_require__(7192)
-const gt = __nccwpck_require__(6599)
-const lt = __nccwpck_require__(3872)
-const eq = __nccwpck_require__(5082)
-const neq = __nccwpck_require__(4974)
-const gte = __nccwpck_require__(1236)
-const lte = __nccwpck_require__(6717)
-const cmp = __nccwpck_require__(8646)
-const coerce = __nccwpck_require__(5385)
-const Comparator = __nccwpck_require__(9379)
-const Range = __nccwpck_require__(6782)
-const satisfies = __nccwpck_require__(8011)
-const toComparators = __nccwpck_require__(4750)
-const maxSatisfying = __nccwpck_require__(5574)
-const minSatisfying = __nccwpck_require__(8595)
-const minVersion = __nccwpck_require__(1866)
-const validRange = __nccwpck_require__(4737)
-const outside = __nccwpck_require__(280)
-const gtr = __nccwpck_require__(2276)
-const ltr = __nccwpck_require__(5213)
-const intersects = __nccwpck_require__(3465)
-const simplifyRange = __nccwpck_require__(2028)
-const subset = __nccwpck_require__(1489)
-module.exports = {
- parse,
- valid,
- clean,
- inc,
- diff,
- major,
- minor,
- patch,
- prerelease,
- compare,
- rcompare,
- compareLoose,
- compareBuild,
- sort,
- rsort,
- gt,
- lt,
- eq,
- neq,
- gte,
- lte,
- cmp,
- coerce,
- Comparator,
- Range,
- satisfies,
- toComparators,
- maxSatisfying,
- minSatisfying,
- minVersion,
- validRange,
- outside,
- gtr,
- ltr,
- intersects,
- simplifyRange,
- subset,
- SemVer,
- re: internalRe.re,
- src: internalRe.src,
- tokens: internalRe.t,
- SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION,
- RELEASE_TYPES: constants.RELEASE_TYPES,
- compareIdentifiers: identifiers.compareIdentifiers,
- rcompareIdentifiers: identifiers.rcompareIdentifiers,
-}
-
-
-/***/ }),
-
-/***/ 5101:
-/***/ ((module) => {
-
-
-
-// Note: this is the semver.org version of the spec that it implements
-// Not necessarily the package version of this code.
-const SEMVER_SPEC_VERSION = '2.0.0'
-
-const MAX_LENGTH = 256
-const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
-/* istanbul ignore next */ 9007199254740991
-
-// Max safe segment length for coercion.
-const MAX_SAFE_COMPONENT_LENGTH = 16
-
-// Max safe length for a build identifier. The max length minus 6 characters for
-// the shortest version with a build 0.0.0+BUILD.
-const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6
-
-const RELEASE_TYPES = [
- 'major',
- 'premajor',
- 'minor',
- 'preminor',
- 'patch',
- 'prepatch',
- 'prerelease',
-]
-
-module.exports = {
- MAX_LENGTH,
- MAX_SAFE_COMPONENT_LENGTH,
- MAX_SAFE_BUILD_LENGTH,
- MAX_SAFE_INTEGER,
- RELEASE_TYPES,
- SEMVER_SPEC_VERSION,
- FLAG_INCLUDE_PRERELEASE: 0b001,
- FLAG_LOOSE: 0b010,
-}
-
-
-/***/ }),
-
-/***/ 1159:
-/***/ ((module) => {
-
-
-
-const debug = (
- typeof process === 'object' &&
- process.env &&
- process.env.NODE_DEBUG &&
- /\bsemver\b/i.test(process.env.NODE_DEBUG)
-) ? (...args) => console.error('SEMVER', ...args)
- : () => {}
-
-module.exports = debug
-
-
-/***/ }),
-
-/***/ 3348:
-/***/ ((module) => {
-
-
-
-const numeric = /^[0-9]+$/
-const compareIdentifiers = (a, b) => {
- if (typeof a === 'number' && typeof b === 'number') {
- return a === b ? 0 : a < b ? -1 : 1
- }
-
- const anum = numeric.test(a)
- const bnum = numeric.test(b)
-
- if (anum && bnum) {
- a = +a
- b = +b
- }
-
- return a === b ? 0
- : (anum && !bnum) ? -1
- : (bnum && !anum) ? 1
- : a < b ? -1
- : 1
-}
-
-const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a)
-
-module.exports = {
- compareIdentifiers,
- rcompareIdentifiers,
-}
-
-
-/***/ }),
-
-/***/ 1383:
-/***/ ((module) => {
-
-
-
-class LRUCache {
- constructor () {
- this.max = 1000
- this.map = new Map()
- }
-
- get (key) {
- const value = this.map.get(key)
- if (value === undefined) {
- return undefined
- } else {
- // Remove the key from the map and add it to the end
- this.map.delete(key)
- this.map.set(key, value)
- return value
- }
- }
-
- delete (key) {
- return this.map.delete(key)
- }
-
- set (key, value) {
- const deleted = this.delete(key)
-
- if (!deleted && value !== undefined) {
- // If cache is full, delete the least recently used item
- if (this.map.size >= this.max) {
- const firstKey = this.map.keys().next().value
- this.delete(firstKey)
- }
-
- this.map.set(key, value)
- }
-
- return this
- }
-}
-
-module.exports = LRUCache
-
-
-/***/ }),
-
-/***/ 356:
-/***/ ((module) => {
-
-
-
-// parse out just the options we care about
-const looseOption = Object.freeze({ loose: true })
-const emptyOpts = Object.freeze({ })
-const parseOptions = options => {
- if (!options) {
- return emptyOpts
- }
-
- if (typeof options !== 'object') {
- return looseOption
- }
-
- return options
-}
-module.exports = parseOptions
-
-
-/***/ }),
-
-/***/ 5471:
-/***/ ((module, exports, __nccwpck_require__) => {
-
-
-
-const {
- MAX_SAFE_COMPONENT_LENGTH,
- MAX_SAFE_BUILD_LENGTH,
- MAX_LENGTH,
-} = __nccwpck_require__(5101)
-const debug = __nccwpck_require__(1159)
-exports = module.exports = {}
-
-// The actual regexps go on exports.re
-const re = exports.re = []
-const safeRe = exports.safeRe = []
-const src = exports.src = []
-const safeSrc = exports.safeSrc = []
-const t = exports.t = {}
-let R = 0
-
-const LETTERDASHNUMBER = '[a-zA-Z0-9-]'
-
-// Replace some greedy regex tokens to prevent regex dos issues. These regex are
-// used internally via the safeRe object since all inputs in this library get
-// normalized first to trim and collapse all extra whitespace. The original
-// regexes are exported for userland consumption and lower level usage. A
-// future breaking change could export the safer regex only with a note that
-// all input should have extra whitespace removed.
-const safeRegexReplacements = [
- ['\\s', 1],
- ['\\d', MAX_LENGTH],
- [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH],
-]
-
-const makeSafeRegex = (value) => {
- for (const [token, max] of safeRegexReplacements) {
- value = value
- .split(`${token}*`).join(`${token}{0,${max}}`)
- .split(`${token}+`).join(`${token}{1,${max}}`)
- }
- return value
-}
-
-const createToken = (name, value, isGlobal) => {
- const safe = makeSafeRegex(value)
- const index = R++
- debug(name, index, value)
- t[name] = index
- src[index] = value
- safeSrc[index] = safe
- re[index] = new RegExp(value, isGlobal ? 'g' : undefined)
- safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined)
-}
-
-// The following Regular Expressions can be used for tokenizing,
-// validating, and parsing SemVer version strings.
-
-// ## Numeric Identifier
-// A single `0`, or a non-zero digit followed by zero or more digits.
-
-createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*')
-createToken('NUMERICIDENTIFIERLOOSE', '\\d+')
-
-// ## Non-numeric Identifier
-// Zero or more digits, followed by a letter or hyphen, and then zero or
-// more letters, digits, or hyphens.
-
-createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`)
-
-// ## Main Version
-// Three dot-separated numeric identifiers.
-
-createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` +
- `(${src[t.NUMERICIDENTIFIER]})\\.` +
- `(${src[t.NUMERICIDENTIFIER]})`)
-
-createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
- `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
- `(${src[t.NUMERICIDENTIFIERLOOSE]})`)
-
-// ## Pre-release Version Identifier
-// A numeric identifier, or a non-numeric identifier.
-// Non-numeric identifiers include numeric identifiers but can be longer.
-// Therefore non-numeric identifiers must go first.
-
-createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NONNUMERICIDENTIFIER]
-}|${src[t.NUMERICIDENTIFIER]})`)
-
-createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NONNUMERICIDENTIFIER]
-}|${src[t.NUMERICIDENTIFIERLOOSE]})`)
-
-// ## Pre-release Version
-// Hyphen, followed by one or more dot-separated pre-release version
-// identifiers.
-
-createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]
-}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`)
-
-createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]
-}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`)
-
-// ## Build Metadata Identifier
-// Any combination of digits, letters, or hyphens.
-
-createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`)
-
-// ## Build Metadata
-// Plus sign, followed by one or more period-separated build metadata
-// identifiers.
-
-createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER]
-}(?:\\.${src[t.BUILDIDENTIFIER]})*))`)
-
-// ## Full Version String
-// A main version, followed optionally by a pre-release version and
-// build metadata.
-
-// Note that the only major, minor, patch, and pre-release sections of
-// the version string are capturing groups. The build metadata is not a
-// capturing group, because it should not ever be used in version
-// comparison.
-
-createToken('FULLPLAIN', `v?${src[t.MAINVERSION]
-}${src[t.PRERELEASE]}?${
- src[t.BUILD]}?`)
-
-createToken('FULL', `^${src[t.FULLPLAIN]}$`)
-
-// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
-// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
-// common in the npm registry.
-createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE]
-}${src[t.PRERELEASELOOSE]}?${
- src[t.BUILD]}?`)
-
-createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`)
-
-createToken('GTLT', '((?:<|>)?=?)')
-
-// Something like "2.*" or "1.2.x".
-// Note that "x.x" is a valid xRange identifer, meaning "any version"
-// Only the first item is strictly required.
-createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`)
-createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`)
-
-createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` +
- `(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
- `(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
- `(?:${src[t.PRERELEASE]})?${
- src[t.BUILD]}?` +
- `)?)?`)
-
-createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +
- `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
- `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
- `(?:${src[t.PRERELEASELOOSE]})?${
- src[t.BUILD]}?` +
- `)?)?`)
-
-createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`)
-createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`)
-
-// Coercion.
-// Extract anything that could conceivably be a part of a valid semver
-createToken('COERCEPLAIN', `${'(^|[^\\d])' +
- '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +
- `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +
- `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`)
-createToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\d])`)
-createToken('COERCEFULL', src[t.COERCEPLAIN] +
- `(?:${src[t.PRERELEASE]})?` +
- `(?:${src[t.BUILD]})?` +
- `(?:$|[^\\d])`)
-createToken('COERCERTL', src[t.COERCE], true)
-createToken('COERCERTLFULL', src[t.COERCEFULL], true)
-
-// Tilde ranges.
-// Meaning is "reasonably at or greater than"
-createToken('LONETILDE', '(?:~>?)')
-
-createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true)
-exports.tildeTrimReplace = '$1~'
-
-createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`)
-createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`)
-
-// Caret ranges.
-// Meaning is "at least and backwards compatible with"
-createToken('LONECARET', '(?:\\^)')
-
-createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true)
-exports.caretTrimReplace = '$1^'
-
-createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`)
-createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`)
-
-// A simple gt/lt/eq thing, or just "" to indicate "any version"
-createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`)
-createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`)
-
-// An expression to strip any whitespace between the gtlt and the thing
-// it modifies, so that `> 1.2.3` ==> `>1.2.3`
-createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT]
-}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true)
-exports.comparatorTrimReplace = '$1$2$3'
-
-// Something like `1.2.3 - 1.2.4`
-// Note that these all use the loose form, because they'll be
-// checked against either the strict or loose comparator form
-// later.
-createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` +
- `\\s+-\\s+` +
- `(${src[t.XRANGEPLAIN]})` +
- `\\s*$`)
-
-createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` +
- `\\s+-\\s+` +
- `(${src[t.XRANGEPLAINLOOSE]})` +
- `\\s*$`)
-
-// Star ranges basically just allow anything at all.
-createToken('STAR', '(<|>)?=?\\s*\\*')
-// >=0.0.0 is like a star
-createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$')
-createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$')
-
-
-/***/ }),
-
-/***/ 2276:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-// Determine if version is greater than all the versions possible in the range.
-const outside = __nccwpck_require__(280)
-const gtr = (version, range, options) => outside(version, range, '>', options)
-module.exports = gtr
-
-
-/***/ }),
-
-/***/ 3465:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const Range = __nccwpck_require__(6782)
-const intersects = (r1, r2, options) => {
- r1 = new Range(r1, options)
- r2 = new Range(r2, options)
- return r1.intersects(r2, options)
-}
-module.exports = intersects
-
-
-/***/ }),
-
-/***/ 5213:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const outside = __nccwpck_require__(280)
-// Determine if version is less than all the versions possible in the range
-const ltr = (version, range, options) => outside(version, range, '<', options)
-module.exports = ltr
-
-
-/***/ }),
-
-/***/ 5574:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const SemVer = __nccwpck_require__(7163)
-const Range = __nccwpck_require__(6782)
-
-const maxSatisfying = (versions, range, options) => {
- let max = null
- let maxSV = null
- let rangeObj = null
- try {
- rangeObj = new Range(range, options)
- } catch (er) {
- return null
- }
- versions.forEach((v) => {
- if (rangeObj.test(v)) {
- // satisfies(v, range, options)
- if (!max || maxSV.compare(v) === -1) {
- // compare(max, v, true)
- max = v
- maxSV = new SemVer(max, options)
- }
- }
- })
- return max
-}
-module.exports = maxSatisfying
-
-
-/***/ }),
-
-/***/ 8595:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const SemVer = __nccwpck_require__(7163)
-const Range = __nccwpck_require__(6782)
-const minSatisfying = (versions, range, options) => {
- let min = null
- let minSV = null
- let rangeObj = null
- try {
- rangeObj = new Range(range, options)
- } catch (er) {
- return null
- }
- versions.forEach((v) => {
- if (rangeObj.test(v)) {
- // satisfies(v, range, options)
- if (!min || minSV.compare(v) === 1) {
- // compare(min, v, true)
- min = v
- minSV = new SemVer(min, options)
- }
- }
- })
- return min
-}
-module.exports = minSatisfying
-
-
-/***/ }),
-
-/***/ 1866:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const SemVer = __nccwpck_require__(7163)
-const Range = __nccwpck_require__(6782)
-const gt = __nccwpck_require__(6599)
-
-const minVersion = (range, loose) => {
- range = new Range(range, loose)
-
- let minver = new SemVer('0.0.0')
- if (range.test(minver)) {
- return minver
- }
-
- minver = new SemVer('0.0.0-0')
- if (range.test(minver)) {
- return minver
- }
-
- minver = null
- for (let i = 0; i < range.set.length; ++i) {
- const comparators = range.set[i]
-
- let setMin = null
- comparators.forEach((comparator) => {
- // Clone to avoid manipulating the comparator's semver object.
- const compver = new SemVer(comparator.semver.version)
- switch (comparator.operator) {
- case '>':
- if (compver.prerelease.length === 0) {
- compver.patch++
- } else {
- compver.prerelease.push(0)
- }
- compver.raw = compver.format()
- /* fallthrough */
- case '':
- case '>=':
- if (!setMin || gt(compver, setMin)) {
- setMin = compver
- }
- break
- case '<':
- case '<=':
- /* Ignore maximum versions */
- break
- /* istanbul ignore next */
- default:
- throw new Error(`Unexpected operation: ${comparator.operator}`)
- }
- })
- if (setMin && (!minver || gt(minver, setMin))) {
- minver = setMin
- }
- }
-
- if (minver && range.test(minver)) {
- return minver
- }
-
- return null
-}
-module.exports = minVersion
-
-
-/***/ }),
-
-/***/ 280:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const SemVer = __nccwpck_require__(7163)
-const Comparator = __nccwpck_require__(9379)
-const { ANY } = Comparator
-const Range = __nccwpck_require__(6782)
-const satisfies = __nccwpck_require__(8011)
-const gt = __nccwpck_require__(6599)
-const lt = __nccwpck_require__(3872)
-const lte = __nccwpck_require__(6717)
-const gte = __nccwpck_require__(1236)
-
-const outside = (version, range, hilo, options) => {
- version = new SemVer(version, options)
- range = new Range(range, options)
-
- let gtfn, ltefn, ltfn, comp, ecomp
- switch (hilo) {
- case '>':
- gtfn = gt
- ltefn = lte
- ltfn = lt
- comp = '>'
- ecomp = '>='
- break
- case '<':
- gtfn = lt
- ltefn = gte
- ltfn = gt
- comp = '<'
- ecomp = '<='
- break
- default:
- throw new TypeError('Must provide a hilo val of "<" or ">"')
- }
-
- // If it satisfies the range it is not outside
- if (satisfies(version, range, options)) {
- return false
- }
-
- // From now on, variable terms are as if we're in "gtr" mode.
- // but note that everything is flipped for the "ltr" function.
-
- for (let i = 0; i < range.set.length; ++i) {
- const comparators = range.set[i]
-
- let high = null
- let low = null
-
- comparators.forEach((comparator) => {
- if (comparator.semver === ANY) {
- comparator = new Comparator('>=0.0.0')
- }
- high = high || comparator
- low = low || comparator
- if (gtfn(comparator.semver, high.semver, options)) {
- high = comparator
- } else if (ltfn(comparator.semver, low.semver, options)) {
- low = comparator
- }
- })
-
- // If the edge version comparator has a operator then our version
- // isn't outside it
- if (high.operator === comp || high.operator === ecomp) {
- return false
- }
-
- // If the lowest version comparator has an operator and our version
- // is less than it then it isn't higher than the range
- if ((!low.operator || low.operator === comp) &&
- ltefn(version, low.semver)) {
- return false
- } else if (low.operator === ecomp && ltfn(version, low.semver)) {
- return false
- }
- }
- return true
-}
-
-module.exports = outside
-
-
-/***/ }),
-
-/***/ 2028:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-// given a set of versions and a range, create a "simplified" range
-// that includes the same versions that the original range does
-// If the original range is shorter than the simplified one, return that.
-const satisfies = __nccwpck_require__(8011)
-const compare = __nccwpck_require__(8469)
-module.exports = (versions, range, options) => {
- const set = []
- let first = null
- let prev = null
- const v = versions.sort((a, b) => compare(a, b, options))
- for (const version of v) {
- const included = satisfies(version, range, options)
- if (included) {
- prev = version
- if (!first) {
- first = version
- }
- } else {
- if (prev) {
- set.push([first, prev])
- }
- prev = null
- first = null
- }
- }
- if (first) {
- set.push([first, null])
- }
-
- const ranges = []
- for (const [min, max] of set) {
- if (min === max) {
- ranges.push(min)
- } else if (!max && min === v[0]) {
- ranges.push('*')
- } else if (!max) {
- ranges.push(`>=${min}`)
- } else if (min === v[0]) {
- ranges.push(`<=${max}`)
- } else {
- ranges.push(`${min} - ${max}`)
- }
- }
- const simplified = ranges.join(' || ')
- const original = typeof range.raw === 'string' ? range.raw : String(range)
- return simplified.length < original.length ? simplified : range
-}
-
-
-/***/ }),
-
-/***/ 1489:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const Range = __nccwpck_require__(6782)
-const Comparator = __nccwpck_require__(9379)
-const { ANY } = Comparator
-const satisfies = __nccwpck_require__(8011)
-const compare = __nccwpck_require__(8469)
-
-// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff:
-// - Every simple range `r1, r2, ...` is a null set, OR
-// - Every simple range `r1, r2, ...` which is not a null set is a subset of
-// some `R1, R2, ...`
-//
-// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff:
-// - If c is only the ANY comparator
-// - If C is only the ANY comparator, return true
-// - Else if in prerelease mode, return false
-// - else replace c with `[>=0.0.0]`
-// - If C is only the ANY comparator
-// - if in prerelease mode, return true
-// - else replace C with `[>=0.0.0]`
-// - Let EQ be the set of = comparators in c
-// - If EQ is more than one, return true (null set)
-// - Let GT be the highest > or >= comparator in c
-// - Let LT be the lowest < or <= comparator in c
-// - If GT and LT, and GT.semver > LT.semver, return true (null set)
-// - If any C is a = range, and GT or LT are set, return false
-// - If EQ
-// - If GT, and EQ does not satisfy GT, return true (null set)
-// - If LT, and EQ does not satisfy LT, return true (null set)
-// - If EQ satisfies every C, return true
-// - Else return false
-// - If GT
-// - If GT.semver is lower than any > or >= comp in C, return false
-// - If GT is >=, and GT.semver does not satisfy every C, return false
-// - If GT.semver has a prerelease, and not in prerelease mode
-// - If no C has a prerelease and the GT.semver tuple, return false
-// - If LT
-// - If LT.semver is greater than any < or <= comp in C, return false
-// - If LT is <=, and LT.semver does not satisfy every C, return false
-// - If LT.semver has a prerelease, and not in prerelease mode
-// - If no C has a prerelease and the LT.semver tuple, return false
-// - Else return true
-
-const subset = (sub, dom, options = {}) => {
- if (sub === dom) {
- return true
- }
-
- sub = new Range(sub, options)
- dom = new Range(dom, options)
- let sawNonNull = false
-
- OUTER: for (const simpleSub of sub.set) {
- for (const simpleDom of dom.set) {
- const isSub = simpleSubset(simpleSub, simpleDom, options)
- sawNonNull = sawNonNull || isSub !== null
- if (isSub) {
- continue OUTER
- }
- }
- // the null set is a subset of everything, but null simple ranges in
- // a complex range should be ignored. so if we saw a non-null range,
- // then we know this isn't a subset, but if EVERY simple range was null,
- // then it is a subset.
- if (sawNonNull) {
- return false
- }
- }
- return true
-}
-
-const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')]
-const minimumVersion = [new Comparator('>=0.0.0')]
-
-const simpleSubset = (sub, dom, options) => {
- if (sub === dom) {
- return true
- }
-
- if (sub.length === 1 && sub[0].semver === ANY) {
- if (dom.length === 1 && dom[0].semver === ANY) {
- return true
- } else if (options.includePrerelease) {
- sub = minimumVersionWithPreRelease
- } else {
- sub = minimumVersion
- }
- }
-
- if (dom.length === 1 && dom[0].semver === ANY) {
- if (options.includePrerelease) {
- return true
- } else {
- dom = minimumVersion
- }
- }
-
- const eqSet = new Set()
- let gt, lt
- for (const c of sub) {
- if (c.operator === '>' || c.operator === '>=') {
- gt = higherGT(gt, c, options)
- } else if (c.operator === '<' || c.operator === '<=') {
- lt = lowerLT(lt, c, options)
- } else {
- eqSet.add(c.semver)
- }
- }
-
- if (eqSet.size > 1) {
- return null
- }
-
- let gtltComp
- if (gt && lt) {
- gtltComp = compare(gt.semver, lt.semver, options)
- if (gtltComp > 0) {
- return null
- } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) {
- return null
- }
- }
-
- // will iterate one or zero times
- for (const eq of eqSet) {
- if (gt && !satisfies(eq, String(gt), options)) {
- return null
- }
-
- if (lt && !satisfies(eq, String(lt), options)) {
- return null
- }
-
- for (const c of dom) {
- if (!satisfies(eq, String(c), options)) {
- return false
- }
- }
-
- return true
- }
-
- let higher, lower
- let hasDomLT, hasDomGT
- // if the subset has a prerelease, we need a comparator in the superset
- // with the same tuple and a prerelease, or it's not a subset
- let needDomLTPre = lt &&
- !options.includePrerelease &&
- lt.semver.prerelease.length ? lt.semver : false
- let needDomGTPre = gt &&
- !options.includePrerelease &&
- gt.semver.prerelease.length ? gt.semver : false
- // exception: <1.2.3-0 is the same as <1.2.3
- if (needDomLTPre && needDomLTPre.prerelease.length === 1 &&
- lt.operator === '<' && needDomLTPre.prerelease[0] === 0) {
- needDomLTPre = false
- }
-
- for (const c of dom) {
- hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='
- hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='
- if (gt) {
- if (needDomGTPre) {
- if (c.semver.prerelease && c.semver.prerelease.length &&
- c.semver.major === needDomGTPre.major &&
- c.semver.minor === needDomGTPre.minor &&
- c.semver.patch === needDomGTPre.patch) {
- needDomGTPre = false
- }
- }
- if (c.operator === '>' || c.operator === '>=') {
- higher = higherGT(gt, c, options)
- if (higher === c && higher !== gt) {
- return false
- }
- } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) {
- return false
- }
- }
- if (lt) {
- if (needDomLTPre) {
- if (c.semver.prerelease && c.semver.prerelease.length &&
- c.semver.major === needDomLTPre.major &&
- c.semver.minor === needDomLTPre.minor &&
- c.semver.patch === needDomLTPre.patch) {
- needDomLTPre = false
- }
- }
- if (c.operator === '<' || c.operator === '<=') {
- lower = lowerLT(lt, c, options)
- if (lower === c && lower !== lt) {
- return false
- }
- } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) {
- return false
- }
- }
- if (!c.operator && (lt || gt) && gtltComp !== 0) {
- return false
- }
- }
-
- // if there was a < or >, and nothing in the dom, then must be false
- // UNLESS it was limited by another range in the other direction.
- // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0
- if (gt && hasDomLT && !lt && gtltComp !== 0) {
- return false
- }
-
- if (lt && hasDomGT && !gt && gtltComp !== 0) {
- return false
- }
-
- // we needed a prerelease range in a specific tuple, but didn't get one
- // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0,
- // because it includes prereleases in the 1.2.3 tuple
- if (needDomGTPre || needDomLTPre) {
- return false
- }
-
- return true
-}
-
-// >=1.2.3 is lower than >1.2.3
-const higherGT = (a, b, options) => {
- if (!a) {
- return b
- }
- const comp = compare(a.semver, b.semver, options)
- return comp > 0 ? a
- : comp < 0 ? b
- : b.operator === '>' && a.operator === '>=' ? b
- : a
-}
-
-// <=1.2.3 is higher than <1.2.3
-const lowerLT = (a, b, options) => {
- if (!a) {
- return b
- }
- const comp = compare(a.semver, b.semver, options)
- return comp < 0 ? a
- : comp > 0 ? b
- : b.operator === '<' && a.operator === '<=' ? b
- : a
-}
-
-module.exports = subset
-
-
-/***/ }),
-
-/***/ 4750:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const Range = __nccwpck_require__(6782)
-
-// Mostly just for testing and legacy API reasons
-const toComparators = (range, options) =>
- new Range(range, options).set
- .map(comp => comp.map(c => c.value).join(' ').trim().split(' '))
-
-module.exports = toComparators
-
-
-/***/ }),
-
-/***/ 4737:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const Range = __nccwpck_require__(6782)
-const validRange = (range, options) => {
- try {
- // Return '*' instead of '' so that truthiness works.
- // This will throw if it's invalid anyway
- return new Range(range, options).range || '*'
- } catch (er) {
- return null
- }
-}
-module.exports = validRange
-
-
-/***/ }),
-
-/***/ 1860:
-/***/ ((module) => {
-
-/******************************************************************************
-Copyright (c) Microsoft Corporation.
-
-Permission to use, copy, modify, and/or distribute this software for any
-purpose with or without fee is hereby granted.
-
-THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
-REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
-INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
-OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-PERFORMANCE OF THIS SOFTWARE.
-***************************************************************************** */
-/* global global, define, Symbol, Reflect, Promise, SuppressedError, Iterator */
-var __extends;
-var __assign;
-var __rest;
-var __decorate;
-var __param;
-var __esDecorate;
-var __runInitializers;
-var __propKey;
-var __setFunctionName;
-var __metadata;
-var __awaiter;
-var __generator;
-var __exportStar;
-var __values;
-var __read;
-var __spread;
-var __spreadArrays;
-var __spreadArray;
-var __await;
-var __asyncGenerator;
-var __asyncDelegator;
-var __asyncValues;
-var __makeTemplateObject;
-var __importStar;
-var __importDefault;
-var __classPrivateFieldGet;
-var __classPrivateFieldSet;
-var __classPrivateFieldIn;
-var __createBinding;
-var __addDisposableResource;
-var __disposeResources;
-var __rewriteRelativeImportExtension;
-(function (factory) {
- var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {};
- if (typeof define === "function" && define.amd) {
- define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); });
- }
- else if ( true && typeof module.exports === "object") {
- factory(createExporter(root, createExporter(module.exports)));
- }
- else {
- factory(createExporter(root));
- }
- function createExporter(exports, previous) {
- if (exports !== root) {
- if (typeof Object.create === "function") {
- Object.defineProperty(exports, "__esModule", { value: true });
- }
- else {
- exports.__esModule = true;
- }
- }
- return function (id, v) { return exports[id] = previous ? previous(id, v) : v; };
- }
-})
-(function (exporter) {
- var extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
-
- __extends = function (d, b) {
- if (typeof b !== "function" && b !== null)
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
-
- __assign = Object.assign || function (t) {
- for (var s, i = 1, n = arguments.length; i < n; i++) {
- s = arguments[i];
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
- }
- return t;
- };
-
- __rest = function (s, e) {
- var t = {};
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
- t[p] = s[p];
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
- t[p[i]] = s[p[i]];
- }
- return t;
- };
-
- __decorate = function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
-
- __param = function (paramIndex, decorator) {
- return function (target, key) { decorator(target, key, paramIndex); }
- };
-
- __esDecorate = function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
- function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
- var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
- var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
- var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
- var _, done = false;
- for (var i = decorators.length - 1; i >= 0; i--) {
- var context = {};
- for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
- for (var p in contextIn.access) context.access[p] = contextIn.access[p];
- context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
- var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
- if (kind === "accessor") {
- if (result === void 0) continue;
- if (result === null || typeof result !== "object") throw new TypeError("Object expected");
- if (_ = accept(result.get)) descriptor.get = _;
- if (_ = accept(result.set)) descriptor.set = _;
- if (_ = accept(result.init)) initializers.unshift(_);
- }
- else if (_ = accept(result)) {
- if (kind === "field") initializers.unshift(_);
- else descriptor[key] = _;
- }
- }
- if (target) Object.defineProperty(target, contextIn.name, descriptor);
- done = true;
- };
-
- __runInitializers = function (thisArg, initializers, value) {
- var useValue = arguments.length > 2;
- for (var i = 0; i < initializers.length; i++) {
- value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
- }
- return useValue ? value : void 0;
- };
-
- __propKey = function (x) {
- return typeof x === "symbol" ? x : "".concat(x);
- };
-
- __setFunctionName = function (f, name, prefix) {
- if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
- return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
- };
-
- __metadata = function (metadataKey, metadataValue) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
- };
-
- __awaiter = function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
-
- __generator = function (thisArg, body) {
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
- function verb(n) { return function (v) { return step([n, v]); }; }
- function step(op) {
- if (f) throw new TypeError("Generator is already executing.");
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
- if (y = 0, t) op = [op[0] & 2, t.value];
- switch (op[0]) {
- case 0: case 1: t = op; break;
- case 4: _.label++; return { value: op[1], done: false };
- case 5: _.label++; y = op[1]; op = [0]; continue;
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
- default:
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
- if (t[2]) _.ops.pop();
- _.trys.pop(); continue;
- }
- op = body.call(thisArg, _);
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
- }
- };
-
- __exportStar = function(m, o) {
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);
- };
-
- __createBinding = Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- var desc = Object.getOwnPropertyDescriptor(m, k);
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() { return m[k]; } };
- }
- Object.defineProperty(o, k2, desc);
- }) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
- });
-
- __values = function (o) {
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
- if (m) return m.call(o);
- if (o && typeof o.length === "number") return {
- next: function () {
- if (o && i >= o.length) o = void 0;
- return { value: o && o[i++], done: !o };
- }
- };
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
- };
-
- __read = function (o, n) {
- var m = typeof Symbol === "function" && o[Symbol.iterator];
- if (!m) return o;
- var i = m.call(o), r, ar = [], e;
- try {
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
- }
- catch (error) { e = { error: error }; }
- finally {
- try {
- if (r && !r.done && (m = i["return"])) m.call(i);
- }
- finally { if (e) throw e.error; }
- }
- return ar;
- };
-
- /** @deprecated */
- __spread = function () {
- for (var ar = [], i = 0; i < arguments.length; i++)
- ar = ar.concat(__read(arguments[i]));
- return ar;
- };
-
- /** @deprecated */
- __spreadArrays = function () {
- for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
- for (var r = Array(s), k = 0, i = 0; i < il; i++)
- for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
- r[k] = a[j];
- return r;
- };
-
- __spreadArray = function (to, from, pack) {
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
- if (ar || !(i in from)) {
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
- ar[i] = from[i];
- }
- }
- return to.concat(ar || Array.prototype.slice.call(from));
- };
-
- __await = function (v) {
- return this instanceof __await ? (this.v = v, this) : new __await(v);
- };
-
- __asyncGenerator = function (thisArg, _arguments, generator) {
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
- var g = generator.apply(thisArg, _arguments || []), i, q = [];
- return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
- function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
- function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
- function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
- function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
- function fulfill(value) { resume("next", value); }
- function reject(value) { resume("throw", value); }
- function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
- };
-
- __asyncDelegator = function (o) {
- var i, p;
- return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
- function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }
- };
-
- __asyncValues = function (o) {
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
- var m = o[Symbol.asyncIterator], i;
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
- function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
- function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
- };
-
- __makeTemplateObject = function (cooked, raw) {
- if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
- return cooked;
- };
-
- var __setModuleDefault = Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
- }) : function(o, v) {
- o["default"] = v;
- };
-
- var ownKeys = function(o) {
- ownKeys = Object.getOwnPropertyNames || function (o) {
- var ar = [];
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
- return ar;
- };
- return ownKeys(o);
- };
-
- __importStar = function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
- __setModuleDefault(result, mod);
- return result;
- };
-
- __importDefault = function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
- };
-
- __classPrivateFieldGet = function (receiver, state, kind, f) {
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
- };
-
- __classPrivateFieldSet = function (receiver, state, value, kind, f) {
- if (kind === "m") throw new TypeError("Private method is not writable");
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
- };
-
- __classPrivateFieldIn = function (state, receiver) {
- if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object");
- return typeof state === "function" ? receiver === state : state.has(receiver);
- };
-
- __addDisposableResource = function (env, value, async) {
- if (value !== null && value !== void 0) {
- if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
- var dispose, inner;
- if (async) {
- if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
- dispose = value[Symbol.asyncDispose];
- }
- if (dispose === void 0) {
- if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
- dispose = value[Symbol.dispose];
- if (async) inner = dispose;
- }
- if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
- if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
- env.stack.push({ value: value, dispose: dispose, async: async });
- }
- else if (async) {
- env.stack.push({ async: true });
- }
- return value;
- };
-
- var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
- var e = new Error(message);
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
- };
-
- __disposeResources = function (env) {
- function fail(e) {
- env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
- env.hasError = true;
- }
- var r, s = 0;
- function next() {
- while (r = env.stack.pop()) {
- try {
- if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
- if (r.dispose) {
- var result = r.dispose.call(r.value);
- if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
- }
- else s |= 1;
- }
- catch (e) {
- fail(e);
- }
- }
- if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
- if (env.hasError) throw env.error;
- }
- return next();
- };
-
- __rewriteRelativeImportExtension = function (path, preserveJsx) {
- if (typeof path === "string" && /^\.\.?\//.test(path)) {
- return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
- return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
- });
- }
- return path;
- };
-
- exporter("__extends", __extends);
- exporter("__assign", __assign);
- exporter("__rest", __rest);
- exporter("__decorate", __decorate);
- exporter("__param", __param);
- exporter("__esDecorate", __esDecorate);
- exporter("__runInitializers", __runInitializers);
- exporter("__propKey", __propKey);
- exporter("__setFunctionName", __setFunctionName);
- exporter("__metadata", __metadata);
- exporter("__awaiter", __awaiter);
- exporter("__generator", __generator);
- exporter("__exportStar", __exportStar);
- exporter("__createBinding", __createBinding);
- exporter("__values", __values);
- exporter("__read", __read);
- exporter("__spread", __spread);
- exporter("__spreadArrays", __spreadArrays);
- exporter("__spreadArray", __spreadArray);
- exporter("__await", __await);
- exporter("__asyncGenerator", __asyncGenerator);
- exporter("__asyncDelegator", __asyncDelegator);
- exporter("__asyncValues", __asyncValues);
- exporter("__makeTemplateObject", __makeTemplateObject);
- exporter("__importStar", __importStar);
- exporter("__importDefault", __importDefault);
- exporter("__classPrivateFieldGet", __classPrivateFieldGet);
- exporter("__classPrivateFieldSet", __classPrivateFieldSet);
- exporter("__classPrivateFieldIn", __classPrivateFieldIn);
- exporter("__addDisposableResource", __addDisposableResource);
- exporter("__disposeResources", __disposeResources);
- exporter("__rewriteRelativeImportExtension", __rewriteRelativeImportExtension);
-});
-
-0 && (0);
-
-
-/***/ }),
-
-/***/ 770:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-module.exports = __nccwpck_require__(218);
-
-
-/***/ }),
-
-/***/ 218:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var net = __nccwpck_require__(9278);
-var tls = __nccwpck_require__(4756);
-var http = __nccwpck_require__(8611);
-var https = __nccwpck_require__(5692);
-var events = __nccwpck_require__(4434);
-var assert = __nccwpck_require__(2613);
-var util = __nccwpck_require__(9023);
-
-
-exports.httpOverHttp = httpOverHttp;
-exports.httpsOverHttp = httpsOverHttp;
-exports.httpOverHttps = httpOverHttps;
-exports.httpsOverHttps = httpsOverHttps;
-
-
-function httpOverHttp(options) {
- var agent = new TunnelingAgent(options);
- agent.request = http.request;
- return agent;
-}
-
-function httpsOverHttp(options) {
- var agent = new TunnelingAgent(options);
- agent.request = http.request;
- agent.createSocket = createSecureSocket;
- agent.defaultPort = 443;
- return agent;
-}
-
-function httpOverHttps(options) {
- var agent = new TunnelingAgent(options);
- agent.request = https.request;
- return agent;
-}
-
-function httpsOverHttps(options) {
- var agent = new TunnelingAgent(options);
- agent.request = https.request;
- agent.createSocket = createSecureSocket;
- agent.defaultPort = 443;
- return agent;
-}
-
-
-function TunnelingAgent(options) {
- var self = this;
- self.options = options || {};
- self.proxyOptions = self.options.proxy || {};
- self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets;
- self.requests = [];
- self.sockets = [];
-
- self.on('free', function onFree(socket, host, port, localAddress) {
- var options = toOptions(host, port, localAddress);
- for (var i = 0, len = self.requests.length; i < len; ++i) {
- var pending = self.requests[i];
- if (pending.host === options.host && pending.port === options.port) {
- // Detect the request to connect same origin server,
- // reuse the connection.
- self.requests.splice(i, 1);
- pending.request.onSocket(socket);
- return;
- }
- }
- socket.destroy();
- self.removeSocket(socket);
- });
-}
-util.inherits(TunnelingAgent, events.EventEmitter);
-
-TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) {
- var self = this;
- var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress));
-
- if (self.sockets.length >= this.maxSockets) {
- // We are over limit so we'll add it to the queue.
- self.requests.push(options);
- return;
- }
-
- // If we are under maxSockets create a new one.
- self.createSocket(options, function(socket) {
- socket.on('free', onFree);
- socket.on('close', onCloseOrRemove);
- socket.on('agentRemove', onCloseOrRemove);
- req.onSocket(socket);
-
- function onFree() {
- self.emit('free', socket, options);
- }
-
- function onCloseOrRemove(err) {
- self.removeSocket(socket);
- socket.removeListener('free', onFree);
- socket.removeListener('close', onCloseOrRemove);
- socket.removeListener('agentRemove', onCloseOrRemove);
- }
- });
-};
-
-TunnelingAgent.prototype.createSocket = function createSocket(options, cb) {
- var self = this;
- var placeholder = {};
- self.sockets.push(placeholder);
-
- var connectOptions = mergeOptions({}, self.proxyOptions, {
- method: 'CONNECT',
- path: options.host + ':' + options.port,
- agent: false,
- headers: {
- host: options.host + ':' + options.port
- }
- });
- if (options.localAddress) {
- connectOptions.localAddress = options.localAddress;
- }
- if (connectOptions.proxyAuth) {
- connectOptions.headers = connectOptions.headers || {};
- connectOptions.headers['Proxy-Authorization'] = 'Basic ' +
- new Buffer(connectOptions.proxyAuth).toString('base64');
- }
-
- debug('making CONNECT request');
- var connectReq = self.request(connectOptions);
- connectReq.useChunkedEncodingByDefault = false; // for v0.6
- connectReq.once('response', onResponse); // for v0.6
- connectReq.once('upgrade', onUpgrade); // for v0.6
- connectReq.once('connect', onConnect); // for v0.7 or later
- connectReq.once('error', onError);
- connectReq.end();
-
- function onResponse(res) {
- // Very hacky. This is necessary to avoid http-parser leaks.
- res.upgrade = true;
- }
-
- function onUpgrade(res, socket, head) {
- // Hacky.
- process.nextTick(function() {
- onConnect(res, socket, head);
- });
- }
-
- function onConnect(res, socket, head) {
- connectReq.removeAllListeners();
- socket.removeAllListeners();
-
- if (res.statusCode !== 200) {
- debug('tunneling socket could not be established, statusCode=%d',
- res.statusCode);
- socket.destroy();
- var error = new Error('tunneling socket could not be established, ' +
- 'statusCode=' + res.statusCode);
- error.code = 'ECONNRESET';
- options.request.emit('error', error);
- self.removeSocket(placeholder);
- return;
- }
- if (head.length > 0) {
- debug('got illegal response body from proxy');
- socket.destroy();
- var error = new Error('got illegal response body from proxy');
- error.code = 'ECONNRESET';
- options.request.emit('error', error);
- self.removeSocket(placeholder);
- return;
- }
- debug('tunneling connection has established');
- self.sockets[self.sockets.indexOf(placeholder)] = socket;
- return cb(socket);
- }
-
- function onError(cause) {
- connectReq.removeAllListeners();
-
- debug('tunneling socket could not be established, cause=%s\n',
- cause.message, cause.stack);
- var error = new Error('tunneling socket could not be established, ' +
- 'cause=' + cause.message);
- error.code = 'ECONNRESET';
- options.request.emit('error', error);
- self.removeSocket(placeholder);
- }
-};
-
-TunnelingAgent.prototype.removeSocket = function removeSocket(socket) {
- var pos = this.sockets.indexOf(socket)
- if (pos === -1) {
- return;
- }
- this.sockets.splice(pos, 1);
-
- var pending = this.requests.shift();
- if (pending) {
- // If we have pending requests and a socket gets closed a new one
- // needs to be created to take over in the pool for the one that closed.
- this.createSocket(pending, function(socket) {
- pending.request.onSocket(socket);
- });
- }
-};
-
-function createSecureSocket(options, cb) {
- var self = this;
- TunnelingAgent.prototype.createSocket.call(self, options, function(socket) {
- var hostHeader = options.request.getHeader('host');
- var tlsOptions = mergeOptions({}, self.options, {
- socket: socket,
- servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host
- });
-
- // 0 is dummy port for v0.6
- var secureSocket = tls.connect(0, tlsOptions);
- self.sockets[self.sockets.indexOf(socket)] = secureSocket;
- cb(secureSocket);
- });
-}
-
-
-function toOptions(host, port, localAddress) {
- if (typeof host === 'string') { // since v0.10
- return {
- host: host,
- port: port,
- localAddress: localAddress
- };
- }
- return host; // for v0.11 or later
-}
-
-function mergeOptions(target) {
- for (var i = 1, len = arguments.length; i < len; ++i) {
- var overrides = arguments[i];
- if (typeof overrides === 'object') {
- var keys = Object.keys(overrides);
- for (var j = 0, keyLen = keys.length; j < keyLen; ++j) {
- var k = keys[j];
- if (overrides[k] !== undefined) {
- target[k] = overrides[k];
- }
- }
- }
- }
- return target;
-}
-
-
-var debug;
-if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) {
- debug = function() {
- var args = Array.prototype.slice.call(arguments);
- if (typeof args[0] === 'string') {
- args[0] = 'TUNNEL: ' + args[0];
- } else {
- args.unshift('TUNNEL:');
- }
- console.error.apply(console, args);
- }
-} else {
- debug = function() {};
-}
-exports.debug = debug; // for test
-
-
-/***/ }),
-
-/***/ 75:
-/***/ ((module) => {
-
-module.exports = eval("require")("supports-color");
-
-
-/***/ }),
-
-/***/ 2613:
-/***/ ((module) => {
-
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("assert");
-
-/***/ }),
-
-/***/ 181:
-/***/ ((module) => {
-
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("buffer");
-
-/***/ }),
-
-/***/ 4434:
-/***/ ((module) => {
-
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("events");
-
-/***/ }),
-
-/***/ 8611:
-/***/ ((module) => {
-
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("http");
-
-/***/ }),
-
-/***/ 5692:
-/***/ ((module) => {
-
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("https");
-
-/***/ }),
-
-/***/ 9278:
-/***/ ((module) => {
-
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("net");
-
-/***/ }),
-
-/***/ 4589:
-/***/ ((module) => {
-
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:assert");
-
-/***/ }),
-
-/***/ 6698:
-/***/ ((module) => {
-
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:async_hooks");
-
-/***/ }),
-
-/***/ 4573:
-/***/ ((module) => {
-
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:buffer");
-
-/***/ }),
-
-/***/ 7540:
-/***/ ((module) => {
-
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:console");
-
-/***/ }),
-
-/***/ 7598:
-/***/ ((module) => {
-
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:crypto");
-
-/***/ }),
-
-/***/ 3053:
-/***/ ((module) => {
-
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:diagnostics_channel");
-
-/***/ }),
-
-/***/ 610:
-/***/ ((module) => {
-
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:dns");
-
-/***/ }),
-
-/***/ 8474:
-/***/ ((module) => {
-
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:events");
-
-/***/ }),
-
-/***/ 7067:
-/***/ ((module) => {
-
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:http");
-
-/***/ }),
-
-/***/ 2467:
-/***/ ((module) => {
-
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:http2");
-
-/***/ }),
-
-/***/ 7030:
-/***/ ((module) => {
-
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:net");
-
-/***/ }),
-
-/***/ 8161:
-/***/ ((module) => {
-
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:os");
-
-/***/ }),
-
-/***/ 643:
-/***/ ((module) => {
-
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:perf_hooks");
-
-/***/ }),
-
-/***/ 1708:
-/***/ ((module) => {
-
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:process");
-
-/***/ }),
-
-/***/ 1792:
-/***/ ((module) => {
-
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:querystring");
-
-/***/ }),
-
-/***/ 7075:
-/***/ ((module) => {
-
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:stream");
-
-/***/ }),
-
-/***/ 1692:
-/***/ ((module) => {
-
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:tls");
-
-/***/ }),
-
-/***/ 3136:
-/***/ ((module) => {
-
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:url");
-
-/***/ }),
-
-/***/ 7975:
-/***/ ((module) => {
-
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:util");
-
-/***/ }),
-
-/***/ 3429:
-/***/ ((module) => {
-
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:util/types");
-
-/***/ }),
-
-/***/ 5919:
-/***/ ((module) => {
-
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:worker_threads");
-
-/***/ }),
-
-/***/ 8522:
-/***/ ((module) => {
-
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:zlib");
-
-/***/ }),
-
-/***/ 6928:
-/***/ ((module) => {
-
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("path");
-
-/***/ }),
-
-/***/ 932:
-/***/ ((module) => {
-
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("process");
-
-/***/ }),
-
-/***/ 3193:
-/***/ ((module) => {
-
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("string_decoder");
-
-/***/ }),
-
-/***/ 4756:
-/***/ ((module) => {
-
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("tls");
-
-/***/ }),
-
-/***/ 2018:
-/***/ ((module) => {
-
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("tty");
-
-/***/ }),
-
-/***/ 7016:
-/***/ ((module) => {
-
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("url");
-
-/***/ }),
-
-/***/ 9023:
-/***/ ((module) => {
-
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("util");
-
-/***/ }),
-
-/***/ 3345:
-/***/ ((__unused_webpack_module, exports) => {
-
-var __webpack_unused_export__;
-
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-__webpack_unused_export__ = ({ value: true });
-exports.w = void 0;
-/**
- * Holds the singleton operationRequestMap, to be shared across CJS and ESM imports.
- */
-exports.w = {
- operationRequestMap: new WeakMap(),
-};
-//# sourceMappingURL=state-cjs.cjs.map
-
-/***/ }),
-
-/***/ 8914:
-/***/ ((__unused_webpack_module, exports) => {
-
-var __webpack_unused_export__;
-
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-__webpack_unused_export__ = ({ value: true });
-exports.w = void 0;
-/**
- * @internal
- *
- * Holds the singleton instrumenter, to be shared across CJS and ESM imports.
- */
-exports.w = {
- instrumenterImplementation: undefined,
-};
-//# sourceMappingURL=state-cjs.cjs.map
-
-/***/ }),
-
-/***/ 5209:
-/***/ ((__unused_webpack_module, exports) => {
-
-
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.cancelablePromiseRace = cancelablePromiseRace;
-/**
- * promise.race() wrapper that aborts rest of promises as soon as the first promise settles.
- */
-async function cancelablePromiseRace(abortablePromiseBuilders, options) {
- const aborter = new AbortController();
- function abortHandler() {
- aborter.abort();
- }
- options?.abortSignal?.addEventListener("abort", abortHandler);
- try {
- return await Promise.race(abortablePromiseBuilders.map((p) => p({ abortSignal: aborter.signal })));
- }
- finally {
- aborter.abort();
- options?.abortSignal?.removeEventListener("abort", abortHandler);
- }
-}
-//# sourceMappingURL=aborterUtils.js.map
-
-/***/ }),
-
-/***/ 3128:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.createAbortablePromise = createAbortablePromise;
-const abort_controller_1 = __nccwpck_require__(6492);
-/**
- * Creates an abortable promise.
- * @param buildPromise - A function that takes the resolve and reject functions as parameters.
- * @param options - The options for the abortable promise.
- * @returns A promise that can be aborted.
- */
-function createAbortablePromise(buildPromise, options) {
- const { cleanupBeforeAbort, abortSignal, abortErrorMsg } = options ?? {};
- return new Promise((resolve, reject) => {
- function rejectOnAbort() {
- reject(new abort_controller_1.AbortError(abortErrorMsg ?? "The operation was aborted."));
- }
- function removeListeners() {
- abortSignal?.removeEventListener("abort", onAbort);
- }
- function onAbort() {
- cleanupBeforeAbort?.();
- removeListeners();
- rejectOnAbort();
- }
- if (abortSignal?.aborted) {
- return rejectOnAbort();
- }
- try {
- buildPromise((x) => {
- removeListeners();
- resolve(x);
- }, (x) => {
- removeListeners();
- reject(x);
- });
- }
- catch (err) {
- reject(err);
- }
- abortSignal?.addEventListener("abort", onAbort);
- });
-}
-//# sourceMappingURL=createAbortablePromise.js.map
-
-/***/ }),
-
-/***/ 636:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.delay = delay;
-exports.calculateRetryDelay = calculateRetryDelay;
-const createAbortablePromise_js_1 = __nccwpck_require__(3128);
-const util_1 = __nccwpck_require__(5750);
-const StandardAbortMessage = "The delay was aborted.";
-/**
- * A wrapper for setTimeout that resolves a promise after timeInMs milliseconds.
- * @param timeInMs - The number of milliseconds to be delayed.
- * @param options - The options for delay - currently abort options
- * @returns Promise that is resolved after timeInMs
- */
-function delay(timeInMs, options) {
- let token;
- const { abortSignal, abortErrorMsg } = options ?? {};
- return (0, createAbortablePromise_js_1.createAbortablePromise)((resolve) => {
- token = setTimeout(resolve, timeInMs);
- }, {
- cleanupBeforeAbort: () => clearTimeout(token),
- abortSignal,
- abortErrorMsg: abortErrorMsg ?? StandardAbortMessage,
- });
-}
-/**
- * Calculates the delay interval for retry attempts using exponential delay with jitter.
- * @param retryAttempt - The current retry attempt number.
- * @param config - The exponential retry configuration.
- * @returns An object containing the calculated retry delay.
- */
-function calculateRetryDelay(retryAttempt, config) {
- // Exponentially increase the delay each time
- const exponentialDelay = config.retryDelayInMs * Math.pow(2, retryAttempt);
- // Don't let the delay exceed the maximum
- const clampedDelay = Math.min(config.maxRetryDelayInMs, exponentialDelay);
- // Allow the final value to have some "jitter" (within 50% of the delay size) so
- // that retries across multiple clients don't occur simultaneously.
- const retryAfterInMs = clampedDelay / 2 + (0, util_1.getRandomIntegerInclusive)(0, clampedDelay / 2);
- return { retryAfterInMs };
-}
-//# sourceMappingURL=delay.js.map
-
-/***/ }),
-
-/***/ 9945:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.getErrorMessage = getErrorMessage;
-const util_1 = __nccwpck_require__(5750);
-/**
- * Given what is thought to be an error object, return the message if possible.
- * If the message is missing, returns a stringified version of the input.
- * @param e - Something thrown from a try block
- * @returns The error message or a string of the input
- */
-function getErrorMessage(e) {
- if ((0, util_1.isError)(e)) {
- return e.message;
- }
- else {
- let stringified;
- try {
- if (typeof e === "object" && e) {
- stringified = JSON.stringify(e);
- }
- else {
- stringified = String(e);
- }
- }
- catch (err) {
- stringified = "[unable to stringify input]";
- }
- return `Unknown error ${stringified}`;
- }
-}
-//# sourceMappingURL=error.js.map
-
-/***/ }),
-
-/***/ 7779:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.isWebWorker = exports.isReactNative = exports.isNodeRuntime = exports.isNodeLike = exports.isNode = exports.isDeno = exports.isBun = exports.isBrowser = exports.objectHasProperty = exports.isObjectWithProperties = exports.isDefined = exports.getErrorMessage = exports.delay = exports.createAbortablePromise = exports.cancelablePromiseRace = void 0;
-exports.calculateRetryDelay = calculateRetryDelay;
-exports.computeSha256Hash = computeSha256Hash;
-exports.computeSha256Hmac = computeSha256Hmac;
-exports.getRandomIntegerInclusive = getRandomIntegerInclusive;
-exports.isError = isError;
-exports.isObject = isObject;
-exports.randomUUID = randomUUID;
-exports.uint8ArrayToString = uint8ArrayToString;
-exports.stringToUint8Array = stringToUint8Array;
-const tslib_1 = __nccwpck_require__(1860);
-const tspRuntime = tslib_1.__importStar(__nccwpck_require__(5750));
-var aborterUtils_js_1 = __nccwpck_require__(5209);
-Object.defineProperty(exports, "cancelablePromiseRace", ({ enumerable: true, get: function () { return aborterUtils_js_1.cancelablePromiseRace; } }));
-var createAbortablePromise_js_1 = __nccwpck_require__(3128);
-Object.defineProperty(exports, "createAbortablePromise", ({ enumerable: true, get: function () { return createAbortablePromise_js_1.createAbortablePromise; } }));
-var delay_js_1 = __nccwpck_require__(636);
-Object.defineProperty(exports, "delay", ({ enumerable: true, get: function () { return delay_js_1.delay; } }));
-var error_js_1 = __nccwpck_require__(9945);
-Object.defineProperty(exports, "getErrorMessage", ({ enumerable: true, get: function () { return error_js_1.getErrorMessage; } }));
-var typeGuards_js_1 = __nccwpck_require__(6277);
-Object.defineProperty(exports, "isDefined", ({ enumerable: true, get: function () { return typeGuards_js_1.isDefined; } }));
-Object.defineProperty(exports, "isObjectWithProperties", ({ enumerable: true, get: function () { return typeGuards_js_1.isObjectWithProperties; } }));
-Object.defineProperty(exports, "objectHasProperty", ({ enumerable: true, get: function () { return typeGuards_js_1.objectHasProperty; } }));
-/**
- * Calculates the delay interval for retry attempts using exponential delay with jitter.
- *
- * @param retryAttempt - The current retry attempt number.
- *
- * @param config - The exponential retry configuration.
- *
- * @returns An object containing the calculated retry delay.
- */
-function calculateRetryDelay(retryAttempt, config) {
- return tspRuntime.calculateRetryDelay(retryAttempt, config);
-}
-/**
- * Generates a SHA-256 hash.
- *
- * @param content - The data to be included in the hash.
- *
- * @param encoding - The textual encoding to use for the returned hash.
- */
-function computeSha256Hash(content, encoding) {
- return tspRuntime.computeSha256Hash(content, encoding);
-}
-/**
- * Generates a SHA-256 HMAC signature.
- *
- * @param key - The HMAC key represented as a base64 string, used to generate the cryptographic HMAC hash.
- *
- * @param stringToSign - The data to be signed.
- *
- * @param encoding - The textual encoding to use for the returned HMAC digest.
- */
-function computeSha256Hmac(key, stringToSign, encoding) {
- return tspRuntime.computeSha256Hmac(key, stringToSign, encoding);
-}
-/**
- * Returns a random integer value between a lower and upper bound, inclusive of both bounds. Note that this uses Math.random and isn't secure. If you need to use this for any kind of security purpose, find a better source of random.
- *
- * @param min - The smallest integer value allowed.
- *
- * @param max - The largest integer value allowed.
- */
-function getRandomIntegerInclusive(min, max) {
- return tspRuntime.getRandomIntegerInclusive(min, max);
-}
-/**
- * Typeguard for an error object shape (has name and message)
- *
- * @param e - Something caught by a catch clause.
- */
-function isError(e) {
- return tspRuntime.isError(e);
-}
-/**
- * Helper to determine when an input is a generic JS object.
- *
- * @returns true when input is an object type that is not null, Array, RegExp, or Date.
- */
-function isObject(input) {
- return tspRuntime.isObject(input);
-}
-/**
- * Generated Universally Unique Identifier
- *
- * @returns RFC4122 v4 UUID.
- */
-function randomUUID() {
- return tspRuntime.randomUUID();
-}
-/**
- * A constant that indicates whether the environment the code is running is a Web Browser.
- */
-exports.isBrowser = tspRuntime.isBrowser;
-/**
- * A constant that indicates whether the environment the code is running is Bun.sh.
- */
-exports.isBun = tspRuntime.isBun;
-/**
- * A constant that indicates whether the environment the code is running is Deno.
- */
-exports.isDeno = tspRuntime.isDeno;
-/**
- * A constant that indicates whether the environment the code is running is a Node.js compatible environment.
- *
- * @deprecated
- *
- * Use `isNodeLike` instead.
- */
-exports.isNode = tspRuntime.isNodeLike;
-/**
- * A constant that indicates whether the environment the code is running is a Node.js compatible environment.
- */
-exports.isNodeLike = tspRuntime.isNodeLike;
-/**
- * A constant that indicates whether the environment the code is running is Node.JS.
- */
-exports.isNodeRuntime = tspRuntime.isNodeRuntime;
-/**
- * A constant that indicates whether the environment the code is running is in React-Native.
- */
-exports.isReactNative = tspRuntime.isReactNative;
-/**
- * A constant that indicates whether the environment the code is running is a Web Worker.
- */
-exports.isWebWorker = tspRuntime.isWebWorker;
-/**
- * The helper that transforms bytes with specific character encoding into string
- * @param bytes - the uint8array bytes
- * @param format - the format we use to encode the byte
- * @returns a string of the encoded string
- */
-function uint8ArrayToString(bytes, format) {
- return tspRuntime.uint8ArrayToString(bytes, format);
-}
-/**
- * The helper that transforms string to specific character encoded bytes array.
- * @param value - the string to be converted
- * @param format - the format we use to decode the value
- * @returns a uint8array
- */
-function stringToUint8Array(value, format) {
- return tspRuntime.stringToUint8Array(value, format);
-}
-//# sourceMappingURL=index.js.map
-
-/***/ }),
-
-/***/ 6277:
-/***/ ((__unused_webpack_module, exports) => {
-
-
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.isDefined = isDefined;
-exports.isObjectWithProperties = isObjectWithProperties;
-exports.objectHasProperty = objectHasProperty;
-/**
- * Helper TypeGuard that checks if something is defined or not.
- * @param thing - Anything
- */
-function isDefined(thing) {
- return typeof thing !== "undefined" && thing !== null;
-}
-/**
- * Helper TypeGuard that checks if the input is an object with the specified properties.
- * @param thing - Anything.
- * @param properties - The name of the properties that should appear in the object.
- */
-function isObjectWithProperties(thing, properties) {
- if (!isDefined(thing) || typeof thing !== "object") {
- return false;
- }
- for (const property of properties) {
- if (!objectHasProperty(thing, property)) {
- return false;
- }
- }
- return true;
-}
-/**
- * Helper TypeGuard that checks if the input is an object with the specified property.
- * @param thing - Any object.
- * @param property - The name of the property that should appear in the object.
- */
-function objectHasProperty(thing, property) {
- return (isDefined(thing) && typeof thing === "object" && property in thing);
-}
-//# sourceMappingURL=typeGuards.js.map
-
-/***/ }),
-
-/***/ 1658:
-/***/ ((__unused_webpack_module, exports) => {
-
-
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.AbortError = void 0;
-/**
- * This error is thrown when an asynchronous operation has been aborted.
- * Check for this error by testing the `name` that the name property of the
- * error matches `"AbortError"`.
- *
- * @example
- * ```ts
- * const controller = new AbortController();
- * controller.abort();
- * try {
- * doAsyncWork(controller.signal)
- * } catch (e) {
- * if (e.name === 'AbortError') {
- * // handle abort error here.
- * }
- * }
- * ```
- */
-class AbortError extends Error {
- constructor(message) {
- super(message);
- this.name = "AbortError";
- }
-}
-exports.AbortError = AbortError;
-//# sourceMappingURL=AbortError.js.map
-
-/***/ }),
-
-/***/ 6492:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.AbortError = void 0;
-var AbortError_js_1 = __nccwpck_require__(1658);
-Object.defineProperty(exports, "AbortError", ({ enumerable: true, get: function () { return AbortError_js_1.AbortError; } }));
-//# sourceMappingURL=index.js.map
-
-/***/ }),
-
-/***/ 6515:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.AzureLogger = void 0;
-exports.setLogLevel = setLogLevel;
-exports.getLogLevel = getLogLevel;
-exports.createClientLogger = createClientLogger;
-const logger_1 = __nccwpck_require__(2490);
-const context = (0, logger_1.createLoggerContext)({
- logLevelEnvVarName: "AZURE_LOG_LEVEL",
- namespace: "azure",
-});
-/**
- * The AzureLogger provides a mechanism for overriding where logs are output to.
- * By default, logs are sent to stderr.
- * Override the `log` method to redirect logs to another location.
- */
-exports.AzureLogger = context.logger;
-/**
- * Immediately enables logging at the specified log level. If no level is specified, logging is disabled.
- * @param level - The log level to enable for logging.
- * Options from most verbose to least verbose are:
- * - verbose
- * - info
- * - warning
- * - error
- */
-function setLogLevel(level) {
- context.setLogLevel(level);
-}
-/**
- * Retrieves the currently specified log level.
- */
-function getLogLevel() {
- return context.getLogLevel();
-}
-/**
- * Creates a logger for use by the Azure SDKs that inherits from `AzureLogger`.
- * @param namespace - The name of the SDK package.
- * @hidden
- */
-function createClientLogger(namespace) {
- return context.createClientLogger(namespace);
-}
-//# sourceMappingURL=index.js.map
-
-/***/ }),
-
-/***/ 6836:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const log_js_1 = __nccwpck_require__(8029);
-const debugEnvVariable = (typeof process !== "undefined" && process.env && process.env.DEBUG) || undefined;
-let enabledString;
-let enabledNamespaces = [];
-let skippedNamespaces = [];
-const debuggers = [];
-if (debugEnvVariable) {
- enable(debugEnvVariable);
-}
-const debugObj = Object.assign((namespace) => {
- return createDebugger(namespace);
-}, {
- enable,
- enabled,
- disable,
- log: log_js_1.log,
-});
-function enable(namespaces) {
- enabledString = namespaces;
- enabledNamespaces = [];
- skippedNamespaces = [];
- const namespaceList = namespaces.split(",").map((ns) => ns.trim());
- for (const ns of namespaceList) {
- if (ns.startsWith("-")) {
- skippedNamespaces.push(ns.substring(1));
- }
- else {
- enabledNamespaces.push(ns);
- }
- }
- for (const instance of debuggers) {
- instance.enabled = enabled(instance.namespace);
- }
-}
-function enabled(namespace) {
- if (namespace.endsWith("*")) {
- return true;
- }
- for (const skipped of skippedNamespaces) {
- if (namespaceMatches(namespace, skipped)) {
- return false;
- }
- }
- for (const enabledNamespace of enabledNamespaces) {
- if (namespaceMatches(namespace, enabledNamespace)) {
- return true;
- }
- }
- return false;
-}
-/**
- * Given a namespace, check if it matches a pattern.
- * Patterns only have a single wildcard character which is *.
- * The behavior of * is that it matches zero or more other characters.
- */
-function namespaceMatches(namespace, patternToMatch) {
- // simple case, no pattern matching required
- if (patternToMatch.indexOf("*") === -1) {
- return namespace === patternToMatch;
- }
- let pattern = patternToMatch;
- // normalize successive * if needed
- if (patternToMatch.indexOf("**") !== -1) {
- const patternParts = [];
- let lastCharacter = "";
- for (const character of patternToMatch) {
- if (character === "*" && lastCharacter === "*") {
- continue;
- }
- else {
- lastCharacter = character;
- patternParts.push(character);
- }
- }
- pattern = patternParts.join("");
- }
- let namespaceIndex = 0;
- let patternIndex = 0;
- const patternLength = pattern.length;
- const namespaceLength = namespace.length;
- let lastWildcard = -1;
- let lastWildcardNamespace = -1;
- while (namespaceIndex < namespaceLength && patternIndex < patternLength) {
- if (pattern[patternIndex] === "*") {
- lastWildcard = patternIndex;
- patternIndex++;
- if (patternIndex === patternLength) {
- // if wildcard is the last character, it will match the remaining namespace string
- return true;
- }
- // now we let the wildcard eat characters until we match the next literal in the pattern
- while (namespace[namespaceIndex] !== pattern[patternIndex]) {
- namespaceIndex++;
- // reached the end of the namespace without a match
- if (namespaceIndex === namespaceLength) {
- return false;
- }
- }
- // now that we have a match, let's try to continue on
- // however, it's possible we could find a later match
- // so keep a reference in case we have to backtrack
- lastWildcardNamespace = namespaceIndex;
- namespaceIndex++;
- patternIndex++;
- continue;
- }
- else if (pattern[patternIndex] === namespace[namespaceIndex]) {
- // simple case: literal pattern matches so keep going
- patternIndex++;
- namespaceIndex++;
- }
- else if (lastWildcard >= 0) {
- // special case: we don't have a literal match, but there is a previous wildcard
- // which we can backtrack to and try having the wildcard eat the match instead
- patternIndex = lastWildcard + 1;
- namespaceIndex = lastWildcardNamespace + 1;
- // we've reached the end of the namespace without a match
- if (namespaceIndex === namespaceLength) {
- return false;
- }
- // similar to the previous logic, let's keep going until we find the next literal match
- while (namespace[namespaceIndex] !== pattern[patternIndex]) {
- namespaceIndex++;
- if (namespaceIndex === namespaceLength) {
- return false;
- }
- }
- lastWildcardNamespace = namespaceIndex;
- namespaceIndex++;
- patternIndex++;
- continue;
- }
- else {
- return false;
- }
- }
- const namespaceDone = namespaceIndex === namespace.length;
- const patternDone = patternIndex === pattern.length;
- // this is to detect the case of an unneeded final wildcard
- // e.g. the pattern `ab*` should match the string `ab`
- const trailingWildCard = patternIndex === pattern.length - 1 && pattern[patternIndex] === "*";
- return namespaceDone && (patternDone || trailingWildCard);
-}
-function disable() {
- const result = enabledString || "";
- enable("");
- return result;
-}
-function createDebugger(namespace) {
- const newDebugger = Object.assign(debug, {
- enabled: enabled(namespace),
- destroy,
- log: debugObj.log,
- namespace,
- extend,
- });
- function debug(...args) {
- if (!newDebugger.enabled) {
- return;
- }
- if (args.length > 0) {
- args[0] = `${namespace} ${args[0]}`;
- }
- newDebugger.log(...args);
- }
- debuggers.push(newDebugger);
- return newDebugger;
-}
-function destroy() {
- const index = debuggers.indexOf(this);
- if (index >= 0) {
- debuggers.splice(index, 1);
- return true;
- }
- return false;
-}
-function extend(namespace) {
- const newDebugger = createDebugger(`${this.namespace}:${namespace}`);
- newDebugger.log = this.log;
- return newDebugger;
-}
-exports["default"] = debugObj;
-//# sourceMappingURL=debug.js.map
-
-/***/ }),
-
-/***/ 2490:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.createLoggerContext = void 0;
-var logger_js_1 = __nccwpck_require__(8459);
-Object.defineProperty(exports, "createLoggerContext", ({ enumerable: true, get: function () { return logger_js_1.createLoggerContext; } }));
-//# sourceMappingURL=internal.js.map
-
-/***/ }),
-
-/***/ 8029:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.log = log;
-const tslib_1 = __nccwpck_require__(1860);
-const node_os_1 = __nccwpck_require__(8161);
-const node_util_1 = tslib_1.__importDefault(__nccwpck_require__(7975));
-const node_process_1 = tslib_1.__importDefault(__nccwpck_require__(1708));
-function log(message, ...args) {
- node_process_1.default.stderr.write(`${node_util_1.default.format(message, ...args)}${node_os_1.EOL}`);
-}
-//# sourceMappingURL=log.js.map
-
-/***/ }),
-
-/***/ 8459:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.TypeSpecRuntimeLogger = void 0;
-exports.createLoggerContext = createLoggerContext;
-exports.setLogLevel = setLogLevel;
-exports.getLogLevel = getLogLevel;
-exports.createClientLogger = createClientLogger;
-const tslib_1 = __nccwpck_require__(1860);
-const debug_js_1 = tslib_1.__importDefault(__nccwpck_require__(6836));
-const TYPESPEC_RUNTIME_LOG_LEVELS = ["verbose", "info", "warning", "error"];
-const levelMap = {
- verbose: 400,
- info: 300,
- warning: 200,
- error: 100,
-};
-function patchLogMethod(parent, child) {
- child.log = (...args) => {
- parent.log(...args);
- };
-}
-function isTypeSpecRuntimeLogLevel(level) {
- return TYPESPEC_RUNTIME_LOG_LEVELS.includes(level);
-}
-/**
- * Creates a logger context base on the provided options.
- * @param options - The options for creating a logger context.
- * @returns The logger context.
- */
-function createLoggerContext(options) {
- const registeredLoggers = new Set();
- const logLevelFromEnv = (typeof process !== "undefined" && process.env && process.env[options.logLevelEnvVarName]) ||
- undefined;
- let logLevel;
- const clientLogger = (0, debug_js_1.default)(options.namespace);
- clientLogger.log = (...args) => {
- debug_js_1.default.log(...args);
- };
- function contextSetLogLevel(level) {
- if (level && !isTypeSpecRuntimeLogLevel(level)) {
- throw new Error(`Unknown log level '${level}'. Acceptable values: ${TYPESPEC_RUNTIME_LOG_LEVELS.join(",")}`);
- }
- logLevel = level;
- const enabledNamespaces = [];
- for (const logger of registeredLoggers) {
- if (shouldEnable(logger)) {
- enabledNamespaces.push(logger.namespace);
- }
- }
- debug_js_1.default.enable(enabledNamespaces.join(","));
- }
- if (logLevelFromEnv) {
- // avoid calling setLogLevel because we don't want a mis-set environment variable to crash
- if (isTypeSpecRuntimeLogLevel(logLevelFromEnv)) {
- contextSetLogLevel(logLevelFromEnv);
- }
- else {
- console.error(`${options.logLevelEnvVarName} set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${TYPESPEC_RUNTIME_LOG_LEVELS.join(", ")}.`);
- }
- }
- function shouldEnable(logger) {
- return Boolean(logLevel && levelMap[logger.level] <= levelMap[logLevel]);
- }
- function createLogger(parent, level) {
- const logger = Object.assign(parent.extend(level), {
- level,
- });
- patchLogMethod(parent, logger);
- if (shouldEnable(logger)) {
- const enabledNamespaces = debug_js_1.default.disable();
- debug_js_1.default.enable(enabledNamespaces + "," + logger.namespace);
- }
- registeredLoggers.add(logger);
- return logger;
- }
- function contextGetLogLevel() {
- return logLevel;
- }
- function contextCreateClientLogger(namespace) {
- const clientRootLogger = clientLogger.extend(namespace);
- patchLogMethod(clientLogger, clientRootLogger);
- return {
- error: createLogger(clientRootLogger, "error"),
- warning: createLogger(clientRootLogger, "warning"),
- info: createLogger(clientRootLogger, "info"),
- verbose: createLogger(clientRootLogger, "verbose"),
- };
- }
- return {
- setLogLevel: contextSetLogLevel,
- getLogLevel: contextGetLogLevel,
- createClientLogger: contextCreateClientLogger,
- logger: clientLogger,
- };
-}
-const context = createLoggerContext({
- logLevelEnvVarName: "TYPESPEC_RUNTIME_LOG_LEVEL",
- namespace: "typeSpecRuntime",
-});
-/**
- * Immediately enables logging at the specified log level. If no level is specified, logging is disabled.
- * @param level - The log level to enable for logging.
- * Options from most verbose to least verbose are:
- * - verbose
- * - info
- * - warning
- * - error
- */
-// eslint-disable-next-line @typescript-eslint/no-redeclare
-exports.TypeSpecRuntimeLogger = context.logger;
-/**
- * Retrieves the currently specified log level.
- */
-function setLogLevel(logLevel) {
- context.setLogLevel(logLevel);
-}
-/**
- * Retrieves the currently specified log level.
- */
-function getLogLevel() {
- return context.getLogLevel();
-}
-/**
- * Creates a logger for use by the SDKs that inherits from `TypeSpecRuntimeLogger`.
- * @param namespace - The name of the SDK package.
- * @hidden
- */
-function createClientLogger(namespace) {
- return context.createClientLogger(namespace);
-}
-//# sourceMappingURL=logger.js.map
-
-/***/ }),
-
-/***/ 2921:
-/***/ ((__unused_webpack_module, exports) => {
-
-
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.uint8ArrayToString = uint8ArrayToString;
-exports.stringToUint8Array = stringToUint8Array;
-/**
- * The helper that transforms bytes with specific character encoding into string
- * @param bytes - the uint8array bytes
- * @param format - the format we use to encode the byte
- * @returns a string of the encoded string
- */
-function uint8ArrayToString(bytes, format) {
- return Buffer.from(bytes).toString(format);
-}
-/**
- * The helper that transforms string to specific character encoded bytes array.
- * @param value - the string to be converted
- * @param format - the format we use to decode the value
- * @returns a uint8array
- */
-function stringToUint8Array(value, format) {
- return Buffer.from(value, format);
-}
-//# sourceMappingURL=bytesEncoding.js.map
-
-/***/ }),
-
-/***/ 5086:
-/***/ ((__unused_webpack_module, exports) => {
-
-
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.isReactNative = exports.isNodeRuntime = exports.isNodeLike = exports.isBun = exports.isDeno = exports.isWebWorker = exports.isBrowser = void 0;
-/**
- * A constant that indicates whether the environment the code is running is a Web Browser.
- */
-// eslint-disable-next-line @azure/azure-sdk/ts-no-window
-exports.isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined";
-/**
- * A constant that indicates whether the environment the code is running is a Web Worker.
- */
-exports.isWebWorker = typeof self === "object" &&
- typeof self?.importScripts === "function" &&
- (self.constructor?.name === "DedicatedWorkerGlobalScope" ||
- self.constructor?.name === "ServiceWorkerGlobalScope" ||
- self.constructor?.name === "SharedWorkerGlobalScope");
-/**
- * A constant that indicates whether the environment the code is running is Deno.
- */
-exports.isDeno = typeof Deno !== "undefined" &&
- typeof Deno.version !== "undefined" &&
- typeof Deno.version.deno !== "undefined";
-/**
- * A constant that indicates whether the environment the code is running is Bun.sh.
- */
-exports.isBun = typeof Bun !== "undefined" && typeof Bun.version !== "undefined";
-/**
- * A constant that indicates whether the environment the code is running is a Node.js compatible environment.
- */
-exports.isNodeLike = typeof globalThis.process !== "undefined" &&
- Boolean(globalThis.process.version) &&
- Boolean(globalThis.process.versions?.node);
-/**
- * A constant that indicates whether the environment the code is running is Node.JS.
- */
-exports.isNodeRuntime = exports.isNodeLike && !exports.isBun && !exports.isDeno;
-/**
- * A constant that indicates whether the environment the code is running is in React-Native.
- */
-// https://github.com/facebook/react-native/blob/main/packages/react-native/Libraries/Core/setUpNavigator.js
-exports.isReactNative = typeof navigator !== "undefined" && navigator?.product === "ReactNative";
-//# sourceMappingURL=checkEnvironment.js.map
-
-/***/ }),
-
-/***/ 6776:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.calculateRetryDelay = calculateRetryDelay;
-const random_js_1 = __nccwpck_require__(8640);
-/**
- * Calculates the delay interval for retry attempts using exponential delay with jitter.
- * @param retryAttempt - The current retry attempt number.
- * @param config - The exponential retry configuration.
- * @returns An object containing the calculated retry delay.
- */
-function calculateRetryDelay(retryAttempt, config) {
- // Exponentially increase the delay each time
- const exponentialDelay = config.retryDelayInMs * Math.pow(2, retryAttempt);
- // Don't let the delay exceed the maximum
- const clampedDelay = Math.min(config.maxRetryDelayInMs, exponentialDelay);
- // Allow the final value to have some "jitter" (within 50% of the delay size) so
- // that retries across multiple clients don't occur simultaneously.
- const retryAfterInMs = clampedDelay / 2 + (0, random_js_1.getRandomIntegerInclusive)(0, clampedDelay / 2);
- return { retryAfterInMs };
-}
-//# sourceMappingURL=delay.js.map
-
-/***/ }),
-
-/***/ 2573:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.isError = isError;
-const object_js_1 = __nccwpck_require__(3632);
-/**
- * Typeguard for an error object shape (has name and message)
- * @param e - Something caught by a catch clause.
- */
-function isError(e) {
- if ((0, object_js_1.isObject)(e)) {
- const hasName = typeof e.name === "string";
- const hasMessage = typeof e.message === "string";
- return hasName && hasMessage;
- }
- return false;
-}
-//# sourceMappingURL=error.js.map
-
-/***/ }),
-
-/***/ 5750:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.Sanitizer = exports.uint8ArrayToString = exports.stringToUint8Array = exports.isWebWorker = exports.isReactNative = exports.isDeno = exports.isNodeRuntime = exports.isNodeLike = exports.isBun = exports.isBrowser = exports.randomUUID = exports.computeSha256Hmac = exports.computeSha256Hash = exports.isError = exports.isObject = exports.getRandomIntegerInclusive = exports.calculateRetryDelay = void 0;
-var delay_js_1 = __nccwpck_require__(6776);
-Object.defineProperty(exports, "calculateRetryDelay", ({ enumerable: true, get: function () { return delay_js_1.calculateRetryDelay; } }));
-var random_js_1 = __nccwpck_require__(8640);
-Object.defineProperty(exports, "getRandomIntegerInclusive", ({ enumerable: true, get: function () { return random_js_1.getRandomIntegerInclusive; } }));
-var object_js_1 = __nccwpck_require__(3632);
-Object.defineProperty(exports, "isObject", ({ enumerable: true, get: function () { return object_js_1.isObject; } }));
-var error_js_1 = __nccwpck_require__(2573);
-Object.defineProperty(exports, "isError", ({ enumerable: true, get: function () { return error_js_1.isError; } }));
-var sha256_js_1 = __nccwpck_require__(2016);
-Object.defineProperty(exports, "computeSha256Hash", ({ enumerable: true, get: function () { return sha256_js_1.computeSha256Hash; } }));
-Object.defineProperty(exports, "computeSha256Hmac", ({ enumerable: true, get: function () { return sha256_js_1.computeSha256Hmac; } }));
-var uuidUtils_js_1 = __nccwpck_require__(5023);
-Object.defineProperty(exports, "randomUUID", ({ enumerable: true, get: function () { return uuidUtils_js_1.randomUUID; } }));
-var checkEnvironment_js_1 = __nccwpck_require__(5086);
-Object.defineProperty(exports, "isBrowser", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isBrowser; } }));
-Object.defineProperty(exports, "isBun", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isBun; } }));
-Object.defineProperty(exports, "isNodeLike", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isNodeLike; } }));
-Object.defineProperty(exports, "isNodeRuntime", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isNodeRuntime; } }));
-Object.defineProperty(exports, "isDeno", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isDeno; } }));
-Object.defineProperty(exports, "isReactNative", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isReactNative; } }));
-Object.defineProperty(exports, "isWebWorker", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isWebWorker; } }));
-var bytesEncoding_js_1 = __nccwpck_require__(2921);
-Object.defineProperty(exports, "stringToUint8Array", ({ enumerable: true, get: function () { return bytesEncoding_js_1.stringToUint8Array; } }));
-Object.defineProperty(exports, "uint8ArrayToString", ({ enumerable: true, get: function () { return bytesEncoding_js_1.uint8ArrayToString; } }));
-var sanitizer_js_1 = __nccwpck_require__(7784);
-Object.defineProperty(exports, "Sanitizer", ({ enumerable: true, get: function () { return sanitizer_js_1.Sanitizer; } }));
-//# sourceMappingURL=internal.js.map
-
-/***/ }),
-
-/***/ 3632:
-/***/ ((__unused_webpack_module, exports) => {
-
-
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.isObject = isObject;
-/**
- * Helper to determine when an input is a generic JS object.
- * @returns true when input is an object type that is not null, Array, RegExp, or Date.
- */
-function isObject(input) {
- return (typeof input === "object" &&
- input !== null &&
- !Array.isArray(input) &&
- !(input instanceof RegExp) &&
- !(input instanceof Date));
-}
-//# sourceMappingURL=object.js.map
-
-/***/ }),
-
-/***/ 8640:
-/***/ ((__unused_webpack_module, exports) => {
-
-
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.getRandomIntegerInclusive = getRandomIntegerInclusive;
-/**
- * Returns a random integer value between a lower and upper bound,
- * inclusive of both bounds.
- * Note that this uses Math.random and isn't secure. If you need to use
- * this for any kind of security purpose, find a better source of random.
- * @param min - The smallest integer value allowed.
- * @param max - The largest integer value allowed.
- */
-function getRandomIntegerInclusive(min, max) {
- // Make sure inputs are integers.
- min = Math.ceil(min);
- max = Math.floor(max);
- // Pick a random offset from zero to the size of the range.
- // Since Math.random() can never return 1, we have to make the range one larger
- // in order to be inclusive of the maximum value after we take the floor.
- const offset = Math.floor(Math.random() * (max - min + 1));
- return offset + min;
-}
-//# sourceMappingURL=random.js.map
-
-/***/ }),
-
-/***/ 7784:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.Sanitizer = void 0;
-const object_js_1 = __nccwpck_require__(3632);
-const RedactedString = "REDACTED";
-// Make sure this list is up-to-date with the one under core/logger/Readme#Keyconcepts
-const defaultAllowedHeaderNames = [
- "x-ms-client-request-id",
- "x-ms-return-client-request-id",
- "x-ms-useragent",
- "x-ms-correlation-request-id",
- "x-ms-request-id",
- "client-request-id",
- "ms-cv",
- "return-client-request-id",
- "traceparent",
- "Access-Control-Allow-Credentials",
- "Access-Control-Allow-Headers",
- "Access-Control-Allow-Methods",
- "Access-Control-Allow-Origin",
- "Access-Control-Expose-Headers",
- "Access-Control-Max-Age",
- "Access-Control-Request-Headers",
- "Access-Control-Request-Method",
- "Origin",
- "Accept",
- "Accept-Encoding",
- "Cache-Control",
- "Connection",
- "Content-Length",
- "Content-Type",
- "Date",
- "ETag",
- "Expires",
- "If-Match",
- "If-Modified-Since",
- "If-None-Match",
- "If-Unmodified-Since",
- "Last-Modified",
- "Pragma",
- "Request-Id",
- "Retry-After",
- "Server",
- "Transfer-Encoding",
- "User-Agent",
- "WWW-Authenticate",
-];
-const defaultAllowedQueryParameters = ["api-version"];
-/**
- * A utility class to sanitize objects for logging.
- */
-class Sanitizer {
- allowedHeaderNames;
- allowedQueryParameters;
- constructor({ additionalAllowedHeaderNames: allowedHeaderNames = [], additionalAllowedQueryParameters: allowedQueryParameters = [], } = {}) {
- allowedHeaderNames = defaultAllowedHeaderNames.concat(allowedHeaderNames);
- allowedQueryParameters = defaultAllowedQueryParameters.concat(allowedQueryParameters);
- this.allowedHeaderNames = new Set(allowedHeaderNames.map((n) => n.toLowerCase()));
- this.allowedQueryParameters = new Set(allowedQueryParameters.map((p) => p.toLowerCase()));
- }
- /**
- * Sanitizes an object for logging.
- * @param obj - The object to sanitize
- * @returns - The sanitized object as a string
- */
- sanitize(obj) {
- const seen = new Set();
- return JSON.stringify(obj, (key, value) => {
- // Ensure Errors include their interesting non-enumerable members
- if (value instanceof Error) {
- return {
- ...value,
- name: value.name,
- message: value.message,
- };
- }
- if (key === "headers") {
- return this.sanitizeHeaders(value);
- }
- else if (key === "url") {
- return this.sanitizeUrl(value);
- }
- else if (key === "query") {
- return this.sanitizeQuery(value);
- }
- else if (key === "body") {
- // Don't log the request body
- return undefined;
- }
- else if (key === "response") {
- // Don't log response again
- return undefined;
- }
- else if (key === "operationSpec") {
- // When using sendOperationRequest, the request carries a massive
- // field with the autorest spec. No need to log it.
- return undefined;
- }
- else if (Array.isArray(value) || (0, object_js_1.isObject)(value)) {
- if (seen.has(value)) {
- return "[Circular]";
- }
- seen.add(value);
- }
- return value;
- }, 2);
- }
- /**
- * Sanitizes a URL for logging.
- * @param value - The URL to sanitize
- * @returns - The sanitized URL as a string
- */
- sanitizeUrl(value) {
- if (typeof value !== "string" || value === null || value === "") {
- return value;
- }
- const url = new URL(value);
- if (!url.search) {
- return value;
- }
- for (const [key] of url.searchParams) {
- if (!this.allowedQueryParameters.has(key.toLowerCase())) {
- url.searchParams.set(key, RedactedString);
- }
- }
- return url.toString();
- }
- sanitizeHeaders(obj) {
- const sanitized = {};
- for (const key of Object.keys(obj)) {
- if (this.allowedHeaderNames.has(key.toLowerCase())) {
- sanitized[key] = obj[key];
- }
- else {
- sanitized[key] = RedactedString;
- }
- }
- return sanitized;
- }
- sanitizeQuery(value) {
- if (typeof value !== "object" || value === null) {
- return value;
- }
- const sanitized = {};
- for (const k of Object.keys(value)) {
- if (this.allowedQueryParameters.has(k.toLowerCase())) {
- sanitized[k] = value[k];
- }
- else {
- sanitized[k] = RedactedString;
- }
- }
- return sanitized;
- }
-}
-exports.Sanitizer = Sanitizer;
-//# sourceMappingURL=sanitizer.js.map
-
-/***/ }),
-
-/***/ 2016:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.computeSha256Hmac = computeSha256Hmac;
-exports.computeSha256Hash = computeSha256Hash;
-const node_crypto_1 = __nccwpck_require__(7598);
-/**
- * Generates a SHA-256 HMAC signature.
- * @param key - The HMAC key represented as a base64 string, used to generate the cryptographic HMAC hash.
- * @param stringToSign - The data to be signed.
- * @param encoding - The textual encoding to use for the returned HMAC digest.
- */
-async function computeSha256Hmac(key, stringToSign, encoding) {
- const decodedKey = Buffer.from(key, "base64");
- return (0, node_crypto_1.createHmac)("sha256", decodedKey).update(stringToSign).digest(encoding);
-}
-/**
- * Generates a SHA-256 hash.
- * @param content - The data to be included in the hash.
- * @param encoding - The textual encoding to use for the returned hash.
- */
-async function computeSha256Hash(content, encoding) {
- return (0, node_crypto_1.createHash)("sha256").update(content).digest(encoding);
-}
-//# sourceMappingURL=sha256.js.map
-
-/***/ }),
-
-/***/ 5023:
-/***/ ((__unused_webpack_module, exports) => {
-
-
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.randomUUID = randomUUID;
-/**
- * Generated Universally Unique Identifier
- *
- * @returns RFC4122 v4 UUID.
- */
-function randomUUID() {
- return crypto.randomUUID();
-}
-//# sourceMappingURL=uuidUtils.js.map
-
-/***/ }),
-
-/***/ 1120:
-/***/ ((module) => {
-
-var __webpack_unused_export__;
-
-
-const NullObject = function NullObject () { }
-NullObject.prototype = Object.create(null)
-
-/**
- * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1
- *
- * parameter = token "=" ( token / quoted-string )
- * token = 1*tchar
- * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
- * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
- * / DIGIT / ALPHA
- * ; any VCHAR, except delimiters
- * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE
- * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text
- * obs-text = %x80-FF
- * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text )
- */
-const paramRE = /; *([!#$%&'*+.^\w`|~-]+)=("(?:[\v\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\v\u0020-\u00ff])*"|[!#$%&'*+.^\w`|~-]+) */gu
-
-/**
- * RegExp to match quoted-pair in RFC 7230 sec 3.2.6
- *
- * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text )
- * obs-text = %x80-FF
- */
-const quotedPairRE = /\\([\v\u0020-\u00ff])/gu
-
-/**
- * RegExp to match type in RFC 7231 sec 3.1.1.1
- *
- * media-type = type "/" subtype
- * type = token
- * subtype = token
- */
-const mediaTypeRE = /^[!#$%&'*+.^\w|~-]+\/[!#$%&'*+.^\w|~-]+$/u
-
-// default ContentType to prevent repeated object creation
-const defaultContentType = { type: '', parameters: new NullObject() }
-Object.freeze(defaultContentType.parameters)
-Object.freeze(defaultContentType)
-
-/**
- * Parse media type to object.
- *
- * @param {string|object} header
- * @return {Object}
- * @public
- */
-
-function parse (header) {
- if (typeof header !== 'string') {
- throw new TypeError('argument header is required and must be a string')
- }
-
- let index = header.indexOf(';')
- const type = index !== -1
- ? header.slice(0, index).trim()
- : header.trim()
-
- if (mediaTypeRE.test(type) === false) {
- throw new TypeError('invalid media type')
- }
-
- const result = {
- type: type.toLowerCase(),
- parameters: new NullObject()
- }
-
- // parse parameters
- if (index === -1) {
- return result
- }
-
- let key
- let match
- let value
-
- paramRE.lastIndex = index
-
- while ((match = paramRE.exec(header))) {
- if (match.index !== index) {
- throw new TypeError('invalid parameter format')
- }
-
- index += match[0].length
- key = match[1].toLowerCase()
- value = match[2]
-
- if (value[0] === '"') {
- // remove quotes and escapes
- value = value
- .slice(1, value.length - 1)
-
- quotedPairRE.test(value) && (value = value.replace(quotedPairRE, '$1'))
- }
-
- result.parameters[key] = value
- }
-
- if (index !== header.length) {
- throw new TypeError('invalid parameter format')
- }
-
- return result
-}
-
-function safeParse (header) {
- if (typeof header !== 'string') {
- return defaultContentType
- }
-
- let index = header.indexOf(';')
- const type = index !== -1
- ? header.slice(0, index).trim()
- : header.trim()
-
- if (mediaTypeRE.test(type) === false) {
- return defaultContentType
- }
-
- const result = {
- type: type.toLowerCase(),
- parameters: new NullObject()
- }
-
- // parse parameters
- if (index === -1) {
- return result
- }
-
- let key
- let match
- let value
-
- paramRE.lastIndex = index
-
- while ((match = paramRE.exec(header))) {
- if (match.index !== index) {
- return defaultContentType
- }
-
- index += match[0].length
- key = match[1].toLowerCase()
- value = match[2]
-
- if (value[0] === '"') {
- // remove quotes and escapes
- value = value
- .slice(1, value.length - 1)
-
- quotedPairRE.test(value) && (value = value.replace(quotedPairRE, '$1'))
- }
-
- result.parameters[key] = value
- }
-
- if (index !== header.length) {
- return defaultContentType
- }
-
- return result
-}
-
-__webpack_unused_export__ = { parse, safeParse }
-__webpack_unused_export__ = parse
-module.exports.xL = safeParse
-__webpack_unused_export__ = defaultContentType
-
-
-/***/ }),
-
-/***/ 7349:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var identity = __nccwpck_require__(1127);
-var Scalar = __nccwpck_require__(3301);
-var YAMLMap = __nccwpck_require__(4454);
-var YAMLSeq = __nccwpck_require__(2223);
-var resolveBlockMap = __nccwpck_require__(7103);
-var resolveBlockSeq = __nccwpck_require__(334);
-var resolveFlowCollection = __nccwpck_require__(3142);
-
-function resolveCollection(CN, ctx, token, onError, tagName, tag) {
- const coll = token.type === 'block-map'
- ? resolveBlockMap.resolveBlockMap(CN, ctx, token, onError, tag)
- : token.type === 'block-seq'
- ? resolveBlockSeq.resolveBlockSeq(CN, ctx, token, onError, tag)
- : resolveFlowCollection.resolveFlowCollection(CN, ctx, token, onError, tag);
- const Coll = coll.constructor;
- // If we got a tagName matching the class, or the tag name is '!',
- // then use the tagName from the node class used to create it.
- if (tagName === '!' || tagName === Coll.tagName) {
- coll.tag = Coll.tagName;
- return coll;
- }
- if (tagName)
- coll.tag = tagName;
- return coll;
-}
-function composeCollection(CN, ctx, token, props, onError) {
- const tagToken = props.tag;
- const tagName = !tagToken
- ? null
- : ctx.directives.tagName(tagToken.source, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg));
- if (token.type === 'block-seq') {
- const { anchor, newlineAfterProp: nl } = props;
- const lastProp = anchor && tagToken
- ? anchor.offset > tagToken.offset
- ? anchor
- : tagToken
- : (anchor ?? tagToken);
- if (lastProp && (!nl || nl.offset < lastProp.offset)) {
- const message = 'Missing newline after block sequence props';
- onError(lastProp, 'MISSING_CHAR', message);
- }
- }
- const expType = token.type === 'block-map'
- ? 'map'
- : token.type === 'block-seq'
- ? 'seq'
- : token.start.source === '{'
- ? 'map'
- : 'seq';
- // shortcut: check if it's a generic YAMLMap or YAMLSeq
- // before jumping into the custom tag logic.
- if (!tagToken ||
- !tagName ||
- tagName === '!' ||
- (tagName === YAMLMap.YAMLMap.tagName && expType === 'map') ||
- (tagName === YAMLSeq.YAMLSeq.tagName && expType === 'seq')) {
- return resolveCollection(CN, ctx, token, onError, tagName);
- }
- let tag = ctx.schema.tags.find(t => t.tag === tagName && t.collection === expType);
- if (!tag) {
- const kt = ctx.schema.knownTags[tagName];
- if (kt?.collection === expType) {
- ctx.schema.tags.push(Object.assign({}, kt, { default: false }));
- tag = kt;
- }
- else {
- if (kt) {
- onError(tagToken, 'BAD_COLLECTION_TYPE', `${kt.tag} used for ${expType} collection, but expects ${kt.collection ?? 'scalar'}`, true);
- }
- else {
- onError(tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, true);
- }
- return resolveCollection(CN, ctx, token, onError, tagName);
- }
- }
- const coll = resolveCollection(CN, ctx, token, onError, tagName, tag);
- const res = tag.resolve?.(coll, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg), ctx.options) ?? coll;
- const node = identity.isNode(res)
- ? res
- : new Scalar.Scalar(res);
- node.range = coll.range;
- node.tag = tagName;
- if (tag?.format)
- node.format = tag.format;
- return node;
-}
-
-exports.composeCollection = composeCollection;
-
-
-/***/ }),
-
-/***/ 3683:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var Document = __nccwpck_require__(3021);
-var composeNode = __nccwpck_require__(5937);
-var resolveEnd = __nccwpck_require__(7788);
-var resolveProps = __nccwpck_require__(4631);
-
-function composeDoc(options, directives, { offset, start, value, end }, onError) {
- const opts = Object.assign({ _directives: directives }, options);
- const doc = new Document.Document(undefined, opts);
- const ctx = {
- atKey: false,
- atRoot: true,
- directives: doc.directives,
- options: doc.options,
- schema: doc.schema
- };
- const props = resolveProps.resolveProps(start, {
- indicator: 'doc-start',
- next: value ?? end?.[0],
- offset,
- onError,
- parentIndent: 0,
- startOnNewline: true
- });
- if (props.found) {
- doc.directives.docStart = true;
- if (value &&
- (value.type === 'block-map' || value.type === 'block-seq') &&
- !props.hasNewline)
- onError(props.end, 'MISSING_CHAR', 'Block collection cannot start on same line with directives-end marker');
- }
- // @ts-expect-error If Contents is set, let's trust the user
- doc.contents = value
- ? composeNode.composeNode(ctx, value, props, onError)
- : composeNode.composeEmptyNode(ctx, props.end, start, null, props, onError);
- const contentEnd = doc.contents.range[2];
- const re = resolveEnd.resolveEnd(end, contentEnd, false, onError);
- if (re.comment)
- doc.comment = re.comment;
- doc.range = [offset, contentEnd, re.offset];
- return doc;
-}
-
-exports.composeDoc = composeDoc;
-
-
-/***/ }),
-
-/***/ 5937:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var Alias = __nccwpck_require__(4065);
-var identity = __nccwpck_require__(1127);
-var composeCollection = __nccwpck_require__(7349);
-var composeScalar = __nccwpck_require__(7794);
-var resolveEnd = __nccwpck_require__(7788);
-var utilEmptyScalarPosition = __nccwpck_require__(2599);
-
-const CN = { composeNode, composeEmptyNode };
-function composeNode(ctx, token, props, onError) {
- const atKey = ctx.atKey;
- const { spaceBefore, comment, anchor, tag } = props;
- let node;
- let isSrcToken = true;
- switch (token.type) {
- case 'alias':
- node = composeAlias(ctx, token, onError);
- if (anchor || tag)
- onError(token, 'ALIAS_PROPS', 'An alias node must not specify any properties');
- break;
- case 'scalar':
- case 'single-quoted-scalar':
- case 'double-quoted-scalar':
- case 'block-scalar':
- node = composeScalar.composeScalar(ctx, token, tag, onError);
- if (anchor)
- node.anchor = anchor.source.substring(1);
- break;
- case 'block-map':
- case 'block-seq':
- case 'flow-collection':
- try {
- node = composeCollection.composeCollection(CN, ctx, token, props, onError);
- if (anchor)
- node.anchor = anchor.source.substring(1);
- }
- catch (error) {
- // Almost certainly here due to a stack overflow
- const message = error instanceof Error ? error.message : String(error);
- onError(token, 'RESOURCE_EXHAUSTION', message);
- }
- break;
- default: {
- const message = token.type === 'error'
- ? token.message
- : `Unsupported token (type: ${token.type})`;
- onError(token, 'UNEXPECTED_TOKEN', message);
- isSrcToken = false;
- }
- }
- node ?? (node = composeEmptyNode(ctx, token.offset, undefined, null, props, onError));
- if (anchor && node.anchor === '')
- onError(anchor, 'BAD_ALIAS', 'Anchor cannot be an empty string');
- if (atKey &&
- ctx.options.stringKeys &&
- (!identity.isScalar(node) ||
- typeof node.value !== 'string' ||
- (node.tag && node.tag !== 'tag:yaml.org,2002:str'))) {
- const msg = 'With stringKeys, all keys must be strings';
- onError(tag ?? token, 'NON_STRING_KEY', msg);
- }
- if (spaceBefore)
- node.spaceBefore = true;
- if (comment) {
- if (token.type === 'scalar' && token.source === '')
- node.comment = comment;
- else
- node.commentBefore = comment;
- }
- // @ts-expect-error Type checking misses meaning of isSrcToken
- if (ctx.options.keepSourceTokens && isSrcToken)
- node.srcToken = token;
- return node;
-}
-function composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError) {
- const token = {
- type: 'scalar',
- offset: utilEmptyScalarPosition.emptyScalarPosition(offset, before, pos),
- indent: -1,
- source: ''
- };
- const node = composeScalar.composeScalar(ctx, token, tag, onError);
- if (anchor) {
- node.anchor = anchor.source.substring(1);
- if (node.anchor === '')
- onError(anchor, 'BAD_ALIAS', 'Anchor cannot be an empty string');
- }
- if (spaceBefore)
- node.spaceBefore = true;
- if (comment) {
- node.comment = comment;
- node.range[2] = end;
- }
- return node;
-}
-function composeAlias({ options }, { offset, source, end }, onError) {
- const alias = new Alias.Alias(source.substring(1));
- if (alias.source === '')
- onError(offset, 'BAD_ALIAS', 'Alias cannot be an empty string');
- if (alias.source.endsWith(':'))
- onError(offset + source.length - 1, 'BAD_ALIAS', 'Alias ending in : is ambiguous', true);
- const valueEnd = offset + source.length;
- const re = resolveEnd.resolveEnd(end, valueEnd, options.strict, onError);
- alias.range = [offset, valueEnd, re.offset];
- if (re.comment)
- alias.comment = re.comment;
- return alias;
-}
-
-exports.composeEmptyNode = composeEmptyNode;
-exports.composeNode = composeNode;
-
-
-/***/ }),
-
-/***/ 7794:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var identity = __nccwpck_require__(1127);
-var Scalar = __nccwpck_require__(3301);
-var resolveBlockScalar = __nccwpck_require__(8913);
-var resolveFlowScalar = __nccwpck_require__(6842);
-
-function composeScalar(ctx, token, tagToken, onError) {
- const { value, type, comment, range } = token.type === 'block-scalar'
- ? resolveBlockScalar.resolveBlockScalar(ctx, token, onError)
- : resolveFlowScalar.resolveFlowScalar(token, ctx.options.strict, onError);
- const tagName = tagToken
- ? ctx.directives.tagName(tagToken.source, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg))
- : null;
- let tag;
- if (ctx.options.stringKeys && ctx.atKey) {
- tag = ctx.schema[identity.SCALAR];
- }
- else if (tagName)
- tag = findScalarTagByName(ctx.schema, value, tagName, tagToken, onError);
- else if (token.type === 'scalar')
- tag = findScalarTagByTest(ctx, value, token, onError);
- else
- tag = ctx.schema[identity.SCALAR];
- let scalar;
- try {
- const res = tag.resolve(value, msg => onError(tagToken ?? token, 'TAG_RESOLVE_FAILED', msg), ctx.options);
- scalar = identity.isScalar(res) ? res : new Scalar.Scalar(res);
- }
- catch (error) {
- const msg = error instanceof Error ? error.message : String(error);
- onError(tagToken ?? token, 'TAG_RESOLVE_FAILED', msg);
- scalar = new Scalar.Scalar(value);
- }
- scalar.range = range;
- scalar.source = value;
- if (type)
- scalar.type = type;
- if (tagName)
- scalar.tag = tagName;
- if (tag.format)
- scalar.format = tag.format;
- if (comment)
- scalar.comment = comment;
- return scalar;
-}
-function findScalarTagByName(schema, value, tagName, tagToken, onError) {
- if (tagName === '!')
- return schema[identity.SCALAR]; // non-specific tag
- const matchWithTest = [];
- for (const tag of schema.tags) {
- if (!tag.collection && tag.tag === tagName) {
- if (tag.default && tag.test)
- matchWithTest.push(tag);
- else
- return tag;
- }
- }
- for (const tag of matchWithTest)
- if (tag.test?.test(value))
- return tag;
- const kt = schema.knownTags[tagName];
- if (kt && !kt.collection) {
- // Ensure that the known tag is available for stringifying,
- // but does not get used by default.
- schema.tags.push(Object.assign({}, kt, { default: false, test: undefined }));
- return kt;
- }
- onError(tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, tagName !== 'tag:yaml.org,2002:str');
- return schema[identity.SCALAR];
-}
-function findScalarTagByTest({ atKey, directives, schema }, value, token, onError) {
- const tag = schema.tags.find(tag => (tag.default === true || (atKey && tag.default === 'key')) &&
- tag.test?.test(value)) || schema[identity.SCALAR];
- if (schema.compat) {
- const compat = schema.compat.find(tag => tag.default && tag.test?.test(value)) ??
- schema[identity.SCALAR];
- if (tag.tag !== compat.tag) {
- const ts = directives.tagString(tag.tag);
- const cs = directives.tagString(compat.tag);
- const msg = `Value may be parsed as either ${ts} or ${cs}`;
- onError(token, 'TAG_RESOLVE_FAILED', msg, true);
- }
- }
- return tag;
-}
-
-exports.composeScalar = composeScalar;
-
-
-/***/ }),
-
-/***/ 9984:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var node_process = __nccwpck_require__(932);
-var directives = __nccwpck_require__(1342);
-var Document = __nccwpck_require__(3021);
-var errors = __nccwpck_require__(1464);
-var identity = __nccwpck_require__(1127);
-var composeDoc = __nccwpck_require__(3683);
-var resolveEnd = __nccwpck_require__(7788);
-
-function getErrorPos(src) {
- if (typeof src === 'number')
- return [src, src + 1];
- if (Array.isArray(src))
- return src.length === 2 ? src : [src[0], src[1]];
- const { offset, source } = src;
- return [offset, offset + (typeof source === 'string' ? source.length : 1)];
-}
-function parsePrelude(prelude) {
- let comment = '';
- let atComment = false;
- let afterEmptyLine = false;
- for (let i = 0; i < prelude.length; ++i) {
- const source = prelude[i];
- switch (source[0]) {
- case '#':
- comment +=
- (comment === '' ? '' : afterEmptyLine ? '\n\n' : '\n') +
- (source.substring(1) || ' ');
- atComment = true;
- afterEmptyLine = false;
- break;
- case '%':
- if (prelude[i + 1]?.[0] !== '#')
- i += 1;
- atComment = false;
- break;
- default:
- // This may be wrong after doc-end, but in that case it doesn't matter
- if (!atComment)
- afterEmptyLine = true;
- atComment = false;
- }
- }
- return { comment, afterEmptyLine };
-}
-/**
- * Compose a stream of CST nodes into a stream of YAML Documents.
- *
- * ```ts
- * import { Composer, Parser } from 'yaml'
- *
- * const src: string = ...
- * const tokens = new Parser().parse(src)
- * const docs = new Composer().compose(tokens)
- * ```
- */
-class Composer {
- constructor(options = {}) {
- this.doc = null;
- this.atDirectives = false;
- this.prelude = [];
- this.errors = [];
- this.warnings = [];
- this.onError = (source, code, message, warning) => {
- const pos = getErrorPos(source);
- if (warning)
- this.warnings.push(new errors.YAMLWarning(pos, code, message));
- else
- this.errors.push(new errors.YAMLParseError(pos, code, message));
- };
- // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
- this.directives = new directives.Directives({ version: options.version || '1.2' });
- this.options = options;
- }
- decorate(doc, afterDoc) {
- const { comment, afterEmptyLine } = parsePrelude(this.prelude);
- //console.log({ dc: doc.comment, prelude, comment })
- if (comment) {
- const dc = doc.contents;
- if (afterDoc) {
- doc.comment = doc.comment ? `${doc.comment}\n${comment}` : comment;
- }
- else if (afterEmptyLine || doc.directives.docStart || !dc) {
- doc.commentBefore = comment;
- }
- else if (identity.isCollection(dc) && !dc.flow && dc.items.length > 0) {
- let it = dc.items[0];
- if (identity.isPair(it))
- it = it.key;
- const cb = it.commentBefore;
- it.commentBefore = cb ? `${comment}\n${cb}` : comment;
- }
- else {
- const cb = dc.commentBefore;
- dc.commentBefore = cb ? `${comment}\n${cb}` : comment;
- }
- }
- if (afterDoc) {
- Array.prototype.push.apply(doc.errors, this.errors);
- Array.prototype.push.apply(doc.warnings, this.warnings);
- }
- else {
- doc.errors = this.errors;
- doc.warnings = this.warnings;
- }
- this.prelude = [];
- this.errors = [];
- this.warnings = [];
- }
- /**
- * Current stream status information.
- *
- * Mostly useful at the end of input for an empty stream.
- */
- streamInfo() {
- return {
- comment: parsePrelude(this.prelude).comment,
- directives: this.directives,
- errors: this.errors,
- warnings: this.warnings
- };
- }
- /**
- * Compose tokens into documents.
- *
- * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.
- * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.
- */
- *compose(tokens, forceDoc = false, endOffset = -1) {
- for (const token of tokens)
- yield* this.next(token);
- yield* this.end(forceDoc, endOffset);
- }
- /** Advance the composer by one CST token. */
- *next(token) {
- if (node_process.env.LOG_STREAM)
- console.dir(token, { depth: null });
- switch (token.type) {
- case 'directive':
- this.directives.add(token.source, (offset, message, warning) => {
- const pos = getErrorPos(token);
- pos[0] += offset;
- this.onError(pos, 'BAD_DIRECTIVE', message, warning);
- });
- this.prelude.push(token.source);
- this.atDirectives = true;
- break;
- case 'document': {
- const doc = composeDoc.composeDoc(this.options, this.directives, token, this.onError);
- if (this.atDirectives && !doc.directives.docStart)
- this.onError(token, 'MISSING_CHAR', 'Missing directives-end/doc-start indicator line');
- this.decorate(doc, false);
- if (this.doc)
- yield this.doc;
- this.doc = doc;
- this.atDirectives = false;
- break;
- }
- case 'byte-order-mark':
- case 'space':
- break;
- case 'comment':
- case 'newline':
- this.prelude.push(token.source);
- break;
- case 'error': {
- const msg = token.source
- ? `${token.message}: ${JSON.stringify(token.source)}`
- : token.message;
- const error = new errors.YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', msg);
- if (this.atDirectives || !this.doc)
- this.errors.push(error);
- else
- this.doc.errors.push(error);
- break;
- }
- case 'doc-end': {
- if (!this.doc) {
- const msg = 'Unexpected doc-end without preceding document';
- this.errors.push(new errors.YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', msg));
- break;
- }
- this.doc.directives.docEnd = true;
- const end = resolveEnd.resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError);
- this.decorate(this.doc, true);
- if (end.comment) {
- const dc = this.doc.comment;
- this.doc.comment = dc ? `${dc}\n${end.comment}` : end.comment;
- }
- this.doc.range[2] = end.offset;
- break;
- }
- default:
- this.errors.push(new errors.YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', `Unsupported token ${token.type}`));
- }
- }
- /**
- * Call at end of input to yield any remaining document.
- *
- * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.
- * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.
- */
- *end(forceDoc = false, endOffset = -1) {
- if (this.doc) {
- this.decorate(this.doc, true);
- yield this.doc;
- this.doc = null;
- }
- else if (forceDoc) {
- const opts = Object.assign({ _directives: this.directives }, this.options);
- const doc = new Document.Document(undefined, opts);
- if (this.atDirectives)
- this.onError(endOffset, 'MISSING_CHAR', 'Missing directives-end indicator line');
- doc.range = [0, endOffset, endOffset];
- this.decorate(doc, false);
- yield doc;
- }
- }
-}
-
-exports.Composer = Composer;
-
-
-/***/ }),
-
-/***/ 7103:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var Pair = __nccwpck_require__(7165);
-var YAMLMap = __nccwpck_require__(4454);
-var resolveProps = __nccwpck_require__(4631);
-var utilContainsNewline = __nccwpck_require__(9499);
-var utilFlowIndentCheck = __nccwpck_require__(4051);
-var utilMapIncludes = __nccwpck_require__(1187);
-
-const startColMsg = 'All mapping items must start at the same column';
-function resolveBlockMap({ composeNode, composeEmptyNode }, ctx, bm, onError, tag) {
- const NodeClass = tag?.nodeClass ?? YAMLMap.YAMLMap;
- const map = new NodeClass(ctx.schema);
- if (ctx.atRoot)
- ctx.atRoot = false;
- let offset = bm.offset;
- let commentEnd = null;
- for (const collItem of bm.items) {
- const { start, key, sep, value } = collItem;
- // key properties
- const keyProps = resolveProps.resolveProps(start, {
- indicator: 'explicit-key-ind',
- next: key ?? sep?.[0],
- offset,
- onError,
- parentIndent: bm.indent,
- startOnNewline: true
- });
- const implicitKey = !keyProps.found;
- if (implicitKey) {
- if (key) {
- if (key.type === 'block-seq')
- onError(offset, 'BLOCK_AS_IMPLICIT_KEY', 'A block sequence may not be used as an implicit map key');
- else if ('indent' in key && key.indent !== bm.indent)
- onError(offset, 'BAD_INDENT', startColMsg);
- }
- if (!keyProps.anchor && !keyProps.tag && !sep) {
- commentEnd = keyProps.end;
- if (keyProps.comment) {
- if (map.comment)
- map.comment += '\n' + keyProps.comment;
- else
- map.comment = keyProps.comment;
- }
- continue;
- }
- if (keyProps.newlineAfterProp || utilContainsNewline.containsNewline(key)) {
- onError(key ?? start[start.length - 1], 'MULTILINE_IMPLICIT_KEY', 'Implicit keys need to be on a single line');
- }
- }
- else if (keyProps.found?.indent !== bm.indent) {
- onError(offset, 'BAD_INDENT', startColMsg);
- }
- // key value
- ctx.atKey = true;
- const keyStart = keyProps.end;
- const keyNode = key
- ? composeNode(ctx, key, keyProps, onError)
- : composeEmptyNode(ctx, keyStart, start, null, keyProps, onError);
- if (ctx.schema.compat)
- utilFlowIndentCheck.flowIndentCheck(bm.indent, key, onError);
- ctx.atKey = false;
- if (utilMapIncludes.mapIncludes(ctx, map.items, keyNode))
- onError(keyStart, 'DUPLICATE_KEY', 'Map keys must be unique');
- // value properties
- const valueProps = resolveProps.resolveProps(sep ?? [], {
- indicator: 'map-value-ind',
- next: value,
- offset: keyNode.range[2],
- onError,
- parentIndent: bm.indent,
- startOnNewline: !key || key.type === 'block-scalar'
- });
- offset = valueProps.end;
- if (valueProps.found) {
- if (implicitKey) {
- if (value?.type === 'block-map' && !valueProps.hasNewline)
- onError(offset, 'BLOCK_AS_IMPLICIT_KEY', 'Nested mappings are not allowed in compact mappings');
- if (ctx.options.strict &&
- keyProps.start < valueProps.found.offset - 1024)
- onError(keyNode.range, 'KEY_OVER_1024_CHARS', 'The : indicator must be at most 1024 chars after the start of an implicit block mapping key');
- }
- // value value
- const valueNode = value
- ? composeNode(ctx, value, valueProps, onError)
- : composeEmptyNode(ctx, offset, sep, null, valueProps, onError);
- if (ctx.schema.compat)
- utilFlowIndentCheck.flowIndentCheck(bm.indent, value, onError);
- offset = valueNode.range[2];
- const pair = new Pair.Pair(keyNode, valueNode);
- if (ctx.options.keepSourceTokens)
- pair.srcToken = collItem;
- map.items.push(pair);
- }
- else {
- // key with no value
- if (implicitKey)
- onError(keyNode.range, 'MISSING_CHAR', 'Implicit map keys need to be followed by map values');
- if (valueProps.comment) {
- if (keyNode.comment)
- keyNode.comment += '\n' + valueProps.comment;
- else
- keyNode.comment = valueProps.comment;
- }
- const pair = new Pair.Pair(keyNode);
- if (ctx.options.keepSourceTokens)
- pair.srcToken = collItem;
- map.items.push(pair);
- }
- }
- if (commentEnd && commentEnd < offset)
- onError(commentEnd, 'IMPOSSIBLE', 'Map comment with trailing content');
- map.range = [bm.offset, offset, commentEnd ?? offset];
- return map;
-}
-
-exports.resolveBlockMap = resolveBlockMap;
-
-
-/***/ }),
-
-/***/ 8913:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var Scalar = __nccwpck_require__(3301);
-
-function resolveBlockScalar(ctx, scalar, onError) {
- const start = scalar.offset;
- const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError);
- if (!header)
- return { value: '', type: null, comment: '', range: [start, start, start] };
- const type = header.mode === '>' ? Scalar.Scalar.BLOCK_FOLDED : Scalar.Scalar.BLOCK_LITERAL;
- const lines = scalar.source ? splitLines(scalar.source) : [];
- // determine the end of content & start of chomping
- let chompStart = lines.length;
- for (let i = lines.length - 1; i >= 0; --i) {
- const content = lines[i][1];
- if (content === '' || content === '\r')
- chompStart = i;
- else
- break;
- }
- // shortcut for empty contents
- if (chompStart === 0) {
- const value = header.chomp === '+' && lines.length > 0
- ? '\n'.repeat(Math.max(1, lines.length - 1))
- : '';
- let end = start + header.length;
- if (scalar.source)
- end += scalar.source.length;
- return { value, type, comment: header.comment, range: [start, end, end] };
- }
- // find the indentation level to trim from start
- let trimIndent = scalar.indent + header.indent;
- let offset = scalar.offset + header.length;
- let contentStart = 0;
- for (let i = 0; i < chompStart; ++i) {
- const [indent, content] = lines[i];
- if (content === '' || content === '\r') {
- if (header.indent === 0 && indent.length > trimIndent)
- trimIndent = indent.length;
- }
- else {
- if (indent.length < trimIndent) {
- const message = 'Block scalars with more-indented leading empty lines must use an explicit indentation indicator';
- onError(offset + indent.length, 'MISSING_CHAR', message);
- }
- if (header.indent === 0)
- trimIndent = indent.length;
- contentStart = i;
- if (trimIndent === 0 && !ctx.atRoot) {
- const message = 'Block scalar values in collections must be indented';
- onError(offset, 'BAD_INDENT', message);
- }
- break;
- }
- offset += indent.length + content.length + 1;
- }
- // include trailing more-indented empty lines in content
- for (let i = lines.length - 1; i >= chompStart; --i) {
- if (lines[i][0].length > trimIndent)
- chompStart = i + 1;
- }
- let value = '';
- let sep = '';
- let prevMoreIndented = false;
- // leading whitespace is kept intact
- for (let i = 0; i < contentStart; ++i)
- value += lines[i][0].slice(trimIndent) + '\n';
- for (let i = contentStart; i < chompStart; ++i) {
- let [indent, content] = lines[i];
- offset += indent.length + content.length + 1;
- const crlf = content[content.length - 1] === '\r';
- if (crlf)
- content = content.slice(0, -1);
- /* istanbul ignore if already caught in lexer */
- if (content && indent.length < trimIndent) {
- const src = header.indent
- ? 'explicit indentation indicator'
- : 'first line';
- const message = `Block scalar lines must not be less indented than their ${src}`;
- onError(offset - content.length - (crlf ? 2 : 1), 'BAD_INDENT', message);
- indent = '';
- }
- if (type === Scalar.Scalar.BLOCK_LITERAL) {
- value += sep + indent.slice(trimIndent) + content;
- sep = '\n';
- }
- else if (indent.length > trimIndent || content[0] === '\t') {
- // more-indented content within a folded block
- if (sep === ' ')
- sep = '\n';
- else if (!prevMoreIndented && sep === '\n')
- sep = '\n\n';
- value += sep + indent.slice(trimIndent) + content;
- sep = '\n';
- prevMoreIndented = true;
- }
- else if (content === '') {
- // empty line
- if (sep === '\n')
- value += '\n';
- else
- sep = '\n';
- }
- else {
- value += sep + content;
- sep = ' ';
- prevMoreIndented = false;
- }
- }
- switch (header.chomp) {
- case '-':
- break;
- case '+':
- for (let i = chompStart; i < lines.length; ++i)
- value += '\n' + lines[i][0].slice(trimIndent);
- if (value[value.length - 1] !== '\n')
- value += '\n';
- break;
- default:
- value += '\n';
- }
- const end = start + header.length + scalar.source.length;
- return { value, type, comment: header.comment, range: [start, end, end] };
-}
-function parseBlockScalarHeader({ offset, props }, strict, onError) {
- /* istanbul ignore if should not happen */
- if (props[0].type !== 'block-scalar-header') {
- onError(props[0], 'IMPOSSIBLE', 'Block scalar header not found');
- return null;
- }
- const { source } = props[0];
- const mode = source[0];
- let indent = 0;
- let chomp = '';
- let error = -1;
- for (let i = 1; i < source.length; ++i) {
- const ch = source[i];
- if (!chomp && (ch === '-' || ch === '+'))
- chomp = ch;
- else {
- const n = Number(ch);
- if (!indent && n)
- indent = n;
- else if (error === -1)
- error = offset + i;
- }
- }
- if (error !== -1)
- onError(error, 'UNEXPECTED_TOKEN', `Block scalar header includes extra characters: ${source}`);
- let hasSpace = false;
- let comment = '';
- let length = source.length;
- for (let i = 1; i < props.length; ++i) {
- const token = props[i];
- switch (token.type) {
- case 'space':
- hasSpace = true;
- // fallthrough
- case 'newline':
- length += token.source.length;
- break;
- case 'comment':
- if (strict && !hasSpace) {
- const message = 'Comments must be separated from other tokens by white space characters';
- onError(token, 'MISSING_CHAR', message);
- }
- length += token.source.length;
- comment = token.source.substring(1);
- break;
- case 'error':
- onError(token, 'UNEXPECTED_TOKEN', token.message);
- length += token.source.length;
- break;
- /* istanbul ignore next should not happen */
- default: {
- const message = `Unexpected token in block scalar header: ${token.type}`;
- onError(token, 'UNEXPECTED_TOKEN', message);
- const ts = token.source;
- if (ts && typeof ts === 'string')
- length += ts.length;
- }
- }
- }
- return { mode, indent, chomp, comment, length };
-}
-/** @returns Array of lines split up as `[indent, content]` */
-function splitLines(source) {
- const split = source.split(/\n( *)/);
- const first = split[0];
- const m = first.match(/^( *)/);
- const line0 = m?.[1]
- ? [m[1], first.slice(m[1].length)]
- : ['', first];
- const lines = [line0];
- for (let i = 1; i < split.length; i += 2)
- lines.push([split[i], split[i + 1]]);
- return lines;
-}
-
-exports.resolveBlockScalar = resolveBlockScalar;
-
-
-/***/ }),
-
-/***/ 334:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var YAMLSeq = __nccwpck_require__(2223);
-var resolveProps = __nccwpck_require__(4631);
-var utilFlowIndentCheck = __nccwpck_require__(4051);
-
-function resolveBlockSeq({ composeNode, composeEmptyNode }, ctx, bs, onError, tag) {
- const NodeClass = tag?.nodeClass ?? YAMLSeq.YAMLSeq;
- const seq = new NodeClass(ctx.schema);
- if (ctx.atRoot)
- ctx.atRoot = false;
- if (ctx.atKey)
- ctx.atKey = false;
- let offset = bs.offset;
- let commentEnd = null;
- for (const { start, value } of bs.items) {
- const props = resolveProps.resolveProps(start, {
- indicator: 'seq-item-ind',
- next: value,
- offset,
- onError,
- parentIndent: bs.indent,
- startOnNewline: true
- });
- if (!props.found) {
- if (props.anchor || props.tag || value) {
- if (value?.type === 'block-seq')
- onError(props.end, 'BAD_INDENT', 'All sequence items must start at the same column');
- else
- onError(offset, 'MISSING_CHAR', 'Sequence item without - indicator');
- }
- else {
- commentEnd = props.end;
- if (props.comment)
- seq.comment = props.comment;
- continue;
- }
- }
- const node = value
- ? composeNode(ctx, value, props, onError)
- : composeEmptyNode(ctx, props.end, start, null, props, onError);
- if (ctx.schema.compat)
- utilFlowIndentCheck.flowIndentCheck(bs.indent, value, onError);
- offset = node.range[2];
- seq.items.push(node);
- }
- seq.range = [bs.offset, offset, commentEnd ?? offset];
- return seq;
-}
-
-exports.resolveBlockSeq = resolveBlockSeq;
-
-
-/***/ }),
-
-/***/ 7788:
-/***/ ((__unused_webpack_module, exports) => {
-
-
-
-function resolveEnd(end, offset, reqSpace, onError) {
- let comment = '';
- if (end) {
- let hasSpace = false;
- let sep = '';
- for (const token of end) {
- const { source, type } = token;
- switch (type) {
- case 'space':
- hasSpace = true;
- break;
- case 'comment': {
- if (reqSpace && !hasSpace)
- onError(token, 'MISSING_CHAR', 'Comments must be separated from other tokens by white space characters');
- const cb = source.substring(1) || ' ';
- if (!comment)
- comment = cb;
- else
- comment += sep + cb;
- sep = '';
- break;
- }
- case 'newline':
- if (comment)
- sep += source;
- hasSpace = true;
- break;
- default:
- onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${type} at node end`);
- }
- offset += source.length;
- }
- }
- return { comment, offset };
-}
-
-exports.resolveEnd = resolveEnd;
-
-
-/***/ }),
-
-/***/ 3142:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var identity = __nccwpck_require__(1127);
-var Pair = __nccwpck_require__(7165);
-var YAMLMap = __nccwpck_require__(4454);
-var YAMLSeq = __nccwpck_require__(2223);
-var resolveEnd = __nccwpck_require__(7788);
-var resolveProps = __nccwpck_require__(4631);
-var utilContainsNewline = __nccwpck_require__(9499);
-var utilMapIncludes = __nccwpck_require__(1187);
-
-const blockMsg = 'Block collections are not allowed within flow collections';
-const isBlock = (token) => token && (token.type === 'block-map' || token.type === 'block-seq');
-function resolveFlowCollection({ composeNode, composeEmptyNode }, ctx, fc, onError, tag) {
- const isMap = fc.start.source === '{';
- const fcName = isMap ? 'flow map' : 'flow sequence';
- const NodeClass = (tag?.nodeClass ?? (isMap ? YAMLMap.YAMLMap : YAMLSeq.YAMLSeq));
- const coll = new NodeClass(ctx.schema);
- coll.flow = true;
- const atRoot = ctx.atRoot;
- if (atRoot)
- ctx.atRoot = false;
- if (ctx.atKey)
- ctx.atKey = false;
- let offset = fc.offset + fc.start.source.length;
- for (let i = 0; i < fc.items.length; ++i) {
- const collItem = fc.items[i];
- const { start, key, sep, value } = collItem;
- const props = resolveProps.resolveProps(start, {
- flow: fcName,
- indicator: 'explicit-key-ind',
- next: key ?? sep?.[0],
- offset,
- onError,
- parentIndent: fc.indent,
- startOnNewline: false
- });
- if (!props.found) {
- if (!props.anchor && !props.tag && !sep && !value) {
- if (i === 0 && props.comma)
- onError(props.comma, 'UNEXPECTED_TOKEN', `Unexpected , in ${fcName}`);
- else if (i < fc.items.length - 1)
- onError(props.start, 'UNEXPECTED_TOKEN', `Unexpected empty item in ${fcName}`);
- if (props.comment) {
- if (coll.comment)
- coll.comment += '\n' + props.comment;
- else
- coll.comment = props.comment;
- }
- offset = props.end;
- continue;
- }
- if (!isMap && ctx.options.strict && utilContainsNewline.containsNewline(key))
- onError(key, // checked by containsNewline()
- 'MULTILINE_IMPLICIT_KEY', 'Implicit keys of flow sequence pairs need to be on a single line');
- }
- if (i === 0) {
- if (props.comma)
- onError(props.comma, 'UNEXPECTED_TOKEN', `Unexpected , in ${fcName}`);
- }
- else {
- if (!props.comma)
- onError(props.start, 'MISSING_CHAR', `Missing , between ${fcName} items`);
- if (props.comment) {
- let prevItemComment = '';
- loop: for (const st of start) {
- switch (st.type) {
- case 'comma':
- case 'space':
- break;
- case 'comment':
- prevItemComment = st.source.substring(1);
- break loop;
- default:
- break loop;
- }
- }
- if (prevItemComment) {
- let prev = coll.items[coll.items.length - 1];
- if (identity.isPair(prev))
- prev = prev.value ?? prev.key;
- if (prev.comment)
- prev.comment += '\n' + prevItemComment;
- else
- prev.comment = prevItemComment;
- props.comment = props.comment.substring(prevItemComment.length + 1);
- }
- }
- }
- if (!isMap && !sep && !props.found) {
- // item is a value in a seq
- // → key & sep are empty, start does not include ? or :
- const valueNode = value
- ? composeNode(ctx, value, props, onError)
- : composeEmptyNode(ctx, props.end, sep, null, props, onError);
- coll.items.push(valueNode);
- offset = valueNode.range[2];
- if (isBlock(value))
- onError(valueNode.range, 'BLOCK_IN_FLOW', blockMsg);
- }
- else {
- // item is a key+value pair
- // key value
- ctx.atKey = true;
- const keyStart = props.end;
- const keyNode = key
- ? composeNode(ctx, key, props, onError)
- : composeEmptyNode(ctx, keyStart, start, null, props, onError);
- if (isBlock(key))
- onError(keyNode.range, 'BLOCK_IN_FLOW', blockMsg);
- ctx.atKey = false;
- // value properties
- const valueProps = resolveProps.resolveProps(sep ?? [], {
- flow: fcName,
- indicator: 'map-value-ind',
- next: value,
- offset: keyNode.range[2],
- onError,
- parentIndent: fc.indent,
- startOnNewline: false
- });
- if (valueProps.found) {
- if (!isMap && !props.found && ctx.options.strict) {
- if (sep)
- for (const st of sep) {
- if (st === valueProps.found)
- break;
- if (st.type === 'newline') {
- onError(st, 'MULTILINE_IMPLICIT_KEY', 'Implicit keys of flow sequence pairs need to be on a single line');
- break;
- }
- }
- if (props.start < valueProps.found.offset - 1024)
- onError(valueProps.found, 'KEY_OVER_1024_CHARS', 'The : indicator must be at most 1024 chars after the start of an implicit flow sequence key');
- }
- }
- else if (value) {
- if ('source' in value && value.source?.[0] === ':')
- onError(value, 'MISSING_CHAR', `Missing space after : in ${fcName}`);
- else
- onError(valueProps.start, 'MISSING_CHAR', `Missing , or : between ${fcName} items`);
- }
- // value value
- const valueNode = value
- ? composeNode(ctx, value, valueProps, onError)
- : valueProps.found
- ? composeEmptyNode(ctx, valueProps.end, sep, null, valueProps, onError)
- : null;
- if (valueNode) {
- if (isBlock(value))
- onError(valueNode.range, 'BLOCK_IN_FLOW', blockMsg);
- }
- else if (valueProps.comment) {
- if (keyNode.comment)
- keyNode.comment += '\n' + valueProps.comment;
- else
- keyNode.comment = valueProps.comment;
- }
- const pair = new Pair.Pair(keyNode, valueNode);
- if (ctx.options.keepSourceTokens)
- pair.srcToken = collItem;
- if (isMap) {
- const map = coll;
- if (utilMapIncludes.mapIncludes(ctx, map.items, keyNode))
- onError(keyStart, 'DUPLICATE_KEY', 'Map keys must be unique');
- map.items.push(pair);
- }
- else {
- const map = new YAMLMap.YAMLMap(ctx.schema);
- map.flow = true;
- map.items.push(pair);
- const endRange = (valueNode ?? keyNode).range;
- map.range = [keyNode.range[0], endRange[1], endRange[2]];
- coll.items.push(map);
- }
- offset = valueNode ? valueNode.range[2] : valueProps.end;
- }
- }
- const expectedEnd = isMap ? '}' : ']';
- const [ce, ...ee] = fc.end;
- let cePos = offset;
- if (ce?.source === expectedEnd)
- cePos = ce.offset + ce.source.length;
- else {
- const name = fcName[0].toUpperCase() + fcName.substring(1);
- const msg = atRoot
- ? `${name} must end with a ${expectedEnd}`
- : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`;
- onError(offset, atRoot ? 'MISSING_CHAR' : 'BAD_INDENT', msg);
- if (ce && ce.source.length !== 1)
- ee.unshift(ce);
- }
- if (ee.length > 0) {
- const end = resolveEnd.resolveEnd(ee, cePos, ctx.options.strict, onError);
- if (end.comment) {
- if (coll.comment)
- coll.comment += '\n' + end.comment;
- else
- coll.comment = end.comment;
- }
- coll.range = [fc.offset, cePos, end.offset];
- }
- else {
- coll.range = [fc.offset, cePos, cePos];
- }
- return coll;
-}
-
-exports.resolveFlowCollection = resolveFlowCollection;
-
-
-/***/ }),
-
-/***/ 6842:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var Scalar = __nccwpck_require__(3301);
-var resolveEnd = __nccwpck_require__(7788);
-
-function resolveFlowScalar(scalar, strict, onError) {
- const { offset, type, source, end } = scalar;
- let _type;
- let value;
- const _onError = (rel, code, msg) => onError(offset + rel, code, msg);
- switch (type) {
- case 'scalar':
- _type = Scalar.Scalar.PLAIN;
- value = plainValue(source, _onError);
- break;
- case 'single-quoted-scalar':
- _type = Scalar.Scalar.QUOTE_SINGLE;
- value = singleQuotedValue(source, _onError);
- break;
- case 'double-quoted-scalar':
- _type = Scalar.Scalar.QUOTE_DOUBLE;
- value = doubleQuotedValue(source, _onError);
- break;
- /* istanbul ignore next should not happen */
- default:
- onError(scalar, 'UNEXPECTED_TOKEN', `Expected a flow scalar value, but found: ${type}`);
- return {
- value: '',
- type: null,
- comment: '',
- range: [offset, offset + source.length, offset + source.length]
- };
- }
- const valueEnd = offset + source.length;
- const re = resolveEnd.resolveEnd(end, valueEnd, strict, onError);
- return {
- value,
- type: _type,
- comment: re.comment,
- range: [offset, valueEnd, re.offset]
- };
-}
-function plainValue(source, onError) {
- let badChar = '';
- switch (source[0]) {
- /* istanbul ignore next should not happen */
- case '\t':
- badChar = 'a tab character';
- break;
- case ',':
- badChar = 'flow indicator character ,';
- break;
- case '%':
- badChar = 'directive indicator character %';
- break;
- case '|':
- case '>': {
- badChar = `block scalar indicator ${source[0]}`;
- break;
- }
- case '@':
- case '`': {
- badChar = `reserved character ${source[0]}`;
- break;
- }
- }
- if (badChar)
- onError(0, 'BAD_SCALAR_START', `Plain value cannot start with ${badChar}`);
- return foldLines(source);
-}
-function singleQuotedValue(source, onError) {
- if (source[source.length - 1] !== "'" || source.length === 1)
- onError(source.length, 'MISSING_CHAR', "Missing closing 'quote");
- return foldLines(source.slice(1, -1)).replace(/''/g, "'");
-}
-function foldLines(source) {
- /**
- * The negative lookbehind here and in the `re` RegExp is to
- * prevent causing a polynomial search time in certain cases.
- *
- * The try-catch is for Safari, which doesn't support this yet:
- * https://caniuse.com/js-regexp-lookbehind
- */
- let first, line;
- try {
- first = new RegExp('(.*?)(? wsStart ? source.slice(wsStart, i + 1) : ch;
- }
- else {
- res += ch;
- }
- }
- if (source[source.length - 1] !== '"' || source.length === 1)
- onError(source.length, 'MISSING_CHAR', 'Missing closing "quote');
- return res;
-}
-/**
- * Fold a single newline into a space, multiple newlines to N - 1 newlines.
- * Presumes `source[offset] === '\n'`
- */
-function foldNewline(source, offset) {
- let fold = '';
- let ch = source[offset + 1];
- while (ch === ' ' || ch === '\t' || ch === '\n' || ch === '\r') {
- if (ch === '\r' && source[offset + 2] !== '\n')
- break;
- if (ch === '\n')
- fold += '\n';
- offset += 1;
- ch = source[offset + 1];
- }
- if (!fold)
- fold = ' ';
- return { fold, offset };
-}
-const escapeCodes = {
- '0': '\0', // null character
- a: '\x07', // bell character
- b: '\b', // backspace
- e: '\x1b', // escape character
- f: '\f', // form feed
- n: '\n', // line feed
- r: '\r', // carriage return
- t: '\t', // horizontal tab
- v: '\v', // vertical tab
- N: '\u0085', // Unicode next line
- _: '\u00a0', // Unicode non-breaking space
- L: '\u2028', // Unicode line separator
- P: '\u2029', // Unicode paragraph separator
- ' ': ' ',
- '"': '"',
- '/': '/',
- '\\': '\\',
- '\t': '\t'
-};
-function parseCharCode(source, offset, length, onError) {
- const cc = source.substr(offset, length);
- const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc);
- const code = ok ? parseInt(cc, 16) : NaN;
- if (isNaN(code)) {
- const raw = source.substr(offset - 2, length + 2);
- onError(offset - 2, 'BAD_DQ_ESCAPE', `Invalid escape sequence ${raw}`);
- return raw;
- }
- return String.fromCodePoint(code);
-}
-
-exports.resolveFlowScalar = resolveFlowScalar;
-
-
-/***/ }),
-
-/***/ 4631:
-/***/ ((__unused_webpack_module, exports) => {
-
-
-
-function resolveProps(tokens, { flow, indicator, next, offset, onError, parentIndent, startOnNewline }) {
- let spaceBefore = false;
- let atNewline = startOnNewline;
- let hasSpace = startOnNewline;
- let comment = '';
- let commentSep = '';
- let hasNewline = false;
- let reqSpace = false;
- let tab = null;
- let anchor = null;
- let tag = null;
- let newlineAfterProp = null;
- let comma = null;
- let found = null;
- let start = null;
- for (const token of tokens) {
- if (reqSpace) {
- if (token.type !== 'space' &&
- token.type !== 'newline' &&
- token.type !== 'comma')
- onError(token.offset, 'MISSING_CHAR', 'Tags and anchors must be separated from the next token by white space');
- reqSpace = false;
- }
- if (tab) {
- if (atNewline && token.type !== 'comment' && token.type !== 'newline') {
- onError(tab, 'TAB_AS_INDENT', 'Tabs are not allowed as indentation');
- }
- tab = null;
- }
- switch (token.type) {
- case 'space':
- // At the doc level, tabs at line start may be parsed
- // as leading white space rather than indentation.
- // In a flow collection, only the parser handles indent.
- if (!flow &&
- (indicator !== 'doc-start' || next?.type !== 'flow-collection') &&
- token.source.includes('\t')) {
- tab = token;
- }
- hasSpace = true;
- break;
- case 'comment': {
- if (!hasSpace)
- onError(token, 'MISSING_CHAR', 'Comments must be separated from other tokens by white space characters');
- const cb = token.source.substring(1) || ' ';
- if (!comment)
- comment = cb;
- else
- comment += commentSep + cb;
- commentSep = '';
- atNewline = false;
- break;
- }
- case 'newline':
- if (atNewline) {
- if (comment)
- comment += token.source;
- else if (!found || indicator !== 'seq-item-ind')
- spaceBefore = true;
- }
- else
- commentSep += token.source;
- atNewline = true;
- hasNewline = true;
- if (anchor || tag)
- newlineAfterProp = token;
- hasSpace = true;
- break;
- case 'anchor':
- if (anchor)
- onError(token, 'MULTIPLE_ANCHORS', 'A node can have at most one anchor');
- if (token.source.endsWith(':'))
- onError(token.offset + token.source.length - 1, 'BAD_ALIAS', 'Anchor ending in : is ambiguous', true);
- anchor = token;
- start ?? (start = token.offset);
- atNewline = false;
- hasSpace = false;
- reqSpace = true;
- break;
- case 'tag': {
- if (tag)
- onError(token, 'MULTIPLE_TAGS', 'A node can have at most one tag');
- tag = token;
- start ?? (start = token.offset);
- atNewline = false;
- hasSpace = false;
- reqSpace = true;
- break;
- }
- case indicator:
- // Could here handle preceding comments differently
- if (anchor || tag)
- onError(token, 'BAD_PROP_ORDER', `Anchors and tags must be after the ${token.source} indicator`);
- if (found)
- onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${token.source} in ${flow ?? 'collection'}`);
- found = token;
- atNewline =
- indicator === 'seq-item-ind' || indicator === 'explicit-key-ind';
- hasSpace = false;
- break;
- case 'comma':
- if (flow) {
- if (comma)
- onError(token, 'UNEXPECTED_TOKEN', `Unexpected , in ${flow}`);
- comma = token;
- atNewline = false;
- hasSpace = false;
- break;
- }
- // else fallthrough
- default:
- onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${token.type} token`);
- atNewline = false;
- hasSpace = false;
- }
- }
- const last = tokens[tokens.length - 1];
- const end = last ? last.offset + last.source.length : offset;
- if (reqSpace &&
- next &&
- next.type !== 'space' &&
- next.type !== 'newline' &&
- next.type !== 'comma' &&
- (next.type !== 'scalar' || next.source !== '')) {
- onError(next.offset, 'MISSING_CHAR', 'Tags and anchors must be separated from the next token by white space');
- }
- if (tab &&
- ((atNewline && tab.indent <= parentIndent) ||
- next?.type === 'block-map' ||
- next?.type === 'block-seq'))
- onError(tab, 'TAB_AS_INDENT', 'Tabs are not allowed as indentation');
- return {
- comma,
- found,
- spaceBefore,
- comment,
- hasNewline,
- anchor,
- tag,
- newlineAfterProp,
- end,
- start: start ?? end
- };
-}
-
-exports.resolveProps = resolveProps;
-
-
-/***/ }),
-
-/***/ 9499:
-/***/ ((__unused_webpack_module, exports) => {
-
-
-
-function containsNewline(key) {
- if (!key)
- return null;
- switch (key.type) {
- case 'alias':
- case 'scalar':
- case 'double-quoted-scalar':
- case 'single-quoted-scalar':
- if (key.source.includes('\n'))
- return true;
- if (key.end)
- for (const st of key.end)
- if (st.type === 'newline')
- return true;
- return false;
- case 'flow-collection':
- for (const it of key.items) {
- for (const st of it.start)
- if (st.type === 'newline')
- return true;
- if (it.sep)
- for (const st of it.sep)
- if (st.type === 'newline')
- return true;
- if (containsNewline(it.key) || containsNewline(it.value))
- return true;
- }
- return false;
- default:
- return true;
- }
-}
-
-exports.containsNewline = containsNewline;
-
-
-/***/ }),
-
-/***/ 2599:
-/***/ ((__unused_webpack_module, exports) => {
-
-
-
-function emptyScalarPosition(offset, before, pos) {
- if (before) {
- pos ?? (pos = before.length);
- for (let i = pos - 1; i >= 0; --i) {
- let st = before[i];
- switch (st.type) {
- case 'space':
- case 'comment':
- case 'newline':
- offset -= st.source.length;
- continue;
- }
- // Technically, an empty scalar is immediately after the last non-empty
- // node, but it's more useful to place it after any whitespace.
- st = before[++i];
- while (st?.type === 'space') {
- offset += st.source.length;
- st = before[++i];
- }
- break;
- }
- }
- return offset;
-}
-
-exports.emptyScalarPosition = emptyScalarPosition;
-
-
-/***/ }),
-
-/***/ 4051:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var utilContainsNewline = __nccwpck_require__(9499);
-
-function flowIndentCheck(indent, fc, onError) {
- if (fc?.type === 'flow-collection') {
- const end = fc.end[0];
- if (end.indent === indent &&
- (end.source === ']' || end.source === '}') &&
- utilContainsNewline.containsNewline(fc)) {
- const msg = 'Flow end indicator should be more indented than parent';
- onError(end, 'BAD_INDENT', msg, true);
- }
- }
-}
-
-exports.flowIndentCheck = flowIndentCheck;
-
-
-/***/ }),
-
-/***/ 1187:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var identity = __nccwpck_require__(1127);
-
-function mapIncludes(ctx, items, search) {
- const { uniqueKeys } = ctx.options;
- if (uniqueKeys === false)
- return false;
- const isEqual = typeof uniqueKeys === 'function'
- ? uniqueKeys
- : (a, b) => a === b || (identity.isScalar(a) && identity.isScalar(b) && a.value === b.value);
- return items.some(pair => isEqual(pair.key, search));
-}
-
-exports.mapIncludes = mapIncludes;
-
-
-/***/ }),
-
-/***/ 3021:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var Alias = __nccwpck_require__(4065);
-var Collection = __nccwpck_require__(101);
-var identity = __nccwpck_require__(1127);
-var Pair = __nccwpck_require__(7165);
-var toJS = __nccwpck_require__(4043);
-var Schema = __nccwpck_require__(5840);
-var stringifyDocument = __nccwpck_require__(6829);
-var anchors = __nccwpck_require__(1596);
-var applyReviver = __nccwpck_require__(3661);
-var createNode = __nccwpck_require__(2404);
-var directives = __nccwpck_require__(1342);
-
-class Document {
- constructor(value, replacer, options) {
- /** A comment before this Document */
- this.commentBefore = null;
- /** A comment immediately after this Document */
- this.comment = null;
- /** Errors encountered during parsing. */
- this.errors = [];
- /** Warnings encountered during parsing. */
- this.warnings = [];
- Object.defineProperty(this, identity.NODE_TYPE, { value: identity.DOC });
- let _replacer = null;
- if (typeof replacer === 'function' || Array.isArray(replacer)) {
- _replacer = replacer;
- }
- else if (options === undefined && replacer) {
- options = replacer;
- replacer = undefined;
- }
- const opt = Object.assign({
- intAsBigInt: false,
- keepSourceTokens: false,
- logLevel: 'warn',
- prettyErrors: true,
- strict: true,
- stringKeys: false,
- uniqueKeys: true,
- version: '1.2'
- }, options);
- this.options = opt;
- let { version } = opt;
- if (options?._directives) {
- this.directives = options._directives.atDocument();
- if (this.directives.yaml.explicit)
- version = this.directives.yaml.version;
- }
- else
- this.directives = new directives.Directives({ version });
- this.setSchema(version, options);
- // @ts-expect-error We can't really know that this matches Contents.
- this.contents =
- value === undefined ? null : this.createNode(value, _replacer, options);
- }
- /**
- * Create a deep copy of this Document and its contents.
- *
- * Custom Node values that inherit from `Object` still refer to their original instances.
- */
- clone() {
- const copy = Object.create(Document.prototype, {
- [identity.NODE_TYPE]: { value: identity.DOC }
- });
- copy.commentBefore = this.commentBefore;
- copy.comment = this.comment;
- copy.errors = this.errors.slice();
- copy.warnings = this.warnings.slice();
- copy.options = Object.assign({}, this.options);
- if (this.directives)
- copy.directives = this.directives.clone();
- copy.schema = this.schema.clone();
- // @ts-expect-error We can't really know that this matches Contents.
- copy.contents = identity.isNode(this.contents)
- ? this.contents.clone(copy.schema)
- : this.contents;
- if (this.range)
- copy.range = this.range.slice();
- return copy;
- }
- /** Adds a value to the document. */
- add(value) {
- if (assertCollection(this.contents))
- this.contents.add(value);
- }
- /** Adds a value to the document. */
- addIn(path, value) {
- if (assertCollection(this.contents))
- this.contents.addIn(path, value);
- }
- /**
- * Create a new `Alias` node, ensuring that the target `node` has the required anchor.
- *
- * If `node` already has an anchor, `name` is ignored.
- * Otherwise, the `node.anchor` value will be set to `name`,
- * or if an anchor with that name is already present in the document,
- * `name` will be used as a prefix for a new unique anchor.
- * If `name` is undefined, the generated anchor will use 'a' as a prefix.
- */
- createAlias(node, name) {
- if (!node.anchor) {
- const prev = anchors.anchorNames(this);
- node.anchor =
- // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
- !name || prev.has(name) ? anchors.findNewAnchor(name || 'a', prev) : name;
- }
- return new Alias.Alias(node.anchor);
- }
- createNode(value, replacer, options) {
- let _replacer = undefined;
- if (typeof replacer === 'function') {
- value = replacer.call({ '': value }, '', value);
- _replacer = replacer;
- }
- else if (Array.isArray(replacer)) {
- const keyToStr = (v) => typeof v === 'number' || v instanceof String || v instanceof Number;
- const asStr = replacer.filter(keyToStr).map(String);
- if (asStr.length > 0)
- replacer = replacer.concat(asStr);
- _replacer = replacer;
- }
- else if (options === undefined && replacer) {
- options = replacer;
- replacer = undefined;
- }
- const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {};
- const { onAnchor, setAnchors, sourceObjects } = anchors.createNodeAnchors(this,
- // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
- anchorPrefix || 'a');
- const ctx = {
- aliasDuplicateObjects: aliasDuplicateObjects ?? true,
- keepUndefined: keepUndefined ?? false,
- onAnchor,
- onTagObj,
- replacer: _replacer,
- schema: this.schema,
- sourceObjects
- };
- const node = createNode.createNode(value, tag, ctx);
- if (flow && identity.isCollection(node))
- node.flow = true;
- setAnchors();
- return node;
- }
- /**
- * Convert a key and a value into a `Pair` using the current schema,
- * recursively wrapping all values as `Scalar` or `Collection` nodes.
- */
- createPair(key, value, options = {}) {
- const k = this.createNode(key, null, options);
- const v = this.createNode(value, null, options);
- return new Pair.Pair(k, v);
- }
- /**
- * Removes a value from the document.
- * @returns `true` if the item was found and removed.
- */
- delete(key) {
- return assertCollection(this.contents) ? this.contents.delete(key) : false;
- }
- /**
- * Removes a value from the document.
- * @returns `true` if the item was found and removed.
- */
- deleteIn(path) {
- if (Collection.isEmptyPath(path)) {
- if (this.contents == null)
- return false;
- // @ts-expect-error Presumed impossible if Strict extends false
- this.contents = null;
- return true;
- }
- return assertCollection(this.contents)
- ? this.contents.deleteIn(path)
- : false;
- }
- /**
- * Returns item at `key`, or `undefined` if not found. By default unwraps
- * scalar values from their surrounding node; to disable set `keepScalar` to
- * `true` (collections are always returned intact).
- */
- get(key, keepScalar) {
- return identity.isCollection(this.contents)
- ? this.contents.get(key, keepScalar)
- : undefined;
- }
- /**
- * Returns item at `path`, or `undefined` if not found. By default unwraps
- * scalar values from their surrounding node; to disable set `keepScalar` to
- * `true` (collections are always returned intact).
- */
- getIn(path, keepScalar) {
- if (Collection.isEmptyPath(path))
- return !keepScalar && identity.isScalar(this.contents)
- ? this.contents.value
- : this.contents;
- return identity.isCollection(this.contents)
- ? this.contents.getIn(path, keepScalar)
- : undefined;
- }
- /**
- * Checks if the document includes a value with the key `key`.
- */
- has(key) {
- return identity.isCollection(this.contents) ? this.contents.has(key) : false;
- }
- /**
- * Checks if the document includes a value at `path`.
- */
- hasIn(path) {
- if (Collection.isEmptyPath(path))
- return this.contents !== undefined;
- return identity.isCollection(this.contents) ? this.contents.hasIn(path) : false;
- }
- /**
- * Sets a value in this document. For `!!set`, `value` needs to be a
- * boolean to add/remove the item from the set.
- */
- set(key, value) {
- if (this.contents == null) {
- // @ts-expect-error We can't really know that this matches Contents.
- this.contents = Collection.collectionFromPath(this.schema, [key], value);
- }
- else if (assertCollection(this.contents)) {
- this.contents.set(key, value);
- }
- }
- /**
- * Sets a value in this document. For `!!set`, `value` needs to be a
- * boolean to add/remove the item from the set.
- */
- setIn(path, value) {
- if (Collection.isEmptyPath(path)) {
- // @ts-expect-error We can't really know that this matches Contents.
- this.contents = value;
- }
- else if (this.contents == null) {
- // @ts-expect-error We can't really know that this matches Contents.
- this.contents = Collection.collectionFromPath(this.schema, Array.from(path), value);
- }
- else if (assertCollection(this.contents)) {
- this.contents.setIn(path, value);
- }
- }
- /**
- * Change the YAML version and schema used by the document.
- * A `null` version disables support for directives, explicit tags, anchors, and aliases.
- * It also requires the `schema` option to be given as a `Schema` instance value.
- *
- * Overrides all previously set schema options.
- */
- setSchema(version, options = {}) {
- if (typeof version === 'number')
- version = String(version);
- let opt;
- switch (version) {
- case '1.1':
- if (this.directives)
- this.directives.yaml.version = '1.1';
- else
- this.directives = new directives.Directives({ version: '1.1' });
- opt = { resolveKnownTags: false, schema: 'yaml-1.1' };
- break;
- case '1.2':
- case 'next':
- if (this.directives)
- this.directives.yaml.version = version;
- else
- this.directives = new directives.Directives({ version });
- opt = { resolveKnownTags: true, schema: 'core' };
- break;
- case null:
- if (this.directives)
- delete this.directives;
- opt = null;
- break;
- default: {
- const sv = JSON.stringify(version);
- throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`);
- }
- }
- // Not using `instanceof Schema` to allow for duck typing
- if (options.schema instanceof Object)
- this.schema = options.schema;
- else if (opt)
- this.schema = new Schema.Schema(Object.assign(opt, options));
- else
- throw new Error(`With a null YAML version, the { schema: Schema } option is required`);
- }
- // json & jsonArg are only used from toJSON()
- toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
- const ctx = {
- anchors: new Map(),
- doc: this,
- keep: !json,
- mapAsMap: mapAsMap === true,
- mapKeyWarned: false,
- maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100
- };
- const res = toJS.toJS(this.contents, jsonArg ?? '', ctx);
- if (typeof onAnchor === 'function')
- for (const { count, res } of ctx.anchors.values())
- onAnchor(res, count);
- return typeof reviver === 'function'
- ? applyReviver.applyReviver(reviver, { '': res }, '', res)
- : res;
- }
- /**
- * A JSON representation of the document `contents`.
- *
- * @param jsonArg Used by `JSON.stringify` to indicate the array index or
- * property name.
- */
- toJSON(jsonArg, onAnchor) {
- return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor });
- }
- /** A YAML representation of the document. */
- toString(options = {}) {
- if (this.errors.length > 0)
- throw new Error('Document with errors cannot be stringified');
- if ('indent' in options &&
- (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) {
- const s = JSON.stringify(options.indent);
- throw new Error(`"indent" option must be a positive integer, not ${s}`);
- }
- return stringifyDocument.stringifyDocument(this, options);
- }
-}
-function assertCollection(contents) {
- if (identity.isCollection(contents))
- return true;
- throw new Error('Expected a YAML collection as document contents');
-}
-
-exports.Document = Document;
-
-
-/***/ }),
-
-/***/ 1596:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var identity = __nccwpck_require__(1127);
-var visit = __nccwpck_require__(204);
-
-/**
- * Verify that the input string is a valid anchor.
- *
- * Will throw on errors.
- */
-function anchorIsValid(anchor) {
- if (/[\x00-\x19\s,[\]{}]/.test(anchor)) {
- const sa = JSON.stringify(anchor);
- const msg = `Anchor must not contain whitespace or control characters: ${sa}`;
- throw new Error(msg);
- }
- return true;
-}
-function anchorNames(root) {
- const anchors = new Set();
- visit.visit(root, {
- Value(_key, node) {
- if (node.anchor)
- anchors.add(node.anchor);
- }
- });
- return anchors;
-}
-/** Find a new anchor name with the given `prefix` and a one-indexed suffix. */
-function findNewAnchor(prefix, exclude) {
- for (let i = 1; true; ++i) {
- const name = `${prefix}${i}`;
- if (!exclude.has(name))
- return name;
- }
-}
-function createNodeAnchors(doc, prefix) {
- const aliasObjects = [];
- const sourceObjects = new Map();
- let prevAnchors = null;
- return {
- onAnchor: (source) => {
- aliasObjects.push(source);
- prevAnchors ?? (prevAnchors = anchorNames(doc));
- const anchor = findNewAnchor(prefix, prevAnchors);
- prevAnchors.add(anchor);
- return anchor;
- },
- /**
- * With circular references, the source node is only resolved after all
- * of its child nodes are. This is why anchors are set only after all of
- * the nodes have been created.
- */
- setAnchors: () => {
- for (const source of aliasObjects) {
- const ref = sourceObjects.get(source);
- if (typeof ref === 'object' &&
- ref.anchor &&
- (identity.isScalar(ref.node) || identity.isCollection(ref.node))) {
- ref.node.anchor = ref.anchor;
- }
- else {
- const error = new Error('Failed to resolve repeated object (this should not happen)');
- error.source = source;
- throw error;
- }
- }
- },
- sourceObjects
- };
-}
-
-exports.anchorIsValid = anchorIsValid;
-exports.anchorNames = anchorNames;
-exports.createNodeAnchors = createNodeAnchors;
-exports.findNewAnchor = findNewAnchor;
-
-
-/***/ }),
-
-/***/ 3661:
-/***/ ((__unused_webpack_module, exports) => {
-
-
-
-/**
- * Applies the JSON.parse reviver algorithm as defined in the ECMA-262 spec,
- * in section 24.5.1.1 "Runtime Semantics: InternalizeJSONProperty" of the
- * 2021 edition: https://tc39.es/ecma262/#sec-json.parse
- *
- * Includes extensions for handling Map and Set objects.
- */
-function applyReviver(reviver, obj, key, val) {
- if (val && typeof val === 'object') {
- if (Array.isArray(val)) {
- for (let i = 0, len = val.length; i < len; ++i) {
- const v0 = val[i];
- const v1 = applyReviver(reviver, val, String(i), v0);
- // eslint-disable-next-line @typescript-eslint/no-array-delete
- if (v1 === undefined)
- delete val[i];
- else if (v1 !== v0)
- val[i] = v1;
- }
- }
- else if (val instanceof Map) {
- for (const k of Array.from(val.keys())) {
- const v0 = val.get(k);
- const v1 = applyReviver(reviver, val, k, v0);
- if (v1 === undefined)
- val.delete(k);
- else if (v1 !== v0)
- val.set(k, v1);
- }
- }
- else if (val instanceof Set) {
- for (const v0 of Array.from(val)) {
- const v1 = applyReviver(reviver, val, v0, v0);
- if (v1 === undefined)
- val.delete(v0);
- else if (v1 !== v0) {
- val.delete(v0);
- val.add(v1);
- }
- }
- }
- else {
- for (const [k, v0] of Object.entries(val)) {
- const v1 = applyReviver(reviver, val, k, v0);
- if (v1 === undefined)
- delete val[k];
- else if (v1 !== v0)
- val[k] = v1;
- }
- }
- }
- return reviver.call(obj, key, val);
-}
-
-exports.applyReviver = applyReviver;
-
-
-/***/ }),
-
-/***/ 2404:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var Alias = __nccwpck_require__(4065);
-var identity = __nccwpck_require__(1127);
-var Scalar = __nccwpck_require__(3301);
-
-const defaultTagPrefix = 'tag:yaml.org,2002:';
-function findTagObject(value, tagName, tags) {
- if (tagName) {
- const match = tags.filter(t => t.tag === tagName);
- const tagObj = match.find(t => !t.format) ?? match[0];
- if (!tagObj)
- throw new Error(`Tag ${tagName} not found`);
- return tagObj;
- }
- return tags.find(t => t.identify?.(value) && !t.format);
-}
-function createNode(value, tagName, ctx) {
- if (identity.isDocument(value))
- value = value.contents;
- if (identity.isNode(value))
- return value;
- if (identity.isPair(value)) {
- const map = ctx.schema[identity.MAP].createNode?.(ctx.schema, null, ctx);
- map.items.push(value);
- return map;
- }
- if (value instanceof String ||
- value instanceof Number ||
- value instanceof Boolean ||
- (typeof BigInt !== 'undefined' && value instanceof BigInt) // not supported everywhere
- ) {
- // https://tc39.es/ecma262/#sec-serializejsonproperty
- value = value.valueOf();
- }
- const { aliasDuplicateObjects, onAnchor, onTagObj, schema, sourceObjects } = ctx;
- // Detect duplicate references to the same object & use Alias nodes for all
- // after first. The `ref` wrapper allows for circular references to resolve.
- let ref = undefined;
- if (aliasDuplicateObjects && value && typeof value === 'object') {
- ref = sourceObjects.get(value);
- if (ref) {
- ref.anchor ?? (ref.anchor = onAnchor(value));
- return new Alias.Alias(ref.anchor);
- }
- else {
- ref = { anchor: null, node: null };
- sourceObjects.set(value, ref);
- }
- }
- if (tagName?.startsWith('!!'))
- tagName = defaultTagPrefix + tagName.slice(2);
- let tagObj = findTagObject(value, tagName, schema.tags);
- if (!tagObj) {
- if (value && typeof value.toJSON === 'function') {
- // eslint-disable-next-line @typescript-eslint/no-unsafe-call
- value = value.toJSON();
- }
- if (!value || typeof value !== 'object') {
- const node = new Scalar.Scalar(value);
- if (ref)
- ref.node = node;
- return node;
- }
- tagObj =
- value instanceof Map
- ? schema[identity.MAP]
- : Symbol.iterator in Object(value)
- ? schema[identity.SEQ]
- : schema[identity.MAP];
- }
- if (onTagObj) {
- onTagObj(tagObj);
- delete ctx.onTagObj;
- }
- const node = tagObj?.createNode
- ? tagObj.createNode(ctx.schema, value, ctx)
- : typeof tagObj?.nodeClass?.from === 'function'
- ? tagObj.nodeClass.from(ctx.schema, value, ctx)
- : new Scalar.Scalar(value);
- if (tagName)
- node.tag = tagName;
- else if (!tagObj.default)
- node.tag = tagObj.tag;
- if (ref)
- ref.node = node;
- return node;
-}
-
-exports.createNode = createNode;
-
-
-/***/ }),
-
-/***/ 1342:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var identity = __nccwpck_require__(1127);
-var visit = __nccwpck_require__(204);
-
-const escapeChars = {
- '!': '%21',
- ',': '%2C',
- '[': '%5B',
- ']': '%5D',
- '{': '%7B',
- '}': '%7D'
-};
-const escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, ch => escapeChars[ch]);
-class Directives {
- constructor(yaml, tags) {
- /**
- * The directives-end/doc-start marker `---`. If `null`, a marker may still be
- * included in the document's stringified representation.
- */
- this.docStart = null;
- /** The doc-end marker `...`. */
- this.docEnd = false;
- this.yaml = Object.assign({}, Directives.defaultYaml, yaml);
- this.tags = Object.assign({}, Directives.defaultTags, tags);
- }
- clone() {
- const copy = new Directives(this.yaml, this.tags);
- copy.docStart = this.docStart;
- return copy;
- }
- /**
- * During parsing, get a Directives instance for the current document and
- * update the stream state according to the current version's spec.
- */
- atDocument() {
- const res = new Directives(this.yaml, this.tags);
- switch (this.yaml.version) {
- case '1.1':
- this.atNextDocument = true;
- break;
- case '1.2':
- this.atNextDocument = false;
- this.yaml = {
- explicit: Directives.defaultYaml.explicit,
- version: '1.2'
- };
- this.tags = Object.assign({}, Directives.defaultTags);
- break;
- }
- return res;
- }
- /**
- * @param onError - May be called even if the action was successful
- * @returns `true` on success
- */
- add(line, onError) {
- if (this.atNextDocument) {
- this.yaml = { explicit: Directives.defaultYaml.explicit, version: '1.1' };
- this.tags = Object.assign({}, Directives.defaultTags);
- this.atNextDocument = false;
- }
- const parts = line.trim().split(/[ \t]+/);
- const name = parts.shift();
- switch (name) {
- case '%TAG': {
- if (parts.length !== 2) {
- onError(0, '%TAG directive should contain exactly two parts');
- if (parts.length < 2)
- return false;
- }
- const [handle, prefix] = parts;
- this.tags[handle] = prefix;
- return true;
- }
- case '%YAML': {
- this.yaml.explicit = true;
- if (parts.length !== 1) {
- onError(0, '%YAML directive should contain exactly one part');
- return false;
- }
- const [version] = parts;
- if (version === '1.1' || version === '1.2') {
- this.yaml.version = version;
- return true;
- }
- else {
- const isValid = /^\d+\.\d+$/.test(version);
- onError(6, `Unsupported YAML version ${version}`, isValid);
- return false;
- }
- }
- default:
- onError(0, `Unknown directive ${name}`, true);
- return false;
- }
- }
- /**
- * Resolves a tag, matching handles to those defined in %TAG directives.
- *
- * @returns Resolved tag, which may also be the non-specific tag `'!'` or a
- * `'!local'` tag, or `null` if unresolvable.
- */
- tagName(source, onError) {
- if (source === '!')
- return '!'; // non-specific tag
- if (source[0] !== '!') {
- onError(`Not a valid tag: ${source}`);
- return null;
- }
- if (source[1] === '<') {
- const verbatim = source.slice(2, -1);
- if (verbatim === '!' || verbatim === '!!') {
- onError(`Verbatim tags aren't resolved, so ${source} is invalid.`);
- return null;
- }
- if (source[source.length - 1] !== '>')
- onError('Verbatim tags must end with a >');
- return verbatim;
- }
- const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s);
- if (!suffix)
- onError(`The ${source} tag has no suffix`);
- const prefix = this.tags[handle];
- if (prefix) {
- try {
- return prefix + decodeURIComponent(suffix);
- }
- catch (error) {
- onError(String(error));
- return null;
- }
- }
- if (handle === '!')
- return source; // local tag
- onError(`Could not resolve tag: ${source}`);
- return null;
- }
- /**
- * Given a fully resolved tag, returns its printable string form,
- * taking into account current tag prefixes and defaults.
- */
- tagString(tag) {
- for (const [handle, prefix] of Object.entries(this.tags)) {
- if (tag.startsWith(prefix))
- return handle + escapeTagName(tag.substring(prefix.length));
- }
- return tag[0] === '!' ? tag : `!<${tag}>`;
- }
- toString(doc) {
- const lines = this.yaml.explicit
- ? [`%YAML ${this.yaml.version || '1.2'}`]
- : [];
- const tagEntries = Object.entries(this.tags);
- let tagNames;
- if (doc && tagEntries.length > 0 && identity.isNode(doc.contents)) {
- const tags = {};
- visit.visit(doc.contents, (_key, node) => {
- if (identity.isNode(node) && node.tag)
- tags[node.tag] = true;
- });
- tagNames = Object.keys(tags);
- }
- else
- tagNames = [];
- for (const [handle, prefix] of tagEntries) {
- if (handle === '!!' && prefix === 'tag:yaml.org,2002:')
- continue;
- if (!doc || tagNames.some(tn => tn.startsWith(prefix)))
- lines.push(`%TAG ${handle} ${prefix}`);
- }
- return lines.join('\n');
- }
-}
-Directives.defaultYaml = { explicit: false, version: '1.2' };
-Directives.defaultTags = { '!!': 'tag:yaml.org,2002:' };
-
-exports.Directives = Directives;
-
-
-/***/ }),
-
-/***/ 1464:
-/***/ ((__unused_webpack_module, exports) => {
-
-
-
-class YAMLError extends Error {
- constructor(name, pos, code, message) {
- super();
- this.name = name;
- this.code = code;
- this.message = message;
- this.pos = pos;
- }
-}
-class YAMLParseError extends YAMLError {
- constructor(pos, code, message) {
- super('YAMLParseError', pos, code, message);
- }
-}
-class YAMLWarning extends YAMLError {
- constructor(pos, code, message) {
- super('YAMLWarning', pos, code, message);
- }
-}
-const prettifyError = (src, lc) => (error) => {
- if (error.pos[0] === -1)
- return;
- error.linePos = error.pos.map(pos => lc.linePos(pos));
- const { line, col } = error.linePos[0];
- error.message += ` at line ${line}, column ${col}`;
- let ci = col - 1;
- let lineStr = src
- .substring(lc.lineStarts[line - 1], lc.lineStarts[line])
- .replace(/[\n\r]+$/, '');
- // Trim to max 80 chars, keeping col position near the middle
- if (ci >= 60 && lineStr.length > 80) {
- const trimStart = Math.min(ci - 39, lineStr.length - 79);
- lineStr = '…' + lineStr.substring(trimStart);
- ci -= trimStart - 1;
- }
- if (lineStr.length > 80)
- lineStr = lineStr.substring(0, 79) + '…';
- // Include previous line in context if pointing at line start
- if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) {
- // Regexp won't match if start is trimmed
- let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]);
- if (prev.length > 80)
- prev = prev.substring(0, 79) + '…\n';
- lineStr = prev + lineStr;
- }
- if (/[^ ]/.test(lineStr)) {
- let count = 1;
- const end = error.linePos[1];
- if (end?.line === line && end.col > col) {
- count = Math.max(1, Math.min(end.col - col, 80 - ci));
- }
- const pointer = ' '.repeat(ci) + '^'.repeat(count);
- error.message += `:\n\n${lineStr}\n${pointer}\n`;
- }
-};
-
-exports.YAMLError = YAMLError;
-exports.YAMLParseError = YAMLParseError;
-exports.YAMLWarning = YAMLWarning;
-exports.prettifyError = prettifyError;
-
-
-/***/ }),
-
-/***/ 8815:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var composer = __nccwpck_require__(9984);
-var Document = __nccwpck_require__(3021);
-var Schema = __nccwpck_require__(5840);
-var errors = __nccwpck_require__(1464);
-var Alias = __nccwpck_require__(4065);
-var identity = __nccwpck_require__(1127);
-var Pair = __nccwpck_require__(7165);
-var Scalar = __nccwpck_require__(3301);
-var YAMLMap = __nccwpck_require__(4454);
-var YAMLSeq = __nccwpck_require__(2223);
-var cst = __nccwpck_require__(3461);
-var lexer = __nccwpck_require__(361);
-var lineCounter = __nccwpck_require__(6628);
-var parser = __nccwpck_require__(3456);
-var publicApi = __nccwpck_require__(4047);
-var visit = __nccwpck_require__(204);
-
-
-
-exports.Composer = composer.Composer;
-exports.Document = Document.Document;
-exports.Schema = Schema.Schema;
-exports.YAMLError = errors.YAMLError;
-exports.YAMLParseError = errors.YAMLParseError;
-exports.YAMLWarning = errors.YAMLWarning;
-exports.Alias = Alias.Alias;
-exports.isAlias = identity.isAlias;
-exports.isCollection = identity.isCollection;
-exports.isDocument = identity.isDocument;
-exports.isMap = identity.isMap;
-exports.isNode = identity.isNode;
-exports.isPair = identity.isPair;
-exports.isScalar = identity.isScalar;
-exports.isSeq = identity.isSeq;
-exports.Pair = Pair.Pair;
-exports.Scalar = Scalar.Scalar;
-exports.YAMLMap = YAMLMap.YAMLMap;
-exports.YAMLSeq = YAMLSeq.YAMLSeq;
-exports.CST = cst;
-exports.Lexer = lexer.Lexer;
-exports.LineCounter = lineCounter.LineCounter;
-exports.Parser = parser.Parser;
-exports.parse = publicApi.parse;
-exports.parseAllDocuments = publicApi.parseAllDocuments;
-exports.parseDocument = publicApi.parseDocument;
-exports.stringify = publicApi.stringify;
-exports.visit = visit.visit;
-exports.visitAsync = visit.visitAsync;
-
-
-/***/ }),
-
-/***/ 7249:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var node_process = __nccwpck_require__(932);
-
-function debug(logLevel, ...messages) {
- if (logLevel === 'debug')
- console.log(...messages);
-}
-function warn(logLevel, warning) {
- if (logLevel === 'debug' || logLevel === 'warn') {
- if (typeof node_process.emitWarning === 'function')
- node_process.emitWarning(warning);
- else
- console.warn(warning);
- }
-}
-
-exports.debug = debug;
-exports.warn = warn;
-
-
-/***/ }),
-
-/***/ 4065:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var anchors = __nccwpck_require__(1596);
-var visit = __nccwpck_require__(204);
-var identity = __nccwpck_require__(1127);
-var Node = __nccwpck_require__(6673);
-var toJS = __nccwpck_require__(4043);
-
-class Alias extends Node.NodeBase {
- constructor(source) {
- super(identity.ALIAS);
- this.source = source;
- Object.defineProperty(this, 'tag', {
- set() {
- throw new Error('Alias nodes cannot have tags');
- }
- });
- }
- /**
- * Resolve the value of this alias within `doc`, finding the last
- * instance of the `source` anchor before this node.
- */
- resolve(doc, ctx) {
- let nodes;
- if (ctx?.aliasResolveCache) {
- nodes = ctx.aliasResolveCache;
- }
- else {
- nodes = [];
- visit.visit(doc, {
- Node: (_key, node) => {
- if (identity.isAlias(node) || identity.hasAnchor(node))
- nodes.push(node);
- }
- });
- if (ctx)
- ctx.aliasResolveCache = nodes;
- }
- let found = undefined;
- for (const node of nodes) {
- if (node === this)
- break;
- if (node.anchor === this.source)
- found = node;
- }
- return found;
- }
- toJSON(_arg, ctx) {
- if (!ctx)
- return { source: this.source };
- const { anchors, doc, maxAliasCount } = ctx;
- const source = this.resolve(doc, ctx);
- if (!source) {
- const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
- throw new ReferenceError(msg);
- }
- let data = anchors.get(source);
- if (!data) {
- // Resolve anchors for Node.prototype.toJS()
- toJS.toJS(source, null, ctx);
- data = anchors.get(source);
- }
- /* istanbul ignore if */
- if (data?.res === undefined) {
- const msg = 'This should not happen: Alias anchor was not resolved?';
- throw new ReferenceError(msg);
- }
- if (maxAliasCount >= 0) {
- data.count += 1;
- if (data.aliasCount === 0)
- data.aliasCount = getAliasCount(doc, source, anchors);
- if (data.count * data.aliasCount > maxAliasCount) {
- const msg = 'Excessive alias count indicates a resource exhaustion attack';
- throw new ReferenceError(msg);
- }
- }
- return data.res;
- }
- toString(ctx, _onComment, _onChompKeep) {
- const src = `*${this.source}`;
- if (ctx) {
- anchors.anchorIsValid(this.source);
- if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) {
- const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
- throw new Error(msg);
- }
- if (ctx.implicitKey)
- return `${src} `;
- }
- return src;
- }
-}
-function getAliasCount(doc, node, anchors) {
- if (identity.isAlias(node)) {
- const source = node.resolve(doc);
- const anchor = anchors && source && anchors.get(source);
- return anchor ? anchor.count * anchor.aliasCount : 0;
- }
- else if (identity.isCollection(node)) {
- let count = 0;
- for (const item of node.items) {
- const c = getAliasCount(doc, item, anchors);
- if (c > count)
- count = c;
- }
- return count;
- }
- else if (identity.isPair(node)) {
- const kc = getAliasCount(doc, node.key, anchors);
- const vc = getAliasCount(doc, node.value, anchors);
- return Math.max(kc, vc);
- }
- return 1;
-}
-
-exports.Alias = Alias;
-
-
-/***/ }),
-
-/***/ 101:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var createNode = __nccwpck_require__(2404);
-var identity = __nccwpck_require__(1127);
-var Node = __nccwpck_require__(6673);
-
-function collectionFromPath(schema, path, value) {
- let v = value;
- for (let i = path.length - 1; i >= 0; --i) {
- const k = path[i];
- if (typeof k === 'number' && Number.isInteger(k) && k >= 0) {
- const a = [];
- a[k] = v;
- v = a;
- }
- else {
- v = new Map([[k, v]]);
- }
- }
- return createNode.createNode(v, undefined, {
- aliasDuplicateObjects: false,
- keepUndefined: false,
- onAnchor: () => {
- throw new Error('This should not happen, please report a bug.');
- },
- schema,
- sourceObjects: new Map()
- });
-}
-// Type guard is intentionally a little wrong so as to be more useful,
-// as it does not cover untypable empty non-string iterables (e.g. []).
-const isEmptyPath = (path) => path == null ||
- (typeof path === 'object' && !!path[Symbol.iterator]().next().done);
-class Collection extends Node.NodeBase {
- constructor(type, schema) {
- super(type);
- Object.defineProperty(this, 'schema', {
- value: schema,
- configurable: true,
- enumerable: false,
- writable: true
- });
- }
- /**
- * Create a copy of this collection.
- *
- * @param schema - If defined, overwrites the original's schema
- */
- clone(schema) {
- const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
- if (schema)
- copy.schema = schema;
- copy.items = copy.items.map(it => identity.isNode(it) || identity.isPair(it) ? it.clone(schema) : it);
- if (this.range)
- copy.range = this.range.slice();
- return copy;
- }
- /**
- * Adds a value to the collection. For `!!map` and `!!omap` the value must
- * be a Pair instance or a `{ key, value }` object, which may not have a key
- * that already exists in the map.
- */
- addIn(path, value) {
- if (isEmptyPath(path))
- this.add(value);
- else {
- const [key, ...rest] = path;
- const node = this.get(key, true);
- if (identity.isCollection(node))
- node.addIn(rest, value);
- else if (node === undefined && this.schema)
- this.set(key, collectionFromPath(this.schema, rest, value));
- else
- throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
- }
- }
- /**
- * Removes a value from the collection.
- * @returns `true` if the item was found and removed.
- */
- deleteIn(path) {
- const [key, ...rest] = path;
- if (rest.length === 0)
- return this.delete(key);
- const node = this.get(key, true);
- if (identity.isCollection(node))
- return node.deleteIn(rest);
- else
- throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
- }
- /**
- * Returns item at `key`, or `undefined` if not found. By default unwraps
- * scalar values from their surrounding node; to disable set `keepScalar` to
- * `true` (collections are always returned intact).
- */
- getIn(path, keepScalar) {
- const [key, ...rest] = path;
- const node = this.get(key, true);
- if (rest.length === 0)
- return !keepScalar && identity.isScalar(node) ? node.value : node;
- else
- return identity.isCollection(node) ? node.getIn(rest, keepScalar) : undefined;
- }
- hasAllNullValues(allowScalar) {
- return this.items.every(node => {
- if (!identity.isPair(node))
- return false;
- const n = node.value;
- return (n == null ||
- (allowScalar &&
- identity.isScalar(n) &&
- n.value == null &&
- !n.commentBefore &&
- !n.comment &&
- !n.tag));
- });
- }
- /**
- * Checks if the collection includes a value with the key `key`.
- */
- hasIn(path) {
- const [key, ...rest] = path;
- if (rest.length === 0)
- return this.has(key);
- const node = this.get(key, true);
- return identity.isCollection(node) ? node.hasIn(rest) : false;
- }
- /**
- * Sets a value in this collection. For `!!set`, `value` needs to be a
- * boolean to add/remove the item from the set.
- */
- setIn(path, value) {
- const [key, ...rest] = path;
- if (rest.length === 0) {
- this.set(key, value);
- }
- else {
- const node = this.get(key, true);
- if (identity.isCollection(node))
- node.setIn(rest, value);
- else if (node === undefined && this.schema)
- this.set(key, collectionFromPath(this.schema, rest, value));
- else
- throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
- }
- }
-}
-
-exports.Collection = Collection;
-exports.collectionFromPath = collectionFromPath;
-exports.isEmptyPath = isEmptyPath;
-
-
-/***/ }),
-
-/***/ 6673:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var applyReviver = __nccwpck_require__(3661);
-var identity = __nccwpck_require__(1127);
-var toJS = __nccwpck_require__(4043);
-
-class NodeBase {
- constructor(type) {
- Object.defineProperty(this, identity.NODE_TYPE, { value: type });
- }
- /** Create a copy of this node. */
- clone() {
- const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
- if (this.range)
- copy.range = this.range.slice();
- return copy;
- }
- /** A plain JavaScript representation of this node. */
- toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
- if (!identity.isDocument(doc))
- throw new TypeError('A document argument is required');
- const ctx = {
- anchors: new Map(),
- doc,
- keep: true,
- mapAsMap: mapAsMap === true,
- mapKeyWarned: false,
- maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100
- };
- const res = toJS.toJS(this, '', ctx);
- if (typeof onAnchor === 'function')
- for (const { count, res } of ctx.anchors.values())
- onAnchor(res, count);
- return typeof reviver === 'function'
- ? applyReviver.applyReviver(reviver, { '': res }, '', res)
- : res;
- }
-}
-
-exports.NodeBase = NodeBase;
-
-
-/***/ }),
-
-/***/ 7165:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var createNode = __nccwpck_require__(2404);
-var stringifyPair = __nccwpck_require__(9748);
-var addPairToJSMap = __nccwpck_require__(7104);
-var identity = __nccwpck_require__(1127);
-
-function createPair(key, value, ctx) {
- const k = createNode.createNode(key, undefined, ctx);
- const v = createNode.createNode(value, undefined, ctx);
- return new Pair(k, v);
-}
-class Pair {
- constructor(key, value = null) {
- Object.defineProperty(this, identity.NODE_TYPE, { value: identity.PAIR });
- this.key = key;
- this.value = value;
- }
- clone(schema) {
- let { key, value } = this;
- if (identity.isNode(key))
- key = key.clone(schema);
- if (identity.isNode(value))
- value = value.clone(schema);
- return new Pair(key, value);
- }
- toJSON(_, ctx) {
- const pair = ctx?.mapAsMap ? new Map() : {};
- return addPairToJSMap.addPairToJSMap(ctx, pair, this);
- }
- toString(ctx, onComment, onChompKeep) {
- return ctx?.doc
- ? stringifyPair.stringifyPair(this, ctx, onComment, onChompKeep)
- : JSON.stringify(this);
- }
-}
-
-exports.Pair = Pair;
-exports.createPair = createPair;
-
-
-/***/ }),
-
-/***/ 3301:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var identity = __nccwpck_require__(1127);
-var Node = __nccwpck_require__(6673);
-var toJS = __nccwpck_require__(4043);
-
-const isScalarValue = (value) => !value || (typeof value !== 'function' && typeof value !== 'object');
-class Scalar extends Node.NodeBase {
- constructor(value) {
- super(identity.SCALAR);
- this.value = value;
- }
- toJSON(arg, ctx) {
- return ctx?.keep ? this.value : toJS.toJS(this.value, arg, ctx);
- }
- toString() {
- return String(this.value);
- }
-}
-Scalar.BLOCK_FOLDED = 'BLOCK_FOLDED';
-Scalar.BLOCK_LITERAL = 'BLOCK_LITERAL';
-Scalar.PLAIN = 'PLAIN';
-Scalar.QUOTE_DOUBLE = 'QUOTE_DOUBLE';
-Scalar.QUOTE_SINGLE = 'QUOTE_SINGLE';
-
-exports.Scalar = Scalar;
-exports.isScalarValue = isScalarValue;
-
-
-/***/ }),
-
-/***/ 4454:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var stringifyCollection = __nccwpck_require__(1212);
-var addPairToJSMap = __nccwpck_require__(7104);
-var Collection = __nccwpck_require__(101);
-var identity = __nccwpck_require__(1127);
-var Pair = __nccwpck_require__(7165);
-var Scalar = __nccwpck_require__(3301);
-
-function findPair(items, key) {
- const k = identity.isScalar(key) ? key.value : key;
- for (const it of items) {
- if (identity.isPair(it)) {
- if (it.key === key || it.key === k)
- return it;
- if (identity.isScalar(it.key) && it.key.value === k)
- return it;
- }
- }
- return undefined;
-}
-class YAMLMap extends Collection.Collection {
- static get tagName() {
- return 'tag:yaml.org,2002:map';
- }
- constructor(schema) {
- super(identity.MAP, schema);
- this.items = [];
- }
- /**
- * A generic collection parsing method that can be extended
- * to other node classes that inherit from YAMLMap
- */
- static from(schema, obj, ctx) {
- const { keepUndefined, replacer } = ctx;
- const map = new this(schema);
- const add = (key, value) => {
- if (typeof replacer === 'function')
- value = replacer.call(obj, key, value);
- else if (Array.isArray(replacer) && !replacer.includes(key))
- return;
- if (value !== undefined || keepUndefined)
- map.items.push(Pair.createPair(key, value, ctx));
- };
- if (obj instanceof Map) {
- for (const [key, value] of obj)
- add(key, value);
- }
- else if (obj && typeof obj === 'object') {
- for (const key of Object.keys(obj))
- add(key, obj[key]);
- }
- if (typeof schema.sortMapEntries === 'function') {
- map.items.sort(schema.sortMapEntries);
- }
- return map;
- }
- /**
- * Adds a value to the collection.
- *
- * @param overwrite - If not set `true`, using a key that is already in the
- * collection will throw. Otherwise, overwrites the previous value.
- */
- add(pair, overwrite) {
- let _pair;
- if (identity.isPair(pair))
- _pair = pair;
- else if (!pair || typeof pair !== 'object' || !('key' in pair)) {
- // In TypeScript, this never happens.
- _pair = new Pair.Pair(pair, pair?.value);
- }
- else
- _pair = new Pair.Pair(pair.key, pair.value);
- const prev = findPair(this.items, _pair.key);
- const sortEntries = this.schema?.sortMapEntries;
- if (prev) {
- if (!overwrite)
- throw new Error(`Key ${_pair.key} already set`);
- // For scalars, keep the old node & its comments and anchors
- if (identity.isScalar(prev.value) && Scalar.isScalarValue(_pair.value))
- prev.value.value = _pair.value;
- else
- prev.value = _pair.value;
- }
- else if (sortEntries) {
- const i = this.items.findIndex(item => sortEntries(_pair, item) < 0);
- if (i === -1)
- this.items.push(_pair);
- else
- this.items.splice(i, 0, _pair);
- }
- else {
- this.items.push(_pair);
- }
- }
- delete(key) {
- const it = findPair(this.items, key);
- if (!it)
- return false;
- const del = this.items.splice(this.items.indexOf(it), 1);
- return del.length > 0;
- }
- get(key, keepScalar) {
- const it = findPair(this.items, key);
- const node = it?.value;
- return (!keepScalar && identity.isScalar(node) ? node.value : node) ?? undefined;
- }
- has(key) {
- return !!findPair(this.items, key);
- }
- set(key, value) {
- this.add(new Pair.Pair(key, value), true);
- }
- /**
- * @param ctx - Conversion context, originally set in Document#toJS()
- * @param {Class} Type - If set, forces the returned collection type
- * @returns Instance of Type, Map, or Object
- */
- toJSON(_, ctx, Type) {
- const map = Type ? new Type() : ctx?.mapAsMap ? new Map() : {};
- if (ctx?.onCreate)
- ctx.onCreate(map);
- for (const item of this.items)
- addPairToJSMap.addPairToJSMap(ctx, map, item);
- return map;
- }
- toString(ctx, onComment, onChompKeep) {
- if (!ctx)
- return JSON.stringify(this);
- for (const item of this.items) {
- if (!identity.isPair(item))
- throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`);
- }
- if (!ctx.allNullValues && this.hasAllNullValues(false))
- ctx = Object.assign({}, ctx, { allNullValues: true });
- return stringifyCollection.stringifyCollection(this, ctx, {
- blockItemPrefix: '',
- flowChars: { start: '{', end: '}' },
- itemIndent: ctx.indent || '',
- onChompKeep,
- onComment
- });
- }
-}
-
-exports.YAMLMap = YAMLMap;
-exports.findPair = findPair;
-
-
-/***/ }),
-
-/***/ 2223:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var createNode = __nccwpck_require__(2404);
-var stringifyCollection = __nccwpck_require__(1212);
-var Collection = __nccwpck_require__(101);
-var identity = __nccwpck_require__(1127);
-var Scalar = __nccwpck_require__(3301);
-var toJS = __nccwpck_require__(4043);
-
-class YAMLSeq extends Collection.Collection {
- static get tagName() {
- return 'tag:yaml.org,2002:seq';
- }
- constructor(schema) {
- super(identity.SEQ, schema);
- this.items = [];
- }
- add(value) {
- this.items.push(value);
- }
- /**
- * Removes a value from the collection.
- *
- * `key` must contain a representation of an integer for this to succeed.
- * It may be wrapped in a `Scalar`.
- *
- * @returns `true` if the item was found and removed.
- */
- delete(key) {
- const idx = asItemIndex(key);
- if (typeof idx !== 'number')
- return false;
- const del = this.items.splice(idx, 1);
- return del.length > 0;
- }
- get(key, keepScalar) {
- const idx = asItemIndex(key);
- if (typeof idx !== 'number')
- return undefined;
- const it = this.items[idx];
- return !keepScalar && identity.isScalar(it) ? it.value : it;
- }
- /**
- * Checks if the collection includes a value with the key `key`.
- *
- * `key` must contain a representation of an integer for this to succeed.
- * It may be wrapped in a `Scalar`.
- */
- has(key) {
- const idx = asItemIndex(key);
- return typeof idx === 'number' && idx < this.items.length;
- }
- /**
- * Sets a value in this collection. For `!!set`, `value` needs to be a
- * boolean to add/remove the item from the set.
- *
- * If `key` does not contain a representation of an integer, this will throw.
- * It may be wrapped in a `Scalar`.
- */
- set(key, value) {
- const idx = asItemIndex(key);
- if (typeof idx !== 'number')
- throw new Error(`Expected a valid index, not ${key}.`);
- const prev = this.items[idx];
- if (identity.isScalar(prev) && Scalar.isScalarValue(value))
- prev.value = value;
- else
- this.items[idx] = value;
- }
- toJSON(_, ctx) {
- const seq = [];
- if (ctx?.onCreate)
- ctx.onCreate(seq);
- let i = 0;
- for (const item of this.items)
- seq.push(toJS.toJS(item, String(i++), ctx));
- return seq;
- }
- toString(ctx, onComment, onChompKeep) {
- if (!ctx)
- return JSON.stringify(this);
- return stringifyCollection.stringifyCollection(this, ctx, {
- blockItemPrefix: '- ',
- flowChars: { start: '[', end: ']' },
- itemIndent: (ctx.indent || '') + ' ',
- onChompKeep,
- onComment
- });
- }
- static from(schema, obj, ctx) {
- const { replacer } = ctx;
- const seq = new this(schema);
- if (obj && Symbol.iterator in Object(obj)) {
- let i = 0;
- for (let it of obj) {
- if (typeof replacer === 'function') {
- const key = obj instanceof Set ? it : String(i++);
- it = replacer.call(obj, key, it);
- }
- seq.items.push(createNode.createNode(it, undefined, ctx));
- }
- }
- return seq;
- }
-}
-function asItemIndex(key) {
- let idx = identity.isScalar(key) ? key.value : key;
- if (idx && typeof idx === 'string')
- idx = Number(idx);
- return typeof idx === 'number' && Number.isInteger(idx) && idx >= 0
- ? idx
- : null;
-}
-
-exports.YAMLSeq = YAMLSeq;
-
-
-/***/ }),
-
-/***/ 7104:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var log = __nccwpck_require__(7249);
-var merge = __nccwpck_require__(452);
-var stringify = __nccwpck_require__(9767);
-var identity = __nccwpck_require__(1127);
-var toJS = __nccwpck_require__(4043);
-
-function addPairToJSMap(ctx, map, { key, value }) {
- if (identity.isNode(key) && key.addToJSMap)
- key.addToJSMap(ctx, map, value);
- // TODO: Should drop this special case for bare << handling
- else if (merge.isMergeKey(ctx, key))
- merge.addMergeToJSMap(ctx, map, value);
- else {
- const jsKey = toJS.toJS(key, '', ctx);
- if (map instanceof Map) {
- map.set(jsKey, toJS.toJS(value, jsKey, ctx));
- }
- else if (map instanceof Set) {
- map.add(jsKey);
- }
- else {
- const stringKey = stringifyKey(key, jsKey, ctx);
- const jsValue = toJS.toJS(value, stringKey, ctx);
- if (stringKey in map)
- Object.defineProperty(map, stringKey, {
- value: jsValue,
- writable: true,
- enumerable: true,
- configurable: true
- });
- else
- map[stringKey] = jsValue;
- }
- }
- return map;
-}
-function stringifyKey(key, jsKey, ctx) {
- if (jsKey === null)
- return '';
- // eslint-disable-next-line @typescript-eslint/no-base-to-string
- if (typeof jsKey !== 'object')
- return String(jsKey);
- if (identity.isNode(key) && ctx?.doc) {
- const strCtx = stringify.createStringifyContext(ctx.doc, {});
- strCtx.anchors = new Set();
- for (const node of ctx.anchors.keys())
- strCtx.anchors.add(node.anchor);
- strCtx.inFlow = true;
- strCtx.inStringifyKey = true;
- const strKey = key.toString(strCtx);
- if (!ctx.mapKeyWarned) {
- let jsonStr = JSON.stringify(strKey);
- if (jsonStr.length > 40)
- jsonStr = jsonStr.substring(0, 36) + '..."';
- log.warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`);
- ctx.mapKeyWarned = true;
- }
- return strKey;
- }
- return JSON.stringify(jsKey);
-}
-
-exports.addPairToJSMap = addPairToJSMap;
-
-
-/***/ }),
-
-/***/ 1127:
-/***/ ((__unused_webpack_module, exports) => {
-
-
-
-const ALIAS = Symbol.for('yaml.alias');
-const DOC = Symbol.for('yaml.document');
-const MAP = Symbol.for('yaml.map');
-const PAIR = Symbol.for('yaml.pair');
-const SCALAR = Symbol.for('yaml.scalar');
-const SEQ = Symbol.for('yaml.seq');
-const NODE_TYPE = Symbol.for('yaml.node.type');
-const isAlias = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === ALIAS;
-const isDocument = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === DOC;
-const isMap = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === MAP;
-const isPair = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === PAIR;
-const isScalar = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SCALAR;
-const isSeq = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SEQ;
-function isCollection(node) {
- if (node && typeof node === 'object')
- switch (node[NODE_TYPE]) {
- case MAP:
- case SEQ:
- return true;
- }
- return false;
-}
-function isNode(node) {
- if (node && typeof node === 'object')
- switch (node[NODE_TYPE]) {
- case ALIAS:
- case MAP:
- case SCALAR:
- case SEQ:
- return true;
- }
- return false;
-}
-const hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor;
-
-exports.ALIAS = ALIAS;
-exports.DOC = DOC;
-exports.MAP = MAP;
-exports.NODE_TYPE = NODE_TYPE;
-exports.PAIR = PAIR;
-exports.SCALAR = SCALAR;
-exports.SEQ = SEQ;
-exports.hasAnchor = hasAnchor;
-exports.isAlias = isAlias;
-exports.isCollection = isCollection;
-exports.isDocument = isDocument;
-exports.isMap = isMap;
-exports.isNode = isNode;
-exports.isPair = isPair;
-exports.isScalar = isScalar;
-exports.isSeq = isSeq;
-
-
-/***/ }),
-
-/***/ 4043:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var identity = __nccwpck_require__(1127);
-
-/**
- * Recursively convert any node or its contents to native JavaScript
- *
- * @param value - The input value
- * @param arg - If `value` defines a `toJSON()` method, use this
- * as its first argument
- * @param ctx - Conversion context, originally set in Document#toJS(). If
- * `{ keep: true }` is not set, output should be suitable for JSON
- * stringification.
- */
-function toJS(value, arg, ctx) {
- // eslint-disable-next-line @typescript-eslint/no-unsafe-return
- if (Array.isArray(value))
- return value.map((v, i) => toJS(v, String(i), ctx));
- if (value && typeof value.toJSON === 'function') {
- // eslint-disable-next-line @typescript-eslint/no-unsafe-call
- if (!ctx || !identity.hasAnchor(value))
- return value.toJSON(arg, ctx);
- const data = { aliasCount: 0, count: 1, res: undefined };
- ctx.anchors.set(value, data);
- ctx.onCreate = res => {
- data.res = res;
- delete ctx.onCreate;
- };
- const res = value.toJSON(arg, ctx);
- if (ctx.onCreate)
- ctx.onCreate(res);
- return res;
- }
- if (typeof value === 'bigint' && !ctx?.keep)
- return Number(value);
- return value;
-}
-
-exports.toJS = toJS;
-
-
-/***/ }),
-
-/***/ 110:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var resolveBlockScalar = __nccwpck_require__(8913);
-var resolveFlowScalar = __nccwpck_require__(6842);
-var errors = __nccwpck_require__(1464);
-var stringifyString = __nccwpck_require__(5450);
-
-function resolveAsScalar(token, strict = true, onError) {
- if (token) {
- const _onError = (pos, code, message) => {
- const offset = typeof pos === 'number' ? pos : Array.isArray(pos) ? pos[0] : pos.offset;
- if (onError)
- onError(offset, code, message);
- else
- throw new errors.YAMLParseError([offset, offset + 1], code, message);
- };
- switch (token.type) {
- case 'scalar':
- case 'single-quoted-scalar':
- case 'double-quoted-scalar':
- return resolveFlowScalar.resolveFlowScalar(token, strict, _onError);
- case 'block-scalar':
- return resolveBlockScalar.resolveBlockScalar({ options: { strict } }, token, _onError);
- }
- }
- return null;
-}
-/**
- * Create a new scalar token with `value`
- *
- * Values that represent an actual string but may be parsed as a different type should use a `type` other than `'PLAIN'`,
- * as this function does not support any schema operations and won't check for such conflicts.
- *
- * @param value The string representation of the value, which will have its content properly indented.
- * @param context.end Comments and whitespace after the end of the value, or after the block scalar header. If undefined, a newline will be added.
- * @param context.implicitKey Being within an implicit key may affect the resolved type of the token's value.
- * @param context.indent The indent level of the token.
- * @param context.inFlow Is this scalar within a flow collection? This may affect the resolved type of the token's value.
- * @param context.offset The offset position of the token.
- * @param context.type The preferred type of the scalar token. If undefined, the previous type of the `token` will be used, defaulting to `'PLAIN'`.
- */
-function createScalarToken(value, context) {
- const { implicitKey = false, indent, inFlow = false, offset = -1, type = 'PLAIN' } = context;
- const source = stringifyString.stringifyString({ type, value }, {
- implicitKey,
- indent: indent > 0 ? ' '.repeat(indent) : '',
- inFlow,
- options: { blockQuote: true, lineWidth: -1 }
- });
- const end = context.end ?? [
- { type: 'newline', offset: -1, indent, source: '\n' }
- ];
- switch (source[0]) {
- case '|':
- case '>': {
- const he = source.indexOf('\n');
- const head = source.substring(0, he);
- const body = source.substring(he + 1) + '\n';
- const props = [
- { type: 'block-scalar-header', offset, indent, source: head }
- ];
- if (!addEndtoBlockProps(props, end))
- props.push({ type: 'newline', offset: -1, indent, source: '\n' });
- return { type: 'block-scalar', offset, indent, props, source: body };
- }
- case '"':
- return { type: 'double-quoted-scalar', offset, indent, source, end };
- case "'":
- return { type: 'single-quoted-scalar', offset, indent, source, end };
- default:
- return { type: 'scalar', offset, indent, source, end };
- }
-}
-/**
- * Set the value of `token` to the given string `value`, overwriting any previous contents and type that it may have.
- *
- * Best efforts are made to retain any comments previously associated with the `token`,
- * though all contents within a collection's `items` will be overwritten.
- *
- * Values that represent an actual string but may be parsed as a different type should use a `type` other than `'PLAIN'`,
- * as this function does not support any schema operations and won't check for such conflicts.
- *
- * @param token Any token. If it does not include an `indent` value, the value will be stringified as if it were an implicit key.
- * @param value The string representation of the value, which will have its content properly indented.
- * @param context.afterKey In most cases, values after a key should have an additional level of indentation.
- * @param context.implicitKey Being within an implicit key may affect the resolved type of the token's value.
- * @param context.inFlow Being within a flow collection may affect the resolved type of the token's value.
- * @param context.type The preferred type of the scalar token. If undefined, the previous type of the `token` will be used, defaulting to `'PLAIN'`.
- */
-function setScalarValue(token, value, context = {}) {
- let { afterKey = false, implicitKey = false, inFlow = false, type } = context;
- let indent = 'indent' in token ? token.indent : null;
- if (afterKey && typeof indent === 'number')
- indent += 2;
- if (!type)
- switch (token.type) {
- case 'single-quoted-scalar':
- type = 'QUOTE_SINGLE';
- break;
- case 'double-quoted-scalar':
- type = 'QUOTE_DOUBLE';
- break;
- case 'block-scalar': {
- const header = token.props[0];
- if (header.type !== 'block-scalar-header')
- throw new Error('Invalid block scalar header');
- type = header.source[0] === '>' ? 'BLOCK_FOLDED' : 'BLOCK_LITERAL';
- break;
- }
- default:
- type = 'PLAIN';
- }
- const source = stringifyString.stringifyString({ type, value }, {
- implicitKey: implicitKey || indent === null,
- indent: indent !== null && indent > 0 ? ' '.repeat(indent) : '',
- inFlow,
- options: { blockQuote: true, lineWidth: -1 }
- });
- switch (source[0]) {
- case '|':
- case '>':
- setBlockScalarValue(token, source);
- break;
- case '"':
- setFlowScalarValue(token, source, 'double-quoted-scalar');
- break;
- case "'":
- setFlowScalarValue(token, source, 'single-quoted-scalar');
- break;
- default:
- setFlowScalarValue(token, source, 'scalar');
- }
-}
-function setBlockScalarValue(token, source) {
- const he = source.indexOf('\n');
- const head = source.substring(0, he);
- const body = source.substring(he + 1) + '\n';
- if (token.type === 'block-scalar') {
- const header = token.props[0];
- if (header.type !== 'block-scalar-header')
- throw new Error('Invalid block scalar header');
- header.source = head;
- token.source = body;
- }
- else {
- const { offset } = token;
- const indent = 'indent' in token ? token.indent : -1;
- const props = [
- { type: 'block-scalar-header', offset, indent, source: head }
- ];
- if (!addEndtoBlockProps(props, 'end' in token ? token.end : undefined))
- props.push({ type: 'newline', offset: -1, indent, source: '\n' });
- for (const key of Object.keys(token))
- if (key !== 'type' && key !== 'offset')
- delete token[key];
- Object.assign(token, { type: 'block-scalar', indent, props, source: body });
- }
-}
-/** @returns `true` if last token is a newline */
-function addEndtoBlockProps(props, end) {
- if (end)
- for (const st of end)
- switch (st.type) {
- case 'space':
- case 'comment':
- props.push(st);
- break;
- case 'newline':
- props.push(st);
- return true;
- }
- return false;
-}
-function setFlowScalarValue(token, source, type) {
- switch (token.type) {
- case 'scalar':
- case 'double-quoted-scalar':
- case 'single-quoted-scalar':
- token.type = type;
- token.source = source;
- break;
- case 'block-scalar': {
- const end = token.props.slice(1);
- let oa = source.length;
- if (token.props[0].type === 'block-scalar-header')
- oa -= token.props[0].source.length;
- for (const tok of end)
- tok.offset += oa;
- delete token.props;
- Object.assign(token, { type, source, end });
- break;
- }
- case 'block-map':
- case 'block-seq': {
- const offset = token.offset + source.length;
- const nl = { type: 'newline', offset, indent: token.indent, source: '\n' };
- delete token.items;
- Object.assign(token, { type, source, end: [nl] });
- break;
- }
- default: {
- const indent = 'indent' in token ? token.indent : -1;
- const end = 'end' in token && Array.isArray(token.end)
- ? token.end.filter(st => st.type === 'space' ||
- st.type === 'comment' ||
- st.type === 'newline')
- : [];
- for (const key of Object.keys(token))
- if (key !== 'type' && key !== 'offset')
- delete token[key];
- Object.assign(token, { type, indent, source, end });
- }
- }
-}
-
-exports.createScalarToken = createScalarToken;
-exports.resolveAsScalar = resolveAsScalar;
-exports.setScalarValue = setScalarValue;
-
-
-/***/ }),
-
-/***/ 1733:
-/***/ ((__unused_webpack_module, exports) => {
-
-
-
-/**
- * Stringify a CST document, token, or collection item
- *
- * Fair warning: This applies no validation whatsoever, and
- * simply concatenates the sources in their logical order.
- */
-const stringify = (cst) => 'type' in cst ? stringifyToken(cst) : stringifyItem(cst);
-function stringifyToken(token) {
- switch (token.type) {
- case 'block-scalar': {
- let res = '';
- for (const tok of token.props)
- res += stringifyToken(tok);
- return res + token.source;
- }
- case 'block-map':
- case 'block-seq': {
- let res = '';
- for (const item of token.items)
- res += stringifyItem(item);
- return res;
- }
- case 'flow-collection': {
- let res = token.start.source;
- for (const item of token.items)
- res += stringifyItem(item);
- for (const st of token.end)
- res += st.source;
- return res;
- }
- case 'document': {
- let res = stringifyItem(token);
- if (token.end)
- for (const st of token.end)
- res += st.source;
- return res;
- }
- default: {
- let res = token.source;
- if ('end' in token && token.end)
- for (const st of token.end)
- res += st.source;
- return res;
- }
- }
-}
-function stringifyItem({ start, key, sep, value }) {
- let res = '';
- for (const st of start)
- res += st.source;
- if (key)
- res += stringifyToken(key);
- if (sep)
- for (const st of sep)
- res += st.source;
- if (value)
- res += stringifyToken(value);
- return res;
-}
-
-exports.stringify = stringify;
-
-
-/***/ }),
-
-/***/ 7715:
-/***/ ((__unused_webpack_module, exports) => {
-
-
-
-const BREAK = Symbol('break visit');
-const SKIP = Symbol('skip children');
-const REMOVE = Symbol('remove item');
-/**
- * Apply a visitor to a CST document or item.
- *
- * Walks through the tree (depth-first) starting from the root, calling a
- * `visitor` function with two arguments when entering each item:
- * - `item`: The current item, which included the following members:
- * - `start: SourceToken[]` – Source tokens before the key or value,
- * possibly including its anchor or tag.
- * - `key?: Token | null` – Set for pair values. May then be `null`, if
- * the key before the `:` separator is empty.
- * - `sep?: SourceToken[]` – Source tokens between the key and the value,
- * which should include the `:` map value indicator if `value` is set.
- * - `value?: Token` – The value of a sequence item, or of a map pair.
- * - `path`: The steps from the root to the current node, as an array of
- * `['key' | 'value', number]` tuples.
- *
- * The return value of the visitor may be used to control the traversal:
- * - `undefined` (default): Do nothing and continue
- * - `visit.SKIP`: Do not visit the children of this token, continue with
- * next sibling
- * - `visit.BREAK`: Terminate traversal completely
- * - `visit.REMOVE`: Remove the current item, then continue with the next one
- * - `number`: Set the index of the next step. This is useful especially if
- * the index of the current token has changed.
- * - `function`: Define the next visitor for this item. After the original
- * visitor is called on item entry, next visitors are called after handling
- * a non-empty `key` and when exiting the item.
- */
-function visit(cst, visitor) {
- if ('type' in cst && cst.type === 'document')
- cst = { start: cst.start, value: cst.value };
- _visit(Object.freeze([]), cst, visitor);
-}
-// Without the `as symbol` casts, TS declares these in the `visit`
-// namespace using `var`, but then complains about that because
-// `unique symbol` must be `const`.
-/** Terminate visit traversal completely */
-visit.BREAK = BREAK;
-/** Do not visit the children of the current item */
-visit.SKIP = SKIP;
-/** Remove the current item */
-visit.REMOVE = REMOVE;
-/** Find the item at `path` from `cst` as the root */
-visit.itemAtPath = (cst, path) => {
- let item = cst;
- for (const [field, index] of path) {
- const tok = item?.[field];
- if (tok && 'items' in tok) {
- item = tok.items[index];
- }
- else
- return undefined;
- }
- return item;
-};
-/**
- * Get the immediate parent collection of the item at `path` from `cst` as the root.
- *
- * Throws an error if the collection is not found, which should never happen if the item itself exists.
- */
-visit.parentCollection = (cst, path) => {
- const parent = visit.itemAtPath(cst, path.slice(0, -1));
- const field = path[path.length - 1][0];
- const coll = parent?.[field];
- if (coll && 'items' in coll)
- return coll;
- throw new Error('Parent collection not found');
-};
-function _visit(path, item, visitor) {
- let ctrl = visitor(item, path);
- if (typeof ctrl === 'symbol')
- return ctrl;
- for (const field of ['key', 'value']) {
- const token = item[field];
- if (token && 'items' in token) {
- for (let i = 0; i < token.items.length; ++i) {
- const ci = _visit(Object.freeze(path.concat([[field, i]])), token.items[i], visitor);
- if (typeof ci === 'number')
- i = ci - 1;
- else if (ci === BREAK)
- return BREAK;
- else if (ci === REMOVE) {
- token.items.splice(i, 1);
- i -= 1;
- }
- }
- if (typeof ctrl === 'function' && field === 'key')
- ctrl = ctrl(item, path);
- }
- }
- return typeof ctrl === 'function' ? ctrl(item, path) : ctrl;
-}
-
-exports.visit = visit;
-
-
-/***/ }),
-
-/***/ 3461:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var cstScalar = __nccwpck_require__(110);
-var cstStringify = __nccwpck_require__(1733);
-var cstVisit = __nccwpck_require__(7715);
-
-/** The byte order mark */
-const BOM = '\u{FEFF}';
-/** Start of doc-mode */
-const DOCUMENT = '\x02'; // C0: Start of Text
-/** Unexpected end of flow-mode */
-const FLOW_END = '\x18'; // C0: Cancel
-/** Next token is a scalar value */
-const SCALAR = '\x1f'; // C0: Unit Separator
-/** @returns `true` if `token` is a flow or block collection */
-const isCollection = (token) => !!token && 'items' in token;
-/** @returns `true` if `token` is a flow or block scalar; not an alias */
-const isScalar = (token) => !!token &&
- (token.type === 'scalar' ||
- token.type === 'single-quoted-scalar' ||
- token.type === 'double-quoted-scalar' ||
- token.type === 'block-scalar');
-/* istanbul ignore next */
-/** Get a printable representation of a lexer token */
-function prettyToken(token) {
- switch (token) {
- case BOM:
- return '';
- case DOCUMENT:
- return '';
- case FLOW_END:
- return '';
- case SCALAR:
- return '';
- default:
- return JSON.stringify(token);
- }
-}
-/** Identify the type of a lexer token. May return `null` for unknown tokens. */
-function tokenType(source) {
- switch (source) {
- case BOM:
- return 'byte-order-mark';
- case DOCUMENT:
- return 'doc-mode';
- case FLOW_END:
- return 'flow-error-end';
- case SCALAR:
- return 'scalar';
- case '---':
- return 'doc-start';
- case '...':
- return 'doc-end';
- case '':
- case '\n':
- case '\r\n':
- return 'newline';
- case '-':
- return 'seq-item-ind';
- case '?':
- return 'explicit-key-ind';
- case ':':
- return 'map-value-ind';
- case '{':
- return 'flow-map-start';
- case '}':
- return 'flow-map-end';
- case '[':
- return 'flow-seq-start';
- case ']':
- return 'flow-seq-end';
- case ',':
- return 'comma';
- }
- switch (source[0]) {
- case ' ':
- case '\t':
- return 'space';
- case '#':
- return 'comment';
- case '%':
- return 'directive-line';
- case '*':
- return 'alias';
- case '&':
- return 'anchor';
- case '!':
- return 'tag';
- case "'":
- return 'single-quoted-scalar';
- case '"':
- return 'double-quoted-scalar';
- case '|':
- case '>':
- return 'block-scalar-header';
- }
- return null;
-}
-
-exports.createScalarToken = cstScalar.createScalarToken;
-exports.resolveAsScalar = cstScalar.resolveAsScalar;
-exports.setScalarValue = cstScalar.setScalarValue;
-exports.stringify = cstStringify.stringify;
-exports.visit = cstVisit.visit;
-exports.BOM = BOM;
-exports.DOCUMENT = DOCUMENT;
-exports.FLOW_END = FLOW_END;
-exports.SCALAR = SCALAR;
-exports.isCollection = isCollection;
-exports.isScalar = isScalar;
-exports.prettyToken = prettyToken;
-exports.tokenType = tokenType;
-
-
-/***/ }),
-
-/***/ 361:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var cst = __nccwpck_require__(3461);
-
-/*
-START -> stream
-
-stream
- directive -> line-end -> stream
- indent + line-end -> stream
- [else] -> line-start
-
-line-end
- comment -> line-end
- newline -> .
- input-end -> END
-
-line-start
- doc-start -> doc
- doc-end -> stream
- [else] -> indent -> block-start
-
-block-start
- seq-item-start -> block-start
- explicit-key-start -> block-start
- map-value-start -> block-start
- [else] -> doc
-
-doc
- line-end -> line-start
- spaces -> doc
- anchor -> doc
- tag -> doc
- flow-start -> flow -> doc
- flow-end -> error -> doc
- seq-item-start -> error -> doc
- explicit-key-start -> error -> doc
- map-value-start -> doc
- alias -> doc
- quote-start -> quoted-scalar -> doc
- block-scalar-header -> line-end -> block-scalar(min) -> line-start
- [else] -> plain-scalar(false, min) -> doc
-
-flow
- line-end -> flow
- spaces -> flow
- anchor -> flow
- tag -> flow
- flow-start -> flow -> flow
- flow-end -> .
- seq-item-start -> error -> flow
- explicit-key-start -> flow
- map-value-start -> flow
- alias -> flow
- quote-start -> quoted-scalar -> flow
- comma -> flow
- [else] -> plain-scalar(true, 0) -> flow
-
-quoted-scalar
- quote-end -> .
- [else] -> quoted-scalar
-
-block-scalar(min)
- newline + peek(indent < min) -> .
- [else] -> block-scalar(min)
-
-plain-scalar(is-flow, min)
- scalar-end(is-flow) -> .
- peek(newline + (indent < min)) -> .
- [else] -> plain-scalar(min)
-*/
-function isEmpty(ch) {
- switch (ch) {
- case undefined:
- case ' ':
- case '\n':
- case '\r':
- case '\t':
- return true;
- default:
- return false;
- }
-}
-const hexDigits = new Set('0123456789ABCDEFabcdef');
-const tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()");
-const flowIndicatorChars = new Set(',[]{}');
-const invalidAnchorChars = new Set(' ,[]{}\n\r\t');
-const isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch);
-/**
- * Splits an input string into lexical tokens, i.e. smaller strings that are
- * easily identifiable by `tokens.tokenType()`.
- *
- * Lexing starts always in a "stream" context. Incomplete input may be buffered
- * until a complete token can be emitted.
- *
- * In addition to slices of the original input, the following control characters
- * may also be emitted:
- *
- * - `\x02` (Start of Text): A document starts with the next token
- * - `\x18` (Cancel): Unexpected end of flow-mode (indicates an error)
- * - `\x1f` (Unit Separator): Next token is a scalar value
- * - `\u{FEFF}` (Byte order mark): Emitted separately outside documents
- */
-class Lexer {
- constructor() {
- /**
- * Flag indicating whether the end of the current buffer marks the end of
- * all input
- */
- this.atEnd = false;
- /**
- * Explicit indent set in block scalar header, as an offset from the current
- * minimum indent, so e.g. set to 1 from a header `|2+`. Set to -1 if not
- * explicitly set.
- */
- this.blockScalarIndent = -1;
- /**
- * Block scalars that include a + (keep) chomping indicator in their header
- * include trailing empty lines, which are otherwise excluded from the
- * scalar's contents.
- */
- this.blockScalarKeep = false;
- /** Current input */
- this.buffer = '';
- /**
- * Flag noting whether the map value indicator : can immediately follow this
- * node within a flow context.
- */
- this.flowKey = false;
- /** Count of surrounding flow collection levels. */
- this.flowLevel = 0;
- /**
- * Minimum level of indentation required for next lines to be parsed as a
- * part of the current scalar value.
- */
- this.indentNext = 0;
- /** Indentation level of the current line. */
- this.indentValue = 0;
- /** Position of the next \n character. */
- this.lineEndPos = null;
- /** Stores the state of the lexer if reaching the end of incpomplete input */
- this.next = null;
- /** A pointer to `buffer`; the current position of the lexer. */
- this.pos = 0;
- }
- /**
- * Generate YAML tokens from the `source` string. If `incomplete`,
- * a part of the last line may be left as a buffer for the next call.
- *
- * @returns A generator of lexical tokens
- */
- *lex(source, incomplete = false) {
- if (source) {
- if (typeof source !== 'string')
- throw TypeError('source is not a string');
- this.buffer = this.buffer ? this.buffer + source : source;
- this.lineEndPos = null;
- }
- this.atEnd = !incomplete;
- let next = this.next ?? 'stream';
- while (next && (incomplete || this.hasChars(1)))
- next = yield* this.parseNext(next);
- }
- atLineEnd() {
- let i = this.pos;
- let ch = this.buffer[i];
- while (ch === ' ' || ch === '\t')
- ch = this.buffer[++i];
- if (!ch || ch === '#' || ch === '\n')
- return true;
- if (ch === '\r')
- return this.buffer[i + 1] === '\n';
- return false;
- }
- charAt(n) {
- return this.buffer[this.pos + n];
- }
- continueScalar(offset) {
- let ch = this.buffer[offset];
- if (this.indentNext > 0) {
- let indent = 0;
- while (ch === ' ')
- ch = this.buffer[++indent + offset];
- if (ch === '\r') {
- const next = this.buffer[indent + offset + 1];
- if (next === '\n' || (!next && !this.atEnd))
- return offset + indent + 1;
- }
- return ch === '\n' || indent >= this.indentNext || (!ch && !this.atEnd)
- ? offset + indent
- : -1;
- }
- if (ch === '-' || ch === '.') {
- const dt = this.buffer.substr(offset, 3);
- if ((dt === '---' || dt === '...') && isEmpty(this.buffer[offset + 3]))
- return -1;
- }
- return offset;
- }
- getLine() {
- let end = this.lineEndPos;
- if (typeof end !== 'number' || (end !== -1 && end < this.pos)) {
- end = this.buffer.indexOf('\n', this.pos);
- this.lineEndPos = end;
- }
- if (end === -1)
- return this.atEnd ? this.buffer.substring(this.pos) : null;
- if (this.buffer[end - 1] === '\r')
- end -= 1;
- return this.buffer.substring(this.pos, end);
- }
- hasChars(n) {
- return this.pos + n <= this.buffer.length;
- }
- setNext(state) {
- this.buffer = this.buffer.substring(this.pos);
- this.pos = 0;
- this.lineEndPos = null;
- this.next = state;
- return null;
- }
- peek(n) {
- return this.buffer.substr(this.pos, n);
- }
- *parseNext(next) {
- switch (next) {
- case 'stream':
- return yield* this.parseStream();
- case 'line-start':
- return yield* this.parseLineStart();
- case 'block-start':
- return yield* this.parseBlockStart();
- case 'doc':
- return yield* this.parseDocument();
- case 'flow':
- return yield* this.parseFlowCollection();
- case 'quoted-scalar':
- return yield* this.parseQuotedScalar();
- case 'block-scalar':
- return yield* this.parseBlockScalar();
- case 'plain-scalar':
- return yield* this.parsePlainScalar();
- }
- }
- *parseStream() {
- let line = this.getLine();
- if (line === null)
- return this.setNext('stream');
- if (line[0] === cst.BOM) {
- yield* this.pushCount(1);
- line = line.substring(1);
- }
- if (line[0] === '%') {
- let dirEnd = line.length;
- let cs = line.indexOf('#');
- while (cs !== -1) {
- const ch = line[cs - 1];
- if (ch === ' ' || ch === '\t') {
- dirEnd = cs - 1;
- break;
- }
- else {
- cs = line.indexOf('#', cs + 1);
- }
- }
- while (true) {
- const ch = line[dirEnd - 1];
- if (ch === ' ' || ch === '\t')
- dirEnd -= 1;
- else
- break;
- }
- const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true));
- yield* this.pushCount(line.length - n); // possible comment
- this.pushNewline();
- return 'stream';
- }
- if (this.atLineEnd()) {
- const sp = yield* this.pushSpaces(true);
- yield* this.pushCount(line.length - sp);
- yield* this.pushNewline();
- return 'stream';
- }
- yield cst.DOCUMENT;
- return yield* this.parseLineStart();
- }
- *parseLineStart() {
- const ch = this.charAt(0);
- if (!ch && !this.atEnd)
- return this.setNext('line-start');
- if (ch === '-' || ch === '.') {
- if (!this.atEnd && !this.hasChars(4))
- return this.setNext('line-start');
- const s = this.peek(3);
- if ((s === '---' || s === '...') && isEmpty(this.charAt(3))) {
- yield* this.pushCount(3);
- this.indentValue = 0;
- this.indentNext = 0;
- return s === '---' ? 'doc' : 'stream';
- }
- }
- this.indentValue = yield* this.pushSpaces(false);
- if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1)))
- this.indentNext = this.indentValue;
- return yield* this.parseBlockStart();
- }
- *parseBlockStart() {
- const [ch0, ch1] = this.peek(2);
- if (!ch1 && !this.atEnd)
- return this.setNext('block-start');
- if ((ch0 === '-' || ch0 === '?' || ch0 === ':') && isEmpty(ch1)) {
- const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true));
- this.indentNext = this.indentValue + 1;
- this.indentValue += n;
- return yield* this.parseBlockStart();
- }
- return 'doc';
- }
- *parseDocument() {
- yield* this.pushSpaces(true);
- const line = this.getLine();
- if (line === null)
- return this.setNext('doc');
- let n = yield* this.pushIndicators();
- switch (line[n]) {
- case '#':
- yield* this.pushCount(line.length - n);
- // fallthrough
- case undefined:
- yield* this.pushNewline();
- return yield* this.parseLineStart();
- case '{':
- case '[':
- yield* this.pushCount(1);
- this.flowKey = false;
- this.flowLevel = 1;
- return 'flow';
- case '}':
- case ']':
- // this is an error
- yield* this.pushCount(1);
- return 'doc';
- case '*':
- yield* this.pushUntil(isNotAnchorChar);
- return 'doc';
- case '"':
- case "'":
- return yield* this.parseQuotedScalar();
- case '|':
- case '>':
- n += yield* this.parseBlockScalarHeader();
- n += yield* this.pushSpaces(true);
- yield* this.pushCount(line.length - n);
- yield* this.pushNewline();
- return yield* this.parseBlockScalar();
- default:
- return yield* this.parsePlainScalar();
- }
- }
- *parseFlowCollection() {
- let nl, sp;
- let indent = -1;
- do {
- nl = yield* this.pushNewline();
- if (nl > 0) {
- sp = yield* this.pushSpaces(false);
- this.indentValue = indent = sp;
- }
- else {
- sp = 0;
- }
- sp += yield* this.pushSpaces(true);
- } while (nl + sp > 0);
- const line = this.getLine();
- if (line === null)
- return this.setNext('flow');
- if ((indent !== -1 && indent < this.indentNext && line[0] !== '#') ||
- (indent === 0 &&
- (line.startsWith('---') || line.startsWith('...')) &&
- isEmpty(line[3]))) {
- // Allowing for the terminal ] or } at the same (rather than greater)
- // indent level as the initial [ or { is technically invalid, but
- // failing here would be surprising to users.
- const atFlowEndMarker = indent === this.indentNext - 1 &&
- this.flowLevel === 1 &&
- (line[0] === ']' || line[0] === '}');
- if (!atFlowEndMarker) {
- // this is an error
- this.flowLevel = 0;
- yield cst.FLOW_END;
- return yield* this.parseLineStart();
- }
- }
- let n = 0;
- while (line[n] === ',') {
- n += yield* this.pushCount(1);
- n += yield* this.pushSpaces(true);
- this.flowKey = false;
- }
- n += yield* this.pushIndicators();
- switch (line[n]) {
- case undefined:
- return 'flow';
- case '#':
- yield* this.pushCount(line.length - n);
- return 'flow';
- case '{':
- case '[':
- yield* this.pushCount(1);
- this.flowKey = false;
- this.flowLevel += 1;
- return 'flow';
- case '}':
- case ']':
- yield* this.pushCount(1);
- this.flowKey = true;
- this.flowLevel -= 1;
- return this.flowLevel ? 'flow' : 'doc';
- case '*':
- yield* this.pushUntil(isNotAnchorChar);
- return 'flow';
- case '"':
- case "'":
- this.flowKey = true;
- return yield* this.parseQuotedScalar();
- case ':': {
- const next = this.charAt(1);
- if (this.flowKey || isEmpty(next) || next === ',') {
- this.flowKey = false;
- yield* this.pushCount(1);
- yield* this.pushSpaces(true);
- return 'flow';
- }
- }
- // fallthrough
- default:
- this.flowKey = false;
- return yield* this.parsePlainScalar();
- }
- }
- *parseQuotedScalar() {
- const quote = this.charAt(0);
- let end = this.buffer.indexOf(quote, this.pos + 1);
- if (quote === "'") {
- while (end !== -1 && this.buffer[end + 1] === "'")
- end = this.buffer.indexOf("'", end + 2);
- }
- else {
- // double-quote
- while (end !== -1) {
- let n = 0;
- while (this.buffer[end - 1 - n] === '\\')
- n += 1;
- if (n % 2 === 0)
- break;
- end = this.buffer.indexOf('"', end + 1);
- }
- }
- // Only looking for newlines within the quotes
- const qb = this.buffer.substring(0, end);
- let nl = qb.indexOf('\n', this.pos);
- if (nl !== -1) {
- while (nl !== -1) {
- const cs = this.continueScalar(nl + 1);
- if (cs === -1)
- break;
- nl = qb.indexOf('\n', cs);
- }
- if (nl !== -1) {
- // this is an error caused by an unexpected unindent
- end = nl - (qb[nl - 1] === '\r' ? 2 : 1);
- }
- }
- if (end === -1) {
- if (!this.atEnd)
- return this.setNext('quoted-scalar');
- end = this.buffer.length;
- }
- yield* this.pushToIndex(end + 1, false);
- return this.flowLevel ? 'flow' : 'doc';
- }
- *parseBlockScalarHeader() {
- this.blockScalarIndent = -1;
- this.blockScalarKeep = false;
- let i = this.pos;
- while (true) {
- const ch = this.buffer[++i];
- if (ch === '+')
- this.blockScalarKeep = true;
- else if (ch > '0' && ch <= '9')
- this.blockScalarIndent = Number(ch) - 1;
- else if (ch !== '-')
- break;
- }
- return yield* this.pushUntil(ch => isEmpty(ch) || ch === '#');
- }
- *parseBlockScalar() {
- let nl = this.pos - 1; // may be -1 if this.pos === 0
- let indent = 0;
- let ch;
- loop: for (let i = this.pos; (ch = this.buffer[i]); ++i) {
- switch (ch) {
- case ' ':
- indent += 1;
- break;
- case '\n':
- nl = i;
- indent = 0;
- break;
- case '\r': {
- const next = this.buffer[i + 1];
- if (!next && !this.atEnd)
- return this.setNext('block-scalar');
- if (next === '\n')
- break;
- } // fallthrough
- default:
- break loop;
- }
- }
- if (!ch && !this.atEnd)
- return this.setNext('block-scalar');
- if (indent >= this.indentNext) {
- if (this.blockScalarIndent === -1)
- this.indentNext = indent;
- else {
- this.indentNext =
- this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext);
- }
- do {
- const cs = this.continueScalar(nl + 1);
- if (cs === -1)
- break;
- nl = this.buffer.indexOf('\n', cs);
- } while (nl !== -1);
- if (nl === -1) {
- if (!this.atEnd)
- return this.setNext('block-scalar');
- nl = this.buffer.length;
- }
- }
- // Trailing insufficiently indented tabs are invalid.
- // To catch that during parsing, we include them in the block scalar value.
- let i = nl + 1;
- ch = this.buffer[i];
- while (ch === ' ')
- ch = this.buffer[++i];
- if (ch === '\t') {
- while (ch === '\t' || ch === ' ' || ch === '\r' || ch === '\n')
- ch = this.buffer[++i];
- nl = i - 1;
- }
- else if (!this.blockScalarKeep) {
- do {
- let i = nl - 1;
- let ch = this.buffer[i];
- if (ch === '\r')
- ch = this.buffer[--i];
- const lastChar = i; // Drop the line if last char not more indented
- while (ch === ' ')
- ch = this.buffer[--i];
- if (ch === '\n' && i >= this.pos && i + 1 + indent > lastChar)
- nl = i;
- else
- break;
- } while (true);
- }
- yield cst.SCALAR;
- yield* this.pushToIndex(nl + 1, true);
- return yield* this.parseLineStart();
- }
- *parsePlainScalar() {
- const inFlow = this.flowLevel > 0;
- let end = this.pos - 1;
- let i = this.pos - 1;
- let ch;
- while ((ch = this.buffer[++i])) {
- if (ch === ':') {
- const next = this.buffer[i + 1];
- if (isEmpty(next) || (inFlow && flowIndicatorChars.has(next)))
- break;
- end = i;
- }
- else if (isEmpty(ch)) {
- let next = this.buffer[i + 1];
- if (ch === '\r') {
- if (next === '\n') {
- i += 1;
- ch = '\n';
- next = this.buffer[i + 1];
- }
- else
- end = i;
- }
- if (next === '#' || (inFlow && flowIndicatorChars.has(next)))
- break;
- if (ch === '\n') {
- const cs = this.continueScalar(i + 1);
- if (cs === -1)
- break;
- i = Math.max(i, cs - 2); // to advance, but still account for ' #'
- }
- }
- else {
- if (inFlow && flowIndicatorChars.has(ch))
- break;
- end = i;
- }
- }
- if (!ch && !this.atEnd)
- return this.setNext('plain-scalar');
- yield cst.SCALAR;
- yield* this.pushToIndex(end + 1, true);
- return inFlow ? 'flow' : 'doc';
- }
- *pushCount(n) {
- if (n > 0) {
- yield this.buffer.substr(this.pos, n);
- this.pos += n;
- return n;
- }
- return 0;
- }
- *pushToIndex(i, allowEmpty) {
- const s = this.buffer.slice(this.pos, i);
- if (s) {
- yield s;
- this.pos += s.length;
- return s.length;
- }
- else if (allowEmpty)
- yield '';
- return 0;
- }
- *pushIndicators() {
- switch (this.charAt(0)) {
- case '!':
- return ((yield* this.pushTag()) +
- (yield* this.pushSpaces(true)) +
- (yield* this.pushIndicators()));
- case '&':
- return ((yield* this.pushUntil(isNotAnchorChar)) +
- (yield* this.pushSpaces(true)) +
- (yield* this.pushIndicators()));
- case '-': // this is an error
- case '?': // this is an error outside flow collections
- case ':': {
- const inFlow = this.flowLevel > 0;
- const ch1 = this.charAt(1);
- if (isEmpty(ch1) || (inFlow && flowIndicatorChars.has(ch1))) {
- if (!inFlow)
- this.indentNext = this.indentValue + 1;
- else if (this.flowKey)
- this.flowKey = false;
- return ((yield* this.pushCount(1)) +
- (yield* this.pushSpaces(true)) +
- (yield* this.pushIndicators()));
- }
- }
- }
- return 0;
- }
- *pushTag() {
- if (this.charAt(1) === '<') {
- let i = this.pos + 2;
- let ch = this.buffer[i];
- while (!isEmpty(ch) && ch !== '>')
- ch = this.buffer[++i];
- return yield* this.pushToIndex(ch === '>' ? i + 1 : i, false);
- }
- else {
- let i = this.pos + 1;
- let ch = this.buffer[i];
- while (ch) {
- if (tagChars.has(ch))
- ch = this.buffer[++i];
- else if (ch === '%' &&
- hexDigits.has(this.buffer[i + 1]) &&
- hexDigits.has(this.buffer[i + 2])) {
- ch = this.buffer[(i += 3)];
- }
- else
- break;
- }
- return yield* this.pushToIndex(i, false);
- }
- }
- *pushNewline() {
- const ch = this.buffer[this.pos];
- if (ch === '\n')
- return yield* this.pushCount(1);
- else if (ch === '\r' && this.charAt(1) === '\n')
- return yield* this.pushCount(2);
- else
- return 0;
- }
- *pushSpaces(allowTabs) {
- let i = this.pos - 1;
- let ch;
- do {
- ch = this.buffer[++i];
- } while (ch === ' ' || (allowTabs && ch === '\t'));
- const n = i - this.pos;
- if (n > 0) {
- yield this.buffer.substr(this.pos, n);
- this.pos = i;
- }
- return n;
- }
- *pushUntil(test) {
- let i = this.pos;
- let ch = this.buffer[i];
- while (!test(ch))
- ch = this.buffer[++i];
- return yield* this.pushToIndex(i, false);
- }
-}
-
-exports.Lexer = Lexer;
-
-
-/***/ }),
-
-/***/ 6628:
-/***/ ((__unused_webpack_module, exports) => {
-
-
-
-/**
- * Tracks newlines during parsing in order to provide an efficient API for
- * determining the one-indexed `{ line, col }` position for any offset
- * within the input.
- */
-class LineCounter {
- constructor() {
- this.lineStarts = [];
- /**
- * Should be called in ascending order. Otherwise, call
- * `lineCounter.lineStarts.sort()` before calling `linePos()`.
- */
- this.addNewLine = (offset) => this.lineStarts.push(offset);
- /**
- * Performs a binary search and returns the 1-indexed { line, col }
- * position of `offset`. If `line === 0`, `addNewLine` has never been
- * called or `offset` is before the first known newline.
- */
- this.linePos = (offset) => {
- let low = 0;
- let high = this.lineStarts.length;
- while (low < high) {
- const mid = (low + high) >> 1; // Math.floor((low + high) / 2)
- if (this.lineStarts[mid] < offset)
- low = mid + 1;
- else
- high = mid;
- }
- if (this.lineStarts[low] === offset)
- return { line: low + 1, col: 1 };
- if (low === 0)
- return { line: 0, col: offset };
- const start = this.lineStarts[low - 1];
- return { line: low, col: offset - start + 1 };
- };
- }
-}
-
-exports.LineCounter = LineCounter;
-
-
-/***/ }),
-
-/***/ 3456:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var node_process = __nccwpck_require__(932);
-var cst = __nccwpck_require__(3461);
-var lexer = __nccwpck_require__(361);
-
-function includesToken(list, type) {
- for (let i = 0; i < list.length; ++i)
- if (list[i].type === type)
- return true;
- return false;
-}
-function findNonEmptyIndex(list) {
- for (let i = 0; i < list.length; ++i) {
- switch (list[i].type) {
- case 'space':
- case 'comment':
- case 'newline':
- break;
- default:
- return i;
- }
- }
- return -1;
-}
-function isFlowToken(token) {
- switch (token?.type) {
- case 'alias':
- case 'scalar':
- case 'single-quoted-scalar':
- case 'double-quoted-scalar':
- case 'flow-collection':
- return true;
- default:
- return false;
- }
-}
-function getPrevProps(parent) {
- switch (parent.type) {
- case 'document':
- return parent.start;
- case 'block-map': {
- const it = parent.items[parent.items.length - 1];
- return it.sep ?? it.start;
- }
- case 'block-seq':
- return parent.items[parent.items.length - 1].start;
- /* istanbul ignore next should not happen */
- default:
- return [];
- }
-}
-/** Note: May modify input array */
-function getFirstKeyStartProps(prev) {
- if (prev.length === 0)
- return [];
- let i = prev.length;
- loop: while (--i >= 0) {
- switch (prev[i].type) {
- case 'doc-start':
- case 'explicit-key-ind':
- case 'map-value-ind':
- case 'seq-item-ind':
- case 'newline':
- break loop;
- }
- }
- while (prev[++i]?.type === 'space') {
- /* loop */
- }
- return prev.splice(i, prev.length);
-}
-function fixFlowSeqItems(fc) {
- if (fc.start.type === 'flow-seq-start') {
- for (const it of fc.items) {
- if (it.sep &&
- !it.value &&
- !includesToken(it.start, 'explicit-key-ind') &&
- !includesToken(it.sep, 'map-value-ind')) {
- if (it.key)
- it.value = it.key;
- delete it.key;
- if (isFlowToken(it.value)) {
- if (it.value.end)
- Array.prototype.push.apply(it.value.end, it.sep);
- else
- it.value.end = it.sep;
- }
- else
- Array.prototype.push.apply(it.start, it.sep);
- delete it.sep;
- }
- }
- }
-}
-/**
- * A YAML concrete syntax tree (CST) parser
- *
- * ```ts
- * const src: string = ...
- * for (const token of new Parser().parse(src)) {
- * // token: Token
- * }
- * ```
- *
- * To use the parser with a user-provided lexer:
- *
- * ```ts
- * function* parse(source: string, lexer: Lexer) {
- * const parser = new Parser()
- * for (const lexeme of lexer.lex(source))
- * yield* parser.next(lexeme)
- * yield* parser.end()
- * }
- *
- * const src: string = ...
- * const lexer = new Lexer()
- * for (const token of parse(src, lexer)) {
- * // token: Token
- * }
- * ```
- */
-class Parser {
- /**
- * @param onNewLine - If defined, called separately with the start position of
- * each new line (in `parse()`, including the start of input).
- */
- constructor(onNewLine) {
- /** If true, space and sequence indicators count as indentation */
- this.atNewLine = true;
- /** If true, next token is a scalar value */
- this.atScalar = false;
- /** Current indentation level */
- this.indent = 0;
- /** Current offset since the start of parsing */
- this.offset = 0;
- /** On the same line with a block map key */
- this.onKeyLine = false;
- /** Top indicates the node that's currently being built */
- this.stack = [];
- /** The source of the current token, set in parse() */
- this.source = '';
- /** The type of the current token, set in parse() */
- this.type = '';
- // Must be defined after `next()`
- this.lexer = new lexer.Lexer();
- this.onNewLine = onNewLine;
- }
- /**
- * Parse `source` as a YAML stream.
- * If `incomplete`, a part of the last line may be left as a buffer for the next call.
- *
- * Errors are not thrown, but yielded as `{ type: 'error', message }` tokens.
- *
- * @returns A generator of tokens representing each directive, document, and other structure.
- */
- *parse(source, incomplete = false) {
- if (this.onNewLine && this.offset === 0)
- this.onNewLine(0);
- for (const lexeme of this.lexer.lex(source, incomplete))
- yield* this.next(lexeme);
- if (!incomplete)
- yield* this.end();
- }
- /**
- * Advance the parser by the `source` of one lexical token.
- */
- *next(source) {
- this.source = source;
- if (node_process.env.LOG_TOKENS)
- console.log('|', cst.prettyToken(source));
- if (this.atScalar) {
- this.atScalar = false;
- yield* this.step();
- this.offset += source.length;
- return;
- }
- const type = cst.tokenType(source);
- if (!type) {
- const message = `Not a YAML token: ${source}`;
- yield* this.pop({ type: 'error', offset: this.offset, message, source });
- this.offset += source.length;
- }
- else if (type === 'scalar') {
- this.atNewLine = false;
- this.atScalar = true;
- this.type = 'scalar';
- }
- else {
- this.type = type;
- yield* this.step();
- switch (type) {
- case 'newline':
- this.atNewLine = true;
- this.indent = 0;
- if (this.onNewLine)
- this.onNewLine(this.offset + source.length);
- break;
- case 'space':
- if (this.atNewLine && source[0] === ' ')
- this.indent += source.length;
- break;
- case 'explicit-key-ind':
- case 'map-value-ind':
- case 'seq-item-ind':
- if (this.atNewLine)
- this.indent += source.length;
- break;
- case 'doc-mode':
- case 'flow-error-end':
- return;
- default:
- this.atNewLine = false;
- }
- this.offset += source.length;
- }
- }
- /** Call at end of input to push out any remaining constructions */
- *end() {
- while (this.stack.length > 0)
- yield* this.pop();
- }
- get sourceToken() {
- const st = {
- type: this.type,
- offset: this.offset,
- indent: this.indent,
- source: this.source
- };
- return st;
- }
- *step() {
- const top = this.peek(1);
- if (this.type === 'doc-end' && top?.type !== 'doc-end') {
- while (this.stack.length > 0)
- yield* this.pop();
- this.stack.push({
- type: 'doc-end',
- offset: this.offset,
- source: this.source
- });
- return;
- }
- if (!top)
- return yield* this.stream();
- switch (top.type) {
- case 'document':
- return yield* this.document(top);
- case 'alias':
- case 'scalar':
- case 'single-quoted-scalar':
- case 'double-quoted-scalar':
- return yield* this.scalar(top);
- case 'block-scalar':
- return yield* this.blockScalar(top);
- case 'block-map':
- return yield* this.blockMap(top);
- case 'block-seq':
- return yield* this.blockSequence(top);
- case 'flow-collection':
- return yield* this.flowCollection(top);
- case 'doc-end':
- return yield* this.documentEnd(top);
- }
- /* istanbul ignore next should not happen */
- yield* this.pop();
- }
- peek(n) {
- return this.stack[this.stack.length - n];
- }
- *pop(error) {
- const token = error ?? this.stack.pop();
- /* istanbul ignore if should not happen */
- if (!token) {
- const message = 'Tried to pop an empty stack';
- yield { type: 'error', offset: this.offset, source: '', message };
- }
- else if (this.stack.length === 0) {
- yield token;
- }
- else {
- const top = this.peek(1);
- if (token.type === 'block-scalar') {
- // Block scalars use their parent rather than header indent
- token.indent = 'indent' in top ? top.indent : 0;
- }
- else if (token.type === 'flow-collection' && top.type === 'document') {
- // Ignore all indent for top-level flow collections
- token.indent = 0;
- }
- if (token.type === 'flow-collection')
- fixFlowSeqItems(token);
- switch (top.type) {
- case 'document':
- top.value = token;
- break;
- case 'block-scalar':
- top.props.push(token); // error
- break;
- case 'block-map': {
- const it = top.items[top.items.length - 1];
- if (it.value) {
- top.items.push({ start: [], key: token, sep: [] });
- this.onKeyLine = true;
- return;
- }
- else if (it.sep) {
- it.value = token;
- }
- else {
- Object.assign(it, { key: token, sep: [] });
- this.onKeyLine = !it.explicitKey;
- return;
- }
- break;
- }
- case 'block-seq': {
- const it = top.items[top.items.length - 1];
- if (it.value)
- top.items.push({ start: [], value: token });
- else
- it.value = token;
- break;
- }
- case 'flow-collection': {
- const it = top.items[top.items.length - 1];
- if (!it || it.value)
- top.items.push({ start: [], key: token, sep: [] });
- else if (it.sep)
- it.value = token;
- else
- Object.assign(it, { key: token, sep: [] });
- return;
- }
- /* istanbul ignore next should not happen */
- default:
- yield* this.pop();
- yield* this.pop(token);
- }
- if ((top.type === 'document' ||
- top.type === 'block-map' ||
- top.type === 'block-seq') &&
- (token.type === 'block-map' || token.type === 'block-seq')) {
- const last = token.items[token.items.length - 1];
- if (last &&
- !last.sep &&
- !last.value &&
- last.start.length > 0 &&
- findNonEmptyIndex(last.start) === -1 &&
- (token.indent === 0 ||
- last.start.every(st => st.type !== 'comment' || st.indent < token.indent))) {
- if (top.type === 'document')
- top.end = last.start;
- else
- top.items.push({ start: last.start });
- token.items.splice(-1, 1);
- }
- }
- }
- }
- *stream() {
- switch (this.type) {
- case 'directive-line':
- yield { type: 'directive', offset: this.offset, source: this.source };
- return;
- case 'byte-order-mark':
- case 'space':
- case 'comment':
- case 'newline':
- yield this.sourceToken;
- return;
- case 'doc-mode':
- case 'doc-start': {
- const doc = {
- type: 'document',
- offset: this.offset,
- start: []
- };
- if (this.type === 'doc-start')
- doc.start.push(this.sourceToken);
- this.stack.push(doc);
- return;
- }
- }
- yield {
- type: 'error',
- offset: this.offset,
- message: `Unexpected ${this.type} token in YAML stream`,
- source: this.source
- };
- }
- *document(doc) {
- if (doc.value)
- return yield* this.lineEnd(doc);
- switch (this.type) {
- case 'doc-start': {
- if (findNonEmptyIndex(doc.start) !== -1) {
- yield* this.pop();
- yield* this.step();
- }
- else
- doc.start.push(this.sourceToken);
- return;
- }
- case 'anchor':
- case 'tag':
- case 'space':
- case 'comment':
- case 'newline':
- doc.start.push(this.sourceToken);
- return;
- }
- const bv = this.startBlockValue(doc);
- if (bv)
- this.stack.push(bv);
- else {
- yield {
- type: 'error',
- offset: this.offset,
- message: `Unexpected ${this.type} token in YAML document`,
- source: this.source
- };
- }
- }
- *scalar(scalar) {
- if (this.type === 'map-value-ind') {
- const prev = getPrevProps(this.peek(2));
- const start = getFirstKeyStartProps(prev);
- let sep;
- if (scalar.end) {
- sep = scalar.end;
- sep.push(this.sourceToken);
- delete scalar.end;
- }
- else
- sep = [this.sourceToken];
- const map = {
- type: 'block-map',
- offset: scalar.offset,
- indent: scalar.indent,
- items: [{ start, key: scalar, sep }]
- };
- this.onKeyLine = true;
- this.stack[this.stack.length - 1] = map;
- }
- else
- yield* this.lineEnd(scalar);
- }
- *blockScalar(scalar) {
- switch (this.type) {
- case 'space':
- case 'comment':
- case 'newline':
- scalar.props.push(this.sourceToken);
- return;
- case 'scalar':
- scalar.source = this.source;
- // block-scalar source includes trailing newline
- this.atNewLine = true;
- this.indent = 0;
- if (this.onNewLine) {
- let nl = this.source.indexOf('\n') + 1;
- while (nl !== 0) {
- this.onNewLine(this.offset + nl);
- nl = this.source.indexOf('\n', nl) + 1;
- }
- }
- yield* this.pop();
- break;
- /* istanbul ignore next should not happen */
- default:
- yield* this.pop();
- yield* this.step();
- }
- }
- *blockMap(map) {
- const it = map.items[map.items.length - 1];
- // it.sep is true-ish if pair already has key or : separator
- switch (this.type) {
- case 'newline':
- this.onKeyLine = false;
- if (it.value) {
- const end = 'end' in it.value ? it.value.end : undefined;
- const last = Array.isArray(end) ? end[end.length - 1] : undefined;
- if (last?.type === 'comment')
- end?.push(this.sourceToken);
- else
- map.items.push({ start: [this.sourceToken] });
- }
- else if (it.sep) {
- it.sep.push(this.sourceToken);
- }
- else {
- it.start.push(this.sourceToken);
- }
- return;
- case 'space':
- case 'comment':
- if (it.value) {
- map.items.push({ start: [this.sourceToken] });
- }
- else if (it.sep) {
- it.sep.push(this.sourceToken);
- }
- else {
- if (this.atIndentedComment(it.start, map.indent)) {
- const prev = map.items[map.items.length - 2];
- const end = prev?.value?.end;
- if (Array.isArray(end)) {
- Array.prototype.push.apply(end, it.start);
- end.push(this.sourceToken);
- map.items.pop();
- return;
- }
- }
- it.start.push(this.sourceToken);
- }
- return;
- }
- if (this.indent >= map.indent) {
- const atMapIndent = !this.onKeyLine && this.indent === map.indent;
- const atNextItem = atMapIndent &&
- (it.sep || it.explicitKey) &&
- this.type !== 'seq-item-ind';
- // For empty nodes, assign newline-separated not indented empty tokens to following node
- let start = [];
- if (atNextItem && it.sep && !it.value) {
- const nl = [];
- for (let i = 0; i < it.sep.length; ++i) {
- const st = it.sep[i];
- switch (st.type) {
- case 'newline':
- nl.push(i);
- break;
- case 'space':
- break;
- case 'comment':
- if (st.indent > map.indent)
- nl.length = 0;
- break;
- default:
- nl.length = 0;
- }
- }
- if (nl.length >= 2)
- start = it.sep.splice(nl[1]);
- }
- switch (this.type) {
- case 'anchor':
- case 'tag':
- if (atNextItem || it.value) {
- start.push(this.sourceToken);
- map.items.push({ start });
- this.onKeyLine = true;
- }
- else if (it.sep) {
- it.sep.push(this.sourceToken);
- }
- else {
- it.start.push(this.sourceToken);
- }
- return;
- case 'explicit-key-ind':
- if (!it.sep && !it.explicitKey) {
- it.start.push(this.sourceToken);
- it.explicitKey = true;
- }
- else if (atNextItem || it.value) {
- start.push(this.sourceToken);
- map.items.push({ start, explicitKey: true });
- }
- else {
- this.stack.push({
- type: 'block-map',
- offset: this.offset,
- indent: this.indent,
- items: [{ start: [this.sourceToken], explicitKey: true }]
- });
- }
- this.onKeyLine = true;
- return;
- case 'map-value-ind':
- if (it.explicitKey) {
- if (!it.sep) {
- if (includesToken(it.start, 'newline')) {
- Object.assign(it, { key: null, sep: [this.sourceToken] });
- }
- else {
- const start = getFirstKeyStartProps(it.start);
- this.stack.push({
- type: 'block-map',
- offset: this.offset,
- indent: this.indent,
- items: [{ start, key: null, sep: [this.sourceToken] }]
- });
- }
- }
- else if (it.value) {
- map.items.push({ start: [], key: null, sep: [this.sourceToken] });
- }
- else if (includesToken(it.sep, 'map-value-ind')) {
- this.stack.push({
- type: 'block-map',
- offset: this.offset,
- indent: this.indent,
- items: [{ start, key: null, sep: [this.sourceToken] }]
- });
- }
- else if (isFlowToken(it.key) &&
- !includesToken(it.sep, 'newline')) {
- const start = getFirstKeyStartProps(it.start);
- const key = it.key;
- const sep = it.sep;
- sep.push(this.sourceToken);
- // @ts-expect-error type guard is wrong here
- delete it.key;
- // @ts-expect-error type guard is wrong here
- delete it.sep;
- this.stack.push({
- type: 'block-map',
- offset: this.offset,
- indent: this.indent,
- items: [{ start, key, sep }]
- });
- }
- else if (start.length > 0) {
- // Not actually at next item
- it.sep = it.sep.concat(start, this.sourceToken);
- }
- else {
- it.sep.push(this.sourceToken);
- }
- }
- else {
- if (!it.sep) {
- Object.assign(it, { key: null, sep: [this.sourceToken] });
- }
- else if (it.value || atNextItem) {
- map.items.push({ start, key: null, sep: [this.sourceToken] });
- }
- else if (includesToken(it.sep, 'map-value-ind')) {
- this.stack.push({
- type: 'block-map',
- offset: this.offset,
- indent: this.indent,
- items: [{ start: [], key: null, sep: [this.sourceToken] }]
- });
- }
- else {
- it.sep.push(this.sourceToken);
- }
- }
- this.onKeyLine = true;
- return;
- case 'alias':
- case 'scalar':
- case 'single-quoted-scalar':
- case 'double-quoted-scalar': {
- const fs = this.flowScalar(this.type);
- if (atNextItem || it.value) {
- map.items.push({ start, key: fs, sep: [] });
- this.onKeyLine = true;
- }
- else if (it.sep) {
- this.stack.push(fs);
- }
- else {
- Object.assign(it, { key: fs, sep: [] });
- this.onKeyLine = true;
- }
- return;
- }
- default: {
- const bv = this.startBlockValue(map);
- if (bv) {
- if (bv.type === 'block-seq') {
- if (!it.explicitKey &&
- it.sep &&
- !includesToken(it.sep, 'newline')) {
- yield* this.pop({
- type: 'error',
- offset: this.offset,
- message: 'Unexpected block-seq-ind on same line with key',
- source: this.source
- });
- return;
- }
- }
- else if (atMapIndent) {
- map.items.push({ start });
- }
- this.stack.push(bv);
- return;
- }
- }
- }
- }
- yield* this.pop();
- yield* this.step();
- }
- *blockSequence(seq) {
- const it = seq.items[seq.items.length - 1];
- switch (this.type) {
- case 'newline':
- if (it.value) {
- const end = 'end' in it.value ? it.value.end : undefined;
- const last = Array.isArray(end) ? end[end.length - 1] : undefined;
- if (last?.type === 'comment')
- end?.push(this.sourceToken);
- else
- seq.items.push({ start: [this.sourceToken] });
- }
- else
- it.start.push(this.sourceToken);
- return;
- case 'space':
- case 'comment':
- if (it.value)
- seq.items.push({ start: [this.sourceToken] });
- else {
- if (this.atIndentedComment(it.start, seq.indent)) {
- const prev = seq.items[seq.items.length - 2];
- const end = prev?.value?.end;
- if (Array.isArray(end)) {
- Array.prototype.push.apply(end, it.start);
- end.push(this.sourceToken);
- seq.items.pop();
- return;
- }
- }
- it.start.push(this.sourceToken);
- }
- return;
- case 'anchor':
- case 'tag':
- if (it.value || this.indent <= seq.indent)
- break;
- it.start.push(this.sourceToken);
- return;
- case 'seq-item-ind':
- if (this.indent !== seq.indent)
- break;
- if (it.value || includesToken(it.start, 'seq-item-ind'))
- seq.items.push({ start: [this.sourceToken] });
- else
- it.start.push(this.sourceToken);
- return;
- }
- if (this.indent > seq.indent) {
- const bv = this.startBlockValue(seq);
- if (bv) {
- this.stack.push(bv);
- return;
- }
- }
- yield* this.pop();
- yield* this.step();
- }
- *flowCollection(fc) {
- const it = fc.items[fc.items.length - 1];
- if (this.type === 'flow-error-end') {
- let top;
- do {
- yield* this.pop();
- top = this.peek(1);
- } while (top?.type === 'flow-collection');
- }
- else if (fc.end.length === 0) {
- switch (this.type) {
- case 'comma':
- case 'explicit-key-ind':
- if (!it || it.sep)
- fc.items.push({ start: [this.sourceToken] });
- else
- it.start.push(this.sourceToken);
- return;
- case 'map-value-ind':
- if (!it || it.value)
- fc.items.push({ start: [], key: null, sep: [this.sourceToken] });
- else if (it.sep)
- it.sep.push(this.sourceToken);
- else
- Object.assign(it, { key: null, sep: [this.sourceToken] });
- return;
- case 'space':
- case 'comment':
- case 'newline':
- case 'anchor':
- case 'tag':
- if (!it || it.value)
- fc.items.push({ start: [this.sourceToken] });
- else if (it.sep)
- it.sep.push(this.sourceToken);
- else
- it.start.push(this.sourceToken);
- return;
- case 'alias':
- case 'scalar':
- case 'single-quoted-scalar':
- case 'double-quoted-scalar': {
- const fs = this.flowScalar(this.type);
- if (!it || it.value)
- fc.items.push({ start: [], key: fs, sep: [] });
- else if (it.sep)
- this.stack.push(fs);
- else
- Object.assign(it, { key: fs, sep: [] });
- return;
- }
- case 'flow-map-end':
- case 'flow-seq-end':
- fc.end.push(this.sourceToken);
- return;
- }
- const bv = this.startBlockValue(fc);
- /* istanbul ignore else should not happen */
- if (bv)
- this.stack.push(bv);
- else {
- yield* this.pop();
- yield* this.step();
- }
- }
- else {
- const parent = this.peek(2);
- if (parent.type === 'block-map' &&
- ((this.type === 'map-value-ind' && parent.indent === fc.indent) ||
- (this.type === 'newline' &&
- !parent.items[parent.items.length - 1].sep))) {
- yield* this.pop();
- yield* this.step();
- }
- else if (this.type === 'map-value-ind' &&
- parent.type !== 'flow-collection') {
- const prev = getPrevProps(parent);
- const start = getFirstKeyStartProps(prev);
- fixFlowSeqItems(fc);
- const sep = fc.end.splice(1, fc.end.length);
- sep.push(this.sourceToken);
- const map = {
- type: 'block-map',
- offset: fc.offset,
- indent: fc.indent,
- items: [{ start, key: fc, sep }]
- };
- this.onKeyLine = true;
- this.stack[this.stack.length - 1] = map;
- }
- else {
- yield* this.lineEnd(fc);
- }
- }
- }
- flowScalar(type) {
- if (this.onNewLine) {
- let nl = this.source.indexOf('\n') + 1;
- while (nl !== 0) {
- this.onNewLine(this.offset + nl);
- nl = this.source.indexOf('\n', nl) + 1;
- }
- }
- return {
- type,
- offset: this.offset,
- indent: this.indent,
- source: this.source
- };
- }
- startBlockValue(parent) {
- switch (this.type) {
- case 'alias':
- case 'scalar':
- case 'single-quoted-scalar':
- case 'double-quoted-scalar':
- return this.flowScalar(this.type);
- case 'block-scalar-header':
- return {
- type: 'block-scalar',
- offset: this.offset,
- indent: this.indent,
- props: [this.sourceToken],
- source: ''
- };
- case 'flow-map-start':
- case 'flow-seq-start':
- return {
- type: 'flow-collection',
- offset: this.offset,
- indent: this.indent,
- start: this.sourceToken,
- items: [],
- end: []
- };
- case 'seq-item-ind':
- return {
- type: 'block-seq',
- offset: this.offset,
- indent: this.indent,
- items: [{ start: [this.sourceToken] }]
- };
- case 'explicit-key-ind': {
- this.onKeyLine = true;
- const prev = getPrevProps(parent);
- const start = getFirstKeyStartProps(prev);
- start.push(this.sourceToken);
- return {
- type: 'block-map',
- offset: this.offset,
- indent: this.indent,
- items: [{ start, explicitKey: true }]
- };
- }
- case 'map-value-ind': {
- this.onKeyLine = true;
- const prev = getPrevProps(parent);
- const start = getFirstKeyStartProps(prev);
- return {
- type: 'block-map',
- offset: this.offset,
- indent: this.indent,
- items: [{ start, key: null, sep: [this.sourceToken] }]
- };
- }
- }
- return null;
- }
- atIndentedComment(start, indent) {
- if (this.type !== 'comment')
- return false;
- if (this.indent <= indent)
- return false;
- return start.every(st => st.type === 'newline' || st.type === 'space');
- }
- *documentEnd(docEnd) {
- if (this.type !== 'doc-mode') {
- if (docEnd.end)
- docEnd.end.push(this.sourceToken);
- else
- docEnd.end = [this.sourceToken];
- if (this.type === 'newline')
- yield* this.pop();
- }
- }
- *lineEnd(token) {
- switch (this.type) {
- case 'comma':
- case 'doc-start':
- case 'doc-end':
- case 'flow-seq-end':
- case 'flow-map-end':
- case 'map-value-ind':
- yield* this.pop();
- yield* this.step();
- break;
- case 'newline':
- this.onKeyLine = false;
- // fallthrough
- case 'space':
- case 'comment':
- default:
- // all other values are errors
- if (token.end)
- token.end.push(this.sourceToken);
- else
- token.end = [this.sourceToken];
- if (this.type === 'newline')
- yield* this.pop();
- }
- }
-}
-
-exports.Parser = Parser;
-
-
-/***/ }),
-
-/***/ 4047:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var composer = __nccwpck_require__(9984);
-var Document = __nccwpck_require__(3021);
-var errors = __nccwpck_require__(1464);
-var log = __nccwpck_require__(7249);
-var identity = __nccwpck_require__(1127);
-var lineCounter = __nccwpck_require__(6628);
-var parser = __nccwpck_require__(3456);
-
-function parseOptions(options) {
- const prettyErrors = options.prettyErrors !== false;
- const lineCounter$1 = options.lineCounter || (prettyErrors && new lineCounter.LineCounter()) || null;
- return { lineCounter: lineCounter$1, prettyErrors };
-}
-/**
- * Parse the input as a stream of YAML documents.
- *
- * Documents should be separated from each other by `...` or `---` marker lines.
- *
- * @returns If an empty `docs` array is returned, it will be of type
- * EmptyStream and contain additional stream information. In
- * TypeScript, you should use `'empty' in docs` as a type guard for it.
- */
-function parseAllDocuments(source, options = {}) {
- const { lineCounter, prettyErrors } = parseOptions(options);
- const parser$1 = new parser.Parser(lineCounter?.addNewLine);
- const composer$1 = new composer.Composer(options);
- const docs = Array.from(composer$1.compose(parser$1.parse(source)));
- if (prettyErrors && lineCounter)
- for (const doc of docs) {
- doc.errors.forEach(errors.prettifyError(source, lineCounter));
- doc.warnings.forEach(errors.prettifyError(source, lineCounter));
- }
- if (docs.length > 0)
- return docs;
- return Object.assign([], { empty: true }, composer$1.streamInfo());
-}
-/** Parse an input string into a single YAML.Document */
-function parseDocument(source, options = {}) {
- const { lineCounter, prettyErrors } = parseOptions(options);
- const parser$1 = new parser.Parser(lineCounter?.addNewLine);
- const composer$1 = new composer.Composer(options);
- // `doc` is always set by compose.end(true) at the very latest
- let doc = null;
- for (const _doc of composer$1.compose(parser$1.parse(source), true, source.length)) {
- if (!doc)
- doc = _doc;
- else if (doc.options.logLevel !== 'silent') {
- doc.errors.push(new errors.YAMLParseError(_doc.range.slice(0, 2), 'MULTIPLE_DOCS', 'Source contains multiple documents; please use YAML.parseAllDocuments()'));
- break;
- }
- }
- if (prettyErrors && lineCounter) {
- doc.errors.forEach(errors.prettifyError(source, lineCounter));
- doc.warnings.forEach(errors.prettifyError(source, lineCounter));
- }
- return doc;
-}
-function parse(src, reviver, options) {
- let _reviver = undefined;
- if (typeof reviver === 'function') {
- _reviver = reviver;
- }
- else if (options === undefined && reviver && typeof reviver === 'object') {
- options = reviver;
- }
- const doc = parseDocument(src, options);
- if (!doc)
- return null;
- doc.warnings.forEach(warning => log.warn(doc.options.logLevel, warning));
- if (doc.errors.length > 0) {
- if (doc.options.logLevel !== 'silent')
- throw doc.errors[0];
- else
- doc.errors = [];
- }
- return doc.toJS(Object.assign({ reviver: _reviver }, options));
-}
-function stringify(value, replacer, options) {
- let _replacer = null;
- if (typeof replacer === 'function' || Array.isArray(replacer)) {
- _replacer = replacer;
- }
- else if (options === undefined && replacer) {
- options = replacer;
- }
- if (typeof options === 'string')
- options = options.length;
- if (typeof options === 'number') {
- const indent = Math.round(options);
- options = indent < 1 ? undefined : indent > 8 ? { indent: 8 } : { indent };
- }
- if (value === undefined) {
- const { keepUndefined } = options ?? replacer ?? {};
- if (!keepUndefined)
- return undefined;
- }
- if (identity.isDocument(value) && !_replacer)
- return value.toString(options);
- return new Document.Document(value, _replacer, options).toString(options);
-}
-
-exports.parse = parse;
-exports.parseAllDocuments = parseAllDocuments;
-exports.parseDocument = parseDocument;
-exports.stringify = stringify;
-
-
-/***/ }),
-
-/***/ 5840:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var identity = __nccwpck_require__(1127);
-var map = __nccwpck_require__(7451);
-var seq = __nccwpck_require__(1706);
-var string = __nccwpck_require__(6464);
-var tags = __nccwpck_require__(18);
-
-const sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0;
-class Schema {
- constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults }) {
- this.compat = Array.isArray(compat)
- ? tags.getTags(compat, 'compat')
- : compat
- ? tags.getTags(null, compat)
- : null;
- this.name = (typeof schema === 'string' && schema) || 'core';
- this.knownTags = resolveKnownTags ? tags.coreKnownTags : {};
- this.tags = tags.getTags(customTags, this.name, merge);
- this.toStringOptions = toStringDefaults ?? null;
- Object.defineProperty(this, identity.MAP, { value: map.map });
- Object.defineProperty(this, identity.SCALAR, { value: string.string });
- Object.defineProperty(this, identity.SEQ, { value: seq.seq });
- // Used by createMap()
- this.sortMapEntries =
- typeof sortMapEntries === 'function'
- ? sortMapEntries
- : sortMapEntries === true
- ? sortMapEntriesByKey
- : null;
- }
- clone() {
- const copy = Object.create(Schema.prototype, Object.getOwnPropertyDescriptors(this));
- copy.tags = this.tags.slice();
- return copy;
- }
-}
-
-exports.Schema = Schema;
-
-
-/***/ }),
-
-/***/ 7451:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var identity = __nccwpck_require__(1127);
-var YAMLMap = __nccwpck_require__(4454);
-
-const map = {
- collection: 'map',
- default: true,
- nodeClass: YAMLMap.YAMLMap,
- tag: 'tag:yaml.org,2002:map',
- resolve(map, onError) {
- if (!identity.isMap(map))
- onError('Expected a mapping for this tag');
- return map;
- },
- createNode: (schema, obj, ctx) => YAMLMap.YAMLMap.from(schema, obj, ctx)
-};
-
-exports.map = map;
-
-
-/***/ }),
-
-/***/ 1251:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var Scalar = __nccwpck_require__(3301);
-
-const nullTag = {
- identify: value => value == null,
- createNode: () => new Scalar.Scalar(null),
- default: true,
- tag: 'tag:yaml.org,2002:null',
- test: /^(?:~|[Nn]ull|NULL)?$/,
- resolve: () => new Scalar.Scalar(null),
- stringify: ({ source }, ctx) => typeof source === 'string' && nullTag.test.test(source)
- ? source
- : ctx.options.nullStr
-};
-
-exports.nullTag = nullTag;
-
-
-/***/ }),
-
-/***/ 1706:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var identity = __nccwpck_require__(1127);
-var YAMLSeq = __nccwpck_require__(2223);
-
-const seq = {
- collection: 'seq',
- default: true,
- nodeClass: YAMLSeq.YAMLSeq,
- tag: 'tag:yaml.org,2002:seq',
- resolve(seq, onError) {
- if (!identity.isSeq(seq))
- onError('Expected a sequence for this tag');
- return seq;
- },
- createNode: (schema, obj, ctx) => YAMLSeq.YAMLSeq.from(schema, obj, ctx)
-};
-
-exports.seq = seq;
-
-
-/***/ }),
-
-/***/ 6464:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var stringifyString = __nccwpck_require__(5450);
-
-const string = {
- identify: value => typeof value === 'string',
- default: true,
- tag: 'tag:yaml.org,2002:str',
- resolve: str => str,
- stringify(item, ctx, onComment, onChompKeep) {
- ctx = Object.assign({ actualString: true }, ctx);
- return stringifyString.stringifyString(item, ctx, onComment, onChompKeep);
- }
-};
-
-exports.string = string;
-
-
-/***/ }),
-
-/***/ 6340:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var Scalar = __nccwpck_require__(3301);
-
-const boolTag = {
- identify: value => typeof value === 'boolean',
- default: true,
- tag: 'tag:yaml.org,2002:bool',
- test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,
- resolve: str => new Scalar.Scalar(str[0] === 't' || str[0] === 'T'),
- stringify({ source, value }, ctx) {
- if (source && boolTag.test.test(source)) {
- const sv = source[0] === 't' || source[0] === 'T';
- if (value === sv)
- return source;
- }
- return value ? ctx.options.trueStr : ctx.options.falseStr;
- }
-};
-
-exports.boolTag = boolTag;
-
-
-/***/ }),
-
-/***/ 8405:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var Scalar = __nccwpck_require__(3301);
-var stringifyNumber = __nccwpck_require__(8689);
-
-const floatNaN = {
- identify: value => typeof value === 'number',
- default: true,
- tag: 'tag:yaml.org,2002:float',
- test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,
- resolve: str => str.slice(-3).toLowerCase() === 'nan'
- ? NaN
- : str[0] === '-'
- ? Number.NEGATIVE_INFINITY
- : Number.POSITIVE_INFINITY,
- stringify: stringifyNumber.stringifyNumber
-};
-const floatExp = {
- identify: value => typeof value === 'number',
- default: true,
- tag: 'tag:yaml.org,2002:float',
- format: 'EXP',
- test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,
- resolve: str => parseFloat(str),
- stringify(node) {
- const num = Number(node.value);
- return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node);
- }
-};
-const float = {
- identify: value => typeof value === 'number',
- default: true,
- tag: 'tag:yaml.org,2002:float',
- test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,
- resolve(str) {
- const node = new Scalar.Scalar(parseFloat(str));
- const dot = str.indexOf('.');
- if (dot !== -1 && str[str.length - 1] === '0')
- node.minFractionDigits = str.length - dot - 1;
- return node;
- },
- stringify: stringifyNumber.stringifyNumber
-};
-
-exports.float = float;
-exports.floatExp = floatExp;
-exports.floatNaN = floatNaN;
-
-
-/***/ }),
-
-/***/ 9874:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var stringifyNumber = __nccwpck_require__(8689);
-
-const intIdentify = (value) => typeof value === 'bigint' || Number.isInteger(value);
-const intResolve = (str, offset, radix, { intAsBigInt }) => (intAsBigInt ? BigInt(str) : parseInt(str.substring(offset), radix));
-function intStringify(node, radix, prefix) {
- const { value } = node;
- if (intIdentify(value) && value >= 0)
- return prefix + value.toString(radix);
- return stringifyNumber.stringifyNumber(node);
-}
-const intOct = {
- identify: value => intIdentify(value) && value >= 0,
- default: true,
- tag: 'tag:yaml.org,2002:int',
- format: 'OCT',
- test: /^0o[0-7]+$/,
- resolve: (str, _onError, opt) => intResolve(str, 2, 8, opt),
- stringify: node => intStringify(node, 8, '0o')
-};
-const int = {
- identify: intIdentify,
- default: true,
- tag: 'tag:yaml.org,2002:int',
- test: /^[-+]?[0-9]+$/,
- resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),
- stringify: stringifyNumber.stringifyNumber
-};
-const intHex = {
- identify: value => intIdentify(value) && value >= 0,
- default: true,
- tag: 'tag:yaml.org,2002:int',
- format: 'HEX',
- test: /^0x[0-9a-fA-F]+$/,
- resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),
- stringify: node => intStringify(node, 16, '0x')
-};
-
-exports.int = int;
-exports.intHex = intHex;
-exports.intOct = intOct;
-
-
-/***/ }),
-
-/***/ 896:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var map = __nccwpck_require__(7451);
-var _null = __nccwpck_require__(1251);
-var seq = __nccwpck_require__(1706);
-var string = __nccwpck_require__(6464);
-var bool = __nccwpck_require__(6340);
-var float = __nccwpck_require__(8405);
-var int = __nccwpck_require__(9874);
-
-const schema = [
- map.map,
- seq.seq,
- string.string,
- _null.nullTag,
- bool.boolTag,
- int.intOct,
- int.int,
- int.intHex,
- float.floatNaN,
- float.floatExp,
- float.float
-];
-
-exports.schema = schema;
-
-
-/***/ }),
-
-/***/ 3559:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var Scalar = __nccwpck_require__(3301);
-var map = __nccwpck_require__(7451);
-var seq = __nccwpck_require__(1706);
-
-function intIdentify(value) {
- return typeof value === 'bigint' || Number.isInteger(value);
-}
-const stringifyJSON = ({ value }) => JSON.stringify(value);
-const jsonScalars = [
- {
- identify: value => typeof value === 'string',
- default: true,
- tag: 'tag:yaml.org,2002:str',
- resolve: str => str,
- stringify: stringifyJSON
- },
- {
- identify: value => value == null,
- createNode: () => new Scalar.Scalar(null),
- default: true,
- tag: 'tag:yaml.org,2002:null',
- test: /^null$/,
- resolve: () => null,
- stringify: stringifyJSON
- },
- {
- identify: value => typeof value === 'boolean',
- default: true,
- tag: 'tag:yaml.org,2002:bool',
- test: /^true$|^false$/,
- resolve: str => str === 'true',
- stringify: stringifyJSON
- },
- {
- identify: intIdentify,
- default: true,
- tag: 'tag:yaml.org,2002:int',
- test: /^-?(?:0|[1-9][0-9]*)$/,
- resolve: (str, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str, 10),
- stringify: ({ value }) => intIdentify(value) ? value.toString() : JSON.stringify(value)
- },
- {
- identify: value => typeof value === 'number',
- default: true,
- tag: 'tag:yaml.org,2002:float',
- test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,
- resolve: str => parseFloat(str),
- stringify: stringifyJSON
- }
-];
-const jsonError = {
- default: true,
- tag: '',
- test: /^/,
- resolve(str, onError) {
- onError(`Unresolved plain scalar ${JSON.stringify(str)}`);
- return str;
- }
-};
-const schema = [map.map, seq.seq].concat(jsonScalars, jsonError);
-
-exports.schema = schema;
-
-
-/***/ }),
-
-/***/ 18:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var map = __nccwpck_require__(7451);
-var _null = __nccwpck_require__(1251);
-var seq = __nccwpck_require__(1706);
-var string = __nccwpck_require__(6464);
-var bool = __nccwpck_require__(6340);
-var float = __nccwpck_require__(8405);
-var int = __nccwpck_require__(9874);
-var schema = __nccwpck_require__(896);
-var schema$1 = __nccwpck_require__(3559);
-var binary = __nccwpck_require__(6083);
-var merge = __nccwpck_require__(452);
-var omap = __nccwpck_require__(303);
-var pairs = __nccwpck_require__(8385);
-var schema$2 = __nccwpck_require__(5913);
-var set = __nccwpck_require__(1528);
-var timestamp = __nccwpck_require__(6752);
-
-const schemas = new Map([
- ['core', schema.schema],
- ['failsafe', [map.map, seq.seq, string.string]],
- ['json', schema$1.schema],
- ['yaml11', schema$2.schema],
- ['yaml-1.1', schema$2.schema]
-]);
-const tagsByName = {
- binary: binary.binary,
- bool: bool.boolTag,
- float: float.float,
- floatExp: float.floatExp,
- floatNaN: float.floatNaN,
- floatTime: timestamp.floatTime,
- int: int.int,
- intHex: int.intHex,
- intOct: int.intOct,
- intTime: timestamp.intTime,
- map: map.map,
- merge: merge.merge,
- null: _null.nullTag,
- omap: omap.omap,
- pairs: pairs.pairs,
- seq: seq.seq,
- set: set.set,
- timestamp: timestamp.timestamp
-};
-const coreKnownTags = {
- 'tag:yaml.org,2002:binary': binary.binary,
- 'tag:yaml.org,2002:merge': merge.merge,
- 'tag:yaml.org,2002:omap': omap.omap,
- 'tag:yaml.org,2002:pairs': pairs.pairs,
- 'tag:yaml.org,2002:set': set.set,
- 'tag:yaml.org,2002:timestamp': timestamp.timestamp
-};
-function getTags(customTags, schemaName, addMergeTag) {
- const schemaTags = schemas.get(schemaName);
- if (schemaTags && !customTags) {
- return addMergeTag && !schemaTags.includes(merge.merge)
- ? schemaTags.concat(merge.merge)
- : schemaTags.slice();
- }
- let tags = schemaTags;
- if (!tags) {
- if (Array.isArray(customTags))
- tags = [];
- else {
- const keys = Array.from(schemas.keys())
- .filter(key => key !== 'yaml11')
- .map(key => JSON.stringify(key))
- .join(', ');
- throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`);
- }
- }
- if (Array.isArray(customTags)) {
- for (const tag of customTags)
- tags = tags.concat(tag);
- }
- else if (typeof customTags === 'function') {
- tags = customTags(tags.slice());
- }
- if (addMergeTag)
- tags = tags.concat(merge.merge);
- return tags.reduce((tags, tag) => {
- const tagObj = typeof tag === 'string' ? tagsByName[tag] : tag;
- if (!tagObj) {
- const tagName = JSON.stringify(tag);
- const keys = Object.keys(tagsByName)
- .map(key => JSON.stringify(key))
- .join(', ');
- throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`);
- }
- if (!tags.includes(tagObj))
- tags.push(tagObj);
- return tags;
- }, []);
-}
-
-exports.coreKnownTags = coreKnownTags;
-exports.getTags = getTags;
-
-
-/***/ }),
-
-/***/ 6083:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var node_buffer = __nccwpck_require__(181);
-var Scalar = __nccwpck_require__(3301);
-var stringifyString = __nccwpck_require__(5450);
-
-const binary = {
- identify: value => value instanceof Uint8Array, // Buffer inherits from Uint8Array
- default: false,
- tag: 'tag:yaml.org,2002:binary',
- /**
- * Returns a Buffer in node and an Uint8Array in browsers
- *
- * To use the resulting buffer as an image, you'll want to do something like:
- *
- * const blob = new Blob([buffer], { type: 'image/jpeg' })
- * document.querySelector('#photo').src = URL.createObjectURL(blob)
- */
- resolve(src, onError) {
- if (typeof node_buffer.Buffer === 'function') {
- return node_buffer.Buffer.from(src, 'base64');
- }
- else if (typeof atob === 'function') {
- // On IE 11, atob() can't handle newlines
- const str = atob(src.replace(/[\n\r]/g, ''));
- const buffer = new Uint8Array(str.length);
- for (let i = 0; i < str.length; ++i)
- buffer[i] = str.charCodeAt(i);
- return buffer;
- }
- else {
- onError('This environment does not support reading binary tags; either Buffer or atob is required');
- return src;
- }
- },
- stringify({ comment, type, value }, ctx, onComment, onChompKeep) {
- if (!value)
- return '';
- const buf = value; // checked earlier by binary.identify()
- let str;
- if (typeof node_buffer.Buffer === 'function') {
- str =
- buf instanceof node_buffer.Buffer
- ? buf.toString('base64')
- : node_buffer.Buffer.from(buf.buffer).toString('base64');
- }
- else if (typeof btoa === 'function') {
- let s = '';
- for (let i = 0; i < buf.length; ++i)
- s += String.fromCharCode(buf[i]);
- str = btoa(s);
- }
- else {
- throw new Error('This environment does not support writing binary tags; either Buffer or btoa is required');
- }
- type ?? (type = Scalar.Scalar.BLOCK_LITERAL);
- if (type !== Scalar.Scalar.QUOTE_DOUBLE) {
- const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth);
- const n = Math.ceil(str.length / lineWidth);
- const lines = new Array(n);
- for (let i = 0, o = 0; i < n; ++i, o += lineWidth) {
- lines[i] = str.substr(o, lineWidth);
- }
- str = lines.join(type === Scalar.Scalar.BLOCK_LITERAL ? '\n' : ' ');
- }
- return stringifyString.stringifyString({ comment, type, value: str }, ctx, onComment, onChompKeep);
- }
-};
-
-exports.binary = binary;
-
-
-/***/ }),
-
-/***/ 8398:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var Scalar = __nccwpck_require__(3301);
-
-function boolStringify({ value, source }, ctx) {
- const boolObj = value ? trueTag : falseTag;
- if (source && boolObj.test.test(source))
- return source;
- return value ? ctx.options.trueStr : ctx.options.falseStr;
-}
-const trueTag = {
- identify: value => value === true,
- default: true,
- tag: 'tag:yaml.org,2002:bool',
- test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,
- resolve: () => new Scalar.Scalar(true),
- stringify: boolStringify
-};
-const falseTag = {
- identify: value => value === false,
- default: true,
- tag: 'tag:yaml.org,2002:bool',
- test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,
- resolve: () => new Scalar.Scalar(false),
- stringify: boolStringify
-};
-
-exports.falseTag = falseTag;
-exports.trueTag = trueTag;
-
-
-/***/ }),
-
-/***/ 5782:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var Scalar = __nccwpck_require__(3301);
-var stringifyNumber = __nccwpck_require__(8689);
-
-const floatNaN = {
- identify: value => typeof value === 'number',
- default: true,
- tag: 'tag:yaml.org,2002:float',
- test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,
- resolve: (str) => str.slice(-3).toLowerCase() === 'nan'
- ? NaN
- : str[0] === '-'
- ? Number.NEGATIVE_INFINITY
- : Number.POSITIVE_INFINITY,
- stringify: stringifyNumber.stringifyNumber
-};
-const floatExp = {
- identify: value => typeof value === 'number',
- default: true,
- tag: 'tag:yaml.org,2002:float',
- format: 'EXP',
- test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,
- resolve: (str) => parseFloat(str.replace(/_/g, '')),
- stringify(node) {
- const num = Number(node.value);
- return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node);
- }
-};
-const float = {
- identify: value => typeof value === 'number',
- default: true,
- tag: 'tag:yaml.org,2002:float',
- test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,
- resolve(str) {
- const node = new Scalar.Scalar(parseFloat(str.replace(/_/g, '')));
- const dot = str.indexOf('.');
- if (dot !== -1) {
- const f = str.substring(dot + 1).replace(/_/g, '');
- if (f[f.length - 1] === '0')
- node.minFractionDigits = f.length;
- }
- return node;
- },
- stringify: stringifyNumber.stringifyNumber
-};
-
-exports.float = float;
-exports.floatExp = floatExp;
-exports.floatNaN = floatNaN;
-
-
-/***/ }),
-
-/***/ 873:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var stringifyNumber = __nccwpck_require__(8689);
-
-const intIdentify = (value) => typeof value === 'bigint' || Number.isInteger(value);
-function intResolve(str, offset, radix, { intAsBigInt }) {
- const sign = str[0];
- if (sign === '-' || sign === '+')
- offset += 1;
- str = str.substring(offset).replace(/_/g, '');
- if (intAsBigInt) {
- switch (radix) {
- case 2:
- str = `0b${str}`;
- break;
- case 8:
- str = `0o${str}`;
- break;
- case 16:
- str = `0x${str}`;
- break;
- }
- const n = BigInt(str);
- return sign === '-' ? BigInt(-1) * n : n;
- }
- const n = parseInt(str, radix);
- return sign === '-' ? -1 * n : n;
-}
-function intStringify(node, radix, prefix) {
- const { value } = node;
- if (intIdentify(value)) {
- const str = value.toString(radix);
- return value < 0 ? '-' + prefix + str.substr(1) : prefix + str;
- }
- return stringifyNumber.stringifyNumber(node);
-}
-const intBin = {
- identify: intIdentify,
- default: true,
- tag: 'tag:yaml.org,2002:int',
- format: 'BIN',
- test: /^[-+]?0b[0-1_]+$/,
- resolve: (str, _onError, opt) => intResolve(str, 2, 2, opt),
- stringify: node => intStringify(node, 2, '0b')
-};
-const intOct = {
- identify: intIdentify,
- default: true,
- tag: 'tag:yaml.org,2002:int',
- format: 'OCT',
- test: /^[-+]?0[0-7_]+$/,
- resolve: (str, _onError, opt) => intResolve(str, 1, 8, opt),
- stringify: node => intStringify(node, 8, '0')
-};
-const int = {
- identify: intIdentify,
- default: true,
- tag: 'tag:yaml.org,2002:int',
- test: /^[-+]?[0-9][0-9_]*$/,
- resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),
- stringify: stringifyNumber.stringifyNumber
-};
-const intHex = {
- identify: intIdentify,
- default: true,
- tag: 'tag:yaml.org,2002:int',
- format: 'HEX',
- test: /^[-+]?0x[0-9a-fA-F_]+$/,
- resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),
- stringify: node => intStringify(node, 16, '0x')
-};
-
-exports.int = int;
-exports.intBin = intBin;
-exports.intHex = intHex;
-exports.intOct = intOct;
-
-
-/***/ }),
-
-/***/ 452:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var identity = __nccwpck_require__(1127);
-var Scalar = __nccwpck_require__(3301);
-
-// If the value associated with a merge key is a single mapping node, each of
-// its key/value pairs is inserted into the current mapping, unless the key
-// already exists in it. If the value associated with the merge key is a
-// sequence, then this sequence is expected to contain mapping nodes and each
-// of these nodes is merged in turn according to its order in the sequence.
-// Keys in mapping nodes earlier in the sequence override keys specified in
-// later mapping nodes. -- http://yaml.org/type/merge.html
-const MERGE_KEY = '<<';
-const merge = {
- identify: value => value === MERGE_KEY ||
- (typeof value === 'symbol' && value.description === MERGE_KEY),
- default: 'key',
- tag: 'tag:yaml.org,2002:merge',
- test: /^<<$/,
- resolve: () => Object.assign(new Scalar.Scalar(Symbol(MERGE_KEY)), {
- addToJSMap: addMergeToJSMap
- }),
- stringify: () => MERGE_KEY
-};
-const isMergeKey = (ctx, key) => (merge.identify(key) ||
- (identity.isScalar(key) &&
- (!key.type || key.type === Scalar.Scalar.PLAIN) &&
- merge.identify(key.value))) &&
- ctx?.doc.schema.tags.some(tag => tag.tag === merge.tag && tag.default);
-function addMergeToJSMap(ctx, map, value) {
- value = ctx && identity.isAlias(value) ? value.resolve(ctx.doc) : value;
- if (identity.isSeq(value))
- for (const it of value.items)
- mergeValue(ctx, map, it);
- else if (Array.isArray(value))
- for (const it of value)
- mergeValue(ctx, map, it);
- else
- mergeValue(ctx, map, value);
-}
-function mergeValue(ctx, map, value) {
- const source = ctx && identity.isAlias(value) ? value.resolve(ctx.doc) : value;
- if (!identity.isMap(source))
- throw new Error('Merge sources must be maps or map aliases');
- const srcMap = source.toJSON(null, ctx, Map);
- for (const [key, value] of srcMap) {
- if (map instanceof Map) {
- if (!map.has(key))
- map.set(key, value);
- }
- else if (map instanceof Set) {
- map.add(key);
- }
- else if (!Object.prototype.hasOwnProperty.call(map, key)) {
- Object.defineProperty(map, key, {
- value,
- writable: true,
- enumerable: true,
- configurable: true
- });
- }
- }
- return map;
-}
-
-exports.addMergeToJSMap = addMergeToJSMap;
-exports.isMergeKey = isMergeKey;
-exports.merge = merge;
-
-
-/***/ }),
-
-/***/ 303:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var identity = __nccwpck_require__(1127);
-var toJS = __nccwpck_require__(4043);
-var YAMLMap = __nccwpck_require__(4454);
-var YAMLSeq = __nccwpck_require__(2223);
-var pairs = __nccwpck_require__(8385);
-
-class YAMLOMap extends YAMLSeq.YAMLSeq {
- constructor() {
- super();
- this.add = YAMLMap.YAMLMap.prototype.add.bind(this);
- this.delete = YAMLMap.YAMLMap.prototype.delete.bind(this);
- this.get = YAMLMap.YAMLMap.prototype.get.bind(this);
- this.has = YAMLMap.YAMLMap.prototype.has.bind(this);
- this.set = YAMLMap.YAMLMap.prototype.set.bind(this);
- this.tag = YAMLOMap.tag;
- }
- /**
- * If `ctx` is given, the return type is actually `Map`,
- * but TypeScript won't allow widening the signature of a child method.
- */
- toJSON(_, ctx) {
- if (!ctx)
- return super.toJSON(_);
- const map = new Map();
- if (ctx?.onCreate)
- ctx.onCreate(map);
- for (const pair of this.items) {
- let key, value;
- if (identity.isPair(pair)) {
- key = toJS.toJS(pair.key, '', ctx);
- value = toJS.toJS(pair.value, key, ctx);
- }
- else {
- key = toJS.toJS(pair, '', ctx);
- }
- if (map.has(key))
- throw new Error('Ordered maps must not include duplicate keys');
- map.set(key, value);
- }
- return map;
- }
- static from(schema, iterable, ctx) {
- const pairs$1 = pairs.createPairs(schema, iterable, ctx);
- const omap = new this();
- omap.items = pairs$1.items;
- return omap;
- }
-}
-YAMLOMap.tag = 'tag:yaml.org,2002:omap';
-const omap = {
- collection: 'seq',
- identify: value => value instanceof Map,
- nodeClass: YAMLOMap,
- default: false,
- tag: 'tag:yaml.org,2002:omap',
- resolve(seq, onError) {
- const pairs$1 = pairs.resolvePairs(seq, onError);
- const seenKeys = [];
- for (const { key } of pairs$1.items) {
- if (identity.isScalar(key)) {
- if (seenKeys.includes(key.value)) {
- onError(`Ordered maps must not include duplicate keys: ${key.value}`);
- }
- else {
- seenKeys.push(key.value);
- }
- }
- }
- return Object.assign(new YAMLOMap(), pairs$1);
- },
- createNode: (schema, iterable, ctx) => YAMLOMap.from(schema, iterable, ctx)
-};
-
-exports.YAMLOMap = YAMLOMap;
-exports.omap = omap;
-
-
-/***/ }),
-
-/***/ 8385:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var identity = __nccwpck_require__(1127);
-var Pair = __nccwpck_require__(7165);
-var Scalar = __nccwpck_require__(3301);
-var YAMLSeq = __nccwpck_require__(2223);
-
-function resolvePairs(seq, onError) {
- if (identity.isSeq(seq)) {
- for (let i = 0; i < seq.items.length; ++i) {
- let item = seq.items[i];
- if (identity.isPair(item))
- continue;
- else if (identity.isMap(item)) {
- if (item.items.length > 1)
- onError('Each pair must have its own sequence indicator');
- const pair = item.items[0] || new Pair.Pair(new Scalar.Scalar(null));
- if (item.commentBefore)
- pair.key.commentBefore = pair.key.commentBefore
- ? `${item.commentBefore}\n${pair.key.commentBefore}`
- : item.commentBefore;
- if (item.comment) {
- const cn = pair.value ?? pair.key;
- cn.comment = cn.comment
- ? `${item.comment}\n${cn.comment}`
- : item.comment;
- }
- item = pair;
- }
- seq.items[i] = identity.isPair(item) ? item : new Pair.Pair(item);
- }
- }
- else
- onError('Expected a sequence for this tag');
- return seq;
-}
-function createPairs(schema, iterable, ctx) {
- const { replacer } = ctx;
- const pairs = new YAMLSeq.YAMLSeq(schema);
- pairs.tag = 'tag:yaml.org,2002:pairs';
- let i = 0;
- if (iterable && Symbol.iterator in Object(iterable))
- for (let it of iterable) {
- if (typeof replacer === 'function')
- it = replacer.call(iterable, String(i++), it);
- let key, value;
- if (Array.isArray(it)) {
- if (it.length === 2) {
- key = it[0];
- value = it[1];
- }
- else
- throw new TypeError(`Expected [key, value] tuple: ${it}`);
- }
- else if (it && it instanceof Object) {
- const keys = Object.keys(it);
- if (keys.length === 1) {
- key = keys[0];
- value = it[key];
- }
- else {
- throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`);
- }
- }
- else {
- key = it;
- }
- pairs.items.push(Pair.createPair(key, value, ctx));
- }
- return pairs;
-}
-const pairs = {
- collection: 'seq',
- default: false,
- tag: 'tag:yaml.org,2002:pairs',
- resolve: resolvePairs,
- createNode: createPairs
-};
-
-exports.createPairs = createPairs;
-exports.pairs = pairs;
-exports.resolvePairs = resolvePairs;
-
-
-/***/ }),
-
-/***/ 5913:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var map = __nccwpck_require__(7451);
-var _null = __nccwpck_require__(1251);
-var seq = __nccwpck_require__(1706);
-var string = __nccwpck_require__(6464);
-var binary = __nccwpck_require__(6083);
-var bool = __nccwpck_require__(8398);
-var float = __nccwpck_require__(5782);
-var int = __nccwpck_require__(873);
-var merge = __nccwpck_require__(452);
-var omap = __nccwpck_require__(303);
-var pairs = __nccwpck_require__(8385);
-var set = __nccwpck_require__(1528);
-var timestamp = __nccwpck_require__(6752);
-
-const schema = [
- map.map,
- seq.seq,
- string.string,
- _null.nullTag,
- bool.trueTag,
- bool.falseTag,
- int.intBin,
- int.intOct,
- int.int,
- int.intHex,
- float.floatNaN,
- float.floatExp,
- float.float,
- binary.binary,
- merge.merge,
- omap.omap,
- pairs.pairs,
- set.set,
- timestamp.intTime,
- timestamp.floatTime,
- timestamp.timestamp
-];
-
-exports.schema = schema;
-
-
-/***/ }),
-
-/***/ 1528:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var identity = __nccwpck_require__(1127);
-var Pair = __nccwpck_require__(7165);
-var YAMLMap = __nccwpck_require__(4454);
-
-class YAMLSet extends YAMLMap.YAMLMap {
- constructor(schema) {
- super(schema);
- this.tag = YAMLSet.tag;
- }
- add(key) {
- let pair;
- if (identity.isPair(key))
- pair = key;
- else if (key &&
- typeof key === 'object' &&
- 'key' in key &&
- 'value' in key &&
- key.value === null)
- pair = new Pair.Pair(key.key, null);
- else
- pair = new Pair.Pair(key, null);
- const prev = YAMLMap.findPair(this.items, pair.key);
- if (!prev)
- this.items.push(pair);
- }
- /**
- * If `keepPair` is `true`, returns the Pair matching `key`.
- * Otherwise, returns the value of that Pair's key.
- */
- get(key, keepPair) {
- const pair = YAMLMap.findPair(this.items, key);
- return !keepPair && identity.isPair(pair)
- ? identity.isScalar(pair.key)
- ? pair.key.value
- : pair.key
- : pair;
- }
- set(key, value) {
- if (typeof value !== 'boolean')
- throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`);
- const prev = YAMLMap.findPair(this.items, key);
- if (prev && !value) {
- this.items.splice(this.items.indexOf(prev), 1);
- }
- else if (!prev && value) {
- this.items.push(new Pair.Pair(key));
- }
- }
- toJSON(_, ctx) {
- return super.toJSON(_, ctx, Set);
- }
- toString(ctx, onComment, onChompKeep) {
- if (!ctx)
- return JSON.stringify(this);
- if (this.hasAllNullValues(true))
- return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep);
- else
- throw new Error('Set items must all have null values');
- }
- static from(schema, iterable, ctx) {
- const { replacer } = ctx;
- const set = new this(schema);
- if (iterable && Symbol.iterator in Object(iterable))
- for (let value of iterable) {
- if (typeof replacer === 'function')
- value = replacer.call(iterable, value, value);
- set.items.push(Pair.createPair(value, null, ctx));
- }
- return set;
- }
-}
-YAMLSet.tag = 'tag:yaml.org,2002:set';
-const set = {
- collection: 'map',
- identify: value => value instanceof Set,
- nodeClass: YAMLSet,
- default: false,
- tag: 'tag:yaml.org,2002:set',
- createNode: (schema, iterable, ctx) => YAMLSet.from(schema, iterable, ctx),
- resolve(map, onError) {
- if (identity.isMap(map)) {
- if (map.hasAllNullValues(true))
- return Object.assign(new YAMLSet(), map);
- else
- onError('Set items must all have null values');
- }
- else
- onError('Expected a mapping for this tag');
- return map;
- }
-};
-
-exports.YAMLSet = YAMLSet;
-exports.set = set;
-
-
-/***/ }),
-
-/***/ 6752:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var stringifyNumber = __nccwpck_require__(8689);
-
-/** Internal types handle bigint as number, because TS can't figure it out. */
-function parseSexagesimal(str, asBigInt) {
- const sign = str[0];
- const parts = sign === '-' || sign === '+' ? str.substring(1) : str;
- const num = (n) => asBigInt ? BigInt(n) : Number(n);
- const res = parts
- .replace(/_/g, '')
- .split(':')
- .reduce((res, p) => res * num(60) + num(p), num(0));
- return (sign === '-' ? num(-1) * res : res);
-}
-/**
- * hhhh:mm:ss.sss
- *
- * Internal types handle bigint as number, because TS can't figure it out.
- */
-function stringifySexagesimal(node) {
- let { value } = node;
- let num = (n) => n;
- if (typeof value === 'bigint')
- num = n => BigInt(n);
- else if (isNaN(value) || !isFinite(value))
- return stringifyNumber.stringifyNumber(node);
- let sign = '';
- if (value < 0) {
- sign = '-';
- value *= num(-1);
- }
- const _60 = num(60);
- const parts = [value % _60]; // seconds, including ms
- if (value < 60) {
- parts.unshift(0); // at least one : is required
- }
- else {
- value = (value - parts[0]) / _60;
- parts.unshift(value % _60); // minutes
- if (value >= 60) {
- value = (value - parts[0]) / _60;
- parts.unshift(value); // hours
- }
- }
- return (sign +
- parts
- .map(n => String(n).padStart(2, '0'))
- .join(':')
- .replace(/000000\d*$/, '') // % 60 may introduce error
- );
-}
-const intTime = {
- identify: value => typeof value === 'bigint' || Number.isInteger(value),
- default: true,
- tag: 'tag:yaml.org,2002:int',
- format: 'TIME',
- test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,
- resolve: (str, _onError, { intAsBigInt }) => parseSexagesimal(str, intAsBigInt),
- stringify: stringifySexagesimal
-};
-const floatTime = {
- identify: value => typeof value === 'number',
- default: true,
- tag: 'tag:yaml.org,2002:float',
- format: 'TIME',
- test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,
- resolve: str => parseSexagesimal(str, false),
- stringify: stringifySexagesimal
-};
-const timestamp = {
- identify: value => value instanceof Date,
- default: true,
- tag: 'tag:yaml.org,2002:timestamp',
- // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part
- // may be omitted altogether, resulting in a date format. In such a case, the time part is
- // assumed to be 00:00:00Z (start of day, UTC).
- test: RegExp('^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})' + // YYYY-Mm-Dd
- '(?:' + // time is optional
- '(?:t|T|[ \\t]+)' + // t | T | whitespace
- '([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)' + // Hh:Mm:Ss(.ss)?
- '(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?' + // Z | +5 | -03:30
- ')?$'),
- resolve(str) {
- const match = str.match(timestamp.test);
- if (!match)
- throw new Error('!!timestamp expects a date, starting with yyyy-mm-dd');
- const [, year, month, day, hour, minute, second] = match.map(Number);
- const millisec = match[7] ? Number((match[7] + '00').substr(1, 3)) : 0;
- let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec);
- const tz = match[8];
- if (tz && tz !== 'Z') {
- let d = parseSexagesimal(tz, false);
- if (Math.abs(d) < 30)
- d *= 60;
- date -= 60000 * d;
- }
- return new Date(date);
- },
- stringify: ({ value }) => value?.toISOString().replace(/(T00:00:00)?\.000Z$/, '') ?? ''
-};
-
-exports.floatTime = floatTime;
-exports.intTime = intTime;
-exports.timestamp = timestamp;
-
-
-/***/ }),
-
-/***/ 4475:
-/***/ ((__unused_webpack_module, exports) => {
-
-
-
-const FOLD_FLOW = 'flow';
-const FOLD_BLOCK = 'block';
-const FOLD_QUOTED = 'quoted';
-/**
- * Tries to keep input at up to `lineWidth` characters, splitting only on spaces
- * not followed by newlines or spaces unless `mode` is `'quoted'`. Lines are
- * terminated with `\n` and started with `indent`.
- */
-function foldFlowLines(text, indent, mode = 'flow', { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) {
- if (!lineWidth || lineWidth < 0)
- return text;
- if (lineWidth < minContentWidth)
- minContentWidth = 0;
- const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length);
- if (text.length <= endStep)
- return text;
- const folds = [];
- const escapedFolds = {};
- let end = lineWidth - indent.length;
- if (typeof indentAtStart === 'number') {
- if (indentAtStart > lineWidth - Math.max(2, minContentWidth))
- folds.push(0);
- else
- end = lineWidth - indentAtStart;
- }
- let split = undefined;
- let prev = undefined;
- let overflow = false;
- let i = -1;
- let escStart = -1;
- let escEnd = -1;
- if (mode === FOLD_BLOCK) {
- i = consumeMoreIndentedLines(text, i, indent.length);
- if (i !== -1)
- end = i + endStep;
- }
- for (let ch; (ch = text[(i += 1)]);) {
- if (mode === FOLD_QUOTED && ch === '\\') {
- escStart = i;
- switch (text[i + 1]) {
- case 'x':
- i += 3;
- break;
- case 'u':
- i += 5;
- break;
- case 'U':
- i += 9;
- break;
- default:
- i += 1;
- }
- escEnd = i;
- }
- if (ch === '\n') {
- if (mode === FOLD_BLOCK)
- i = consumeMoreIndentedLines(text, i, indent.length);
- end = i + indent.length + endStep;
- split = undefined;
- }
- else {
- if (ch === ' ' &&
- prev &&
- prev !== ' ' &&
- prev !== '\n' &&
- prev !== '\t') {
- // space surrounded by non-space can be replaced with newline + indent
- const next = text[i + 1];
- if (next && next !== ' ' && next !== '\n' && next !== '\t')
- split = i;
- }
- if (i >= end) {
- if (split) {
- folds.push(split);
- end = split + endStep;
- split = undefined;
- }
- else if (mode === FOLD_QUOTED) {
- // white-space collected at end may stretch past lineWidth
- while (prev === ' ' || prev === '\t') {
- prev = ch;
- ch = text[(i += 1)];
- overflow = true;
- }
- // Account for newline escape, but don't break preceding escape
- const j = i > escEnd + 1 ? i - 2 : escStart - 1;
- // Bail out if lineWidth & minContentWidth are shorter than an escape string
- if (escapedFolds[j])
- return text;
- folds.push(j);
- escapedFolds[j] = true;
- end = j + endStep;
- split = undefined;
- }
- else {
- overflow = true;
- }
- }
- }
- prev = ch;
- }
- if (overflow && onOverflow)
- onOverflow();
- if (folds.length === 0)
- return text;
- if (onFold)
- onFold();
- let res = text.slice(0, folds[0]);
- for (let i = 0; i < folds.length; ++i) {
- const fold = folds[i];
- const end = folds[i + 1] || text.length;
- if (fold === 0)
- res = `\n${indent}${text.slice(0, end)}`;
- else {
- if (mode === FOLD_QUOTED && escapedFolds[fold])
- res += `${text[fold]}\\`;
- res += `\n${indent}${text.slice(fold + 1, end)}`;
- }
- }
- return res;
-}
-/**
- * Presumes `i + 1` is at the start of a line
- * @returns index of last newline in more-indented block
- */
-function consumeMoreIndentedLines(text, i, indent) {
- let end = i;
- let start = i + 1;
- let ch = text[start];
- while (ch === ' ' || ch === '\t') {
- if (i < start + indent) {
- ch = text[++i];
- }
- else {
- do {
- ch = text[++i];
- } while (ch && ch !== '\n');
- end = i;
- start = i + 1;
- ch = text[start];
- }
- }
- return end;
-}
-
-exports.FOLD_BLOCK = FOLD_BLOCK;
-exports.FOLD_FLOW = FOLD_FLOW;
-exports.FOLD_QUOTED = FOLD_QUOTED;
-exports.foldFlowLines = foldFlowLines;
-
-
-/***/ }),
-
-/***/ 9767:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var anchors = __nccwpck_require__(1596);
-var identity = __nccwpck_require__(1127);
-var stringifyComment = __nccwpck_require__(9799);
-var stringifyString = __nccwpck_require__(5450);
-
-function createStringifyContext(doc, options) {
- const opt = Object.assign({
- blockQuote: true,
- commentString: stringifyComment.stringifyComment,
- defaultKeyType: null,
- defaultStringType: 'PLAIN',
- directives: null,
- doubleQuotedAsJSON: false,
- doubleQuotedMinMultiLineLength: 40,
- falseStr: 'false',
- flowCollectionPadding: true,
- indentSeq: true,
- lineWidth: 80,
- minContentWidth: 20,
- nullStr: 'null',
- simpleKeys: false,
- singleQuote: null,
- trailingComma: false,
- trueStr: 'true',
- verifyAliasOrder: true
- }, doc.schema.toStringOptions, options);
- let inFlow;
- switch (opt.collectionStyle) {
- case 'block':
- inFlow = false;
- break;
- case 'flow':
- inFlow = true;
- break;
- default:
- inFlow = null;
- }
- return {
- anchors: new Set(),
- doc,
- flowCollectionPadding: opt.flowCollectionPadding ? ' ' : '',
- indent: '',
- indentStep: typeof opt.indent === 'number' ? ' '.repeat(opt.indent) : ' ',
- inFlow,
- options: opt
- };
-}
-function getTagObject(tags, item) {
- if (item.tag) {
- const match = tags.filter(t => t.tag === item.tag);
- if (match.length > 0)
- return match.find(t => t.format === item.format) ?? match[0];
- }
- let tagObj = undefined;
- let obj;
- if (identity.isScalar(item)) {
- obj = item.value;
- let match = tags.filter(t => t.identify?.(obj));
- if (match.length > 1) {
- const testMatch = match.filter(t => t.test);
- if (testMatch.length > 0)
- match = testMatch;
- }
- tagObj =
- match.find(t => t.format === item.format) ?? match.find(t => !t.format);
- }
- else {
- obj = item;
- tagObj = tags.find(t => t.nodeClass && obj instanceof t.nodeClass);
- }
- if (!tagObj) {
- const name = obj?.constructor?.name ?? (obj === null ? 'null' : typeof obj);
- throw new Error(`Tag not resolved for ${name} value`);
- }
- return tagObj;
-}
-// needs to be called before value stringifier to allow for circular anchor refs
-function stringifyProps(node, tagObj, { anchors: anchors$1, doc }) {
- if (!doc.directives)
- return '';
- const props = [];
- const anchor = (identity.isScalar(node) || identity.isCollection(node)) && node.anchor;
- if (anchor && anchors.anchorIsValid(anchor)) {
- anchors$1.add(anchor);
- props.push(`&${anchor}`);
- }
- const tag = node.tag ?? (tagObj.default ? null : tagObj.tag);
- if (tag)
- props.push(doc.directives.tagString(tag));
- return props.join(' ');
-}
-function stringify(item, ctx, onComment, onChompKeep) {
- if (identity.isPair(item))
- return item.toString(ctx, onComment, onChompKeep);
- if (identity.isAlias(item)) {
- if (ctx.doc.directives)
- return item.toString(ctx);
- if (ctx.resolvedAliases?.has(item)) {
- throw new TypeError(`Cannot stringify circular structure without alias nodes`);
- }
- else {
- if (ctx.resolvedAliases)
- ctx.resolvedAliases.add(item);
- else
- ctx.resolvedAliases = new Set([item]);
- item = item.resolve(ctx.doc);
- }
- }
- let tagObj = undefined;
- const node = identity.isNode(item)
- ? item
- : ctx.doc.createNode(item, { onTagObj: o => (tagObj = o) });
- tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node));
- const props = stringifyProps(node, tagObj, ctx);
- if (props.length > 0)
- ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1;
- const str = typeof tagObj.stringify === 'function'
- ? tagObj.stringify(node, ctx, onComment, onChompKeep)
- : identity.isScalar(node)
- ? stringifyString.stringifyString(node, ctx, onComment, onChompKeep)
- : node.toString(ctx, onComment, onChompKeep);
- if (!props)
- return str;
- return identity.isScalar(node) || str[0] === '{' || str[0] === '['
- ? `${props} ${str}`
- : `${props}\n${ctx.indent}${str}`;
-}
-
-exports.createStringifyContext = createStringifyContext;
-exports.stringify = stringify;
-
-
-/***/ }),
-
-/***/ 1212:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var identity = __nccwpck_require__(1127);
-var stringify = __nccwpck_require__(9767);
-var stringifyComment = __nccwpck_require__(9799);
-
-function stringifyCollection(collection, ctx, options) {
- const flow = ctx.inFlow ?? collection.flow;
- const stringify = flow ? stringifyFlowCollection : stringifyBlockCollection;
- return stringify(collection, ctx, options);
-}
-function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) {
- const { indent, options: { commentString } } = ctx;
- const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null });
- let chompKeep = false; // flag for the preceding node's status
- const lines = [];
- for (let i = 0; i < items.length; ++i) {
- const item = items[i];
- let comment = null;
- if (identity.isNode(item)) {
- if (!chompKeep && item.spaceBefore)
- lines.push('');
- addCommentBefore(ctx, lines, item.commentBefore, chompKeep);
- if (item.comment)
- comment = item.comment;
- }
- else if (identity.isPair(item)) {
- const ik = identity.isNode(item.key) ? item.key : null;
- if (ik) {
- if (!chompKeep && ik.spaceBefore)
- lines.push('');
- addCommentBefore(ctx, lines, ik.commentBefore, chompKeep);
- }
- }
- chompKeep = false;
- let str = stringify.stringify(item, itemCtx, () => (comment = null), () => (chompKeep = true));
- if (comment)
- str += stringifyComment.lineComment(str, itemIndent, commentString(comment));
- if (chompKeep && comment)
- chompKeep = false;
- lines.push(blockItemPrefix + str);
- }
- let str;
- if (lines.length === 0) {
- str = flowChars.start + flowChars.end;
- }
- else {
- str = lines[0];
- for (let i = 1; i < lines.length; ++i) {
- const line = lines[i];
- str += line ? `\n${indent}${line}` : '\n';
- }
- }
- if (comment) {
- str += '\n' + stringifyComment.indentComment(commentString(comment), indent);
- if (onComment)
- onComment();
- }
- else if (chompKeep && onChompKeep)
- onChompKeep();
- return str;
-}
-function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) {
- const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx;
- itemIndent += indentStep;
- const itemCtx = Object.assign({}, ctx, {
- indent: itemIndent,
- inFlow: true,
- type: null
- });
- let reqNewline = false;
- let linesAtValue = 0;
- const lines = [];
- for (let i = 0; i < items.length; ++i) {
- const item = items[i];
- let comment = null;
- if (identity.isNode(item)) {
- if (item.spaceBefore)
- lines.push('');
- addCommentBefore(ctx, lines, item.commentBefore, false);
- if (item.comment)
- comment = item.comment;
- }
- else if (identity.isPair(item)) {
- const ik = identity.isNode(item.key) ? item.key : null;
- if (ik) {
- if (ik.spaceBefore)
- lines.push('');
- addCommentBefore(ctx, lines, ik.commentBefore, false);
- if (ik.comment)
- reqNewline = true;
- }
- const iv = identity.isNode(item.value) ? item.value : null;
- if (iv) {
- if (iv.comment)
- comment = iv.comment;
- if (iv.commentBefore)
- reqNewline = true;
- }
- else if (item.value == null && ik?.comment) {
- comment = ik.comment;
- }
- }
- if (comment)
- reqNewline = true;
- let str = stringify.stringify(item, itemCtx, () => (comment = null));
- reqNewline || (reqNewline = lines.length > linesAtValue || str.includes('\n'));
- if (i < items.length - 1) {
- str += ',';
- }
- else if (ctx.options.trailingComma) {
- if (ctx.options.lineWidth > 0) {
- reqNewline || (reqNewline = lines.reduce((sum, line) => sum + line.length + 2, 2) +
- (str.length + 2) >
- ctx.options.lineWidth);
- }
- if (reqNewline) {
- str += ',';
- }
- }
- if (comment)
- str += stringifyComment.lineComment(str, itemIndent, commentString(comment));
- lines.push(str);
- linesAtValue = lines.length;
- }
- const { start, end } = flowChars;
- if (lines.length === 0) {
- return start + end;
- }
- else {
- if (!reqNewline) {
- const len = lines.reduce((sum, line) => sum + line.length + 2, 2);
- reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth;
- }
- if (reqNewline) {
- let str = start;
- for (const line of lines)
- str += line ? `\n${indentStep}${indent}${line}` : '\n';
- return `${str}\n${indent}${end}`;
- }
- else {
- return `${start}${fcPadding}${lines.join(' ')}${fcPadding}${end}`;
- }
- }
-}
-function addCommentBefore({ indent, options: { commentString } }, lines, comment, chompKeep) {
- if (comment && chompKeep)
- comment = comment.replace(/^\n+/, '');
- if (comment) {
- const ic = stringifyComment.indentComment(commentString(comment), indent);
- lines.push(ic.trimStart()); // Avoid double indent on first line
- }
-}
-
-exports.stringifyCollection = stringifyCollection;
-
-
-/***/ }),
-
-/***/ 9799:
-/***/ ((__unused_webpack_module, exports) => {
-
-
-
-/**
- * Stringifies a comment.
- *
- * Empty comment lines are left empty,
- * lines consisting of a single space are replaced by `#`,
- * and all other lines are prefixed with a `#`.
- */
-const stringifyComment = (str) => str.replace(/^(?!$)(?: $)?/gm, '#');
-function indentComment(comment, indent) {
- if (/^\n+$/.test(comment))
- return comment.substring(1);
- return indent ? comment.replace(/^(?! *$)/gm, indent) : comment;
-}
-const lineComment = (str, indent, comment) => str.endsWith('\n')
- ? indentComment(comment, indent)
- : comment.includes('\n')
- ? '\n' + indentComment(comment, indent)
- : (str.endsWith(' ') ? '' : ' ') + comment;
-
-exports.indentComment = indentComment;
-exports.lineComment = lineComment;
-exports.stringifyComment = stringifyComment;
-
-
-/***/ }),
-
-/***/ 6829:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var identity = __nccwpck_require__(1127);
-var stringify = __nccwpck_require__(9767);
-var stringifyComment = __nccwpck_require__(9799);
-
-function stringifyDocument(doc, options) {
- const lines = [];
- let hasDirectives = options.directives === true;
- if (options.directives !== false && doc.directives) {
- const dir = doc.directives.toString(doc);
- if (dir) {
- lines.push(dir);
- hasDirectives = true;
- }
- else if (doc.directives.docStart)
- hasDirectives = true;
- }
- if (hasDirectives)
- lines.push('---');
- const ctx = stringify.createStringifyContext(doc, options);
- const { commentString } = ctx.options;
- if (doc.commentBefore) {
- if (lines.length !== 1)
- lines.unshift('');
- const cs = commentString(doc.commentBefore);
- lines.unshift(stringifyComment.indentComment(cs, ''));
- }
- let chompKeep = false;
- let contentComment = null;
- if (doc.contents) {
- if (identity.isNode(doc.contents)) {
- if (doc.contents.spaceBefore && hasDirectives)
- lines.push('');
- if (doc.contents.commentBefore) {
- const cs = commentString(doc.contents.commentBefore);
- lines.push(stringifyComment.indentComment(cs, ''));
- }
- // top-level block scalars need to be indented if followed by a comment
- ctx.forceBlockIndent = !!doc.comment;
- contentComment = doc.contents.comment;
- }
- const onChompKeep = contentComment ? undefined : () => (chompKeep = true);
- let body = stringify.stringify(doc.contents, ctx, () => (contentComment = null), onChompKeep);
- if (contentComment)
- body += stringifyComment.lineComment(body, '', commentString(contentComment));
- if ((body[0] === '|' || body[0] === '>') &&
- lines[lines.length - 1] === '---') {
- // Top-level block scalars with a preceding doc marker ought to use the
- // same line for their header.
- lines[lines.length - 1] = `--- ${body}`;
- }
- else
- lines.push(body);
- }
- else {
- lines.push(stringify.stringify(doc.contents, ctx));
- }
- if (doc.directives?.docEnd) {
- if (doc.comment) {
- const cs = commentString(doc.comment);
- if (cs.includes('\n')) {
- lines.push('...');
- lines.push(stringifyComment.indentComment(cs, ''));
- }
- else {
- lines.push(`... ${cs}`);
- }
- }
- else {
- lines.push('...');
- }
- }
- else {
- let dc = doc.comment;
- if (dc && chompKeep)
- dc = dc.replace(/^\n+/, '');
- if (dc) {
- if ((!chompKeep || contentComment) && lines[lines.length - 1] !== '')
- lines.push('');
- lines.push(stringifyComment.indentComment(commentString(dc), ''));
- }
- }
- return lines.join('\n') + '\n';
-}
-
-exports.stringifyDocument = stringifyDocument;
-
-
-/***/ }),
-
-/***/ 8689:
-/***/ ((__unused_webpack_module, exports) => {
-
-
-
-function stringifyNumber({ format, minFractionDigits, tag, value }) {
- if (typeof value === 'bigint')
- return String(value);
- const num = typeof value === 'number' ? value : Number(value);
- if (!isFinite(num))
- return isNaN(num) ? '.nan' : num < 0 ? '-.inf' : '.inf';
- let n = Object.is(value, -0) ? '-0' : JSON.stringify(value);
- if (!format &&
- minFractionDigits &&
- (!tag || tag === 'tag:yaml.org,2002:float') &&
- /^\d/.test(n)) {
- let i = n.indexOf('.');
- if (i < 0) {
- i = n.length;
- n += '.';
- }
- let d = minFractionDigits - (n.length - i - 1);
- while (d-- > 0)
- n += '0';
- }
- return n;
-}
-
-exports.stringifyNumber = stringifyNumber;
-
-
-/***/ }),
-
-/***/ 9748:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var identity = __nccwpck_require__(1127);
-var Scalar = __nccwpck_require__(3301);
-var stringify = __nccwpck_require__(9767);
-var stringifyComment = __nccwpck_require__(9799);
-
-function stringifyPair({ key, value }, ctx, onComment, onChompKeep) {
- const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx;
- let keyComment = (identity.isNode(key) && key.comment) || null;
- if (simpleKeys) {
- if (keyComment) {
- throw new Error('With simple keys, key nodes cannot have comments');
- }
- if (identity.isCollection(key) || (!identity.isNode(key) && typeof key === 'object')) {
- const msg = 'With simple keys, collection cannot be used as a key value';
- throw new Error(msg);
- }
- }
- let explicitKey = !simpleKeys &&
- (!key ||
- (keyComment && value == null && !ctx.inFlow) ||
- identity.isCollection(key) ||
- (identity.isScalar(key)
- ? key.type === Scalar.Scalar.BLOCK_FOLDED || key.type === Scalar.Scalar.BLOCK_LITERAL
- : typeof key === 'object'));
- ctx = Object.assign({}, ctx, {
- allNullValues: false,
- implicitKey: !explicitKey && (simpleKeys || !allNullValues),
- indent: indent + indentStep
- });
- let keyCommentDone = false;
- let chompKeep = false;
- let str = stringify.stringify(key, ctx, () => (keyCommentDone = true), () => (chompKeep = true));
- if (!explicitKey && !ctx.inFlow && str.length > 1024) {
- if (simpleKeys)
- throw new Error('With simple keys, single line scalar must not span more than 1024 characters');
- explicitKey = true;
- }
- if (ctx.inFlow) {
- if (allNullValues || value == null) {
- if (keyCommentDone && onComment)
- onComment();
- return str === '' ? '?' : explicitKey ? `? ${str}` : str;
- }
- }
- else if ((allNullValues && !simpleKeys) || (value == null && explicitKey)) {
- str = `? ${str}`;
- if (keyComment && !keyCommentDone) {
- str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));
- }
- else if (chompKeep && onChompKeep)
- onChompKeep();
- return str;
- }
- if (keyCommentDone)
- keyComment = null;
- if (explicitKey) {
- if (keyComment)
- str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));
- str = `? ${str}\n${indent}:`;
- }
- else {
- str = `${str}:`;
- if (keyComment)
- str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));
- }
- let vsb, vcb, valueComment;
- if (identity.isNode(value)) {
- vsb = !!value.spaceBefore;
- vcb = value.commentBefore;
- valueComment = value.comment;
- }
- else {
- vsb = false;
- vcb = null;
- valueComment = null;
- if (value && typeof value === 'object')
- value = doc.createNode(value);
- }
- ctx.implicitKey = false;
- if (!explicitKey && !keyComment && identity.isScalar(value))
- ctx.indentAtStart = str.length + 1;
- chompKeep = false;
- if (!indentSeq &&
- indentStep.length >= 2 &&
- !ctx.inFlow &&
- !explicitKey &&
- identity.isSeq(value) &&
- !value.flow &&
- !value.tag &&
- !value.anchor) {
- // If indentSeq === false, consider '- ' as part of indentation where possible
- ctx.indent = ctx.indent.substring(2);
- }
- let valueCommentDone = false;
- const valueStr = stringify.stringify(value, ctx, () => (valueCommentDone = true), () => (chompKeep = true));
- let ws = ' ';
- if (keyComment || vsb || vcb) {
- ws = vsb ? '\n' : '';
- if (vcb) {
- const cs = commentString(vcb);
- ws += `\n${stringifyComment.indentComment(cs, ctx.indent)}`;
- }
- if (valueStr === '' && !ctx.inFlow) {
- if (ws === '\n' && valueComment)
- ws = '\n\n';
- }
- else {
- ws += `\n${ctx.indent}`;
- }
- }
- else if (!explicitKey && identity.isCollection(value)) {
- const vs0 = valueStr[0];
- const nl0 = valueStr.indexOf('\n');
- const hasNewline = nl0 !== -1;
- const flow = ctx.inFlow ?? value.flow ?? value.items.length === 0;
- if (hasNewline || !flow) {
- let hasPropsLine = false;
- if (hasNewline && (vs0 === '&' || vs0 === '!')) {
- let sp0 = valueStr.indexOf(' ');
- if (vs0 === '&' &&
- sp0 !== -1 &&
- sp0 < nl0 &&
- valueStr[sp0 + 1] === '!') {
- sp0 = valueStr.indexOf(' ', sp0 + 1);
- }
- if (sp0 === -1 || nl0 < sp0)
- hasPropsLine = true;
- }
- if (!hasPropsLine)
- ws = `\n${ctx.indent}`;
- }
- }
- else if (valueStr === '' || valueStr[0] === '\n') {
- ws = '';
- }
- str += ws + valueStr;
- if (ctx.inFlow) {
- if (valueCommentDone && onComment)
- onComment();
- }
- else if (valueComment && !valueCommentDone) {
- str += stringifyComment.lineComment(str, ctx.indent, commentString(valueComment));
- }
- else if (chompKeep && onChompKeep) {
- onChompKeep();
- }
- return str;
-}
-
-exports.stringifyPair = stringifyPair;
-
-
-/***/ }),
-
-/***/ 5450:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var Scalar = __nccwpck_require__(3301);
-var foldFlowLines = __nccwpck_require__(4475);
-
-const getFoldOptions = (ctx, isBlock) => ({
- indentAtStart: isBlock ? ctx.indent.length : ctx.indentAtStart,
- lineWidth: ctx.options.lineWidth,
- minContentWidth: ctx.options.minContentWidth
-});
-// Also checks for lines starting with %, as parsing the output as YAML 1.1 will
-// presume that's starting a new document.
-const containsDocumentMarker = (str) => /^(%|---|\.\.\.)/m.test(str);
-function lineLengthOverLimit(str, lineWidth, indentLength) {
- if (!lineWidth || lineWidth < 0)
- return false;
- const limit = lineWidth - indentLength;
- const strLen = str.length;
- if (strLen <= limit)
- return false;
- for (let i = 0, start = 0; i < strLen; ++i) {
- if (str[i] === '\n') {
- if (i - start > limit)
- return true;
- start = i + 1;
- if (strLen - start <= limit)
- return false;
- }
- }
- return true;
-}
-function doubleQuotedString(value, ctx) {
- const json = JSON.stringify(value);
- if (ctx.options.doubleQuotedAsJSON)
- return json;
- const { implicitKey } = ctx;
- const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength;
- const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : '');
- let str = '';
- let start = 0;
- for (let i = 0, ch = json[i]; ch; ch = json[++i]) {
- if (ch === ' ' && json[i + 1] === '\\' && json[i + 2] === 'n') {
- // space before newline needs to be escaped to not be folded
- str += json.slice(start, i) + '\\ ';
- i += 1;
- start = i;
- ch = '\\';
- }
- if (ch === '\\')
- switch (json[i + 1]) {
- case 'u':
- {
- str += json.slice(start, i);
- const code = json.substr(i + 2, 4);
- switch (code) {
- case '0000':
- str += '\\0';
- break;
- case '0007':
- str += '\\a';
- break;
- case '000b':
- str += '\\v';
- break;
- case '001b':
- str += '\\e';
- break;
- case '0085':
- str += '\\N';
- break;
- case '00a0':
- str += '\\_';
- break;
- case '2028':
- str += '\\L';
- break;
- case '2029':
- str += '\\P';
- break;
- default:
- if (code.substr(0, 2) === '00')
- str += '\\x' + code.substr(2);
- else
- str += json.substr(i, 6);
- }
- i += 5;
- start = i + 1;
- }
- break;
- case 'n':
- if (implicitKey ||
- json[i + 2] === '"' ||
- json.length < minMultiLineLength) {
- i += 1;
- }
- else {
- // folding will eat first newline
- str += json.slice(start, i) + '\n\n';
- while (json[i + 2] === '\\' &&
- json[i + 3] === 'n' &&
- json[i + 4] !== '"') {
- str += '\n';
- i += 2;
- }
- str += indent;
- // space after newline needs to be escaped to not be folded
- if (json[i + 2] === ' ')
- str += '\\';
- i += 1;
- start = i + 1;
- }
- break;
- default:
- i += 1;
- }
- }
- str = start ? str + json.slice(start) : json;
- return implicitKey
- ? str
- : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_QUOTED, getFoldOptions(ctx, false));
-}
-function singleQuotedString(value, ctx) {
- if (ctx.options.singleQuote === false ||
- (ctx.implicitKey && value.includes('\n')) ||
- /[ \t]\n|\n[ \t]/.test(value) // single quoted string can't have leading or trailing whitespace around newline
- )
- return doubleQuotedString(value, ctx);
- const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : '');
- const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$&\n${indent}`) + "'";
- return ctx.implicitKey
- ? res
- : foldFlowLines.foldFlowLines(res, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false));
-}
-function quotedString(value, ctx) {
- const { singleQuote } = ctx.options;
- let qs;
- if (singleQuote === false)
- qs = doubleQuotedString;
- else {
- const hasDouble = value.includes('"');
- const hasSingle = value.includes("'");
- if (hasDouble && !hasSingle)
- qs = singleQuotedString;
- else if (hasSingle && !hasDouble)
- qs = doubleQuotedString;
- else
- qs = singleQuote ? singleQuotedString : doubleQuotedString;
- }
- return qs(value, ctx);
-}
-// The negative lookbehind avoids a polynomial search,
-// but isn't supported yet on Safari: https://caniuse.com/js-regexp-lookbehind
-let blockEndNewlines;
-try {
- blockEndNewlines = new RegExp('(^|(?\n';
- // determine chomping from whitespace at value end
- let chomp;
- let endStart;
- for (endStart = value.length; endStart > 0; --endStart) {
- const ch = value[endStart - 1];
- if (ch !== '\n' && ch !== '\t' && ch !== ' ')
- break;
- }
- let end = value.substring(endStart);
- const endNlPos = end.indexOf('\n');
- if (endNlPos === -1) {
- chomp = '-'; // strip
- }
- else if (value === end || endNlPos !== end.length - 1) {
- chomp = '+'; // keep
- if (onChompKeep)
- onChompKeep();
- }
- else {
- chomp = ''; // clip
- }
- if (end) {
- value = value.slice(0, -end.length);
- if (end[end.length - 1] === '\n')
- end = end.slice(0, -1);
- end = end.replace(blockEndNewlines, `$&${indent}`);
- }
- // determine indent indicator from whitespace at value start
- let startWithSpace = false;
- let startEnd;
- let startNlPos = -1;
- for (startEnd = 0; startEnd < value.length; ++startEnd) {
- const ch = value[startEnd];
- if (ch === ' ')
- startWithSpace = true;
- else if (ch === '\n')
- startNlPos = startEnd;
- else
- break;
- }
- let start = value.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd);
- if (start) {
- value = value.substring(start.length);
- start = start.replace(/\n+/g, `$&${indent}`);
- }
- const indentSize = indent ? '2' : '1'; // root is at -1
- // Leading | or > is added later
- let header = (startWithSpace ? indentSize : '') + chomp;
- if (comment) {
- header += ' ' + commentString(comment.replace(/ ?[\r\n]+/g, ' '));
- if (onComment)
- onComment();
- }
- if (!literal) {
- const foldedValue = value
- .replace(/\n+/g, '\n$&')
- .replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, '$1$2') // more-indented lines aren't folded
- // ^ more-ind. ^ empty ^ capture next empty lines only at end of indent
- .replace(/\n+/g, `$&${indent}`);
- let literalFallback = false;
- const foldOptions = getFoldOptions(ctx, true);
- if (blockQuote !== 'folded' && type !== Scalar.Scalar.BLOCK_FOLDED) {
- foldOptions.onOverflow = () => {
- literalFallback = true;
- };
- }
- const body = foldFlowLines.foldFlowLines(`${start}${foldedValue}${end}`, indent, foldFlowLines.FOLD_BLOCK, foldOptions);
- if (!literalFallback)
- return `>${header}\n${indent}${body}`;
- }
- value = value.replace(/\n+/g, `$&${indent}`);
- return `|${header}\n${indent}${start}${value}${end}`;
-}
-function plainString(item, ctx, onComment, onChompKeep) {
- const { type, value } = item;
- const { actualString, implicitKey, indent, indentStep, inFlow } = ctx;
- if ((implicitKey && value.includes('\n')) ||
- (inFlow && /[[\]{},]/.test(value))) {
- return quotedString(value, ctx);
- }
- if (/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) {
- // not allowed:
- // - '-' or '?'
- // - start with an indicator character (except [?:-]) or /[?-] /
- // - '\n ', ': ' or ' \n' anywhere
- // - '#' not preceded by a non-space char
- // - end with ' ' or ':'
- return implicitKey || inFlow || !value.includes('\n')
- ? quotedString(value, ctx)
- : blockString(item, ctx, onComment, onChompKeep);
- }
- if (!implicitKey &&
- !inFlow &&
- type !== Scalar.Scalar.PLAIN &&
- value.includes('\n')) {
- // Where allowed & type not set explicitly, prefer block style for multiline strings
- return blockString(item, ctx, onComment, onChompKeep);
- }
- if (containsDocumentMarker(value)) {
- if (indent === '') {
- ctx.forceBlockIndent = true;
- return blockString(item, ctx, onComment, onChompKeep);
- }
- else if (implicitKey && indent === indentStep) {
- return quotedString(value, ctx);
- }
- }
- const str = value.replace(/\n+/g, `$&\n${indent}`);
- // Verify that output will be parsed as a string, as e.g. plain numbers and
- // booleans get parsed with those types in v1.2 (e.g. '42', 'true' & '0.9e-3'),
- // and others in v1.1.
- if (actualString) {
- const test = (tag) => tag.default && tag.tag !== 'tag:yaml.org,2002:str' && tag.test?.test(str);
- const { compat, tags } = ctx.doc.schema;
- if (tags.some(test) || compat?.some(test))
- return quotedString(value, ctx);
- }
- return implicitKey
- ? str
- : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false));
-}
-function stringifyString(item, ctx, onComment, onChompKeep) {
- const { implicitKey, inFlow } = ctx;
- const ss = typeof item.value === 'string'
- ? item
- : Object.assign({}, item, { value: String(item.value) });
- let { type } = item;
- if (type !== Scalar.Scalar.QUOTE_DOUBLE) {
- // force double quotes on control characters & unpaired surrogates
- if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value))
- type = Scalar.Scalar.QUOTE_DOUBLE;
- }
- const _stringify = (_type) => {
- switch (_type) {
- case Scalar.Scalar.BLOCK_FOLDED:
- case Scalar.Scalar.BLOCK_LITERAL:
- return implicitKey || inFlow
- ? quotedString(ss.value, ctx) // blocks are not valid inside flow containers
- : blockString(ss, ctx, onComment, onChompKeep);
- case Scalar.Scalar.QUOTE_DOUBLE:
- return doubleQuotedString(ss.value, ctx);
- case Scalar.Scalar.QUOTE_SINGLE:
- return singleQuotedString(ss.value, ctx);
- case Scalar.Scalar.PLAIN:
- return plainString(ss, ctx, onComment, onChompKeep);
- default:
- return null;
- }
- };
- let res = _stringify(type);
- if (res === null) {
- const { defaultKeyType, defaultStringType } = ctx.options;
- const t = (implicitKey && defaultKeyType) || defaultStringType;
- res = _stringify(t);
- if (res === null)
- throw new Error(`Unsupported default string type ${t}`);
- }
- return res;
-}
-
-exports.stringifyString = stringifyString;
-
-
-/***/ }),
-
-/***/ 204:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-
-var identity = __nccwpck_require__(1127);
-
-const BREAK = Symbol('break visit');
-const SKIP = Symbol('skip children');
-const REMOVE = Symbol('remove node');
-/**
- * Apply a visitor to an AST node or document.
- *
- * Walks through the tree (depth-first) starting from `node`, calling a
- * `visitor` function with three arguments:
- * - `key`: For sequence values and map `Pair`, the node's index in the
- * collection. Within a `Pair`, `'key'` or `'value'`, correspondingly.
- * `null` for the root node.
- * - `node`: The current node.
- * - `path`: The ancestry of the current node.
- *
- * The return value of the visitor may be used to control the traversal:
- * - `undefined` (default): Do nothing and continue
- * - `visit.SKIP`: Do not visit the children of this node, continue with next
- * sibling
- * - `visit.BREAK`: Terminate traversal completely
- * - `visit.REMOVE`: Remove the current node, then continue with the next one
- * - `Node`: Replace the current node, then continue by visiting it
- * - `number`: While iterating the items of a sequence or map, set the index
- * of the next step. This is useful especially if the index of the current
- * node has changed.
- *
- * If `visitor` is a single function, it will be called with all values
- * encountered in the tree, including e.g. `null` values. Alternatively,
- * separate visitor functions may be defined for each `Map`, `Pair`, `Seq`,
- * `Alias` and `Scalar` node. To define the same visitor function for more than
- * one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar)
- * and `Node` (alias, map, seq & scalar) targets. Of all these, only the most
- * specific defined one will be used for each node.
- */
-function visit(node, visitor) {
- const visitor_ = initVisitor(visitor);
- if (identity.isDocument(node)) {
- const cd = visit_(null, node.contents, visitor_, Object.freeze([node]));
- if (cd === REMOVE)
- node.contents = null;
- }
- else
- visit_(null, node, visitor_, Object.freeze([]));
-}
-// Without the `as symbol` casts, TS declares these in the `visit`
-// namespace using `var`, but then complains about that because
-// `unique symbol` must be `const`.
-/** Terminate visit traversal completely */
-visit.BREAK = BREAK;
-/** Do not visit the children of the current node */
-visit.SKIP = SKIP;
-/** Remove the current node */
-visit.REMOVE = REMOVE;
-function visit_(key, node, visitor, path) {
- const ctrl = callVisitor(key, node, visitor, path);
- if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
- replaceNode(key, path, ctrl);
- return visit_(key, ctrl, visitor, path);
- }
- if (typeof ctrl !== 'symbol') {
- if (identity.isCollection(node)) {
- path = Object.freeze(path.concat(node));
- for (let i = 0; i < node.items.length; ++i) {
- const ci = visit_(i, node.items[i], visitor, path);
- if (typeof ci === 'number')
- i = ci - 1;
- else if (ci === BREAK)
- return BREAK;
- else if (ci === REMOVE) {
- node.items.splice(i, 1);
- i -= 1;
- }
- }
- }
- else if (identity.isPair(node)) {
- path = Object.freeze(path.concat(node));
- const ck = visit_('key', node.key, visitor, path);
- if (ck === BREAK)
- return BREAK;
- else if (ck === REMOVE)
- node.key = null;
- const cv = visit_('value', node.value, visitor, path);
- if (cv === BREAK)
- return BREAK;
- else if (cv === REMOVE)
- node.value = null;
- }
- }
- return ctrl;
-}
-/**
- * Apply an async visitor to an AST node or document.
- *
- * Walks through the tree (depth-first) starting from `node`, calling a
- * `visitor` function with three arguments:
- * - `key`: For sequence values and map `Pair`, the node's index in the
- * collection. Within a `Pair`, `'key'` or `'value'`, correspondingly.
- * `null` for the root node.
- * - `node`: The current node.
- * - `path`: The ancestry of the current node.
- *
- * The return value of the visitor may be used to control the traversal:
- * - `Promise`: Must resolve to one of the following values
- * - `undefined` (default): Do nothing and continue
- * - `visit.SKIP`: Do not visit the children of this node, continue with next
- * sibling
- * - `visit.BREAK`: Terminate traversal completely
- * - `visit.REMOVE`: Remove the current node, then continue with the next one
- * - `Node`: Replace the current node, then continue by visiting it
- * - `number`: While iterating the items of a sequence or map, set the index
- * of the next step. This is useful especially if the index of the current
- * node has changed.
- *
- * If `visitor` is a single function, it will be called with all values
- * encountered in the tree, including e.g. `null` values. Alternatively,
- * separate visitor functions may be defined for each `Map`, `Pair`, `Seq`,
- * `Alias` and `Scalar` node. To define the same visitor function for more than
- * one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar)
- * and `Node` (alias, map, seq & scalar) targets. Of all these, only the most
- * specific defined one will be used for each node.
- */
-async function visitAsync(node, visitor) {
- const visitor_ = initVisitor(visitor);
- if (identity.isDocument(node)) {
- const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node]));
- if (cd === REMOVE)
- node.contents = null;
- }
- else
- await visitAsync_(null, node, visitor_, Object.freeze([]));
-}
-// Without the `as symbol` casts, TS declares these in the `visit`
-// namespace using `var`, but then complains about that because
-// `unique symbol` must be `const`.
-/** Terminate visit traversal completely */
-visitAsync.BREAK = BREAK;
-/** Do not visit the children of the current node */
-visitAsync.SKIP = SKIP;
-/** Remove the current node */
-visitAsync.REMOVE = REMOVE;
-async function visitAsync_(key, node, visitor, path) {
- const ctrl = await callVisitor(key, node, visitor, path);
- if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
- replaceNode(key, path, ctrl);
- return visitAsync_(key, ctrl, visitor, path);
- }
- if (typeof ctrl !== 'symbol') {
- if (identity.isCollection(node)) {
- path = Object.freeze(path.concat(node));
- for (let i = 0; i < node.items.length; ++i) {
- const ci = await visitAsync_(i, node.items[i], visitor, path);
- if (typeof ci === 'number')
- i = ci - 1;
- else if (ci === BREAK)
- return BREAK;
- else if (ci === REMOVE) {
- node.items.splice(i, 1);
- i -= 1;
- }
- }
- }
- else if (identity.isPair(node)) {
- path = Object.freeze(path.concat(node));
- const ck = await visitAsync_('key', node.key, visitor, path);
- if (ck === BREAK)
- return BREAK;
- else if (ck === REMOVE)
- node.key = null;
- const cv = await visitAsync_('value', node.value, visitor, path);
- if (cv === BREAK)
- return BREAK;
- else if (cv === REMOVE)
- node.value = null;
- }
- }
- return ctrl;
-}
-function initVisitor(visitor) {
- if (typeof visitor === 'object' &&
- (visitor.Collection || visitor.Node || visitor.Value)) {
- return Object.assign({
- Alias: visitor.Node,
- Map: visitor.Node,
- Scalar: visitor.Node,
- Seq: visitor.Node
- }, visitor.Value && {
- Map: visitor.Value,
- Scalar: visitor.Value,
- Seq: visitor.Value
- }, visitor.Collection && {
- Map: visitor.Collection,
- Seq: visitor.Collection
- }, visitor);
- }
- return visitor;
-}
-function callVisitor(key, node, visitor, path) {
- if (typeof visitor === 'function')
- return visitor(key, node, path);
- if (identity.isMap(node))
- return visitor.Map?.(key, node, path);
- if (identity.isSeq(node))
- return visitor.Seq?.(key, node, path);
- if (identity.isPair(node))
- return visitor.Pair?.(key, node, path);
- if (identity.isScalar(node))
- return visitor.Scalar?.(key, node, path);
- if (identity.isAlias(node))
- return visitor.Alias?.(key, node, path);
- return undefined;
-}
-function replaceNode(key, path, node) {
- const parent = path[path.length - 1];
- if (identity.isCollection(parent)) {
- parent.items[key] = node;
- }
- else if (identity.isPair(parent)) {
- if (key === 'key')
- parent.key = node;
- else
- parent.value = node;
- }
- else if (identity.isDocument(parent)) {
- parent.contents = node;
- }
- else {
- const pt = identity.isAlias(parent) ? 'alias' : 'scalar';
- throw new Error(`Cannot replace node with ${pt} parent`);
- }
-}
-
-exports.visit = visit;
-exports.visitAsync = visitAsync;
-
-
-/***/ }),
-
-/***/ 8658:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-// This file exists as a CommonJS module to read the version from package.json.
-// In an ESM package, using `require()` directly in .ts files requires disabling
-// ESLint rules and doesn't work reliably across all Node.js versions.
-// By keeping this as a .cjs file, we can use require() naturally and export
-// the version for the ESM modules to import.
-const packageJson = __nccwpck_require__(4012)
-module.exports = { version: packageJson.version }
-
-
-/***/ }),
-
-/***/ 4012:
-/***/ ((module) => {
-
-module.exports = /*#__PURE__*/JSON.parse('{"name":"@actions/cache","version":"6.0.0","description":"Actions cache lib","keywords":["github","actions","cache"],"homepage":"https://github.com/actions/toolkit/tree/main/packages/cache","license":"MIT","type":"module","main":"lib/cache.js","types":"lib/cache.d.ts","exports":{".":{"types":"./lib/cache.d.ts","import":"./lib/cache.js"}},"directories":{"lib":"lib","test":"__tests__"},"files":["lib","!.DS_Store"],"publishConfig":{"access":"public"},"repository":{"type":"git","url":"git+https://github.com/actions/toolkit.git","directory":"packages/cache"},"scripts":{"audit-moderate":"npm install && npm audit --json --audit-level=moderate > audit.json","test":"echo \\"Error: run tests from root\\" && exit 1","tsc":"tsc && cp src/internal/shared/package-version.cjs lib/internal/shared/"},"bugs":{"url":"https://github.com/actions/toolkit/issues"},"dependencies":{"@actions/core":"^3.0.0","@actions/exec":"^3.0.0","@actions/glob":"^0.6.1","@actions/http-client":"^4.0.0","@actions/io":"^3.0.0","@azure/core-rest-pipeline":"^1.22.0","@azure/storage-blob":"^12.30.0","@protobuf-ts/runtime-rpc":"^2.11.1","semver":"^7.7.3"},"devDependencies":{"@protobuf-ts/plugin":"^2.9.4","@types/node":"^25.1.0","@types/semver":"^7.7.1","typescript":"^5.2.2"},"overrides":{"uri-js":"npm:uri-js-replace@^1.0.1","node-fetch":"^3.3.2"}}');
-
-/***/ })
-
-/******/ });
-/************************************************************************/
-/******/ // The module cache
-/******/ var __webpack_module_cache__ = {};
-/******/
-/******/ // The require function
-/******/ function __nccwpck_require__(moduleId) {
-/******/ // Check if module is in cache
-/******/ var cachedModule = __webpack_module_cache__[moduleId];
-/******/ if (cachedModule !== undefined) {
-/******/ return cachedModule.exports;
-/******/ }
-/******/ // Create a new module (and put it into the cache)
-/******/ var module = __webpack_module_cache__[moduleId] = {
-/******/ // no module.id needed
-/******/ // no module.loaded needed
-/******/ exports: {}
-/******/ };
-/******/
-/******/ // Execute the module function
-/******/ var threw = true;
-/******/ try {
-/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __nccwpck_require__);
-/******/ threw = false;
-/******/ } finally {
-/******/ if(threw) delete __webpack_module_cache__[moduleId];
-/******/ }
-/******/
-/******/ // Return the exports of the module
-/******/ return module.exports;
-/******/ }
-/******/
-/************************************************************************/
-/******/ /* webpack/runtime/create fake namespace object */
-/******/ (() => {
-/******/ var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);
-/******/ var leafPrototypes;
-/******/ // create a fake namespace object
-/******/ // mode & 1: value is a module id, require it
-/******/ // mode & 2: merge all properties of value into the ns
-/******/ // mode & 4: return value when already ns object
-/******/ // mode & 16: return value when it's Promise-like
-/******/ // mode & 8|1: behave like require
-/******/ __nccwpck_require__.t = function(value, mode) {
-/******/ if(mode & 1) value = this(value);
-/******/ if(mode & 8) return value;
-/******/ if(typeof value === 'object' && value) {
-/******/ if((mode & 4) && value.__esModule) return value;
-/******/ if((mode & 16) && typeof value.then === 'function') return value;
-/******/ }
-/******/ var ns = Object.create(null);
-/******/ __nccwpck_require__.r(ns);
-/******/ var def = {};
-/******/ leafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];
-/******/ for(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) {
-/******/ Object.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));
-/******/ }
-/******/ def['default'] = () => (value);
-/******/ __nccwpck_require__.d(ns, def);
-/******/ return ns;
-/******/ };
-/******/ })();
-/******/
-/******/ /* webpack/runtime/define property getters */
-/******/ (() => {
-/******/ // define getter functions for harmony exports
-/******/ __nccwpck_require__.d = (exports, definition) => {
-/******/ for(var key in definition) {
-/******/ if(__nccwpck_require__.o(definition, key) && !__nccwpck_require__.o(exports, key)) {
-/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
-/******/ }
-/******/ }
-/******/ };
-/******/ })();
-/******/
-/******/ /* webpack/runtime/hasOwnProperty shorthand */
-/******/ (() => {
-/******/ __nccwpck_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
-/******/ })();
-/******/
-/******/ /* webpack/runtime/make namespace object */
-/******/ (() => {
-/******/ // define __esModule on exports
-/******/ __nccwpck_require__.r = (exports) => {
-/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
-/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
-/******/ }
-/******/ Object.defineProperty(exports, '__esModule', { value: true });
-/******/ };
-/******/ })();
-/******/
-/******/ /* webpack/runtime/compat */
-/******/
-/******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = new URL('.', import.meta.url).pathname.slice(import.meta.url.match(/^file:\/\/\/\w:/) ? 1 : 0, -1) + "/";
-/******/
-/************************************************************************/
-var __webpack_exports__ = {};
-
-// NAMESPACE OBJECT: ./node_modules/@azure/storage-blob/dist/esm/generated/src/models/mappers.js
-var mappers_namespaceObject = {};
-__nccwpck_require__.r(mappers_namespaceObject);
-__nccwpck_require__.d(mappers_namespaceObject, {
- AccessPolicy: () => (AccessPolicy),
- AppendBlobAppendBlockExceptionHeaders: () => (AppendBlobAppendBlockExceptionHeaders),
- AppendBlobAppendBlockFromUrlExceptionHeaders: () => (AppendBlobAppendBlockFromUrlExceptionHeaders),
- AppendBlobAppendBlockFromUrlHeaders: () => (AppendBlobAppendBlockFromUrlHeaders),
- AppendBlobAppendBlockHeaders: () => (AppendBlobAppendBlockHeaders),
- AppendBlobCreateExceptionHeaders: () => (AppendBlobCreateExceptionHeaders),
- AppendBlobCreateHeaders: () => (AppendBlobCreateHeaders),
- AppendBlobSealExceptionHeaders: () => (AppendBlobSealExceptionHeaders),
- AppendBlobSealHeaders: () => (AppendBlobSealHeaders),
- ArrowConfiguration: () => (ArrowConfiguration),
- ArrowField: () => (ArrowField),
- BlobAbortCopyFromURLExceptionHeaders: () => (BlobAbortCopyFromURLExceptionHeaders),
- BlobAbortCopyFromURLHeaders: () => (BlobAbortCopyFromURLHeaders),
- BlobAcquireLeaseExceptionHeaders: () => (BlobAcquireLeaseExceptionHeaders),
- BlobAcquireLeaseHeaders: () => (BlobAcquireLeaseHeaders),
- BlobBreakLeaseExceptionHeaders: () => (BlobBreakLeaseExceptionHeaders),
- BlobBreakLeaseHeaders: () => (BlobBreakLeaseHeaders),
- BlobChangeLeaseExceptionHeaders: () => (BlobChangeLeaseExceptionHeaders),
- BlobChangeLeaseHeaders: () => (BlobChangeLeaseHeaders),
- BlobCopyFromURLExceptionHeaders: () => (BlobCopyFromURLExceptionHeaders),
- BlobCopyFromURLHeaders: () => (BlobCopyFromURLHeaders),
- BlobCreateSnapshotExceptionHeaders: () => (BlobCreateSnapshotExceptionHeaders),
- BlobCreateSnapshotHeaders: () => (BlobCreateSnapshotHeaders),
- BlobDeleteExceptionHeaders: () => (BlobDeleteExceptionHeaders),
- BlobDeleteHeaders: () => (BlobDeleteHeaders),
- BlobDeleteImmutabilityPolicyExceptionHeaders: () => (BlobDeleteImmutabilityPolicyExceptionHeaders),
- BlobDeleteImmutabilityPolicyHeaders: () => (BlobDeleteImmutabilityPolicyHeaders),
- BlobDownloadExceptionHeaders: () => (BlobDownloadExceptionHeaders),
- BlobDownloadHeaders: () => (BlobDownloadHeaders),
- BlobFlatListSegment: () => (BlobFlatListSegment),
- BlobGetAccountInfoExceptionHeaders: () => (BlobGetAccountInfoExceptionHeaders),
- BlobGetAccountInfoHeaders: () => (BlobGetAccountInfoHeaders),
- BlobGetPropertiesExceptionHeaders: () => (BlobGetPropertiesExceptionHeaders),
- BlobGetPropertiesHeaders: () => (BlobGetPropertiesHeaders),
- BlobGetTagsExceptionHeaders: () => (BlobGetTagsExceptionHeaders),
- BlobGetTagsHeaders: () => (BlobGetTagsHeaders),
- BlobHierarchyListSegment: () => (BlobHierarchyListSegment),
- BlobItemInternal: () => (BlobItemInternal),
- BlobName: () => (BlobName),
- BlobPrefix: () => (BlobPrefix),
- BlobPropertiesInternal: () => (BlobPropertiesInternal),
- BlobQueryExceptionHeaders: () => (BlobQueryExceptionHeaders),
- BlobQueryHeaders: () => (BlobQueryHeaders),
- BlobReleaseLeaseExceptionHeaders: () => (BlobReleaseLeaseExceptionHeaders),
- BlobReleaseLeaseHeaders: () => (BlobReleaseLeaseHeaders),
- BlobRenewLeaseExceptionHeaders: () => (BlobRenewLeaseExceptionHeaders),
- BlobRenewLeaseHeaders: () => (BlobRenewLeaseHeaders),
- BlobServiceProperties: () => (BlobServiceProperties),
- BlobServiceStatistics: () => (BlobServiceStatistics),
- BlobSetExpiryExceptionHeaders: () => (BlobSetExpiryExceptionHeaders),
- BlobSetExpiryHeaders: () => (BlobSetExpiryHeaders),
- BlobSetHttpHeadersExceptionHeaders: () => (BlobSetHttpHeadersExceptionHeaders),
- BlobSetHttpHeadersHeaders: () => (BlobSetHttpHeadersHeaders),
- BlobSetImmutabilityPolicyExceptionHeaders: () => (BlobSetImmutabilityPolicyExceptionHeaders),
- BlobSetImmutabilityPolicyHeaders: () => (BlobSetImmutabilityPolicyHeaders),
- BlobSetLegalHoldExceptionHeaders: () => (BlobSetLegalHoldExceptionHeaders),
- BlobSetLegalHoldHeaders: () => (BlobSetLegalHoldHeaders),
- BlobSetMetadataExceptionHeaders: () => (BlobSetMetadataExceptionHeaders),
- BlobSetMetadataHeaders: () => (BlobSetMetadataHeaders),
- BlobSetTagsExceptionHeaders: () => (BlobSetTagsExceptionHeaders),
- BlobSetTagsHeaders: () => (BlobSetTagsHeaders),
- BlobSetTierExceptionHeaders: () => (BlobSetTierExceptionHeaders),
- BlobSetTierHeaders: () => (BlobSetTierHeaders),
- BlobStartCopyFromURLExceptionHeaders: () => (BlobStartCopyFromURLExceptionHeaders),
- BlobStartCopyFromURLHeaders: () => (BlobStartCopyFromURLHeaders),
- BlobTag: () => (BlobTag),
- BlobTags: () => (BlobTags),
- BlobUndeleteExceptionHeaders: () => (BlobUndeleteExceptionHeaders),
- BlobUndeleteHeaders: () => (BlobUndeleteHeaders),
- Block: () => (Block),
- BlockBlobCommitBlockListExceptionHeaders: () => (BlockBlobCommitBlockListExceptionHeaders),
- BlockBlobCommitBlockListHeaders: () => (BlockBlobCommitBlockListHeaders),
- BlockBlobGetBlockListExceptionHeaders: () => (BlockBlobGetBlockListExceptionHeaders),
- BlockBlobGetBlockListHeaders: () => (BlockBlobGetBlockListHeaders),
- BlockBlobPutBlobFromUrlExceptionHeaders: () => (BlockBlobPutBlobFromUrlExceptionHeaders),
- BlockBlobPutBlobFromUrlHeaders: () => (BlockBlobPutBlobFromUrlHeaders),
- BlockBlobStageBlockExceptionHeaders: () => (BlockBlobStageBlockExceptionHeaders),
- BlockBlobStageBlockFromURLExceptionHeaders: () => (BlockBlobStageBlockFromURLExceptionHeaders),
- BlockBlobStageBlockFromURLHeaders: () => (BlockBlobStageBlockFromURLHeaders),
- BlockBlobStageBlockHeaders: () => (BlockBlobStageBlockHeaders),
- BlockBlobUploadExceptionHeaders: () => (BlockBlobUploadExceptionHeaders),
- BlockBlobUploadHeaders: () => (BlockBlobUploadHeaders),
- BlockList: () => (BlockList),
- BlockLookupList: () => (BlockLookupList),
- ClearRange: () => (ClearRange),
- ContainerAcquireLeaseExceptionHeaders: () => (ContainerAcquireLeaseExceptionHeaders),
- ContainerAcquireLeaseHeaders: () => (ContainerAcquireLeaseHeaders),
- ContainerBreakLeaseExceptionHeaders: () => (ContainerBreakLeaseExceptionHeaders),
- ContainerBreakLeaseHeaders: () => (ContainerBreakLeaseHeaders),
- ContainerChangeLeaseExceptionHeaders: () => (ContainerChangeLeaseExceptionHeaders),
- ContainerChangeLeaseHeaders: () => (ContainerChangeLeaseHeaders),
- ContainerCreateExceptionHeaders: () => (ContainerCreateExceptionHeaders),
- ContainerCreateHeaders: () => (ContainerCreateHeaders),
- ContainerDeleteExceptionHeaders: () => (ContainerDeleteExceptionHeaders),
- ContainerDeleteHeaders: () => (ContainerDeleteHeaders),
- ContainerFilterBlobsExceptionHeaders: () => (ContainerFilterBlobsExceptionHeaders),
- ContainerFilterBlobsHeaders: () => (ContainerFilterBlobsHeaders),
- ContainerGetAccessPolicyExceptionHeaders: () => (ContainerGetAccessPolicyExceptionHeaders),
- ContainerGetAccessPolicyHeaders: () => (ContainerGetAccessPolicyHeaders),
- ContainerGetAccountInfoExceptionHeaders: () => (ContainerGetAccountInfoExceptionHeaders),
- ContainerGetAccountInfoHeaders: () => (ContainerGetAccountInfoHeaders),
- ContainerGetPropertiesExceptionHeaders: () => (ContainerGetPropertiesExceptionHeaders),
- ContainerGetPropertiesHeaders: () => (ContainerGetPropertiesHeaders),
- ContainerItem: () => (ContainerItem),
- ContainerListBlobFlatSegmentExceptionHeaders: () => (ContainerListBlobFlatSegmentExceptionHeaders),
- ContainerListBlobFlatSegmentHeaders: () => (ContainerListBlobFlatSegmentHeaders),
- ContainerListBlobHierarchySegmentExceptionHeaders: () => (ContainerListBlobHierarchySegmentExceptionHeaders),
- ContainerListBlobHierarchySegmentHeaders: () => (ContainerListBlobHierarchySegmentHeaders),
- ContainerProperties: () => (ContainerProperties),
- ContainerReleaseLeaseExceptionHeaders: () => (ContainerReleaseLeaseExceptionHeaders),
- ContainerReleaseLeaseHeaders: () => (ContainerReleaseLeaseHeaders),
- ContainerRenameExceptionHeaders: () => (ContainerRenameExceptionHeaders),
- ContainerRenameHeaders: () => (ContainerRenameHeaders),
- ContainerRenewLeaseExceptionHeaders: () => (ContainerRenewLeaseExceptionHeaders),
- ContainerRenewLeaseHeaders: () => (ContainerRenewLeaseHeaders),
- ContainerRestoreExceptionHeaders: () => (ContainerRestoreExceptionHeaders),
- ContainerRestoreHeaders: () => (ContainerRestoreHeaders),
- ContainerSetAccessPolicyExceptionHeaders: () => (ContainerSetAccessPolicyExceptionHeaders),
- ContainerSetAccessPolicyHeaders: () => (ContainerSetAccessPolicyHeaders),
- ContainerSetMetadataExceptionHeaders: () => (ContainerSetMetadataExceptionHeaders),
- ContainerSetMetadataHeaders: () => (ContainerSetMetadataHeaders),
- ContainerSubmitBatchExceptionHeaders: () => (ContainerSubmitBatchExceptionHeaders),
- ContainerSubmitBatchHeaders: () => (ContainerSubmitBatchHeaders),
- CorsRule: () => (CorsRule),
- DelimitedTextConfiguration: () => (DelimitedTextConfiguration),
- FilterBlobItem: () => (FilterBlobItem),
- FilterBlobSegment: () => (FilterBlobSegment),
- GeoReplication: () => (GeoReplication),
- JsonTextConfiguration: () => (JsonTextConfiguration),
- KeyInfo: () => (KeyInfo),
- ListBlobsFlatSegmentResponse: () => (ListBlobsFlatSegmentResponse),
- ListBlobsHierarchySegmentResponse: () => (ListBlobsHierarchySegmentResponse),
- ListContainersSegmentResponse: () => (ListContainersSegmentResponse),
- Logging: () => (Logging),
- Metrics: () => (Metrics),
- PageBlobClearPagesExceptionHeaders: () => (PageBlobClearPagesExceptionHeaders),
- PageBlobClearPagesHeaders: () => (PageBlobClearPagesHeaders),
- PageBlobCopyIncrementalExceptionHeaders: () => (PageBlobCopyIncrementalExceptionHeaders),
- PageBlobCopyIncrementalHeaders: () => (PageBlobCopyIncrementalHeaders),
- PageBlobCreateExceptionHeaders: () => (PageBlobCreateExceptionHeaders),
- PageBlobCreateHeaders: () => (PageBlobCreateHeaders),
- PageBlobGetPageRangesDiffExceptionHeaders: () => (PageBlobGetPageRangesDiffExceptionHeaders),
- PageBlobGetPageRangesDiffHeaders: () => (PageBlobGetPageRangesDiffHeaders),
- PageBlobGetPageRangesExceptionHeaders: () => (PageBlobGetPageRangesExceptionHeaders),
- PageBlobGetPageRangesHeaders: () => (PageBlobGetPageRangesHeaders),
- PageBlobResizeExceptionHeaders: () => (PageBlobResizeExceptionHeaders),
- PageBlobResizeHeaders: () => (PageBlobResizeHeaders),
- PageBlobUpdateSequenceNumberExceptionHeaders: () => (PageBlobUpdateSequenceNumberExceptionHeaders),
- PageBlobUpdateSequenceNumberHeaders: () => (PageBlobUpdateSequenceNumberHeaders),
- PageBlobUploadPagesExceptionHeaders: () => (PageBlobUploadPagesExceptionHeaders),
- PageBlobUploadPagesFromURLExceptionHeaders: () => (PageBlobUploadPagesFromURLExceptionHeaders),
- PageBlobUploadPagesFromURLHeaders: () => (PageBlobUploadPagesFromURLHeaders),
- PageBlobUploadPagesHeaders: () => (PageBlobUploadPagesHeaders),
- PageList: () => (PageList),
- PageRange: () => (PageRange),
- QueryFormat: () => (QueryFormat),
- QueryRequest: () => (QueryRequest),
- QuerySerialization: () => (QuerySerialization),
- RetentionPolicy: () => (RetentionPolicy),
- ServiceFilterBlobsExceptionHeaders: () => (ServiceFilterBlobsExceptionHeaders),
- ServiceFilterBlobsHeaders: () => (ServiceFilterBlobsHeaders),
- ServiceGetAccountInfoExceptionHeaders: () => (ServiceGetAccountInfoExceptionHeaders),
- ServiceGetAccountInfoHeaders: () => (ServiceGetAccountInfoHeaders),
- ServiceGetPropertiesExceptionHeaders: () => (ServiceGetPropertiesExceptionHeaders),
- ServiceGetPropertiesHeaders: () => (ServiceGetPropertiesHeaders),
- ServiceGetStatisticsExceptionHeaders: () => (ServiceGetStatisticsExceptionHeaders),
- ServiceGetStatisticsHeaders: () => (ServiceGetStatisticsHeaders),
- ServiceGetUserDelegationKeyExceptionHeaders: () => (ServiceGetUserDelegationKeyExceptionHeaders),
- ServiceGetUserDelegationKeyHeaders: () => (ServiceGetUserDelegationKeyHeaders),
- ServiceListContainersSegmentExceptionHeaders: () => (ServiceListContainersSegmentExceptionHeaders),
- ServiceListContainersSegmentHeaders: () => (ServiceListContainersSegmentHeaders),
- ServiceSetPropertiesExceptionHeaders: () => (ServiceSetPropertiesExceptionHeaders),
- ServiceSetPropertiesHeaders: () => (ServiceSetPropertiesHeaders),
- ServiceSubmitBatchExceptionHeaders: () => (ServiceSubmitBatchExceptionHeaders),
- ServiceSubmitBatchHeaders: () => (ServiceSubmitBatchHeaders),
- SignedIdentifier: () => (SignedIdentifier),
- StaticWebsite: () => (StaticWebsite),
- StorageError: () => (StorageError),
- UserDelegationKey: () => (UserDelegationKey)
-});
-
-;// CONCATENATED MODULE: external "fs"
-const external_fs_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("fs");
-;// CONCATENATED MODULE: external "timers/promises"
-const promises_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("timers/promises");
-;// CONCATENATED MODULE: external "os"
-const external_os_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("os");
-;// CONCATENATED MODULE: ./node_modules/@actions/core/lib/utils.js
-// We use any as a valid input type
-/* eslint-disable @typescript-eslint/no-explicit-any */
-/**
- * Sanitizes an input into a string so it can be passed into issueCommand safely
- * @param input input to sanitize into a string
- */
-function utils_toCommandValue(input) {
- if (input === null || input === undefined) {
- return '';
- }
- else if (typeof input === 'string' || input instanceof String) {
- return input;
- }
- return JSON.stringify(input);
-}
-/**
- *
- * @param annotationProperties
- * @returns The command properties to send with the actual annotation command
- * See IssueCommandProperties: https://github.com/actions/runner/blob/main/src/Runner.Worker/ActionCommandManager.cs#L646
- */
-function utils_toCommandProperties(annotationProperties) {
- if (!Object.keys(annotationProperties).length) {
- return {};
- }
- return {
- title: annotationProperties.title,
- file: annotationProperties.file,
- line: annotationProperties.startLine,
- endLine: annotationProperties.endLine,
- col: annotationProperties.startColumn,
- endColumn: annotationProperties.endColumn
- };
-}
-//# sourceMappingURL=utils.js.map
-;// CONCATENATED MODULE: ./node_modules/@actions/core/lib/command.js
-
-
-/**
- * Issues a command to the GitHub Actions runner
- *
- * @param command - The command name to issue
- * @param properties - Additional properties for the command (key-value pairs)
- * @param message - The message to include with the command
- * @remarks
- * This function outputs a specially formatted string to stdout that the Actions
- * runner interprets as a command. These commands can control workflow behavior,
- * set outputs, create annotations, mask values, and more.
- *
- * Command Format:
- * ::name key=value,key=value::message
- *
- * @example
- * ```typescript
- * // Issue a warning annotation
- * issueCommand('warning', {}, 'This is a warning message');
- * // Output: ::warning::This is a warning message
- *
- * // Set an environment variable
- * issueCommand('set-env', { name: 'MY_VAR' }, 'some value');
- * // Output: ::set-env name=MY_VAR::some value
- *
- * // Add a secret mask
- * issueCommand('add-mask', {}, 'secretValue123');
- * // Output: ::add-mask::secretValue123
- * ```
- *
- * @internal
- * This is an internal utility function that powers the public API functions
- * such as setSecret, warning, error, and exportVariable.
- */
-function command_issueCommand(command, properties, message) {
- const cmd = new Command(command, properties, message);
- process.stdout.write(cmd.toString() + external_os_namespaceObject.EOL);
-}
-function command_issue(name, message = '') {
- command_issueCommand(name, {}, message);
-}
-const CMD_STRING = '::';
-class Command {
- constructor(command, properties, message) {
- if (!command) {
- command = 'missing.command';
- }
- this.command = command;
- this.properties = properties;
- this.message = message;
- }
- toString() {
- let cmdStr = CMD_STRING + this.command;
- if (this.properties && Object.keys(this.properties).length > 0) {
- cmdStr += ' ';
- let first = true;
- for (const key in this.properties) {
- if (this.properties.hasOwnProperty(key)) {
- const val = this.properties[key];
- if (val) {
- if (first) {
- first = false;
- }
- else {
- cmdStr += ',';
- }
- cmdStr += `${key}=${escapeProperty(val)}`;
- }
- }
- }
- }
- cmdStr += `${CMD_STRING}${escapeData(this.message)}`;
- return cmdStr;
- }
-}
-function escapeData(s) {
- return utils_toCommandValue(s)
- .replace(/%/g, '%25')
- .replace(/\r/g, '%0D')
- .replace(/\n/g, '%0A');
-}
-function escapeProperty(s) {
- return utils_toCommandValue(s)
- .replace(/%/g, '%25')
- .replace(/\r/g, '%0D')
- .replace(/\n/g, '%0A')
- .replace(/:/g, '%3A')
- .replace(/,/g, '%2C');
-}
-//# sourceMappingURL=command.js.map
-;// CONCATENATED MODULE: external "crypto"
-const external_crypto_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("crypto");
-;// CONCATENATED MODULE: ./node_modules/@actions/core/lib/file-command.js
-// For internal use, subject to change.
-// We use any as a valid input type
-/* eslint-disable @typescript-eslint/no-explicit-any */
-
-
-
-
-function file_command_issueFileCommand(command, message) {
- const filePath = process.env[`GITHUB_${command}`];
- if (!filePath) {
- throw new Error(`Unable to find environment variable for file command ${command}`);
- }
- if (!external_fs_namespaceObject.existsSync(filePath)) {
- throw new Error(`Missing file at path: ${filePath}`);
- }
- external_fs_namespaceObject.appendFileSync(filePath, `${utils_toCommandValue(message)}${external_os_namespaceObject.EOL}`, {
- encoding: 'utf8'
- });
-}
-function file_command_prepareKeyValueMessage(key, value) {
- const delimiter = `ghadelimiter_${external_crypto_namespaceObject.randomUUID()}`;
- const convertedValue = utils_toCommandValue(value);
- // These should realistically never happen, but just in case someone finds a
- // way to exploit uuid generation let's not allow keys or values that contain
- // the delimiter.
- if (key.includes(delimiter)) {
- throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`);
- }
- if (convertedValue.includes(delimiter)) {
- throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`);
- }
- return `${key}<<${delimiter}${external_os_namespaceObject.EOL}${convertedValue}${external_os_namespaceObject.EOL}${delimiter}`;
-}
-//# sourceMappingURL=file-command.js.map
-// EXTERNAL MODULE: external "path"
-var external_path_ = __nccwpck_require__(6928);
-// EXTERNAL MODULE: external "http"
-var external_http_ = __nccwpck_require__(8611);
-var external_http_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(external_http_, 2);
-// EXTERNAL MODULE: external "https"
-var external_https_ = __nccwpck_require__(5692);
-var external_https_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(external_https_, 2);
-;// CONCATENATED MODULE: ./node_modules/@actions/http-client/lib/proxy.js
-function getProxyUrl(reqUrl) {
- const usingSsl = reqUrl.protocol === 'https:';
- if (checkBypass(reqUrl)) {
- return undefined;
- }
- const proxyVar = (() => {
- if (usingSsl) {
- return process.env['https_proxy'] || process.env['HTTPS_PROXY'];
- }
- else {
- return process.env['http_proxy'] || process.env['HTTP_PROXY'];
- }
- })();
- if (proxyVar) {
- try {
- return new DecodedURL(proxyVar);
- }
- catch (_a) {
- if (!proxyVar.startsWith('http://') && !proxyVar.startsWith('https://'))
- return new DecodedURL(`http://${proxyVar}`);
- }
- }
- else {
- return undefined;
- }
-}
-function checkBypass(reqUrl) {
- if (!reqUrl.hostname) {
- return false;
- }
- const reqHost = reqUrl.hostname;
- if (isLoopbackAddress(reqHost)) {
- return true;
- }
- const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || '';
- if (!noProxy) {
- return false;
- }
- // Determine the request port
- let reqPort;
- if (reqUrl.port) {
- reqPort = Number(reqUrl.port);
- }
- else if (reqUrl.protocol === 'http:') {
- reqPort = 80;
- }
- else if (reqUrl.protocol === 'https:') {
- reqPort = 443;
- }
- // Format the request hostname and hostname with port
- const upperReqHosts = [reqUrl.hostname.toUpperCase()];
- if (typeof reqPort === 'number') {
- upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`);
- }
- // Compare request host against noproxy
- for (const upperNoProxyItem of noProxy
- .split(',')
- .map(x => x.trim().toUpperCase())
- .filter(x => x)) {
- if (upperNoProxyItem === '*' ||
- upperReqHosts.some(x => x === upperNoProxyItem ||
- x.endsWith(`.${upperNoProxyItem}`) ||
- (upperNoProxyItem.startsWith('.') &&
- x.endsWith(`${upperNoProxyItem}`)))) {
- return true;
- }
- }
- return false;
-}
-function isLoopbackAddress(host) {
- const hostLower = host.toLowerCase();
- return (hostLower === 'localhost' ||
- hostLower.startsWith('127.') ||
- hostLower.startsWith('[::1]') ||
- hostLower.startsWith('[0:0:0:0:0:0:0:1]'));
-}
-class DecodedURL extends URL {
- constructor(url, base) {
- super(url, base);
- this._decodedUsername = decodeURIComponent(super.username);
- this._decodedPassword = decodeURIComponent(super.password);
- }
- get username() {
- return this._decodedUsername;
- }
- get password() {
- return this._decodedPassword;
- }
-}
-//# sourceMappingURL=proxy.js.map
-// EXTERNAL MODULE: ./node_modules/tunnel/index.js
-var tunnel = __nccwpck_require__(770);
-// EXTERNAL MODULE: ./node_modules/@actions/http-client/node_modules/undici/index.js
-var undici = __nccwpck_require__(3368);
-;// CONCATENATED MODULE: ./node_modules/@actions/http-client/lib/index.js
-/* eslint-disable @typescript-eslint/no-explicit-any */
-var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-
-
-
-
-
-var HttpCodes;
-(function (HttpCodes) {
- HttpCodes[HttpCodes["OK"] = 200] = "OK";
- HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices";
- HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently";
- HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved";
- HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther";
- HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified";
- HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy";
- HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy";
- HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect";
- HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect";
- HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest";
- HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized";
- HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired";
- HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden";
- HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound";
- HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed";
- HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable";
- HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired";
- HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout";
- HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict";
- HttpCodes[HttpCodes["Gone"] = 410] = "Gone";
- HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests";
- HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError";
- HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented";
- HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway";
- HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable";
- HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout";
-})(HttpCodes || (HttpCodes = {}));
-var Headers;
-(function (Headers) {
- Headers["Accept"] = "accept";
- Headers["ContentType"] = "content-type";
-})(Headers || (Headers = {}));
-var MediaTypes;
-(function (MediaTypes) {
- MediaTypes["ApplicationJson"] = "application/json";
-})(MediaTypes || (MediaTypes = {}));
-/**
- * Returns the proxy URL, depending upon the supplied url and proxy environment variables.
- * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com
- */
-function lib_getProxyUrl(serverUrl) {
- const proxyUrl = pm.getProxyUrl(new URL(serverUrl));
- return proxyUrl ? proxyUrl.href : '';
-}
-const HttpRedirectCodes = [
- HttpCodes.MovedPermanently,
- HttpCodes.ResourceMoved,
- HttpCodes.SeeOther,
- HttpCodes.TemporaryRedirect,
- HttpCodes.PermanentRedirect
-];
-const HttpResponseRetryCodes = [
- HttpCodes.BadGateway,
- HttpCodes.ServiceUnavailable,
- HttpCodes.GatewayTimeout
-];
-const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD'];
-const ExponentialBackoffCeiling = 10;
-const ExponentialBackoffTimeSlice = 5;
-class lib_HttpClientError extends Error {
- constructor(message, statusCode) {
- super(message);
- this.name = 'HttpClientError';
- this.statusCode = statusCode;
- Object.setPrototypeOf(this, lib_HttpClientError.prototype);
- }
-}
-class HttpClientResponse {
- constructor(message) {
- this.message = message;
- }
- readBody() {
- return __awaiter(this, void 0, void 0, function* () {
- return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {
- let output = Buffer.alloc(0);
- this.message.on('data', (chunk) => {
- output = Buffer.concat([output, chunk]);
- });
- this.message.on('end', () => {
- resolve(output.toString());
- });
- }));
- });
- }
- readBodyBuffer() {
- return __awaiter(this, void 0, void 0, function* () {
- return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {
- const chunks = [];
- this.message.on('data', (chunk) => {
- chunks.push(chunk);
- });
- this.message.on('end', () => {
- resolve(Buffer.concat(chunks));
- });
- }));
- });
- }
-}
-function isHttps(requestUrl) {
- const parsedUrl = new URL(requestUrl);
- return parsedUrl.protocol === 'https:';
-}
-class lib_HttpClient {
- constructor(userAgent, handlers, requestOptions) {
- this._ignoreSslError = false;
- this._allowRedirects = true;
- this._allowRedirectDowngrade = false;
- this._maxRedirects = 50;
- this._allowRetries = false;
- this._maxRetries = 1;
- this._keepAlive = false;
- this._disposed = false;
- this.userAgent = this._getUserAgentWithOrchestrationId(userAgent);
- this.handlers = handlers || [];
- this.requestOptions = requestOptions;
- if (requestOptions) {
- if (requestOptions.ignoreSslError != null) {
- this._ignoreSslError = requestOptions.ignoreSslError;
- }
- this._socketTimeout = requestOptions.socketTimeout;
- if (requestOptions.allowRedirects != null) {
- this._allowRedirects = requestOptions.allowRedirects;
- }
- if (requestOptions.allowRedirectDowngrade != null) {
- this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade;
- }
- if (requestOptions.maxRedirects != null) {
- this._maxRedirects = Math.max(requestOptions.maxRedirects, 0);
- }
- if (requestOptions.keepAlive != null) {
- this._keepAlive = requestOptions.keepAlive;
- }
- if (requestOptions.allowRetries != null) {
- this._allowRetries = requestOptions.allowRetries;
- }
- if (requestOptions.maxRetries != null) {
- this._maxRetries = requestOptions.maxRetries;
- }
- }
- }
- options(requestUrl, additionalHeaders) {
- return __awaiter(this, void 0, void 0, function* () {
- return this.request('OPTIONS', requestUrl, null, additionalHeaders || {});
- });
- }
- get(requestUrl, additionalHeaders) {
- return __awaiter(this, void 0, void 0, function* () {
- return this.request('GET', requestUrl, null, additionalHeaders || {});
- });
- }
- del(requestUrl, additionalHeaders) {
- return __awaiter(this, void 0, void 0, function* () {
- return this.request('DELETE', requestUrl, null, additionalHeaders || {});
- });
- }
- post(requestUrl, data, additionalHeaders) {
- return __awaiter(this, void 0, void 0, function* () {
- return this.request('POST', requestUrl, data, additionalHeaders || {});
- });
- }
- patch(requestUrl, data, additionalHeaders) {
- return __awaiter(this, void 0, void 0, function* () {
- return this.request('PATCH', requestUrl, data, additionalHeaders || {});
- });
- }
- put(requestUrl, data, additionalHeaders) {
- return __awaiter(this, void 0, void 0, function* () {
- return this.request('PUT', requestUrl, data, additionalHeaders || {});
- });
- }
- head(requestUrl, additionalHeaders) {
- return __awaiter(this, void 0, void 0, function* () {
- return this.request('HEAD', requestUrl, null, additionalHeaders || {});
- });
- }
- sendStream(verb, requestUrl, stream, additionalHeaders) {
- return __awaiter(this, void 0, void 0, function* () {
- return this.request(verb, requestUrl, stream, additionalHeaders);
- });
- }
- /**
- * Gets a typed object from an endpoint
- * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise
- */
- getJson(requestUrl_1) {
- return __awaiter(this, arguments, void 0, function* (requestUrl, additionalHeaders = {}) {
- additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
- const res = yield this.get(requestUrl, additionalHeaders);
- return this._processResponse(res, this.requestOptions);
- });
- }
- postJson(requestUrl_1, obj_1) {
- return __awaiter(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) {
- const data = JSON.stringify(obj, null, 2);
- additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
- additionalHeaders[Headers.ContentType] =
- this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson);
- const res = yield this.post(requestUrl, data, additionalHeaders);
- return this._processResponse(res, this.requestOptions);
- });
- }
- putJson(requestUrl_1, obj_1) {
- return __awaiter(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) {
- const data = JSON.stringify(obj, null, 2);
- additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
- additionalHeaders[Headers.ContentType] =
- this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson);
- const res = yield this.put(requestUrl, data, additionalHeaders);
- return this._processResponse(res, this.requestOptions);
- });
- }
- patchJson(requestUrl_1, obj_1) {
- return __awaiter(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) {
- const data = JSON.stringify(obj, null, 2);
- additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
- additionalHeaders[Headers.ContentType] =
- this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson);
- const res = yield this.patch(requestUrl, data, additionalHeaders);
- return this._processResponse(res, this.requestOptions);
- });
- }
- /**
- * Makes a raw http request.
- * All other methods such as get, post, patch, and request ultimately call this.
- * Prefer get, del, post and patch
- */
- request(verb, requestUrl, data, headers) {
- return __awaiter(this, void 0, void 0, function* () {
- if (this._disposed) {
- throw new Error('Client has already been disposed.');
- }
- const parsedUrl = new URL(requestUrl);
- let info = this._prepareRequest(verb, parsedUrl, headers);
- // Only perform retries on reads since writes may not be idempotent.
- const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb)
- ? this._maxRetries + 1
- : 1;
- let numTries = 0;
- let response;
- do {
- response = yield this.requestRaw(info, data);
- // Check if it's an authentication challenge
- if (response &&
- response.message &&
- response.message.statusCode === HttpCodes.Unauthorized) {
- let authenticationHandler;
- for (const handler of this.handlers) {
- if (handler.canHandleAuthentication(response)) {
- authenticationHandler = handler;
- break;
- }
- }
- if (authenticationHandler) {
- return authenticationHandler.handleAuthentication(this, info, data);
- }
- else {
- // We have received an unauthorized response but have no handlers to handle it.
- // Let the response return to the caller.
- return response;
- }
- }
- let redirectsRemaining = this._maxRedirects;
- while (response.message.statusCode &&
- HttpRedirectCodes.includes(response.message.statusCode) &&
- this._allowRedirects &&
- redirectsRemaining > 0) {
- const redirectUrl = response.message.headers['location'];
- if (!redirectUrl) {
- // if there's no location to redirect to, we won't
- break;
- }
- const parsedRedirectUrl = new URL(redirectUrl);
- if (parsedUrl.protocol === 'https:' &&
- parsedUrl.protocol !== parsedRedirectUrl.protocol &&
- !this._allowRedirectDowngrade) {
- throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.');
- }
- // we need to finish reading the response before reassigning response
- // which will leak the open socket.
- yield response.readBody();
- // strip authorization header if redirected to a different hostname
- if (parsedRedirectUrl.hostname !== parsedUrl.hostname) {
- for (const header in headers) {
- // header names are case insensitive
- if (header.toLowerCase() === 'authorization') {
- delete headers[header];
- }
- }
- }
- // let's make the request with the new redirectUrl
- info = this._prepareRequest(verb, parsedRedirectUrl, headers);
- response = yield this.requestRaw(info, data);
- redirectsRemaining--;
- }
- if (!response.message.statusCode ||
- !HttpResponseRetryCodes.includes(response.message.statusCode)) {
- // If not a retry code, return immediately instead of retrying
- return response;
- }
- numTries += 1;
- if (numTries < maxTries) {
- yield response.readBody();
- yield this._performExponentialBackoff(numTries);
- }
- } while (numTries < maxTries);
- return response;
- });
- }
- /**
- * Needs to be called if keepAlive is set to true in request options.
- */
- dispose() {
- if (this._agent) {
- this._agent.destroy();
- }
- this._disposed = true;
- }
- /**
- * Raw request.
- * @param info
- * @param data
- */
- requestRaw(info, data) {
- return __awaiter(this, void 0, void 0, function* () {
- return new Promise((resolve, reject) => {
- function callbackForResult(err, res) {
- if (err) {
- reject(err);
- }
- else if (!res) {
- // If `err` is not passed, then `res` must be passed.
- reject(new Error('Unknown error'));
- }
- else {
- resolve(res);
- }
- }
- this.requestRawWithCallback(info, data, callbackForResult);
- });
- });
- }
- /**
- * Raw request with callback.
- * @param info
- * @param data
- * @param onResult
- */
- requestRawWithCallback(info, data, onResult) {
- if (typeof data === 'string') {
- if (!info.options.headers) {
- info.options.headers = {};
- }
- info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8');
- }
- let callbackCalled = false;
- function handleResult(err, res) {
- if (!callbackCalled) {
- callbackCalled = true;
- onResult(err, res);
- }
- }
- const req = info.httpModule.request(info.options, (msg) => {
- const res = new HttpClientResponse(msg);
- handleResult(undefined, res);
- });
- let socket;
- req.on('socket', sock => {
- socket = sock;
- });
- // If we ever get disconnected, we want the socket to timeout eventually
- req.setTimeout(this._socketTimeout || 3 * 60000, () => {
- if (socket) {
- socket.end();
- }
- handleResult(new Error(`Request timeout: ${info.options.path}`));
- });
- req.on('error', function (err) {
- // err has statusCode property
- // res should have headers
- handleResult(err);
- });
- if (data && typeof data === 'string') {
- req.write(data, 'utf8');
- }
- if (data && typeof data !== 'string') {
- data.on('close', function () {
- req.end();
- });
- data.pipe(req);
- }
- else {
- req.end();
- }
- }
- /**
- * Gets an http agent. This function is useful when you need an http agent that handles
- * routing through a proxy server - depending upon the url and proxy environment variables.
- * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com
- */
- getAgent(serverUrl) {
- const parsedUrl = new URL(serverUrl);
- return this._getAgent(parsedUrl);
- }
- getAgentDispatcher(serverUrl) {
- const parsedUrl = new URL(serverUrl);
- const proxyUrl = getProxyUrl(parsedUrl);
- const useProxy = proxyUrl && proxyUrl.hostname;
- if (!useProxy) {
- return;
- }
- return this._getProxyAgentDispatcher(parsedUrl, proxyUrl);
- }
- _prepareRequest(method, requestUrl, headers) {
- const info = {};
- info.parsedUrl = requestUrl;
- const usingSsl = info.parsedUrl.protocol === 'https:';
- info.httpModule = usingSsl ? external_https_namespaceObject : external_http_namespaceObject;
- const defaultPort = usingSsl ? 443 : 80;
- info.options = {};
- info.options.host = info.parsedUrl.hostname;
- info.options.port = info.parsedUrl.port
- ? parseInt(info.parsedUrl.port)
- : defaultPort;
- info.options.path =
- (info.parsedUrl.pathname || '') + (info.parsedUrl.search || '');
- info.options.method = method;
- info.options.headers = this._mergeHeaders(headers);
- if (this.userAgent != null) {
- info.options.headers['user-agent'] = this.userAgent;
- }
- info.options.agent = this._getAgent(info.parsedUrl);
- // gives handlers an opportunity to participate
- if (this.handlers) {
- for (const handler of this.handlers) {
- handler.prepareRequest(info.options);
- }
- }
- return info;
- }
- _mergeHeaders(headers) {
- if (this.requestOptions && this.requestOptions.headers) {
- return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {}));
- }
- return lowercaseKeys(headers || {});
- }
- /**
- * Gets an existing header value or returns a default.
- * Handles converting number header values to strings since HTTP headers must be strings.
- * Note: This returns string | string[] since some headers can have multiple values.
- * For headers that must always be a single string (like Content-Type), use the
- * specialized _getExistingOrDefaultContentTypeHeader method instead.
- */
- _getExistingOrDefaultHeader(additionalHeaders, header, _default) {
- let clientHeader;
- if (this.requestOptions && this.requestOptions.headers) {
- const headerValue = lowercaseKeys(this.requestOptions.headers)[header];
- if (headerValue) {
- clientHeader =
- typeof headerValue === 'number' ? headerValue.toString() : headerValue;
- }
- }
- const additionalValue = additionalHeaders[header];
- if (additionalValue !== undefined) {
- return typeof additionalValue === 'number'
- ? additionalValue.toString()
- : additionalValue;
- }
- if (clientHeader !== undefined) {
- return clientHeader;
- }
- return _default;
- }
- /**
- * Specialized version of _getExistingOrDefaultHeader for Content-Type header.
- * Always returns a single string (not an array) since Content-Type should be a single value.
- * Converts arrays to comma-separated strings and numbers to strings to ensure type safety.
- * This was split from _getExistingOrDefaultHeader to provide stricter typing for callers
- * that assign the result to places expecting a string (e.g., additionalHeaders[Headers.ContentType]).
- */
- _getExistingOrDefaultContentTypeHeader(additionalHeaders, _default) {
- let clientHeader;
- if (this.requestOptions && this.requestOptions.headers) {
- const headerValue = lowercaseKeys(this.requestOptions.headers)[Headers.ContentType];
- if (headerValue) {
- if (typeof headerValue === 'number') {
- clientHeader = String(headerValue);
- }
- else if (Array.isArray(headerValue)) {
- clientHeader = headerValue.join(', ');
- }
- else {
- clientHeader = headerValue;
- }
- }
- }
- const additionalValue = additionalHeaders[Headers.ContentType];
- // Return the first non-undefined value, converting numbers or arrays to strings if necessary
- if (additionalValue !== undefined) {
- if (typeof additionalValue === 'number') {
- return String(additionalValue);
- }
- else if (Array.isArray(additionalValue)) {
- return additionalValue.join(', ');
- }
- else {
- return additionalValue;
- }
- }
- if (clientHeader !== undefined) {
- return clientHeader;
- }
- return _default;
- }
- _getAgent(parsedUrl) {
- let agent;
- const proxyUrl = getProxyUrl(parsedUrl);
- const useProxy = proxyUrl && proxyUrl.hostname;
- if (this._keepAlive && useProxy) {
- agent = this._proxyAgent;
- }
- if (!useProxy) {
- agent = this._agent;
- }
- // if agent is already assigned use that agent.
- if (agent) {
- return agent;
- }
- const usingSsl = parsedUrl.protocol === 'https:';
- let maxSockets = 100;
- if (this.requestOptions) {
- maxSockets = this.requestOptions.maxSockets || external_http_.globalAgent.maxSockets;
- }
- // This is `useProxy` again, but we need to check `proxyURl` directly for TypeScripts's flow analysis.
- if (proxyUrl && proxyUrl.hostname) {
- const agentOptions = {
- maxSockets,
- keepAlive: this._keepAlive,
- proxy: Object.assign(Object.assign({}, ((proxyUrl.username || proxyUrl.password) && {
- proxyAuth: `${proxyUrl.username}:${proxyUrl.password}`
- })), { host: proxyUrl.hostname, port: proxyUrl.port })
- };
- let tunnelAgent;
- const overHttps = proxyUrl.protocol === 'https:';
- if (usingSsl) {
- tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp;
- }
- else {
- tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp;
- }
- agent = tunnelAgent(agentOptions);
- this._proxyAgent = agent;
- }
- // if tunneling agent isn't assigned create a new agent
- if (!agent) {
- const options = { keepAlive: this._keepAlive, maxSockets };
- agent = usingSsl ? new external_https_.Agent(options) : new external_http_.Agent(options);
- this._agent = agent;
- }
- if (usingSsl && this._ignoreSslError) {
- // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process
- // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options
- // we have to cast it to any and change it directly
- agent.options = Object.assign(agent.options || {}, {
- rejectUnauthorized: false
- });
- }
- return agent;
- }
- _getProxyAgentDispatcher(parsedUrl, proxyUrl) {
- let proxyAgent;
- if (this._keepAlive) {
- proxyAgent = this._proxyAgentDispatcher;
- }
- // if agent is already assigned use that agent.
- if (proxyAgent) {
- return proxyAgent;
- }
- const usingSsl = parsedUrl.protocol === 'https:';
- proxyAgent = new undici/* ProxyAgent */.kT(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, ((proxyUrl.username || proxyUrl.password) && {
- token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString('base64')}`
- })));
- this._proxyAgentDispatcher = proxyAgent;
- if (usingSsl && this._ignoreSslError) {
- // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process
- // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options
- // we have to cast it to any and change it directly
- proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, {
- rejectUnauthorized: false
- });
- }
- return proxyAgent;
- }
- _getUserAgentWithOrchestrationId(userAgent) {
- const baseUserAgent = userAgent || 'actions/http-client';
- const orchId = process.env['ACTIONS_ORCHESTRATION_ID'];
- if (orchId) {
- // Sanitize the orchestration ID to ensure it contains only valid characters
- // Valid characters: 0-9, a-z, _, -, .
- const sanitizedId = orchId.replace(/[^a-z0-9_.-]/gi, '_');
- return `${baseUserAgent} actions_orchestration_id/${sanitizedId}`;
- }
- return baseUserAgent;
- }
- _performExponentialBackoff(retryNumber) {
- return __awaiter(this, void 0, void 0, function* () {
- retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber);
- const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber);
- return new Promise(resolve => setTimeout(() => resolve(), ms));
- });
- }
- _processResponse(res, options) {
- return __awaiter(this, void 0, void 0, function* () {
- return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
- const statusCode = res.message.statusCode || 0;
- const response = {
- statusCode,
- result: null,
- headers: {}
- };
- // not found leads to null obj returned
- if (statusCode === HttpCodes.NotFound) {
- resolve(response);
- }
- // get the result from the body
- function dateTimeDeserializer(key, value) {
- if (typeof value === 'string') {
- const a = new Date(value);
- if (!isNaN(a.valueOf())) {
- return a;
- }
- }
- return value;
- }
- let obj;
- let contents;
- try {
- contents = yield res.readBody();
- if (contents && contents.length > 0) {
- if (options && options.deserializeDates) {
- obj = JSON.parse(contents, dateTimeDeserializer);
- }
- else {
- obj = JSON.parse(contents);
- }
- response.result = obj;
- }
- response.headers = res.message.headers;
- }
- catch (err) {
- // Invalid resource (contents not json); leaving result obj null
- }
- // note that 3xx redirects are handled by the http layer.
- if (statusCode > 299) {
- let msg;
- // if exception/error in body, attempt to get better error
- if (obj && obj.message) {
- msg = obj.message;
- }
- else if (contents && contents.length > 0) {
- // it may be the case that the exception is in the body message as string
- msg = contents;
- }
- else {
- msg = `Failed request: (${statusCode})`;
- }
- const err = new lib_HttpClientError(msg, statusCode);
- err.result = response.result;
- reject(err);
- }
- else {
- resolve(response);
- }
- }));
- });
- }
-}
-const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {});
-//# sourceMappingURL=index.js.map
-;// CONCATENATED MODULE: ./node_modules/@actions/http-client/lib/auth.js
-var auth_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-class BasicCredentialHandler {
- constructor(username, password) {
- this.username = username;
- this.password = password;
- }
- prepareRequest(options) {
- if (!options.headers) {
- throw Error('The request has no headers');
- }
- options.headers['Authorization'] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString('base64')}`;
- }
- // This handler cannot handle 401
- canHandleAuthentication() {
- return false;
- }
- handleAuthentication() {
- return auth_awaiter(this, void 0, void 0, function* () {
- throw new Error('not implemented');
- });
- }
-}
-class auth_BearerCredentialHandler {
- constructor(token) {
- this.token = token;
- }
- // currently implements pre-authorization
- // TODO: support preAuth = false where it hooks on 401
- prepareRequest(options) {
- if (!options.headers) {
- throw Error('The request has no headers');
- }
- options.headers['Authorization'] = `Bearer ${this.token}`;
- }
- // This handler cannot handle 401
- canHandleAuthentication() {
- return false;
- }
- handleAuthentication() {
- return auth_awaiter(this, void 0, void 0, function* () {
- throw new Error('not implemented');
- });
- }
-}
-class PersonalAccessTokenCredentialHandler {
- constructor(token) {
- this.token = token;
- }
- // currently implements pre-authorization
- // TODO: support preAuth = false where it hooks on 401
- prepareRequest(options) {
- if (!options.headers) {
- throw Error('The request has no headers');
- }
- options.headers['Authorization'] = `Basic ${Buffer.from(`PAT:${this.token}`).toString('base64')}`;
- }
- // This handler cannot handle 401
- canHandleAuthentication() {
- return false;
- }
- handleAuthentication() {
- return auth_awaiter(this, void 0, void 0, function* () {
- throw new Error('not implemented');
- });
- }
-}
-//# sourceMappingURL=auth.js.map
-;// CONCATENATED MODULE: ./node_modules/@actions/core/lib/oidc-utils.js
-var oidc_utils_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-
-
-
-class oidc_utils_OidcClient {
- static createHttpClient(allowRetry = true, maxRetry = 10) {
- const requestOptions = {
- allowRetries: allowRetry,
- maxRetries: maxRetry
- };
- return new HttpClient('actions/oidc-client', [new BearerCredentialHandler(oidc_utils_OidcClient.getRequestToken())], requestOptions);
- }
- static getRequestToken() {
- const token = process.env['ACTIONS_ID_TOKEN_REQUEST_TOKEN'];
- if (!token) {
- throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable');
- }
- return token;
- }
- static getIDTokenUrl() {
- const runtimeUrl = process.env['ACTIONS_ID_TOKEN_REQUEST_URL'];
- if (!runtimeUrl) {
- throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable');
- }
- return runtimeUrl;
- }
- static getCall(id_token_url) {
- return oidc_utils_awaiter(this, void 0, void 0, function* () {
- var _a;
- const httpclient = oidc_utils_OidcClient.createHttpClient();
- const res = yield httpclient
- .getJson(id_token_url)
- .catch(error => {
- throw new Error(`Failed to get ID Token. \n
- Error Code : ${error.statusCode}\n
- Error Message: ${error.message}`);
- });
- const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value;
- if (!id_token) {
- throw new Error('Response json body do not have ID Token field');
- }
- return id_token;
- });
- }
- static getIDToken(audience) {
- return oidc_utils_awaiter(this, void 0, void 0, function* () {
- try {
- // New ID Token is requested from action service
- let id_token_url = oidc_utils_OidcClient.getIDTokenUrl();
- if (audience) {
- const encodedAudience = encodeURIComponent(audience);
- id_token_url = `${id_token_url}&audience=${encodedAudience}`;
- }
- debug(`ID token url is ${id_token_url}`);
- const id_token = yield oidc_utils_OidcClient.getCall(id_token_url);
- setSecret(id_token);
- return id_token;
- }
- catch (error) {
- throw new Error(`Error message: ${error.message}`);
- }
- });
- }
-}
-//# sourceMappingURL=oidc-utils.js.map
-;// CONCATENATED MODULE: ./node_modules/@actions/core/lib/summary.js
-var summary_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-
-
-const { access, appendFile, writeFile } = external_fs_namespaceObject.promises;
-const SUMMARY_ENV_VAR = 'GITHUB_STEP_SUMMARY';
-const SUMMARY_DOCS_URL = 'https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary';
-class Summary {
- constructor() {
- this._buffer = '';
- }
- /**
- * Finds the summary file path from the environment, rejects if env var is not found or file does not exist
- * Also checks r/w permissions.
- *
- * @returns step summary file path
- */
- filePath() {
- return summary_awaiter(this, void 0, void 0, function* () {
- if (this._filePath) {
- return this._filePath;
- }
- const pathFromEnv = process.env[SUMMARY_ENV_VAR];
- if (!pathFromEnv) {
- throw new Error(`Unable to find environment variable for $${SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`);
- }
- try {
- yield access(pathFromEnv, external_fs_namespaceObject.constants.R_OK | external_fs_namespaceObject.constants.W_OK);
- }
- catch (_a) {
- throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`);
- }
- this._filePath = pathFromEnv;
- return this._filePath;
- });
- }
- /**
- * Wraps content in an HTML tag, adding any HTML attributes
- *
- * @param {string} tag HTML tag to wrap
- * @param {string | null} content content within the tag
- * @param {[attribute: string]: string} attrs key-value list of HTML attributes to add
- *
- * @returns {string} content wrapped in HTML element
- */
- wrap(tag, content, attrs = {}) {
- const htmlAttrs = Object.entries(attrs)
- .map(([key, value]) => ` ${key}="${value}"`)
- .join('');
- if (!content) {
- return `<${tag}${htmlAttrs}>`;
- }
- return `<${tag}${htmlAttrs}>${content}${tag}>`;
- }
- /**
- * Writes text in the buffer to the summary buffer file and empties buffer. Will append by default.
- *
- * @param {SummaryWriteOptions} [options] (optional) options for write operation
- *
- * @returns {Promise} summary instance
- */
- write(options) {
- return summary_awaiter(this, void 0, void 0, function* () {
- const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite);
- const filePath = yield this.filePath();
- const writeFunc = overwrite ? writeFile : appendFile;
- yield writeFunc(filePath, this._buffer, { encoding: 'utf8' });
- return this.emptyBuffer();
- });
- }
- /**
- * Clears the summary buffer and wipes the summary file
- *
- * @returns {Summary} summary instance
- */
- clear() {
- return summary_awaiter(this, void 0, void 0, function* () {
- return this.emptyBuffer().write({ overwrite: true });
- });
- }
- /**
- * Returns the current summary buffer as a string
- *
- * @returns {string} string of summary buffer
- */
- stringify() {
- return this._buffer;
- }
- /**
- * If the summary buffer is empty
- *
- * @returns {boolen} true if the buffer is empty
- */
- isEmptyBuffer() {
- return this._buffer.length === 0;
- }
- /**
- * Resets the summary buffer without writing to summary file
- *
- * @returns {Summary} summary instance
- */
- emptyBuffer() {
- this._buffer = '';
- return this;
- }
- /**
- * Adds raw text to the summary buffer
- *
- * @param {string} text content to add
- * @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false)
- *
- * @returns {Summary} summary instance
- */
- addRaw(text, addEOL = false) {
- this._buffer += text;
- return addEOL ? this.addEOL() : this;
- }
- /**
- * Adds the operating system-specific end-of-line marker to the buffer
- *
- * @returns {Summary} summary instance
- */
- addEOL() {
- return this.addRaw(external_os_namespaceObject.EOL);
- }
- /**
- * Adds an HTML codeblock to the summary buffer
- *
- * @param {string} code content to render within fenced code block
- * @param {string} lang (optional) language to syntax highlight code
- *
- * @returns {Summary} summary instance
- */
- addCodeBlock(code, lang) {
- const attrs = Object.assign({}, (lang && { lang }));
- const element = this.wrap('pre', this.wrap('code', code), attrs);
- return this.addRaw(element).addEOL();
- }
- /**
- * Adds an HTML list to the summary buffer
- *
- * @param {string[]} items list of items to render
- * @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false)
- *
- * @returns {Summary} summary instance
- */
- addList(items, ordered = false) {
- const tag = ordered ? 'ol' : 'ul';
- const listItems = items.map(item => this.wrap('li', item)).join('');
- const element = this.wrap(tag, listItems);
- return this.addRaw(element).addEOL();
- }
- /**
- * Adds an HTML table to the summary buffer
- *
- * @param {SummaryTableCell[]} rows table rows
- *
- * @returns {Summary} summary instance
- */
- addTable(rows) {
- const tableBody = rows
- .map(row => {
- const cells = row
- .map(cell => {
- if (typeof cell === 'string') {
- return this.wrap('td', cell);
- }
- const { header, data, colspan, rowspan } = cell;
- const tag = header ? 'th' : 'td';
- const attrs = Object.assign(Object.assign({}, (colspan && { colspan })), (rowspan && { rowspan }));
- return this.wrap(tag, data, attrs);
- })
- .join('');
- return this.wrap('tr', cells);
- })
- .join('');
- const element = this.wrap('table', tableBody);
- return this.addRaw(element).addEOL();
- }
- /**
- * Adds a collapsable HTML details element to the summary buffer
- *
- * @param {string} label text for the closed state
- * @param {string} content collapsable content
- *
- * @returns {Summary} summary instance
- */
- addDetails(label, content) {
- const element = this.wrap('details', this.wrap('summary', label) + content);
- return this.addRaw(element).addEOL();
- }
- /**
- * Adds an HTML image tag to the summary buffer
- *
- * @param {string} src path to the image you to embed
- * @param {string} alt text description of the image
- * @param {SummaryImageOptions} options (optional) addition image attributes
- *
- * @returns {Summary} summary instance
- */
- addImage(src, alt, options) {
- const { width, height } = options || {};
- const attrs = Object.assign(Object.assign({}, (width && { width })), (height && { height }));
- const element = this.wrap('img', null, Object.assign({ src, alt }, attrs));
- return this.addRaw(element).addEOL();
- }
- /**
- * Adds an HTML section heading element
- *
- * @param {string} text heading text
- * @param {number | string} [level=1] (optional) the heading level, default: 1
- *
- * @returns {Summary} summary instance
- */
- addHeading(text, level) {
- const tag = `h${level}`;
- const allowedTag = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tag)
- ? tag
- : 'h1';
- const element = this.wrap(allowedTag, text);
- return this.addRaw(element).addEOL();
- }
- /**
- * Adds an HTML thematic break (
) to the summary buffer
- *
- * @returns {Summary} summary instance
- */
- addSeparator() {
- const element = this.wrap('hr', null);
- return this.addRaw(element).addEOL();
- }
- /**
- * Adds an HTML line break (
) to the summary buffer
- *
- * @returns {Summary} summary instance
- */
- addBreak() {
- const element = this.wrap('br', null);
- return this.addRaw(element).addEOL();
- }
- /**
- * Adds an HTML blockquote to the summary buffer
- *
- * @param {string} text quote text
- * @param {string} cite (optional) citation url
- *
- * @returns {Summary} summary instance
- */
- addQuote(text, cite) {
- const attrs = Object.assign({}, (cite && { cite }));
- const element = this.wrap('blockquote', text, attrs);
- return this.addRaw(element).addEOL();
- }
- /**
- * Adds an HTML anchor tag to the summary buffer
- *
- * @param {string} text link text/content
- * @param {string} href hyperlink
- *
- * @returns {Summary} summary instance
- */
- addLink(text, href) {
- const element = this.wrap('a', text, { href });
- return this.addRaw(element).addEOL();
- }
-}
-const _summary = new Summary();
-/**
- * @deprecated use `core.summary`
- */
-const markdownSummary = (/* unused pure expression or super */ null && (_summary));
-const summary = (/* unused pure expression or super */ null && (_summary));
-//# sourceMappingURL=summary.js.map
-;// CONCATENATED MODULE: ./node_modules/@actions/core/lib/path-utils.js
-
-/**
- * toPosixPath converts the given path to the posix form. On Windows, \\ will be
- * replaced with /.
- *
- * @param pth. Path to transform.
- * @return string Posix path.
- */
-function toPosixPath(pth) {
- return pth.replace(/[\\]/g, '/');
-}
-/**
- * toWin32Path converts the given path to the win32 form. On Linux, / will be
- * replaced with \\.
- *
- * @param pth. Path to transform.
- * @return string Win32 path.
- */
-function toWin32Path(pth) {
- return pth.replace(/[/]/g, '\\');
-}
-/**
- * toPlatformPath converts the given path to a platform-specific path. It does
- * this by replacing instances of / and \ with the platform-specific path
- * separator.
- *
- * @param pth The path to platformize.
- * @return string The platform-specific path.
- */
-function toPlatformPath(pth) {
- return pth.replace(/[/\\]/g, path.sep);
-}
-//# sourceMappingURL=path-utils.js.map
-// EXTERNAL MODULE: external "string_decoder"
-var external_string_decoder_ = __nccwpck_require__(3193);
-// EXTERNAL MODULE: external "events"
-var external_events_ = __nccwpck_require__(4434);
-;// CONCATENATED MODULE: external "child_process"
-const external_child_process_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("child_process");
-// EXTERNAL MODULE: external "assert"
-var external_assert_ = __nccwpck_require__(2613);
-;// CONCATENATED MODULE: ./node_modules/@actions/io/lib/io-util.js
-var io_util_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-
-
-const { chmod, copyFile, lstat, mkdir, open: io_util_open, readdir, rename, rm, rmdir, stat, symlink, unlink } = external_fs_namespaceObject.promises;
-// export const {open} = 'fs'
-const IS_WINDOWS = process.platform === 'win32';
-/**
- * Custom implementation of readlink to ensure Windows junctions
- * maintain trailing backslash for backward compatibility with Node.js < 24
- *
- * In Node.js 20, Windows junctions (directory symlinks) always returned paths
- * with trailing backslashes. Node.js 24 removed this behavior, which breaks
- * code that relied on this format for path operations.
- *
- * This implementation restores the Node 20 behavior by adding a trailing
- * backslash to all junction results on Windows.
- */
-function readlink(fsPath) {
- return io_util_awaiter(this, void 0, void 0, function* () {
- const result = yield external_fs_namespaceObject.promises.readlink(fsPath);
- // On Windows, restore Node 20 behavior: add trailing backslash to all results
- // since junctions on Windows are always directory links
- if (IS_WINDOWS && !result.endsWith('\\')) {
- return `${result}\\`;
- }
- return result;
- });
-}
-// See https://github.com/nodejs/node/blob/d0153aee367422d0858105abec186da4dff0a0c5/deps/uv/include/uv/win.h#L691
-const UV_FS_O_EXLOCK = 0x10000000;
-const READONLY = external_fs_namespaceObject.constants.O_RDONLY;
-function exists(fsPath) {
- return io_util_awaiter(this, void 0, void 0, function* () {
- try {
- yield stat(fsPath);
- }
- catch (err) {
- if (err.code === 'ENOENT') {
- return false;
- }
- throw err;
- }
- return true;
- });
-}
-function isDirectory(fsPath_1) {
- return io_util_awaiter(this, arguments, void 0, function* (fsPath, useStat = false) {
- const stats = useStat ? yield stat(fsPath) : yield lstat(fsPath);
- return stats.isDirectory();
- });
-}
-/**
- * On OSX/Linux, true if path starts with '/'. On Windows, true for paths like:
- * \, \hello, \\hello\share, C:, and C:\hello (and corresponding alternate separator cases).
- */
-function isRooted(p) {
- p = normalizeSeparators(p);
- if (!p) {
- throw new Error('isRooted() parameter "p" cannot be empty');
- }
- if (IS_WINDOWS) {
- return (p.startsWith('\\') || /^[A-Z]:/i.test(p) // e.g. \ or \hello or \\hello
- ); // e.g. C: or C:\hello
- }
- return p.startsWith('/');
-}
-/**
- * Best effort attempt to determine whether a file exists and is executable.
- * @param filePath file path to check
- * @param extensions additional file extensions to try
- * @return if file exists and is executable, returns the file path. otherwise empty string.
- */
-function tryGetExecutablePath(filePath, extensions) {
- return io_util_awaiter(this, void 0, void 0, function* () {
- let stats = undefined;
- try {
- // test file exists
- stats = yield stat(filePath);
- }
- catch (err) {
- if (err.code !== 'ENOENT') {
- // eslint-disable-next-line no-console
- console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`);
- }
- }
- if (stats && stats.isFile()) {
- if (IS_WINDOWS) {
- // on Windows, test for valid extension
- const upperExt = external_path_.extname(filePath).toUpperCase();
- if (extensions.some(validExt => validExt.toUpperCase() === upperExt)) {
- return filePath;
- }
- }
- else {
- if (isUnixExecutable(stats)) {
- return filePath;
- }
- }
- }
- // try each extension
- const originalFilePath = filePath;
- for (const extension of extensions) {
- filePath = originalFilePath + extension;
- stats = undefined;
- try {
- stats = yield stat(filePath);
- }
- catch (err) {
- if (err.code !== 'ENOENT') {
- // eslint-disable-next-line no-console
- console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`);
- }
- }
- if (stats && stats.isFile()) {
- if (IS_WINDOWS) {
- // preserve the case of the actual file (since an extension was appended)
- try {
- const directory = external_path_.dirname(filePath);
- const upperName = external_path_.basename(filePath).toUpperCase();
- for (const actualName of yield readdir(directory)) {
- if (upperName === actualName.toUpperCase()) {
- filePath = external_path_.join(directory, actualName);
- break;
- }
- }
- }
- catch (err) {
- // eslint-disable-next-line no-console
- console.log(`Unexpected error attempting to determine the actual case of the file '${filePath}': ${err}`);
- }
- return filePath;
- }
- else {
- if (isUnixExecutable(stats)) {
- return filePath;
- }
- }
- }
- }
- return '';
- });
-}
-function normalizeSeparators(p) {
- p = p || '';
- if (IS_WINDOWS) {
- // convert slashes on Windows
- p = p.replace(/\//g, '\\');
- // remove redundant slashes
- return p.replace(/\\\\+/g, '\\');
- }
- // remove redundant slashes
- return p.replace(/\/\/+/g, '/');
-}
-// on Mac/Linux, test the execute bit
-// R W X R W X R W X
-// 256 128 64 32 16 8 4 2 1
-function isUnixExecutable(stats) {
- return ((stats.mode & 1) > 0 ||
- ((stats.mode & 8) > 0 &&
- process.getgid !== undefined &&
- stats.gid === process.getgid()) ||
- ((stats.mode & 64) > 0 &&
- process.getuid !== undefined &&
- stats.uid === process.getuid()));
-}
-// Get the path of cmd.exe in windows
-function getCmdPath() {
- var _a;
- return (_a = process.env['COMSPEC']) !== null && _a !== void 0 ? _a : `cmd.exe`;
-}
-//# sourceMappingURL=io-util.js.map
-;// CONCATENATED MODULE: ./node_modules/@actions/io/lib/io.js
-var io_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-
-
-
-/**
- * Copies a file or folder.
- * Based off of shelljs - https://github.com/shelljs/shelljs/blob/9237f66c52e5daa40458f94f9565e18e8132f5a6/src/cp.js
- *
- * @param source source path
- * @param dest destination path
- * @param options optional. See CopyOptions.
- */
-function io_cp(source_1, dest_1) {
- return io_awaiter(this, arguments, void 0, function* (source, dest, options = {}) {
- const { force, recursive, copySourceDirectory } = readCopyOptions(options);
- const destStat = (yield exists(dest)) ? yield stat(dest) : null;
- // Dest is an existing file, but not forcing
- if (destStat && destStat.isFile() && !force) {
- return;
- }
- // If dest is an existing directory, should copy inside.
- const newDest = destStat && destStat.isDirectory() && copySourceDirectory
- ? external_path_.join(dest, external_path_.basename(source))
- : dest;
- if (!(yield exists(source))) {
- throw new Error(`no such file or directory: ${source}`);
- }
- const sourceStat = yield stat(source);
- if (sourceStat.isDirectory()) {
- if (!recursive) {
- throw new Error(`Failed to copy. ${source} is a directory, but tried to copy without recursive flag.`);
- }
- else {
- yield cpDirRecursive(source, newDest, 0, force);
- }
- }
- else {
- if (external_path_.relative(source, newDest) === '') {
- // a file cannot be copied to itself
- throw new Error(`'${newDest}' and '${source}' are the same file`);
- }
- yield io_copyFile(source, newDest, force);
- }
- });
-}
-/**
- * Moves a path.
- *
- * @param source source path
- * @param dest destination path
- * @param options optional. See MoveOptions.
- */
-function mv(source_1, dest_1) {
- return io_awaiter(this, arguments, void 0, function* (source, dest, options = {}) {
- if (yield ioUtil.exists(dest)) {
- let destExists = true;
- if (yield ioUtil.isDirectory(dest)) {
- // If dest is directory copy src into dest
- dest = path.join(dest, path.basename(source));
- destExists = yield ioUtil.exists(dest);
- }
- if (destExists) {
- if (options.force == null || options.force) {
- yield rmRF(dest);
- }
- else {
- throw new Error('Destination already exists');
- }
- }
- }
- yield mkdirP(path.dirname(dest));
- yield ioUtil.rename(source, dest);
- });
-}
-/**
- * Remove a path recursively with force
- *
- * @param inputPath path to remove
- */
-function rmRF(inputPath) {
- return io_awaiter(this, void 0, void 0, function* () {
- if (IS_WINDOWS) {
- // Check for invalid characters
- // https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
- if (/[*"<>|]/.test(inputPath)) {
- throw new Error('File path must not contain `*`, `"`, `<`, `>` or `|` on Windows');
- }
- }
- try {
- // note if path does not exist, error is silent
- yield rm(inputPath, {
- force: true,
- maxRetries: 3,
- recursive: true,
- retryDelay: 300
- });
- }
- catch (err) {
- throw new Error(`File was unable to be removed ${err}`);
- }
- });
-}
-/**
- * Make a directory. Creates the full path with folders in between
- * Will throw if it fails
- *
- * @param fsPath path to create
- * @returns Promise
- */
-function mkdirP(fsPath) {
- return io_awaiter(this, void 0, void 0, function* () {
- (0,external_assert_.ok)(fsPath, 'a path argument must be provided');
- yield mkdir(fsPath, { recursive: true });
- });
-}
-/**
- * Returns path of a tool had the tool actually been invoked. Resolves via paths.
- * If you check and the tool does not exist, it will throw.
- *
- * @param tool name of the tool
- * @param check whether to check if tool exists
- * @returns Promise path to tool
- */
-function which(tool, check) {
- return io_awaiter(this, void 0, void 0, function* () {
- if (!tool) {
- throw new Error("parameter 'tool' is required");
- }
- // recursive when check=true
- if (check) {
- const result = yield which(tool, false);
- if (!result) {
- if (IS_WINDOWS) {
- throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.`);
- }
- else {
- throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.`);
- }
- }
- return result;
- }
- const matches = yield findInPath(tool);
- if (matches && matches.length > 0) {
- return matches[0];
- }
- return '';
- });
-}
-/**
- * Returns a list of all occurrences of the given tool on the system path.
- *
- * @returns Promise the paths of the tool
- */
-function findInPath(tool) {
- return io_awaiter(this, void 0, void 0, function* () {
- if (!tool) {
- throw new Error("parameter 'tool' is required");
- }
- // build the list of extensions to try
- const extensions = [];
- if (IS_WINDOWS && process.env['PATHEXT']) {
- for (const extension of process.env['PATHEXT'].split(external_path_.delimiter)) {
- if (extension) {
- extensions.push(extension);
- }
- }
- }
- // if it's rooted, return it if exists. otherwise return empty.
- if (isRooted(tool)) {
- const filePath = yield tryGetExecutablePath(tool, extensions);
- if (filePath) {
- return [filePath];
- }
- return [];
- }
- // if any path separators, return empty
- if (tool.includes(external_path_.sep)) {
- return [];
- }
- // build the list of directories
- //
- // Note, technically "where" checks the current directory on Windows. From a toolkit perspective,
- // it feels like we should not do this. Checking the current directory seems like more of a use
- // case of a shell, and the which() function exposed by the toolkit should strive for consistency
- // across platforms.
- const directories = [];
- if (process.env.PATH) {
- for (const p of process.env.PATH.split(external_path_.delimiter)) {
- if (p) {
- directories.push(p);
- }
- }
- }
- // find all matches
- const matches = [];
- for (const directory of directories) {
- const filePath = yield tryGetExecutablePath(external_path_.join(directory, tool), extensions);
- if (filePath) {
- matches.push(filePath);
- }
- }
- return matches;
- });
-}
-function readCopyOptions(options) {
- const force = options.force == null ? true : options.force;
- const recursive = Boolean(options.recursive);
- const copySourceDirectory = options.copySourceDirectory == null
- ? true
- : Boolean(options.copySourceDirectory);
- return { force, recursive, copySourceDirectory };
-}
-function cpDirRecursive(sourceDir, destDir, currentDepth, force) {
- return io_awaiter(this, void 0, void 0, function* () {
- // Ensure there is not a run away recursive copy
- if (currentDepth >= 255)
- return;
- currentDepth++;
- yield mkdirP(destDir);
- const files = yield readdir(sourceDir);
- for (const fileName of files) {
- const srcFile = `${sourceDir}/${fileName}`;
- const destFile = `${destDir}/${fileName}`;
- const srcFileStat = yield lstat(srcFile);
- if (srcFileStat.isDirectory()) {
- // Recurse
- yield cpDirRecursive(srcFile, destFile, currentDepth, force);
- }
- else {
- yield io_copyFile(srcFile, destFile, force);
- }
- }
- // Change the mode for the newly created directory
- yield chmod(destDir, (yield stat(sourceDir)).mode);
- });
-}
-// Buffered file copy
-function io_copyFile(srcFile, destFile, force) {
- return io_awaiter(this, void 0, void 0, function* () {
- if ((yield lstat(srcFile)).isSymbolicLink()) {
- // unlink/re-link it
- try {
- yield lstat(destFile);
- yield unlink(destFile);
- }
- catch (e) {
- // Try to override file permission
- if (e.code === 'EPERM') {
- yield chmod(destFile, '0666');
- yield unlink(destFile);
- }
- // other errors = it doesn't exist, no work to do
- }
- // Copy over symlink
- const symlinkFull = yield readlink(srcFile);
- yield symlink(symlinkFull, destFile, IS_WINDOWS ? 'junction' : null);
- }
- else if (!(yield exists(destFile)) || force) {
- yield copyFile(srcFile, destFile);
- }
- });
-}
-//# sourceMappingURL=io.js.map
-;// CONCATENATED MODULE: external "timers"
-const external_timers_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("timers");
-;// CONCATENATED MODULE: ./node_modules/@actions/exec/lib/toolrunner.js
-var toolrunner_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-
-
-
-
-
-
-
-/* eslint-disable @typescript-eslint/unbound-method */
-const toolrunner_IS_WINDOWS = process.platform === 'win32';
-/*
- * Class for running command line tools. Handles quoting and arg parsing in a platform agnostic way.
- */
-class ToolRunner extends external_events_.EventEmitter {
- constructor(toolPath, args, options) {
- super();
- if (!toolPath) {
- throw new Error("Parameter 'toolPath' cannot be null or empty.");
- }
- this.toolPath = toolPath;
- this.args = args || [];
- this.options = options || {};
- }
- _debug(message) {
- if (this.options.listeners && this.options.listeners.debug) {
- this.options.listeners.debug(message);
- }
- }
- _getCommandString(options, noPrefix) {
- const toolPath = this._getSpawnFileName();
- const args = this._getSpawnArgs(options);
- let cmd = noPrefix ? '' : '[command]'; // omit prefix when piped to a second tool
- if (toolrunner_IS_WINDOWS) {
- // Windows + cmd file
- if (this._isCmdFile()) {
- cmd += toolPath;
- for (const a of args) {
- cmd += ` ${a}`;
- }
- }
- // Windows + verbatim
- else if (options.windowsVerbatimArguments) {
- cmd += `"${toolPath}"`;
- for (const a of args) {
- cmd += ` ${a}`;
- }
- }
- // Windows (regular)
- else {
- cmd += this._windowsQuoteCmdArg(toolPath);
- for (const a of args) {
- cmd += ` ${this._windowsQuoteCmdArg(a)}`;
- }
- }
- }
- else {
- // OSX/Linux - this can likely be improved with some form of quoting.
- // creating processes on Unix is fundamentally different than Windows.
- // on Unix, execvp() takes an arg array.
- cmd += toolPath;
- for (const a of args) {
- cmd += ` ${a}`;
- }
- }
- return cmd;
- }
- _processLineBuffer(data, strBuffer, onLine) {
- try {
- let s = strBuffer + data.toString();
- let n = s.indexOf(external_os_namespaceObject.EOL);
- while (n > -1) {
- const line = s.substring(0, n);
- onLine(line);
- // the rest of the string ...
- s = s.substring(n + external_os_namespaceObject.EOL.length);
- n = s.indexOf(external_os_namespaceObject.EOL);
- }
- return s;
- }
- catch (err) {
- // streaming lines to console is best effort. Don't fail a build.
- this._debug(`error processing line. Failed with error ${err}`);
- return '';
- }
- }
- _getSpawnFileName() {
- if (toolrunner_IS_WINDOWS) {
- if (this._isCmdFile()) {
- return process.env['COMSPEC'] || 'cmd.exe';
- }
- }
- return this.toolPath;
- }
- _getSpawnArgs(options) {
- if (toolrunner_IS_WINDOWS) {
- if (this._isCmdFile()) {
- let argline = `/D /S /C "${this._windowsQuoteCmdArg(this.toolPath)}`;
- for (const a of this.args) {
- argline += ' ';
- argline += options.windowsVerbatimArguments
- ? a
- : this._windowsQuoteCmdArg(a);
- }
- argline += '"';
- return [argline];
- }
- }
- return this.args;
- }
- _endsWith(str, end) {
- return str.endsWith(end);
- }
- _isCmdFile() {
- const upperToolPath = this.toolPath.toUpperCase();
- return (this._endsWith(upperToolPath, '.CMD') ||
- this._endsWith(upperToolPath, '.BAT'));
- }
- _windowsQuoteCmdArg(arg) {
- // for .exe, apply the normal quoting rules that libuv applies
- if (!this._isCmdFile()) {
- return this._uvQuoteCmdArg(arg);
- }
- // otherwise apply quoting rules specific to the cmd.exe command line parser.
- // the libuv rules are generic and are not designed specifically for cmd.exe
- // command line parser.
- //
- // for a detailed description of the cmd.exe command line parser, refer to
- // http://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/7970912#7970912
- // need quotes for empty arg
- if (!arg) {
- return '""';
- }
- // determine whether the arg needs to be quoted
- const cmdSpecialChars = [
- ' ',
- '\t',
- '&',
- '(',
- ')',
- '[',
- ']',
- '{',
- '}',
- '^',
- '=',
- ';',
- '!',
- "'",
- '+',
- ',',
- '`',
- '~',
- '|',
- '<',
- '>',
- '"'
- ];
- let needsQuotes = false;
- for (const char of arg) {
- if (cmdSpecialChars.some(x => x === char)) {
- needsQuotes = true;
- break;
- }
- }
- // short-circuit if quotes not needed
- if (!needsQuotes) {
- return arg;
- }
- // the following quoting rules are very similar to the rules that by libuv applies.
- //
- // 1) wrap the string in quotes
- //
- // 2) double-up quotes - i.e. " => ""
- //
- // this is different from the libuv quoting rules. libuv replaces " with \", which unfortunately
- // doesn't work well with a cmd.exe command line.
- //
- // note, replacing " with "" also works well if the arg is passed to a downstream .NET console app.
- // for example, the command line:
- // foo.exe "myarg:""my val"""
- // is parsed by a .NET console app into an arg array:
- // [ "myarg:\"my val\"" ]
- // which is the same end result when applying libuv quoting rules. although the actual
- // command line from libuv quoting rules would look like:
- // foo.exe "myarg:\"my val\""
- //
- // 3) double-up slashes that precede a quote,
- // e.g. hello \world => "hello \world"
- // hello\"world => "hello\\""world"
- // hello\\"world => "hello\\\\""world"
- // hello world\ => "hello world\\"
- //
- // technically this is not required for a cmd.exe command line, or the batch argument parser.
- // the reasons for including this as a .cmd quoting rule are:
- //
- // a) this is optimized for the scenario where the argument is passed from the .cmd file to an
- // external program. many programs (e.g. .NET console apps) rely on the slash-doubling rule.
- //
- // b) it's what we've been doing previously (by deferring to node default behavior) and we
- // haven't heard any complaints about that aspect.
- //
- // note, a weakness of the quoting rules chosen here, is that % is not escaped. in fact, % cannot be
- // escaped when used on the command line directly - even though within a .cmd file % can be escaped
- // by using %%.
- //
- // the saving grace is, on the command line, %var% is left as-is if var is not defined. this contrasts
- // the line parsing rules within a .cmd file, where if var is not defined it is replaced with nothing.
- //
- // one option that was explored was replacing % with ^% - i.e. %var% => ^%var^%. this hack would
- // often work, since it is unlikely that var^ would exist, and the ^ character is removed when the
- // variable is used. the problem, however, is that ^ is not removed when %* is used to pass the args
- // to an external program.
- //
- // an unexplored potential solution for the % escaping problem, is to create a wrapper .cmd file.
- // % can be escaped within a .cmd file.
- let reverse = '"';
- let quoteHit = true;
- for (let i = arg.length; i > 0; i--) {
- // walk the string in reverse
- reverse += arg[i - 1];
- if (quoteHit && arg[i - 1] === '\\') {
- reverse += '\\'; // double the slash
- }
- else if (arg[i - 1] === '"') {
- quoteHit = true;
- reverse += '"'; // double the quote
- }
- else {
- quoteHit = false;
- }
- }
- reverse += '"';
- return reverse.split('').reverse().join('');
- }
- _uvQuoteCmdArg(arg) {
- // Tool runner wraps child_process.spawn() and needs to apply the same quoting as
- // Node in certain cases where the undocumented spawn option windowsVerbatimArguments
- // is used.
- //
- // Since this function is a port of quote_cmd_arg from Node 4.x (technically, lib UV,
- // see https://github.com/nodejs/node/blob/v4.x/deps/uv/src/win/process.c for details),
- // pasting copyright notice from Node within this function:
- //
- // 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.
- if (!arg) {
- // Need double quotation for empty argument
- return '""';
- }
- if (!arg.includes(' ') && !arg.includes('\t') && !arg.includes('"')) {
- // No quotation needed
- return arg;
- }
- if (!arg.includes('"') && !arg.includes('\\')) {
- // No embedded double quotes or backslashes, so I can just wrap
- // quote marks around the whole thing.
- return `"${arg}"`;
- }
- // Expected input/output:
- // input : hello"world
- // output: "hello\"world"
- // input : hello""world
- // output: "hello\"\"world"
- // input : hello\world
- // output: hello\world
- // input : hello\\world
- // output: hello\\world
- // input : hello\"world
- // output: "hello\\\"world"
- // input : hello\\"world
- // output: "hello\\\\\"world"
- // input : hello world\
- // output: "hello world\\" - note the comment in libuv actually reads "hello world\"
- // but it appears the comment is wrong, it should be "hello world\\"
- let reverse = '"';
- let quoteHit = true;
- for (let i = arg.length; i > 0; i--) {
- // walk the string in reverse
- reverse += arg[i - 1];
- if (quoteHit && arg[i - 1] === '\\') {
- reverse += '\\';
- }
- else if (arg[i - 1] === '"') {
- quoteHit = true;
- reverse += '\\';
- }
- else {
- quoteHit = false;
- }
- }
- reverse += '"';
- return reverse.split('').reverse().join('');
- }
- _cloneExecOptions(options) {
- options = options || {};
- const result = {
- cwd: options.cwd || process.cwd(),
- env: options.env || process.env,
- silent: options.silent || false,
- windowsVerbatimArguments: options.windowsVerbatimArguments || false,
- failOnStdErr: options.failOnStdErr || false,
- ignoreReturnCode: options.ignoreReturnCode || false,
- delay: options.delay || 10000
- };
- result.outStream = options.outStream || process.stdout;
- result.errStream = options.errStream || process.stderr;
- return result;
- }
- _getSpawnOptions(options, toolPath) {
- options = options || {};
- const result = {};
- result.cwd = options.cwd;
- result.env = options.env;
- result['windowsVerbatimArguments'] =
- options.windowsVerbatimArguments || this._isCmdFile();
- if (options.windowsVerbatimArguments) {
- result.argv0 = `"${toolPath}"`;
- }
- return result;
- }
- /**
- * Exec a tool.
- * Output will be streamed to the live console.
- * Returns promise with return code
- *
- * @param tool path to tool to exec
- * @param options optional exec options. See ExecOptions
- * @returns number
- */
- exec() {
- return toolrunner_awaiter(this, void 0, void 0, function* () {
- // root the tool path if it is unrooted and contains relative pathing
- if (!isRooted(this.toolPath) &&
- (this.toolPath.includes('/') ||
- (toolrunner_IS_WINDOWS && this.toolPath.includes('\\')))) {
- // prefer options.cwd if it is specified, however options.cwd may also need to be rooted
- this.toolPath = external_path_.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath);
- }
- // if the tool is only a file name, then resolve it from the PATH
- // otherwise verify it exists (add extension on Windows if necessary)
- this.toolPath = yield which(this.toolPath, true);
- return new Promise((resolve, reject) => toolrunner_awaiter(this, void 0, void 0, function* () {
- this._debug(`exec tool: ${this.toolPath}`);
- this._debug('arguments:');
- for (const arg of this.args) {
- this._debug(` ${arg}`);
- }
- const optionsNonNull = this._cloneExecOptions(this.options);
- if (!optionsNonNull.silent && optionsNonNull.outStream) {
- optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + external_os_namespaceObject.EOL);
- }
- const state = new ExecState(optionsNonNull, this.toolPath);
- state.on('debug', (message) => {
- this._debug(message);
- });
- if (this.options.cwd && !(yield exists(this.options.cwd))) {
- return reject(new Error(`The cwd: ${this.options.cwd} does not exist!`));
- }
- const fileName = this._getSpawnFileName();
- const cp = external_child_process_namespaceObject.spawn(fileName, this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(this.options, fileName));
- let stdbuffer = '';
- if (cp.stdout) {
- cp.stdout.on('data', (data) => {
- if (this.options.listeners && this.options.listeners.stdout) {
- this.options.listeners.stdout(data);
- }
- if (!optionsNonNull.silent && optionsNonNull.outStream) {
- optionsNonNull.outStream.write(data);
- }
- stdbuffer = this._processLineBuffer(data, stdbuffer, (line) => {
- if (this.options.listeners && this.options.listeners.stdline) {
- this.options.listeners.stdline(line);
- }
- });
- });
- }
- let errbuffer = '';
- if (cp.stderr) {
- cp.stderr.on('data', (data) => {
- state.processStderr = true;
- if (this.options.listeners && this.options.listeners.stderr) {
- this.options.listeners.stderr(data);
- }
- if (!optionsNonNull.silent &&
- optionsNonNull.errStream &&
- optionsNonNull.outStream) {
- const s = optionsNonNull.failOnStdErr
- ? optionsNonNull.errStream
- : optionsNonNull.outStream;
- s.write(data);
- }
- errbuffer = this._processLineBuffer(data, errbuffer, (line) => {
- if (this.options.listeners && this.options.listeners.errline) {
- this.options.listeners.errline(line);
- }
- });
- });
- }
- cp.on('error', (err) => {
- state.processError = err.message;
- state.processExited = true;
- state.processClosed = true;
- state.CheckComplete();
- });
- cp.on('exit', (code) => {
- state.processExitCode = code;
- state.processExited = true;
- this._debug(`Exit code ${code} received from tool '${this.toolPath}'`);
- state.CheckComplete();
- });
- cp.on('close', (code) => {
- state.processExitCode = code;
- state.processExited = true;
- state.processClosed = true;
- this._debug(`STDIO streams have closed for tool '${this.toolPath}'`);
- state.CheckComplete();
- });
- state.on('done', (error, exitCode) => {
- if (stdbuffer.length > 0) {
- this.emit('stdline', stdbuffer);
- }
- if (errbuffer.length > 0) {
- this.emit('errline', errbuffer);
- }
- cp.removeAllListeners();
- if (error) {
- reject(error);
- }
- else {
- resolve(exitCode);
- }
- });
- if (this.options.input) {
- if (!cp.stdin) {
- throw new Error('child process missing stdin');
- }
- cp.stdin.end(this.options.input);
- }
- }));
- });
- }
-}
-/**
- * Convert an arg string to an array of args. Handles escaping
- *
- * @param argString string of arguments
- * @returns string[] array of arguments
- */
-function argStringToArray(argString) {
- const args = [];
- let inQuotes = false;
- let escaped = false;
- let arg = '';
- function append(c) {
- // we only escape double quotes.
- if (escaped && c !== '"') {
- arg += '\\';
- }
- arg += c;
- escaped = false;
- }
- for (let i = 0; i < argString.length; i++) {
- const c = argString.charAt(i);
- if (c === '"') {
- if (!escaped) {
- inQuotes = !inQuotes;
- }
- else {
- append(c);
- }
- continue;
- }
- if (c === '\\' && escaped) {
- append(c);
- continue;
- }
- if (c === '\\' && inQuotes) {
- escaped = true;
- continue;
- }
- if (c === ' ' && !inQuotes) {
- if (arg.length > 0) {
- args.push(arg);
- arg = '';
- }
- continue;
- }
- append(c);
- }
- if (arg.length > 0) {
- args.push(arg.trim());
- }
- return args;
-}
-class ExecState extends external_events_.EventEmitter {
- constructor(options, toolPath) {
- super();
- this.processClosed = false; // tracks whether the process has exited and stdio is closed
- this.processError = '';
- this.processExitCode = 0;
- this.processExited = false; // tracks whether the process has exited
- this.processStderr = false; // tracks whether stderr was written to
- this.delay = 10000; // 10 seconds
- this.done = false;
- this.timeout = null;
- if (!toolPath) {
- throw new Error('toolPath must not be empty');
- }
- this.options = options;
- this.toolPath = toolPath;
- if (options.delay) {
- this.delay = options.delay;
- }
- }
- CheckComplete() {
- if (this.done) {
- return;
- }
- if (this.processClosed) {
- this._setResult();
- }
- else if (this.processExited) {
- this.timeout = (0,external_timers_namespaceObject.setTimeout)(ExecState.HandleTimeout, this.delay, this);
- }
- }
- _debug(message) {
- this.emit('debug', message);
- }
- _setResult() {
- // determine whether there is an error
- let error;
- if (this.processExited) {
- if (this.processError) {
- error = new Error(`There was an error when attempting to execute the process '${this.toolPath}'. This may indicate the process failed to start. Error: ${this.processError}`);
- }
- else if (this.processExitCode !== 0 && !this.options.ignoreReturnCode) {
- error = new Error(`The process '${this.toolPath}' failed with exit code ${this.processExitCode}`);
- }
- else if (this.processStderr && this.options.failOnStdErr) {
- error = new Error(`The process '${this.toolPath}' failed because one or more lines were written to the STDERR stream`);
- }
- }
- // clear the timeout
- if (this.timeout) {
- clearTimeout(this.timeout);
- this.timeout = null;
- }
- this.done = true;
- this.emit('done', error, this.processExitCode);
- }
- static HandleTimeout(state) {
- if (state.done) {
- return;
- }
- if (!state.processClosed && state.processExited) {
- const message = `The STDIO streams did not close within ${state.delay / 1000} seconds of the exit event from process '${state.toolPath}'. This may indicate a child process inherited the STDIO streams and has not yet exited.`;
- state._debug(message);
- }
- state._setResult();
- }
-}
-//# sourceMappingURL=toolrunner.js.map
-;// CONCATENATED MODULE: ./node_modules/@actions/exec/lib/exec.js
-var exec_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-
-
-/**
- * Exec a command.
- * Output will be streamed to the live console.
- * Returns promise with return code
- *
- * @param commandLine command to execute (can include additional args). Must be correctly escaped.
- * @param args optional arguments for tool. Escaping is handled by the lib.
- * @param options optional exec options. See ExecOptions
- * @returns Promise exit code
- */
-function exec_exec(commandLine, args, options) {
- return exec_awaiter(this, void 0, void 0, function* () {
- const commandArgs = argStringToArray(commandLine);
- if (commandArgs.length === 0) {
- throw new Error(`Parameter 'commandLine' cannot be null or empty.`);
- }
- // Path to tool to execute should be first arg
- const toolPath = commandArgs[0];
- args = commandArgs.slice(1).concat(args || []);
- const runner = new ToolRunner(toolPath, args, options);
- return runner.exec();
- });
-}
-/**
- * Exec a command and get the output.
- * Output will be streamed to the live console.
- * Returns promise with the exit code and collected stdout and stderr
- *
- * @param commandLine command to execute (can include additional args). Must be correctly escaped.
- * @param args optional arguments for tool. Escaping is handled by the lib.
- * @param options optional exec options. See ExecOptions
- * @returns Promise exit code, stdout, and stderr
- */
-function getExecOutput(commandLine, args, options) {
- return exec_awaiter(this, void 0, void 0, function* () {
- var _a, _b;
- let stdout = '';
- let stderr = '';
- //Using string decoder covers the case where a mult-byte character is split
- const stdoutDecoder = new StringDecoder('utf8');
- const stderrDecoder = new StringDecoder('utf8');
- const originalStdoutListener = (_a = options === null || options === void 0 ? void 0 : options.listeners) === null || _a === void 0 ? void 0 : _a.stdout;
- const originalStdErrListener = (_b = options === null || options === void 0 ? void 0 : options.listeners) === null || _b === void 0 ? void 0 : _b.stderr;
- const stdErrListener = (data) => {
- stderr += stderrDecoder.write(data);
- if (originalStdErrListener) {
- originalStdErrListener(data);
- }
- };
- const stdOutListener = (data) => {
- stdout += stdoutDecoder.write(data);
- if (originalStdoutListener) {
- originalStdoutListener(data);
- }
- };
- const listeners = Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.listeners), { stdout: stdOutListener, stderr: stdErrListener });
- const exitCode = yield exec_exec(commandLine, args, Object.assign(Object.assign({}, options), { listeners }));
- //flush any remaining characters
- stdout += stdoutDecoder.end();
- stderr += stderrDecoder.end();
- return {
- exitCode,
- stdout,
- stderr
- };
- });
-}
-//# sourceMappingURL=exec.js.map
-;// CONCATENATED MODULE: ./node_modules/@actions/core/lib/platform.js
-var platform_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-
-
-const getWindowsInfo = () => platform_awaiter(void 0, void 0, void 0, function* () {
- const { stdout: version } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Version"', undefined, {
- silent: true
- });
- const { stdout: name } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Caption"', undefined, {
- silent: true
- });
- return {
- name: name.trim(),
- version: version.trim()
- };
-});
-const getMacOsInfo = () => platform_awaiter(void 0, void 0, void 0, function* () {
- var _a, _b, _c, _d;
- const { stdout } = yield exec.getExecOutput('sw_vers', undefined, {
- silent: true
- });
- const version = (_b = (_a = stdout.match(/ProductVersion:\s*(.+)/)) === null || _a === void 0 ? void 0 : _a[1]) !== null && _b !== void 0 ? _b : '';
- const name = (_d = (_c = stdout.match(/ProductName:\s*(.+)/)) === null || _c === void 0 ? void 0 : _c[1]) !== null && _d !== void 0 ? _d : '';
- return {
- name,
- version
- };
-});
-const getLinuxInfo = () => platform_awaiter(void 0, void 0, void 0, function* () {
- const { stdout } = yield exec.getExecOutput('lsb_release', ['-i', '-r', '-s'], {
- silent: true
- });
- const [name, version] = stdout.trim().split('\n');
- return {
- name,
- version
- };
-});
-const platform = external_os_namespaceObject.platform();
-const arch = external_os_namespaceObject.arch();
-const isWindows = platform === 'win32';
-const isMacOS = platform === 'darwin';
-const isLinux = platform === 'linux';
-function getDetails() {
- return platform_awaiter(this, void 0, void 0, function* () {
- return Object.assign(Object.assign({}, (yield (isWindows
- ? getWindowsInfo()
- : isMacOS
- ? getMacOsInfo()
- : getLinuxInfo()))), { platform,
- arch,
- isWindows,
- isMacOS,
- isLinux });
- });
-}
-//# sourceMappingURL=platform.js.map
-;// CONCATENATED MODULE: ./node_modules/@actions/core/lib/core.js
-var core_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-
-
-
-
-
-
-/**
- * The code to exit an action
- */
-var ExitCode;
-(function (ExitCode) {
- /**
- * A code indicating that the action was successful
- */
- ExitCode[ExitCode["Success"] = 0] = "Success";
- /**
- * A code indicating that the action was a failure
- */
- ExitCode[ExitCode["Failure"] = 1] = "Failure";
-})(ExitCode || (ExitCode = {}));
-//-----------------------------------------------------------------------
-// Variables
-//-----------------------------------------------------------------------
-/**
- * Sets env variable for this action and future actions in the job
- * @param name the name of the variable to set
- * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify
- */
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-function exportVariable(name, val) {
- const convertedVal = utils_toCommandValue(val);
- process.env[name] = convertedVal;
- const filePath = process.env['GITHUB_ENV'] || '';
- if (filePath) {
- return file_command_issueFileCommand('ENV', file_command_prepareKeyValueMessage(name, val));
- }
- command_issueCommand('set-env', { name }, convertedVal);
-}
-/**
- * Registers a secret which will get masked from logs
- *
- * @param secret - Value of the secret to be masked
- * @remarks
- * This function instructs the Actions runner to mask the specified value in any
- * logs produced during the workflow run. Once registered, the secret value will
- * be replaced with asterisks (***) whenever it appears in console output, logs,
- * or error messages.
- *
- * This is useful for protecting sensitive information such as:
- * - API keys
- * - Access tokens
- * - Authentication credentials
- * - URL parameters containing signatures (SAS tokens)
- *
- * Note that masking only affects future logs; any previous appearances of the
- * secret in logs before calling this function will remain unmasked.
- *
- * @example
- * ```typescript
- * // Register an API token as a secret
- * const apiToken = "abc123xyz456";
- * setSecret(apiToken);
- *
- * // Now any logs containing this value will show *** instead
- * console.log(`Using token: ${apiToken}`); // Outputs: "Using token: ***"
- * ```
- */
-function core_setSecret(secret) {
- command_issueCommand('add-mask', {}, secret);
-}
-/**
- * Prepends inputPath to the PATH (for this action and future actions)
- * @param inputPath
- */
-function addPath(inputPath) {
- const filePath = process.env['GITHUB_PATH'] || '';
- if (filePath) {
- file_command_issueFileCommand('PATH', inputPath);
- }
- else {
- command_issueCommand('add-path', {}, inputPath);
- }
- process.env['PATH'] = `${inputPath}${external_path_.delimiter}${process.env['PATH']}`;
-}
-/**
- * Gets the value of an input.
- * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed.
- * Returns an empty string if the value is not defined.
- *
- * @param name name of the input to get
- * @param options optional. See InputOptions.
- * @returns string
- */
-function getInput(name, options) {
- const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || '';
- if (options && options.required && !val) {
- throw new Error(`Input required and not supplied: ${name}`);
- }
- if (options && options.trimWhitespace === false) {
- return val;
- }
- return val.trim();
-}
-/**
- * Gets the values of an multiline input. Each value is also trimmed.
- *
- * @param name name of the input to get
- * @param options optional. See InputOptions.
- * @returns string[]
- *
- */
-function getMultilineInput(name, options) {
- const inputs = getInput(name, options)
- .split('\n')
- .filter(x => x !== '');
- if (options && options.trimWhitespace === false) {
- return inputs;
- }
- return inputs.map(input => input.trim());
-}
-/**
- * Gets the input value of the boolean type in the YAML 1.2 "core schema" specification.
- * Support boolean input list: `true | True | TRUE | false | False | FALSE` .
- * The return value is also in boolean type.
- * ref: https://yaml.org/spec/1.2/spec.html#id2804923
- *
- * @param name name of the input to get
- * @param options optional. See InputOptions.
- * @returns boolean
- */
-function getBooleanInput(name, options) {
- const trueValue = ['true', 'True', 'TRUE'];
- const falseValue = ['false', 'False', 'FALSE'];
- const val = getInput(name, options);
- if (trueValue.includes(val))
- return true;
- if (falseValue.includes(val))
- return false;
- throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${name}\n` +
- `Support boolean input list: \`true | True | TRUE | false | False | FALSE\``);
-}
-/**
- * Sets the value of an output.
- *
- * @param name name of the output to set
- * @param value value to store. Non-string values will be converted to a string via JSON.stringify
- */
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-function setOutput(name, value) {
- const filePath = process.env['GITHUB_OUTPUT'] || '';
- if (filePath) {
- return issueFileCommand('OUTPUT', prepareKeyValueMessage(name, value));
- }
- process.stdout.write(os.EOL);
- issueCommand('set-output', { name }, toCommandValue(value));
-}
-/**
- * Enables or disables the echoing of commands into stdout for the rest of the step.
- * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set.
- *
- */
-function setCommandEcho(enabled) {
- issue('echo', enabled ? 'on' : 'off');
-}
-//-----------------------------------------------------------------------
-// Results
-//-----------------------------------------------------------------------
-/**
- * Sets the action status to failed.
- * When the action exits it will be with an exit code of 1
- * @param message add error issue message
- */
-function setFailed(message) {
- process.exitCode = ExitCode.Failure;
- core_error(message);
-}
-//-----------------------------------------------------------------------
-// Logging Commands
-//-----------------------------------------------------------------------
-/**
- * Gets whether Actions Step Debug is on or not
- */
-function isDebug() {
- return process.env['RUNNER_DEBUG'] === '1';
-}
-/**
- * Writes debug message to user log
- * @param message debug message
- */
-function core_debug(message) {
- command_issueCommand('debug', {}, message);
-}
-/**
- * Adds an error issue
- * @param message error issue message. Errors will be converted to string via toString()
- * @param properties optional properties to add to the annotation.
- */
-function core_error(message, properties = {}) {
- command_issueCommand('error', utils_toCommandProperties(properties), message instanceof Error ? message.toString() : message);
-}
-/**
- * Adds a warning issue
- * @param message warning issue message. Errors will be converted to string via toString()
- * @param properties optional properties to add to the annotation.
- */
-function warning(message, properties = {}) {
- command_issueCommand('warning', utils_toCommandProperties(properties), message instanceof Error ? message.toString() : message);
-}
-/**
- * Adds a notice issue
- * @param message notice issue message. Errors will be converted to string via toString()
- * @param properties optional properties to add to the annotation.
- */
-function notice(message, properties = {}) {
- issueCommand('notice', toCommandProperties(properties), message instanceof Error ? message.toString() : message);
-}
-/**
- * Writes info to log with console.log.
- * @param message info message
- */
-function info(message) {
- process.stdout.write(message + external_os_namespaceObject.EOL);
-}
-/**
- * Begin an output group.
- *
- * Output until the next `groupEnd` will be foldable in this group
- *
- * @param name The name of the output group
- */
-function startGroup(name) {
- command_issue('group', name);
-}
-/**
- * End an output group.
- */
-function endGroup() {
- command_issue('endgroup');
-}
-/**
- * Wrap an asynchronous function call in a group.
- *
- * Returns the same type as the function itself.
- *
- * @param name The name of the group
- * @param fn The function to wrap in the group
- */
-function group(name, fn) {
- return core_awaiter(this, void 0, void 0, function* () {
- startGroup(name);
- let result;
- try {
- result = yield fn();
- }
- finally {
- endGroup();
- }
- return result;
- });
-}
-//-----------------------------------------------------------------------
-// Wrapper action state
-//-----------------------------------------------------------------------
-/**
- * Saves state for current action, the state can only be retrieved by this action's post job execution.
- *
- * @param name name of the state to store
- * @param value value to store. Non-string values will be converted to a string via JSON.stringify
- */
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-function saveState(name, value) {
- const filePath = process.env['GITHUB_STATE'] || '';
- if (filePath) {
- return file_command_issueFileCommand('STATE', file_command_prepareKeyValueMessage(name, value));
- }
- command_issueCommand('save-state', { name }, utils_toCommandValue(value));
-}
-/**
- * Gets the value of an state set by this action's main execution.
- *
- * @param name name of the state to get
- * @returns string
- */
-function getState(name) {
- return process.env[`STATE_${name}`] || '';
-}
-function getIDToken(aud) {
- return core_awaiter(this, void 0, void 0, function* () {
- return yield OidcClient.getIDToken(aud);
- });
-}
-/**
- * Summary exports
- */
-
-/**
- * @deprecated use core.summary
- */
-
-/**
- * Path exports
- */
-
-/**
- * Platform utilities exports
- */
-
-//# sourceMappingURL=core.js.map
-;// CONCATENATED MODULE: ./node_modules/@actions/glob/lib/internal-glob-options-helper.js
-
-/**
- * Returns a copy with defaults filled in.
- */
-function getOptions(copy) {
- const result = {
- followSymbolicLinks: true,
- implicitDescendants: true,
- matchDirectories: true,
- omitBrokenSymbolicLinks: true,
- excludeHiddenFiles: false
- };
- if (copy) {
- if (typeof copy.followSymbolicLinks === 'boolean') {
- result.followSymbolicLinks = copy.followSymbolicLinks;
- core_debug(`followSymbolicLinks '${result.followSymbolicLinks}'`);
- }
- if (typeof copy.implicitDescendants === 'boolean') {
- result.implicitDescendants = copy.implicitDescendants;
- core_debug(`implicitDescendants '${result.implicitDescendants}'`);
- }
- if (typeof copy.matchDirectories === 'boolean') {
- result.matchDirectories = copy.matchDirectories;
- core_debug(`matchDirectories '${result.matchDirectories}'`);
- }
- if (typeof copy.omitBrokenSymbolicLinks === 'boolean') {
- result.omitBrokenSymbolicLinks = copy.omitBrokenSymbolicLinks;
- core_debug(`omitBrokenSymbolicLinks '${result.omitBrokenSymbolicLinks}'`);
- }
- if (typeof copy.excludeHiddenFiles === 'boolean') {
- result.excludeHiddenFiles = copy.excludeHiddenFiles;
- core_debug(`excludeHiddenFiles '${result.excludeHiddenFiles}'`);
- }
- }
- return result;
-}
-//# sourceMappingURL=internal-glob-options-helper.js.map
-;// CONCATENATED MODULE: ./node_modules/@actions/glob/lib/internal-path-helper.js
-
-
-const internal_path_helper_IS_WINDOWS = process.platform === 'win32';
-/**
- * Similar to path.dirname except normalizes the path separators and slightly better handling for Windows UNC paths.
- *
- * For example, on Linux/macOS:
- * - `/ => /`
- * - `/hello => /`
- *
- * For example, on Windows:
- * - `C:\ => C:\`
- * - `C:\hello => C:\`
- * - `C: => C:`
- * - `C:hello => C:`
- * - `\ => \`
- * - `\hello => \`
- * - `\\hello => \\hello`
- * - `\\hello\world => \\hello\world`
- */
-function dirname(p) {
- // Normalize slashes and trim unnecessary trailing slash
- p = safeTrimTrailingSeparator(p);
- // Windows UNC root, e.g. \\hello or \\hello\world
- if (internal_path_helper_IS_WINDOWS && /^\\\\[^\\]+(\\[^\\]+)?$/.test(p)) {
- return p;
- }
- // Get dirname
- let result = external_path_.dirname(p);
- // Trim trailing slash for Windows UNC root, e.g. \\hello\world\
- if (internal_path_helper_IS_WINDOWS && /^\\\\[^\\]+\\[^\\]+\\$/.test(result)) {
- result = safeTrimTrailingSeparator(result);
- }
- return result;
-}
-/**
- * Roots the path if not already rooted. On Windows, relative roots like `\`
- * or `C:` are expanded based on the current working directory.
- */
-function ensureAbsoluteRoot(root, itemPath) {
- external_assert_(root, `ensureAbsoluteRoot parameter 'root' must not be empty`);
- external_assert_(itemPath, `ensureAbsoluteRoot parameter 'itemPath' must not be empty`);
- // Already rooted
- if (hasAbsoluteRoot(itemPath)) {
- return itemPath;
- }
- // Windows
- if (internal_path_helper_IS_WINDOWS) {
- // Check for itemPath like C: or C:foo
- if (itemPath.match(/^[A-Z]:[^\\/]|^[A-Z]:$/i)) {
- let cwd = process.cwd();
- external_assert_(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`);
- // Drive letter matches cwd? Expand to cwd
- if (itemPath[0].toUpperCase() === cwd[0].toUpperCase()) {
- // Drive only, e.g. C:
- if (itemPath.length === 2) {
- // Preserve specified drive letter case (upper or lower)
- return `${itemPath[0]}:\\${cwd.substr(3)}`;
- }
- // Drive + path, e.g. C:foo
- else {
- if (!cwd.endsWith('\\')) {
- cwd += '\\';
- }
- // Preserve specified drive letter case (upper or lower)
- return `${itemPath[0]}:\\${cwd.substr(3)}${itemPath.substr(2)}`;
- }
- }
- // Different drive
- else {
- return `${itemPath[0]}:\\${itemPath.substr(2)}`;
- }
- }
- // Check for itemPath like \ or \foo
- else if (internal_path_helper_normalizeSeparators(itemPath).match(/^\\$|^\\[^\\]/)) {
- const cwd = process.cwd();
- external_assert_(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`);
- return `${cwd[0]}:\\${itemPath.substr(1)}`;
- }
- }
- external_assert_(hasAbsoluteRoot(root), `ensureAbsoluteRoot parameter 'root' must have an absolute root`);
- // Otherwise ensure root ends with a separator
- if (root.endsWith('/') || (internal_path_helper_IS_WINDOWS && root.endsWith('\\'))) {
- // Intentionally empty
- }
- else {
- // Append separator
- root += external_path_.sep;
- }
- return root + itemPath;
-}
-/**
- * On Linux/macOS, true if path starts with `/`. On Windows, true for paths like:
- * `\\hello\share` and `C:\hello` (and using alternate separator).
- */
-function hasAbsoluteRoot(itemPath) {
- external_assert_(itemPath, `hasAbsoluteRoot parameter 'itemPath' must not be empty`);
- // Normalize separators
- itemPath = internal_path_helper_normalizeSeparators(itemPath);
- // Windows
- if (internal_path_helper_IS_WINDOWS) {
- // E.g. \\hello\share or C:\hello
- return itemPath.startsWith('\\\\') || /^[A-Z]:\\/i.test(itemPath);
- }
- // E.g. /hello
- return itemPath.startsWith('/');
-}
-/**
- * On Linux/macOS, true if path starts with `/`. On Windows, true for paths like:
- * `\`, `\hello`, `\\hello\share`, `C:`, and `C:\hello` (and using alternate separator).
- */
-function hasRoot(itemPath) {
- external_assert_(itemPath, `isRooted parameter 'itemPath' must not be empty`);
- // Normalize separators
- itemPath = internal_path_helper_normalizeSeparators(itemPath);
- // Windows
- if (internal_path_helper_IS_WINDOWS) {
- // E.g. \ or \hello or \\hello
- // E.g. C: or C:\hello
- return itemPath.startsWith('\\') || /^[A-Z]:/i.test(itemPath);
- }
- // E.g. /hello
- return itemPath.startsWith('/');
-}
-/**
- * Removes redundant slashes and converts `/` to `\` on Windows
- */
-function internal_path_helper_normalizeSeparators(p) {
- p = p || '';
- // Windows
- if (internal_path_helper_IS_WINDOWS) {
- // Convert slashes on Windows
- p = p.replace(/\//g, '\\');
- // Remove redundant slashes
- const isUnc = /^\\\\+[^\\]/.test(p); // e.g. \\hello
- return (isUnc ? '\\' : '') + p.replace(/\\\\+/g, '\\'); // preserve leading \\ for UNC
- }
- // Remove redundant slashes
- return p.replace(/\/\/+/g, '/');
-}
-/**
- * Normalizes the path separators and trims the trailing separator (when safe).
- * For example, `/foo/ => /foo` but `/ => /`
- */
-function safeTrimTrailingSeparator(p) {
- // Short-circuit if empty
- if (!p) {
- return '';
- }
- // Normalize separators
- p = internal_path_helper_normalizeSeparators(p);
- // No trailing slash
- if (!p.endsWith(external_path_.sep)) {
- return p;
- }
- // Check '/' on Linux/macOS and '\' on Windows
- if (p === external_path_.sep) {
- return p;
- }
- // On Windows check if drive root. E.g. C:\
- if (internal_path_helper_IS_WINDOWS && /^[A-Z]:\\$/i.test(p)) {
- return p;
- }
- // Otherwise trim trailing slash
- return p.substr(0, p.length - 1);
-}
-//# sourceMappingURL=internal-path-helper.js.map
-;// CONCATENATED MODULE: ./node_modules/@actions/glob/lib/internal-match-kind.js
-/**
- * Indicates whether a pattern matches a path
- */
-var MatchKind;
-(function (MatchKind) {
- /** Not matched */
- MatchKind[MatchKind["None"] = 0] = "None";
- /** Matched if the path is a directory */
- MatchKind[MatchKind["Directory"] = 1] = "Directory";
- /** Matched if the path is a regular file */
- MatchKind[MatchKind["File"] = 2] = "File";
- /** Matched */
- MatchKind[MatchKind["All"] = 3] = "All";
-})(MatchKind || (MatchKind = {}));
-//# sourceMappingURL=internal-match-kind.js.map
-;// CONCATENATED MODULE: ./node_modules/@actions/glob/lib/internal-pattern-helper.js
-
-
-const internal_pattern_helper_IS_WINDOWS = process.platform === 'win32';
-/**
- * Given an array of patterns, returns an array of paths to search.
- * Duplicates and paths under other included paths are filtered out.
- */
-function getSearchPaths(patterns) {
- // Ignore negate patterns
- patterns = patterns.filter(x => !x.negate);
- // Create a map of all search paths
- const searchPathMap = {};
- for (const pattern of patterns) {
- const key = internal_pattern_helper_IS_WINDOWS
- ? pattern.searchPath.toUpperCase()
- : pattern.searchPath;
- searchPathMap[key] = 'candidate';
- }
- const result = [];
- for (const pattern of patterns) {
- // Check if already included
- const key = internal_pattern_helper_IS_WINDOWS
- ? pattern.searchPath.toUpperCase()
- : pattern.searchPath;
- if (searchPathMap[key] === 'included') {
- continue;
- }
- // Check for an ancestor search path
- let foundAncestor = false;
- let tempKey = key;
- let parent = dirname(tempKey);
- while (parent !== tempKey) {
- if (searchPathMap[parent]) {
- foundAncestor = true;
- break;
- }
- tempKey = parent;
- parent = dirname(tempKey);
- }
- // Include the search pattern in the result
- if (!foundAncestor) {
- result.push(pattern.searchPath);
- searchPathMap[key] = 'included';
- }
- }
- return result;
-}
-/**
- * Matches the patterns against the path
- */
-function internal_pattern_helper_match(patterns, itemPath) {
- let result = MatchKind.None;
- for (const pattern of patterns) {
- if (pattern.negate) {
- result &= ~pattern.match(itemPath);
- }
- else {
- result |= pattern.match(itemPath);
- }
- }
- return result;
-}
-/**
- * Checks whether to descend further into the directory
- */
-function internal_pattern_helper_partialMatch(patterns, itemPath) {
- return patterns.some(x => !x.negate && x.partialMatch(itemPath));
-}
-//# sourceMappingURL=internal-pattern-helper.js.map
-// EXTERNAL MODULE: ./node_modules/minimatch/minimatch.js
-var minimatch = __nccwpck_require__(3772);
-;// CONCATENATED MODULE: ./node_modules/@actions/glob/lib/internal-path.js
-
-
-
-const internal_path_IS_WINDOWS = process.platform === 'win32';
-/**
- * Helper class for parsing paths into segments
- */
-class Path {
- /**
- * Constructs a Path
- * @param itemPath Path or array of segments
- */
- constructor(itemPath) {
- this.segments = [];
- // String
- if (typeof itemPath === 'string') {
- external_assert_(itemPath, `Parameter 'itemPath' must not be empty`);
- // Normalize slashes and trim unnecessary trailing slash
- itemPath = safeTrimTrailingSeparator(itemPath);
- // Not rooted
- if (!hasRoot(itemPath)) {
- this.segments = itemPath.split(external_path_.sep);
- }
- // Rooted
- else {
- // Add all segments, while not at the root
- let remaining = itemPath;
- let dir = dirname(remaining);
- while (dir !== remaining) {
- // Add the segment
- const basename = external_path_.basename(remaining);
- this.segments.unshift(basename);
- // Truncate the last segment
- remaining = dir;
- dir = dirname(remaining);
- }
- // Remainder is the root
- this.segments.unshift(remaining);
- }
- }
- // Array
- else {
- // Must not be empty
- external_assert_(itemPath.length > 0, `Parameter 'itemPath' must not be an empty array`);
- // Each segment
- for (let i = 0; i < itemPath.length; i++) {
- let segment = itemPath[i];
- // Must not be empty
- external_assert_(segment, `Parameter 'itemPath' must not contain any empty segments`);
- // Normalize slashes
- segment = internal_path_helper_normalizeSeparators(itemPath[i]);
- // Root segment
- if (i === 0 && hasRoot(segment)) {
- segment = safeTrimTrailingSeparator(segment);
- external_assert_(segment === dirname(segment), `Parameter 'itemPath' root segment contains information for multiple segments`);
- this.segments.push(segment);
- }
- // All other segments
- else {
- // Must not contain slash
- external_assert_(!segment.includes(external_path_.sep), `Parameter 'itemPath' contains unexpected path separators`);
- this.segments.push(segment);
- }
- }
- }
- }
- /**
- * Converts the path to it's string representation
- */
- toString() {
- // First segment
- let result = this.segments[0];
- // All others
- let skipSlash = result.endsWith(external_path_.sep) || (internal_path_IS_WINDOWS && /^[A-Z]:$/i.test(result));
- for (let i = 1; i < this.segments.length; i++) {
- if (skipSlash) {
- skipSlash = false;
- }
- else {
- result += external_path_.sep;
- }
- result += this.segments[i];
- }
- return result;
- }
-}
-//# sourceMappingURL=internal-path.js.map
-;// CONCATENATED MODULE: ./node_modules/@actions/glob/lib/internal-pattern.js
-
-
-
-
-
-
-
-const { Minimatch } = minimatch;
-const internal_pattern_IS_WINDOWS = process.platform === 'win32';
-class Pattern {
- constructor(patternOrNegate, isImplicitPattern = false, segments, homedir) {
- /**
- * Indicates whether matches should be excluded from the result set
- */
- this.negate = false;
- // Pattern overload
- let pattern;
- if (typeof patternOrNegate === 'string') {
- pattern = patternOrNegate.trim();
- }
- // Segments overload
- else {
- // Convert to pattern
- segments = segments || [];
- external_assert_(segments.length, `Parameter 'segments' must not empty`);
- const root = Pattern.getLiteral(segments[0]);
- external_assert_(root && hasAbsoluteRoot(root), `Parameter 'segments' first element must be a root path`);
- pattern = new Path(segments).toString().trim();
- if (patternOrNegate) {
- pattern = `!${pattern}`;
- }
- }
- // Negate
- while (pattern.startsWith('!')) {
- this.negate = !this.negate;
- pattern = pattern.substr(1).trim();
- }
- // Normalize slashes and ensures absolute root
- pattern = Pattern.fixupPattern(pattern, homedir);
- // Segments
- this.segments = new Path(pattern).segments;
- // Trailing slash indicates the pattern should only match directories, not regular files
- this.trailingSeparator = internal_path_helper_normalizeSeparators(pattern)
- .endsWith(external_path_.sep);
- pattern = safeTrimTrailingSeparator(pattern);
- // Search path (literal path prior to the first glob segment)
- let foundGlob = false;
- const searchSegments = this.segments
- .map(x => Pattern.getLiteral(x))
- .filter(x => !foundGlob && !(foundGlob = x === ''));
- this.searchPath = new Path(searchSegments).toString();
- // Root RegExp (required when determining partial match)
- this.rootRegExp = new RegExp(Pattern.regExpEscape(searchSegments[0]), internal_pattern_IS_WINDOWS ? 'i' : '');
- this.isImplicitPattern = isImplicitPattern;
- // Create minimatch
- const minimatchOptions = {
- dot: true,
- nobrace: true,
- nocase: internal_pattern_IS_WINDOWS,
- nocomment: true,
- noext: true,
- nonegate: true
- };
- pattern = internal_pattern_IS_WINDOWS ? pattern.replace(/\\/g, '/') : pattern;
- this.minimatch = new Minimatch(pattern, minimatchOptions);
- }
- /**
- * Matches the pattern against the specified path
- */
- match(itemPath) {
- // Last segment is globstar?
- if (this.segments[this.segments.length - 1] === '**') {
- // Normalize slashes
- itemPath = internal_path_helper_normalizeSeparators(itemPath);
- // Append a trailing slash. Otherwise Minimatch will not match the directory immediately
- // preceding the globstar. For example, given the pattern `/foo/**`, Minimatch returns
- // false for `/foo` but returns true for `/foo/`. Append a trailing slash to handle that quirk.
- if (!itemPath.endsWith(external_path_.sep) && this.isImplicitPattern === false) {
- // Note, this is safe because the constructor ensures the pattern has an absolute root.
- // For example, formats like C: and C:foo on Windows are resolved to an absolute root.
- itemPath = `${itemPath}${external_path_.sep}`;
- }
- }
- else {
- // Normalize slashes and trim unnecessary trailing slash
- itemPath = safeTrimTrailingSeparator(itemPath);
- }
- // Match
- if (this.minimatch.match(itemPath)) {
- return this.trailingSeparator ? MatchKind.Directory : MatchKind.All;
- }
- return MatchKind.None;
- }
- /**
- * Indicates whether the pattern may match descendants of the specified path
- */
- partialMatch(itemPath) {
- // Normalize slashes and trim unnecessary trailing slash
- itemPath = safeTrimTrailingSeparator(itemPath);
- // matchOne does not handle root path correctly
- if (dirname(itemPath) === itemPath) {
- return this.rootRegExp.test(itemPath);
- }
- return this.minimatch.matchOne(itemPath.split(internal_pattern_IS_WINDOWS ? /\\+/ : /\/+/), this.minimatch.set[0], true);
- }
- /**
- * Escapes glob patterns within a path
- */
- static globEscape(s) {
- return (internal_pattern_IS_WINDOWS ? s : s.replace(/\\/g, '\\\\')) // escape '\' on Linux/macOS
- .replace(/(\[)(?=[^/]+\])/g, '[[]') // escape '[' when ']' follows within the path segment
- .replace(/\?/g, '[?]') // escape '?'
- .replace(/\*/g, '[*]'); // escape '*'
- }
- /**
- * Normalizes slashes and ensures absolute root
- */
- static fixupPattern(pattern, homedir) {
- // Empty
- external_assert_(pattern, 'pattern cannot be empty');
- // Must not contain `.` segment, unless first segment
- // Must not contain `..` segment
- const literalSegments = new Path(pattern).segments.map(x => Pattern.getLiteral(x));
- external_assert_(literalSegments.every((x, i) => (x !== '.' || i === 0) && x !== '..'), `Invalid pattern '${pattern}'. Relative pathing '.' and '..' is not allowed.`);
- // Must not contain globs in root, e.g. Windows UNC path \\foo\b*r
- external_assert_(!hasRoot(pattern) || literalSegments[0], `Invalid pattern '${pattern}'. Root segment must not contain globs.`);
- // Normalize slashes
- pattern = internal_path_helper_normalizeSeparators(pattern);
- // Replace leading `.` segment
- if (pattern === '.' || pattern.startsWith(`.${external_path_.sep}`)) {
- pattern = Pattern.globEscape(process.cwd()) + pattern.substr(1);
- }
- // Replace leading `~` segment
- else if (pattern === '~' || pattern.startsWith(`~${external_path_.sep}`)) {
- homedir = homedir || external_os_namespaceObject.homedir();
- external_assert_(homedir, 'Unable to determine HOME directory');
- external_assert_(hasAbsoluteRoot(homedir), `Expected HOME directory to be a rooted path. Actual '${homedir}'`);
- pattern = Pattern.globEscape(homedir) + pattern.substr(1);
- }
- // Replace relative drive root, e.g. pattern is C: or C:foo
- else if (internal_pattern_IS_WINDOWS &&
- (pattern.match(/^[A-Z]:$/i) || pattern.match(/^[A-Z]:[^\\]/i))) {
- let root = ensureAbsoluteRoot('C:\\dummy-root', pattern.substr(0, 2));
- if (pattern.length > 2 && !root.endsWith('\\')) {
- root += '\\';
- }
- pattern = Pattern.globEscape(root) + pattern.substr(2);
- }
- // Replace relative root, e.g. pattern is \ or \foo
- else if (internal_pattern_IS_WINDOWS && (pattern === '\\' || pattern.match(/^\\[^\\]/))) {
- let root = ensureAbsoluteRoot('C:\\dummy-root', '\\');
- if (!root.endsWith('\\')) {
- root += '\\';
- }
- pattern = Pattern.globEscape(root) + pattern.substr(1);
- }
- // Otherwise ensure absolute root
- else {
- pattern = ensureAbsoluteRoot(Pattern.globEscape(process.cwd()), pattern);
- }
- return internal_path_helper_normalizeSeparators(pattern);
- }
- /**
- * Attempts to unescape a pattern segment to create a literal path segment.
- * Otherwise returns empty string.
- */
- static getLiteral(segment) {
- let literal = '';
- for (let i = 0; i < segment.length; i++) {
- const c = segment[i];
- // Escape
- if (c === '\\' && !internal_pattern_IS_WINDOWS && i + 1 < segment.length) {
- literal += segment[++i];
- continue;
- }
- // Wildcard
- else if (c === '*' || c === '?') {
- return '';
- }
- // Character set
- else if (c === '[' && i + 1 < segment.length) {
- let set = '';
- let closed = -1;
- for (let i2 = i + 1; i2 < segment.length; i2++) {
- const c2 = segment[i2];
- // Escape
- if (c2 === '\\' && !internal_pattern_IS_WINDOWS && i2 + 1 < segment.length) {
- set += segment[++i2];
- continue;
- }
- // Closed
- else if (c2 === ']') {
- closed = i2;
- break;
- }
- // Otherwise
- else {
- set += c2;
- }
- }
- // Closed?
- if (closed >= 0) {
- // Cannot convert
- if (set.length > 1) {
- return '';
- }
- // Convert to literal
- if (set) {
- literal += set;
- i = closed;
- continue;
- }
- }
- // Otherwise fall thru
- }
- // Append
- literal += c;
- }
- return literal;
- }
- /**
- * Escapes regexp special characters
- * https://javascript.info/regexp-escaping
- */
- static regExpEscape(s) {
- return s.replace(/[[\\^$.|?*+()]/g, '\\$&');
- }
-}
-//# sourceMappingURL=internal-pattern.js.map
-;// CONCATENATED MODULE: ./node_modules/@actions/glob/lib/internal-search-state.js
-class SearchState {
- constructor(path, level) {
- this.path = path;
- this.level = level;
- }
-}
-//# sourceMappingURL=internal-search-state.js.map
-;// CONCATENATED MODULE: ./node_modules/@actions/glob/lib/internal-globber.js
-var internal_globber_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-var __asyncValues = (undefined && undefined.__asyncValues) || function (o) {
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
- var m = o[Symbol.asyncIterator], i;
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
- function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
- function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
-};
-var __await = (undefined && undefined.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }
-var __asyncGenerator = (undefined && undefined.__asyncGenerator) || function (thisArg, _arguments, generator) {
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
- var g = generator.apply(thisArg, _arguments || []), i, q = [];
- return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
- function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
- function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
- function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
- function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
- function fulfill(value) { resume("next", value); }
- function reject(value) { resume("throw", value); }
- function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
-};
-
-
-
-
-
-
-
-
-const internal_globber_IS_WINDOWS = process.platform === 'win32';
-class DefaultGlobber {
- constructor(options) {
- this.patterns = [];
- this.searchPaths = [];
- this.options = getOptions(options);
- }
- getSearchPaths() {
- // Return a copy
- return this.searchPaths.slice();
- }
- glob() {
- return internal_globber_awaiter(this, void 0, void 0, function* () {
- var _a, e_1, _b, _c;
- const result = [];
- try {
- for (var _d = true, _e = __asyncValues(this.globGenerator()), _f; _f = yield _e.next(), _a = _f.done, !_a; _d = true) {
- _c = _f.value;
- _d = false;
- const itemPath = _c;
- result.push(itemPath);
- }
- }
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
- finally {
- try {
- if (!_d && !_a && (_b = _e.return)) yield _b.call(_e);
- }
- finally { if (e_1) throw e_1.error; }
- }
- return result;
- });
- }
- globGenerator() {
- return __asyncGenerator(this, arguments, function* globGenerator_1() {
- // Fill in defaults options
- const options = getOptions(this.options);
- // Implicit descendants?
- const patterns = [];
- for (const pattern of this.patterns) {
- patterns.push(pattern);
- if (options.implicitDescendants &&
- (pattern.trailingSeparator ||
- pattern.segments[pattern.segments.length - 1] !== '**')) {
- patterns.push(new Pattern(pattern.negate, true, pattern.segments.concat('**')));
- }
- }
- // Push the search paths
- const stack = [];
- for (const searchPath of getSearchPaths(patterns)) {
- core_debug(`Search path '${searchPath}'`);
- // Exists?
- try {
- // Intentionally using lstat. Detection for broken symlink
- // will be performed later (if following symlinks).
- yield __await(external_fs_namespaceObject.promises.lstat(searchPath));
- }
- catch (err) {
- if (err.code === 'ENOENT') {
- continue;
- }
- throw err;
- }
- stack.unshift(new SearchState(searchPath, 1));
- }
- // Search
- const traversalChain = []; // used to detect cycles
- while (stack.length) {
- // Pop
- const item = stack.pop();
- // Match?
- const match = internal_pattern_helper_match(patterns, item.path);
- const partialMatch = !!match || internal_pattern_helper_partialMatch(patterns, item.path);
- if (!match && !partialMatch) {
- continue;
- }
- // Stat
- const stats = yield __await(DefaultGlobber.stat(item, options, traversalChain)
- // Broken symlink, or symlink cycle detected, or no longer exists
- );
- // Broken symlink, or symlink cycle detected, or no longer exists
- if (!stats) {
- continue;
- }
- // Hidden file or directory?
- if (options.excludeHiddenFiles && external_path_.basename(item.path).match(/^\./)) {
- continue;
- }
- // Directory
- if (stats.isDirectory()) {
- // Matched
- if (match & MatchKind.Directory && options.matchDirectories) {
- yield yield __await(item.path);
- }
- // Descend?
- else if (!partialMatch) {
- continue;
- }
- // Push the child items in reverse
- const childLevel = item.level + 1;
- const childItems = (yield __await(external_fs_namespaceObject.promises.readdir(item.path))).map(x => new SearchState(external_path_.join(item.path, x), childLevel));
- stack.push(...childItems.reverse());
- }
- // File
- else if (match & MatchKind.File) {
- yield yield __await(item.path);
- }
- }
- });
- }
- /**
- * Constructs a DefaultGlobber
- */
- static create(patterns, options) {
- return internal_globber_awaiter(this, void 0, void 0, function* () {
- const result = new DefaultGlobber(options);
- if (internal_globber_IS_WINDOWS) {
- patterns = patterns.replace(/\r\n/g, '\n');
- patterns = patterns.replace(/\r/g, '\n');
- }
- const lines = patterns.split('\n').map(x => x.trim());
- for (const line of lines) {
- // Empty or comment
- if (!line || line.startsWith('#')) {
- continue;
- }
- // Pattern
- else {
- result.patterns.push(new Pattern(line));
- }
- }
- result.searchPaths.push(...getSearchPaths(result.patterns));
- return result;
- });
- }
- static stat(item, options, traversalChain) {
- return internal_globber_awaiter(this, void 0, void 0, function* () {
- // Note:
- // `stat` returns info about the target of a symlink (or symlink chain)
- // `lstat` returns info about a symlink itself
- let stats;
- if (options.followSymbolicLinks) {
- try {
- // Use `stat` (following symlinks)
- stats = yield external_fs_namespaceObject.promises.stat(item.path);
- }
- catch (err) {
- if (err.code === 'ENOENT') {
- if (options.omitBrokenSymbolicLinks) {
- core_debug(`Broken symlink '${item.path}'`);
- return undefined;
- }
- throw new Error(`No information found for the path '${item.path}'. This may indicate a broken symbolic link.`);
- }
- throw err;
- }
- }
- else {
- // Use `lstat` (not following symlinks)
- stats = yield external_fs_namespaceObject.promises.lstat(item.path);
- }
- // Note, isDirectory() returns false for the lstat of a symlink
- if (stats.isDirectory() && options.followSymbolicLinks) {
- // Get the realpath
- const realPath = yield external_fs_namespaceObject.promises.realpath(item.path);
- // Fixup the traversal chain to match the item level
- while (traversalChain.length >= item.level) {
- traversalChain.pop();
- }
- // Test for a cycle
- if (traversalChain.some((x) => x === realPath)) {
- core_debug(`Symlink cycle detected for path '${item.path}' and realpath '${realPath}'`);
- return undefined;
- }
- // Update the traversal chain
- traversalChain.push(realPath);
- }
- return stats;
- });
- }
-}
-//# sourceMappingURL=internal-globber.js.map
-;// CONCATENATED MODULE: external "stream"
-const external_stream_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("stream");
-// EXTERNAL MODULE: external "util"
-var external_util_ = __nccwpck_require__(9023);
-;// CONCATENATED MODULE: ./node_modules/@actions/glob/lib/internal-hash-files.js
-var internal_hash_files_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-var internal_hash_files_asyncValues = (undefined && undefined.__asyncValues) || function (o) {
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
- var m = o[Symbol.asyncIterator], i;
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
- function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
- function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
-};
-
-
-
-
-
-
-function hashFiles(globber_1, currentWorkspace_1) {
- return internal_hash_files_awaiter(this, arguments, void 0, function* (globber, currentWorkspace, verbose = false) {
- var _a, e_1, _b, _c;
- var _d;
- const writeDelegate = verbose ? info : core_debug;
- let hasMatch = false;
- const githubWorkspace = currentWorkspace
- ? currentWorkspace
- : ((_d = process.env['GITHUB_WORKSPACE']) !== null && _d !== void 0 ? _d : process.cwd());
- const result = external_crypto_namespaceObject.createHash('sha256');
- let count = 0;
- try {
- for (var _e = true, _f = internal_hash_files_asyncValues(globber.globGenerator()), _g; _g = yield _f.next(), _a = _g.done, !_a; _e = true) {
- _c = _g.value;
- _e = false;
- const file = _c;
- writeDelegate(file);
- if (!file.startsWith(`${githubWorkspace}${external_path_.sep}`)) {
- writeDelegate(`Ignore '${file}' since it is not under GITHUB_WORKSPACE.`);
- continue;
- }
- if (external_fs_namespaceObject.statSync(file).isDirectory()) {
- writeDelegate(`Skip directory '${file}'.`);
- continue;
- }
- const hash = external_crypto_namespaceObject.createHash('sha256');
- const pipeline = external_util_.promisify(external_stream_namespaceObject.pipeline);
- yield pipeline(external_fs_namespaceObject.createReadStream(file), hash);
- result.write(hash.digest());
- count++;
- if (!hasMatch) {
- hasMatch = true;
- }
- }
- }
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
- finally {
- try {
- if (!_e && !_a && (_b = _f.return)) yield _b.call(_f);
- }
- finally { if (e_1) throw e_1.error; }
- }
- result.end();
- if (hasMatch) {
- writeDelegate(`Found ${count} files to hash.`);
- return result.digest('hex');
- }
- else {
- writeDelegate(`No matches found for glob`);
- return '';
- }
- });
-}
-//# sourceMappingURL=internal-hash-files.js.map
-;// CONCATENATED MODULE: ./node_modules/@actions/glob/lib/glob.js
-var glob_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-
-
-/**
- * Constructs a globber
- *
- * @param patterns Patterns separated by newlines
- * @param options Glob options
- */
-function create(patterns, options) {
- return glob_awaiter(this, void 0, void 0, function* () {
- return yield DefaultGlobber.create(patterns, options);
- });
-}
-/**
- * Computes the sha256 hash of a glob
- *
- * @param patterns Patterns separated by newlines
- * @param currentWorkspace Workspace used when matching files
- * @param options Glob options
- * @param verbose Enables verbose logging
- */
-function glob_hashFiles(patterns_1) {
- return glob_awaiter(this, arguments, void 0, function* (patterns, currentWorkspace = '', options, verbose = false) {
- let followSymbolicLinks = true;
- if (options && typeof options.followSymbolicLinks === 'boolean') {
- followSymbolicLinks = options.followSymbolicLinks;
- }
- const globber = yield create(patterns, { followSymbolicLinks });
- return hashFiles(globber, currentWorkspace, verbose);
- });
-}
-//# sourceMappingURL=glob.js.map
-// EXTERNAL MODULE: ./node_modules/semver/index.js
-var node_modules_semver = __nccwpck_require__(2088);
-;// CONCATENATED MODULE: ./node_modules/@actions/cache/lib/internal/constants.js
-var CacheFilename;
-(function (CacheFilename) {
- CacheFilename["Gzip"] = "cache.tgz";
- CacheFilename["Zstd"] = "cache.tzst";
-})(CacheFilename || (CacheFilename = {}));
-var CompressionMethod;
-(function (CompressionMethod) {
- CompressionMethod["Gzip"] = "gzip";
- // Long range mode was added to zstd in v1.3.2.
- // This enum is for earlier version of zstd that does not have --long support
- CompressionMethod["ZstdWithoutLong"] = "zstd-without-long";
- CompressionMethod["Zstd"] = "zstd";
-})(CompressionMethod || (CompressionMethod = {}));
-var ArchiveToolType;
-(function (ArchiveToolType) {
- ArchiveToolType["GNU"] = "gnu";
- ArchiveToolType["BSD"] = "bsd";
-})(ArchiveToolType || (ArchiveToolType = {}));
-// The default number of retry attempts.
-const DefaultRetryAttempts = 2;
-// The default delay in milliseconds between retry attempts.
-const DefaultRetryDelay = 5000;
-// Socket timeout in milliseconds during download. If no traffic is received
-// over the socket during this period, the socket is destroyed and the download
-// is aborted.
-const SocketTimeout = 5000;
-// The default path of GNUtar on hosted Windows runners
-const GnuTarPathOnWindows = `${process.env['PROGRAMFILES']}\\Git\\usr\\bin\\tar.exe`;
-// The default path of BSDtar on hosted Windows runners
-const SystemTarPathOnWindows = `${process.env['SYSTEMDRIVE']}\\Windows\\System32\\tar.exe`;
-const TarFilename = 'cache.tar';
-const constants_ManifestFilename = 'manifest.txt';
-const CacheFileSizeLimit = 10 * Math.pow(1024, 3); // 10GiB per repository
-//# sourceMappingURL=constants.js.map
-;// CONCATENATED MODULE: ./node_modules/@actions/cache/lib/internal/cacheUtils.js
-var cacheUtils_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-var cacheUtils_asyncValues = (undefined && undefined.__asyncValues) || function (o) {
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
- var m = o[Symbol.asyncIterator], i;
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
- function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
- function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
-};
-
-
-
-
-
-
-
-
-
-
-const versionSalt = '1.0';
-// From https://github.com/actions/toolkit/blob/main/packages/tool-cache/src/tool-cache.ts#L23
-function createTempDirectory() {
- return cacheUtils_awaiter(this, void 0, void 0, function* () {
- const IS_WINDOWS = process.platform === 'win32';
- let tempDirectory = process.env['RUNNER_TEMP'] || '';
- if (!tempDirectory) {
- let baseLocation;
- if (IS_WINDOWS) {
- // On Windows use the USERPROFILE env variable
- baseLocation = process.env['USERPROFILE'] || 'C:\\';
- }
- else {
- if (process.platform === 'darwin') {
- baseLocation = '/Users';
- }
- else {
- baseLocation = '/home';
- }
- }
- tempDirectory = external_path_.join(baseLocation, 'actions', 'temp');
- }
- const dest = external_path_.join(tempDirectory, external_crypto_namespaceObject.randomUUID());
- yield mkdirP(dest);
- return dest;
- });
-}
-function getArchiveFileSizeInBytes(filePath) {
- return external_fs_namespaceObject.statSync(filePath).size;
-}
-function resolvePaths(patterns) {
- return cacheUtils_awaiter(this, void 0, void 0, function* () {
- var _a, e_1, _b, _c;
- var _d;
- const paths = [];
- const workspace = (_d = process.env['GITHUB_WORKSPACE']) !== null && _d !== void 0 ? _d : process.cwd();
- const globber = yield glob.create(patterns.join('\n'), {
- implicitDescendants: false
- });
- try {
- for (var _e = true, _f = cacheUtils_asyncValues(globber.globGenerator()), _g; _g = yield _f.next(), _a = _g.done, !_a; _e = true) {
- _c = _g.value;
- _e = false;
- const file = _c;
- const relativeFile = path
- .relative(workspace, file)
- .replace(new RegExp(`\\${path.sep}`, 'g'), '/');
- core.debug(`Matched: ${relativeFile}`);
- // Paths are made relative so the tar entries are all relative to the root of the workspace.
- if (relativeFile === '') {
- // path.relative returns empty string if workspace and file are equal
- paths.push('.');
- }
- else {
- paths.push(`${relativeFile}`);
- }
- }
- }
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
- finally {
- try {
- if (!_e && !_a && (_b = _f.return)) yield _b.call(_f);
- }
- finally { if (e_1) throw e_1.error; }
- }
- return paths;
- });
-}
-function unlinkFile(filePath) {
- return cacheUtils_awaiter(this, void 0, void 0, function* () {
- return external_util_.promisify(external_fs_namespaceObject.unlink)(filePath);
- });
-}
-function getVersion(app_1) {
- return cacheUtils_awaiter(this, arguments, void 0, function* (app, additionalArgs = []) {
- let versionOutput = '';
- additionalArgs.push('--version');
- core_debug(`Checking ${app} ${additionalArgs.join(' ')}`);
- try {
- yield exec_exec(`${app}`, additionalArgs, {
- ignoreReturnCode: true,
- silent: true,
- listeners: {
- stdout: (data) => (versionOutput += data.toString()),
- stderr: (data) => (versionOutput += data.toString())
- }
- });
- }
- catch (err) {
- core_debug(err.message);
- }
- versionOutput = versionOutput.trim();
- core_debug(versionOutput);
- return versionOutput;
- });
-}
-// Use zstandard if possible to maximize cache performance
-function getCompressionMethod() {
- return cacheUtils_awaiter(this, void 0, void 0, function* () {
- const versionOutput = yield getVersion('zstd', ['--quiet']);
- const version = node_modules_semver.clean(versionOutput);
- core_debug(`zstd version: ${version}`);
- if (versionOutput === '') {
- return CompressionMethod.Gzip;
- }
- else {
- return CompressionMethod.ZstdWithoutLong;
- }
- });
-}
-function getCacheFileName(compressionMethod) {
- return compressionMethod === CompressionMethod.Gzip
- ? CacheFilename.Gzip
- : CacheFilename.Zstd;
-}
-function getGnuTarPathOnWindows() {
- return cacheUtils_awaiter(this, void 0, void 0, function* () {
- if (external_fs_namespaceObject.existsSync(GnuTarPathOnWindows)) {
- return GnuTarPathOnWindows;
- }
- const versionOutput = yield getVersion('tar');
- return versionOutput.toLowerCase().includes('gnu tar') ? which('tar') : '';
- });
-}
-function assertDefined(name, value) {
- if (value === undefined) {
- throw Error(`Expected ${name} but value was undefiend`);
- }
- return value;
-}
-function getCacheVersion(paths, compressionMethod, enableCrossOsArchive = false) {
- // don't pass changes upstream
- const components = paths.slice();
- // Add compression method to cache version to restore
- // compressed cache as per compression method
- if (compressionMethod) {
- components.push(compressionMethod);
- }
- // Only check for windows platforms if enableCrossOsArchive is false
- if (process.platform === 'win32' && !enableCrossOsArchive) {
- components.push('windows-only');
- }
- // Add salt to cache version to support breaking changes in cache entry
- components.push(versionSalt);
- return external_crypto_namespaceObject.createHash('sha256').update(components.join('|')).digest('hex');
-}
-function getRuntimeToken() {
- const token = process.env['ACTIONS_RUNTIME_TOKEN'];
- if (!token) {
- throw new Error('Unable to get the ACTIONS_RUNTIME_TOKEN env variable');
- }
- return token;
-}
-//# sourceMappingURL=cacheUtils.js.map
-// EXTERNAL MODULE: external "url"
-var external_url_ = __nccwpck_require__(7016);
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/abort-controller/AbortError.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-/**
- * This error is thrown when an asynchronous operation has been aborted.
- * Check for this error by testing the `name` that the name property of the
- * error matches `"AbortError"`.
- *
- * @example
- * ```ts snippet:ReadmeSampleAbortError
- * import { AbortError } from "@typespec/ts-http-runtime";
- *
- * async function doAsyncWork(options: { abortSignal: AbortSignal }): Promise {
- * if (options.abortSignal.aborted) {
- * throw new AbortError();
- * }
- *
- * // do async work
- * }
- *
- * const controller = new AbortController();
- * controller.abort();
- *
- * try {
- * doAsyncWork({ abortSignal: controller.signal });
- * } catch (e) {
- * if (e instanceof Error && e.name === "AbortError") {
- * // handle abort error here.
- * }
- * }
- * ```
- */
-class AbortError extends Error {
- constructor(message) {
- super(message);
- this.name = "AbortError";
- }
-}
-//# sourceMappingURL=AbortError.js.map
-// EXTERNAL MODULE: external "node:os"
-var external_node_os_ = __nccwpck_require__(8161);
-// EXTERNAL MODULE: external "node:util"
-var external_node_util_ = __nccwpck_require__(7975);
-// EXTERNAL MODULE: external "node:process"
-var external_node_process_ = __nccwpck_require__(1708);
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/logger/log.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-
-function log(message, ...args) {
- external_node_process_.stderr.write(`${external_node_util_.format(message, ...args)}${external_node_os_.EOL}`);
-}
-//# sourceMappingURL=log.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/logger/debug.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-const debugEnvVariable = (typeof process !== "undefined" && process.env && process.env.DEBUG) || undefined;
-let enabledString;
-let enabledNamespaces = [];
-let skippedNamespaces = [];
-const debuggers = [];
-if (debugEnvVariable) {
- enable(debugEnvVariable);
-}
-const debugObj = Object.assign((namespace) => {
- return createDebugger(namespace);
-}, {
- enable,
- enabled,
- disable,
- log: log,
-});
-function enable(namespaces) {
- enabledString = namespaces;
- enabledNamespaces = [];
- skippedNamespaces = [];
- const namespaceList = namespaces.split(",").map((ns) => ns.trim());
- for (const ns of namespaceList) {
- if (ns.startsWith("-")) {
- skippedNamespaces.push(ns.substring(1));
- }
- else {
- enabledNamespaces.push(ns);
- }
- }
- for (const instance of debuggers) {
- instance.enabled = enabled(instance.namespace);
- }
-}
-function enabled(namespace) {
- if (namespace.endsWith("*")) {
- return true;
- }
- for (const skipped of skippedNamespaces) {
- if (namespaceMatches(namespace, skipped)) {
- return false;
- }
- }
- for (const enabledNamespace of enabledNamespaces) {
- if (namespaceMatches(namespace, enabledNamespace)) {
- return true;
- }
- }
- return false;
-}
-/**
- * Given a namespace, check if it matches a pattern.
- * Patterns only have a single wildcard character which is *.
- * The behavior of * is that it matches zero or more other characters.
- */
-function namespaceMatches(namespace, patternToMatch) {
- // simple case, no pattern matching required
- if (patternToMatch.indexOf("*") === -1) {
- return namespace === patternToMatch;
- }
- let pattern = patternToMatch;
- // normalize successive * if needed
- if (patternToMatch.indexOf("**") !== -1) {
- const patternParts = [];
- let lastCharacter = "";
- for (const character of patternToMatch) {
- if (character === "*" && lastCharacter === "*") {
- continue;
- }
- else {
- lastCharacter = character;
- patternParts.push(character);
- }
- }
- pattern = patternParts.join("");
- }
- let namespaceIndex = 0;
- let patternIndex = 0;
- const patternLength = pattern.length;
- const namespaceLength = namespace.length;
- let lastWildcard = -1;
- let lastWildcardNamespace = -1;
- while (namespaceIndex < namespaceLength && patternIndex < patternLength) {
- if (pattern[patternIndex] === "*") {
- lastWildcard = patternIndex;
- patternIndex++;
- if (patternIndex === patternLength) {
- // if wildcard is the last character, it will match the remaining namespace string
- return true;
- }
- // now we let the wildcard eat characters until we match the next literal in the pattern
- while (namespace[namespaceIndex] !== pattern[patternIndex]) {
- namespaceIndex++;
- // reached the end of the namespace without a match
- if (namespaceIndex === namespaceLength) {
- return false;
- }
- }
- // now that we have a match, let's try to continue on
- // however, it's possible we could find a later match
- // so keep a reference in case we have to backtrack
- lastWildcardNamespace = namespaceIndex;
- namespaceIndex++;
- patternIndex++;
- continue;
- }
- else if (pattern[patternIndex] === namespace[namespaceIndex]) {
- // simple case: literal pattern matches so keep going
- patternIndex++;
- namespaceIndex++;
- }
- else if (lastWildcard >= 0) {
- // special case: we don't have a literal match, but there is a previous wildcard
- // which we can backtrack to and try having the wildcard eat the match instead
- patternIndex = lastWildcard + 1;
- namespaceIndex = lastWildcardNamespace + 1;
- // we've reached the end of the namespace without a match
- if (namespaceIndex === namespaceLength) {
- return false;
- }
- // similar to the previous logic, let's keep going until we find the next literal match
- while (namespace[namespaceIndex] !== pattern[patternIndex]) {
- namespaceIndex++;
- if (namespaceIndex === namespaceLength) {
- return false;
- }
- }
- lastWildcardNamespace = namespaceIndex;
- namespaceIndex++;
- patternIndex++;
- continue;
- }
- else {
- return false;
- }
- }
- const namespaceDone = namespaceIndex === namespace.length;
- const patternDone = patternIndex === pattern.length;
- // this is to detect the case of an unneeded final wildcard
- // e.g. the pattern `ab*` should match the string `ab`
- const trailingWildCard = patternIndex === pattern.length - 1 && pattern[patternIndex] === "*";
- return namespaceDone && (patternDone || trailingWildCard);
-}
-function disable() {
- const result = enabledString || "";
- enable("");
- return result;
-}
-function createDebugger(namespace) {
- const newDebugger = Object.assign(debug, {
- enabled: enabled(namespace),
- destroy,
- log: debugObj.log,
- namespace,
- extend,
- });
- function debug(...args) {
- if (!newDebugger.enabled) {
- return;
- }
- if (args.length > 0) {
- args[0] = `${namespace} ${args[0]}`;
- }
- newDebugger.log(...args);
- }
- debuggers.push(newDebugger);
- return newDebugger;
-}
-function destroy() {
- const index = debuggers.indexOf(this);
- if (index >= 0) {
- debuggers.splice(index, 1);
- return true;
- }
- return false;
-}
-function extend(namespace) {
- const newDebugger = createDebugger(`${this.namespace}:${namespace}`);
- newDebugger.log = this.log;
- return newDebugger;
-}
-/* harmony default export */ const logger_debug = (debugObj);
-//# sourceMappingURL=debug.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/logger/logger.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-const TYPESPEC_RUNTIME_LOG_LEVELS = ["verbose", "info", "warning", "error"];
-const levelMap = {
- verbose: 400,
- info: 300,
- warning: 200,
- error: 100,
-};
-function patchLogMethod(parent, child) {
- child.log = (...args) => {
- parent.log(...args);
- };
-}
-function isTypeSpecRuntimeLogLevel(level) {
- return TYPESPEC_RUNTIME_LOG_LEVELS.includes(level);
-}
-/**
- * Creates a logger context base on the provided options.
- * @param options - The options for creating a logger context.
- * @returns The logger context.
- */
-function createLoggerContext(options) {
- const registeredLoggers = new Set();
- const logLevelFromEnv = (typeof process !== "undefined" && process.env && process.env[options.logLevelEnvVarName]) ||
- undefined;
- let logLevel;
- const clientLogger = logger_debug(options.namespace);
- clientLogger.log = (...args) => {
- logger_debug.log(...args);
- };
- function contextSetLogLevel(level) {
- if (level && !isTypeSpecRuntimeLogLevel(level)) {
- throw new Error(`Unknown log level '${level}'. Acceptable values: ${TYPESPEC_RUNTIME_LOG_LEVELS.join(",")}`);
- }
- logLevel = level;
- const enabledNamespaces = [];
- for (const logger of registeredLoggers) {
- if (shouldEnable(logger)) {
- enabledNamespaces.push(logger.namespace);
- }
- }
- logger_debug.enable(enabledNamespaces.join(","));
- }
- if (logLevelFromEnv) {
- // avoid calling setLogLevel because we don't want a mis-set environment variable to crash
- if (isTypeSpecRuntimeLogLevel(logLevelFromEnv)) {
- contextSetLogLevel(logLevelFromEnv);
- }
- else {
- console.error(`${options.logLevelEnvVarName} set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${TYPESPEC_RUNTIME_LOG_LEVELS.join(", ")}.`);
- }
- }
- function shouldEnable(logger) {
- return Boolean(logLevel && levelMap[logger.level] <= levelMap[logLevel]);
- }
- function createLogger(parent, level) {
- const logger = Object.assign(parent.extend(level), {
- level,
- });
- patchLogMethod(parent, logger);
- if (shouldEnable(logger)) {
- const enabledNamespaces = logger_debug.disable();
- logger_debug.enable(enabledNamespaces + "," + logger.namespace);
- }
- registeredLoggers.add(logger);
- return logger;
- }
- function contextGetLogLevel() {
- return logLevel;
- }
- function contextCreateClientLogger(namespace) {
- const clientRootLogger = clientLogger.extend(namespace);
- patchLogMethod(clientLogger, clientRootLogger);
- return {
- error: createLogger(clientRootLogger, "error"),
- warning: createLogger(clientRootLogger, "warning"),
- info: createLogger(clientRootLogger, "info"),
- verbose: createLogger(clientRootLogger, "verbose"),
- };
- }
- return {
- setLogLevel: contextSetLogLevel,
- getLogLevel: contextGetLogLevel,
- createClientLogger: contextCreateClientLogger,
- logger: clientLogger,
- };
-}
-const context = createLoggerContext({
- logLevelEnvVarName: "TYPESPEC_RUNTIME_LOG_LEVEL",
- namespace: "typeSpecRuntime",
-});
-/**
- * Immediately enables logging at the specified log level. If no level is specified, logging is disabled.
- * @param level - The log level to enable for logging.
- * Options from most verbose to least verbose are:
- * - verbose
- * - info
- * - warning
- * - error
- */
-// eslint-disable-next-line @typescript-eslint/no-redeclare
-const TypeSpecRuntimeLogger = context.logger;
-/**
- * Retrieves the currently specified log level.
- */
-function setLogLevel(logLevel) {
- context.setLogLevel(logLevel);
-}
-/**
- * Retrieves the currently specified log level.
- */
-function getLogLevel() {
- return context.getLogLevel();
-}
-/**
- * Creates a logger for use by the SDKs that inherits from `TypeSpecRuntimeLogger`.
- * @param namespace - The name of the SDK package.
- * @hidden
- */
-function createClientLogger(namespace) {
- return context.createClientLogger(namespace);
-}
-//# sourceMappingURL=logger.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/httpHeaders.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-function normalizeName(name) {
- return name.toLowerCase();
-}
-function* headerIterator(map) {
- for (const entry of map.values()) {
- yield [entry.name, entry.value];
- }
-}
-class HttpHeadersImpl {
- _headersMap;
- constructor(rawHeaders) {
- this._headersMap = new Map();
- if (rawHeaders) {
- for (const headerName of Object.keys(rawHeaders)) {
- this.set(headerName, rawHeaders[headerName]);
- }
- }
- }
- /**
- * Set a header in this collection with the provided name and value. The name is
- * case-insensitive.
- * @param name - The name of the header to set. This value is case-insensitive.
- * @param value - The value of the header to set.
- */
- set(name, value) {
- this._headersMap.set(normalizeName(name), { name, value: String(value).trim() });
- }
- /**
- * Get the header value for the provided header name, or undefined if no header exists in this
- * collection with the provided name.
- * @param name - The name of the header. This value is case-insensitive.
- */
- get(name) {
- return this._headersMap.get(normalizeName(name))?.value;
- }
- /**
- * Get whether or not this header collection contains a header entry for the provided header name.
- * @param name - The name of the header to set. This value is case-insensitive.
- */
- has(name) {
- return this._headersMap.has(normalizeName(name));
- }
- /**
- * Remove the header with the provided headerName.
- * @param name - The name of the header to remove.
- */
- delete(name) {
- this._headersMap.delete(normalizeName(name));
- }
- /**
- * Get the JSON object representation of this HTTP header collection.
- */
- toJSON(options = {}) {
- const result = {};
- if (options.preserveCase) {
- for (const entry of this._headersMap.values()) {
- result[entry.name] = entry.value;
- }
- }
- else {
- for (const [normalizedName, entry] of this._headersMap) {
- result[normalizedName] = entry.value;
- }
- }
- return result;
- }
- /**
- * Get the string representation of this HTTP header collection.
- */
- toString() {
- return JSON.stringify(this.toJSON({ preserveCase: true }));
- }
- /**
- * Iterate over tuples of header [name, value] pairs.
- */
- [Symbol.iterator]() {
- return headerIterator(this._headersMap);
- }
-}
-/**
- * Creates an object that satisfies the `HttpHeaders` interface.
- * @param rawHeaders - A simple object representing initial headers
- */
-function httpHeaders_createHttpHeaders(rawHeaders) {
- return new HttpHeadersImpl(rawHeaders);
-}
-//# sourceMappingURL=httpHeaders.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/util/uuidUtils.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-/**
- * Generated Universally Unique Identifier
- *
- * @returns RFC4122 v4 UUID.
- */
-function randomUUID() {
- return crypto.randomUUID();
-}
-//# sourceMappingURL=uuidUtils.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/pipelineRequest.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-class PipelineRequestImpl {
- url;
- method;
- headers;
- timeout;
- withCredentials;
- body;
- multipartBody;
- formData;
- streamResponseStatusCodes;
- enableBrowserStreams;
- proxySettings;
- disableKeepAlive;
- abortSignal;
- requestId;
- allowInsecureConnection;
- onUploadProgress;
- onDownloadProgress;
- requestOverrides;
- authSchemes;
- constructor(options) {
- this.url = options.url;
- this.body = options.body;
- this.headers = options.headers ?? httpHeaders_createHttpHeaders();
- this.method = options.method ?? "GET";
- this.timeout = options.timeout ?? 0;
- this.multipartBody = options.multipartBody;
- this.formData = options.formData;
- this.disableKeepAlive = options.disableKeepAlive ?? false;
- this.proxySettings = options.proxySettings;
- this.streamResponseStatusCodes = options.streamResponseStatusCodes;
- this.withCredentials = options.withCredentials ?? false;
- this.abortSignal = options.abortSignal;
- this.onUploadProgress = options.onUploadProgress;
- this.onDownloadProgress = options.onDownloadProgress;
- this.requestId = options.requestId || randomUUID();
- this.allowInsecureConnection = options.allowInsecureConnection ?? false;
- this.enableBrowserStreams = options.enableBrowserStreams ?? false;
- this.requestOverrides = options.requestOverrides;
- this.authSchemes = options.authSchemes;
- }
-}
-/**
- * Creates a new pipeline request with the given options.
- * This method is to allow for the easy setting of default values and not required.
- * @param options - The options to create the request with.
- */
-function pipelineRequest_createPipelineRequest(options) {
- return new PipelineRequestImpl(options);
-}
-//# sourceMappingURL=pipelineRequest.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/pipeline.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-const ValidPhaseNames = new Set(["Deserialize", "Serialize", "Retry", "Sign"]);
-/**
- * A private implementation of Pipeline.
- * Do not export this class from the package.
- * @internal
- */
-class HttpPipeline {
- _policies = [];
- _orderedPolicies;
- constructor(policies) {
- this._policies = policies?.slice(0) ?? [];
- this._orderedPolicies = undefined;
- }
- addPolicy(policy, options = {}) {
- if (options.phase && options.afterPhase) {
- throw new Error("Policies inside a phase cannot specify afterPhase.");
- }
- if (options.phase && !ValidPhaseNames.has(options.phase)) {
- throw new Error(`Invalid phase name: ${options.phase}`);
- }
- if (options.afterPhase && !ValidPhaseNames.has(options.afterPhase)) {
- throw new Error(`Invalid afterPhase name: ${options.afterPhase}`);
- }
- this._policies.push({
- policy,
- options,
- });
- this._orderedPolicies = undefined;
- }
- removePolicy(options) {
- const removedPolicies = [];
- this._policies = this._policies.filter((policyDescriptor) => {
- if ((options.name && policyDescriptor.policy.name === options.name) ||
- (options.phase && policyDescriptor.options.phase === options.phase)) {
- removedPolicies.push(policyDescriptor.policy);
- return false;
- }
- else {
- return true;
- }
- });
- this._orderedPolicies = undefined;
- return removedPolicies;
- }
- sendRequest(httpClient, request) {
- const policies = this.getOrderedPolicies();
- const pipeline = policies.reduceRight((next, policy) => {
- return (req) => {
- return policy.sendRequest(req, next);
- };
- }, (req) => httpClient.sendRequest(req));
- return pipeline(request);
- }
- getOrderedPolicies() {
- if (!this._orderedPolicies) {
- this._orderedPolicies = this.orderPolicies();
- }
- return this._orderedPolicies;
- }
- clone() {
- return new HttpPipeline(this._policies);
- }
- static create() {
- return new HttpPipeline();
- }
- orderPolicies() {
- /**
- * The goal of this method is to reliably order pipeline policies
- * based on their declared requirements when they were added.
- *
- * Order is first determined by phase:
- *
- * 1. Serialize Phase
- * 2. Policies not in a phase
- * 3. Deserialize Phase
- * 4. Retry Phase
- * 5. Sign Phase
- *
- * Within each phase, policies are executed in the order
- * they were added unless they were specified to execute
- * before/after other policies or after a particular phase.
- *
- * To determine the final order, we will walk the policy list
- * in phase order multiple times until all dependencies are
- * satisfied.
- *
- * `afterPolicies` are the set of policies that must be
- * executed before a given policy. This requirement is
- * considered satisfied when each of the listed policies
- * have been scheduled.
- *
- * `beforePolicies` are the set of policies that must be
- * executed after a given policy. Since this dependency
- * can be expressed by converting it into a equivalent
- * `afterPolicies` declarations, they are normalized
- * into that form for simplicity.
- *
- * An `afterPhase` dependency is considered satisfied when all
- * policies in that phase have scheduled.
- *
- */
- const result = [];
- // Track all policies we know about.
- const policyMap = new Map();
- function createPhase(name) {
- return {
- name,
- policies: new Set(),
- hasRun: false,
- hasAfterPolicies: false,
- };
- }
- // Track policies for each phase.
- const serializePhase = createPhase("Serialize");
- const noPhase = createPhase("None");
- const deserializePhase = createPhase("Deserialize");
- const retryPhase = createPhase("Retry");
- const signPhase = createPhase("Sign");
- // a list of phases in order
- const orderedPhases = [serializePhase, noPhase, deserializePhase, retryPhase, signPhase];
- // Small helper function to map phase name to each Phase
- function getPhase(phase) {
- if (phase === "Retry") {
- return retryPhase;
- }
- else if (phase === "Serialize") {
- return serializePhase;
- }
- else if (phase === "Deserialize") {
- return deserializePhase;
- }
- else if (phase === "Sign") {
- return signPhase;
- }
- else {
- return noPhase;
- }
- }
- // First walk each policy and create a node to track metadata.
- for (const descriptor of this._policies) {
- const policy = descriptor.policy;
- const options = descriptor.options;
- const policyName = policy.name;
- if (policyMap.has(policyName)) {
- throw new Error("Duplicate policy names not allowed in pipeline");
- }
- const node = {
- policy,
- dependsOn: new Set(),
- dependants: new Set(),
- };
- if (options.afterPhase) {
- node.afterPhase = getPhase(options.afterPhase);
- node.afterPhase.hasAfterPolicies = true;
- }
- policyMap.set(policyName, node);
- const phase = getPhase(options.phase);
- phase.policies.add(node);
- }
- // Now that each policy has a node, connect dependency references.
- for (const descriptor of this._policies) {
- const { policy, options } = descriptor;
- const policyName = policy.name;
- const node = policyMap.get(policyName);
- if (!node) {
- throw new Error(`Missing node for policy ${policyName}`);
- }
- if (options.afterPolicies) {
- for (const afterPolicyName of options.afterPolicies) {
- const afterNode = policyMap.get(afterPolicyName);
- if (afterNode) {
- // Linking in both directions helps later
- // when we want to notify dependants.
- node.dependsOn.add(afterNode);
- afterNode.dependants.add(node);
- }
- }
- }
- if (options.beforePolicies) {
- for (const beforePolicyName of options.beforePolicies) {
- const beforeNode = policyMap.get(beforePolicyName);
- if (beforeNode) {
- // To execute before another node, make it
- // depend on the current node.
- beforeNode.dependsOn.add(node);
- node.dependants.add(beforeNode);
- }
- }
- }
- }
- function walkPhase(phase) {
- phase.hasRun = true;
- // Sets iterate in insertion order
- for (const node of phase.policies) {
- if (node.afterPhase && (!node.afterPhase.hasRun || node.afterPhase.policies.size)) {
- // If this node is waiting on a phase to complete,
- // we need to skip it for now.
- // Even if the phase is empty, we should wait for it
- // to be walked to avoid re-ordering policies.
- continue;
- }
- if (node.dependsOn.size === 0) {
- // If there's nothing else we're waiting for, we can
- // add this policy to the result list.
- result.push(node.policy);
- // Notify anything that depends on this policy that
- // the policy has been scheduled.
- for (const dependant of node.dependants) {
- dependant.dependsOn.delete(node);
- }
- policyMap.delete(node.policy.name);
- phase.policies.delete(node);
- }
- }
- }
- function walkPhases() {
- for (const phase of orderedPhases) {
- walkPhase(phase);
- // if the phase isn't complete
- if (phase.policies.size > 0 && phase !== noPhase) {
- if (!noPhase.hasRun) {
- // Try running noPhase to see if that unblocks this phase next tick.
- // This can happen if a phase that happens before noPhase
- // is waiting on a noPhase policy to complete.
- walkPhase(noPhase);
- }
- // Don't proceed to the next phase until this phase finishes.
- return;
- }
- if (phase.hasAfterPolicies) {
- // Run any policies unblocked by this phase
- walkPhase(noPhase);
- }
- }
- }
- // Iterate until we've put every node in the result list.
- let iteration = 0;
- while (policyMap.size > 0) {
- iteration++;
- const initialResultLength = result.length;
- // Keep walking each phase in order until we can order every node.
- walkPhases();
- // The result list *should* get at least one larger each time
- // after the first full pass.
- // Otherwise, we're going to loop forever.
- if (result.length <= initialResultLength && iteration > 1) {
- throw new Error("Cannot satisfy policy dependencies due to requirements cycle.");
- }
- }
- return result;
- }
-}
-/**
- * Creates a totally empty pipeline.
- * Useful for testing or creating a custom one.
- */
-function pipeline_createEmptyPipeline() {
- return HttpPipeline.create();
-}
-//# sourceMappingURL=pipeline.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/util/object.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-/**
- * Helper to determine when an input is a generic JS object.
- * @returns true when input is an object type that is not null, Array, RegExp, or Date.
- */
-function isObject(input) {
- return (typeof input === "object" &&
- input !== null &&
- !Array.isArray(input) &&
- !(input instanceof RegExp) &&
- !(input instanceof Date));
-}
-//# sourceMappingURL=object.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/util/error.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-/**
- * Typeguard for an error object shape (has name and message)
- * @param e - Something caught by a catch clause.
- */
-function isError(e) {
- if (isObject(e)) {
- const hasName = typeof e.name === "string";
- const hasMessage = typeof e.message === "string";
- return hasName && hasMessage;
- }
- return false;
-}
-//# sourceMappingURL=error.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/util/inspect.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-const custom = external_node_util_.inspect.custom;
-//# sourceMappingURL=inspect.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/util/sanitizer.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-const RedactedString = "REDACTED";
-// Make sure this list is up-to-date with the one under core/logger/Readme#Keyconcepts
-const defaultAllowedHeaderNames = [
- "x-ms-client-request-id",
- "x-ms-return-client-request-id",
- "x-ms-useragent",
- "x-ms-correlation-request-id",
- "x-ms-request-id",
- "client-request-id",
- "ms-cv",
- "return-client-request-id",
- "traceparent",
- "Access-Control-Allow-Credentials",
- "Access-Control-Allow-Headers",
- "Access-Control-Allow-Methods",
- "Access-Control-Allow-Origin",
- "Access-Control-Expose-Headers",
- "Access-Control-Max-Age",
- "Access-Control-Request-Headers",
- "Access-Control-Request-Method",
- "Origin",
- "Accept",
- "Accept-Encoding",
- "Cache-Control",
- "Connection",
- "Content-Length",
- "Content-Type",
- "Date",
- "ETag",
- "Expires",
- "If-Match",
- "If-Modified-Since",
- "If-None-Match",
- "If-Unmodified-Since",
- "Last-Modified",
- "Pragma",
- "Request-Id",
- "Retry-After",
- "Server",
- "Transfer-Encoding",
- "User-Agent",
- "WWW-Authenticate",
-];
-const defaultAllowedQueryParameters = ["api-version"];
-/**
- * A utility class to sanitize objects for logging.
- */
-class Sanitizer {
- allowedHeaderNames;
- allowedQueryParameters;
- constructor({ additionalAllowedHeaderNames: allowedHeaderNames = [], additionalAllowedQueryParameters: allowedQueryParameters = [], } = {}) {
- allowedHeaderNames = defaultAllowedHeaderNames.concat(allowedHeaderNames);
- allowedQueryParameters = defaultAllowedQueryParameters.concat(allowedQueryParameters);
- this.allowedHeaderNames = new Set(allowedHeaderNames.map((n) => n.toLowerCase()));
- this.allowedQueryParameters = new Set(allowedQueryParameters.map((p) => p.toLowerCase()));
- }
- /**
- * Sanitizes an object for logging.
- * @param obj - The object to sanitize
- * @returns - The sanitized object as a string
- */
- sanitize(obj) {
- const seen = new Set();
- return JSON.stringify(obj, (key, value) => {
- // Ensure Errors include their interesting non-enumerable members
- if (value instanceof Error) {
- return {
- ...value,
- name: value.name,
- message: value.message,
- };
- }
- if (key === "headers") {
- return this.sanitizeHeaders(value);
- }
- else if (key === "url") {
- return this.sanitizeUrl(value);
- }
- else if (key === "query") {
- return this.sanitizeQuery(value);
- }
- else if (key === "body") {
- // Don't log the request body
- return undefined;
- }
- else if (key === "response") {
- // Don't log response again
- return undefined;
- }
- else if (key === "operationSpec") {
- // When using sendOperationRequest, the request carries a massive
- // field with the autorest spec. No need to log it.
- return undefined;
- }
- else if (Array.isArray(value) || isObject(value)) {
- if (seen.has(value)) {
- return "[Circular]";
- }
- seen.add(value);
- }
- return value;
- }, 2);
- }
- /**
- * Sanitizes a URL for logging.
- * @param value - The URL to sanitize
- * @returns - The sanitized URL as a string
- */
- sanitizeUrl(value) {
- if (typeof value !== "string" || value === null || value === "") {
- return value;
- }
- const url = new URL(value);
- if (!url.search) {
- return value;
- }
- for (const [key] of url.searchParams) {
- if (!this.allowedQueryParameters.has(key.toLowerCase())) {
- url.searchParams.set(key, RedactedString);
- }
- }
- return url.toString();
- }
- sanitizeHeaders(obj) {
- const sanitized = {};
- for (const key of Object.keys(obj)) {
- if (this.allowedHeaderNames.has(key.toLowerCase())) {
- sanitized[key] = obj[key];
- }
- else {
- sanitized[key] = RedactedString;
- }
- }
- return sanitized;
- }
- sanitizeQuery(value) {
- if (typeof value !== "object" || value === null) {
- return value;
- }
- const sanitized = {};
- for (const k of Object.keys(value)) {
- if (this.allowedQueryParameters.has(k.toLowerCase())) {
- sanitized[k] = value[k];
- }
- else {
- sanitized[k] = RedactedString;
- }
- }
- return sanitized;
- }
-}
-//# sourceMappingURL=sanitizer.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/restError.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-
-const errorSanitizer = new Sanitizer();
-/**
- * A custom error type for failed pipeline requests.
- */
-class restError_RestError extends Error {
- /**
- * Something went wrong when making the request.
- * This means the actual request failed for some reason,
- * such as a DNS issue or the connection being lost.
- */
- static REQUEST_SEND_ERROR = "REQUEST_SEND_ERROR";
- /**
- * This means that parsing the response from the server failed.
- * It may have been malformed.
- */
- static PARSE_ERROR = "PARSE_ERROR";
- /**
- * The code of the error itself (use statics on RestError if possible.)
- */
- code;
- /**
- * The HTTP status code of the request (if applicable.)
- */
- statusCode;
- /**
- * The request that was made.
- * This property is non-enumerable.
- */
- request;
- /**
- * The response received (if any.)
- * This property is non-enumerable.
- */
- response;
- /**
- * Bonus property set by the throw site.
- */
- details;
- constructor(message, options = {}) {
- super(message);
- this.name = "RestError";
- this.code = options.code;
- this.statusCode = options.statusCode;
- // The request and response may contain sensitive information in the headers or body.
- // To help prevent this sensitive information being accidentally logged, the request and response
- // properties are marked as non-enumerable here. This prevents them showing up in the output of
- // JSON.stringify and console.log.
- Object.defineProperty(this, "request", { value: options.request, enumerable: false });
- Object.defineProperty(this, "response", { value: options.response, enumerable: false });
- // Only include useful agent information in the request for logging, as the full agent object
- // may contain large binary data.
- const agent = this.request?.agent
- ? {
- maxFreeSockets: this.request.agent.maxFreeSockets,
- maxSockets: this.request.agent.maxSockets,
- }
- : undefined;
- // Logging method for util.inspect in Node
- Object.defineProperty(this, custom, {
- value: () => {
- // Extract non-enumerable properties and add them back. This is OK since in this output the request and
- // response get sanitized.
- return `RestError: ${this.message} \n ${errorSanitizer.sanitize({
- ...this,
- request: { ...this.request, agent },
- response: this.response,
- })}`;
- },
- enumerable: false,
- });
- Object.setPrototypeOf(this, restError_RestError.prototype);
- }
-}
-/**
- * Typeguard for RestError
- * @param e - Something caught by a catch clause.
- */
-function restError_isRestError(e) {
- if (e instanceof restError_RestError) {
- return true;
- }
- return isError(e) && e.name === "RestError";
-}
-//# sourceMappingURL=restError.js.map
-// EXTERNAL MODULE: external "node:http"
-var external_node_http_ = __nccwpck_require__(7067);
-;// CONCATENATED MODULE: external "node:https"
-const external_node_https_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:https");
-// EXTERNAL MODULE: external "node:zlib"
-var external_node_zlib_ = __nccwpck_require__(8522);
-// EXTERNAL MODULE: external "node:stream"
-var external_node_stream_ = __nccwpck_require__(7075);
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/log.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-const log_logger = createClientLogger("ts-http-runtime");
-//# sourceMappingURL=log.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/nodeHttpClient.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-
-
-
-
-
-
-
-const DEFAULT_TLS_SETTINGS = {};
-function nodeHttpClient_isReadableStream(body) {
- return body && typeof body.pipe === "function";
-}
-function isStreamComplete(stream) {
- if (stream.readable === false) {
- return Promise.resolve();
- }
- return new Promise((resolve) => {
- const handler = () => {
- resolve();
- stream.removeListener("close", handler);
- stream.removeListener("end", handler);
- stream.removeListener("error", handler);
- };
- stream.on("close", handler);
- stream.on("end", handler);
- stream.on("error", handler);
- });
-}
-function isArrayBuffer(body) {
- return body && typeof body.byteLength === "number";
-}
-class ReportTransform extends external_node_stream_.Transform {
- loadedBytes = 0;
- progressCallback;
- // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
- _transform(chunk, _encoding, callback) {
- this.push(chunk);
- this.loadedBytes += chunk.length;
- try {
- this.progressCallback({ loadedBytes: this.loadedBytes });
- callback();
- }
- catch (e) {
- callback(e);
- }
- }
- constructor(progressCallback) {
- super();
- this.progressCallback = progressCallback;
- }
-}
-/**
- * A HttpClient implementation that uses Node's "https" module to send HTTPS requests.
- * @internal
- */
-class NodeHttpClient {
- cachedHttpAgent;
- cachedHttpsAgents = new WeakMap();
- /**
- * Makes a request over an underlying transport layer and returns the response.
- * @param request - The request to be made.
- */
- async sendRequest(request) {
- const abortController = new AbortController();
- let abortListener;
- if (request.abortSignal) {
- if (request.abortSignal.aborted) {
- throw new AbortError("The operation was aborted. Request has already been canceled.");
- }
- abortListener = (event) => {
- if (event.type === "abort") {
- abortController.abort();
- }
- };
- request.abortSignal.addEventListener("abort", abortListener);
- }
- let timeoutId;
- if (request.timeout > 0) {
- timeoutId = setTimeout(() => {
- const sanitizer = new Sanitizer();
- log_logger.info(`request to '${sanitizer.sanitizeUrl(request.url)}' timed out. canceling...`);
- abortController.abort();
- }, request.timeout);
- }
- const acceptEncoding = request.headers.get("Accept-Encoding");
- const shouldDecompress = acceptEncoding?.includes("gzip") || acceptEncoding?.includes("deflate");
- let body = typeof request.body === "function" ? request.body() : request.body;
- if (body && !request.headers.has("Content-Length")) {
- const bodyLength = getBodyLength(body);
- if (bodyLength !== null) {
- request.headers.set("Content-Length", bodyLength);
- }
- }
- let responseStream;
- try {
- if (body && request.onUploadProgress) {
- const onUploadProgress = request.onUploadProgress;
- const uploadReportStream = new ReportTransform(onUploadProgress);
- uploadReportStream.on("error", (e) => {
- log_logger.error("Error in upload progress", e);
- });
- if (nodeHttpClient_isReadableStream(body)) {
- body.pipe(uploadReportStream);
- }
- else {
- uploadReportStream.end(body);
- }
- body = uploadReportStream;
- }
- const res = await this.makeRequest(request, abortController, body);
- if (timeoutId !== undefined) {
- clearTimeout(timeoutId);
- }
- const headers = getResponseHeaders(res);
- const status = res.statusCode ?? 0;
- const response = {
- status,
- headers,
- request,
- };
- // Responses to HEAD must not have a body.
- // If they do return a body, that body must be ignored.
- if (request.method === "HEAD") {
- // call resume() and not destroy() to avoid closing the socket
- // and losing keep alive
- res.resume();
- return response;
- }
- responseStream = shouldDecompress ? getDecodedResponseStream(res, headers) : res;
- const onDownloadProgress = request.onDownloadProgress;
- if (onDownloadProgress) {
- const downloadReportStream = new ReportTransform(onDownloadProgress);
- downloadReportStream.on("error", (e) => {
- log_logger.error("Error in download progress", e);
- });
- responseStream.pipe(downloadReportStream);
- responseStream = downloadReportStream;
- }
- if (
- // Value of POSITIVE_INFINITY in streamResponseStatusCodes is considered as any status code
- request.streamResponseStatusCodes?.has(Number.POSITIVE_INFINITY) ||
- request.streamResponseStatusCodes?.has(response.status)) {
- response.readableStreamBody = responseStream;
- }
- else {
- response.bodyAsText = await streamToText(responseStream);
- }
- return response;
- }
- finally {
- // clean up event listener
- if (request.abortSignal && abortListener) {
- let uploadStreamDone = Promise.resolve();
- if (nodeHttpClient_isReadableStream(body)) {
- uploadStreamDone = isStreamComplete(body);
- }
- let downloadStreamDone = Promise.resolve();
- if (nodeHttpClient_isReadableStream(responseStream)) {
- downloadStreamDone = isStreamComplete(responseStream);
- }
- Promise.all([uploadStreamDone, downloadStreamDone])
- .then(() => {
- // eslint-disable-next-line promise/always-return
- if (abortListener) {
- request.abortSignal?.removeEventListener("abort", abortListener);
- }
- })
- .catch((e) => {
- log_logger.warning("Error when cleaning up abortListener on httpRequest", e);
- });
- }
- }
- }
- makeRequest(request, abortController, body) {
- const url = new URL(request.url);
- const isInsecure = url.protocol !== "https:";
- if (isInsecure && !request.allowInsecureConnection) {
- throw new Error(`Cannot connect to ${request.url} while allowInsecureConnection is false.`);
- }
- const agent = request.agent ?? this.getOrCreateAgent(request, isInsecure);
- const options = {
- agent,
- hostname: url.hostname,
- path: `${url.pathname}${url.search}`,
- port: url.port,
- method: request.method,
- headers: request.headers.toJSON({ preserveCase: true }),
- ...request.requestOverrides,
- };
- return new Promise((resolve, reject) => {
- const req = isInsecure ? external_node_http_.request(options, resolve) : external_node_https_namespaceObject.request(options, resolve);
- req.once("error", (err) => {
- reject(new restError_RestError(err.message, { code: err.code ?? restError_RestError.REQUEST_SEND_ERROR, request }));
- });
- abortController.signal.addEventListener("abort", () => {
- const abortError = new AbortError("The operation was aborted. Rejecting from abort signal callback while making request.");
- req.destroy(abortError);
- reject(abortError);
- });
- if (body && nodeHttpClient_isReadableStream(body)) {
- body.pipe(req);
- }
- else if (body) {
- if (typeof body === "string" || Buffer.isBuffer(body)) {
- req.end(body);
- }
- else if (isArrayBuffer(body)) {
- req.end(ArrayBuffer.isView(body) ? Buffer.from(body.buffer) : Buffer.from(body));
- }
- else {
- log_logger.error("Unrecognized body type", body);
- reject(new restError_RestError("Unrecognized body type"));
- }
- }
- else {
- // streams don't like "undefined" being passed as data
- req.end();
- }
- });
- }
- getOrCreateAgent(request, isInsecure) {
- const disableKeepAlive = request.disableKeepAlive;
- // Handle Insecure requests first
- if (isInsecure) {
- if (disableKeepAlive) {
- // keepAlive:false is the default so we don't need a custom Agent
- return external_node_http_.globalAgent;
- }
- if (!this.cachedHttpAgent) {
- // If there is no cached agent create a new one and cache it.
- this.cachedHttpAgent = new external_node_http_.Agent({ keepAlive: true });
- }
- return this.cachedHttpAgent;
- }
- else {
- if (disableKeepAlive && !request.tlsSettings) {
- // When there are no tlsSettings and keepAlive is false
- // we don't need a custom agent
- return external_node_https_namespaceObject.globalAgent;
- }
- // We use the tlsSettings to index cached clients
- const tlsSettings = request.tlsSettings ?? DEFAULT_TLS_SETTINGS;
- // Get the cached agent or create a new one with the
- // provided values for keepAlive and tlsSettings
- let agent = this.cachedHttpsAgents.get(tlsSettings);
- if (agent && agent.options.keepAlive === !disableKeepAlive) {
- return agent;
- }
- log_logger.info("No cached TLS Agent exist, creating a new Agent");
- agent = new external_node_https_namespaceObject.Agent({
- // keepAlive is true if disableKeepAlive is false.
- keepAlive: !disableKeepAlive,
- // Since we are spreading, if no tslSettings were provided, nothing is added to the agent options.
- ...tlsSettings,
- });
- this.cachedHttpsAgents.set(tlsSettings, agent);
- return agent;
- }
- }
-}
-function getResponseHeaders(res) {
- const headers = httpHeaders_createHttpHeaders();
- for (const header of Object.keys(res.headers)) {
- const value = res.headers[header];
- if (Array.isArray(value)) {
- if (value.length > 0) {
- headers.set(header, value[0]);
- }
- }
- else if (value) {
- headers.set(header, value);
- }
- }
- return headers;
-}
-function getDecodedResponseStream(stream, headers) {
- const contentEncoding = headers.get("Content-Encoding");
- if (contentEncoding === "gzip") {
- const unzip = external_node_zlib_.createGunzip();
- stream.pipe(unzip);
- return unzip;
- }
- else if (contentEncoding === "deflate") {
- const inflate = external_node_zlib_.createInflate();
- stream.pipe(inflate);
- return inflate;
- }
- return stream;
-}
-function streamToText(stream) {
- return new Promise((resolve, reject) => {
- const buffer = [];
- stream.on("data", (chunk) => {
- if (Buffer.isBuffer(chunk)) {
- buffer.push(chunk);
- }
- else {
- buffer.push(Buffer.from(chunk));
- }
- });
- stream.on("end", () => {
- resolve(Buffer.concat(buffer).toString("utf8"));
- });
- stream.on("error", (e) => {
- if (e && e?.name === "AbortError") {
- reject(e);
- }
- else {
- reject(new restError_RestError(`Error reading response as text: ${e.message}`, {
- code: restError_RestError.PARSE_ERROR,
- }));
- }
- });
- });
-}
-/** @internal */
-function getBodyLength(body) {
- if (!body) {
- return 0;
- }
- else if (Buffer.isBuffer(body)) {
- return body.length;
- }
- else if (nodeHttpClient_isReadableStream(body)) {
- return null;
- }
- else if (isArrayBuffer(body)) {
- return body.byteLength;
- }
- else if (typeof body === "string") {
- return Buffer.from(body).length;
- }
- else {
- return null;
- }
-}
-/**
- * Create a new HttpClient instance for the NodeJS environment.
- * @internal
- */
-function createNodeHttpClient() {
- return new NodeHttpClient();
-}
-//# sourceMappingURL=nodeHttpClient.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/defaultHttpClient.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-/**
- * Create the correct HttpClient for the current environment.
- */
-function defaultHttpClient_createDefaultHttpClient() {
- return createNodeHttpClient();
-}
-//# sourceMappingURL=defaultHttpClient.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/policies/logPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-/**
- * The programmatic identifier of the logPolicy.
- */
-const logPolicyName = "logPolicy";
-/**
- * A policy that logs all requests and responses.
- * @param options - Options to configure logPolicy.
- */
-function logPolicy_logPolicy(options = {}) {
- const logger = options.logger ?? log_logger.info;
- const sanitizer = new Sanitizer({
- additionalAllowedHeaderNames: options.additionalAllowedHeaderNames,
- additionalAllowedQueryParameters: options.additionalAllowedQueryParameters,
- });
- return {
- name: logPolicyName,
- async sendRequest(request, next) {
- if (!logger.enabled) {
- return next(request);
- }
- logger(`Request: ${sanitizer.sanitize(request)}`);
- const response = await next(request);
- logger(`Response status code: ${response.status}`);
- logger(`Headers: ${sanitizer.sanitize(response.headers)}`);
- return response;
- },
- };
-}
-//# sourceMappingURL=logPolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/util/userAgentPlatform.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-/**
- * @internal
- */
-function getHeaderName() {
- return "User-Agent";
-}
-/**
- * @internal
- */
-async function userAgentPlatform_setPlatformSpecificData(map) {
- if (process && process.versions) {
- const osInfo = `${os.type()} ${os.release()}; ${os.arch()}`;
- const versions = process.versions;
- if (versions.bun) {
- map.set("Bun", `${versions.bun} (${osInfo})`);
- }
- else if (versions.deno) {
- map.set("Deno", `${versions.deno} (${osInfo})`);
- }
- else if (versions.node) {
- map.set("Node", `${versions.node} (${osInfo})`);
- }
- }
-}
-//# sourceMappingURL=userAgentPlatform.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/util/userAgent.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-function getUserAgentString(telemetryInfo) {
- const parts = [];
- for (const [key, value] of telemetryInfo) {
- const token = value ? `${key}/${value}` : key;
- parts.push(token);
- }
- return parts.join(" ");
-}
-/**
- * @internal
- */
-function getUserAgentHeaderName() {
- return getHeaderName();
-}
-/**
- * @internal
- */
-async function userAgent_getUserAgentValue(prefix) {
- const runtimeInfo = new Map();
- runtimeInfo.set("ts-http-runtime", SDK_VERSION);
- await setPlatformSpecificData(runtimeInfo);
- const defaultAgent = getUserAgentString(runtimeInfo);
- const userAgentValue = prefix ? `${prefix} ${defaultAgent}` : defaultAgent;
- return userAgentValue;
-}
-//# sourceMappingURL=userAgent.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/policies/userAgentPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-const UserAgentHeaderName = getUserAgentHeaderName();
-/**
- * The programmatic identifier of the userAgentPolicy.
- */
-const userAgentPolicyName = "userAgentPolicy";
-/**
- * A policy that sets the User-Agent header (or equivalent) to reflect
- * the library version.
- * @param options - Options to customize the user agent value.
- */
-function userAgentPolicy_userAgentPolicy(options = {}) {
- const userAgentValue = getUserAgentValue(options.userAgentPrefix);
- return {
- name: userAgentPolicyName,
- async sendRequest(request, next) {
- if (!request.headers.has(UserAgentHeaderName)) {
- request.headers.set(UserAgentHeaderName, await userAgentValue);
- }
- return next(request);
- },
- };
-}
-//# sourceMappingURL=userAgentPolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/util/random.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-/**
- * Returns a random integer value between a lower and upper bound,
- * inclusive of both bounds.
- * Note that this uses Math.random and isn't secure. If you need to use
- * this for any kind of security purpose, find a better source of random.
- * @param min - The smallest integer value allowed.
- * @param max - The largest integer value allowed.
- */
-function random_getRandomIntegerInclusive(min, max) {
- // Make sure inputs are integers.
- min = Math.ceil(min);
- max = Math.floor(max);
- // Pick a random offset from zero to the size of the range.
- // Since Math.random() can never return 1, we have to make the range one larger
- // in order to be inclusive of the maximum value after we take the floor.
- const offset = Math.floor(Math.random() * (max - min + 1));
- return offset + min;
-}
-//# sourceMappingURL=random.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/util/delay.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-/**
- * Calculates the delay interval for retry attempts using exponential delay with jitter.
- * @param retryAttempt - The current retry attempt number.
- * @param config - The exponential retry configuration.
- * @returns An object containing the calculated retry delay.
- */
-function calculateRetryDelay(retryAttempt, config) {
- // Exponentially increase the delay each time
- const exponentialDelay = config.retryDelayInMs * Math.pow(2, retryAttempt);
- // Don't let the delay exceed the maximum
- const clampedDelay = Math.min(config.maxRetryDelayInMs, exponentialDelay);
- // Allow the final value to have some "jitter" (within 50% of the delay size) so
- // that retries across multiple clients don't occur simultaneously.
- const retryAfterInMs = clampedDelay / 2 + random_getRandomIntegerInclusive(0, clampedDelay / 2);
- return { retryAfterInMs };
-}
-//# sourceMappingURL=delay.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/util/helpers.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-const StandardAbortMessage = "The operation was aborted.";
-/**
- * A wrapper for setTimeout that resolves a promise after delayInMs milliseconds.
- * @param delayInMs - The number of milliseconds to be delayed.
- * @param value - The value to be resolved with after a timeout of t milliseconds.
- * @param options - The options for delay - currently abort options
- * - abortSignal - The abortSignal associated with containing operation.
- * - abortErrorMsg - The abort error message associated with containing operation.
- * @returns Resolved promise
- */
-function delay(delayInMs, value, options) {
- return new Promise((resolve, reject) => {
- let timer = undefined;
- let onAborted = undefined;
- const rejectOnAbort = () => {
- return reject(new AbortError(options?.abortErrorMsg ? options?.abortErrorMsg : StandardAbortMessage));
- };
- const removeListeners = () => {
- if (options?.abortSignal && onAborted) {
- options.abortSignal.removeEventListener("abort", onAborted);
- }
- };
- onAborted = () => {
- if (timer) {
- clearTimeout(timer);
- }
- removeListeners();
- return rejectOnAbort();
- };
- if (options?.abortSignal && options.abortSignal.aborted) {
- return rejectOnAbort();
- }
- timer = setTimeout(() => {
- removeListeners();
- resolve(value);
- }, delayInMs);
- if (options?.abortSignal) {
- options.abortSignal.addEventListener("abort", onAborted);
- }
- });
-}
-/**
- * @internal
- * @returns the parsed value or undefined if the parsed value is invalid.
- */
-function parseHeaderValueAsNumber(response, headerName) {
- const value = response.headers.get(headerName);
- if (!value)
- return;
- const valueAsNum = Number(value);
- if (Number.isNaN(valueAsNum))
- return;
- return valueAsNum;
-}
-//# sourceMappingURL=helpers.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/retryStrategies/throttlingRetryStrategy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-/**
- * The header that comes back from services representing
- * the amount of time (minimum) to wait to retry (in seconds or timestamp after which we can retry).
- */
-const RetryAfterHeader = "Retry-After";
-/**
- * The headers that come back from services representing
- * the amount of time (minimum) to wait to retry.
- *
- * "retry-after-ms", "x-ms-retry-after-ms" : milliseconds
- * "Retry-After" : seconds or timestamp
- */
-const AllRetryAfterHeaders = ["retry-after-ms", "x-ms-retry-after-ms", RetryAfterHeader];
-/**
- * A response is a throttling retry response if it has a throttling status code (429 or 503),
- * as long as one of the [ "Retry-After" or "retry-after-ms" or "x-ms-retry-after-ms" ] headers has a valid value.
- *
- * Returns the `retryAfterInMs` value if the response is a throttling retry response.
- * If not throttling retry response, returns `undefined`.
- *
- * @internal
- */
-function getRetryAfterInMs(response) {
- if (!(response && [429, 503].includes(response.status)))
- return undefined;
- try {
- // Headers: "retry-after-ms", "x-ms-retry-after-ms", "Retry-After"
- for (const header of AllRetryAfterHeaders) {
- const retryAfterValue = parseHeaderValueAsNumber(response, header);
- if (retryAfterValue === 0 || retryAfterValue) {
- // "Retry-After" header ==> seconds
- // "retry-after-ms", "x-ms-retry-after-ms" headers ==> milli-seconds
- const multiplyingFactor = header === RetryAfterHeader ? 1000 : 1;
- return retryAfterValue * multiplyingFactor; // in milli-seconds
- }
- }
- // RetryAfterHeader ("Retry-After") has a special case where it might be formatted as a date instead of a number of seconds
- const retryAfterHeader = response.headers.get(RetryAfterHeader);
- if (!retryAfterHeader)
- return;
- const date = Date.parse(retryAfterHeader);
- const diff = date - Date.now();
- // negative diff would mean a date in the past, so retry asap with 0 milliseconds
- return Number.isFinite(diff) ? Math.max(0, diff) : undefined;
- }
- catch {
- return undefined;
- }
-}
-/**
- * A response is a retry response if it has a throttling status code (429 or 503),
- * as long as one of the [ "Retry-After" or "retry-after-ms" or "x-ms-retry-after-ms" ] headers has a valid value.
- */
-function isThrottlingRetryResponse(response) {
- return Number.isFinite(getRetryAfterInMs(response));
-}
-function throttlingRetryStrategy_throttlingRetryStrategy() {
- return {
- name: "throttlingRetryStrategy",
- retry({ response }) {
- const retryAfterInMs = getRetryAfterInMs(response);
- if (!Number.isFinite(retryAfterInMs)) {
- return { skipStrategy: true };
- }
- return {
- retryAfterInMs,
- };
- },
- };
-}
-//# sourceMappingURL=throttlingRetryStrategy.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/retryStrategies/exponentialRetryStrategy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-// intervals are in milliseconds
-const DEFAULT_CLIENT_RETRY_INTERVAL = 1000;
-const DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 64;
-/**
- * A retry strategy that retries with an exponentially increasing delay in these two cases:
- * - When there are errors in the underlying transport layer (e.g. DNS lookup failures).
- * - Or otherwise if the outgoing request fails (408, greater or equal than 500, except for 501 and 505).
- */
-function exponentialRetryStrategy_exponentialRetryStrategy(options = {}) {
- const retryInterval = options.retryDelayInMs ?? DEFAULT_CLIENT_RETRY_INTERVAL;
- const maxRetryInterval = options.maxRetryDelayInMs ?? DEFAULT_CLIENT_MAX_RETRY_INTERVAL;
- return {
- name: "exponentialRetryStrategy",
- retry({ retryCount, response, responseError }) {
- const matchedSystemError = isSystemError(responseError);
- const ignoreSystemErrors = matchedSystemError && options.ignoreSystemErrors;
- const isExponential = isExponentialRetryResponse(response);
- const ignoreExponentialResponse = isExponential && options.ignoreHttpStatusCodes;
- const unknownResponse = response && (isThrottlingRetryResponse(response) || !isExponential);
- if (unknownResponse || ignoreExponentialResponse || ignoreSystemErrors) {
- return { skipStrategy: true };
- }
- if (responseError && !matchedSystemError && !isExponential) {
- return { errorToThrow: responseError };
- }
- return calculateRetryDelay(retryCount, {
- retryDelayInMs: retryInterval,
- maxRetryDelayInMs: maxRetryInterval,
- });
- },
- };
-}
-/**
- * A response is a retry response if it has status codes:
- * - 408, or
- * - Greater or equal than 500, except for 501 and 505.
- */
-function isExponentialRetryResponse(response) {
- return Boolean(response &&
- response.status !== undefined &&
- (response.status >= 500 || response.status === 408) &&
- response.status !== 501 &&
- response.status !== 505);
-}
-/**
- * Determines whether an error from a pipeline response was triggered in the network layer.
- */
-function isSystemError(err) {
- if (!err) {
- return false;
- }
- return (err.code === "ETIMEDOUT" ||
- err.code === "ESOCKETTIMEDOUT" ||
- err.code === "ECONNREFUSED" ||
- err.code === "ECONNRESET" ||
- err.code === "ENOENT" ||
- err.code === "ENOTFOUND");
-}
-//# sourceMappingURL=exponentialRetryStrategy.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/constants.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-const constants_SDK_VERSION = "0.3.2";
-const constants_DEFAULT_RETRY_POLICY_COUNT = 3;
-//# sourceMappingURL=constants.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/policies/retryPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-
-
-const retryPolicyLogger = createClientLogger("ts-http-runtime retryPolicy");
-/**
- * The programmatic identifier of the retryPolicy.
- */
-const retryPolicyName = "retryPolicy";
-/**
- * retryPolicy is a generic policy to enable retrying requests when certain conditions are met
- */
-function retryPolicy_retryPolicy(strategies, options = { maxRetries: constants_DEFAULT_RETRY_POLICY_COUNT }) {
- const logger = options.logger || retryPolicyLogger;
- return {
- name: retryPolicyName,
- async sendRequest(request, next) {
- let response;
- let responseError;
- let retryCount = -1;
- retryRequest: while (true) {
- retryCount += 1;
- response = undefined;
- responseError = undefined;
- try {
- logger.info(`Retry ${retryCount}: Attempting to send request`, request.requestId);
- response = await next(request);
- logger.info(`Retry ${retryCount}: Received a response from request`, request.requestId);
- }
- catch (e) {
- logger.error(`Retry ${retryCount}: Received an error from request`, request.requestId);
- // RestErrors are valid targets for the retry strategies.
- // If none of the retry strategies can work with them, they will be thrown later in this policy.
- // If the received error is not a RestError, it is immediately thrown.
- responseError = e;
- if (!e || responseError.name !== "RestError") {
- throw e;
- }
- response = responseError.response;
- }
- if (request.abortSignal?.aborted) {
- logger.error(`Retry ${retryCount}: Request aborted.`);
- const abortError = new AbortError();
- throw abortError;
- }
- if (retryCount >= (options.maxRetries ?? constants_DEFAULT_RETRY_POLICY_COUNT)) {
- logger.info(`Retry ${retryCount}: Maximum retries reached. Returning the last received response, or throwing the last received error.`);
- if (responseError) {
- throw responseError;
- }
- else if (response) {
- return response;
- }
- else {
- throw new Error("Maximum retries reached with no response or error to throw");
- }
- }
- logger.info(`Retry ${retryCount}: Processing ${strategies.length} retry strategies.`);
- strategiesLoop: for (const strategy of strategies) {
- const strategyLogger = strategy.logger || logger;
- strategyLogger.info(`Retry ${retryCount}: Processing retry strategy ${strategy.name}.`);
- const modifiers = strategy.retry({
- retryCount,
- response,
- responseError,
- });
- if (modifiers.skipStrategy) {
- strategyLogger.info(`Retry ${retryCount}: Skipped.`);
- continue strategiesLoop;
- }
- const { errorToThrow, retryAfterInMs, redirectTo } = modifiers;
- if (errorToThrow) {
- strategyLogger.error(`Retry ${retryCount}: Retry strategy ${strategy.name} throws error:`, errorToThrow);
- throw errorToThrow;
- }
- if (retryAfterInMs || retryAfterInMs === 0) {
- strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} retries after ${retryAfterInMs}`);
- await delay(retryAfterInMs, undefined, { abortSignal: request.abortSignal });
- continue retryRequest;
- }
- if (redirectTo) {
- strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} redirects to ${redirectTo}`);
- request.url = redirectTo;
- continue retryRequest;
- }
- }
- if (responseError) {
- logger.info(`None of the retry strategies could work with the received error. Throwing it.`);
- throw responseError;
- }
- if (response) {
- logger.info(`None of the retry strategies could work with the received response. Returning it.`);
- return response;
- }
- // If all the retries skip and there's no response,
- // we're still in the retry loop, so a new request will be sent
- // until `maxRetries` is reached.
- }
- },
- };
-}
-//# sourceMappingURL=retryPolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/policies/defaultRetryPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-
-
-/**
- * Name of the {@link defaultRetryPolicy}
- */
-const defaultRetryPolicyName = "defaultRetryPolicy";
-/**
- * A policy that retries according to three strategies:
- * - When the server sends a 429 response with a Retry-After header.
- * - When there are errors in the underlying transport layer (e.g. DNS lookup failures).
- * - Or otherwise if the outgoing request fails, it will retry with an exponentially increasing delay.
- */
-function defaultRetryPolicy_defaultRetryPolicy(options = {}) {
- return {
- name: defaultRetryPolicyName,
- sendRequest: retryPolicy_retryPolicy([throttlingRetryStrategy_throttlingRetryStrategy(), exponentialRetryStrategy_exponentialRetryStrategy(options)], {
- maxRetries: options.maxRetries ?? constants_DEFAULT_RETRY_POLICY_COUNT,
- }).sendRequest,
- };
-}
-//# sourceMappingURL=defaultRetryPolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/util/bytesEncoding.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-/**
- * The helper that transforms bytes with specific character encoding into string
- * @param bytes - the uint8array bytes
- * @param format - the format we use to encode the byte
- * @returns a string of the encoded string
- */
-function bytesEncoding_uint8ArrayToString(bytes, format) {
- return Buffer.from(bytes).toString(format);
-}
-/**
- * The helper that transforms string to specific character encoded bytes array.
- * @param value - the string to be converted
- * @param format - the format we use to decode the value
- * @returns a uint8array
- */
-function bytesEncoding_stringToUint8Array(value, format) {
- return Buffer.from(value, format);
-}
-//# sourceMappingURL=bytesEncoding.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/util/checkEnvironment.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-/**
- * A constant that indicates whether the environment the code is running is a Web Browser.
- */
-// eslint-disable-next-line @azure/azure-sdk/ts-no-window
-const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined";
-/**
- * A constant that indicates whether the environment the code is running is a Web Worker.
- */
-const isWebWorker = typeof self === "object" &&
- typeof self?.importScripts === "function" &&
- (self.constructor?.name === "DedicatedWorkerGlobalScope" ||
- self.constructor?.name === "ServiceWorkerGlobalScope" ||
- self.constructor?.name === "SharedWorkerGlobalScope");
-/**
- * A constant that indicates whether the environment the code is running is Deno.
- */
-const isDeno = typeof Deno !== "undefined" &&
- typeof Deno.version !== "undefined" &&
- typeof Deno.version.deno !== "undefined";
-/**
- * A constant that indicates whether the environment the code is running is Bun.sh.
- */
-const isBun = typeof Bun !== "undefined" && typeof Bun.version !== "undefined";
-/**
- * A constant that indicates whether the environment the code is running is a Node.js compatible environment.
- */
-const checkEnvironment_isNodeLike = typeof globalThis.process !== "undefined" &&
- Boolean(globalThis.process.version) &&
- Boolean(globalThis.process.versions?.node);
-/**
- * A constant that indicates whether the environment the code is running is Node.JS.
- */
-const isNodeRuntime = checkEnvironment_isNodeLike && !isBun && !isDeno;
-/**
- * A constant that indicates whether the environment the code is running is in React-Native.
- */
-// https://github.com/facebook/react-native/blob/main/packages/react-native/Libraries/Core/setUpNavigator.js
-const isReactNative = typeof navigator !== "undefined" && navigator?.product === "ReactNative";
-//# sourceMappingURL=checkEnvironment.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/policies/formDataPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-
-/**
- * The programmatic identifier of the formDataPolicy.
- */
-const formDataPolicyName = "formDataPolicy";
-function formDataToFormDataMap(formData) {
- const formDataMap = {};
- for (const [key, value] of formData.entries()) {
- formDataMap[key] ??= [];
- formDataMap[key].push(value);
- }
- return formDataMap;
-}
-/**
- * A policy that encodes FormData on the request into the body.
- */
-function formDataPolicy_formDataPolicy() {
- return {
- name: formDataPolicyName,
- async sendRequest(request, next) {
- if (checkEnvironment_isNodeLike && typeof FormData !== "undefined" && request.body instanceof FormData) {
- request.formData = formDataToFormDataMap(request.body);
- request.body = undefined;
- }
- if (request.formData) {
- const contentType = request.headers.get("Content-Type");
- if (contentType && contentType.indexOf("application/x-www-form-urlencoded") !== -1) {
- request.body = wwwFormUrlEncode(request.formData);
- }
- else {
- await prepareFormData(request.formData, request);
- }
- request.formData = undefined;
- }
- return next(request);
- },
- };
-}
-function wwwFormUrlEncode(formData) {
- const urlSearchParams = new URLSearchParams();
- for (const [key, value] of Object.entries(formData)) {
- if (Array.isArray(value)) {
- for (const subValue of value) {
- urlSearchParams.append(key, subValue.toString());
- }
- }
- else {
- urlSearchParams.append(key, value.toString());
- }
- }
- return urlSearchParams.toString();
-}
-async function prepareFormData(formData, request) {
- // validate content type (multipart/form-data)
- const contentType = request.headers.get("Content-Type");
- if (contentType && !contentType.startsWith("multipart/form-data")) {
- // content type is specified and is not multipart/form-data. Exit.
- return;
- }
- request.headers.set("Content-Type", contentType ?? "multipart/form-data");
- // set body to MultipartRequestBody using content from FormDataMap
- const parts = [];
- for (const [fieldName, values] of Object.entries(formData)) {
- for (const value of Array.isArray(values) ? values : [values]) {
- if (typeof value === "string") {
- parts.push({
- headers: httpHeaders_createHttpHeaders({
- "Content-Disposition": `form-data; name="${fieldName}"`,
- }),
- body: bytesEncoding_stringToUint8Array(value, "utf-8"),
- });
- }
- else if (value === undefined || value === null || typeof value !== "object") {
- throw new Error(`Unexpected value for key ${fieldName}: ${value}. Value should be serialized to string first.`);
- }
- else {
- // using || instead of ?? here since if value.name is empty we should create a file name
- const fileName = value.name || "blob";
- const headers = httpHeaders_createHttpHeaders();
- headers.set("Content-Disposition", `form-data; name="${fieldName}"; filename="${fileName}"`);
- // again, || is used since an empty value.type means the content type is unset
- headers.set("Content-Type", value.type || "application/octet-stream");
- parts.push({
- headers,
- body: value,
- });
- }
- }
- }
- request.multipartBody = { parts };
-}
-//# sourceMappingURL=formDataPolicy.js.map
-// EXTERNAL MODULE: ./node_modules/https-proxy-agent/dist/index.js
-var dist = __nccwpck_require__(3669);
-// EXTERNAL MODULE: ./node_modules/http-proxy-agent/dist/index.js
-var http_proxy_agent_dist = __nccwpck_require__(1970);
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/policies/proxyPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-
-const HTTPS_PROXY = "HTTPS_PROXY";
-const HTTP_PROXY = "HTTP_PROXY";
-const ALL_PROXY = "ALL_PROXY";
-const NO_PROXY = "NO_PROXY";
-/**
- * The programmatic identifier of the proxyPolicy.
- */
-const proxyPolicyName = "proxyPolicy";
-/**
- * Stores the patterns specified in NO_PROXY environment variable.
- * @internal
- */
-const globalNoProxyList = [];
-let noProxyListLoaded = false;
-/** A cache of whether a host should bypass the proxy. */
-const globalBypassedMap = new Map();
-function getEnvironmentValue(name) {
- if (process.env[name]) {
- return process.env[name];
- }
- else if (process.env[name.toLowerCase()]) {
- return process.env[name.toLowerCase()];
- }
- return undefined;
-}
-function loadEnvironmentProxyValue() {
- if (!process) {
- return undefined;
- }
- const httpsProxy = getEnvironmentValue(HTTPS_PROXY);
- const allProxy = getEnvironmentValue(ALL_PROXY);
- const httpProxy = getEnvironmentValue(HTTP_PROXY);
- return httpsProxy || allProxy || httpProxy;
-}
-/**
- * Check whether the host of a given `uri` matches any pattern in the no proxy list.
- * If there's a match, any request sent to the same host shouldn't have the proxy settings set.
- * This implementation is a port of https://github.com/Azure/azure-sdk-for-net/blob/8cca811371159e527159c7eb65602477898683e2/sdk/core/Azure.Core/src/Pipeline/Internal/HttpEnvironmentProxy.cs#L210
- */
-function isBypassed(uri, noProxyList, bypassedMap) {
- if (noProxyList.length === 0) {
- return false;
- }
- const host = new URL(uri).hostname;
- if (bypassedMap?.has(host)) {
- return bypassedMap.get(host);
- }
- let isBypassedFlag = false;
- for (const pattern of noProxyList) {
- if (pattern[0] === ".") {
- // This should match either domain it self or any subdomain or host
- // .foo.com will match foo.com it self or *.foo.com
- if (host.endsWith(pattern)) {
- isBypassedFlag = true;
- }
- else {
- if (host.length === pattern.length - 1 && host === pattern.slice(1)) {
- isBypassedFlag = true;
- }
- }
- }
- else {
- if (host === pattern) {
- isBypassedFlag = true;
- }
- }
- }
- bypassedMap?.set(host, isBypassedFlag);
- return isBypassedFlag;
-}
-function loadNoProxy() {
- const noProxy = getEnvironmentValue(NO_PROXY);
- noProxyListLoaded = true;
- if (noProxy) {
- return noProxy
- .split(",")
- .map((item) => item.trim())
- .filter((item) => item.length);
- }
- return [];
-}
-/**
- * This method converts a proxy url into `ProxySettings` for use with ProxyPolicy.
- * If no argument is given, it attempts to parse a proxy URL from the environment
- * variables `HTTPS_PROXY` or `HTTP_PROXY`.
- * @param proxyUrl - The url of the proxy to use. May contain authentication information.
- * @deprecated - Internally this method is no longer necessary when setting proxy information.
- */
-function getDefaultProxySettings(proxyUrl) {
- if (!proxyUrl) {
- proxyUrl = loadEnvironmentProxyValue();
- if (!proxyUrl) {
- return undefined;
- }
- }
- const parsedUrl = new URL(proxyUrl);
- const schema = parsedUrl.protocol ? parsedUrl.protocol + "//" : "";
- return {
- host: schema + parsedUrl.hostname,
- port: Number.parseInt(parsedUrl.port || "80"),
- username: parsedUrl.username,
- password: parsedUrl.password,
- };
-}
-/**
- * This method attempts to parse a proxy URL from the environment
- * variables `HTTPS_PROXY` or `HTTP_PROXY`.
- */
-function getDefaultProxySettingsInternal() {
- const envProxy = loadEnvironmentProxyValue();
- return envProxy ? new URL(envProxy) : undefined;
-}
-function getUrlFromProxySettings(settings) {
- let parsedProxyUrl;
- try {
- parsedProxyUrl = new URL(settings.host);
- }
- catch {
- throw new Error(`Expecting a valid host string in proxy settings, but found "${settings.host}".`);
- }
- parsedProxyUrl.port = String(settings.port);
- if (settings.username) {
- parsedProxyUrl.username = settings.username;
- }
- if (settings.password) {
- parsedProxyUrl.password = settings.password;
- }
- return parsedProxyUrl;
-}
-function setProxyAgentOnRequest(request, cachedAgents, proxyUrl) {
- // Custom Agent should take precedence so if one is present
- // we should skip to avoid overwriting it.
- if (request.agent) {
- return;
- }
- const url = new URL(request.url);
- const isInsecure = url.protocol !== "https:";
- if (request.tlsSettings) {
- log_logger.warning("TLS settings are not supported in combination with custom Proxy, certificates provided to the client will be ignored.");
- }
- const headers = request.headers.toJSON();
- if (isInsecure) {
- if (!cachedAgents.httpProxyAgent) {
- cachedAgents.httpProxyAgent = new http_proxy_agent_dist.HttpProxyAgent(proxyUrl, { headers });
- }
- request.agent = cachedAgents.httpProxyAgent;
- }
- else {
- if (!cachedAgents.httpsProxyAgent) {
- cachedAgents.httpsProxyAgent = new dist.HttpsProxyAgent(proxyUrl, { headers });
- }
- request.agent = cachedAgents.httpsProxyAgent;
- }
-}
-/**
- * A policy that allows one to apply proxy settings to all requests.
- * If not passed static settings, they will be retrieved from the HTTPS_PROXY
- * or HTTP_PROXY environment variables.
- * @param proxySettings - ProxySettings to use on each request.
- * @param options - additional settings, for example, custom NO_PROXY patterns
- */
-function proxyPolicy_proxyPolicy(proxySettings, options) {
- if (!noProxyListLoaded) {
- globalNoProxyList.push(...loadNoProxy());
- }
- const defaultProxy = proxySettings
- ? getUrlFromProxySettings(proxySettings)
- : getDefaultProxySettingsInternal();
- const cachedAgents = {};
- return {
- name: proxyPolicyName,
- async sendRequest(request, next) {
- if (!request.proxySettings &&
- defaultProxy &&
- !isBypassed(request.url, options?.customNoProxyList ?? globalNoProxyList, options?.customNoProxyList ? undefined : globalBypassedMap)) {
- setProxyAgentOnRequest(request, cachedAgents, defaultProxy);
- }
- else if (request.proxySettings) {
- setProxyAgentOnRequest(request, cachedAgents, getUrlFromProxySettings(request.proxySettings));
- }
- return next(request);
- },
- };
-}
-//# sourceMappingURL=proxyPolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/util/typeGuards.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-function isNodeReadableStream(x) {
- return Boolean(x && typeof x["pipe"] === "function");
-}
-function isWebReadableStream(x) {
- return Boolean(x &&
- typeof x.getReader === "function" &&
- typeof x.tee === "function");
-}
-function typeGuards_isBinaryBody(body) {
- return (body !== undefined &&
- (body instanceof Uint8Array ||
- typeGuards_isReadableStream(body) ||
- typeof body === "function" ||
- body instanceof Blob));
-}
-function typeGuards_isReadableStream(x) {
- return isNodeReadableStream(x) || isWebReadableStream(x);
-}
-function isBlob(x) {
- return typeof x.stream === "function";
-}
-//# sourceMappingURL=typeGuards.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/util/concat.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-async function* streamAsyncIterator() {
- const reader = this.getReader();
- try {
- while (true) {
- const { done, value } = await reader.read();
- if (done) {
- return;
- }
- yield value;
- }
- }
- finally {
- reader.releaseLock();
- }
-}
-function makeAsyncIterable(webStream) {
- if (!webStream[Symbol.asyncIterator]) {
- webStream[Symbol.asyncIterator] = streamAsyncIterator.bind(webStream);
- }
- if (!webStream.values) {
- webStream.values = streamAsyncIterator.bind(webStream);
- }
-}
-function ensureNodeStream(stream) {
- if (stream instanceof ReadableStream) {
- makeAsyncIterable(stream);
- return external_stream_namespaceObject.Readable.fromWeb(stream);
- }
- else {
- return stream;
- }
-}
-function toStream(source) {
- if (source instanceof Uint8Array) {
- return external_stream_namespaceObject.Readable.from(Buffer.from(source));
- }
- else if (isBlob(source)) {
- return ensureNodeStream(source.stream());
- }
- else {
- return ensureNodeStream(source);
- }
-}
-/**
- * Utility function that concatenates a set of binary inputs into one combined output.
- *
- * @param sources - array of sources for the concatenation
- * @returns - in Node, a (() =\> NodeJS.ReadableStream) which, when read, produces a concatenation of all the inputs.
- * In browser, returns a `Blob` representing all the concatenated inputs.
- *
- * @internal
- */
-async function concat(sources) {
- return function () {
- const streams = sources.map((x) => (typeof x === "function" ? x() : x)).map(toStream);
- return external_stream_namespaceObject.Readable.from((async function* () {
- for (const stream of streams) {
- for await (const chunk of stream) {
- yield chunk;
- }
- }
- })());
- };
-}
-//# sourceMappingURL=concat.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/policies/multipartPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-
-
-function generateBoundary() {
- return `----AzSDKFormBoundary${randomUUID()}`;
-}
-function encodeHeaders(headers) {
- let result = "";
- for (const [key, value] of headers) {
- result += `${key}: ${value}\r\n`;
- }
- return result;
-}
-function getLength(source) {
- if (source instanceof Uint8Array) {
- return source.byteLength;
- }
- else if (isBlob(source)) {
- // if was created using createFile then -1 means we have an unknown size
- return source.size === -1 ? undefined : source.size;
- }
- else {
- return undefined;
- }
-}
-function getTotalLength(sources) {
- let total = 0;
- for (const source of sources) {
- const partLength = getLength(source);
- if (partLength === undefined) {
- return undefined;
- }
- else {
- total += partLength;
- }
- }
- return total;
-}
-async function buildRequestBody(request, parts, boundary) {
- const sources = [
- bytesEncoding_stringToUint8Array(`--${boundary}`, "utf-8"),
- ...parts.flatMap((part) => [
- bytesEncoding_stringToUint8Array("\r\n", "utf-8"),
- bytesEncoding_stringToUint8Array(encodeHeaders(part.headers), "utf-8"),
- bytesEncoding_stringToUint8Array("\r\n", "utf-8"),
- part.body,
- bytesEncoding_stringToUint8Array(`\r\n--${boundary}`, "utf-8"),
- ]),
- bytesEncoding_stringToUint8Array("--\r\n\r\n", "utf-8"),
- ];
- const contentLength = getTotalLength(sources);
- if (contentLength) {
- request.headers.set("Content-Length", contentLength);
- }
- request.body = await concat(sources);
-}
-/**
- * Name of multipart policy
- */
-const multipartPolicy_multipartPolicyName = "multipartPolicy";
-const maxBoundaryLength = 70;
-const validBoundaryCharacters = new Set(`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'()+,-./:=?`);
-function assertValidBoundary(boundary) {
- if (boundary.length > maxBoundaryLength) {
- throw new Error(`Multipart boundary "${boundary}" exceeds maximum length of 70 characters`);
- }
- if (Array.from(boundary).some((x) => !validBoundaryCharacters.has(x))) {
- throw new Error(`Multipart boundary "${boundary}" contains invalid characters`);
- }
-}
-/**
- * Pipeline policy for multipart requests
- */
-function multipartPolicy_multipartPolicy() {
- return {
- name: multipartPolicy_multipartPolicyName,
- async sendRequest(request, next) {
- if (!request.multipartBody) {
- return next(request);
- }
- if (request.body) {
- throw new Error("multipartBody and regular body cannot be set at the same time");
- }
- let boundary = request.multipartBody.boundary;
- const contentTypeHeader = request.headers.get("Content-Type") ?? "multipart/mixed";
- const parsedHeader = contentTypeHeader.match(/^(multipart\/[^ ;]+)(?:; *boundary=(.+))?$/);
- if (!parsedHeader) {
- throw new Error(`Got multipart request body, but content-type header was not multipart: ${contentTypeHeader}`);
- }
- const [, contentType, parsedBoundary] = parsedHeader;
- if (parsedBoundary && boundary && parsedBoundary !== boundary) {
- throw new Error(`Multipart boundary was specified as ${parsedBoundary} in the header, but got ${boundary} in the request body`);
- }
- boundary ??= parsedBoundary;
- if (boundary) {
- assertValidBoundary(boundary);
- }
- else {
- boundary = generateBoundary();
- }
- request.headers.set("Content-Type", `${contentType}; boundary=${boundary}`);
- await buildRequestBody(request, request.multipartBody.parts, boundary);
- request.multipartBody = undefined;
- return next(request);
- },
- };
-}
-//# sourceMappingURL=multipartPolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/createPipelineFromOptions.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-
-
-
-
-
-
-
-
-
-
-/**
- * Create a new pipeline with a default set of customizable policies.
- * @param options - Options to configure a custom pipeline.
- */
-function createPipelineFromOptions_createPipelineFromOptions(options) {
- const pipeline = createEmptyPipeline();
- if (isNodeLike) {
- if (options.agent) {
- pipeline.addPolicy(agentPolicy(options.agent));
- }
- if (options.tlsOptions) {
- pipeline.addPolicy(tlsPolicy(options.tlsOptions));
- }
- pipeline.addPolicy(proxyPolicy(options.proxyOptions));
- pipeline.addPolicy(decompressResponsePolicy());
- }
- pipeline.addPolicy(formDataPolicy(), { beforePolicies: [multipartPolicyName] });
- pipeline.addPolicy(userAgentPolicy(options.userAgentOptions));
- // The multipart policy is added after policies with no phase, so that
- // policies can be added between it and formDataPolicy to modify
- // properties (e.g., making the boundary constant in recorded tests).
- pipeline.addPolicy(multipartPolicy(), { afterPhase: "Deserialize" });
- pipeline.addPolicy(defaultRetryPolicy(options.retryOptions), { phase: "Retry" });
- if (isNodeLike) {
- // Both XHR and Fetch expect to handle redirects automatically,
- // so only include this policy when we're in Node.
- pipeline.addPolicy(redirectPolicy(options.redirectOptions), { afterPhase: "Retry" });
- }
- pipeline.addPolicy(logPolicy(options.loggingOptions), { afterPhase: "Sign" });
- return pipeline;
-}
-//# sourceMappingURL=createPipelineFromOptions.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/policies/auth/checkInsecureConnection.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-// Ensure the warining is only emitted once
-let insecureConnectionWarningEmmitted = false;
-/**
- * Checks if the request is allowed to be sent over an insecure connection.
- *
- * A request is allowed to be sent over an insecure connection when:
- * - The `allowInsecureConnection` option is set to `true`.
- * - The request has the `allowInsecureConnection` property set to `true`.
- * - The request is being sent to `localhost` or `127.0.0.1`
- */
-function allowInsecureConnection(request, options) {
- if (options.allowInsecureConnection && request.allowInsecureConnection) {
- const url = new URL(request.url);
- if (url.hostname === "localhost" || url.hostname === "127.0.0.1") {
- return true;
- }
- }
- return false;
-}
-/**
- * Logs a warning about sending a token over an insecure connection.
- *
- * This function will emit a node warning once, but log the warning every time.
- */
-function emitInsecureConnectionWarning() {
- const warning = "Sending token over insecure transport. Assume any token issued is compromised.";
- logger.warning(warning);
- if (typeof process?.emitWarning === "function" && !insecureConnectionWarningEmmitted) {
- insecureConnectionWarningEmmitted = true;
- process.emitWarning(warning);
- }
-}
-/**
- * Ensures that authentication is only allowed over HTTPS unless explicitly allowed.
- * Throws an error if the connection is not secure and not explicitly allowed.
- */
-function checkInsecureConnection_ensureSecureConnection(request, options) {
- if (!request.url.toLowerCase().startsWith("https://")) {
- if (allowInsecureConnection(request, options)) {
- emitInsecureConnectionWarning();
- }
- else {
- throw new Error("Authentication is not permitted for non-TLS protected (non-https) URLs when allowInsecureConnection is false.");
- }
- }
-}
-//# sourceMappingURL=checkInsecureConnection.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/policies/auth/apiKeyAuthenticationPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-/**
- * Name of the API Key Authentication Policy
- */
-const apiKeyAuthenticationPolicyName = "apiKeyAuthenticationPolicy";
-/**
- * Gets a pipeline policy that adds API key authentication to requests
- */
-function apiKeyAuthenticationPolicy_apiKeyAuthenticationPolicy(options) {
- return {
- name: apiKeyAuthenticationPolicyName,
- async sendRequest(request, next) {
- // Ensure allowInsecureConnection is explicitly set when sending request to non-https URLs
- ensureSecureConnection(request, options);
- const scheme = (request.authSchemes ?? options.authSchemes)?.find((x) => x.kind === "apiKey");
- // Skip adding authentication header if no API key authentication scheme is found
- if (!scheme) {
- return next(request);
- }
- if (scheme.apiKeyLocation !== "header") {
- throw new Error(`Unsupported API key location: ${scheme.apiKeyLocation}`);
- }
- request.headers.set(scheme.name, options.credential.key);
- return next(request);
- },
- };
-}
-//# sourceMappingURL=apiKeyAuthenticationPolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/policies/auth/basicAuthenticationPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-/**
- * Name of the Basic Authentication Policy
- */
-const basicAuthenticationPolicyName = "bearerAuthenticationPolicy";
-/**
- * Gets a pipeline policy that adds basic authentication to requests
- */
-function basicAuthenticationPolicy_basicAuthenticationPolicy(options) {
- return {
- name: basicAuthenticationPolicyName,
- async sendRequest(request, next) {
- // Ensure allowInsecureConnection is explicitly set when sending request to non-https URLs
- ensureSecureConnection(request, options);
- const scheme = (request.authSchemes ?? options.authSchemes)?.find((x) => x.kind === "http" && x.scheme === "basic");
- // Skip adding authentication header if no basic authentication scheme is found
- if (!scheme) {
- return next(request);
- }
- const { username, password } = options.credential;
- const headerValue = uint8ArrayToString(stringToUint8Array(`${username}:${password}`, "utf-8"), "base64");
- request.headers.set("Authorization", `Basic ${headerValue}`);
- return next(request);
- },
- };
-}
-//# sourceMappingURL=basicAuthenticationPolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/policies/auth/bearerAuthenticationPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-/**
- * Name of the Bearer Authentication Policy
- */
-const bearerAuthenticationPolicyName = "bearerAuthenticationPolicy";
-/**
- * Gets a pipeline policy that adds bearer token authentication to requests
- */
-function bearerAuthenticationPolicy_bearerAuthenticationPolicy(options) {
- return {
- name: bearerAuthenticationPolicyName,
- async sendRequest(request, next) {
- // Ensure allowInsecureConnection is explicitly set when sending request to non-https URLs
- ensureSecureConnection(request, options);
- const scheme = (request.authSchemes ?? options.authSchemes)?.find((x) => x.kind === "http" && x.scheme === "bearer");
- // Skip adding authentication header if no bearer authentication scheme is found
- if (!scheme) {
- return next(request);
- }
- const token = await options.credential.getBearerToken({
- abortSignal: request.abortSignal,
- });
- request.headers.set("Authorization", `Bearer ${token}`);
- return next(request);
- },
- };
-}
-//# sourceMappingURL=bearerAuthenticationPolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/policies/auth/oauth2AuthenticationPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-/**
- * Name of the OAuth2 Authentication Policy
- */
-const oauth2AuthenticationPolicyName = "oauth2AuthenticationPolicy";
-/**
- * Gets a pipeline policy that adds authorization header from OAuth2 schemes
- */
-function oauth2AuthenticationPolicy_oauth2AuthenticationPolicy(options) {
- return {
- name: oauth2AuthenticationPolicyName,
- async sendRequest(request, next) {
- // Ensure allowInsecureConnection is explicitly set when sending request to non-https URLs
- ensureSecureConnection(request, options);
- const scheme = (request.authSchemes ?? options.authSchemes)?.find((x) => x.kind === "oauth2");
- // Skip adding authentication header if no OAuth2 authentication scheme is found
- if (!scheme) {
- return next(request);
- }
- const token = await options.credential.getOAuth2Token(scheme.flows, {
- abortSignal: request.abortSignal,
- });
- request.headers.set("Authorization", `Bearer ${token}`);
- return next(request);
- },
- };
-}
-//# sourceMappingURL=oauth2AuthenticationPolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/client/clientHelpers.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-
-
-
-
-
-
-let cachedHttpClient;
-/**
- * Creates a default rest pipeline to re-use accross Rest Level Clients
- */
-function clientHelpers_createDefaultPipeline(options = {}) {
- const pipeline = createPipelineFromOptions(options);
- pipeline.addPolicy(apiVersionPolicy(options));
- const { credential, authSchemes, allowInsecureConnection } = options;
- if (credential) {
- if (isApiKeyCredential(credential)) {
- pipeline.addPolicy(apiKeyAuthenticationPolicy({ authSchemes, credential, allowInsecureConnection }));
- }
- else if (isBasicCredential(credential)) {
- pipeline.addPolicy(basicAuthenticationPolicy({ authSchemes, credential, allowInsecureConnection }));
- }
- else if (isBearerTokenCredential(credential)) {
- pipeline.addPolicy(bearerAuthenticationPolicy({ authSchemes, credential, allowInsecureConnection }));
- }
- else if (isOAuth2TokenCredential(credential)) {
- pipeline.addPolicy(oauth2AuthenticationPolicy({ authSchemes, credential, allowInsecureConnection }));
- }
- }
- return pipeline;
-}
-function clientHelpers_getCachedDefaultHttpsClient() {
- if (!cachedHttpClient) {
- cachedHttpClient = createDefaultHttpClient();
- }
- return cachedHttpClient;
-}
-//# sourceMappingURL=clientHelpers.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/client/multipart.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-
-
-/**
- * Get value of a header in the part descriptor ignoring case
- */
-function getHeaderValue(descriptor, headerName) {
- if (descriptor.headers) {
- const actualHeaderName = Object.keys(descriptor.headers).find((x) => x.toLowerCase() === headerName.toLowerCase());
- if (actualHeaderName) {
- return descriptor.headers[actualHeaderName];
- }
- }
- return undefined;
-}
-function getPartContentType(descriptor) {
- const contentTypeHeader = getHeaderValue(descriptor, "content-type");
- if (contentTypeHeader) {
- return contentTypeHeader;
- }
- // Special value of null means content type is to be omitted
- if (descriptor.contentType === null) {
- return undefined;
- }
- if (descriptor.contentType) {
- return descriptor.contentType;
- }
- const { body } = descriptor;
- if (body === null || body === undefined) {
- return undefined;
- }
- if (typeof body === "string" || typeof body === "number" || typeof body === "boolean") {
- return "text/plain; charset=UTF-8";
- }
- if (body instanceof Blob) {
- return body.type || "application/octet-stream";
- }
- if (isBinaryBody(body)) {
- return "application/octet-stream";
- }
- // arbitrary non-text object -> generic JSON content type by default. We will try to JSON.stringify the body.
- return "application/json";
-}
-/**
- * Enclose value in quotes and escape special characters, for use in the Content-Disposition header
- */
-function escapeDispositionField(value) {
- return JSON.stringify(value);
-}
-function getContentDisposition(descriptor) {
- const contentDispositionHeader = getHeaderValue(descriptor, "content-disposition");
- if (contentDispositionHeader) {
- return contentDispositionHeader;
- }
- if (descriptor.dispositionType === undefined &&
- descriptor.name === undefined &&
- descriptor.filename === undefined) {
- return undefined;
- }
- const dispositionType = descriptor.dispositionType ?? "form-data";
- let disposition = dispositionType;
- if (descriptor.name) {
- disposition += `; name=${escapeDispositionField(descriptor.name)}`;
- }
- let filename = undefined;
- if (descriptor.filename) {
- filename = descriptor.filename;
- }
- else if (typeof File !== "undefined" && descriptor.body instanceof File) {
- const filenameFromFile = descriptor.body.name;
- if (filenameFromFile !== "") {
- filename = filenameFromFile;
- }
- }
- if (filename) {
- disposition += `; filename=${escapeDispositionField(filename)}`;
- }
- return disposition;
-}
-function normalizeBody(body, contentType) {
- if (body === undefined) {
- // zero-length body
- return new Uint8Array([]);
- }
- // binary and primitives should go straight on the wire regardless of content type
- if (isBinaryBody(body)) {
- return body;
- }
- if (typeof body === "string" || typeof body === "number" || typeof body === "boolean") {
- return stringToUint8Array(String(body), "utf-8");
- }
- // stringify objects for JSON-ish content types e.g. application/json, application/merge-patch+json, application/vnd.oci.manifest.v1+json, application.json; charset=UTF-8
- if (contentType && /application\/(.+\+)?json(;.+)?/i.test(String(contentType))) {
- return stringToUint8Array(JSON.stringify(body), "utf-8");
- }
- throw new RestError(`Unsupported body/content-type combination: ${body}, ${contentType}`);
-}
-function buildBodyPart(descriptor) {
- const contentType = getPartContentType(descriptor);
- const contentDisposition = getContentDisposition(descriptor);
- const headers = createHttpHeaders(descriptor.headers ?? {});
- if (contentType) {
- headers.set("content-type", contentType);
- }
- if (contentDisposition) {
- headers.set("content-disposition", contentDisposition);
- }
- const body = normalizeBody(descriptor.body, contentType);
- return {
- headers,
- body,
- };
-}
-function multipart_buildMultipartBody(parts) {
- return { parts: parts.map(buildBodyPart) };
-}
-//# sourceMappingURL=multipart.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/client/sendRequest.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-
-
-
-
-/**
- * Helper function to send request used by the client
- * @param method - method to use to send the request
- * @param url - url to send the request to
- * @param pipeline - pipeline with the policies to run when sending the request
- * @param options - request options
- * @param customHttpClient - a custom HttpClient to use when making the request
- * @returns returns and HttpResponse
- */
-async function sendRequest_sendRequest(method, url, pipeline, options = {}, customHttpClient) {
- const httpClient = customHttpClient ?? getCachedDefaultHttpsClient();
- const request = buildPipelineRequest(method, url, options);
- try {
- const response = await pipeline.sendRequest(httpClient, request);
- const headers = response.headers.toJSON();
- const stream = response.readableStreamBody ?? response.browserStreamBody;
- const parsedBody = options.responseAsStream || stream !== undefined ? undefined : getResponseBody(response);
- const body = stream ?? parsedBody;
- if (options?.onResponse) {
- options.onResponse({ ...response, request, rawHeaders: headers, parsedBody });
- }
- return {
- request,
- headers,
- status: `${response.status}`,
- body,
- };
- }
- catch (e) {
- if (isRestError(e) && e.response && options.onResponse) {
- const { response } = e;
- const rawHeaders = response.headers.toJSON();
- // UNBRANDED DIFFERENCE: onResponse callback does not have a second __legacyError property
- options?.onResponse({ ...response, request, rawHeaders }, e);
- }
- throw e;
- }
-}
-/**
- * Function to determine the request content type
- * @param options - request options InternalRequestParameters
- * @returns returns the content-type
- */
-function getRequestContentType(options = {}) {
- return (options.contentType ??
- options.headers?.["content-type"] ??
- getContentType(options.body));
-}
-/**
- * Function to determine the content-type of a body
- * this is used if an explicit content-type is not provided
- * @param body - body in the request
- * @returns returns the content-type
- */
-function getContentType(body) {
- if (ArrayBuffer.isView(body)) {
- return "application/octet-stream";
- }
- if (typeof body === "string") {
- try {
- JSON.parse(body);
- return "application/json";
- }
- catch (error) {
- // If we fail to parse the body, it is not json
- return undefined;
- }
- }
- // By default return json
- return "application/json";
-}
-function buildPipelineRequest(method, url, options = {}) {
- const requestContentType = getRequestContentType(options);
- const { body, multipartBody } = getRequestBody(options.body, requestContentType);
- const hasContent = body !== undefined || multipartBody !== undefined;
- const headers = createHttpHeaders({
- ...(options.headers ? options.headers : {}),
- accept: options.accept ?? options.headers?.accept ?? "application/json",
- ...(hasContent &&
- requestContentType && {
- "content-type": requestContentType,
- }),
- });
- return createPipelineRequest({
- url,
- method,
- body,
- multipartBody,
- headers,
- allowInsecureConnection: options.allowInsecureConnection,
- abortSignal: options.abortSignal,
- onUploadProgress: options.onUploadProgress,
- onDownloadProgress: options.onDownloadProgress,
- timeout: options.timeout,
- enableBrowserStreams: true,
- streamResponseStatusCodes: options.responseAsStream
- ? new Set([Number.POSITIVE_INFINITY])
- : undefined,
- });
-}
-/**
- * Prepares the body before sending the request
- */
-function getRequestBody(body, contentType = "") {
- if (body === undefined) {
- return { body: undefined };
- }
- if (typeof FormData !== "undefined" && body instanceof FormData) {
- return { body };
- }
- if (isReadableStream(body)) {
- return { body };
- }
- if (ArrayBuffer.isView(body)) {
- return { body: body instanceof Uint8Array ? body : JSON.stringify(body) };
- }
- const firstType = contentType.split(";")[0];
- switch (firstType) {
- case "application/json":
- return { body: JSON.stringify(body) };
- case "multipart/form-data":
- if (Array.isArray(body)) {
- return { multipartBody: buildMultipartBody(body) };
- }
- return { body: JSON.stringify(body) };
- case "text/plain":
- return { body: String(body) };
- default:
- if (typeof body === "string") {
- return { body };
- }
- return { body: JSON.stringify(body) };
- }
-}
-/**
- * Prepares the response body
- */
-function getResponseBody(response) {
- // Set the default response type
- const contentType = response.headers.get("content-type") ?? "";
- const firstType = contentType.split(";")[0];
- const bodyToParse = response.bodyAsText ?? "";
- if (firstType === "text/plain") {
- return String(bodyToParse);
- }
- // Default to "application/json" and fallback to string;
- try {
- return bodyToParse ? JSON.parse(bodyToParse) : undefined;
- }
- catch (error) {
- // If we were supposed to get a JSON object and failed to
- // parse, throw a parse error
- if (firstType === "application/json") {
- throw createParseError(response, error);
- }
- // We are not sure how to handle the response so we return it as
- // plain text.
- return String(bodyToParse);
- }
-}
-function createParseError(response, err) {
- const msg = `Error "${err}" occurred while parsing the response body - ${response.bodyAsText}.`;
- const errCode = err.code ?? RestError.PARSE_ERROR;
- return new RestError(msg, {
- code: errCode,
- statusCode: response.status,
- request: response.request,
- response: response,
- });
-}
-//# sourceMappingURL=sendRequest.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/client/getClient.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-
-
-/**
- * Creates a client with a default pipeline
- * @param endpoint - Base endpoint for the client
- * @param credentials - Credentials to authenticate the requests
- * @param options - Client options
- */
-function getClient(endpoint, clientOptions = {}) {
- const pipeline = clientOptions.pipeline ?? createDefaultPipeline(clientOptions);
- if (clientOptions.additionalPolicies?.length) {
- for (const { policy, position } of clientOptions.additionalPolicies) {
- // Sign happens after Retry and is commonly needed to occur
- // before policies that intercept post-retry.
- const afterPhase = position === "perRetry" ? "Sign" : undefined;
- pipeline.addPolicy(policy, {
- afterPhase,
- });
- }
- }
- const { allowInsecureConnection, httpClient } = clientOptions;
- const endpointUrl = clientOptions.endpoint ?? endpoint;
- const client = (path, ...args) => {
- const getUrl = (requestOptions) => buildRequestUrl(endpointUrl, path, args, { allowInsecureConnection, ...requestOptions });
- return {
- get: (requestOptions = {}) => {
- return buildOperation("GET", getUrl(requestOptions), pipeline, requestOptions, allowInsecureConnection, httpClient);
- },
- post: (requestOptions = {}) => {
- return buildOperation("POST", getUrl(requestOptions), pipeline, requestOptions, allowInsecureConnection, httpClient);
- },
- put: (requestOptions = {}) => {
- return buildOperation("PUT", getUrl(requestOptions), pipeline, requestOptions, allowInsecureConnection, httpClient);
- },
- patch: (requestOptions = {}) => {
- return buildOperation("PATCH", getUrl(requestOptions), pipeline, requestOptions, allowInsecureConnection, httpClient);
- },
- delete: (requestOptions = {}) => {
- return buildOperation("DELETE", getUrl(requestOptions), pipeline, requestOptions, allowInsecureConnection, httpClient);
- },
- head: (requestOptions = {}) => {
- return buildOperation("HEAD", getUrl(requestOptions), pipeline, requestOptions, allowInsecureConnection, httpClient);
- },
- options: (requestOptions = {}) => {
- return buildOperation("OPTIONS", getUrl(requestOptions), pipeline, requestOptions, allowInsecureConnection, httpClient);
- },
- trace: (requestOptions = {}) => {
- return buildOperation("TRACE", getUrl(requestOptions), pipeline, requestOptions, allowInsecureConnection, httpClient);
- },
- };
- };
- return {
- path: client,
- pathUnchecked: client,
- pipeline,
- };
-}
-function buildOperation(method, url, pipeline, options, allowInsecureConnection, httpClient) {
- allowInsecureConnection = options.allowInsecureConnection ?? allowInsecureConnection;
- return {
- then: function (onFulfilled, onrejected) {
- return sendRequest(method, url, pipeline, { ...options, allowInsecureConnection }, httpClient).then(onFulfilled, onrejected);
- },
- async asBrowserStream() {
- if (isNodeLike) {
- throw new Error("`asBrowserStream` is supported only in the browser environment. Use `asNodeStream` instead to obtain the response body stream. If you require a Web stream of the response in Node, consider using `Readable.toWeb` on the result of `asNodeStream`.");
- }
- else {
- return sendRequest(method, url, pipeline, { ...options, allowInsecureConnection, responseAsStream: true }, httpClient);
- }
- },
- async asNodeStream() {
- if (isNodeLike) {
- return sendRequest(method, url, pipeline, { ...options, allowInsecureConnection, responseAsStream: true }, httpClient);
- }
- else {
- throw new Error("`isNodeStream` is not supported in the browser environment. Use `asBrowserStream` to obtain the response body stream.");
- }
- },
- };
-}
-//# sourceMappingURL=getClient.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/client/restError.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-function createRestError(messageOrResponse, response) {
- const resp = typeof messageOrResponse === "string" ? response : messageOrResponse;
- const internalError = resp.body?.error ?? resp.body;
- const message = typeof messageOrResponse === "string"
- ? messageOrResponse
- : (internalError?.message ?? `Unexpected status code: ${resp.status}`);
- return new RestError(message, {
- statusCode: statusCodeToNumber(resp.status),
- code: internalError?.code,
- request: resp.request,
- response: toPipelineResponse(resp),
- });
-}
-function toPipelineResponse(response) {
- return {
- headers: createHttpHeaders(response.headers),
- request: response.request,
- status: statusCodeToNumber(response.status) ?? -1,
- };
-}
-function statusCodeToNumber(statusCode) {
- const status = Number.parseInt(statusCode);
- return Number.isNaN(status) ? undefined : status;
-}
-//# sourceMappingURL=restError.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/index.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-
-
-
-
-
-
-
-
-
-
-
-//# sourceMappingURL=index.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/pipeline.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-/**
- * Creates a totally empty pipeline.
- * Useful for testing or creating a custom one.
- */
-function esm_pipeline_createEmptyPipeline() {
- return pipeline_createEmptyPipeline();
-}
-//# sourceMappingURL=pipeline.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/logger/internal.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-//# sourceMappingURL=internal.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/logger/dist/esm/index.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-const esm_context = createLoggerContext({
- logLevelEnvVarName: "AZURE_LOG_LEVEL",
- namespace: "azure",
-});
-/**
- * The AzureLogger provides a mechanism for overriding where logs are output to.
- * By default, logs are sent to stderr.
- * Override the `log` method to redirect logs to another location.
- */
-const AzureLogger = esm_context.logger;
-/**
- * Immediately enables logging at the specified log level. If no level is specified, logging is disabled.
- * @param level - The log level to enable for logging.
- * Options from most verbose to least verbose are:
- * - verbose
- * - info
- * - warning
- * - error
- */
-function esm_setLogLevel(level) {
- esm_context.setLogLevel(level);
-}
-/**
- * Retrieves the currently specified log level.
- */
-function esm_getLogLevel() {
- return esm_context.getLogLevel();
-}
-/**
- * Creates a logger for use by the Azure SDKs that inherits from `AzureLogger`.
- * @param namespace - The name of the SDK package.
- * @hidden
- */
-function esm_createClientLogger(namespace) {
- return esm_context.createClientLogger(namespace);
-}
-//# sourceMappingURL=index.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/log.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-const esm_log_logger = esm_createClientLogger("core-rest-pipeline");
-//# sourceMappingURL=log.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/policies/agentPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-/**
- * Name of the Agent Policy
- */
-const agentPolicyName = "agentPolicy";
-/**
- * Gets a pipeline policy that sets http.agent
- */
-function agentPolicy_agentPolicy(agent) {
- return {
- name: agentPolicyName,
- sendRequest: async (req, next) => {
- // Users may define an agent on the request, honor it over the client level one
- if (!req.agent) {
- req.agent = agent;
- }
- return next(req);
- },
- };
-}
-//# sourceMappingURL=agentPolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/policies/decompressResponsePolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-/**
- * The programmatic identifier of the decompressResponsePolicy.
- */
-const decompressResponsePolicyName = "decompressResponsePolicy";
-/**
- * A policy to enable response decompression according to Accept-Encoding header
- * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding
- */
-function decompressResponsePolicy_decompressResponsePolicy() {
- return {
- name: decompressResponsePolicyName,
- async sendRequest(request, next) {
- // HEAD requests have no body
- if (request.method !== "HEAD") {
- request.headers.set("Accept-Encoding", "gzip,deflate");
- }
- return next(request);
- },
- };
-}
-//# sourceMappingURL=decompressResponsePolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/policies/exponentialRetryPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-
-/**
- * The programmatic identifier of the exponentialRetryPolicy.
- */
-const exponentialRetryPolicyName = "exponentialRetryPolicy";
-/**
- * A policy that attempts to retry requests while introducing an exponentially increasing delay.
- * @param options - Options that configure retry logic.
- */
-function exponentialRetryPolicy(options = {}) {
- return retryPolicy([
- exponentialRetryStrategy({
- ...options,
- ignoreSystemErrors: true,
- }),
- ], {
- maxRetries: options.maxRetries ?? DEFAULT_RETRY_POLICY_COUNT,
- });
-}
-//# sourceMappingURL=exponentialRetryPolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/policies/systemErrorRetryPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-
-/**
- * Name of the {@link systemErrorRetryPolicy}
- */
-const systemErrorRetryPolicyName = "systemErrorRetryPolicy";
-/**
- * A retry policy that specifically seeks to handle errors in the
- * underlying transport layer (e.g. DNS lookup failures) rather than
- * retryable error codes from the server itself.
- * @param options - Options that customize the policy.
- */
-function systemErrorRetryPolicy(options = {}) {
- return {
- name: systemErrorRetryPolicyName,
- sendRequest: retryPolicy([
- exponentialRetryStrategy({
- ...options,
- ignoreHttpStatusCodes: true,
- }),
- ], {
- maxRetries: options.maxRetries ?? DEFAULT_RETRY_POLICY_COUNT,
- }).sendRequest,
- };
-}
-//# sourceMappingURL=systemErrorRetryPolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/policies/throttlingRetryPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-
-/**
- * Name of the {@link throttlingRetryPolicy}
- */
-const throttlingRetryPolicyName = "throttlingRetryPolicy";
-/**
- * A policy that retries when the server sends a 429 response with a Retry-After header.
- *
- * To learn more, please refer to
- * https://learn.microsoft.com/azure/azure-resource-manager/resource-manager-request-limits,
- * https://learn.microsoft.com/azure/azure-subscription-service-limits and
- * https://learn.microsoft.com/azure/virtual-machines/troubleshooting/troubleshooting-throttling-errors
- *
- * @param options - Options that configure retry logic.
- */
-function throttlingRetryPolicy(options = {}) {
- return {
- name: throttlingRetryPolicyName,
- sendRequest: retryPolicy([throttlingRetryStrategy()], {
- maxRetries: options.maxRetries ?? DEFAULT_RETRY_POLICY_COUNT,
- }).sendRequest,
- };
-}
-//# sourceMappingURL=throttlingRetryPolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/policies/redirectPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-/**
- * The programmatic identifier of the redirectPolicy.
- */
-const redirectPolicyName = "redirectPolicy";
-/**
- * Methods that are allowed to follow redirects 301 and 302
- */
-const allowedRedirect = ["GET", "HEAD"];
-/**
- * A policy to follow Location headers from the server in order
- * to support server-side redirection.
- * In the browser, this policy is not used.
- * @param options - Options to control policy behavior.
- */
-function redirectPolicy_redirectPolicy(options = {}) {
- const { maxRetries = 20 } = options;
- return {
- name: redirectPolicyName,
- async sendRequest(request, next) {
- const response = await next(request);
- return handleRedirect(next, response, maxRetries);
- },
- };
-}
-async function handleRedirect(next, response, maxRetries, currentRetries = 0) {
- const { request, status, headers } = response;
- const locationHeader = headers.get("location");
- if (locationHeader &&
- (status === 300 ||
- (status === 301 && allowedRedirect.includes(request.method)) ||
- (status === 302 && allowedRedirect.includes(request.method)) ||
- (status === 303 && request.method === "POST") ||
- status === 307) &&
- currentRetries < maxRetries) {
- const url = new URL(locationHeader, request.url);
- request.url = url.toString();
- // POST request with Status code 303 should be converted into a
- // redirected GET request if the redirect url is present in the location header
- if (status === 303) {
- request.method = "GET";
- request.headers.delete("Content-Length");
- delete request.body;
- }
- request.headers.delete("Authorization");
- const res = await next(request);
- return handleRedirect(next, res, maxRetries, currentRetries + 1);
- }
- return response;
-}
-//# sourceMappingURL=redirectPolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/policies/tlsPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-/**
- * Name of the TLS Policy
- */
-const tlsPolicyName = "tlsPolicy";
-/**
- * Gets a pipeline policy that adds the client certificate to the HttpClient agent for authentication.
- */
-function tlsPolicy_tlsPolicy(tlsSettings) {
- return {
- name: tlsPolicyName,
- sendRequest: async (req, next) => {
- // Users may define a request tlsSettings, honor those over the client level one
- if (!req.tlsSettings) {
- req.tlsSettings = tlsSettings;
- }
- return next(req);
- },
- };
-}
-//# sourceMappingURL=tlsPolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/policies/internal.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-//# sourceMappingURL=internal.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/policies/logPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-/**
- * The programmatic identifier of the logPolicy.
- */
-const logPolicy_logPolicyName = (/* unused pure expression or super */ null && (tspLogPolicyName));
-/**
- * A policy that logs all requests and responses.
- * @param options - Options to configure logPolicy.
- */
-function policies_logPolicy_logPolicy(options = {}) {
- return logPolicy_logPolicy({
- logger: esm_log_logger.info,
- ...options,
- });
-}
-//# sourceMappingURL=logPolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/policies/redirectPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-/**
- * The programmatic identifier of the redirectPolicy.
- */
-const redirectPolicy_redirectPolicyName = redirectPolicyName;
-/**
- * A policy to follow Location headers from the server in order
- * to support server-side redirection.
- * In the browser, this policy is not used.
- * @param options - Options to control policy behavior.
- */
-function policies_redirectPolicy_redirectPolicy(options = {}) {
- return redirectPolicy_redirectPolicy(options);
-}
-//# sourceMappingURL=redirectPolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/util/userAgentPlatform.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-/**
- * @internal
- */
-function userAgentPlatform_getHeaderName() {
- return "User-Agent";
-}
-/**
- * @internal
- */
-async function util_userAgentPlatform_setPlatformSpecificData(map) {
- if (external_node_process_ && external_node_process_.versions) {
- const osInfo = `${external_node_os_.type()} ${external_node_os_.release()}; ${external_node_os_.arch()}`;
- const versions = external_node_process_.versions;
- if (versions.bun) {
- map.set("Bun", `${versions.bun} (${osInfo})`);
- }
- else if (versions.deno) {
- map.set("Deno", `${versions.deno} (${osInfo})`);
- }
- else if (versions.node) {
- map.set("Node", `${versions.node} (${osInfo})`);
- }
- }
-}
-//# sourceMappingURL=userAgentPlatform.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/constants.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-const esm_constants_SDK_VERSION = "1.22.2";
-const esm_constants_DEFAULT_RETRY_POLICY_COUNT = 3;
-//# sourceMappingURL=constants.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/util/userAgent.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-function userAgent_getUserAgentString(telemetryInfo) {
- const parts = [];
- for (const [key, value] of telemetryInfo) {
- const token = value ? `${key}/${value}` : key;
- parts.push(token);
- }
- return parts.join(" ");
-}
-/**
- * @internal
- */
-function userAgent_getUserAgentHeaderName() {
- return userAgentPlatform_getHeaderName();
-}
-/**
- * @internal
- */
-async function util_userAgent_getUserAgentValue(prefix) {
- const runtimeInfo = new Map();
- runtimeInfo.set("core-rest-pipeline", esm_constants_SDK_VERSION);
- await util_userAgentPlatform_setPlatformSpecificData(runtimeInfo);
- const defaultAgent = userAgent_getUserAgentString(runtimeInfo);
- const userAgentValue = prefix ? `${prefix} ${defaultAgent}` : defaultAgent;
- return userAgentValue;
-}
-//# sourceMappingURL=userAgent.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/policies/userAgentPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-const userAgentPolicy_UserAgentHeaderName = userAgent_getUserAgentHeaderName();
-/**
- * The programmatic identifier of the userAgentPolicy.
- */
-const userAgentPolicy_userAgentPolicyName = "userAgentPolicy";
-/**
- * A policy that sets the User-Agent header (or equivalent) to reflect
- * the library version.
- * @param options - Options to customize the user agent value.
- */
-function policies_userAgentPolicy_userAgentPolicy(options = {}) {
- const userAgentValue = util_userAgent_getUserAgentValue(options.userAgentPrefix);
- return {
- name: userAgentPolicy_userAgentPolicyName,
- async sendRequest(request, next) {
- if (!request.headers.has(userAgentPolicy_UserAgentHeaderName)) {
- request.headers.set(userAgentPolicy_UserAgentHeaderName, await userAgentValue);
- }
- return next(request);
- },
- };
-}
-//# sourceMappingURL=userAgentPolicy.js.map
-// EXTERNAL MODULE: external "node:crypto"
-var external_node_crypto_ = __nccwpck_require__(7598);
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/util/sha256.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-/**
- * Generates a SHA-256 HMAC signature.
- * @param key - The HMAC key represented as a base64 string, used to generate the cryptographic HMAC hash.
- * @param stringToSign - The data to be signed.
- * @param encoding - The textual encoding to use for the returned HMAC digest.
- */
-async function computeSha256Hmac(key, stringToSign, encoding) {
- const decodedKey = Buffer.from(key, "base64");
- return createHmac("sha256", decodedKey).update(stringToSign).digest(encoding);
-}
-/**
- * Generates a SHA-256 hash.
- * @param content - The data to be included in the hash.
- * @param encoding - The textual encoding to use for the returned hash.
- */
-async function computeSha256Hash(content, encoding) {
- return createHash("sha256").update(content).digest(encoding);
-}
-//# sourceMappingURL=sha256.js.map
-;// CONCATENATED MODULE: ./node_modules/@typespec/ts-http-runtime/dist/esm/util/internal.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-
-
-
-
-
-
-
-//# sourceMappingURL=internal.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/esm/AbortError.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-/**
- * This error is thrown when an asynchronous operation has been aborted.
- * Check for this error by testing the `name` that the name property of the
- * error matches `"AbortError"`.
- *
- * @example
- * ```ts
- * const controller = new AbortController();
- * controller.abort();
- * try {
- * doAsyncWork(controller.signal)
- * } catch (e) {
- * if (e.name === 'AbortError') {
- * // handle abort error here.
- * }
- * }
- * ```
- */
-class AbortError_AbortError extends Error {
- constructor(message) {
- super(message);
- this.name = "AbortError";
- }
-}
-//# sourceMappingURL=AbortError.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-util/node_modules/@azure/abort-controller/dist/esm/index.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-
-//# sourceMappingURL=index.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-util/dist/esm/createAbortablePromise.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-/**
- * Creates an abortable promise.
- * @param buildPromise - A function that takes the resolve and reject functions as parameters.
- * @param options - The options for the abortable promise.
- * @returns A promise that can be aborted.
- */
-function createAbortablePromise(buildPromise, options) {
- const { cleanupBeforeAbort, abortSignal, abortErrorMsg } = options ?? {};
- return new Promise((resolve, reject) => {
- function rejectOnAbort() {
- reject(new AbortError_AbortError(abortErrorMsg ?? "The operation was aborted."));
- }
- function removeListeners() {
- abortSignal?.removeEventListener("abort", onAbort);
- }
- function onAbort() {
- cleanupBeforeAbort?.();
- removeListeners();
- rejectOnAbort();
- }
- if (abortSignal?.aborted) {
- return rejectOnAbort();
- }
- try {
- buildPromise((x) => {
- removeListeners();
- resolve(x);
- }, (x) => {
- removeListeners();
- reject(x);
- });
- }
- catch (err) {
- reject(err);
- }
- abortSignal?.addEventListener("abort", onAbort);
- });
-}
-//# sourceMappingURL=createAbortablePromise.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-util/dist/esm/delay.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-const delay_StandardAbortMessage = "The delay was aborted.";
-/**
- * A wrapper for setTimeout that resolves a promise after timeInMs milliseconds.
- * @param timeInMs - The number of milliseconds to be delayed.
- * @param options - The options for delay - currently abort options
- * @returns Promise that is resolved after timeInMs
- */
-function delay_delay(timeInMs, options) {
- let token;
- const { abortSignal, abortErrorMsg } = options ?? {};
- return createAbortablePromise((resolve) => {
- token = setTimeout(resolve, timeInMs);
- }, {
- cleanupBeforeAbort: () => clearTimeout(token),
- abortSignal,
- abortErrorMsg: abortErrorMsg ?? delay_StandardAbortMessage,
- });
-}
-/**
- * Calculates the delay interval for retry attempts using exponential delay with jitter.
- * @param retryAttempt - The current retry attempt number.
- * @param config - The exponential retry configuration.
- * @returns An object containing the calculated retry delay.
- */
-function delay_calculateRetryDelay(retryAttempt, config) {
- // Exponentially increase the delay each time
- const exponentialDelay = config.retryDelayInMs * Math.pow(2, retryAttempt);
- // Don't let the delay exceed the maximum
- const clampedDelay = Math.min(config.maxRetryDelayInMs, exponentialDelay);
- // Allow the final value to have some "jitter" (within 50% of the delay size) so
- // that retries across multiple clients don't occur simultaneously.
- const retryAfterInMs = clampedDelay / 2 + getRandomIntegerInclusive(0, clampedDelay / 2);
- return { retryAfterInMs };
-}
-//# sourceMappingURL=delay.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-util/dist/esm/error.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-/**
- * Given what is thought to be an error object, return the message if possible.
- * If the message is missing, returns a stringified version of the input.
- * @param e - Something thrown from a try block
- * @returns The error message or a string of the input
- */
-function getErrorMessage(e) {
- if (isError(e)) {
- return e.message;
- }
- else {
- let stringified;
- try {
- if (typeof e === "object" && e) {
- stringified = JSON.stringify(e);
- }
- else {
- stringified = String(e);
- }
- }
- catch (err) {
- stringified = "[unable to stringify input]";
- }
- return `Unknown error ${stringified}`;
- }
-}
-//# sourceMappingURL=error.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-util/dist/esm/index.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-
-
-
-
-/**
- * Calculates the delay interval for retry attempts using exponential delay with jitter.
- *
- * @param retryAttempt - The current retry attempt number.
- *
- * @param config - The exponential retry configuration.
- *
- * @returns An object containing the calculated retry delay.
- */
-function esm_calculateRetryDelay(retryAttempt, config) {
- return tspRuntime.calculateRetryDelay(retryAttempt, config);
-}
-/**
- * Generates a SHA-256 hash.
- *
- * @param content - The data to be included in the hash.
- *
- * @param encoding - The textual encoding to use for the returned hash.
- */
-function esm_computeSha256Hash(content, encoding) {
- return tspRuntime.computeSha256Hash(content, encoding);
-}
-/**
- * Generates a SHA-256 HMAC signature.
- *
- * @param key - The HMAC key represented as a base64 string, used to generate the cryptographic HMAC hash.
- *
- * @param stringToSign - The data to be signed.
- *
- * @param encoding - The textual encoding to use for the returned HMAC digest.
- */
-function esm_computeSha256Hmac(key, stringToSign, encoding) {
- return tspRuntime.computeSha256Hmac(key, stringToSign, encoding);
-}
-/**
- * Returns a random integer value between a lower and upper bound, inclusive of both bounds. Note that this uses Math.random and isn't secure. If you need to use this for any kind of security purpose, find a better source of random.
- *
- * @param min - The smallest integer value allowed.
- *
- * @param max - The largest integer value allowed.
- */
-function esm_getRandomIntegerInclusive(min, max) {
- return tspRuntime.getRandomIntegerInclusive(min, max);
-}
-/**
- * Typeguard for an error object shape (has name and message)
- *
- * @param e - Something caught by a catch clause.
- */
-function esm_isError(e) {
- return isError(e);
-}
-/**
- * Helper to determine when an input is a generic JS object.
- *
- * @returns true when input is an object type that is not null, Array, RegExp, or Date.
- */
-function esm_isObject(input) {
- return tspRuntime.isObject(input);
-}
-/**
- * Generated Universally Unique Identifier
- *
- * @returns RFC4122 v4 UUID.
- */
-function esm_randomUUID() {
- return randomUUID();
-}
-/**
- * A constant that indicates whether the environment the code is running is a Web Browser.
- */
-const esm_isBrowser = isBrowser;
-/**
- * A constant that indicates whether the environment the code is running is Bun.sh.
- */
-const esm_isBun = isBun;
-/**
- * A constant that indicates whether the environment the code is running is Deno.
- */
-const esm_isDeno = isDeno;
-/**
- * A constant that indicates whether the environment the code is running is a Node.js compatible environment.
- *
- * @deprecated
- *
- * Use `isNodeLike` instead.
- */
-const isNode = checkEnvironment_isNodeLike;
-/**
- * A constant that indicates whether the environment the code is running is a Node.js compatible environment.
- */
-const esm_isNodeLike = checkEnvironment_isNodeLike;
-/**
- * A constant that indicates whether the environment the code is running is Node.JS.
- */
-const esm_isNodeRuntime = isNodeRuntime;
-/**
- * A constant that indicates whether the environment the code is running is in React-Native.
- */
-const esm_isReactNative = isReactNative;
-/**
- * A constant that indicates whether the environment the code is running is a Web Worker.
- */
-const esm_isWebWorker = isWebWorker;
-/**
- * The helper that transforms bytes with specific character encoding into string
- * @param bytes - the uint8array bytes
- * @param format - the format we use to encode the byte
- * @returns a string of the encoded string
- */
-function esm_uint8ArrayToString(bytes, format) {
- return tspRuntime.uint8ArrayToString(bytes, format);
-}
-/**
- * The helper that transforms string to specific character encoded bytes array.
- * @param value - the string to be converted
- * @param format - the format we use to decode the value
- * @returns a uint8array
- */
-function esm_stringToUint8Array(value, format) {
- return tspRuntime.stringToUint8Array(value, format);
-}
-//# sourceMappingURL=index.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/util/file.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-function file_isNodeReadableStream(x) {
- return Boolean(x && typeof x["pipe"] === "function");
-}
-const unimplementedMethods = {
- arrayBuffer: () => {
- throw new Error("Not implemented");
- },
- bytes: () => {
- throw new Error("Not implemented");
- },
- slice: () => {
- throw new Error("Not implemented");
- },
- text: () => {
- throw new Error("Not implemented");
- },
-};
-/**
- * Private symbol used as key on objects created using createFile containing the
- * original source of the file object.
- *
- * This is used in Node to access the original Node stream without using Blob#stream, which
- * returns a web stream. This is done to avoid a couple of bugs to do with Blob#stream and
- * Readable#to/fromWeb in Node versions we support:
- * - https://github.com/nodejs/node/issues/42694 (fixed in Node 18.14)
- * - https://github.com/nodejs/node/issues/48916 (fixed in Node 20.6)
- *
- * Once these versions are no longer supported, we may be able to stop doing this.
- *
- * @internal
- */
-const rawContent = Symbol("rawContent");
-/**
- * Type guard to check if a given object is a blob-like object with a raw content property.
- */
-function hasRawContent(x) {
- return typeof x[rawContent] === "function";
-}
-/**
- * Extract the raw content from a given blob-like object. If the input was created using createFile
- * or createFileFromStream, the exact content passed into createFile/createFileFromStream will be used.
- * For true instances of Blob and File, returns the actual blob.
- *
- * @internal
- */
-function getRawContent(blob) {
- if (hasRawContent(blob)) {
- return blob[rawContent]();
- }
- else {
- return blob;
- }
-}
-/**
- * Create an object that implements the File interface. This object is intended to be
- * passed into RequestBodyType.formData, and is not guaranteed to work as expected in
- * other situations.
- *
- * Use this function to:
- * - Create a File object for use in RequestBodyType.formData in environments where the
- * global File object is unavailable.
- * - Create a File-like object from a readable stream without reading the stream into memory.
- *
- * @param stream - the content of the file as a callback returning a stream. When a File object made using createFile is
- * passed in a request's form data map, the stream will not be read into memory
- * and instead will be streamed when the request is made. In the event of a retry, the
- * stream needs to be read again, so this callback SHOULD return a fresh stream if possible.
- * @param name - the name of the file.
- * @param options - optional metadata about the file, e.g. file name, file size, MIME type.
- */
-function createFileFromStream(stream, name, options = {}) {
- return {
- ...unimplementedMethods,
- type: options.type ?? "",
- lastModified: options.lastModified ?? new Date().getTime(),
- webkitRelativePath: options.webkitRelativePath ?? "",
- size: options.size ?? -1,
- name,
- stream: () => {
- const s = stream();
- if (file_isNodeReadableStream(s)) {
- throw new Error("Not supported: a Node stream was provided as input to createFileFromStream.");
- }
- return s;
- },
- [rawContent]: stream,
- };
-}
-/**
- * Create an object that implements the File interface. This object is intended to be
- * passed into RequestBodyType.formData, and is not guaranteed to work as expected in
- * other situations.
- *
- * Use this function create a File object for use in RequestBodyType.formData in environments where the global File object is unavailable.
- *
- * @param content - the content of the file as a Uint8Array in memory.
- * @param name - the name of the file.
- * @param options - optional metadata about the file, e.g. file name, file size, MIME type.
- */
-function createFile(content, name, options = {}) {
- if (isNodeLike) {
- return {
- ...unimplementedMethods,
- type: options.type ?? "",
- lastModified: options.lastModified ?? new Date().getTime(),
- webkitRelativePath: options.webkitRelativePath ?? "",
- size: content.byteLength,
- name,
- arrayBuffer: async () => content.buffer,
- stream: () => new Blob([toArrayBuffer(content)]).stream(),
- [rawContent]: () => content,
- };
- }
- else {
- return new File([toArrayBuffer(content)], name, options);
- }
-}
-function toArrayBuffer(source) {
- if ("resize" in source.buffer) {
- // ArrayBuffer
- return source;
- }
- // SharedArrayBuffer
- return source.map((x) => x);
-}
-//# sourceMappingURL=file.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/policies/multipartPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-/**
- * Name of multipart policy
- */
-const policies_multipartPolicy_multipartPolicyName = multipartPolicy_multipartPolicyName;
-/**
- * Pipeline policy for multipart requests
- */
-function policies_multipartPolicy_multipartPolicy() {
- const tspPolicy = multipartPolicy_multipartPolicy();
- return {
- name: policies_multipartPolicy_multipartPolicyName,
- sendRequest: async (request, next) => {
- if (request.multipartBody) {
- for (const part of request.multipartBody.parts) {
- if (hasRawContent(part.body)) {
- part.body = getRawContent(part.body);
- }
- }
- }
- return tspPolicy.sendRequest(request, next);
- },
- };
-}
-//# sourceMappingURL=multipartPolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/policies/decompressResponsePolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-/**
- * The programmatic identifier of the decompressResponsePolicy.
- */
-const decompressResponsePolicy_decompressResponsePolicyName = decompressResponsePolicyName;
-/**
- * A policy to enable response decompression according to Accept-Encoding header
- * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding
- */
-function policies_decompressResponsePolicy_decompressResponsePolicy() {
- return decompressResponsePolicy_decompressResponsePolicy();
-}
-//# sourceMappingURL=decompressResponsePolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/policies/defaultRetryPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-/**
- * Name of the {@link defaultRetryPolicy}
- */
-const defaultRetryPolicy_defaultRetryPolicyName = (/* unused pure expression or super */ null && (tspDefaultRetryPolicyName));
-/**
- * A policy that retries according to three strategies:
- * - When the server sends a 429 response with a Retry-After header.
- * - When there are errors in the underlying transport layer (e.g. DNS lookup failures).
- * - Or otherwise if the outgoing request fails, it will retry with an exponentially increasing delay.
- */
-function policies_defaultRetryPolicy_defaultRetryPolicy(options = {}) {
- return defaultRetryPolicy_defaultRetryPolicy(options);
-}
-//# sourceMappingURL=defaultRetryPolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/policies/formDataPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-/**
- * The programmatic identifier of the formDataPolicy.
- */
-const formDataPolicy_formDataPolicyName = (/* unused pure expression or super */ null && (tspFormDataPolicyName));
-/**
- * A policy that encodes FormData on the request into the body.
- */
-function policies_formDataPolicy_formDataPolicy() {
- return formDataPolicy_formDataPolicy();
-}
-//# sourceMappingURL=formDataPolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/policies/proxyPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-/**
- * The programmatic identifier of the proxyPolicy.
- */
-const proxyPolicy_proxyPolicyName = (/* unused pure expression or super */ null && (tspProxyPolicyName));
-/**
- * This method converts a proxy url into `ProxySettings` for use with ProxyPolicy.
- * If no argument is given, it attempts to parse a proxy URL from the environment
- * variables `HTTPS_PROXY` or `HTTP_PROXY`.
- * @param proxyUrl - The url of the proxy to use. May contain authentication information.
- * @deprecated - Internally this method is no longer necessary when setting proxy information.
- */
-function proxyPolicy_getDefaultProxySettings(proxyUrl) {
- return getDefaultProxySettings(proxyUrl);
-}
-/**
- * A policy that allows one to apply proxy settings to all requests.
- * If not passed static settings, they will be retrieved from the HTTPS_PROXY
- * or HTTP_PROXY environment variables.
- * @param proxySettings - ProxySettings to use on each request.
- * @param options - additional settings, for example, custom NO_PROXY patterns
- */
-function policies_proxyPolicy_proxyPolicy(proxySettings, options) {
- return proxyPolicy_proxyPolicy(proxySettings, options);
-}
-//# sourceMappingURL=proxyPolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/policies/setClientRequestIdPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-/**
- * The programmatic identifier of the setClientRequestIdPolicy.
- */
-const setClientRequestIdPolicyName = "setClientRequestIdPolicy";
-/**
- * Each PipelineRequest gets a unique id upon creation.
- * This policy passes that unique id along via an HTTP header to enable better
- * telemetry and tracing.
- * @param requestIdHeaderName - The name of the header to pass the request ID to.
- */
-function setClientRequestIdPolicy(requestIdHeaderName = "x-ms-client-request-id") {
- return {
- name: setClientRequestIdPolicyName,
- async sendRequest(request, next) {
- if (!request.headers.has(requestIdHeaderName)) {
- request.headers.set(requestIdHeaderName, request.requestId);
- }
- return next(request);
- },
- };
-}
-//# sourceMappingURL=setClientRequestIdPolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/policies/agentPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-/**
- * Name of the Agent Policy
- */
-const agentPolicy_agentPolicyName = (/* unused pure expression or super */ null && (tspAgentPolicyName));
-/**
- * Gets a pipeline policy that sets http.agent
- */
-function policies_agentPolicy_agentPolicy(agent) {
- return agentPolicy_agentPolicy(agent);
-}
-//# sourceMappingURL=agentPolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/policies/tlsPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-/**
- * Name of the TLS Policy
- */
-const tlsPolicy_tlsPolicyName = (/* unused pure expression or super */ null && (tspTlsPolicyName));
-/**
- * Gets a pipeline policy that adds the client certificate to the HttpClient agent for authentication.
- */
-function policies_tlsPolicy_tlsPolicy(tlsSettings) {
- return tlsPolicy_tlsPolicy(tlsSettings);
-}
-//# sourceMappingURL=tlsPolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-tracing/dist/esm/tracingContext.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-/** @internal */
-const knownContextKeys = {
- span: Symbol.for("@azure/core-tracing span"),
- namespace: Symbol.for("@azure/core-tracing namespace"),
-};
-/**
- * Creates a new {@link TracingContext} with the given options.
- * @param options - A set of known keys that may be set on the context.
- * @returns A new {@link TracingContext} with the given options.
- *
- * @internal
- */
-function createTracingContext(options = {}) {
- let context = new TracingContextImpl(options.parentContext);
- if (options.span) {
- context = context.setValue(knownContextKeys.span, options.span);
- }
- if (options.namespace) {
- context = context.setValue(knownContextKeys.namespace, options.namespace);
- }
- return context;
-}
-/** @internal */
-class TracingContextImpl {
- _contextMap;
- constructor(initialContext) {
- this._contextMap =
- initialContext instanceof TracingContextImpl
- ? new Map(initialContext._contextMap)
- : new Map();
- }
- setValue(key, value) {
- const newContext = new TracingContextImpl(this);
- newContext._contextMap.set(key, value);
- return newContext;
- }
- getValue(key) {
- return this._contextMap.get(key);
- }
- deleteValue(key) {
- const newContext = new TracingContextImpl(this);
- newContext._contextMap.delete(key);
- return newContext;
- }
-}
-//# sourceMappingURL=tracingContext.js.map
-// EXTERNAL MODULE: ./node_modules/@azure/core-tracing/dist/commonjs/state.js
-var commonjs_state = __nccwpck_require__(8914);
-;// CONCATENATED MODULE: ./node_modules/@azure/core-tracing/dist/esm/state.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-// @ts-expect-error The recommended approach to sharing module state between ESM and CJS.
-// See https://github.com/isaacs/tshy/blob/main/README.md#module-local-state for additional information.
-
-/**
- * Defines the shared state between CJS and ESM by re-exporting the CJS state.
- */
-const state_state = commonjs_state/* state */.w;
-//# sourceMappingURL=state.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-tracing/dist/esm/instrumenter.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-function createDefaultTracingSpan() {
- return {
- end: () => {
- // noop
- },
- isRecording: () => false,
- recordException: () => {
- // noop
- },
- setAttribute: () => {
- // noop
- },
- setStatus: () => {
- // noop
- },
- addEvent: () => {
- // noop
- },
- };
-}
-function createDefaultInstrumenter() {
- return {
- createRequestHeaders: () => {
- return {};
- },
- parseTraceparentHeader: () => {
- return undefined;
- },
- startSpan: (_name, spanOptions) => {
- return {
- span: createDefaultTracingSpan(),
- tracingContext: createTracingContext({ parentContext: spanOptions.tracingContext }),
- };
- },
- withContext(_context, callback, ...callbackArgs) {
- return callback(...callbackArgs);
- },
- };
-}
-/**
- * Extends the Azure SDK with support for a given instrumenter implementation.
- *
- * @param instrumenter - The instrumenter implementation to use.
- */
-function useInstrumenter(instrumenter) {
- state.instrumenterImplementation = instrumenter;
-}
-/**
- * Gets the currently set instrumenter, a No-Op instrumenter by default.
- *
- * @returns The currently set instrumenter
- */
-function getInstrumenter() {
- if (!state_state.instrumenterImplementation) {
- state_state.instrumenterImplementation = createDefaultInstrumenter();
- }
- return state_state.instrumenterImplementation;
-}
-//# sourceMappingURL=instrumenter.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-tracing/dist/esm/tracingClient.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-/**
- * Creates a new tracing client.
- *
- * @param options - Options used to configure the tracing client.
- * @returns - An instance of {@link TracingClient}.
- */
-function createTracingClient(options) {
- const { namespace, packageName, packageVersion } = options;
- function startSpan(name, operationOptions, spanOptions) {
- const startSpanResult = getInstrumenter().startSpan(name, {
- ...spanOptions,
- packageName: packageName,
- packageVersion: packageVersion,
- tracingContext: operationOptions?.tracingOptions?.tracingContext,
- });
- let tracingContext = startSpanResult.tracingContext;
- const span = startSpanResult.span;
- if (!tracingContext.getValue(knownContextKeys.namespace)) {
- tracingContext = tracingContext.setValue(knownContextKeys.namespace, namespace);
- }
- span.setAttribute("az.namespace", tracingContext.getValue(knownContextKeys.namespace));
- const updatedOptions = Object.assign({}, operationOptions, {
- tracingOptions: { ...operationOptions?.tracingOptions, tracingContext },
- });
- return {
- span,
- updatedOptions,
- };
- }
- async function withSpan(name, operationOptions, callback, spanOptions) {
- const { span, updatedOptions } = startSpan(name, operationOptions, spanOptions);
- try {
- const result = await withContext(updatedOptions.tracingOptions.tracingContext, () => Promise.resolve(callback(updatedOptions, span)));
- span.setStatus({ status: "success" });
- return result;
- }
- catch (err) {
- span.setStatus({ status: "error", error: err });
- throw err;
- }
- finally {
- span.end();
- }
- }
- function withContext(context, callback, ...callbackArgs) {
- return getInstrumenter().withContext(context, callback, ...callbackArgs);
- }
- /**
- * Parses a traceparent header value into a span identifier.
- *
- * @param traceparentHeader - The traceparent header to parse.
- * @returns An implementation-specific identifier for the span.
- */
- function parseTraceparentHeader(traceparentHeader) {
- return getInstrumenter().parseTraceparentHeader(traceparentHeader);
- }
- /**
- * Creates a set of request headers to propagate tracing information to a backend.
- *
- * @param tracingContext - The context containing the span to serialize.
- * @returns The set of headers to add to a request.
- */
- function createRequestHeaders(tracingContext) {
- return getInstrumenter().createRequestHeaders(tracingContext);
- }
- return {
- startSpan,
- withSpan,
- withContext,
- parseTraceparentHeader,
- createRequestHeaders,
- };
-}
-//# sourceMappingURL=tracingClient.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-tracing/dist/esm/index.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-//# sourceMappingURL=index.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/restError.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-/**
- * A custom error type for failed pipeline requests.
- */
-// eslint-disable-next-line @typescript-eslint/no-redeclare
-const esm_restError_RestError = restError_RestError;
-/**
- * Typeguard for RestError
- * @param e - Something caught by a catch clause.
- */
-function esm_restError_isRestError(e) {
- return restError_isRestError(e);
-}
-//# sourceMappingURL=restError.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/policies/tracingPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-
-
-
-
-
-/**
- * The programmatic identifier of the tracingPolicy.
- */
-const tracingPolicyName = "tracingPolicy";
-/**
- * A simple policy to create OpenTelemetry Spans for each request made by the pipeline
- * that has SpanOptions with a parent.
- * Requests made without a parent Span will not be recorded.
- * @param options - Options to configure the telemetry logged by the tracing policy.
- */
-function tracingPolicy(options = {}) {
- const userAgentPromise = util_userAgent_getUserAgentValue(options.userAgentPrefix);
- const sanitizer = new Sanitizer({
- additionalAllowedQueryParameters: options.additionalAllowedQueryParameters,
- });
- const tracingClient = tryCreateTracingClient();
- return {
- name: tracingPolicyName,
- async sendRequest(request, next) {
- if (!tracingClient) {
- return next(request);
- }
- const userAgent = await userAgentPromise;
- const spanAttributes = {
- "http.url": sanitizer.sanitizeUrl(request.url),
- "http.method": request.method,
- "http.user_agent": userAgent,
- requestId: request.requestId,
- };
- if (userAgent) {
- spanAttributes["http.user_agent"] = userAgent;
- }
- const { span, tracingContext } = tryCreateSpan(tracingClient, request, spanAttributes) ?? {};
- if (!span || !tracingContext) {
- return next(request);
- }
- try {
- const response = await tracingClient.withContext(tracingContext, next, request);
- tryProcessResponse(span, response);
- return response;
- }
- catch (err) {
- tryProcessError(span, err);
- throw err;
- }
- },
- };
-}
-function tryCreateTracingClient() {
- try {
- return createTracingClient({
- namespace: "",
- packageName: "@azure/core-rest-pipeline",
- packageVersion: esm_constants_SDK_VERSION,
- });
- }
- catch (e) {
- esm_log_logger.warning(`Error when creating the TracingClient: ${getErrorMessage(e)}`);
- return undefined;
- }
-}
-function tryCreateSpan(tracingClient, request, spanAttributes) {
- try {
- // As per spec, we do not need to differentiate between HTTP and HTTPS in span name.
- const { span, updatedOptions } = tracingClient.startSpan(`HTTP ${request.method}`, { tracingOptions: request.tracingOptions }, {
- spanKind: "client",
- spanAttributes,
- });
- // If the span is not recording, don't do any more work.
- if (!span.isRecording()) {
- span.end();
- return undefined;
- }
- // set headers
- const headers = tracingClient.createRequestHeaders(updatedOptions.tracingOptions.tracingContext);
- for (const [key, value] of Object.entries(headers)) {
- request.headers.set(key, value);
- }
- return { span, tracingContext: updatedOptions.tracingOptions.tracingContext };
- }
- catch (e) {
- esm_log_logger.warning(`Skipping creating a tracing span due to an error: ${getErrorMessage(e)}`);
- return undefined;
- }
-}
-function tryProcessError(span, error) {
- try {
- span.setStatus({
- status: "error",
- error: esm_isError(error) ? error : undefined,
- });
- if (esm_restError_isRestError(error) && error.statusCode) {
- span.setAttribute("http.status_code", error.statusCode);
- }
- span.end();
- }
- catch (e) {
- esm_log_logger.warning(`Skipping tracing span processing due to an error: ${getErrorMessage(e)}`);
- }
-}
-function tryProcessResponse(span, response) {
- try {
- span.setAttribute("http.status_code", response.status);
- const serviceRequestId = response.headers.get("x-ms-request-id");
- if (serviceRequestId) {
- span.setAttribute("serviceRequestId", serviceRequestId);
- }
- // Per semantic conventions, only set the status to error if the status code is 4xx or 5xx.
- // Otherwise, the status MUST remain unset.
- // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
- if (response.status >= 400) {
- span.setStatus({
- status: "error",
- });
- }
- span.end();
- }
- catch (e) {
- esm_log_logger.warning(`Skipping tracing span processing due to an error: ${getErrorMessage(e)}`);
- }
-}
-//# sourceMappingURL=tracingPolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/util/wrapAbortSignal.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-/**
- * Creates a native AbortSignal which reflects the state of the provided AbortSignalLike.
- * If the AbortSignalLike is already a native AbortSignal, it is returned as is.
- * @param abortSignalLike - The AbortSignalLike to wrap.
- * @returns - An object containing the native AbortSignal and an optional cleanup function. The cleanup function should be called when the AbortSignal is no longer needed.
- */
-function wrapAbortSignalLike(abortSignalLike) {
- if (abortSignalLike instanceof AbortSignal) {
- return { abortSignal: abortSignalLike };
- }
- if (abortSignalLike.aborted) {
- return { abortSignal: AbortSignal.abort(abortSignalLike.reason) };
- }
- const controller = new AbortController();
- let needsCleanup = true;
- function cleanup() {
- if (needsCleanup) {
- abortSignalLike.removeEventListener("abort", listener);
- needsCleanup = false;
- }
- }
- function listener() {
- controller.abort(abortSignalLike.reason);
- cleanup();
- }
- abortSignalLike.addEventListener("abort", listener);
- return { abortSignal: controller.signal, cleanup };
-}
-//# sourceMappingURL=wrapAbortSignal.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/policies/wrapAbortSignalLikePolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-const wrapAbortSignalLikePolicyName = "wrapAbortSignalLikePolicy";
-/**
- * Policy that ensure that any AbortSignalLike is wrapped in a native AbortSignal for processing by the pipeline.
- * Since the ts-http-runtime expects a native AbortSignal, this policy is used to ensure that any AbortSignalLike is wrapped in a native AbortSignal.
- *
- * @returns - created policy
- */
-function wrapAbortSignalLikePolicy() {
- return {
- name: wrapAbortSignalLikePolicyName,
- sendRequest: async (request, next) => {
- if (!request.abortSignal) {
- return next(request);
- }
- const { abortSignal, cleanup } = wrapAbortSignalLike(request.abortSignal);
- request.abortSignal = abortSignal;
- try {
- return await next(request);
- }
- finally {
- cleanup?.();
- }
- },
- };
-}
-//# sourceMappingURL=wrapAbortSignalLikePolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/createPipelineFromOptions.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-/**
- * Create a new pipeline with a default set of customizable policies.
- * @param options - Options to configure a custom pipeline.
- */
-function esm_createPipelineFromOptions_createPipelineFromOptions(options) {
- const pipeline = esm_pipeline_createEmptyPipeline();
- if (esm_isNodeLike) {
- if (options.agent) {
- pipeline.addPolicy(policies_agentPolicy_agentPolicy(options.agent));
- }
- if (options.tlsOptions) {
- pipeline.addPolicy(policies_tlsPolicy_tlsPolicy(options.tlsOptions));
- }
- pipeline.addPolicy(policies_proxyPolicy_proxyPolicy(options.proxyOptions));
- pipeline.addPolicy(policies_decompressResponsePolicy_decompressResponsePolicy());
- }
- pipeline.addPolicy(wrapAbortSignalLikePolicy());
- pipeline.addPolicy(policies_formDataPolicy_formDataPolicy(), { beforePolicies: [policies_multipartPolicy_multipartPolicyName] });
- pipeline.addPolicy(policies_userAgentPolicy_userAgentPolicy(options.userAgentOptions));
- pipeline.addPolicy(setClientRequestIdPolicy(options.telemetryOptions?.clientRequestIdHeaderName));
- // The multipart policy is added after policies with no phase, so that
- // policies can be added between it and formDataPolicy to modify
- // properties (e.g., making the boundary constant in recorded tests).
- pipeline.addPolicy(policies_multipartPolicy_multipartPolicy(), { afterPhase: "Deserialize" });
- pipeline.addPolicy(policies_defaultRetryPolicy_defaultRetryPolicy(options.retryOptions), { phase: "Retry" });
- pipeline.addPolicy(tracingPolicy({ ...options.userAgentOptions, ...options.loggingOptions }), {
- afterPhase: "Retry",
- });
- if (esm_isNodeLike) {
- // Both XHR and Fetch expect to handle redirects automatically,
- // so only include this policy when we're in Node.
- pipeline.addPolicy(policies_redirectPolicy_redirectPolicy(options.redirectOptions), { afterPhase: "Retry" });
- }
- pipeline.addPolicy(policies_logPolicy_logPolicy(options.loggingOptions), { afterPhase: "Sign" });
- return pipeline;
-}
-//# sourceMappingURL=createPipelineFromOptions.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/defaultHttpClient.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-/**
- * Create the correct HttpClient for the current environment.
- */
-function esm_defaultHttpClient_createDefaultHttpClient() {
- const client = defaultHttpClient_createDefaultHttpClient();
- return {
- async sendRequest(request) {
- // we wrap any AbortSignalLike here since the TypeSpec runtime expects a native AbortSignal.
- // 99% of the time, this should be a no-op since a native AbortSignal is passed in.
- const { abortSignal, cleanup } = request.abortSignal
- ? wrapAbortSignalLike(request.abortSignal)
- : {};
- try {
- request.abortSignal = abortSignal;
- return await client.sendRequest(request);
- }
- finally {
- cleanup?.();
- }
- },
- };
-}
-//# sourceMappingURL=defaultHttpClient.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/httpHeaders.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-/**
- * Creates an object that satisfies the `HttpHeaders` interface.
- * @param rawHeaders - A simple object representing initial headers
- */
-function esm_httpHeaders_createHttpHeaders(rawHeaders) {
- return httpHeaders_createHttpHeaders(rawHeaders);
-}
-//# sourceMappingURL=httpHeaders.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/pipelineRequest.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-/**
- * Creates a new pipeline request with the given options.
- * This method is to allow for the easy setting of default values and not required.
- * @param options - The options to create the request with.
- */
-function esm_pipelineRequest_createPipelineRequest(options) {
- // Cast required due to difference between ts-http-runtime requiring AbortSignal while core-rest-pipeline allows
- // the more generic AbortSignalLike. The wrapAbortSignalLike pipeline policy will take care of ensuring that any AbortSignalLike in the request
- // is converted into a true AbortSignal.
- return pipelineRequest_createPipelineRequest(options);
-}
-//# sourceMappingURL=pipelineRequest.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/policies/exponentialRetryPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-/**
- * The programmatic identifier of the exponentialRetryPolicy.
- */
-const exponentialRetryPolicy_exponentialRetryPolicyName = (/* unused pure expression or super */ null && (tspExponentialRetryPolicyName));
-/**
- * A policy that attempts to retry requests while introducing an exponentially increasing delay.
- * @param options - Options that configure retry logic.
- */
-function exponentialRetryPolicy_exponentialRetryPolicy(options = {}) {
- return tspExponentialRetryPolicy(options);
-}
-//# sourceMappingURL=exponentialRetryPolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/policies/systemErrorRetryPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-/**
- * Name of the {@link systemErrorRetryPolicy}
- */
-const systemErrorRetryPolicy_systemErrorRetryPolicyName = (/* unused pure expression or super */ null && (tspSystemErrorRetryPolicyName));
-/**
- * A retry policy that specifically seeks to handle errors in the
- * underlying transport layer (e.g. DNS lookup failures) rather than
- * retryable error codes from the server itself.
- * @param options - Options that customize the policy.
- */
-function systemErrorRetryPolicy_systemErrorRetryPolicy(options = {}) {
- return tspSystemErrorRetryPolicy(options);
-}
-//# sourceMappingURL=systemErrorRetryPolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/policies/throttlingRetryPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-/**
- * Name of the {@link throttlingRetryPolicy}
- */
-const throttlingRetryPolicy_throttlingRetryPolicyName = (/* unused pure expression or super */ null && (tspThrottlingRetryPolicyName));
-/**
- * A policy that retries when the server sends a 429 response with a Retry-After header.
- *
- * To learn more, please refer to
- * https://learn.microsoft.com/azure/azure-resource-manager/resource-manager-request-limits,
- * https://learn.microsoft.com/azure/azure-subscription-service-limits and
- * https://learn.microsoft.com/azure/virtual-machines/troubleshooting/troubleshooting-throttling-errors
- *
- * @param options - Options that configure retry logic.
- */
-function throttlingRetryPolicy_throttlingRetryPolicy(options = {}) {
- return tspThrottlingRetryPolicy(options);
-}
-//# sourceMappingURL=throttlingRetryPolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/policies/retryPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-
-const retryPolicy_retryPolicyLogger = esm_createClientLogger("core-rest-pipeline retryPolicy");
-/**
- * retryPolicy is a generic policy to enable retrying requests when certain conditions are met
- */
-function policies_retryPolicy_retryPolicy(strategies, options = { maxRetries: DEFAULT_RETRY_POLICY_COUNT }) {
- // Cast is required since the TSP runtime retry strategy type is slightly different
- // very deep down (using real AbortSignal vs. AbortSignalLike in RestError).
- // In practice the difference doesn't actually matter.
- return tspRetryPolicy(strategies, {
- logger: retryPolicy_retryPolicyLogger,
- ...options,
- });
-}
-//# sourceMappingURL=retryPolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/util/tokenCycler.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-// Default options for the cycler if none are provided
-const DEFAULT_CYCLER_OPTIONS = {
- forcedRefreshWindowInMs: 1000, // Force waiting for a refresh 1s before the token expires
- retryIntervalInMs: 3000, // Allow refresh attempts every 3s
- refreshWindowInMs: 1000 * 60 * 2, // Start refreshing 2m before expiry
-};
-/**
- * Converts an an unreliable access token getter (which may resolve with null)
- * into an AccessTokenGetter by retrying the unreliable getter in a regular
- * interval.
- *
- * @param getAccessToken - A function that produces a promise of an access token that may fail by returning null.
- * @param retryIntervalInMs - The time (in milliseconds) to wait between retry attempts.
- * @param refreshTimeout - The timestamp after which the refresh attempt will fail, throwing an exception.
- * @returns - A promise that, if it resolves, will resolve with an access token.
- */
-async function beginRefresh(getAccessToken, retryIntervalInMs, refreshTimeout) {
- // This wrapper handles exceptions gracefully as long as we haven't exceeded
- // the timeout.
- async function tryGetAccessToken() {
- if (Date.now() < refreshTimeout) {
- try {
- return await getAccessToken();
- }
- catch {
- return null;
- }
- }
- else {
- const finalToken = await getAccessToken();
- // Timeout is up, so throw if it's still null
- if (finalToken === null) {
- throw new Error("Failed to refresh access token.");
- }
- return finalToken;
- }
- }
- let token = await tryGetAccessToken();
- while (token === null) {
- await delay_delay(retryIntervalInMs);
- token = await tryGetAccessToken();
- }
- return token;
-}
-/**
- * Creates a token cycler from a credential, scopes, and optional settings.
- *
- * A token cycler represents a way to reliably retrieve a valid access token
- * from a TokenCredential. It will handle initializing the token, refreshing it
- * when it nears expiration, and synchronizes refresh attempts to avoid
- * concurrency hazards.
- *
- * @param credential - the underlying TokenCredential that provides the access
- * token
- * @param tokenCyclerOptions - optionally override default settings for the cycler
- *
- * @returns - a function that reliably produces a valid access token
- */
-function tokenCycler_createTokenCycler(credential, tokenCyclerOptions) {
- let refreshWorker = null;
- let token = null;
- let tenantId;
- const options = {
- ...DEFAULT_CYCLER_OPTIONS,
- ...tokenCyclerOptions,
- };
- /**
- * This little holder defines several predicates that we use to construct
- * the rules of refreshing the token.
- */
- const cycler = {
- /**
- * Produces true if a refresh job is currently in progress.
- */
- get isRefreshing() {
- return refreshWorker !== null;
- },
- /**
- * Produces true if the cycler SHOULD refresh (we are within the refresh
- * window and not already refreshing)
- */
- get shouldRefresh() {
- if (cycler.isRefreshing) {
- return false;
- }
- if (token?.refreshAfterTimestamp && token.refreshAfterTimestamp < Date.now()) {
- return true;
- }
- return (token?.expiresOnTimestamp ?? 0) - options.refreshWindowInMs < Date.now();
- },
- /**
- * Produces true if the cycler MUST refresh (null or nearly-expired
- * token).
- */
- get mustRefresh() {
- return (token === null || token.expiresOnTimestamp - options.forcedRefreshWindowInMs < Date.now());
- },
- };
- /**
- * Starts a refresh job or returns the existing job if one is already
- * running.
- */
- function refresh(scopes, getTokenOptions) {
- if (!cycler.isRefreshing) {
- // We bind `scopes` here to avoid passing it around a lot
- const tryGetAccessToken = () => credential.getToken(scopes, getTokenOptions);
- // Take advantage of promise chaining to insert an assignment to `token`
- // before the refresh can be considered done.
- refreshWorker = beginRefresh(tryGetAccessToken, options.retryIntervalInMs,
- // If we don't have a token, then we should timeout immediately
- token?.expiresOnTimestamp ?? Date.now())
- .then((_token) => {
- refreshWorker = null;
- token = _token;
- tenantId = getTokenOptions.tenantId;
- return token;
- })
- .catch((reason) => {
- // We also should reset the refresher if we enter a failed state. All
- // existing awaiters will throw, but subsequent requests will start a
- // new retry chain.
- refreshWorker = null;
- token = null;
- tenantId = undefined;
- throw reason;
- });
- }
- return refreshWorker;
- }
- return async (scopes, tokenOptions) => {
- //
- // Simple rules:
- // - If we MUST refresh, then return the refresh task, blocking
- // the pipeline until a token is available.
- // - If we SHOULD refresh, then run refresh but don't return it
- // (we can still use the cached token).
- // - Return the token, since it's fine if we didn't return in
- // step 1.
- //
- const hasClaimChallenge = Boolean(tokenOptions.claims);
- const tenantIdChanged = tenantId !== tokenOptions.tenantId;
- if (hasClaimChallenge) {
- // If we've received a claim, we know the existing token isn't valid
- // We want to clear it so that that refresh worker won't use the old expiration time as a timeout
- token = null;
- }
- // If the tenantId passed in token options is different to the one we have
- // Or if we are in claim challenge and the token was rejected and a new access token need to be issued, we need to
- // refresh the token with the new tenantId or token.
- const mustRefresh = tenantIdChanged || hasClaimChallenge || cycler.mustRefresh;
- if (mustRefresh) {
- return refresh(scopes, tokenOptions);
- }
- if (cycler.shouldRefresh) {
- refresh(scopes, tokenOptions);
- }
- return token;
- };
-}
-//# sourceMappingURL=tokenCycler.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/policies/bearerTokenAuthenticationPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-
-/**
- * The programmatic identifier of the bearerTokenAuthenticationPolicy.
- */
-const bearerTokenAuthenticationPolicyName = "bearerTokenAuthenticationPolicy";
-/**
- * Try to send the given request.
- *
- * When a response is received, returns a tuple of the response received and, if the response was received
- * inside a thrown RestError, the RestError that was thrown.
- *
- * Otherwise, if an error was thrown while sending the request that did not provide an underlying response, it
- * will be rethrown.
- */
-async function trySendRequest(request, next) {
- try {
- return [await next(request), undefined];
- }
- catch (e) {
- if (esm_restError_isRestError(e) && e.response) {
- return [e.response, e];
- }
- else {
- throw e;
- }
- }
-}
-/**
- * Default authorize request handler
- */
-async function defaultAuthorizeRequest(options) {
- const { scopes, getAccessToken, request } = options;
- // Enable CAE true by default
- const getTokenOptions = {
- abortSignal: request.abortSignal,
- tracingOptions: request.tracingOptions,
- enableCae: true,
- };
- const accessToken = await getAccessToken(scopes, getTokenOptions);
- if (accessToken) {
- options.request.headers.set("Authorization", `Bearer ${accessToken.token}`);
- }
-}
-/**
- * We will retrieve the challenge only if the response status code was 401,
- * and if the response contained the header "WWW-Authenticate" with a non-empty value.
- */
-function isChallengeResponse(response) {
- return response.status === 401 && response.headers.has("WWW-Authenticate");
-}
-/**
- * Re-authorize the request for CAE challenge.
- * The response containing the challenge is `options.response`.
- * If this method returns true, the underlying request will be sent once again.
- */
-async function authorizeRequestOnCaeChallenge(onChallengeOptions, caeClaims) {
- const { scopes } = onChallengeOptions;
- const accessToken = await onChallengeOptions.getAccessToken(scopes, {
- enableCae: true,
- claims: caeClaims,
- });
- if (!accessToken) {
- return false;
- }
- onChallengeOptions.request.headers.set("Authorization", `${accessToken.tokenType ?? "Bearer"} ${accessToken.token}`);
- return true;
-}
-/**
- * A policy that can request a token from a TokenCredential implementation and
- * then apply it to the Authorization header of a request as a Bearer token.
- */
-function bearerTokenAuthenticationPolicy(options) {
- const { credential, scopes, challengeCallbacks } = options;
- const logger = options.logger || esm_log_logger;
- const callbacks = {
- authorizeRequest: challengeCallbacks?.authorizeRequest?.bind(challengeCallbacks) ?? defaultAuthorizeRequest,
- authorizeRequestOnChallenge: challengeCallbacks?.authorizeRequestOnChallenge?.bind(challengeCallbacks),
- };
- // This function encapsulates the entire process of reliably retrieving the token
- // The options are left out of the public API until there's demand to configure this.
- // Remember to extend `BearerTokenAuthenticationPolicyOptions` with `TokenCyclerOptions`
- // in order to pass through the `options` object.
- const getAccessToken = credential
- ? tokenCycler_createTokenCycler(credential /* , options */)
- : () => Promise.resolve(null);
- return {
- name: bearerTokenAuthenticationPolicyName,
- /**
- * If there's no challenge parameter:
- * - It will try to retrieve the token using the cache, or the credential's getToken.
- * - Then it will try the next policy with or without the retrieved token.
- *
- * It uses the challenge parameters to:
- * - Skip a first attempt to get the token from the credential if there's no cached token,
- * since it expects the token to be retrievable only after the challenge.
- * - Prepare the outgoing request if the `prepareRequest` method has been provided.
- * - Send an initial request to receive the challenge if it fails.
- * - Process a challenge if the response contains it.
- * - Retrieve a token with the challenge information, then re-send the request.
- */
- async sendRequest(request, next) {
- if (!request.url.toLowerCase().startsWith("https://")) {
- throw new Error("Bearer token authentication is not permitted for non-TLS protected (non-https) URLs.");
- }
- await callbacks.authorizeRequest({
- scopes: Array.isArray(scopes) ? scopes : [scopes],
- request,
- getAccessToken,
- logger,
- });
- let response;
- let error;
- let shouldSendRequest;
- [response, error] = await trySendRequest(request, next);
- if (isChallengeResponse(response)) {
- let claims = getCaeChallengeClaims(response.headers.get("WWW-Authenticate"));
- // Handle CAE by default when receive CAE claim
- if (claims) {
- let parsedClaim;
- // Return the response immediately if claims is not a valid base64 encoded string
- try {
- parsedClaim = atob(claims);
- }
- catch (e) {
- logger.warning(`The WWW-Authenticate header contains "claims" that cannot be parsed. Unable to perform the Continuous Access Evaluation authentication flow. Unparsable claims: ${claims}`);
- return response;
- }
- shouldSendRequest = await authorizeRequestOnCaeChallenge({
- scopes: Array.isArray(scopes) ? scopes : [scopes],
- response,
- request,
- getAccessToken,
- logger,
- }, parsedClaim);
- // Send updated request and handle response for RestError
- if (shouldSendRequest) {
- [response, error] = await trySendRequest(request, next);
- }
- }
- else if (callbacks.authorizeRequestOnChallenge) {
- // Handle custom challenges when client provides custom callback
- shouldSendRequest = await callbacks.authorizeRequestOnChallenge({
- scopes: Array.isArray(scopes) ? scopes : [scopes],
- request,
- response,
- getAccessToken,
- logger,
- });
- // Send updated request and handle response for RestError
- if (shouldSendRequest) {
- [response, error] = await trySendRequest(request, next);
- }
- // If we get another CAE Claim, we will handle it by default and return whatever value we receive for this
- if (isChallengeResponse(response)) {
- claims = getCaeChallengeClaims(response.headers.get("WWW-Authenticate"));
- if (claims) {
- let parsedClaim;
- try {
- parsedClaim = atob(claims);
- }
- catch (e) {
- logger.warning(`The WWW-Authenticate header contains "claims" that cannot be parsed. Unable to perform the Continuous Access Evaluation authentication flow. Unparsable claims: ${claims}`);
- return response;
- }
- shouldSendRequest = await authorizeRequestOnCaeChallenge({
- scopes: Array.isArray(scopes) ? scopes : [scopes],
- response,
- request,
- getAccessToken,
- logger,
- }, parsedClaim);
- // Send updated request and handle response for RestError
- if (shouldSendRequest) {
- [response, error] = await trySendRequest(request, next);
- }
- }
- }
- }
- }
- if (error) {
- throw error;
- }
- else {
- return response;
- }
- },
- };
-}
-/**
- * Converts: `Bearer a="b", c="d", Pop e="f", g="h"`.
- * Into: `[ { scheme: 'Bearer', params: { a: 'b', c: 'd' } }, { scheme: 'Pop', params: { e: 'f', g: 'h' } } ]`.
- *
- * @internal
- */
-function parseChallenges(challenges) {
- // Challenge regex seperates the string to individual challenges with different schemes in the format `Scheme a="b", c=d`
- // The challenge regex captures parameteres with either quotes values or unquoted values
- const challengeRegex = /(\w+)\s+((?:\w+=(?:"[^"]*"|[^,]*),?\s*)+)/g;
- // Parameter regex captures the claims group removed from the scheme in the format `a="b"` and `c="d"`
- // CAE challenge always have quoted parameters. For more reference, https://learn.microsoft.com/entra/identity-platform/claims-challenge
- const paramRegex = /(\w+)="([^"]*)"/g;
- const parsedChallenges = [];
- let match;
- // Iterate over each challenge match
- while ((match = challengeRegex.exec(challenges)) !== null) {
- const scheme = match[1];
- const paramsString = match[2];
- const params = {};
- let paramMatch;
- // Iterate over each parameter match
- while ((paramMatch = paramRegex.exec(paramsString)) !== null) {
- params[paramMatch[1]] = paramMatch[2];
- }
- parsedChallenges.push({ scheme, params });
- }
- return parsedChallenges;
-}
-/**
- * Parse a pipeline response and look for a CAE challenge with "Bearer" scheme
- * Return the value in the header without parsing the challenge
- * @internal
- */
-function getCaeChallengeClaims(challenges) {
- if (!challenges) {
- return;
- }
- // Find all challenges present in the header
- const parsedChallenges = parseChallenges(challenges);
- return parsedChallenges.find((x) => x.scheme === "Bearer" && x.params.claims && x.params.error === "insufficient_claims")?.params.claims;
-}
-//# sourceMappingURL=bearerTokenAuthenticationPolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/policies/auxiliaryAuthenticationHeaderPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-/**
- * The programmatic identifier of the auxiliaryAuthenticationHeaderPolicy.
- */
-const auxiliaryAuthenticationHeaderPolicyName = "auxiliaryAuthenticationHeaderPolicy";
-const AUTHORIZATION_AUXILIARY_HEADER = "x-ms-authorization-auxiliary";
-async function sendAuthorizeRequest(options) {
- const { scopes, getAccessToken, request } = options;
- const getTokenOptions = {
- abortSignal: request.abortSignal,
- tracingOptions: request.tracingOptions,
- };
- return (await getAccessToken(scopes, getTokenOptions))?.token ?? "";
-}
-/**
- * A policy for external tokens to `x-ms-authorization-auxiliary` header.
- * This header will be used when creating a cross-tenant application we may need to handle authentication requests
- * for resources that are in different tenants.
- * You could see [ARM docs](https://learn.microsoft.com/azure/azure-resource-manager/management/authenticate-multi-tenant) for a rundown of how this feature works
- */
-function auxiliaryAuthenticationHeaderPolicy(options) {
- const { credentials, scopes } = options;
- const logger = options.logger || coreLogger;
- const tokenCyclerMap = new WeakMap();
- return {
- name: auxiliaryAuthenticationHeaderPolicyName,
- async sendRequest(request, next) {
- if (!request.url.toLowerCase().startsWith("https://")) {
- throw new Error("Bearer token authentication for auxiliary header is not permitted for non-TLS protected (non-https) URLs.");
- }
- if (!credentials || credentials.length === 0) {
- logger.info(`${auxiliaryAuthenticationHeaderPolicyName} header will not be set due to empty credentials.`);
- return next(request);
- }
- const tokenPromises = [];
- for (const credential of credentials) {
- let getAccessToken = tokenCyclerMap.get(credential);
- if (!getAccessToken) {
- getAccessToken = createTokenCycler(credential);
- tokenCyclerMap.set(credential, getAccessToken);
- }
- tokenPromises.push(sendAuthorizeRequest({
- scopes: Array.isArray(scopes) ? scopes : [scopes],
- request,
- getAccessToken,
- logger,
- }));
- }
- const auxiliaryTokens = (await Promise.all(tokenPromises)).filter((token) => Boolean(token));
- if (auxiliaryTokens.length === 0) {
- logger.warning(`None of the auxiliary tokens are valid. ${AUTHORIZATION_AUXILIARY_HEADER} header will not be set.`);
- return next(request);
- }
- request.headers.set(AUTHORIZATION_AUXILIARY_HEADER, auxiliaryTokens.map((token) => `Bearer ${token}`).join(", "));
- return next(request);
- },
- };
-}
-//# sourceMappingURL=auxiliaryAuthenticationHeaderPolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-rest-pipeline/dist/esm/index.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-//# sourceMappingURL=index.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-auth/dist/esm/keyCredential.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-/**
- * Tests an object to determine whether it implements KeyCredential.
- *
- * @param credential - The assumed KeyCredential to be tested.
- */
-function isKeyCredential(credential) {
- return isObjectWithProperties(credential, ["key"]) && typeof credential.key === "string";
-}
-//# sourceMappingURL=keyCredential.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-auth/dist/esm/azureNamedKeyCredential.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-/**
- * A static name/key-based credential that supports updating
- * the underlying name and key values.
- */
-class AzureNamedKeyCredential {
- _key;
- _name;
- /**
- * The value of the key to be used in authentication.
- */
- get key() {
- return this._key;
- }
- /**
- * The value of the name to be used in authentication.
- */
- get name() {
- return this._name;
- }
- /**
- * Create an instance of an AzureNamedKeyCredential for use
- * with a service client.
- *
- * @param name - The initial value of the name to use in authentication.
- * @param key - The initial value of the key to use in authentication.
- */
- constructor(name, key) {
- if (!name || !key) {
- throw new TypeError("name and key must be non-empty strings");
- }
- this._name = name;
- this._key = key;
- }
- /**
- * Change the value of the key.
- *
- * Updates will take effect upon the next request after
- * updating the key value.
- *
- * @param newName - The new name value to be used.
- * @param newKey - The new key value to be used.
- */
- update(newName, newKey) {
- if (!newName || !newKey) {
- throw new TypeError("newName and newKey must be non-empty strings");
- }
- this._name = newName;
- this._key = newKey;
- }
-}
-/**
- * Tests an object to determine whether it implements NamedKeyCredential.
- *
- * @param credential - The assumed NamedKeyCredential to be tested.
- */
-function isNamedKeyCredential(credential) {
- return (isObjectWithProperties(credential, ["name", "key"]) &&
- typeof credential.key === "string" &&
- typeof credential.name === "string");
-}
-//# sourceMappingURL=azureNamedKeyCredential.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-auth/dist/esm/azureSASCredential.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-/**
- * A static-signature-based credential that supports updating
- * the underlying signature value.
- */
-class AzureSASCredential {
- _signature;
- /**
- * The value of the shared access signature to be used in authentication
- */
- get signature() {
- return this._signature;
- }
- /**
- * Create an instance of an AzureSASCredential for use
- * with a service client.
- *
- * @param signature - The initial value of the shared access signature to use in authentication
- */
- constructor(signature) {
- if (!signature) {
- throw new Error("shared access signature must be a non-empty string");
- }
- this._signature = signature;
- }
- /**
- * Change the value of the signature.
- *
- * Updates will take effect upon the next request after
- * updating the signature value.
- *
- * @param newSignature - The new shared access signature value to be used
- */
- update(newSignature) {
- if (!newSignature) {
- throw new Error("shared access signature must be a non-empty string");
- }
- this._signature = newSignature;
- }
-}
-/**
- * Tests an object to determine whether it implements SASCredential.
- *
- * @param credential - The assumed SASCredential to be tested.
- */
-function isSASCredential(credential) {
- return (isObjectWithProperties(credential, ["signature"]) && typeof credential.signature === "string");
-}
-//# sourceMappingURL=azureSASCredential.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-auth/dist/esm/tokenCredential.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-/**
- * @internal
- * @param accessToken - Access token
- * @returns Whether a token is bearer type or not
- */
-function isBearerToken(accessToken) {
- return !accessToken.tokenType || accessToken.tokenType === "Bearer";
-}
-/**
- * @internal
- * @param accessToken - Access token
- * @returns Whether a token is Pop token or not
- */
-function isPopToken(accessToken) {
- return accessToken.tokenType === "pop";
-}
-/**
- * Tests an object to determine whether it implements TokenCredential.
- *
- * @param credential - The assumed TokenCredential to be tested.
- */
-function isTokenCredential(credential) {
- // Check for an object with a 'getToken' function and possibly with
- // a 'signRequest' function. We do this check to make sure that
- // a ServiceClientCredentials implementor (like TokenClientCredentials
- // in ms-rest-nodeauth) doesn't get mistaken for a TokenCredential if
- // it doesn't actually implement TokenCredential also.
- const castCredential = credential;
- return (castCredential &&
- typeof castCredential.getToken === "function" &&
- (castCredential.signRequest === undefined || castCredential.getToken.length > 0));
-}
-//# sourceMappingURL=tokenCredential.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-auth/dist/esm/index.js
-
-
-
-
-
-//# sourceMappingURL=index.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-http-compat/dist/esm/policies/disableKeepAlivePolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-const disableKeepAlivePolicyName = "DisableKeepAlivePolicy";
-function createDisableKeepAlivePolicy() {
- return {
- name: disableKeepAlivePolicyName,
- async sendRequest(request, next) {
- request.disableKeepAlive = true;
- return next(request);
- },
- };
-}
-/**
- * @internal
- */
-function pipelineContainsDisableKeepAlivePolicy(pipeline) {
- return pipeline.getOrderedPolicies().some((policy) => policy.name === disableKeepAlivePolicyName);
-}
-//# sourceMappingURL=disableKeepAlivePolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-client/dist/esm/base64.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-/**
- * Encodes a string in base64 format.
- * @param value - the string to encode
- * @internal
- */
-function encodeString(value) {
- return Buffer.from(value).toString("base64");
-}
-/**
- * Encodes a byte array in base64 format.
- * @param value - the Uint8Aray to encode
- * @internal
- */
-function encodeByteArray(value) {
- const bufferValue = value instanceof Buffer ? value : Buffer.from(value.buffer);
- return bufferValue.toString("base64");
-}
-/**
- * Decodes a base64 string into a byte array.
- * @param value - the base64 string to decode
- * @internal
- */
-function decodeString(value) {
- return Buffer.from(value, "base64");
-}
-/**
- * Decodes a base64 string into a string.
- * @param value - the base64 string to decode
- * @internal
- */
-function base64_decodeStringToString(value) {
- return Buffer.from(value, "base64").toString();
-}
-//# sourceMappingURL=base64.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-client/dist/esm/interfaces.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-/**
- * Default key used to access the XML attributes.
- */
-const XML_ATTRKEY = "$";
-/**
- * Default key used to access the XML value content.
- */
-const XML_CHARKEY = "_";
-//# sourceMappingURL=interfaces.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-client/dist/esm/utils.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-/**
- * A type guard for a primitive response body.
- * @param value - Value to test
- *
- * @internal
- */
-function isPrimitiveBody(value, mapperTypeName) {
- return (mapperTypeName !== "Composite" &&
- mapperTypeName !== "Dictionary" &&
- (typeof value === "string" ||
- typeof value === "number" ||
- typeof value === "boolean" ||
- mapperTypeName?.match(/^(Date|DateTime|DateTimeRfc1123|UnixTime|ByteArray|Base64Url)$/i) !==
- null ||
- value === undefined ||
- value === null));
-}
-const validateISODuration = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;
-/**
- * Returns true if the given string is in ISO 8601 format.
- * @param value - The value to be validated for ISO 8601 duration format.
- * @internal
- */
-function isDuration(value) {
- return validateISODuration.test(value);
-}
-const validUuidRegex = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/i;
-/**
- * Returns true if the provided uuid is valid.
- *
- * @param uuid - The uuid that needs to be validated.
- *
- * @internal
- */
-function isValidUuid(uuid) {
- return validUuidRegex.test(uuid);
-}
-/**
- * Maps the response as follows:
- * - wraps the response body if needed (typically if its type is primitive).
- * - returns null if the combination of the headers and the body is empty.
- * - otherwise, returns the combination of the headers and the body.
- *
- * @param responseObject - a representation of the parsed response
- * @returns the response that will be returned to the user which can be null and/or wrapped
- *
- * @internal
- */
-function handleNullableResponseAndWrappableBody(responseObject) {
- const combinedHeadersAndBody = {
- ...responseObject.headers,
- ...responseObject.body,
- };
- if (responseObject.hasNullableType &&
- Object.getOwnPropertyNames(combinedHeadersAndBody).length === 0) {
- return responseObject.shouldWrapBody ? { body: null } : null;
- }
- else {
- return responseObject.shouldWrapBody
- ? {
- ...responseObject.headers,
- body: responseObject.body,
- }
- : combinedHeadersAndBody;
- }
-}
-/**
- * Take a `FullOperationResponse` and turn it into a flat
- * response object to hand back to the consumer.
- * @param fullResponse - The processed response from the operation request
- * @param responseSpec - The response map from the OperationSpec
- *
- * @internal
- */
-function flattenResponse(fullResponse, responseSpec) {
- const parsedHeaders = fullResponse.parsedHeaders;
- // head methods never have a body, but we return a boolean set to body property
- // to indicate presence/absence of the resource
- if (fullResponse.request.method === "HEAD") {
- return {
- ...parsedHeaders,
- body: fullResponse.parsedBody,
- };
- }
- const bodyMapper = responseSpec && responseSpec.bodyMapper;
- const isNullable = Boolean(bodyMapper?.nullable);
- const expectedBodyTypeName = bodyMapper?.type.name;
- /** If the body is asked for, we look at the expected body type to handle it */
- if (expectedBodyTypeName === "Stream") {
- return {
- ...parsedHeaders,
- blobBody: fullResponse.blobBody,
- readableStreamBody: fullResponse.readableStreamBody,
- };
- }
- const modelProperties = (expectedBodyTypeName === "Composite" &&
- bodyMapper.type.modelProperties) ||
- {};
- const isPageableResponse = Object.keys(modelProperties).some((k) => modelProperties[k].serializedName === "");
- if (expectedBodyTypeName === "Sequence" || isPageableResponse) {
- const arrayResponse = fullResponse.parsedBody ?? [];
- for (const key of Object.keys(modelProperties)) {
- if (modelProperties[key].serializedName) {
- arrayResponse[key] = fullResponse.parsedBody?.[key];
- }
- }
- if (parsedHeaders) {
- for (const key of Object.keys(parsedHeaders)) {
- arrayResponse[key] = parsedHeaders[key];
- }
- }
- return isNullable &&
- !fullResponse.parsedBody &&
- !parsedHeaders &&
- Object.getOwnPropertyNames(modelProperties).length === 0
- ? null
- : arrayResponse;
- }
- return handleNullableResponseAndWrappableBody({
- body: fullResponse.parsedBody,
- headers: parsedHeaders,
- hasNullableType: isNullable,
- shouldWrapBody: isPrimitiveBody(fullResponse.parsedBody, expectedBodyTypeName),
- });
-}
-//# sourceMappingURL=utils.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-client/dist/esm/serializer.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-
-class SerializerImpl {
- modelMappers;
- isXML;
- constructor(modelMappers = {}, isXML = false) {
- this.modelMappers = modelMappers;
- this.isXML = isXML;
- }
- /**
- * @deprecated Removing the constraints validation on client side.
- */
- validateConstraints(mapper, value, objectName) {
- const failValidation = (constraintName, constraintValue) => {
- throw new Error(`"${objectName}" with value "${value}" should satisfy the constraint "${constraintName}": ${constraintValue}.`);
- };
- if (mapper.constraints && value !== undefined && value !== null) {
- const { ExclusiveMaximum, ExclusiveMinimum, InclusiveMaximum, InclusiveMinimum, MaxItems, MaxLength, MinItems, MinLength, MultipleOf, Pattern, UniqueItems, } = mapper.constraints;
- if (ExclusiveMaximum !== undefined && value >= ExclusiveMaximum) {
- failValidation("ExclusiveMaximum", ExclusiveMaximum);
- }
- if (ExclusiveMinimum !== undefined && value <= ExclusiveMinimum) {
- failValidation("ExclusiveMinimum", ExclusiveMinimum);
- }
- if (InclusiveMaximum !== undefined && value > InclusiveMaximum) {
- failValidation("InclusiveMaximum", InclusiveMaximum);
- }
- if (InclusiveMinimum !== undefined && value < InclusiveMinimum) {
- failValidation("InclusiveMinimum", InclusiveMinimum);
- }
- if (MaxItems !== undefined && value.length > MaxItems) {
- failValidation("MaxItems", MaxItems);
- }
- if (MaxLength !== undefined && value.length > MaxLength) {
- failValidation("MaxLength", MaxLength);
- }
- if (MinItems !== undefined && value.length < MinItems) {
- failValidation("MinItems", MinItems);
- }
- if (MinLength !== undefined && value.length < MinLength) {
- failValidation("MinLength", MinLength);
- }
- if (MultipleOf !== undefined && value % MultipleOf !== 0) {
- failValidation("MultipleOf", MultipleOf);
- }
- if (Pattern) {
- const pattern = typeof Pattern === "string" ? new RegExp(Pattern) : Pattern;
- if (typeof value !== "string" || value.match(pattern) === null) {
- failValidation("Pattern", Pattern);
- }
- }
- if (UniqueItems &&
- value.some((item, i, ar) => ar.indexOf(item) !== i)) {
- failValidation("UniqueItems", UniqueItems);
- }
- }
- }
- /**
- * Serialize the given object based on its metadata defined in the mapper
- *
- * @param mapper - The mapper which defines the metadata of the serializable object
- *
- * @param object - A valid Javascript object to be serialized
- *
- * @param objectName - Name of the serialized object
- *
- * @param options - additional options to serialization
- *
- * @returns A valid serialized Javascript object
- */
- serialize(mapper, object, objectName, options = { xml: {} }) {
- const updatedOptions = {
- xml: {
- rootName: options.xml.rootName ?? "",
- includeRoot: options.xml.includeRoot ?? false,
- xmlCharKey: options.xml.xmlCharKey ?? XML_CHARKEY,
- },
- };
- let payload = {};
- const mapperType = mapper.type.name;
- if (!objectName) {
- objectName = mapper.serializedName;
- }
- if (mapperType.match(/^Sequence$/i) !== null) {
- payload = [];
- }
- if (mapper.isConstant) {
- object = mapper.defaultValue;
- }
- // This table of allowed values should help explain
- // the mapper.required and mapper.nullable properties.
- // X means "neither undefined or null are allowed".
- // || required
- // || true | false
- // nullable || ==========================
- // true || null | undefined/null
- // false || X | undefined
- // undefined || X | undefined/null
- const { required, nullable } = mapper;
- if (required && nullable && object === undefined) {
- throw new Error(`${objectName} cannot be undefined.`);
- }
- if (required && !nullable && (object === undefined || object === null)) {
- throw new Error(`${objectName} cannot be null or undefined.`);
- }
- if (!required && nullable === false && object === null) {
- throw new Error(`${objectName} cannot be null.`);
- }
- if (object === undefined || object === null) {
- payload = object;
- }
- else {
- if (mapperType.match(/^any$/i) !== null) {
- payload = object;
- }
- else if (mapperType.match(/^(Number|String|Boolean|Object|Stream|Uuid)$/i) !== null) {
- payload = serializeBasicTypes(mapperType, objectName, object);
- }
- else if (mapperType.match(/^Enum$/i) !== null) {
- const enumMapper = mapper;
- payload = serializeEnumType(objectName, enumMapper.type.allowedValues, object);
- }
- else if (mapperType.match(/^(Date|DateTime|TimeSpan|DateTimeRfc1123|UnixTime)$/i) !== null) {
- payload = serializeDateTypes(mapperType, object, objectName);
- }
- else if (mapperType.match(/^ByteArray$/i) !== null) {
- payload = serializeByteArrayType(objectName, object);
- }
- else if (mapperType.match(/^Base64Url$/i) !== null) {
- payload = serializeBase64UrlType(objectName, object);
- }
- else if (mapperType.match(/^Sequence$/i) !== null) {
- payload = serializeSequenceType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions);
- }
- else if (mapperType.match(/^Dictionary$/i) !== null) {
- payload = serializeDictionaryType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions);
- }
- else if (mapperType.match(/^Composite$/i) !== null) {
- payload = serializeCompositeType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions);
- }
- }
- return payload;
- }
- /**
- * Deserialize the given object based on its metadata defined in the mapper
- *
- * @param mapper - The mapper which defines the metadata of the serializable object
- *
- * @param responseBody - A valid Javascript entity to be deserialized
- *
- * @param objectName - Name of the deserialized object
- *
- * @param options - Controls behavior of XML parser and builder.
- *
- * @returns A valid deserialized Javascript object
- */
- deserialize(mapper, responseBody, objectName, options = { xml: {} }) {
- const updatedOptions = {
- xml: {
- rootName: options.xml.rootName ?? "",
- includeRoot: options.xml.includeRoot ?? false,
- xmlCharKey: options.xml.xmlCharKey ?? XML_CHARKEY,
- },
- ignoreUnknownProperties: options.ignoreUnknownProperties ?? false,
- };
- if (responseBody === undefined || responseBody === null) {
- if (this.isXML && mapper.type.name === "Sequence" && !mapper.xmlIsWrapped) {
- // Edge case for empty XML non-wrapped lists. xml2js can't distinguish
- // between the list being empty versus being missing,
- // so let's do the more user-friendly thing and return an empty list.
- responseBody = [];
- }
- // specifically check for undefined as default value can be a falsey value `0, "", false, null`
- if (mapper.defaultValue !== undefined) {
- responseBody = mapper.defaultValue;
- }
- return responseBody;
- }
- let payload;
- const mapperType = mapper.type.name;
- if (!objectName) {
- objectName = mapper.serializedName;
- }
- if (mapperType.match(/^Composite$/i) !== null) {
- payload = deserializeCompositeType(this, mapper, responseBody, objectName, updatedOptions);
- }
- else {
- if (this.isXML) {
- const xmlCharKey = updatedOptions.xml.xmlCharKey;
- /**
- * If the mapper specifies this as a non-composite type value but the responseBody contains
- * both header ("$" i.e., XML_ATTRKEY) and body ("#" i.e., XML_CHARKEY) properties,
- * then just reduce the responseBody value to the body ("#" i.e., XML_CHARKEY) property.
- */
- if (responseBody[XML_ATTRKEY] !== undefined && responseBody[xmlCharKey] !== undefined) {
- responseBody = responseBody[xmlCharKey];
- }
- }
- if (mapperType.match(/^Number$/i) !== null) {
- payload = parseFloat(responseBody);
- if (isNaN(payload)) {
- payload = responseBody;
- }
- }
- else if (mapperType.match(/^Boolean$/i) !== null) {
- if (responseBody === "true") {
- payload = true;
- }
- else if (responseBody === "false") {
- payload = false;
- }
- else {
- payload = responseBody;
- }
- }
- else if (mapperType.match(/^(String|Enum|Object|Stream|Uuid|TimeSpan|any)$/i) !== null) {
- payload = responseBody;
- }
- else if (mapperType.match(/^(Date|DateTime|DateTimeRfc1123)$/i) !== null) {
- payload = new Date(responseBody);
- }
- else if (mapperType.match(/^UnixTime$/i) !== null) {
- payload = unixTimeToDate(responseBody);
- }
- else if (mapperType.match(/^ByteArray$/i) !== null) {
- payload = decodeString(responseBody);
- }
- else if (mapperType.match(/^Base64Url$/i) !== null) {
- payload = base64UrlToByteArray(responseBody);
- }
- else if (mapperType.match(/^Sequence$/i) !== null) {
- payload = deserializeSequenceType(this, mapper, responseBody, objectName, updatedOptions);
- }
- else if (mapperType.match(/^Dictionary$/i) !== null) {
- payload = deserializeDictionaryType(this, mapper, responseBody, objectName, updatedOptions);
- }
- }
- if (mapper.isConstant) {
- payload = mapper.defaultValue;
- }
- return payload;
- }
-}
-/**
- * Method that creates and returns a Serializer.
- * @param modelMappers - Known models to map
- * @param isXML - If XML should be supported
- */
-function createSerializer(modelMappers = {}, isXML = false) {
- return new SerializerImpl(modelMappers, isXML);
-}
-function trimEnd(str, ch) {
- let len = str.length;
- while (len - 1 >= 0 && str[len - 1] === ch) {
- --len;
- }
- return str.substr(0, len);
-}
-function bufferToBase64Url(buffer) {
- if (!buffer) {
- return undefined;
- }
- if (!(buffer instanceof Uint8Array)) {
- throw new Error(`Please provide an input of type Uint8Array for converting to Base64Url.`);
- }
- // Uint8Array to Base64.
- const str = encodeByteArray(buffer);
- // Base64 to Base64Url.
- return trimEnd(str, "=").replace(/\+/g, "-").replace(/\//g, "_");
-}
-function base64UrlToByteArray(str) {
- if (!str) {
- return undefined;
- }
- if (str && typeof str.valueOf() !== "string") {
- throw new Error("Please provide an input of type string for converting to Uint8Array");
- }
- // Base64Url to Base64.
- str = str.replace(/-/g, "+").replace(/_/g, "/");
- // Base64 to Uint8Array.
- return decodeString(str);
-}
-function splitSerializeName(prop) {
- const classes = [];
- let partialclass = "";
- if (prop) {
- const subwords = prop.split(".");
- for (const item of subwords) {
- if (item.charAt(item.length - 1) === "\\") {
- partialclass += item.substr(0, item.length - 1) + ".";
- }
- else {
- partialclass += item;
- classes.push(partialclass);
- partialclass = "";
- }
- }
- }
- return classes;
-}
-function dateToUnixTime(d) {
- if (!d) {
- return undefined;
- }
- if (typeof d.valueOf() === "string") {
- d = new Date(d);
- }
- return Math.floor(d.getTime() / 1000);
-}
-function unixTimeToDate(n) {
- if (!n) {
- return undefined;
- }
- return new Date(n * 1000);
-}
-function serializeBasicTypes(typeName, objectName, value) {
- if (value !== null && value !== undefined) {
- if (typeName.match(/^Number$/i) !== null) {
- if (typeof value !== "number") {
- throw new Error(`${objectName} with value ${value} must be of type number.`);
- }
- }
- else if (typeName.match(/^String$/i) !== null) {
- if (typeof value.valueOf() !== "string") {
- throw new Error(`${objectName} with value "${value}" must be of type string.`);
- }
- }
- else if (typeName.match(/^Uuid$/i) !== null) {
- if (!(typeof value.valueOf() === "string" && isValidUuid(value))) {
- throw new Error(`${objectName} with value "${value}" must be of type string and a valid uuid.`);
- }
- }
- else if (typeName.match(/^Boolean$/i) !== null) {
- if (typeof value !== "boolean") {
- throw new Error(`${objectName} with value ${value} must be of type boolean.`);
- }
- }
- else if (typeName.match(/^Stream$/i) !== null) {
- const objectType = typeof value;
- if (objectType !== "string" &&
- typeof value.pipe !== "function" && // NodeJS.ReadableStream
- typeof value.tee !== "function" && // browser ReadableStream
- !(value instanceof ArrayBuffer) &&
- !ArrayBuffer.isView(value) &&
- // File objects count as a type of Blob, so we want to use instanceof explicitly
- !((typeof Blob === "function" || typeof Blob === "object") && value instanceof Blob) &&
- objectType !== "function") {
- throw new Error(`${objectName} must be a string, Blob, ArrayBuffer, ArrayBufferView, ReadableStream, or () => ReadableStream.`);
- }
- }
- }
- return value;
-}
-function serializeEnumType(objectName, allowedValues, value) {
- if (!allowedValues) {
- throw new Error(`Please provide a set of allowedValues to validate ${objectName} as an Enum Type.`);
- }
- const isPresent = allowedValues.some((item) => {
- if (typeof item.valueOf() === "string") {
- return item.toLowerCase() === value.toLowerCase();
- }
- return item === value;
- });
- if (!isPresent) {
- throw new Error(`${value} is not a valid value for ${objectName}. The valid values are: ${JSON.stringify(allowedValues)}.`);
- }
- return value;
-}
-function serializeByteArrayType(objectName, value) {
- if (value !== undefined && value !== null) {
- if (!(value instanceof Uint8Array)) {
- throw new Error(`${objectName} must be of type Uint8Array.`);
- }
- value = encodeByteArray(value);
- }
- return value;
-}
-function serializeBase64UrlType(objectName, value) {
- if (value !== undefined && value !== null) {
- if (!(value instanceof Uint8Array)) {
- throw new Error(`${objectName} must be of type Uint8Array.`);
- }
- value = bufferToBase64Url(value);
- }
- return value;
-}
-function serializeDateTypes(typeName, value, objectName) {
- if (value !== undefined && value !== null) {
- if (typeName.match(/^Date$/i) !== null) {
- if (!(value instanceof Date ||
- (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
- throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`);
- }
- value =
- value instanceof Date
- ? value.toISOString().substring(0, 10)
- : new Date(value).toISOString().substring(0, 10);
- }
- else if (typeName.match(/^DateTime$/i) !== null) {
- if (!(value instanceof Date ||
- (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
- throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`);
- }
- value = value instanceof Date ? value.toISOString() : new Date(value).toISOString();
- }
- else if (typeName.match(/^DateTimeRfc1123$/i) !== null) {
- if (!(value instanceof Date ||
- (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
- throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123 format.`);
- }
- value = value instanceof Date ? value.toUTCString() : new Date(value).toUTCString();
- }
- else if (typeName.match(/^UnixTime$/i) !== null) {
- if (!(value instanceof Date ||
- (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
- throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123/ISO8601 format ` +
- `for it to be serialized in UnixTime/Epoch format.`);
- }
- value = dateToUnixTime(value);
- }
- else if (typeName.match(/^TimeSpan$/i) !== null) {
- if (!isDuration(value)) {
- throw new Error(`${objectName} must be a string in ISO 8601 format. Instead was "${value}".`);
- }
- }
- }
- return value;
-}
-function serializeSequenceType(serializer, mapper, object, objectName, isXml, options) {
- if (!Array.isArray(object)) {
- throw new Error(`${objectName} must be of type Array.`);
- }
- let elementType = mapper.type.element;
- if (!elementType || typeof elementType !== "object") {
- throw new Error(`element" metadata for an Array must be defined in the ` +
- `mapper and it must of type "object" in ${objectName}.`);
- }
- // Quirk: Composite mappers referenced by `element` might
- // not have *all* properties declared (like uberParent),
- // so let's try to look up the full definition by name.
- if (elementType.type.name === "Composite" && elementType.type.className) {
- elementType = serializer.modelMappers[elementType.type.className] ?? elementType;
- }
- const tempArray = [];
- for (let i = 0; i < object.length; i++) {
- const serializedValue = serializer.serialize(elementType, object[i], objectName, options);
- if (isXml && elementType.xmlNamespace) {
- const xmlnsKey = elementType.xmlNamespacePrefix
- ? `xmlns:${elementType.xmlNamespacePrefix}`
- : "xmlns";
- if (elementType.type.name === "Composite") {
- tempArray[i] = { ...serializedValue };
- tempArray[i][XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace };
- }
- else {
- tempArray[i] = {};
- tempArray[i][options.xml.xmlCharKey] = serializedValue;
- tempArray[i][XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace };
- }
- }
- else {
- tempArray[i] = serializedValue;
- }
- }
- return tempArray;
-}
-function serializeDictionaryType(serializer, mapper, object, objectName, isXml, options) {
- if (typeof object !== "object") {
- throw new Error(`${objectName} must be of type object.`);
- }
- const valueType = mapper.type.value;
- if (!valueType || typeof valueType !== "object") {
- throw new Error(`"value" metadata for a Dictionary must be defined in the ` +
- `mapper and it must of type "object" in ${objectName}.`);
- }
- const tempDictionary = {};
- for (const key of Object.keys(object)) {
- const serializedValue = serializer.serialize(valueType, object[key], objectName, options);
- // If the element needs an XML namespace we need to add it within the $ property
- tempDictionary[key] = getXmlObjectValue(valueType, serializedValue, isXml, options);
- }
- // Add the namespace to the root element if needed
- if (isXml && mapper.xmlNamespace) {
- const xmlnsKey = mapper.xmlNamespacePrefix ? `xmlns:${mapper.xmlNamespacePrefix}` : "xmlns";
- const result = tempDictionary;
- result[XML_ATTRKEY] = { [xmlnsKey]: mapper.xmlNamespace };
- return result;
- }
- return tempDictionary;
-}
-/**
- * Resolves the additionalProperties property from a referenced mapper
- * @param serializer - the serializer containing the entire set of mappers
- * @param mapper - the composite mapper to resolve
- * @param objectName - name of the object being serialized
- */
-function resolveAdditionalProperties(serializer, mapper, objectName) {
- const additionalProperties = mapper.type.additionalProperties;
- if (!additionalProperties && mapper.type.className) {
- const modelMapper = resolveReferencedMapper(serializer, mapper, objectName);
- return modelMapper?.type.additionalProperties;
- }
- return additionalProperties;
-}
-/**
- * Finds the mapper referenced by className
- * @param serializer - the serializer containing the entire set of mappers
- * @param mapper - the composite mapper to resolve
- * @param objectName - name of the object being serialized
- */
-function resolveReferencedMapper(serializer, mapper, objectName) {
- const className = mapper.type.className;
- if (!className) {
- throw new Error(`Class name for model "${objectName}" is not provided in the mapper "${JSON.stringify(mapper, undefined, 2)}".`);
- }
- return serializer.modelMappers[className];
-}
-/**
- * Resolves a composite mapper's modelProperties.
- * @param serializer - the serializer containing the entire set of mappers
- * @param mapper - the composite mapper to resolve
- */
-function resolveModelProperties(serializer, mapper, objectName) {
- let modelProps = mapper.type.modelProperties;
- if (!modelProps) {
- const modelMapper = resolveReferencedMapper(serializer, mapper, objectName);
- if (!modelMapper) {
- throw new Error(`mapper() cannot be null or undefined for model "${mapper.type.className}".`);
- }
- modelProps = modelMapper?.type.modelProperties;
- if (!modelProps) {
- throw new Error(`modelProperties cannot be null or undefined in the ` +
- `mapper "${JSON.stringify(modelMapper)}" of type "${mapper.type.className}" for object "${objectName}".`);
- }
- }
- return modelProps;
-}
-function serializeCompositeType(serializer, mapper, object, objectName, isXml, options) {
- if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) {
- mapper = getPolymorphicMapper(serializer, mapper, object, "clientName");
- }
- if (object !== undefined && object !== null) {
- const payload = {};
- const modelProps = resolveModelProperties(serializer, mapper, objectName);
- for (const key of Object.keys(modelProps)) {
- const propertyMapper = modelProps[key];
- if (propertyMapper.readOnly) {
- continue;
- }
- let propName;
- let parentObject = payload;
- if (serializer.isXML) {
- if (propertyMapper.xmlIsWrapped) {
- propName = propertyMapper.xmlName;
- }
- else {
- propName = propertyMapper.xmlElementName || propertyMapper.xmlName;
- }
- }
- else {
- const paths = splitSerializeName(propertyMapper.serializedName);
- propName = paths.pop();
- for (const pathName of paths) {
- const childObject = parentObject[pathName];
- if ((childObject === undefined || childObject === null) &&
- ((object[key] !== undefined && object[key] !== null) ||
- propertyMapper.defaultValue !== undefined)) {
- parentObject[pathName] = {};
- }
- parentObject = parentObject[pathName];
- }
- }
- if (parentObject !== undefined && parentObject !== null) {
- if (isXml && mapper.xmlNamespace) {
- const xmlnsKey = mapper.xmlNamespacePrefix
- ? `xmlns:${mapper.xmlNamespacePrefix}`
- : "xmlns";
- parentObject[XML_ATTRKEY] = {
- ...parentObject[XML_ATTRKEY],
- [xmlnsKey]: mapper.xmlNamespace,
- };
- }
- const propertyObjectName = propertyMapper.serializedName !== ""
- ? objectName + "." + propertyMapper.serializedName
- : objectName;
- let toSerialize = object[key];
- const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper);
- if (polymorphicDiscriminator &&
- polymorphicDiscriminator.clientName === key &&
- (toSerialize === undefined || toSerialize === null)) {
- toSerialize = mapper.serializedName;
- }
- const serializedValue = serializer.serialize(propertyMapper, toSerialize, propertyObjectName, options);
- if (serializedValue !== undefined && propName !== undefined && propName !== null) {
- const value = getXmlObjectValue(propertyMapper, serializedValue, isXml, options);
- if (isXml && propertyMapper.xmlIsAttribute) {
- // XML_ATTRKEY, i.e., $ is the key attributes are kept under in xml2js.
- // This keeps things simple while preventing name collision
- // with names in user documents.
- parentObject[XML_ATTRKEY] = parentObject[XML_ATTRKEY] || {};
- parentObject[XML_ATTRKEY][propName] = serializedValue;
- }
- else if (isXml && propertyMapper.xmlIsWrapped) {
- parentObject[propName] = { [propertyMapper.xmlElementName]: value };
- }
- else {
- parentObject[propName] = value;
- }
- }
- }
- }
- const additionalPropertiesMapper = resolveAdditionalProperties(serializer, mapper, objectName);
- if (additionalPropertiesMapper) {
- const propNames = Object.keys(modelProps);
- for (const clientPropName in object) {
- const isAdditionalProperty = propNames.every((pn) => pn !== clientPropName);
- if (isAdditionalProperty) {
- payload[clientPropName] = serializer.serialize(additionalPropertiesMapper, object[clientPropName], objectName + '["' + clientPropName + '"]', options);
- }
- }
- }
- return payload;
- }
- return object;
-}
-function getXmlObjectValue(propertyMapper, serializedValue, isXml, options) {
- if (!isXml || !propertyMapper.xmlNamespace) {
- return serializedValue;
- }
- const xmlnsKey = propertyMapper.xmlNamespacePrefix
- ? `xmlns:${propertyMapper.xmlNamespacePrefix}`
- : "xmlns";
- const xmlNamespace = { [xmlnsKey]: propertyMapper.xmlNamespace };
- if (["Composite"].includes(propertyMapper.type.name)) {
- if (serializedValue[XML_ATTRKEY]) {
- return serializedValue;
- }
- else {
- const result = { ...serializedValue };
- result[XML_ATTRKEY] = xmlNamespace;
- return result;
- }
- }
- const result = {};
- result[options.xml.xmlCharKey] = serializedValue;
- result[XML_ATTRKEY] = xmlNamespace;
- return result;
-}
-function isSpecialXmlProperty(propertyName, options) {
- return [XML_ATTRKEY, options.xml.xmlCharKey].includes(propertyName);
-}
-function deserializeCompositeType(serializer, mapper, responseBody, objectName, options) {
- const xmlCharKey = options.xml.xmlCharKey ?? XML_CHARKEY;
- if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) {
- mapper = getPolymorphicMapper(serializer, mapper, responseBody, "serializedName");
- }
- const modelProps = resolveModelProperties(serializer, mapper, objectName);
- let instance = {};
- const handledPropertyNames = [];
- for (const key of Object.keys(modelProps)) {
- const propertyMapper = modelProps[key];
- const paths = splitSerializeName(modelProps[key].serializedName);
- handledPropertyNames.push(paths[0]);
- const { serializedName, xmlName, xmlElementName } = propertyMapper;
- let propertyObjectName = objectName;
- if (serializedName !== "" && serializedName !== undefined) {
- propertyObjectName = objectName + "." + serializedName;
- }
- const headerCollectionPrefix = propertyMapper.headerCollectionPrefix;
- if (headerCollectionPrefix) {
- const dictionary = {};
- for (const headerKey of Object.keys(responseBody)) {
- if (headerKey.startsWith(headerCollectionPrefix)) {
- dictionary[headerKey.substring(headerCollectionPrefix.length)] = serializer.deserialize(propertyMapper.type.value, responseBody[headerKey], propertyObjectName, options);
- }
- handledPropertyNames.push(headerKey);
- }
- instance[key] = dictionary;
- }
- else if (serializer.isXML) {
- if (propertyMapper.xmlIsAttribute && responseBody[XML_ATTRKEY]) {
- instance[key] = serializer.deserialize(propertyMapper, responseBody[XML_ATTRKEY][xmlName], propertyObjectName, options);
- }
- else if (propertyMapper.xmlIsMsText) {
- if (responseBody[xmlCharKey] !== undefined) {
- instance[key] = responseBody[xmlCharKey];
- }
- else if (typeof responseBody === "string") {
- // The special case where xml parser parses "content" into JSON of
- // `{ name: "content"}` instead of `{ name: { "_": "content" }}`
- instance[key] = responseBody;
- }
- }
- else {
- const propertyName = xmlElementName || xmlName || serializedName;
- if (propertyMapper.xmlIsWrapped) {
- /* a list of wrapped by
- For the xml example below
-
- ...
- ...
-
- the responseBody has
- {
- Cors: {
- CorsRule: [{...}, {...}]
- }
- }
- xmlName is "Cors" and xmlElementName is"CorsRule".
- */
- const wrapped = responseBody[xmlName];
- const elementList = wrapped?.[xmlElementName] ?? [];
- instance[key] = serializer.deserialize(propertyMapper, elementList, propertyObjectName, options);
- handledPropertyNames.push(xmlName);
- }
- else {
- const property = responseBody[propertyName];
- instance[key] = serializer.deserialize(propertyMapper, property, propertyObjectName, options);
- handledPropertyNames.push(propertyName);
- }
- }
- }
- else {
- // deserialize the property if it is present in the provided responseBody instance
- let propertyInstance;
- let res = responseBody;
- // traversing the object step by step.
- let steps = 0;
- for (const item of paths) {
- if (!res)
- break;
- steps++;
- res = res[item];
- }
- // only accept null when reaching the last position of object otherwise it would be undefined
- if (res === null && steps < paths.length) {
- res = undefined;
- }
- propertyInstance = res;
- const polymorphicDiscriminator = mapper.type.polymorphicDiscriminator;
- // checking that the model property name (key)(ex: "fishtype") and the
- // clientName of the polymorphicDiscriminator {metadata} (ex: "fishtype")
- // instead of the serializedName of the polymorphicDiscriminator (ex: "fish.type")
- // is a better approach. The generator is not consistent with escaping '\.' in the
- // serializedName of the property (ex: "fish\.type") that is marked as polymorphic discriminator
- // and the serializedName of the metadata polymorphicDiscriminator (ex: "fish.type"). However,
- // the clientName transformation of the polymorphicDiscriminator (ex: "fishtype") and
- // the transformation of model property name (ex: "fishtype") is done consistently.
- // Hence, it is a safer bet to rely on the clientName of the polymorphicDiscriminator.
- if (polymorphicDiscriminator &&
- key === polymorphicDiscriminator.clientName &&
- (propertyInstance === undefined || propertyInstance === null)) {
- propertyInstance = mapper.serializedName;
- }
- let serializedValue;
- // paging
- if (Array.isArray(responseBody[key]) && modelProps[key].serializedName === "") {
- propertyInstance = responseBody[key];
- const arrayInstance = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options);
- // Copy over any properties that have already been added into the instance, where they do
- // not exist on the newly de-serialized array
- for (const [k, v] of Object.entries(instance)) {
- if (!Object.prototype.hasOwnProperty.call(arrayInstance, k)) {
- arrayInstance[k] = v;
- }
- }
- instance = arrayInstance;
- }
- else if (propertyInstance !== undefined || propertyMapper.defaultValue !== undefined) {
- serializedValue = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options);
- instance[key] = serializedValue;
- }
- }
- }
- const additionalPropertiesMapper = mapper.type.additionalProperties;
- if (additionalPropertiesMapper) {
- const isAdditionalProperty = (responsePropName) => {
- for (const clientPropName in modelProps) {
- const paths = splitSerializeName(modelProps[clientPropName].serializedName);
- if (paths[0] === responsePropName) {
- return false;
- }
- }
- return true;
- };
- for (const responsePropName in responseBody) {
- if (isAdditionalProperty(responsePropName)) {
- instance[responsePropName] = serializer.deserialize(additionalPropertiesMapper, responseBody[responsePropName], objectName + '["' + responsePropName + '"]', options);
- }
- }
- }
- else if (responseBody && !options.ignoreUnknownProperties) {
- for (const key of Object.keys(responseBody)) {
- if (instance[key] === undefined &&
- !handledPropertyNames.includes(key) &&
- !isSpecialXmlProperty(key, options)) {
- instance[key] = responseBody[key];
- }
- }
- }
- return instance;
-}
-function deserializeDictionaryType(serializer, mapper, responseBody, objectName, options) {
- /* jshint validthis: true */
- const value = mapper.type.value;
- if (!value || typeof value !== "object") {
- throw new Error(`"value" metadata for a Dictionary must be defined in the ` +
- `mapper and it must of type "object" in ${objectName}`);
- }
- if (responseBody) {
- const tempDictionary = {};
- for (const key of Object.keys(responseBody)) {
- tempDictionary[key] = serializer.deserialize(value, responseBody[key], objectName, options);
- }
- return tempDictionary;
- }
- return responseBody;
-}
-function deserializeSequenceType(serializer, mapper, responseBody, objectName, options) {
- let element = mapper.type.element;
- if (!element || typeof element !== "object") {
- throw new Error(`element" metadata for an Array must be defined in the ` +
- `mapper and it must of type "object" in ${objectName}`);
- }
- if (responseBody) {
- if (!Array.isArray(responseBody)) {
- // xml2js will interpret a single element array as just the element, so force it to be an array
- responseBody = [responseBody];
- }
- // Quirk: Composite mappers referenced by `element` might
- // not have *all* properties declared (like uberParent),
- // so let's try to look up the full definition by name.
- if (element.type.name === "Composite" && element.type.className) {
- element = serializer.modelMappers[element.type.className] ?? element;
- }
- const tempArray = [];
- for (let i = 0; i < responseBody.length; i++) {
- tempArray[i] = serializer.deserialize(element, responseBody[i], `${objectName}[${i}]`, options);
- }
- return tempArray;
- }
- return responseBody;
-}
-function getIndexDiscriminator(discriminators, discriminatorValue, typeName) {
- const typeNamesToCheck = [typeName];
- while (typeNamesToCheck.length) {
- const currentName = typeNamesToCheck.shift();
- const indexDiscriminator = discriminatorValue === currentName
- ? discriminatorValue
- : currentName + "." + discriminatorValue;
- if (Object.prototype.hasOwnProperty.call(discriminators, indexDiscriminator)) {
- return discriminators[indexDiscriminator];
- }
- else {
- for (const [name, mapper] of Object.entries(discriminators)) {
- if (name.startsWith(currentName + ".") &&
- mapper.type.uberParent === currentName &&
- mapper.type.className) {
- typeNamesToCheck.push(mapper.type.className);
- }
- }
- }
- }
- return undefined;
-}
-function getPolymorphicMapper(serializer, mapper, object, polymorphicPropertyName) {
- const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper);
- if (polymorphicDiscriminator) {
- let discriminatorName = polymorphicDiscriminator[polymorphicPropertyName];
- if (discriminatorName) {
- // The serializedName might have \\, which we just want to ignore
- if (polymorphicPropertyName === "serializedName") {
- discriminatorName = discriminatorName.replace(/\\/gi, "");
- }
- const discriminatorValue = object[discriminatorName];
- const typeName = mapper.type.uberParent ?? mapper.type.className;
- if (typeof discriminatorValue === "string" && typeName) {
- const polymorphicMapper = getIndexDiscriminator(serializer.modelMappers.discriminators, discriminatorValue, typeName);
- if (polymorphicMapper) {
- mapper = polymorphicMapper;
- }
- }
- }
- }
- return mapper;
-}
-function getPolymorphicDiscriminatorRecursively(serializer, mapper) {
- return (mapper.type.polymorphicDiscriminator ||
- getPolymorphicDiscriminatorSafely(serializer, mapper.type.uberParent) ||
- getPolymorphicDiscriminatorSafely(serializer, mapper.type.className));
-}
-function getPolymorphicDiscriminatorSafely(serializer, typeName) {
- return (typeName &&
- serializer.modelMappers[typeName] &&
- serializer.modelMappers[typeName].type.polymorphicDiscriminator);
-}
-/**
- * Known types of Mappers
- */
-const MapperTypeNames = {
- Base64Url: "Base64Url",
- Boolean: "Boolean",
- ByteArray: "ByteArray",
- Composite: "Composite",
- Date: "Date",
- DateTime: "DateTime",
- DateTimeRfc1123: "DateTimeRfc1123",
- Dictionary: "Dictionary",
- Enum: "Enum",
- Number: "Number",
- Object: "Object",
- Sequence: "Sequence",
- String: "String",
- Stream: "Stream",
- TimeSpan: "TimeSpan",
- UnixTime: "UnixTime",
-};
-//# sourceMappingURL=serializer.js.map
-// EXTERNAL MODULE: ./node_modules/@azure/core-client/dist/commonjs/state.js
-var dist_commonjs_state = __nccwpck_require__(3345);
-;// CONCATENATED MODULE: ./node_modules/@azure/core-client/dist/esm/state.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-// @ts-expect-error The recommended approach to sharing module state between ESM and CJS.
-// See https://github.com/isaacs/tshy/blob/main/README.md#module-local-state for additional information.
-
-/**
- * Defines the shared state between CJS and ESM by re-exporting the CJS state.
- */
-const esm_state_state = dist_commonjs_state/* state */.w;
-//# sourceMappingURL=state.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-client/dist/esm/operationHelpers.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-/**
- * @internal
- * Retrieves the value to use for a given operation argument
- * @param operationArguments - The arguments passed from the generated client
- * @param parameter - The parameter description
- * @param fallbackObject - If something isn't found in the arguments bag, look here.
- * Generally used to look at the service client properties.
- */
-function getOperationArgumentValueFromParameter(operationArguments, parameter, fallbackObject) {
- let parameterPath = parameter.parameterPath;
- const parameterMapper = parameter.mapper;
- let value;
- if (typeof parameterPath === "string") {
- parameterPath = [parameterPath];
- }
- if (Array.isArray(parameterPath)) {
- if (parameterPath.length > 0) {
- if (parameterMapper.isConstant) {
- value = parameterMapper.defaultValue;
- }
- else {
- let propertySearchResult = getPropertyFromParameterPath(operationArguments, parameterPath);
- if (!propertySearchResult.propertyFound && fallbackObject) {
- propertySearchResult = getPropertyFromParameterPath(fallbackObject, parameterPath);
- }
- let useDefaultValue = false;
- if (!propertySearchResult.propertyFound) {
- useDefaultValue =
- parameterMapper.required ||
- (parameterPath[0] === "options" && parameterPath.length === 2);
- }
- value = useDefaultValue ? parameterMapper.defaultValue : propertySearchResult.propertyValue;
- }
- }
- }
- else {
- if (parameterMapper.required) {
- value = {};
- }
- for (const propertyName in parameterPath) {
- const propertyMapper = parameterMapper.type.modelProperties[propertyName];
- const propertyPath = parameterPath[propertyName];
- const propertyValue = getOperationArgumentValueFromParameter(operationArguments, {
- parameterPath: propertyPath,
- mapper: propertyMapper,
- }, fallbackObject);
- if (propertyValue !== undefined) {
- if (!value) {
- value = {};
- }
- value[propertyName] = propertyValue;
- }
- }
- }
- return value;
-}
-function getPropertyFromParameterPath(parent, parameterPath) {
- const result = { propertyFound: false };
- let i = 0;
- for (; i < parameterPath.length; ++i) {
- const parameterPathPart = parameterPath[i];
- // Make sure to check inherited properties too, so don't use hasOwnProperty().
- if (parent && parameterPathPart in parent) {
- parent = parent[parameterPathPart];
- }
- else {
- break;
- }
- }
- if (i === parameterPath.length) {
- result.propertyValue = parent;
- result.propertyFound = true;
- }
- return result;
-}
-const originalRequestSymbol = Symbol.for("@azure/core-client original request");
-function hasOriginalRequest(request) {
- return originalRequestSymbol in request;
-}
-function getOperationRequestInfo(request) {
- if (hasOriginalRequest(request)) {
- return getOperationRequestInfo(request[originalRequestSymbol]);
- }
- let info = esm_state_state.operationRequestMap.get(request);
- if (!info) {
- info = {};
- esm_state_state.operationRequestMap.set(request, info);
- }
- return info;
-}
-//# sourceMappingURL=operationHelpers.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-client/dist/esm/deserializationPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-
-
-const defaultJsonContentTypes = ["application/json", "text/json"];
-const defaultXmlContentTypes = ["application/xml", "application/atom+xml"];
-/**
- * The programmatic identifier of the deserializationPolicy.
- */
-const deserializationPolicyName = "deserializationPolicy";
-/**
- * This policy handles parsing out responses according to OperationSpecs on the request.
- */
-function deserializationPolicy(options = {}) {
- const jsonContentTypes = options.expectedContentTypes?.json ?? defaultJsonContentTypes;
- const xmlContentTypes = options.expectedContentTypes?.xml ?? defaultXmlContentTypes;
- const parseXML = options.parseXML;
- const serializerOptions = options.serializerOptions;
- const updatedOptions = {
- xml: {
- rootName: serializerOptions?.xml.rootName ?? "",
- includeRoot: serializerOptions?.xml.includeRoot ?? false,
- xmlCharKey: serializerOptions?.xml.xmlCharKey ?? XML_CHARKEY,
- },
- };
- return {
- name: deserializationPolicyName,
- async sendRequest(request, next) {
- const response = await next(request);
- return deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, updatedOptions, parseXML);
- },
- };
-}
-function getOperationResponseMap(parsedResponse) {
- let result;
- const request = parsedResponse.request;
- const operationInfo = getOperationRequestInfo(request);
- const operationSpec = operationInfo?.operationSpec;
- if (operationSpec) {
- if (!operationInfo?.operationResponseGetter) {
- result = operationSpec.responses[parsedResponse.status];
- }
- else {
- result = operationInfo?.operationResponseGetter(operationSpec, parsedResponse);
- }
- }
- return result;
-}
-function shouldDeserializeResponse(parsedResponse) {
- const request = parsedResponse.request;
- const operationInfo = getOperationRequestInfo(request);
- const shouldDeserialize = operationInfo?.shouldDeserialize;
- let result;
- if (shouldDeserialize === undefined) {
- result = true;
- }
- else if (typeof shouldDeserialize === "boolean") {
- result = shouldDeserialize;
- }
- else {
- result = shouldDeserialize(parsedResponse);
- }
- return result;
-}
-async function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, options, parseXML) {
- const parsedResponse = await parse(jsonContentTypes, xmlContentTypes, response, options, parseXML);
- if (!shouldDeserializeResponse(parsedResponse)) {
- return parsedResponse;
- }
- const operationInfo = getOperationRequestInfo(parsedResponse.request);
- const operationSpec = operationInfo?.operationSpec;
- if (!operationSpec || !operationSpec.responses) {
- return parsedResponse;
- }
- const responseSpec = getOperationResponseMap(parsedResponse);
- const { error, shouldReturnResponse } = handleErrorResponse(parsedResponse, operationSpec, responseSpec, options);
- if (error) {
- throw error;
- }
- else if (shouldReturnResponse) {
- return parsedResponse;
- }
- // An operation response spec does exist for current status code, so
- // use it to deserialize the response.
- if (responseSpec) {
- if (responseSpec.bodyMapper) {
- let valueToDeserialize = parsedResponse.parsedBody;
- if (operationSpec.isXML && responseSpec.bodyMapper.type.name === MapperTypeNames.Sequence) {
- valueToDeserialize =
- typeof valueToDeserialize === "object"
- ? valueToDeserialize[responseSpec.bodyMapper.xmlElementName]
- : [];
- }
- try {
- parsedResponse.parsedBody = operationSpec.serializer.deserialize(responseSpec.bodyMapper, valueToDeserialize, "operationRes.parsedBody", options);
- }
- catch (deserializeError) {
- const restError = new esm_restError_RestError(`Error ${deserializeError} occurred in deserializing the responseBody - ${parsedResponse.bodyAsText}`, {
- statusCode: parsedResponse.status,
- request: parsedResponse.request,
- response: parsedResponse,
- });
- throw restError;
- }
- }
- else if (operationSpec.httpMethod === "HEAD") {
- // head methods never have a body, but we return a boolean to indicate presence/absence of the resource
- parsedResponse.parsedBody = response.status >= 200 && response.status < 300;
- }
- if (responseSpec.headersMapper) {
- parsedResponse.parsedHeaders = operationSpec.serializer.deserialize(responseSpec.headersMapper, parsedResponse.headers.toJSON(), "operationRes.parsedHeaders", { xml: {}, ignoreUnknownProperties: true });
- }
- }
- return parsedResponse;
-}
-function isOperationSpecEmpty(operationSpec) {
- const expectedStatusCodes = Object.keys(operationSpec.responses);
- return (expectedStatusCodes.length === 0 ||
- (expectedStatusCodes.length === 1 && expectedStatusCodes[0] === "default"));
-}
-function handleErrorResponse(parsedResponse, operationSpec, responseSpec, options) {
- const isSuccessByStatus = 200 <= parsedResponse.status && parsedResponse.status < 300;
- const isExpectedStatusCode = isOperationSpecEmpty(operationSpec)
- ? isSuccessByStatus
- : !!responseSpec;
- if (isExpectedStatusCode) {
- if (responseSpec) {
- if (!responseSpec.isError) {
- return { error: null, shouldReturnResponse: false };
- }
- }
- else {
- return { error: null, shouldReturnResponse: false };
- }
- }
- const errorResponseSpec = responseSpec ?? operationSpec.responses.default;
- const initialErrorMessage = parsedResponse.request.streamResponseStatusCodes?.has(parsedResponse.status)
- ? `Unexpected status code: ${parsedResponse.status}`
- : parsedResponse.bodyAsText;
- const error = new esm_restError_RestError(initialErrorMessage, {
- statusCode: parsedResponse.status,
- request: parsedResponse.request,
- response: parsedResponse,
- });
- // If the item failed but there's no error spec or default spec to deserialize the error,
- // and the parsed body doesn't look like an error object,
- // we should fail so we just throw the parsed response
- if (!errorResponseSpec &&
- !(parsedResponse.parsedBody?.error?.code && parsedResponse.parsedBody?.error?.message)) {
- throw error;
- }
- const defaultBodyMapper = errorResponseSpec?.bodyMapper;
- const defaultHeadersMapper = errorResponseSpec?.headersMapper;
- try {
- // If error response has a body, try to deserialize it using default body mapper.
- // Then try to extract error code & message from it
- if (parsedResponse.parsedBody) {
- const parsedBody = parsedResponse.parsedBody;
- let deserializedError;
- if (defaultBodyMapper) {
- let valueToDeserialize = parsedBody;
- if (operationSpec.isXML && defaultBodyMapper.type.name === MapperTypeNames.Sequence) {
- valueToDeserialize = [];
- const elementName = defaultBodyMapper.xmlElementName;
- if (typeof parsedBody === "object" && elementName) {
- valueToDeserialize = parsedBody[elementName];
- }
- }
- deserializedError = operationSpec.serializer.deserialize(defaultBodyMapper, valueToDeserialize, "error.response.parsedBody", options);
- }
- const internalError = parsedBody.error || deserializedError || parsedBody;
- error.code = internalError.code;
- if (internalError.message) {
- error.message = internalError.message;
- }
- if (defaultBodyMapper) {
- error.response.parsedBody = deserializedError;
- }
- }
- // If error response has headers, try to deserialize it using default header mapper
- if (parsedResponse.headers && defaultHeadersMapper) {
- error.response.parsedHeaders =
- operationSpec.serializer.deserialize(defaultHeadersMapper, parsedResponse.headers.toJSON(), "operationRes.parsedHeaders");
- }
- }
- catch (defaultError) {
- error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody - "${parsedResponse.bodyAsText}" for the default response.`;
- }
- return { error, shouldReturnResponse: false };
-}
-async function parse(jsonContentTypes, xmlContentTypes, operationResponse, opts, parseXML) {
- if (!operationResponse.request.streamResponseStatusCodes?.has(operationResponse.status) &&
- operationResponse.bodyAsText) {
- const text = operationResponse.bodyAsText;
- const contentType = operationResponse.headers.get("Content-Type") || "";
- const contentComponents = !contentType
- ? []
- : contentType.split(";").map((component) => component.toLowerCase());
- try {
- if (contentComponents.length === 0 ||
- contentComponents.some((component) => jsonContentTypes.indexOf(component) !== -1)) {
- operationResponse.parsedBody = JSON.parse(text);
- return operationResponse;
- }
- else if (contentComponents.some((component) => xmlContentTypes.indexOf(component) !== -1)) {
- if (!parseXML) {
- throw new Error("Parsing XML not supported.");
- }
- const body = await parseXML(text, opts.xml);
- operationResponse.parsedBody = body;
- return operationResponse;
- }
- }
- catch (err) {
- const msg = `Error "${err}" occurred while parsing the response body - ${operationResponse.bodyAsText}.`;
- const errCode = err.code || esm_restError_RestError.PARSE_ERROR;
- const e = new esm_restError_RestError(msg, {
- code: errCode,
- statusCode: operationResponse.status,
- request: operationResponse.request,
- response: operationResponse,
- });
- throw e;
- }
- }
- return operationResponse;
-}
-//# sourceMappingURL=deserializationPolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-client/dist/esm/interfaceHelpers.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-/**
- * Gets the list of status codes for streaming responses.
- * @internal
- */
-function getStreamingResponseStatusCodes(operationSpec) {
- const result = new Set();
- for (const statusCode in operationSpec.responses) {
- const operationResponse = operationSpec.responses[statusCode];
- if (operationResponse.bodyMapper &&
- operationResponse.bodyMapper.type.name === MapperTypeNames.Stream) {
- result.add(Number(statusCode));
- }
- }
- return result;
-}
-/**
- * Get the path to this parameter's value as a dotted string (a.b.c).
- * @param parameter - The parameter to get the path string for.
- * @returns The path to this parameter's value as a dotted string.
- * @internal
- */
-function getPathStringFromParameter(parameter) {
- const { parameterPath, mapper } = parameter;
- let result;
- if (typeof parameterPath === "string") {
- result = parameterPath;
- }
- else if (Array.isArray(parameterPath)) {
- result = parameterPath.join(".");
- }
- else {
- result = mapper.serializedName;
- }
- return result;
-}
-//# sourceMappingURL=interfaceHelpers.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-client/dist/esm/serializationPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-
-
-/**
- * The programmatic identifier of the serializationPolicy.
- */
-const serializationPolicyName = "serializationPolicy";
-/**
- * This policy handles assembling the request body and headers using
- * an OperationSpec and OperationArguments on the request.
- */
-function serializationPolicy(options = {}) {
- const stringifyXML = options.stringifyXML;
- return {
- name: serializationPolicyName,
- async sendRequest(request, next) {
- const operationInfo = getOperationRequestInfo(request);
- const operationSpec = operationInfo?.operationSpec;
- const operationArguments = operationInfo?.operationArguments;
- if (operationSpec && operationArguments) {
- serializeHeaders(request, operationArguments, operationSpec);
- serializeRequestBody(request, operationArguments, operationSpec, stringifyXML);
- }
- return next(request);
- },
- };
-}
-/**
- * @internal
- */
-function serializeHeaders(request, operationArguments, operationSpec) {
- if (operationSpec.headerParameters) {
- for (const headerParameter of operationSpec.headerParameters) {
- let headerValue = getOperationArgumentValueFromParameter(operationArguments, headerParameter);
- if ((headerValue !== null && headerValue !== undefined) || headerParameter.mapper.required) {
- headerValue = operationSpec.serializer.serialize(headerParameter.mapper, headerValue, getPathStringFromParameter(headerParameter));
- const headerCollectionPrefix = headerParameter.mapper
- .headerCollectionPrefix;
- if (headerCollectionPrefix) {
- for (const key of Object.keys(headerValue)) {
- request.headers.set(headerCollectionPrefix + key, headerValue[key]);
- }
- }
- else {
- request.headers.set(headerParameter.mapper.serializedName || getPathStringFromParameter(headerParameter), headerValue);
- }
- }
- }
- }
- const customHeaders = operationArguments.options?.requestOptions?.customHeaders;
- if (customHeaders) {
- for (const customHeaderName of Object.keys(customHeaders)) {
- request.headers.set(customHeaderName, customHeaders[customHeaderName]);
- }
- }
-}
-/**
- * @internal
- */
-function serializeRequestBody(request, operationArguments, operationSpec, stringifyXML = function () {
- throw new Error("XML serialization unsupported!");
-}) {
- const serializerOptions = operationArguments.options?.serializerOptions;
- const updatedOptions = {
- xml: {
- rootName: serializerOptions?.xml.rootName ?? "",
- includeRoot: serializerOptions?.xml.includeRoot ?? false,
- xmlCharKey: serializerOptions?.xml.xmlCharKey ?? XML_CHARKEY,
- },
- };
- const xmlCharKey = updatedOptions.xml.xmlCharKey;
- if (operationSpec.requestBody && operationSpec.requestBody.mapper) {
- request.body = getOperationArgumentValueFromParameter(operationArguments, operationSpec.requestBody);
- const bodyMapper = operationSpec.requestBody.mapper;
- const { required, serializedName, xmlName, xmlElementName, xmlNamespace, xmlNamespacePrefix, nullable, } = bodyMapper;
- const typeName = bodyMapper.type.name;
- try {
- if ((request.body !== undefined && request.body !== null) ||
- (nullable && request.body === null) ||
- required) {
- const requestBodyParameterPathString = getPathStringFromParameter(operationSpec.requestBody);
- request.body = operationSpec.serializer.serialize(bodyMapper, request.body, requestBodyParameterPathString, updatedOptions);
- const isStream = typeName === MapperTypeNames.Stream;
- if (operationSpec.isXML) {
- const xmlnsKey = xmlNamespacePrefix ? `xmlns:${xmlNamespacePrefix}` : "xmlns";
- const value = getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, request.body, updatedOptions);
- if (typeName === MapperTypeNames.Sequence) {
- request.body = stringifyXML(prepareXMLRootList(value, xmlElementName || xmlName || serializedName, xmlnsKey, xmlNamespace), { rootName: xmlName || serializedName, xmlCharKey });
- }
- else if (!isStream) {
- request.body = stringifyXML(value, {
- rootName: xmlName || serializedName,
- xmlCharKey,
- });
- }
- }
- else if (typeName === MapperTypeNames.String &&
- (operationSpec.contentType?.match("text/plain") || operationSpec.mediaType === "text")) {
- // the String serializer has validated that request body is a string
- // so just send the string.
- return;
- }
- else if (!isStream) {
- request.body = JSON.stringify(request.body);
- }
- }
- }
- catch (error) {
- throw new Error(`Error "${error.message}" occurred in serializing the payload - ${JSON.stringify(serializedName, undefined, " ")}.`);
- }
- }
- else if (operationSpec.formDataParameters && operationSpec.formDataParameters.length > 0) {
- request.formData = {};
- for (const formDataParameter of operationSpec.formDataParameters) {
- const formDataParameterValue = getOperationArgumentValueFromParameter(operationArguments, formDataParameter);
- if (formDataParameterValue !== undefined && formDataParameterValue !== null) {
- const formDataParameterPropertyName = formDataParameter.mapper.serializedName || getPathStringFromParameter(formDataParameter);
- request.formData[formDataParameterPropertyName] = operationSpec.serializer.serialize(formDataParameter.mapper, formDataParameterValue, getPathStringFromParameter(formDataParameter), updatedOptions);
- }
- }
- }
-}
-/**
- * Adds an xml namespace to the xml serialized object if needed, otherwise it just returns the value itself
- */
-function getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, serializedValue, options) {
- // Composite and Sequence schemas already got their root namespace set during serialization
- // We just need to add xmlns to the other schema types
- if (xmlNamespace && !["Composite", "Sequence", "Dictionary"].includes(typeName)) {
- const result = {};
- result[options.xml.xmlCharKey] = serializedValue;
- result[XML_ATTRKEY] = { [xmlnsKey]: xmlNamespace };
- return result;
- }
- return serializedValue;
-}
-function prepareXMLRootList(obj, elementName, xmlNamespaceKey, xmlNamespace) {
- if (!Array.isArray(obj)) {
- obj = [obj];
- }
- if (!xmlNamespaceKey || !xmlNamespace) {
- return { [elementName]: obj };
- }
- const result = { [elementName]: obj };
- result[XML_ATTRKEY] = { [xmlNamespaceKey]: xmlNamespace };
- return result;
-}
-//# sourceMappingURL=serializationPolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-client/dist/esm/pipeline.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-
-/**
- * Creates a new Pipeline for use with a Service Client.
- * Adds in deserializationPolicy by default.
- * Also adds in bearerTokenAuthenticationPolicy if passed a TokenCredential.
- * @param options - Options to customize the created pipeline.
- */
-function createClientPipeline(options = {}) {
- const pipeline = esm_createPipelineFromOptions_createPipelineFromOptions(options ?? {});
- if (options.credentialOptions) {
- pipeline.addPolicy(bearerTokenAuthenticationPolicy({
- credential: options.credentialOptions.credential,
- scopes: options.credentialOptions.credentialScopes,
- }));
- }
- pipeline.addPolicy(serializationPolicy(options.serializationOptions), { phase: "Serialize" });
- pipeline.addPolicy(deserializationPolicy(options.deserializationOptions), {
- phase: "Deserialize",
- });
- return pipeline;
-}
-//# sourceMappingURL=pipeline.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-client/dist/esm/httpClientCache.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-let httpClientCache_cachedHttpClient;
-function getCachedDefaultHttpClient() {
- if (!httpClientCache_cachedHttpClient) {
- httpClientCache_cachedHttpClient = esm_defaultHttpClient_createDefaultHttpClient();
- }
- return httpClientCache_cachedHttpClient;
-}
-//# sourceMappingURL=httpClientCache.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-client/dist/esm/urlHelpers.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-const CollectionFormatToDelimiterMap = {
- CSV: ",",
- SSV: " ",
- Multi: "Multi",
- TSV: "\t",
- Pipes: "|",
-};
-function getRequestUrl(baseUri, operationSpec, operationArguments, fallbackObject) {
- const urlReplacements = calculateUrlReplacements(operationSpec, operationArguments, fallbackObject);
- let isAbsolutePath = false;
- let requestUrl = replaceAll(baseUri, urlReplacements);
- if (operationSpec.path) {
- let path = replaceAll(operationSpec.path, urlReplacements);
- // QUIRK: sometimes we get a path component like /{nextLink}
- // which may be a fully formed URL with a leading /. In that case, we should
- // remove the leading /
- if (operationSpec.path === "/{nextLink}" && path.startsWith("/")) {
- path = path.substring(1);
- }
- // QUIRK: sometimes we get a path component like {nextLink}
- // which may be a fully formed URL. In that case, we should
- // ignore the baseUri.
- if (isAbsoluteUrl(path)) {
- requestUrl = path;
- isAbsolutePath = true;
- }
- else {
- requestUrl = appendPath(requestUrl, path);
- }
- }
- const { queryParams, sequenceParams } = calculateQueryParameters(operationSpec, operationArguments, fallbackObject);
- /**
- * Notice that this call sets the `noOverwrite` parameter to true if the `requestUrl`
- * is an absolute path. This ensures that existing query parameter values in `requestUrl`
- * do not get overwritten. On the other hand when `requestUrl` is not absolute path, it
- * is still being built so there is nothing to overwrite.
- */
- requestUrl = appendQueryParams(requestUrl, queryParams, sequenceParams, isAbsolutePath);
- return requestUrl;
-}
-function replaceAll(input, replacements) {
- let result = input;
- for (const [searchValue, replaceValue] of replacements) {
- result = result.split(searchValue).join(replaceValue);
- }
- return result;
-}
-function calculateUrlReplacements(operationSpec, operationArguments, fallbackObject) {
- const result = new Map();
- if (operationSpec.urlParameters?.length) {
- for (const urlParameter of operationSpec.urlParameters) {
- let urlParameterValue = getOperationArgumentValueFromParameter(operationArguments, urlParameter, fallbackObject);
- const parameterPathString = getPathStringFromParameter(urlParameter);
- urlParameterValue = operationSpec.serializer.serialize(urlParameter.mapper, urlParameterValue, parameterPathString);
- if (!urlParameter.skipEncoding) {
- urlParameterValue = encodeURIComponent(urlParameterValue);
- }
- result.set(`{${urlParameter.mapper.serializedName || parameterPathString}}`, urlParameterValue);
- }
- }
- return result;
-}
-function isAbsoluteUrl(url) {
- return url.includes("://");
-}
-function appendPath(url, pathToAppend) {
- if (!pathToAppend) {
- return url;
- }
- const parsedUrl = new URL(url);
- let newPath = parsedUrl.pathname;
- if (!newPath.endsWith("/")) {
- newPath = `${newPath}/`;
- }
- if (pathToAppend.startsWith("/")) {
- pathToAppend = pathToAppend.substring(1);
- }
- const searchStart = pathToAppend.indexOf("?");
- if (searchStart !== -1) {
- const path = pathToAppend.substring(0, searchStart);
- const search = pathToAppend.substring(searchStart + 1);
- newPath = newPath + path;
- if (search) {
- parsedUrl.search = parsedUrl.search ? `${parsedUrl.search}&${search}` : search;
- }
- }
- else {
- newPath = newPath + pathToAppend;
- }
- parsedUrl.pathname = newPath;
- return parsedUrl.toString();
-}
-function calculateQueryParameters(operationSpec, operationArguments, fallbackObject) {
- const result = new Map();
- const sequenceParams = new Set();
- if (operationSpec.queryParameters?.length) {
- for (const queryParameter of operationSpec.queryParameters) {
- if (queryParameter.mapper.type.name === "Sequence" && queryParameter.mapper.serializedName) {
- sequenceParams.add(queryParameter.mapper.serializedName);
- }
- let queryParameterValue = getOperationArgumentValueFromParameter(operationArguments, queryParameter, fallbackObject);
- if ((queryParameterValue !== undefined && queryParameterValue !== null) ||
- queryParameter.mapper.required) {
- queryParameterValue = operationSpec.serializer.serialize(queryParameter.mapper, queryParameterValue, getPathStringFromParameter(queryParameter));
- const delimiter = queryParameter.collectionFormat
- ? CollectionFormatToDelimiterMap[queryParameter.collectionFormat]
- : "";
- if (Array.isArray(queryParameterValue)) {
- // replace null and undefined
- queryParameterValue = queryParameterValue.map((item) => {
- if (item === null || item === undefined) {
- return "";
- }
- return item;
- });
- }
- if (queryParameter.collectionFormat === "Multi" && queryParameterValue.length === 0) {
- continue;
- }
- else if (Array.isArray(queryParameterValue) &&
- (queryParameter.collectionFormat === "SSV" || queryParameter.collectionFormat === "TSV")) {
- queryParameterValue = queryParameterValue.join(delimiter);
- }
- if (!queryParameter.skipEncoding) {
- if (Array.isArray(queryParameterValue)) {
- queryParameterValue = queryParameterValue.map((item) => {
- return encodeURIComponent(item);
- });
- }
- else {
- queryParameterValue = encodeURIComponent(queryParameterValue);
- }
- }
- // Join pipes and CSV *after* encoding, or the server will be upset.
- if (Array.isArray(queryParameterValue) &&
- (queryParameter.collectionFormat === "CSV" || queryParameter.collectionFormat === "Pipes")) {
- queryParameterValue = queryParameterValue.join(delimiter);
- }
- result.set(queryParameter.mapper.serializedName || getPathStringFromParameter(queryParameter), queryParameterValue);
- }
- }
- }
- return {
- queryParams: result,
- sequenceParams,
- };
-}
-function simpleParseQueryParams(queryString) {
- const result = new Map();
- if (!queryString || queryString[0] !== "?") {
- return result;
- }
- // remove the leading ?
- queryString = queryString.slice(1);
- const pairs = queryString.split("&");
- for (const pair of pairs) {
- const [name, value] = pair.split("=", 2);
- const existingValue = result.get(name);
- if (existingValue) {
- if (Array.isArray(existingValue)) {
- existingValue.push(value);
- }
- else {
- result.set(name, [existingValue, value]);
- }
- }
- else {
- result.set(name, value);
- }
- }
- return result;
-}
-/** @internal */
-function appendQueryParams(url, queryParams, sequenceParams, noOverwrite = false) {
- if (queryParams.size === 0) {
- return url;
- }
- const parsedUrl = new URL(url);
- // QUIRK: parsedUrl.searchParams will have their name/value pairs decoded, which
- // can change their meaning to the server, such as in the case of a SAS signature.
- // To avoid accidentally un-encoding a query param, we parse the key/values ourselves
- const combinedParams = simpleParseQueryParams(parsedUrl.search);
- for (const [name, value] of queryParams) {
- const existingValue = combinedParams.get(name);
- if (Array.isArray(existingValue)) {
- if (Array.isArray(value)) {
- existingValue.push(...value);
- const valueSet = new Set(existingValue);
- combinedParams.set(name, Array.from(valueSet));
- }
- else {
- existingValue.push(value);
- }
- }
- else if (existingValue) {
- if (Array.isArray(value)) {
- value.unshift(existingValue);
- }
- else if (sequenceParams.has(name)) {
- combinedParams.set(name, [existingValue, value]);
- }
- if (!noOverwrite) {
- combinedParams.set(name, value);
- }
- }
- else {
- combinedParams.set(name, value);
- }
- }
- const searchPieces = [];
- for (const [name, value] of combinedParams) {
- if (typeof value === "string") {
- searchPieces.push(`${name}=${value}`);
- }
- else if (Array.isArray(value)) {
- // QUIRK: If we get an array of values, include multiple key/value pairs
- for (const subValue of value) {
- searchPieces.push(`${name}=${subValue}`);
- }
- }
- else {
- searchPieces.push(`${name}=${value}`);
- }
- }
- // QUIRK: we have to set search manually as searchParams will encode comma when it shouldn't.
- parsedUrl.search = searchPieces.length ? `?${searchPieces.join("&")}` : "";
- return parsedUrl.toString();
-}
-//# sourceMappingURL=urlHelpers.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-client/dist/esm/log.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-const dist_esm_log_logger = esm_createClientLogger("core-client");
-//# sourceMappingURL=log.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-client/dist/esm/serviceClient.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-
-
-
-
-
-
-/**
- * Initializes a new instance of the ServiceClient.
- */
-class ServiceClient {
- /**
- * If specified, this is the base URI that requests will be made against for this ServiceClient.
- * If it is not specified, then all OperationSpecs must contain a baseUrl property.
- */
- _endpoint;
- /**
- * The default request content type for the service.
- * Used if no requestContentType is present on an OperationSpec.
- */
- _requestContentType;
- /**
- * Set to true if the request is sent over HTTP instead of HTTPS
- */
- _allowInsecureConnection;
- /**
- * The HTTP client that will be used to send requests.
- */
- _httpClient;
- /**
- * The pipeline used by this client to make requests
- */
- pipeline;
- /**
- * The ServiceClient constructor
- * @param options - The service client options that govern the behavior of the client.
- */
- constructor(options = {}) {
- this._requestContentType = options.requestContentType;
- this._endpoint = options.endpoint ?? options.baseUri;
- if (options.baseUri) {
- dist_esm_log_logger.warning("The baseUri option for SDK Clients has been deprecated, please use endpoint instead.");
- }
- this._allowInsecureConnection = options.allowInsecureConnection;
- this._httpClient = options.httpClient || getCachedDefaultHttpClient();
- this.pipeline = options.pipeline || serviceClient_createDefaultPipeline(options);
- if (options.additionalPolicies?.length) {
- for (const { policy, position } of options.additionalPolicies) {
- // Sign happens after Retry and is commonly needed to occur
- // before policies that intercept post-retry.
- const afterPhase = position === "perRetry" ? "Sign" : undefined;
- this.pipeline.addPolicy(policy, {
- afterPhase,
- });
- }
- }
- }
- /**
- * Send the provided httpRequest.
- */
- async sendRequest(request) {
- return this.pipeline.sendRequest(this._httpClient, request);
- }
- /**
- * Send an HTTP request that is populated using the provided OperationSpec.
- * @typeParam T - The typed result of the request, based on the OperationSpec.
- * @param operationArguments - The arguments that the HTTP request's templated values will be populated from.
- * @param operationSpec - The OperationSpec to use to populate the httpRequest.
- */
- async sendOperationRequest(operationArguments, operationSpec) {
- const endpoint = operationSpec.baseUrl || this._endpoint;
- if (!endpoint) {
- throw new Error("If operationSpec.baseUrl is not specified, then the ServiceClient must have a endpoint string property that contains the base URL to use.");
- }
- // Templatized URLs sometimes reference properties on the ServiceClient child class,
- // so we have to pass `this` below in order to search these properties if they're
- // not part of OperationArguments
- const url = getRequestUrl(endpoint, operationSpec, operationArguments, this);
- const request = esm_pipelineRequest_createPipelineRequest({
- url,
- });
- request.method = operationSpec.httpMethod;
- const operationInfo = getOperationRequestInfo(request);
- operationInfo.operationSpec = operationSpec;
- operationInfo.operationArguments = operationArguments;
- const contentType = operationSpec.contentType || this._requestContentType;
- if (contentType && operationSpec.requestBody) {
- request.headers.set("Content-Type", contentType);
- }
- const options = operationArguments.options;
- if (options) {
- const requestOptions = options.requestOptions;
- if (requestOptions) {
- if (requestOptions.timeout) {
- request.timeout = requestOptions.timeout;
- }
- if (requestOptions.onUploadProgress) {
- request.onUploadProgress = requestOptions.onUploadProgress;
- }
- if (requestOptions.onDownloadProgress) {
- request.onDownloadProgress = requestOptions.onDownloadProgress;
- }
- if (requestOptions.shouldDeserialize !== undefined) {
- operationInfo.shouldDeserialize = requestOptions.shouldDeserialize;
- }
- if (requestOptions.allowInsecureConnection) {
- request.allowInsecureConnection = true;
- }
- }
- if (options.abortSignal) {
- request.abortSignal = options.abortSignal;
- }
- if (options.tracingOptions) {
- request.tracingOptions = options.tracingOptions;
- }
- }
- if (this._allowInsecureConnection) {
- request.allowInsecureConnection = true;
- }
- if (request.streamResponseStatusCodes === undefined) {
- request.streamResponseStatusCodes = getStreamingResponseStatusCodes(operationSpec);
- }
- try {
- const rawResponse = await this.sendRequest(request);
- const flatResponse = flattenResponse(rawResponse, operationSpec.responses[rawResponse.status]);
- if (options?.onResponse) {
- options.onResponse(rawResponse, flatResponse);
- }
- return flatResponse;
- }
- catch (error) {
- if (typeof error === "object" && error?.response) {
- const rawResponse = error.response;
- const flatResponse = flattenResponse(rawResponse, operationSpec.responses[error.statusCode] || operationSpec.responses["default"]);
- error.details = flatResponse;
- if (options?.onResponse) {
- options.onResponse(rawResponse, flatResponse, error);
- }
- }
- throw error;
- }
- }
-}
-function serviceClient_createDefaultPipeline(options) {
- const credentialScopes = getCredentialScopes(options);
- const credentialOptions = options.credential && credentialScopes
- ? { credentialScopes, credential: options.credential }
- : undefined;
- return createClientPipeline({
- ...options,
- credentialOptions,
- });
-}
-function getCredentialScopes(options) {
- if (options.credentialScopes) {
- return options.credentialScopes;
- }
- if (options.endpoint) {
- return `${options.endpoint}/.default`;
- }
- if (options.baseUri) {
- return `${options.baseUri}/.default`;
- }
- if (options.credential && !options.credentialScopes) {
- throw new Error(`When using credentials, the ServiceClientOptions must contain either a endpoint or a credentialScopes. Unable to create a bearerTokenAuthenticationPolicy`);
- }
- return undefined;
-}
-//# sourceMappingURL=serviceClient.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-client/dist/esm/authorizeRequestOnClaimChallenge.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-/**
- * Converts: `Bearer a="b", c="d", Bearer d="e", f="g"`.
- * Into: `[ { a: 'b', c: 'd' }, { d: 'e', f: 'g' } ]`.
- *
- * @internal
- */
-function parseCAEChallenge(challenges) {
- const bearerChallenges = `, ${challenges.trim()}`.split(", Bearer ").filter((x) => x);
- return bearerChallenges.map((challenge) => {
- const challengeParts = `${challenge.trim()}, `.split('", ').filter((x) => x);
- const keyValuePairs = challengeParts.map((keyValue) => (([key, value]) => ({ [key]: value }))(keyValue.trim().split('="')));
- // Key-value pairs to plain object:
- return keyValuePairs.reduce((a, b) => ({ ...a, ...b }), {});
- });
-}
-/**
- * This function can be used as a callback for the `bearerTokenAuthenticationPolicy` of `@azure/core-rest-pipeline`, to support CAE challenges:
- * [Continuous Access Evaluation](https://learn.microsoft.com/azure/active-directory/conditional-access/concept-continuous-access-evaluation).
- *
- * Call the `bearerTokenAuthenticationPolicy` with the following options:
- *
- * ```ts snippet:AuthorizeRequestOnClaimChallenge
- * import { bearerTokenAuthenticationPolicy } from "@azure/core-rest-pipeline";
- * import { authorizeRequestOnClaimChallenge } from "@azure/core-client";
- *
- * const policy = bearerTokenAuthenticationPolicy({
- * challengeCallbacks: {
- * authorizeRequestOnChallenge: authorizeRequestOnClaimChallenge,
- * },
- * scopes: ["https://service/.default"],
- * });
- * ```
- *
- * Once provided, the `bearerTokenAuthenticationPolicy` policy will internally handle Continuous Access Evaluation (CAE) challenges.
- * When it can't complete a challenge it will return the 401 (unauthorized) response from ARM.
- *
- * Example challenge with claims:
- *
- * ```
- * Bearer authorization_uri="https://login.windows-ppe.net/", error="invalid_token",
- * error_description="User session has been revoked",
- * claims="eyJhY2Nlc3NfdG9rZW4iOnsibmJmIjp7ImVzc2VudGlhbCI6dHJ1ZSwgInZhbHVlIjoiMTYwMzc0MjgwMCJ9fX0="
- * ```
- */
-async function authorizeRequestOnClaimChallenge(onChallengeOptions) {
- const { scopes, response } = onChallengeOptions;
- const logger = onChallengeOptions.logger || coreClientLogger;
- const challenge = response.headers.get("WWW-Authenticate");
- if (!challenge) {
- logger.info(`The WWW-Authenticate header was missing. Failed to perform the Continuous Access Evaluation authentication flow.`);
- return false;
- }
- const challenges = parseCAEChallenge(challenge) || [];
- const parsedChallenge = challenges.find((x) => x.claims);
- if (!parsedChallenge) {
- logger.info(`The WWW-Authenticate header was missing the necessary "claims" to perform the Continuous Access Evaluation authentication flow.`);
- return false;
- }
- const accessToken = await onChallengeOptions.getAccessToken(parsedChallenge.scope ? [parsedChallenge.scope] : scopes, {
- claims: decodeStringToString(parsedChallenge.claims),
- });
- if (!accessToken) {
- return false;
- }
- onChallengeOptions.request.headers.set("Authorization", `${accessToken.tokenType ?? "Bearer"} ${accessToken.token}`);
- return true;
-}
-//# sourceMappingURL=authorizeRequestOnClaimChallenge.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-client/dist/esm/authorizeRequestOnTenantChallenge.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-/**
- * A set of constants used internally when processing requests.
- */
-const Constants = {
- DefaultScope: "/.default",
- /**
- * Defines constants for use with HTTP headers.
- */
- HeaderConstants: {
- /**
- * The Authorization header.
- */
- AUTHORIZATION: "authorization",
- },
-};
-function isUuid(text) {
- return /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/.test(text);
-}
-/**
- * Defines a callback to handle auth challenge for Storage APIs.
- * This implements the bearer challenge process described here: https://learn.microsoft.com/rest/api/storageservices/authorize-with-azure-active-directory#bearer-challenge
- * Handling has specific features for storage that departs to the general AAD challenge docs.
- **/
-const authorizeRequestOnTenantChallenge = async (challengeOptions) => {
- const requestOptions = requestToOptions(challengeOptions.request);
- const challenge = getChallenge(challengeOptions.response);
- if (challenge) {
- const challengeInfo = parseChallenge(challenge);
- const challengeScopes = buildScopes(challengeOptions, challengeInfo);
- const tenantId = extractTenantId(challengeInfo);
- if (!tenantId) {
- return false;
- }
- const accessToken = await challengeOptions.getAccessToken(challengeScopes, {
- ...requestOptions,
- tenantId,
- });
- if (!accessToken) {
- return false;
- }
- challengeOptions.request.headers.set(Constants.HeaderConstants.AUTHORIZATION, `${accessToken.tokenType ?? "Bearer"} ${accessToken.token}`);
- return true;
- }
- return false;
-};
-/**
- * Extracts the tenant id from the challenge information
- * The tenant id is contained in the authorization_uri as the first
- * path part.
- */
-function extractTenantId(challengeInfo) {
- const parsedAuthUri = new URL(challengeInfo.authorization_uri);
- const pathSegments = parsedAuthUri.pathname.split("/");
- const tenantId = pathSegments[1];
- if (tenantId && isUuid(tenantId)) {
- return tenantId;
- }
- return undefined;
-}
-/**
- * Builds the authentication scopes based on the information that comes in the
- * challenge information. Scopes url is present in the resource_id, if it is empty
- * we keep using the original scopes.
- */
-function buildScopes(challengeOptions, challengeInfo) {
- if (!challengeInfo.resource_id) {
- return challengeOptions.scopes;
- }
- const challengeScopes = new URL(challengeInfo.resource_id);
- challengeScopes.pathname = Constants.DefaultScope;
- let scope = challengeScopes.toString();
- if (scope === "https://disk.azure.com/.default") {
- // the extra slash is required by the service
- scope = "https://disk.azure.com//.default";
- }
- return [scope];
-}
-/**
- * We will retrieve the challenge only if the response status code was 401,
- * and if the response contained the header "WWW-Authenticate" with a non-empty value.
- */
-function getChallenge(response) {
- const challenge = response.headers.get("WWW-Authenticate");
- if (response.status === 401 && challenge) {
- return challenge;
- }
- return;
-}
-/**
- * Converts: `Bearer a="b" c="d"`.
- * Into: `[ { a: 'b', c: 'd' }]`.
- *
- * @internal
- */
-function parseChallenge(challenge) {
- const bearerChallenge = challenge.slice("Bearer ".length);
- const challengeParts = `${bearerChallenge.trim()} `.split(" ").filter((x) => x);
- const keyValuePairs = challengeParts.map((keyValue) => (([key, value]) => ({ [key]: value }))(keyValue.trim().split("=")));
- // Key-value pairs to plain object:
- return keyValuePairs.reduce((a, b) => ({ ...a, ...b }), {});
-}
-/**
- * Extracts the options form a Pipeline Request for later re-use
- */
-function requestToOptions(request) {
- return {
- abortSignal: request.abortSignal,
- requestOptions: {
- timeout: request.timeout,
- },
- tracingOptions: request.tracingOptions,
- };
-}
-//# sourceMappingURL=authorizeRequestOnTenantChallenge.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-client/dist/esm/index.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-
-
-
-
-
-
-//# sourceMappingURL=index.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-http-compat/dist/esm/util.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-// We use a custom symbol to cache a reference to the original request without
-// exposing it on the public interface.
-const util_originalRequestSymbol = Symbol("Original PipelineRequest");
-// Symbol.for() will return the same symbol if it's already been created
-// This particular one is used in core-client to handle the case of when a request is
-// cloned but we need to retrieve the OperationSpec and OperationArguments from the
-// original request.
-const originalClientRequestSymbol = Symbol.for("@azure/core-client original request");
-function toPipelineRequest(webResource, options = {}) {
- const compatWebResource = webResource;
- const request = compatWebResource[util_originalRequestSymbol];
- const headers = esm_httpHeaders_createHttpHeaders(webResource.headers.toJson({ preserveCase: true }));
- if (request) {
- request.headers = headers;
- return request;
- }
- else {
- const newRequest = esm_pipelineRequest_createPipelineRequest({
- url: webResource.url,
- method: webResource.method,
- headers,
- withCredentials: webResource.withCredentials,
- timeout: webResource.timeout,
- requestId: webResource.requestId,
- abortSignal: webResource.abortSignal,
- body: webResource.body,
- formData: webResource.formData,
- disableKeepAlive: !!webResource.keepAlive,
- onDownloadProgress: webResource.onDownloadProgress,
- onUploadProgress: webResource.onUploadProgress,
- proxySettings: webResource.proxySettings,
- streamResponseStatusCodes: webResource.streamResponseStatusCodes,
- agent: webResource.agent,
- requestOverrides: webResource.requestOverrides,
- });
- if (options.originalRequest) {
- newRequest[originalClientRequestSymbol] =
- options.originalRequest;
- }
- return newRequest;
- }
-}
-function toWebResourceLike(request, options) {
- const originalRequest = options?.originalRequest ?? request;
- const webResource = {
- url: request.url,
- method: request.method,
- headers: toHttpHeadersLike(request.headers),
- withCredentials: request.withCredentials,
- timeout: request.timeout,
- requestId: request.headers.get("x-ms-client-request-id") || request.requestId,
- abortSignal: request.abortSignal,
- body: request.body,
- formData: request.formData,
- keepAlive: !!request.disableKeepAlive,
- onDownloadProgress: request.onDownloadProgress,
- onUploadProgress: request.onUploadProgress,
- proxySettings: request.proxySettings,
- streamResponseStatusCodes: request.streamResponseStatusCodes,
- agent: request.agent,
- requestOverrides: request.requestOverrides,
- clone() {
- throw new Error("Cannot clone a non-proxied WebResourceLike");
- },
- prepare() {
- throw new Error("WebResourceLike.prepare() is not supported by @azure/core-http-compat");
- },
- validateRequestProperties() {
- /** do nothing */
- },
- };
- if (options?.createProxy) {
- return new Proxy(webResource, {
- get(target, prop, receiver) {
- if (prop === util_originalRequestSymbol) {
- return request;
- }
- else if (prop === "clone") {
- return () => {
- return toWebResourceLike(toPipelineRequest(webResource, { originalRequest }), {
- createProxy: true,
- originalRequest,
- });
- };
- }
- return Reflect.get(target, prop, receiver);
- },
- set(target, prop, value, receiver) {
- if (prop === "keepAlive") {
- request.disableKeepAlive = !value;
- }
- const passThroughProps = [
- "url",
- "method",
- "withCredentials",
- "timeout",
- "requestId",
- "abortSignal",
- "body",
- "formData",
- "onDownloadProgress",
- "onUploadProgress",
- "proxySettings",
- "streamResponseStatusCodes",
- "agent",
- "requestOverrides",
- ];
- if (typeof prop === "string" && passThroughProps.includes(prop)) {
- request[prop] = value;
- }
- return Reflect.set(target, prop, value, receiver);
- },
- });
- }
- else {
- return webResource;
- }
-}
-/**
- * Converts HttpHeaders from core-rest-pipeline to look like
- * HttpHeaders from core-http.
- * @param headers - HttpHeaders from core-rest-pipeline
- * @returns HttpHeaders as they looked in core-http
- */
-function toHttpHeadersLike(headers) {
- return new HttpHeaders(headers.toJSON({ preserveCase: true }));
-}
-/**
- * A collection of HttpHeaders that can be sent with a HTTP request.
- */
-function getHeaderKey(headerName) {
- return headerName.toLowerCase();
-}
-/**
- * A collection of HTTP header key/value pairs.
- */
-class HttpHeaders {
- _headersMap;
- constructor(rawHeaders) {
- this._headersMap = {};
- if (rawHeaders) {
- for (const headerName in rawHeaders) {
- this.set(headerName, rawHeaders[headerName]);
- }
- }
- }
- /**
- * Set a header in this collection with the provided name and value. The name is
- * case-insensitive.
- * @param headerName - The name of the header to set. This value is case-insensitive.
- * @param headerValue - The value of the header to set.
- */
- set(headerName, headerValue) {
- this._headersMap[getHeaderKey(headerName)] = {
- name: headerName,
- value: headerValue.toString(),
- };
- }
- /**
- * Get the header value for the provided header name, or undefined if no header exists in this
- * collection with the provided name.
- * @param headerName - The name of the header.
- */
- get(headerName) {
- const header = this._headersMap[getHeaderKey(headerName)];
- return !header ? undefined : header.value;
- }
- /**
- * Get whether or not this header collection contains a header entry for the provided header name.
- */
- contains(headerName) {
- return !!this._headersMap[getHeaderKey(headerName)];
- }
- /**
- * Remove the header with the provided headerName. Return whether or not the header existed and
- * was removed.
- * @param headerName - The name of the header to remove.
- */
- remove(headerName) {
- const result = this.contains(headerName);
- delete this._headersMap[getHeaderKey(headerName)];
- return result;
- }
- /**
- * Get the headers that are contained this collection as an object.
- */
- rawHeaders() {
- return this.toJson({ preserveCase: true });
- }
- /**
- * Get the headers that are contained in this collection as an array.
- */
- headersArray() {
- const headers = [];
- for (const headerKey in this._headersMap) {
- headers.push(this._headersMap[headerKey]);
- }
- return headers;
- }
- /**
- * Get the header names that are contained in this collection.
- */
- headerNames() {
- const headerNames = [];
- const headers = this.headersArray();
- for (let i = 0; i < headers.length; ++i) {
- headerNames.push(headers[i].name);
- }
- return headerNames;
- }
- /**
- * Get the header values that are contained in this collection.
- */
- headerValues() {
- const headerValues = [];
- const headers = this.headersArray();
- for (let i = 0; i < headers.length; ++i) {
- headerValues.push(headers[i].value);
- }
- return headerValues;
- }
- /**
- * Get the JSON object representation of this HTTP header collection.
- */
- toJson(options = {}) {
- const result = {};
- if (options.preserveCase) {
- for (const headerKey in this._headersMap) {
- const header = this._headersMap[headerKey];
- result[header.name] = header.value;
- }
- }
- else {
- for (const headerKey in this._headersMap) {
- const header = this._headersMap[headerKey];
- result[getHeaderKey(header.name)] = header.value;
- }
- }
- return result;
- }
- /**
- * Get the string representation of this HTTP header collection.
- */
- toString() {
- return JSON.stringify(this.toJson({ preserveCase: true }));
- }
- /**
- * Create a deep clone/copy of this HttpHeaders collection.
- */
- clone() {
- const resultPreservingCasing = {};
- for (const headerKey in this._headersMap) {
- const header = this._headersMap[headerKey];
- resultPreservingCasing[header.name] = header.value;
- }
- return new HttpHeaders(resultPreservingCasing);
- }
-}
-//# sourceMappingURL=util.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-http-compat/dist/esm/response.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-const originalResponse = Symbol("Original FullOperationResponse");
-/**
- * A helper to convert response objects from the new pipeline back to the old one.
- * @param response - A response object from core-client.
- * @returns A response compatible with `HttpOperationResponse` from core-http.
- */
-function toCompatResponse(response, options) {
- let request = toWebResourceLike(response.request);
- let headers = toHttpHeadersLike(response.headers);
- if (options?.createProxy) {
- return new Proxy(response, {
- get(target, prop, receiver) {
- if (prop === "headers") {
- return headers;
- }
- else if (prop === "request") {
- return request;
- }
- else if (prop === originalResponse) {
- return response;
- }
- return Reflect.get(target, prop, receiver);
- },
- set(target, prop, value, receiver) {
- if (prop === "headers") {
- headers = value;
- }
- else if (prop === "request") {
- request = value;
- }
- return Reflect.set(target, prop, value, receiver);
- },
- });
- }
- else {
- return {
- ...response,
- request,
- headers,
- };
- }
-}
-/**
- * A helper to convert back to a PipelineResponse
- * @param compatResponse - A response compatible with `HttpOperationResponse` from core-http.
- */
-function response_toPipelineResponse(compatResponse) {
- const extendedCompatResponse = compatResponse;
- const response = extendedCompatResponse[originalResponse];
- const headers = esm_httpHeaders_createHttpHeaders(compatResponse.headers.toJson({ preserveCase: true }));
- if (response) {
- response.headers = headers;
- return response;
- }
- else {
- return {
- ...compatResponse,
- headers,
- request: toPipelineRequest(compatResponse.request),
- };
- }
-}
-//# sourceMappingURL=response.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-http-compat/dist/esm/extendedClient.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-
-
-/**
- * Client to provide compatability between core V1 & V2.
- */
-class ExtendedServiceClient extends ServiceClient {
- constructor(options) {
- super(options);
- if (options.keepAliveOptions?.enable === false &&
- !pipelineContainsDisableKeepAlivePolicy(this.pipeline)) {
- this.pipeline.addPolicy(createDisableKeepAlivePolicy());
- }
- if (options.redirectOptions?.handleRedirects === false) {
- this.pipeline.removePolicy({
- name: redirectPolicy_redirectPolicyName,
- });
- }
- }
- /**
- * Compatible send operation request function.
- *
- * @param operationArguments - Operation arguments
- * @param operationSpec - Operation Spec
- * @returns
- */
- async sendOperationRequest(operationArguments, operationSpec) {
- const userProvidedCallBack = operationArguments?.options?.onResponse;
- let lastResponse;
- function onResponse(rawResponse, flatResponse, error) {
- lastResponse = rawResponse;
- if (userProvidedCallBack) {
- userProvidedCallBack(rawResponse, flatResponse, error);
- }
- }
- operationArguments.options = {
- ...operationArguments.options,
- onResponse,
- };
- const result = await super.sendOperationRequest(operationArguments, operationSpec);
- if (lastResponse) {
- Object.defineProperty(result, "_response", {
- value: toCompatResponse(lastResponse),
- });
- }
- return result;
- }
-}
-//# sourceMappingURL=extendedClient.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-http-compat/dist/esm/policies/requestPolicyFactoryPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-/**
- * An enum for compatibility with RequestPolicy
- */
-var HttpPipelineLogLevel;
-(function (HttpPipelineLogLevel) {
- HttpPipelineLogLevel[HttpPipelineLogLevel["ERROR"] = 1] = "ERROR";
- HttpPipelineLogLevel[HttpPipelineLogLevel["INFO"] = 3] = "INFO";
- HttpPipelineLogLevel[HttpPipelineLogLevel["OFF"] = 0] = "OFF";
- HttpPipelineLogLevel[HttpPipelineLogLevel["WARNING"] = 2] = "WARNING";
-})(HttpPipelineLogLevel || (HttpPipelineLogLevel = {}));
-const mockRequestPolicyOptions = {
- log(_logLevel, _message) {
- /* do nothing */
- },
- shouldLog(_logLevel) {
- return false;
- },
-};
-/**
- * The name of the RequestPolicyFactoryPolicy
- */
-const requestPolicyFactoryPolicyName = "RequestPolicyFactoryPolicy";
-/**
- * A policy that wraps policies written for core-http.
- * @param factories - An array of `RequestPolicyFactory` objects from a core-http pipeline
- */
-function createRequestPolicyFactoryPolicy(factories) {
- const orderedFactories = factories.slice().reverse();
- return {
- name: requestPolicyFactoryPolicyName,
- async sendRequest(request, next) {
- let httpPipeline = {
- async sendRequest(httpRequest) {
- const response = await next(toPipelineRequest(httpRequest));
- return toCompatResponse(response, { createProxy: true });
- },
- };
- for (const factory of orderedFactories) {
- httpPipeline = factory.create(httpPipeline, mockRequestPolicyOptions);
- }
- const webResourceLike = toWebResourceLike(request, { createProxy: true });
- const response = await httpPipeline.sendRequest(webResourceLike);
- return response_toPipelineResponse(response);
- },
- };
-}
-//# sourceMappingURL=requestPolicyFactoryPolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-http-compat/dist/esm/httpClientAdapter.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-/**
- * Converts a RequestPolicy based HttpClient to a PipelineRequest based HttpClient.
- * @param requestPolicyClient - A HttpClient compatible with core-http
- * @returns A HttpClient compatible with core-rest-pipeline
- */
-function convertHttpClient(requestPolicyClient) {
- return {
- sendRequest: async (request) => {
- const response = await requestPolicyClient.sendRequest(toWebResourceLike(request, { createProxy: true }));
- return response_toPipelineResponse(response);
- },
- };
-}
-//# sourceMappingURL=httpClientAdapter.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-http-compat/dist/esm/index.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-/**
- * A Shim Library that provides compatibility between Core V1 & V2 Packages.
- *
- * @packageDocumentation
- */
-
-
-
-
-
-//# sourceMappingURL=index.js.map
-;// CONCATENATED MODULE: ./node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js
-const EOL = "\n";
-
-/**
- *
- * @param {array} jArray
- * @param {any} options
- * @returns
- */
-function toXml(jArray, options) {
- let indentation = "";
- if (options.format && options.indentBy.length > 0) {
- indentation = EOL;
- }
- return arrToStr(jArray, options, "", indentation);
-}
-
-function arrToStr(arr, options, jPath, indentation) {
- let xmlStr = "";
- let isPreviousElementTag = false;
-
- for (let i = 0; i < arr.length; i++) {
- const tagObj = arr[i];
- const tagName = propName(tagObj);
- if(tagName === undefined) continue;
-
- let newJPath = "";
- if (jPath.length === 0) newJPath = tagName
- else newJPath = `${jPath}.${tagName}`;
-
- if (tagName === options.textNodeName) {
- let tagText = tagObj[tagName];
- if (!isStopNode(newJPath, options)) {
- tagText = options.tagValueProcessor(tagName, tagText);
- tagText = replaceEntitiesValue(tagText, options);
- }
- if (isPreviousElementTag) {
- xmlStr += indentation;
- }
- xmlStr += tagText;
- isPreviousElementTag = false;
- continue;
- } else if (tagName === options.cdataPropName) {
- if (isPreviousElementTag) {
- xmlStr += indentation;
- }
- xmlStr += ``;
- isPreviousElementTag = false;
- continue;
- } else if (tagName === options.commentPropName) {
- xmlStr += indentation + ``;
- isPreviousElementTag = true;
- continue;
- } else if (tagName[0] === "?") {
- const attStr = attr_to_str(tagObj[":@"], options);
- const tempInd = tagName === "?xml" ? "" : indentation;
- let piTextNodeName = tagObj[tagName][0][options.textNodeName];
- piTextNodeName = piTextNodeName.length !== 0 ? " " + piTextNodeName : ""; //remove extra spacing
- xmlStr += tempInd + `<${tagName}${piTextNodeName}${attStr}?>`;
- isPreviousElementTag = true;
- continue;
- }
- let newIdentation = indentation;
- if (newIdentation !== "") {
- newIdentation += options.indentBy;
- }
- const attStr = attr_to_str(tagObj[":@"], options);
- const tagStart = indentation + `<${tagName}${attStr}`;
- const tagValue = arrToStr(tagObj[tagName], options, newJPath, newIdentation);
- if (options.unpairedTags.indexOf(tagName) !== -1) {
- if (options.suppressUnpairedNode) xmlStr += tagStart + ">";
- else xmlStr += tagStart + "/>";
- } else if ((!tagValue || tagValue.length === 0) && options.suppressEmptyNode) {
- xmlStr += tagStart + "/>";
- } else if (tagValue && tagValue.endsWith(">")) {
- xmlStr += tagStart + `>${tagValue}${indentation}${tagName}>`;
- } else {
- xmlStr += tagStart + ">";
- if (tagValue && indentation !== "" && (tagValue.includes("/>") || tagValue.includes(""))) {
- xmlStr += indentation + options.indentBy + tagValue + indentation;
- } else {
- xmlStr += tagValue;
- }
- xmlStr += `${tagName}>`;
- }
- isPreviousElementTag = true;
- }
-
- return xmlStr;
-}
-
-function propName(obj) {
- const keys = Object.keys(obj);
- for (let i = 0; i < keys.length; i++) {
- const key = keys[i];
- if(!obj.hasOwnProperty(key)) continue;
- if (key !== ":@") return key;
- }
-}
-
-function attr_to_str(attrMap, options) {
- let attrStr = "";
- if (attrMap && !options.ignoreAttributes) {
- for (let attr in attrMap) {
- if(!attrMap.hasOwnProperty(attr)) continue;
- let attrVal = options.attributeValueProcessor(attr, attrMap[attr]);
- attrVal = replaceEntitiesValue(attrVal, options);
- if (attrVal === true && options.suppressBooleanAttributes) {
- attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}`;
- } else {
- attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}="${attrVal}"`;
- }
- }
- }
- return attrStr;
-}
-
-function isStopNode(jPath, options) {
- jPath = jPath.substr(0, jPath.length - options.textNodeName.length - 1);
- let tagName = jPath.substr(jPath.lastIndexOf(".") + 1);
- for (let index in options.stopNodes) {
- if (options.stopNodes[index] === jPath || options.stopNodes[index] === "*." + tagName) return true;
- }
- return false;
-}
-
-function replaceEntitiesValue(textValue, options) {
- if (textValue && textValue.length > 0 && options.processEntities) {
- for (let i = 0; i < options.entities.length; i++) {
- const entity = options.entities[i];
- textValue = textValue.replace(entity.regex, entity.val);
- }
- }
- return textValue;
-}
-
-;// CONCATENATED MODULE: ./node_modules/fast-xml-parser/src/ignoreAttributes.js
-function getIgnoreAttributesFn(ignoreAttributes) {
- if (typeof ignoreAttributes === 'function') {
- return ignoreAttributes
- }
- if (Array.isArray(ignoreAttributes)) {
- return (attrName) => {
- for (const pattern of ignoreAttributes) {
- if (typeof pattern === 'string' && attrName === pattern) {
- return true
- }
- if (pattern instanceof RegExp && pattern.test(attrName)) {
- return true
- }
- }
- }
- }
- return () => false
-}
-;// CONCATENATED MODULE: ./node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js
-
-//parse Empty Node as self closing node
-
-
-
-const defaultOptions = {
- attributeNamePrefix: '@_',
- attributesGroupName: false,
- textNodeName: '#text',
- ignoreAttributes: true,
- cdataPropName: false,
- format: false,
- indentBy: ' ',
- suppressEmptyNode: false,
- suppressUnpairedNode: true,
- suppressBooleanAttributes: true,
- tagValueProcessor: function(key, a) {
- return a;
- },
- attributeValueProcessor: function(attrName, a) {
- return a;
- },
- preserveOrder: false,
- commentPropName: false,
- unpairedTags: [],
- entities: [
- { regex: new RegExp("&", "g"), val: "&" },//it must be on top
- { regex: new RegExp(">", "g"), val: ">" },
- { regex: new RegExp("<", "g"), val: "<" },
- { regex: new RegExp("\'", "g"), val: "'" },
- { regex: new RegExp("\"", "g"), val: """ }
- ],
- processEntities: true,
- stopNodes: [],
- // transformTagName: false,
- // transformAttributeName: false,
- oneListGroup: false
-};
-
-function Builder(options) {
- this.options = Object.assign({}, defaultOptions, options);
- if (this.options.ignoreAttributes === true || this.options.attributesGroupName) {
- this.isAttribute = function(/*a*/) {
- return false;
- };
- } else {
- this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes)
- this.attrPrefixLen = this.options.attributeNamePrefix.length;
- this.isAttribute = isAttribute;
- }
-
- this.processTextOrObjNode = processTextOrObjNode
-
- if (this.options.format) {
- this.indentate = indentate;
- this.tagEndChar = '>\n';
- this.newLine = '\n';
- } else {
- this.indentate = function() {
- return '';
- };
- this.tagEndChar = '>';
- this.newLine = '';
- }
-}
-
-Builder.prototype.build = function(jObj) {
- if(this.options.preserveOrder){
- return toXml(jObj, this.options);
- }else {
- if(Array.isArray(jObj) && this.options.arrayNodeName && this.options.arrayNodeName.length > 1){
- jObj = {
- [this.options.arrayNodeName] : jObj
- }
- }
- return this.j2x(jObj, 0, []).val;
- }
-};
-
-Builder.prototype.j2x = function(jObj, level, ajPath) {
- let attrStr = '';
- let val = '';
- const jPath = ajPath.join('.')
- for (let key in jObj) {
- if(!Object.prototype.hasOwnProperty.call(jObj, key)) continue;
- if (typeof jObj[key] === 'undefined') {
- // supress undefined node only if it is not an attribute
- if (this.isAttribute(key)) {
- val += '';
- }
- } else if (jObj[key] === null) {
- // null attribute should be ignored by the attribute list, but should not cause the tag closing
- if (this.isAttribute(key)) {
- val += '';
- } else if (key === this.options.cdataPropName) {
- val += '';
- } else if (key[0] === '?') {
- val += this.indentate(level) + '<' + key + '?' + this.tagEndChar;
- } else {
- val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;
- }
- // val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;
- } else if (jObj[key] instanceof Date) {
- val += this.buildTextValNode(jObj[key], key, '', level);
- } else if (typeof jObj[key] !== 'object') {
- //premitive type
- const attr = this.isAttribute(key);
- if (attr && !this.ignoreAttributesFn(attr, jPath)) {
- attrStr += this.buildAttrPairStr(attr, '' + jObj[key]);
- } else if (!attr) {
- //tag value
- if (key === this.options.textNodeName) {
- let newval = this.options.tagValueProcessor(key, '' + jObj[key]);
- val += this.replaceEntitiesValue(newval);
- } else {
- val += this.buildTextValNode(jObj[key], key, '', level);
- }
- }
- } else if (Array.isArray(jObj[key])) {
- //repeated nodes
- const arrLen = jObj[key].length;
- let listTagVal = "";
- let listTagAttr = "";
- for (let j = 0; j < arrLen; j++) {
- const item = jObj[key][j];
- if (typeof item === 'undefined') {
- // supress undefined node
- } else if (item === null) {
- if(key[0] === "?") val += this.indentate(level) + '<' + key + '?' + this.tagEndChar;
- else val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;
- // val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;
- } else if (typeof item === 'object') {
- if(this.options.oneListGroup){
- const result = this.j2x(item, level + 1, ajPath.concat(key));
- listTagVal += result.val;
- if (this.options.attributesGroupName && item.hasOwnProperty(this.options.attributesGroupName)) {
- listTagAttr += result.attrStr
- }
- }else{
- listTagVal += this.processTextOrObjNode(item, key, level, ajPath)
- }
- } else {
- if (this.options.oneListGroup) {
- let textValue = this.options.tagValueProcessor(key, item);
- textValue = this.replaceEntitiesValue(textValue);
- listTagVal += textValue;
- } else {
- listTagVal += this.buildTextValNode(item, key, '', level);
- }
- }
- }
- if(this.options.oneListGroup){
- listTagVal = this.buildObjectNode(listTagVal, key, listTagAttr, level);
- }
- val += listTagVal;
- } else {
- //nested node
- if (this.options.attributesGroupName && key === this.options.attributesGroupName) {
- const Ks = Object.keys(jObj[key]);
- const L = Ks.length;
- for (let j = 0; j < L; j++) {
- attrStr += this.buildAttrPairStr(Ks[j], '' + jObj[key][Ks[j]]);
- }
- } else {
- val += this.processTextOrObjNode(jObj[key], key, level, ajPath)
- }
- }
- }
- return {attrStr: attrStr, val: val};
-};
-
-Builder.prototype.buildAttrPairStr = function(attrName, val){
- val = this.options.attributeValueProcessor(attrName, '' + val);
- val = this.replaceEntitiesValue(val);
- if (this.options.suppressBooleanAttributes && val === "true") {
- return ' ' + attrName;
- } else return ' ' + attrName + '="' + val + '"';
-}
-
-function processTextOrObjNode (object, key, level, ajPath) {
- const result = this.j2x(object, level + 1, ajPath.concat(key));
- if (object[this.options.textNodeName] !== undefined && Object.keys(object).length === 1) {
- return this.buildTextValNode(object[this.options.textNodeName], key, result.attrStr, level);
- } else {
- return this.buildObjectNode(result.val, key, result.attrStr, level);
- }
-}
-
-Builder.prototype.buildObjectNode = function(val, key, attrStr, level) {
- if(val === ""){
- if(key[0] === "?") return this.indentate(level) + '<' + key + attrStr+ '?' + this.tagEndChar;
- else {
- return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar;
- }
- }else{
-
- let tagEndExp = '' + key + this.tagEndChar;
- let piClosingChar = "";
-
- if(key[0] === "?") {
- piClosingChar = "?";
- tagEndExp = "";
- }
-
- // attrStr is an empty string in case the attribute came as undefined or null
- if ((attrStr || attrStr === '') && val.indexOf('<') === -1) {
- return ( this.indentate(level) + '<' + key + attrStr + piClosingChar + '>' + val + tagEndExp );
- } else if (this.options.commentPropName !== false && key === this.options.commentPropName && piClosingChar.length === 0) {
- return this.indentate(level) + `` + this.newLine;
- }else {
- return (
- this.indentate(level) + '<' + key + attrStr + piClosingChar + this.tagEndChar +
- val +
- this.indentate(level) + tagEndExp );
- }
- }
-}
-
-Builder.prototype.closeTag = function(key){
- let closeTag = "";
- if(this.options.unpairedTags.indexOf(key) !== -1){ //unpaired
- if(!this.options.suppressUnpairedNode) closeTag = "/"
- }else if(this.options.suppressEmptyNode){ //empty
- closeTag = "/";
- }else{
- closeTag = `>${key}`
- }
- return closeTag;
-}
-
-function buildEmptyObjNode(val, key, attrStr, level) {
- if (val !== '') {
- return this.buildObjectNode(val, key, attrStr, level);
- } else {
- if(key[0] === "?") return this.indentate(level) + '<' + key + attrStr+ '?' + this.tagEndChar;
- else {
- return this.indentate(level) + '<' + key + attrStr + '/' + this.tagEndChar;
- // return this.buildTagStr(level,key, attrStr);
- }
- }
-}
-
-Builder.prototype.buildTextValNode = function(val, key, attrStr, level) {
- if (this.options.cdataPropName !== false && key === this.options.cdataPropName) {
- return this.indentate(level) + `` + this.newLine;
- }else if (this.options.commentPropName !== false && key === this.options.commentPropName) {
- return this.indentate(level) + `` + this.newLine;
- }else if(key[0] === "?") {//PI tag
- return this.indentate(level) + '<' + key + attrStr+ '?' + this.tagEndChar;
- }else{
- let textValue = this.options.tagValueProcessor(key, val);
- textValue = this.replaceEntitiesValue(textValue);
-
- if( textValue === ''){
- return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar;
- }else{
- return this.indentate(level) + '<' + key + attrStr + '>' +
- textValue +
- '' + key + this.tagEndChar;
- }
- }
-}
-
-Builder.prototype.replaceEntitiesValue = function(textValue){
- if(textValue && textValue.length > 0 && this.options.processEntities){
- for (let i=0; i","g");
-function validate(xmlData, options) {
- options = Object.assign({}, validator_defaultOptions, options);
-
- //xmlData = xmlData.replace(/(\r\n|\n|\r)/gm,"");//make it single line
- //xmlData = xmlData.replace(/(^\s*<\?xml.*?\?>)/g,"");//Remove XML starting tag
- //xmlData = xmlData.replace(/()/g,"");//Remove DOCTYPE
- const tags = [];
- let tagFound = false;
-
- //indicates that the root tag has been closed (aka. depth 0 has been reached)
- let reachedRoot = false;
-
- if (xmlData[0] === '\ufeff') {
- // check for byte order mark (BOM)
- xmlData = xmlData.substr(1);
- }
-
- for (let i = 0; i < xmlData.length; i++) {
-
- if (xmlData[i] === '<' && xmlData[i+1] === '?') {
- i+=2;
- i = readPI(xmlData,i);
- if (i.err) return i;
- }else if (xmlData[i] === '<') {
- //starting of tag
- //read until you reach to '>' avoiding any '>' in attribute value
- let tagStartPos = i;
- i++;
-
- if (xmlData[i] === '!') {
- i = readCommentAndCDATA(xmlData, i);
- continue;
- } else {
- let closingTag = false;
- if (xmlData[i] === '/') {
- //closing tag
- closingTag = true;
- i++;
- }
- //read tagname
- let tagName = '';
- for (; i < xmlData.length &&
- xmlData[i] !== '>' &&
- xmlData[i] !== ' ' &&
- xmlData[i] !== '\t' &&
- xmlData[i] !== '\n' &&
- xmlData[i] !== '\r'; i++
- ) {
- tagName += xmlData[i];
- }
- tagName = tagName.trim();
- //console.log(tagName);
-
- if (tagName[tagName.length - 1] === '/') {
- //self closing tag without attributes
- tagName = tagName.substring(0, tagName.length - 1);
- //continue;
- i--;
- }
- if (!validateTagName(tagName)) {
- let msg;
- if (tagName.trim().length === 0) {
- msg = "Invalid space after '<'.";
- } else {
- msg = "Tag '"+tagName+"' is an invalid name.";
- }
- return getErrorObject('InvalidTag', msg, getLineNumberForPosition(xmlData, i));
- }
-
- const result = readAttributeStr(xmlData, i);
- if (result === false) {
- return getErrorObject('InvalidAttr', "Attributes for '"+tagName+"' have open quote.", getLineNumberForPosition(xmlData, i));
- }
- let attrStr = result.value;
- i = result.index;
-
- if (attrStr[attrStr.length - 1] === '/') {
- //self closing tag
- const attrStrStart = i - attrStr.length;
- attrStr = attrStr.substring(0, attrStr.length - 1);
- const isValid = validateAttributeString(attrStr, options);
- if (isValid === true) {
- tagFound = true;
- //continue; //text may presents after self closing tag
- } else {
- //the result from the nested function returns the position of the error within the attribute
- //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute
- //this gives us the absolute index in the entire xml, which we can use to find the line at last
- return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid.err.line));
- }
- } else if (closingTag) {
- if (!result.tagClosed) {
- return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' doesn't have proper closing.", getLineNumberForPosition(xmlData, i));
- } else if (attrStr.trim().length > 0) {
- return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' can't have attributes or invalid starting.", getLineNumberForPosition(xmlData, tagStartPos));
- } else if (tags.length === 0) {
- return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' has not been opened.", getLineNumberForPosition(xmlData, tagStartPos));
- } else {
- const otg = tags.pop();
- if (tagName !== otg.tagName) {
- let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos);
- return getErrorObject('InvalidTag',
- "Expected closing tag '"+otg.tagName+"' (opened in line "+openPos.line+", col "+openPos.col+") instead of closing tag '"+tagName+"'.",
- getLineNumberForPosition(xmlData, tagStartPos));
- }
-
- //when there are no more tags, we reached the root level.
- if (tags.length == 0) {
- reachedRoot = true;
- }
- }
- } else {
- const isValid = validateAttributeString(attrStr, options);
- if (isValid !== true) {
- //the result from the nested function returns the position of the error within the attribute
- //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute
- //this gives us the absolute index in the entire xml, which we can use to find the line at last
- return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, i - attrStr.length + isValid.err.line));
- }
-
- //if the root level has been reached before ...
- if (reachedRoot === true) {
- return getErrorObject('InvalidXml', 'Multiple possible root nodes found.', getLineNumberForPosition(xmlData, i));
- } else if(options.unpairedTags.indexOf(tagName) !== -1){
- //don't push into stack
- } else {
- tags.push({tagName, tagStartPos});
- }
- tagFound = true;
- }
-
- //skip tag text value
- //It may include comments and CDATA value
- for (i++; i < xmlData.length; i++) {
- if (xmlData[i] === '<') {
- if (xmlData[i + 1] === '!') {
- //comment or CADATA
- i++;
- i = readCommentAndCDATA(xmlData, i);
- continue;
- } else if (xmlData[i+1] === '?') {
- i = readPI(xmlData, ++i);
- if (i.err) return i;
- } else{
- break;
- }
- } else if (xmlData[i] === '&') {
- const afterAmp = validateAmpersand(xmlData, i);
- if (afterAmp == -1)
- return getErrorObject('InvalidChar', "char '&' is not expected.", getLineNumberForPosition(xmlData, i));
- i = afterAmp;
- }else{
- if (reachedRoot === true && !isWhiteSpace(xmlData[i])) {
- return getErrorObject('InvalidXml', "Extra text at the end", getLineNumberForPosition(xmlData, i));
- }
- }
- } //end of reading tag text value
- if (xmlData[i] === '<') {
- i--;
- }
- }
- } else {
- if ( isWhiteSpace(xmlData[i])) {
- continue;
- }
- return getErrorObject('InvalidChar', "char '"+xmlData[i]+"' is not expected.", getLineNumberForPosition(xmlData, i));
- }
- }
-
- if (!tagFound) {
- return getErrorObject('InvalidXml', 'Start tag expected.', 1);
- }else if (tags.length == 1) {
- return getErrorObject('InvalidTag', "Unclosed tag '"+tags[0].tagName+"'.", getLineNumberForPosition(xmlData, tags[0].tagStartPos));
- }else if (tags.length > 0) {
- return getErrorObject('InvalidXml', "Invalid '"+
- JSON.stringify(tags.map(t => t.tagName), null, 4).replace(/\r?\n/g, '')+
- "' found.", {line: 1, col: 1});
- }
-
- return true;
-};
-
-function isWhiteSpace(char){
- return char === ' ' || char === '\t' || char === '\n' || char === '\r';
-}
-/**
- * Read Processing insstructions and skip
- * @param {*} xmlData
- * @param {*} i
- */
-function readPI(xmlData, i) {
- const start = i;
- for (; i < xmlData.length; i++) {
- if (xmlData[i] == '?' || xmlData[i] == ' ') {
- //tagname
- const tagname = xmlData.substr(start, i - start);
- if (i > 5 && tagname === 'xml') {
- return getErrorObject('InvalidXml', 'XML declaration allowed only at the start of the document.', getLineNumberForPosition(xmlData, i));
- } else if (xmlData[i] == '?' && xmlData[i + 1] == '>') {
- //check if valid attribut string
- i++;
- break;
- } else {
- continue;
- }
- }
- }
- return i;
-}
-
-function readCommentAndCDATA(xmlData, i) {
- if (xmlData.length > i + 5 && xmlData[i + 1] === '-' && xmlData[i + 2] === '-') {
- //comment
- for (i += 3; i < xmlData.length; i++) {
- if (xmlData[i] === '-' && xmlData[i + 1] === '-' && xmlData[i + 2] === '>') {
- i += 2;
- break;
- }
- }
- } else if (
- xmlData.length > i + 8 &&
- xmlData[i + 1] === 'D' &&
- xmlData[i + 2] === 'O' &&
- xmlData[i + 3] === 'C' &&
- xmlData[i + 4] === 'T' &&
- xmlData[i + 5] === 'Y' &&
- xmlData[i + 6] === 'P' &&
- xmlData[i + 7] === 'E'
- ) {
- let angleBracketsCount = 1;
- for (i += 8; i < xmlData.length; i++) {
- if (xmlData[i] === '<') {
- angleBracketsCount++;
- } else if (xmlData[i] === '>') {
- angleBracketsCount--;
- if (angleBracketsCount === 0) {
- break;
- }
- }
- }
- } else if (
- xmlData.length > i + 9 &&
- xmlData[i + 1] === '[' &&
- xmlData[i + 2] === 'C' &&
- xmlData[i + 3] === 'D' &&
- xmlData[i + 4] === 'A' &&
- xmlData[i + 5] === 'T' &&
- xmlData[i + 6] === 'A' &&
- xmlData[i + 7] === '['
- ) {
- for (i += 8; i < xmlData.length; i++) {
- if (xmlData[i] === ']' && xmlData[i + 1] === ']' && xmlData[i + 2] === '>') {
- i += 2;
- break;
- }
- }
- }
-
- return i;
-}
-
-const doubleQuote = '"';
-const singleQuote = "'";
-
-/**
- * Keep reading xmlData until '<' is found outside the attribute value.
- * @param {string} xmlData
- * @param {number} i
- */
-function readAttributeStr(xmlData, i) {
- let attrStr = '';
- let startChar = '';
- let tagClosed = false;
- for (; i < xmlData.length; i++) {
- if (xmlData[i] === doubleQuote || xmlData[i] === singleQuote) {
- if (startChar === '') {
- startChar = xmlData[i];
- } else if (startChar !== xmlData[i]) {
- //if vaue is enclosed with double quote then single quotes are allowed inside the value and vice versa
- } else {
- startChar = '';
- }
- } else if (xmlData[i] === '>') {
- if (startChar === '') {
- tagClosed = true;
- break;
- }
- }
- attrStr += xmlData[i];
- }
- if (startChar !== '') {
- return false;
- }
-
- return {
- value: attrStr,
- index: i,
- tagClosed: tagClosed
- };
-}
-
-/**
- * Select all the attributes whether valid or invalid.
- */
-const validAttrStrRegxp = new RegExp('(\\s*)([^\\s=]+)(\\s*=)?(\\s*([\'"])(([\\s\\S])*?)\\5)?', 'g');
-
-//attr, ="sd", a="amit's", a="sd"b="saf", ab cd=""
-
-function validateAttributeString(attrStr, options) {
- //console.log("start:"+attrStr+":end");
-
- //if(attrStr.trim().length === 0) return true; //empty string
-
- const matches = getAllMatches(attrStr, validAttrStrRegxp);
- const attrNames = {};
-
- for (let i = 0; i < matches.length; i++) {
- if (matches[i][1].length === 0) {
- //nospace before attribute name: a="sd"b="saf"
- return getErrorObject('InvalidAttr', "Attribute '"+matches[i][2]+"' has no space in starting.", getPositionFromMatch(matches[i]))
- } else if (matches[i][3] !== undefined && matches[i][4] === undefined) {
- return getErrorObject('InvalidAttr', "Attribute '"+matches[i][2]+"' is without value.", getPositionFromMatch(matches[i]));
- } else if (matches[i][3] === undefined && !options.allowBooleanAttributes) {
- //independent attribute: ab
- return getErrorObject('InvalidAttr', "boolean attribute '"+matches[i][2]+"' is not allowed.", getPositionFromMatch(matches[i]));
- }
- /* else if(matches[i][6] === undefined){//attribute without value: ab=
- return { err: { code:"InvalidAttr",msg:"attribute " + matches[i][2] + " has no value assigned."}};
- } */
- const attrName = matches[i][2];
- if (!validateAttrName(attrName)) {
- return getErrorObject('InvalidAttr', "Attribute '"+attrName+"' is an invalid name.", getPositionFromMatch(matches[i]));
- }
- if (!attrNames.hasOwnProperty(attrName)) {
- //check for duplicate attribute.
- attrNames[attrName] = 1;
- } else {
- return getErrorObject('InvalidAttr', "Attribute '"+attrName+"' is repeated.", getPositionFromMatch(matches[i]));
- }
- }
-
- return true;
-}
-
-function validateNumberAmpersand(xmlData, i) {
- let re = /\d/;
- if (xmlData[i] === 'x') {
- i++;
- re = /[\da-fA-F]/;
- }
- for (; i < xmlData.length; i++) {
- if (xmlData[i] === ';')
- return i;
- if (!xmlData[i].match(re))
- break;
- }
- return -1;
-}
-
-function validateAmpersand(xmlData, i) {
- // https://www.w3.org/TR/xml/#dt-charref
- i++;
- if (xmlData[i] === ';')
- return -1;
- if (xmlData[i] === '#') {
- i++;
- return validateNumberAmpersand(xmlData, i);
- }
- let count = 0;
- for (; i < xmlData.length; i++, count++) {
- if (xmlData[i].match(/\w/) && count < 20)
- continue;
- if (xmlData[i] === ';')
- break;
- return -1;
- }
- return i;
-}
-
-function getErrorObject(code, message, lineNumber) {
- return {
- err: {
- code: code,
- msg: message,
- line: lineNumber.line || lineNumber,
- col: lineNumber.col,
- },
- };
-}
-
-function validateAttrName(attrName) {
- return isName(attrName);
-}
-
-// const startsWithXML = /^xml/i;
-
-function validateTagName(tagname) {
- return isName(tagname) /* && !tagname.match(startsWithXML) */;
-}
-
-//this function returns the line number for the character at the given index
-function getLineNumberForPosition(xmlData, index) {
- const lines = xmlData.substring(0, index).split(/\r?\n/);
- return {
- line: lines.length,
-
- // column number is last line's length + 1, because column numbering starts at 1:
- col: lines[lines.length - 1].length + 1
- };
-}
-
-//this function returns the position of the first character of match within attrStr
-function getPositionFromMatch(match) {
- return match.startIndex + match[1].length;
-}
-
-;// CONCATENATED MODULE: ./node_modules/fast-xml-parser/src/fxp.js
-
-
-
-
-
-
-const XMLValidator = {
- validate: validate
-}
-
-;// CONCATENATED MODULE: ./node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js
-
-const OptionsBuilder_defaultOptions = {
- preserveOrder: false,
- attributeNamePrefix: '@_',
- attributesGroupName: false,
- textNodeName: '#text',
- ignoreAttributes: true,
- removeNSPrefix: false, // remove NS from tag name or attribute name if true
- allowBooleanAttributes: false, //a tag can have attributes without any value
- //ignoreRootElement : false,
- parseTagValue: true,
- parseAttributeValue: false,
- trimValues: true, //Trim string values of tag and attributes
- cdataPropName: false,
- numberParseOptions: {
- hex: true,
- leadingZeros: true,
- eNotation: true
- },
- tagValueProcessor: function(tagName, val) {
- return val;
- },
- attributeValueProcessor: function(attrName, val) {
- return val;
- },
- stopNodes: [], //nested tags will not be parsed even for errors
- alwaysCreateTextNode: false,
- isArray: () => false,
- commentPropName: false,
- unpairedTags: [],
- processEntities: true,
- htmlEntities: false,
- ignoreDeclaration: false,
- ignorePiTags: false,
- transformTagName: false,
- transformAttributeName: false,
- updateTag: function(tagName, jPath, attrs){
- return tagName
- },
- // skipEmptyListItem: false
- captureMetaData: false,
-};
-
-const buildOptions = function(options) {
- return Object.assign({}, OptionsBuilder_defaultOptions, options);
-};
-
-;// CONCATENATED MODULE: ./node_modules/fast-xml-parser/src/xmlparser/xmlNode.js
-
-
-let METADATA_SYMBOL;
-
-if (typeof Symbol !== "function") {
- METADATA_SYMBOL = "@@xmlMetadata";
-} else {
- METADATA_SYMBOL = Symbol("XML Node Metadata");
-}
-
-class XmlNode{
- constructor(tagname) {
- this.tagname = tagname;
- this.child = []; //nested tags, text, cdata, comments in order
- this[":@"] = {}; //attributes map
- }
- add(key,val){
- // this.child.push( {name : key, val: val, isCdata: isCdata });
- if(key === "__proto__") key = "#__proto__";
- this.child.push( {[key]: val });
- }
- addChild(node, startIndex) {
- if(node.tagname === "__proto__") node.tagname = "#__proto__";
- if(node[":@"] && Object.keys(node[":@"]).length > 0){
- this.child.push( { [node.tagname]: node.child, [":@"]: node[":@"] });
- }else{
- this.child.push( { [node.tagname]: node.child });
- }
- // if requested, add the startIndex
- if (startIndex !== undefined) {
- // Note: for now we just overwrite the metadata. If we had more complex metadata,
- // we might need to do an object append here: metadata = { ...metadata, startIndex }
- this.child[this.child.length - 1][METADATA_SYMBOL] = { startIndex };
- }
- }
- /** symbol used for metadata */
- static getMetaDataSymbol() {
- return METADATA_SYMBOL;
- }
-}
-
-;// CONCATENATED MODULE: ./node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js
-
-
-class DocTypeReader{
- constructor(processEntities){
- this.suppressValidationErr = !processEntities;
- }
-
- readDocType(xmlData, i){
-
- const entities = {};
- if( xmlData[i + 3] === 'O' &&
- xmlData[i + 4] === 'C' &&
- xmlData[i + 5] === 'T' &&
- xmlData[i + 6] === 'Y' &&
- xmlData[i + 7] === 'P' &&
- xmlData[i + 8] === 'E')
- {
- i = i+9;
- let angleBracketsCount = 1;
- let hasBody = false, comment = false;
- let exp = "";
- for(;i') { //Read tag content
- if(comment){
- if( xmlData[i - 1] === "-" && xmlData[i - 2] === "-"){
- comment = false;
- angleBracketsCount--;
- }
- }else{
- angleBracketsCount--;
- }
- if (angleBracketsCount === 0) {
- break;
- }
- }else if( xmlData[i] === '['){
- hasBody = true;
- }else{
- exp += xmlData[i];
- }
- }
- if(angleBracketsCount !== 0){
- throw new Error(`Unclosed DOCTYPE`);
- }
- }else{
- throw new Error(`Invalid Tag instead of DOCTYPE`);
- }
- return {entities, i};
- }
- readEntityExp(xmlData, i) {
- //External entities are not supported
- //
-
- //Parameter entities are not supported
- //
-
- //Internal entities are supported
- //
-
- // Skip leading whitespace after
- //
- //
- //
- //
-
- // Skip leading whitespace after {
- while (index < data.length && /\s/.test(data[index])) {
- index++;
- }
- return index;
-};
-
-
-
-function hasSeq(data, seq,i){
- for(let j=0;j [ , '+', '00', '.123', ..
- if(match){
- const sign = match[1] || "";
- const leadingZeros = match[2];
- let numTrimmedByZeros = trimZeros(match[3]); //complete num without leading zeros
- const decimalAdjacentToLeadingZeros = sign ? // 0., -00., 000.
- str[leadingZeros.length+1] === "."
- : str[leadingZeros.length] === ".";
-
- //trim ending zeros for floating number
- if(!options.leadingZeros //leading zeros are not allowed
- && (leadingZeros.length > 1
- || (leadingZeros.length === 1 && !decimalAdjacentToLeadingZeros))){
- // 00, 00.3, +03.24, 03, 03.24
- return str;
- }
- else{//no leading zeros or leading zeros are allowed
- const num = Number(trimmedStr);
- const parsedStr = String(num);
-
- if( num === 0) return num;
- if(parsedStr.search(/[eE]/) !== -1){ //given number is long and parsed to eNotation
- if(options.eNotation) return num;
- else return str;
- }else if(trimmedStr.indexOf(".") !== -1){ //floating number
- if(parsedStr === "0") return num; //0.0
- else if(parsedStr === numTrimmedByZeros) return num; //0.456. 0.79000
- else if( parsedStr === `${sign}${numTrimmedByZeros}`) return num;
- else return str;
- }
-
- let n = leadingZeros? numTrimmedByZeros : trimmedStr;
- if(leadingZeros){
- // -009 => -9
- return (n === parsedStr) || (sign+n === parsedStr) ? num : str
- }else {
- // +9
- return (n === parsedStr) || (n === sign+parsedStr) ? num : str
- }
- }
- }else{ //non-numeric string
- return str;
- }
- }
-}
-
-const eNotationRegx = /^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;
-function resolveEnotation(str,trimmedStr,options){
- if(!options.eNotation) return str;
- const notation = trimmedStr.match(eNotationRegx);
- if(notation){
- let sign = notation[1] || "";
- const eChar = notation[3].indexOf("e") === -1 ? "E" : "e";
- const leadingZeros = notation[2];
- const eAdjacentToLeadingZeros = sign ? // 0E.
- str[leadingZeros.length+1] === eChar
- : str[leadingZeros.length] === eChar;
-
- if(leadingZeros.length > 1 && eAdjacentToLeadingZeros) return str;
- else if(leadingZeros.length === 1
- && (notation[3].startsWith(`.${eChar}`) || notation[3][0] === eChar)){
- return Number(trimmedStr);
- }else if(options.leadingZeros && !eAdjacentToLeadingZeros){ //accept with leading zeros
- //remove leading 0s
- trimmedStr = (notation[1] || "") + notation[3];
- return Number(trimmedStr);
- }else return str;
- }else{
- return str;
- }
-}
-
-/**
- *
- * @param {string} numStr without leading zeros
- * @returns
- */
-function trimZeros(numStr){
- if(numStr && numStr.indexOf(".") !== -1){//float
- numStr = numStr.replace(/0+$/, ""); //remove ending zeros
- if(numStr === ".") numStr = "0";
- else if(numStr[0] === ".") numStr = "0"+numStr;
- else if(numStr[numStr.length-1] === ".") numStr = numStr.substring(0,numStr.length-1);
- return numStr;
- }
- return numStr;
-}
-
-function parse_int(numStr, base){
- //polyfill
- if(parseInt) return parseInt(numStr, base);
- else if(Number.parseInt) return Number.parseInt(numStr, base);
- else if(window && window.parseInt) return window.parseInt(numStr, base);
- else throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")
-}
-;// CONCATENATED MODULE: ./node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js
-
-///@ts-check
-
-
-
-
-
-
-
-// const regx =
-// '<((!\\[CDATA\\[([\\s\\S]*?)(]]>))|((NAME:)?(NAME))([^>]*)>|((\\/)(NAME)\\s*>))([^<]*)'
-// .replace(/NAME/g, util.nameRegexp);
-
-//const tagsRegx = new RegExp("<(\\/?[\\w:\\-\._]+)([^>]*)>(\\s*"+cdataRegx+")*([^<]+)?","g");
-//const tagsRegx = new RegExp("<(\\/?)((\\w*:)?([\\w:\\-\._]+))([^>]*)>([^<]*)("+cdataRegx+"([^<]*))*([^<]+)?","g");
-
-class OrderedObjParser{
- constructor(options){
- this.options = options;
- this.currentNode = null;
- this.tagsNodeStack = [];
- this.docTypeEntities = {};
- this.lastEntities = {
- "apos" : { regex: /&(apos|#39|#x27);/g, val : "'"},
- "gt" : { regex: /&(gt|#62|#x3E);/g, val : ">"},
- "lt" : { regex: /&(lt|#60|#x3C);/g, val : "<"},
- "quot" : { regex: /&(quot|#34|#x22);/g, val : "\""},
- };
- this.ampEntity = { regex: /&(amp|#38|#x26);/g, val : "&"};
- this.htmlEntities = {
- "space": { regex: /&(nbsp|#160);/g, val: " " },
- // "lt" : { regex: /&(lt|#60);/g, val: "<" },
- // "gt" : { regex: /&(gt|#62);/g, val: ">" },
- // "amp" : { regex: /&(amp|#38);/g, val: "&" },
- // "quot" : { regex: /&(quot|#34);/g, val: "\"" },
- // "apos" : { regex: /&(apos|#39);/g, val: "'" },
- "cent" : { regex: /&(cent|#162);/g, val: "¢" },
- "pound" : { regex: /&(pound|#163);/g, val: "£" },
- "yen" : { regex: /&(yen|#165);/g, val: "¥" },
- "euro" : { regex: /&(euro|#8364);/g, val: "€" },
- "copyright" : { regex: /&(copy|#169);/g, val: "©" },
- "reg" : { regex: /&(reg|#174);/g, val: "®" },
- "inr" : { regex: /&(inr|#8377);/g, val: "₹" },
- "num_dec": { regex: /([0-9]{1,7});/g, val : (_, str) => String.fromCodePoint(Number.parseInt(str, 10)) },
- "num_hex": { regex: /([0-9a-fA-F]{1,6});/g, val : (_, str) => String.fromCodePoint(Number.parseInt(str, 16)) },
- };
- this.addExternalEntities = addExternalEntities;
- this.parseXml = parseXml;
- this.parseTextData = parseTextData;
- this.resolveNameSpace = resolveNameSpace;
- this.buildAttributesMap = buildAttributesMap;
- this.isItStopNode = isItStopNode;
- this.replaceEntitiesValue = OrderedObjParser_replaceEntitiesValue;
- this.readStopNodeData = readStopNodeData;
- this.saveTextToParentTag = saveTextToParentTag;
- this.addChild = addChild;
- this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes)
-
- if(this.options.stopNodes && this.options.stopNodes.length > 0){
- this.stopNodesExact = new Set();
- this.stopNodesWildcard = new Set();
- for(let i = 0; i < this.options.stopNodes.length; i++){
- const stopNodeExp = this.options.stopNodes[i];
- if(typeof stopNodeExp !== 'string') continue;
- if(stopNodeExp.startsWith("*.")){
- this.stopNodesWildcard.add(stopNodeExp.substring(2));
- }else{
- this.stopNodesExact.add(stopNodeExp);
- }
- }
- }
- }
-
-}
-
-function addExternalEntities(externalEntities){
- const entKeys = Object.keys(externalEntities);
- for (let i = 0; i < entKeys.length; i++) {
- const ent = entKeys[i];
- this.lastEntities[ent] = {
- regex: new RegExp("&"+ent+";","g"),
- val : externalEntities[ent]
- }
- }
-}
-
-/**
- * @param {string} val
- * @param {string} tagName
- * @param {string} jPath
- * @param {boolean} dontTrim
- * @param {boolean} hasAttributes
- * @param {boolean} isLeafNode
- * @param {boolean} escapeEntities
- */
-function parseTextData(val, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) {
- if (val !== undefined) {
- if (this.options.trimValues && !dontTrim) {
- val = val.trim();
- }
- if(val.length > 0){
- if(!escapeEntities) val = this.replaceEntitiesValue(val);
-
- const newval = this.options.tagValueProcessor(tagName, val, jPath, hasAttributes, isLeafNode);
- if(newval === null || newval === undefined){
- //don't parse
- return val;
- }else if(typeof newval !== typeof val || newval !== val){
- //overwrite
- return newval;
- }else if(this.options.trimValues){
- return parseValue(val, this.options.parseTagValue, this.options.numberParseOptions);
- }else{
- const trimmedVal = val.trim();
- if(trimmedVal === val){
- return parseValue(val, this.options.parseTagValue, this.options.numberParseOptions);
- }else{
- return val;
- }
- }
- }
- }
-}
-
-function resolveNameSpace(tagname) {
- if (this.options.removeNSPrefix) {
- const tags = tagname.split(':');
- const prefix = tagname.charAt(0) === '/' ? '/' : '';
- if (tags[0] === 'xmlns') {
- return '';
- }
- if (tags.length === 2) {
- tagname = prefix + tags[1];
- }
- }
- return tagname;
-}
-
-//TODO: change regex to capture NS
-//const attrsRegx = new RegExp("([\\w\\-\\.\\:]+)\\s*=\\s*(['\"])((.|\n)*?)\\2","gm");
-const attrsRegx = new RegExp('([^\\s=]+)\\s*(=\\s*([\'"])([\\s\\S]*?)\\3)?', 'gm');
-
-function buildAttributesMap(attrStr, jPath) {
- if (this.options.ignoreAttributes !== true && typeof attrStr === 'string') {
- // attrStr = attrStr.replace(/\r?\n/g, ' ');
- //attrStr = attrStr || attrStr.trim();
-
- const matches = getAllMatches(attrStr, attrsRegx);
- const len = matches.length; //don't make it inline
- const attrs = {};
- for (let i = 0; i < len; i++) {
- const attrName = this.resolveNameSpace(matches[i][1]);
- if (this.ignoreAttributesFn(attrName, jPath)) {
- continue
- }
- let oldVal = matches[i][4];
- let aName = this.options.attributeNamePrefix + attrName;
- if (attrName.length) {
- if (this.options.transformAttributeName) {
- aName = this.options.transformAttributeName(aName);
- }
- if(aName === "__proto__") aName = "#__proto__";
- if (oldVal !== undefined) {
- if (this.options.trimValues) {
- oldVal = oldVal.trim();
- }
- oldVal = this.replaceEntitiesValue(oldVal);
- const newVal = this.options.attributeValueProcessor(attrName, oldVal, jPath);
- if(newVal === null || newVal === undefined){
- //don't parse
- attrs[aName] = oldVal;
- }else if(typeof newVal !== typeof oldVal || newVal !== oldVal){
- //overwrite
- attrs[aName] = newVal;
- }else{
- //parse
- attrs[aName] = parseValue(
- oldVal,
- this.options.parseAttributeValue,
- this.options.numberParseOptions
- );
- }
- } else if (this.options.allowBooleanAttributes) {
- attrs[aName] = true;
- }
- }
- }
- if (!Object.keys(attrs).length) {
- return;
- }
- if (this.options.attributesGroupName) {
- const attrCollection = {};
- attrCollection[this.options.attributesGroupName] = attrs;
- return attrCollection;
- }
- return attrs
- }
-}
-
-const parseXml = function(xmlData) {
- xmlData = xmlData.replace(/\r\n?/g, "\n"); //TODO: remove this line
- const xmlObj = new XmlNode('!xml');
- let currentNode = xmlObj;
- let textData = "";
- let jPath = "";
- const docTypeReader = new DocTypeReader(this.options.processEntities);
- for(let i=0; i< xmlData.length; i++){//for each char in XML data
- const ch = xmlData[i];
- if(ch === '<'){
- // const nextIndex = i+1;
- // const _2ndChar = xmlData[nextIndex];
- if( xmlData[i+1] === '/') {//Closing Tag
- const closeIndex = findClosingIndex(xmlData, ">", i, "Closing Tag is not closed.")
- let tagName = xmlData.substring(i+2,closeIndex).trim();
-
- if(this.options.removeNSPrefix){
- const colonIndex = tagName.indexOf(":");
- if(colonIndex !== -1){
- tagName = tagName.substr(colonIndex+1);
- }
- }
-
- if(this.options.transformTagName) {
- tagName = this.options.transformTagName(tagName);
- }
-
- if(currentNode){
- textData = this.saveTextToParentTag(textData, currentNode, jPath);
- }
-
- //check if last tag of nested tag was unpaired tag
- const lastTagName = jPath.substring(jPath.lastIndexOf(".")+1);
- if(tagName && this.options.unpairedTags.indexOf(tagName) !== -1 ){
- throw new Error(`Unpaired tag can not be used as closing tag: ${tagName}>`);
- }
- let propIndex = 0
- if(lastTagName && this.options.unpairedTags.indexOf(lastTagName) !== -1 ){
- propIndex = jPath.lastIndexOf('.', jPath.lastIndexOf('.')-1)
- this.tagsNodeStack.pop();
- }else{
- propIndex = jPath.lastIndexOf(".");
- }
- jPath = jPath.substring(0, propIndex);
-
- currentNode = this.tagsNodeStack.pop();//avoid recursion, set the parent tag scope
- textData = "";
- i = closeIndex;
- } else if( xmlData[i+1] === '?') {
-
- let tagData = readTagExp(xmlData,i, false, "?>");
- if(!tagData) throw new Error("Pi Tag is not closed.");
-
- textData = this.saveTextToParentTag(textData, currentNode, jPath);
- if( (this.options.ignoreDeclaration && tagData.tagName === "?xml") || this.options.ignorePiTags){
- //do nothing
- }else{
-
- const childNode = new XmlNode(tagData.tagName);
- childNode.add(this.options.textNodeName, "");
-
- if(tagData.tagName !== tagData.tagExp && tagData.attrExpPresent){
- childNode[":@"] = this.buildAttributesMap(tagData.tagExp, jPath);
- }
- this.addChild(currentNode, childNode, jPath, i);
- }
-
-
- i = tagData.closeIndex + 1;
- } else if(xmlData.substr(i + 1, 3) === '!--') {
- const endIndex = findClosingIndex(xmlData, "-->", i+4, "Comment is not closed.")
- if(this.options.commentPropName){
- const comment = xmlData.substring(i + 4, endIndex - 2);
-
- textData = this.saveTextToParentTag(textData, currentNode, jPath);
-
- currentNode.add(this.options.commentPropName, [ { [this.options.textNodeName] : comment } ]);
- }
- i = endIndex;
- } else if( xmlData.substr(i + 1, 2) === '!D') {
- const result = docTypeReader.readDocType(xmlData, i);
- this.docTypeEntities = result.entities;
- i = result.i;
- }else if(xmlData.substr(i + 1, 2) === '![') {
- const closeIndex = findClosingIndex(xmlData, "]]>", i, "CDATA is not closed.") - 2;
- const tagExp = xmlData.substring(i + 9,closeIndex);
-
- textData = this.saveTextToParentTag(textData, currentNode, jPath);
-
- let val = this.parseTextData(tagExp, currentNode.tagname, jPath, true, false, true, true);
- if(val == undefined) val = "";
-
- //cdata should be set even if it is 0 length string
- if(this.options.cdataPropName){
- currentNode.add(this.options.cdataPropName, [ { [this.options.textNodeName] : tagExp } ]);
- }else{
- currentNode.add(this.options.textNodeName, val);
- }
-
- i = closeIndex + 2;
- }else {//Opening tag
- let result = readTagExp(xmlData,i, this.options.removeNSPrefix);
- let tagName= result.tagName;
- const rawTagName = result.rawTagName;
- let tagExp = result.tagExp;
- let attrExpPresent = result.attrExpPresent;
- let closeIndex = result.closeIndex;
-
- if (this.options.transformTagName) {
- //console.log(tagExp, tagName)
- const newTagName = this.options.transformTagName(tagName);
- if(tagExp === tagName) {
- tagExp = newTagName
- }
- tagName = newTagName;
- }
-
- //save text as child node
- if (currentNode && textData) {
- if(currentNode.tagname !== '!xml'){
- //when nested tag is found
- textData = this.saveTextToParentTag(textData, currentNode, jPath, false);
- }
- }
-
- //check if last tag was unpaired tag
- const lastTag = currentNode;
- if(lastTag && this.options.unpairedTags.indexOf(lastTag.tagname) !== -1 ){
- currentNode = this.tagsNodeStack.pop();
- jPath = jPath.substring(0, jPath.lastIndexOf("."));
- }
- if(tagName !== xmlObj.tagname){
- jPath += jPath ? "." + tagName : tagName;
- }
- const startIndex = i;
- if (this.isItStopNode(this.stopNodesExact, this.stopNodesWildcard, jPath, tagName)) {
- let tagContent = "";
- //self-closing tag
- if(tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1){
- if(tagName[tagName.length - 1] === "/"){ //remove trailing '/'
- tagName = tagName.substr(0, tagName.length - 1);
- jPath = jPath.substr(0, jPath.length - 1);
- tagExp = tagName;
- }else{
- tagExp = tagExp.substr(0, tagExp.length - 1);
- }
- i = result.closeIndex;
- }
- //unpaired tag
- else if(this.options.unpairedTags.indexOf(tagName) !== -1){
-
- i = result.closeIndex;
- }
- //normal tag
- else{
- //read until closing tag is found
- const result = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1);
- if(!result) throw new Error(`Unexpected end of ${rawTagName}`);
- i = result.i;
- tagContent = result.tagContent;
- }
-
- const childNode = new XmlNode(tagName);
-
- if(tagName !== tagExp && attrExpPresent){
- childNode[":@"] = this.buildAttributesMap(tagExp, jPath
- );
- }
- if(tagContent) {
- tagContent = this.parseTextData(tagContent, tagName, jPath, true, attrExpPresent, true, true);
- }
-
- jPath = jPath.substr(0, jPath.lastIndexOf("."));
- childNode.add(this.options.textNodeName, tagContent);
-
- this.addChild(currentNode, childNode, jPath, startIndex);
- }else{
- //selfClosing tag
- if(tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1){
- if(tagName[tagName.length - 1] === "/"){ //remove trailing '/'
- tagName = tagName.substr(0, tagName.length - 1);
- jPath = jPath.substr(0, jPath.length - 1);
- tagExp = tagName;
- }else{
- tagExp = tagExp.substr(0, tagExp.length - 1);
- }
-
- if(this.options.transformTagName) {
- const newTagName = this.options.transformTagName(tagName);
- if(tagExp === tagName) {
- tagExp = newTagName
- }
- tagName = newTagName;
- }
-
- const childNode = new XmlNode(tagName);
- if(tagName !== tagExp && attrExpPresent){
- childNode[":@"] = this.buildAttributesMap(tagExp, jPath);
- }
- this.addChild(currentNode, childNode, jPath, startIndex);
- jPath = jPath.substr(0, jPath.lastIndexOf("."));
- }
- //opening tag
- else{
- const childNode = new XmlNode( tagName);
- this.tagsNodeStack.push(currentNode);
-
- if(tagName !== tagExp && attrExpPresent){
- childNode[":@"] = this.buildAttributesMap(tagExp, jPath);
- }
- this.addChild(currentNode, childNode, jPath, startIndex);
- currentNode = childNode;
- }
- textData = "";
- i = closeIndex;
- }
- }
- }else{
- textData += xmlData[i];
- }
- }
- return xmlObj.child;
-}
-
-function addChild(currentNode, childNode, jPath, startIndex){
- // unset startIndex if not requested
- if (!this.options.captureMetaData) startIndex = undefined;
- const result = this.options.updateTag(childNode.tagname, jPath, childNode[":@"])
- if(result === false){
- //do nothing
- } else if(typeof result === "string"){
- childNode.tagname = result
- currentNode.addChild(childNode, startIndex);
- }else{
- currentNode.addChild(childNode, startIndex);
- }
-}
-
-const OrderedObjParser_replaceEntitiesValue = function(val){
-
- if(this.options.processEntities){
- for(let entityName in this.docTypeEntities){
- const entity = this.docTypeEntities[entityName];
- val = val.replace( entity.regx, entity.val);
- }
- for(let entityName in this.lastEntities){
- const entity = this.lastEntities[entityName];
- val = val.replace( entity.regex, entity.val);
- }
- if(this.options.htmlEntities){
- for(let entityName in this.htmlEntities){
- const entity = this.htmlEntities[entityName];
- val = val.replace( entity.regex, entity.val);
- }
- }
- val = val.replace( this.ampEntity.regex, this.ampEntity.val);
- }
- return val;
-}
-function saveTextToParentTag(textData, currentNode, jPath, isLeafNode) {
- if (textData) { //store previously collected data as textNode
- if(isLeafNode === undefined) isLeafNode = currentNode.child.length === 0
-
- textData = this.parseTextData(textData,
- currentNode.tagname,
- jPath,
- false,
- currentNode[":@"] ? Object.keys(currentNode[":@"]).length !== 0 : false,
- isLeafNode);
-
- if (textData !== undefined && textData !== "")
- currentNode.add(this.options.textNodeName, textData);
- textData = "";
- }
- return textData;
-}
-
-//TODO: use jPath to simplify the logic
-/**
- * @param {Set} stopNodesExact
- * @param {Set} stopNodesWildcard
- * @param {string} jPath
- * @param {string} currentTagName
- */
-function isItStopNode(stopNodesExact, stopNodesWildcard, jPath, currentTagName){
- if(stopNodesWildcard && stopNodesWildcard.has(currentTagName)) return true;
- if(stopNodesExact && stopNodesExact.has(jPath)) return true;
- return false;
-}
-
-/**
- * Returns the tag Expression and where it is ending handling single-double quotes situation
- * @param {string} xmlData
- * @param {number} i starting index
- * @returns
- */
-function tagExpWithClosingIndex(xmlData, i, closingChar = ">"){
- let attrBoundary;
- let tagExp = "";
- for (let index = i; index < xmlData.length; index++) {
- let ch = xmlData[index];
- if (attrBoundary) {
- if (ch === attrBoundary) attrBoundary = "";//reset
- } else if (ch === '"' || ch === "'") {
- attrBoundary = ch;
- } else if (ch === closingChar[0]) {
- if(closingChar[1]){
- if(xmlData[index + 1] === closingChar[1]){
- return {
- data: tagExp,
- index: index
- }
- }
- }else{
- return {
- data: tagExp,
- index: index
- }
- }
- } else if (ch === '\t') {
- ch = " "
- }
- tagExp += ch;
- }
-}
-
-function findClosingIndex(xmlData, str, i, errMsg){
- const closingIndex = xmlData.indexOf(str, i);
- if(closingIndex === -1){
- throw new Error(errMsg)
- }else{
- return closingIndex + str.length - 1;
- }
-}
-
-function readTagExp(xmlData,i, removeNSPrefix, closingChar = ">"){
- const result = tagExpWithClosingIndex(xmlData, i+1, closingChar);
- if(!result) return;
- let tagExp = result.data;
- const closeIndex = result.index;
- const separatorIndex = tagExp.search(/\s/);
- let tagName = tagExp;
- let attrExpPresent = true;
- if(separatorIndex !== -1){//separate tag name and attributes expression
- tagName = tagExp.substring(0, separatorIndex);
- tagExp = tagExp.substring(separatorIndex + 1).trimStart();
- }
-
- const rawTagName = tagName;
- if(removeNSPrefix){
- const colonIndex = tagName.indexOf(":");
- if(colonIndex !== -1){
- tagName = tagName.substr(colonIndex+1);
- attrExpPresent = tagName !== result.data.substr(colonIndex + 1);
- }
- }
-
- return {
- tagName: tagName,
- tagExp: tagExp,
- closeIndex: closeIndex,
- attrExpPresent: attrExpPresent,
- rawTagName: rawTagName,
- }
-}
-/**
- * find paired tag for a stop node
- * @param {string} xmlData
- * @param {string} tagName
- * @param {number} i
- */
-function readStopNodeData(xmlData, tagName, i){
- const startIndex = i;
- // Starting at 1 since we already have an open tag
- let openTagCount = 1;
-
- for (; i < xmlData.length; i++) {
- if( xmlData[i] === "<"){
- if (xmlData[i+1] === "/") {//close tag
- const closeIndex = findClosingIndex(xmlData, ">", i, `${tagName} is not closed`);
- let closeTagName = xmlData.substring(i+2,closeIndex).trim();
- if(closeTagName === tagName){
- openTagCount--;
- if (openTagCount === 0) {
- return {
- tagContent: xmlData.substring(startIndex, i),
- i : closeIndex
- }
- }
- }
- i=closeIndex;
- } else if(xmlData[i+1] === '?') {
- const closeIndex = findClosingIndex(xmlData, "?>", i+1, "StopNode is not closed.")
- i=closeIndex;
- } else if(xmlData.substr(i + 1, 3) === '!--') {
- const closeIndex = findClosingIndex(xmlData, "-->", i+3, "StopNode is not closed.")
- i=closeIndex;
- } else if(xmlData.substr(i + 1, 2) === '![') {
- const closeIndex = findClosingIndex(xmlData, "]]>", i, "StopNode is not closed.") - 2;
- i=closeIndex;
- } else {
- const tagData = readTagExp(xmlData, i, '>')
-
- if (tagData) {
- const openTagName = tagData && tagData.tagName;
- if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length-1] !== "/") {
- openTagCount++;
- }
- i=tagData.closeIndex;
- }
- }
- }
- }//end for loop
-}
-
-function parseValue(val, shouldParse, options) {
- if (shouldParse && typeof val === 'string') {
- //console.log(options)
- const newval = val.trim();
- if(newval === 'true' ) return true;
- else if(newval === 'false' ) return false;
- else return toNumber(val, options);
- } else {
- if (isExist(val)) {
- return val;
- } else {
- return '';
- }
- }
-}
-
-;// CONCATENATED MODULE: ./node_modules/fast-xml-parser/src/xmlparser/node2json.js
-
-
-
-
-const node2json_METADATA_SYMBOL = XmlNode.getMetaDataSymbol();
-
-/**
- *
- * @param {array} node
- * @param {any} options
- * @returns
- */
-function prettify(node, options){
- return compress( node, options);
-}
-
-/**
- *
- * @param {array} arr
- * @param {object} options
- * @param {string} jPath
- * @returns object
- */
-function compress(arr, options, jPath){
- let text;
- const compressedObj = {};
- for (let i = 0; i < arr.length; i++) {
- const tagObj = arr[i];
- const property = node2json_propName(tagObj);
- let newJpath = "";
- if(jPath === undefined) newJpath = property;
- else newJpath = jPath + "." + property;
-
- if(property === options.textNodeName){
- if(text === undefined) text = tagObj[property];
- else text += "" + tagObj[property];
- }else if(property === undefined){
- continue;
- }else if(tagObj[property]){
-
- let val = compress(tagObj[property], options, newJpath);
- const isLeaf = isLeafTag(val, options);
- if (tagObj[node2json_METADATA_SYMBOL] !== undefined) {
- val[node2json_METADATA_SYMBOL] = tagObj[node2json_METADATA_SYMBOL]; // copy over metadata
- }
-
- if(tagObj[":@"]){
- assignAttributes( val, tagObj[":@"], newJpath, options);
- }else if(Object.keys(val).length === 1 && val[options.textNodeName] !== undefined && !options.alwaysCreateTextNode){
- val = val[options.textNodeName];
- }else if(Object.keys(val).length === 0){
- if(options.alwaysCreateTextNode) val[options.textNodeName] = "";
- else val = "";
- }
-
- if(compressedObj[property] !== undefined && compressedObj.hasOwnProperty(property)) {
- if(!Array.isArray(compressedObj[property])) {
- compressedObj[property] = [ compressedObj[property] ];
- }
- compressedObj[property].push(val);
- }else{
- //TODO: if a node is not an array, then check if it should be an array
- //also determine if it is a leaf node
- if (options.isArray(property, newJpath, isLeaf )) {
- compressedObj[property] = [val];
- }else{
- compressedObj[property] = val;
- }
- }
- }
-
- }
- // if(text && text.length > 0) compressedObj[options.textNodeName] = text;
- if(typeof text === "string"){
- if(text.length > 0) compressedObj[options.textNodeName] = text;
- }else if(text !== undefined) compressedObj[options.textNodeName] = text;
- return compressedObj;
-}
-
-function node2json_propName(obj){
- const keys = Object.keys(obj);
- for (let i = 0; i < keys.length; i++) {
- const key = keys[i];
- if(key !== ":@") return key;
- }
-}
-
-function assignAttributes(obj, attrMap, jpath, options){
- if (attrMap) {
- const keys = Object.keys(attrMap);
- const len = keys.length; //don't make it inline
- for (let i = 0; i < len; i++) {
- const atrrName = keys[i];
- if (options.isArray(atrrName, jpath + "." + atrrName, true, true)) {
- obj[atrrName] = [ attrMap[atrrName] ];
- } else {
- obj[atrrName] = attrMap[atrrName];
- }
- }
- }
-}
-
-function isLeafTag(obj, options){
- const { textNodeName } = options;
- const propCount = Object.keys(obj).length;
-
- if (propCount === 0) {
- return true;
- }
-
- if (
- propCount === 1 &&
- (obj[textNodeName] || typeof obj[textNodeName] === "boolean" || obj[textNodeName] === 0)
- ) {
- return true;
- }
-
- return false;
-}
-
-;// CONCATENATED MODULE: ./node_modules/fast-xml-parser/src/xmlparser/XMLParser.js
-
-
-
-
-
-
-class XMLParser{
-
- constructor(options){
- this.externalEntities = {};
- this.options = buildOptions(options);
-
- }
- /**
- * Parse XML dats to JS object
- * @param {string|Uint8Array} xmlData
- * @param {boolean|Object} validationOption
- */
- parse(xmlData,validationOption){
- if(typeof xmlData !== "string" && xmlData.toString){
- xmlData = xmlData.toString();
- }else if(typeof xmlData !== "string"){
- throw new Error("XML data is accepted in String or Bytes[] form.")
- }
-
- if( validationOption){
- if(validationOption === true) validationOption = {}; //validate with default options
-
- const result = validate(xmlData, validationOption);
- if (result !== true) {
- throw Error( `${result.err.msg}:${result.err.line}:${result.err.col}` )
- }
- }
- const orderedObjParser = new OrderedObjParser(this.options);
- orderedObjParser.addExternalEntities(this.externalEntities);
- const orderedResult = orderedObjParser.parseXml(xmlData);
- if(this.options.preserveOrder || orderedResult === undefined) return orderedResult;
- else return prettify(orderedResult, this.options);
- }
-
- /**
- * Add Entity which is not by default supported by this library
- * @param {string} key
- * @param {string} value
- */
- addEntity(key, value){
- if(value.indexOf("&") !== -1){
- throw new Error("Entity value can't have '&'")
- }else if(key.indexOf("&") !== -1 || key.indexOf(";") !== -1){
- throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'")
- }else if(value === "&"){
- throw new Error("An entity with value '&' is not permitted");
- }else{
- this.externalEntities[key] = value;
- }
- }
-
- /**
- * Returns a Symbol that can be used to access the metadata
- * property on a node.
- *
- * If Symbol is not available in the environment, an ordinary property is used
- * and the name of the property is here returned.
- *
- * The XMLMetaData property is only present when `captureMetaData`
- * is true in the options.
- */
- static getMetaDataSymbol() {
- return XmlNode.getMetaDataSymbol();
- }
-}
-
-;// CONCATENATED MODULE: ./node_modules/@azure/core-xml/dist/esm/xml.common.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-/**
- * Default key used to access the XML attributes.
- */
-const xml_common_XML_ATTRKEY = "$";
-/**
- * Default key used to access the XML value content.
- */
-const xml_common_XML_CHARKEY = "_";
-//# sourceMappingURL=xml.common.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/core-xml/dist/esm/xml.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-function getCommonOptions(options) {
- var _a;
- return {
- attributesGroupName: xml_common_XML_ATTRKEY,
- textNodeName: (_a = options.xmlCharKey) !== null && _a !== void 0 ? _a : xml_common_XML_CHARKEY,
- ignoreAttributes: false,
- suppressBooleanAttributes: false,
- };
-}
-function getSerializerOptions(options = {}) {
- var _a, _b;
- return Object.assign(Object.assign({}, getCommonOptions(options)), { attributeNamePrefix: "@_", format: true, suppressEmptyNode: true, indentBy: "", rootNodeName: (_a = options.rootName) !== null && _a !== void 0 ? _a : "root", cdataPropName: (_b = options.cdataPropName) !== null && _b !== void 0 ? _b : "__cdata" });
-}
-function getParserOptions(options = {}) {
- return Object.assign(Object.assign({}, getCommonOptions(options)), { parseAttributeValue: false, parseTagValue: false, attributeNamePrefix: "", stopNodes: options.stopNodes, processEntities: true, trimValues: false });
-}
-/**
- * Converts given JSON object to XML string
- * @param obj - JSON object to be converted into XML string
- * @param opts - Options that govern the XML building of given JSON object
- * `rootName` indicates the name of the root element in the resulting XML
- */
-function stringifyXML(obj, opts = {}) {
- const parserOptions = getSerializerOptions(opts);
- const j2x = new Builder(parserOptions);
- const node = { [parserOptions.rootNodeName]: obj };
- const xmlData = j2x.build(node);
- return `${xmlData}`.replace(/\n/g, "");
-}
-/**
- * Converts given XML string into JSON
- * @param str - String containing the XML content to be parsed into JSON
- * @param opts - Options that govern the parsing of given xml string
- * `includeRoot` indicates whether the root element is to be included or not in the output
- */
-async function parseXML(str, opts = {}) {
- if (!str) {
- throw new Error("Document is empty");
- }
- const validation = XMLValidator.validate(str);
- if (validation !== true) {
- throw validation;
- }
- const parser = new XMLParser(getParserOptions(opts));
- const parsedXml = parser.parse(str);
- // Remove the node.
- // This is a change in behavior on fxp v4. Issue #424
- if (parsedXml["?xml"]) {
- delete parsedXml["?xml"];
- }
- if (!opts.includeRoot) {
- for (const key of Object.keys(parsedXml)) {
- const value = parsedXml[key];
- return typeof value === "object" ? Object.assign({}, value) : value;
- }
- }
- return parsedXml;
-}
-//# sourceMappingURL=xml.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/storage-blob/dist/esm/log.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-/**
- * The `@azure/logger` configuration for this package.
- */
-const storage_blob_dist_esm_log_logger = esm_createClientLogger("storage-blob");
-//# sourceMappingURL=log.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/BuffersStream.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-/**
- * This class generates a readable stream from the data in an array of buffers.
- */
-class BuffersStream extends external_node_stream_.Readable {
- buffers;
- byteLength;
- /**
- * The offset of data to be read in the current buffer.
- */
- byteOffsetInCurrentBuffer;
- /**
- * The index of buffer to be read in the array of buffers.
- */
- bufferIndex;
- /**
- * The total length of data already read.
- */
- pushedBytesLength;
- /**
- * Creates an instance of BuffersStream that will emit the data
- * contained in the array of buffers.
- *
- * @param buffers - Array of buffers containing the data
- * @param byteLength - The total length of data contained in the buffers
- */
- constructor(buffers, byteLength, options) {
- super(options);
- this.buffers = buffers;
- this.byteLength = byteLength;
- this.byteOffsetInCurrentBuffer = 0;
- this.bufferIndex = 0;
- this.pushedBytesLength = 0;
- // check byteLength is no larger than buffers[] total length
- let buffersLength = 0;
- for (const buf of this.buffers) {
- buffersLength += buf.byteLength;
- }
- if (buffersLength < this.byteLength) {
- throw new Error("Data size shouldn't be larger than the total length of buffers.");
- }
- }
- /**
- * Internal _read() that will be called when the stream wants to pull more data in.
- *
- * @param size - Optional. The size of data to be read
- */
- _read(size) {
- if (this.pushedBytesLength >= this.byteLength) {
- this.push(null);
- }
- if (!size) {
- size = this.readableHighWaterMark;
- }
- const outBuffers = [];
- let i = 0;
- while (i < size && this.pushedBytesLength < this.byteLength) {
- // The last buffer may be longer than the data it contains.
- const remainingDataInAllBuffers = this.byteLength - this.pushedBytesLength;
- const remainingCapacityInThisBuffer = this.buffers[this.bufferIndex].byteLength - this.byteOffsetInCurrentBuffer;
- const remaining = Math.min(remainingCapacityInThisBuffer, remainingDataInAllBuffers);
- if (remaining > size - i) {
- // chunkSize = size - i
- const end = this.byteOffsetInCurrentBuffer + size - i;
- outBuffers.push(this.buffers[this.bufferIndex].slice(this.byteOffsetInCurrentBuffer, end));
- this.pushedBytesLength += size - i;
- this.byteOffsetInCurrentBuffer = end;
- i = size;
- break;
- }
- else {
- // chunkSize = remaining
- const end = this.byteOffsetInCurrentBuffer + remaining;
- outBuffers.push(this.buffers[this.bufferIndex].slice(this.byteOffsetInCurrentBuffer, end));
- if (remaining === remainingCapacityInThisBuffer) {
- // this.buffers[this.bufferIndex] used up, shift to next one
- this.byteOffsetInCurrentBuffer = 0;
- this.bufferIndex++;
- }
- else {
- this.byteOffsetInCurrentBuffer = end;
- }
- this.pushedBytesLength += remaining;
- i += remaining;
- }
- }
- if (outBuffers.length > 1) {
- this.push(Buffer.concat(outBuffers));
- }
- else if (outBuffers.length === 1) {
- this.push(outBuffers[0]);
- }
- }
-}
-//# sourceMappingURL=BuffersStream.js.map
-// EXTERNAL MODULE: external "node:buffer"
-var external_node_buffer_ = __nccwpck_require__(4573);
-;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/PooledBuffer.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-/**
- * maxBufferLength is max size of each buffer in the pooled buffers.
- */
-const maxBufferLength = external_node_buffer_.constants.MAX_LENGTH;
-/**
- * This class provides a buffer container which conceptually has no hard size limit.
- * It accepts a capacity, an array of input buffers and the total length of input data.
- * It will allocate an internal "buffer" of the capacity and fill the data in the input buffers
- * into the internal "buffer" serially with respect to the total length.
- * Then by calling PooledBuffer.getReadableStream(), you can get a readable stream
- * assembled from all the data in the internal "buffer".
- */
-class PooledBuffer {
- /**
- * Internal buffers used to keep the data.
- * Each buffer has a length of the maxBufferLength except last one.
- */
- buffers = [];
- /**
- * The total size of internal buffers.
- */
- capacity;
- /**
- * The total size of data contained in internal buffers.
- */
- _size;
- /**
- * The size of the data contained in the pooled buffers.
- */
- get size() {
- return this._size;
- }
- constructor(capacity, buffers, totalLength) {
- this.capacity = capacity;
- this._size = 0;
- // allocate
- const bufferNum = Math.ceil(capacity / maxBufferLength);
- for (let i = 0; i < bufferNum; i++) {
- let len = i === bufferNum - 1 ? capacity % maxBufferLength : maxBufferLength;
- if (len === 0) {
- len = maxBufferLength;
- }
- this.buffers.push(Buffer.allocUnsafe(len));
- }
- if (buffers) {
- this.fill(buffers, totalLength);
- }
- }
- /**
- * Fill the internal buffers with data in the input buffers serially
- * with respect to the total length and the total capacity of the internal buffers.
- * Data copied will be shift out of the input buffers.
- *
- * @param buffers - Input buffers containing the data to be filled in the pooled buffer
- * @param totalLength - Total length of the data to be filled in.
- *
- */
- fill(buffers, totalLength) {
- this._size = Math.min(this.capacity, totalLength);
- let i = 0, j = 0, targetOffset = 0, sourceOffset = 0, totalCopiedNum = 0;
- while (totalCopiedNum < this._size) {
- const source = buffers[i];
- const target = this.buffers[j];
- const copiedNum = source.copy(target, targetOffset, sourceOffset);
- totalCopiedNum += copiedNum;
- sourceOffset += copiedNum;
- targetOffset += copiedNum;
- if (sourceOffset === source.length) {
- i++;
- sourceOffset = 0;
- }
- if (targetOffset === target.length) {
- j++;
- targetOffset = 0;
- }
- }
- // clear copied from source buffers
- buffers.splice(0, i);
- if (buffers.length > 0) {
- buffers[0] = buffers[0].slice(sourceOffset);
- }
- }
- /**
- * Get the readable stream assembled from all the data in the internal buffers.
- *
- */
- getReadableStream() {
- return new BuffersStream(this.buffers, this.size);
- }
-}
-//# sourceMappingURL=PooledBuffer.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/BufferScheduler.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-/**
- * This class accepts a Node.js Readable stream as input, and keeps reading data
- * from the stream into the internal buffer structure, until it reaches maxBuffers.
- * Every available buffer will try to trigger outgoingHandler.
- *
- * The internal buffer structure includes an incoming buffer array, and a outgoing
- * buffer array. The incoming buffer array includes the "empty" buffers can be filled
- * with new incoming data. The outgoing array includes the filled buffers to be
- * handled by outgoingHandler. Every above buffer size is defined by parameter bufferSize.
- *
- * NUM_OF_ALL_BUFFERS = BUFFERS_IN_INCOMING + BUFFERS_IN_OUTGOING + BUFFERS_UNDER_HANDLING
- *
- * NUM_OF_ALL_BUFFERS lesser than or equal to maxBuffers
- *
- * PERFORMANCE IMPROVEMENT TIPS:
- * 1. Input stream highWaterMark is better to set a same value with bufferSize
- * parameter, which will avoid Buffer.concat() operations.
- * 2. concurrency should set a smaller value than maxBuffers, which is helpful to
- * reduce the possibility when a outgoing handler waits for the stream data.
- * in this situation, outgoing handlers are blocked.
- * Outgoing queue shouldn't be empty.
- */
-class BufferScheduler {
- /**
- * Size of buffers in incoming and outgoing queues. This class will try to align
- * data read from Readable stream into buffer chunks with bufferSize defined.
- */
- bufferSize;
- /**
- * How many buffers can be created or maintained.
- */
- maxBuffers;
- /**
- * A Node.js Readable stream.
- */
- readable;
- /**
- * OutgoingHandler is an async function triggered by BufferScheduler when there
- * are available buffers in outgoing array.
- */
- outgoingHandler;
- /**
- * An internal event emitter.
- */
- emitter = new external_events_.EventEmitter();
- /**
- * Concurrency of executing outgoingHandlers. (0 lesser than concurrency lesser than or equal to maxBuffers)
- */
- concurrency;
- /**
- * An internal offset marker to track data offset in bytes of next outgoingHandler.
- */
- offset = 0;
- /**
- * An internal marker to track whether stream is end.
- */
- isStreamEnd = false;
- /**
- * An internal marker to track whether stream or outgoingHandler returns error.
- */
- isError = false;
- /**
- * How many handlers are executing.
- */
- executingOutgoingHandlers = 0;
- /**
- * Encoding of the input Readable stream which has string data type instead of Buffer.
- */
- encoding;
- /**
- * How many buffers have been allocated.
- */
- numBuffers = 0;
- /**
- * Because this class doesn't know how much data every time stream pops, which
- * is defined by highWaterMarker of the stream. So BufferScheduler will cache
- * data received from the stream, when data in unresolvedDataArray exceeds the
- * blockSize defined, it will try to concat a blockSize of buffer, fill into available
- * buffers from incoming and push to outgoing array.
- */
- unresolvedDataArray = [];
- /**
- * How much data consisted in unresolvedDataArray.
- */
- unresolvedLength = 0;
- /**
- * The array includes all the available buffers can be used to fill data from stream.
- */
- incoming = [];
- /**
- * The array (queue) includes all the buffers filled from stream data.
- */
- outgoing = [];
- /**
- * Creates an instance of BufferScheduler.
- *
- * @param readable - A Node.js Readable stream
- * @param bufferSize - Buffer size of every maintained buffer
- * @param maxBuffers - How many buffers can be allocated
- * @param outgoingHandler - An async function scheduled to be
- * triggered when a buffer fully filled
- * with stream data
- * @param concurrency - Concurrency of executing outgoingHandlers (>0)
- * @param encoding - [Optional] Encoding of Readable stream when it's a string stream
- */
- constructor(readable, bufferSize, maxBuffers, outgoingHandler, concurrency, encoding) {
- if (bufferSize <= 0) {
- throw new RangeError(`bufferSize must be larger than 0, current is ${bufferSize}`);
- }
- if (maxBuffers <= 0) {
- throw new RangeError(`maxBuffers must be larger than 0, current is ${maxBuffers}`);
- }
- if (concurrency <= 0) {
- throw new RangeError(`concurrency must be larger than 0, current is ${concurrency}`);
- }
- this.bufferSize = bufferSize;
- this.maxBuffers = maxBuffers;
- this.readable = readable;
- this.outgoingHandler = outgoingHandler;
- this.concurrency = concurrency;
- this.encoding = encoding;
- }
- /**
- * Start the scheduler, will return error when stream of any of the outgoingHandlers
- * returns error.
- *
- */
- async do() {
- return new Promise((resolve, reject) => {
- this.readable.on("data", (data) => {
- data = typeof data === "string" ? Buffer.from(data, this.encoding) : data;
- this.appendUnresolvedData(data);
- if (!this.resolveData()) {
- this.readable.pause();
- }
- });
- this.readable.on("error", (err) => {
- this.emitter.emit("error", err);
- });
- this.readable.on("end", () => {
- this.isStreamEnd = true;
- this.emitter.emit("checkEnd");
- });
- this.emitter.on("error", (err) => {
- this.isError = true;
- this.readable.pause();
- reject(err);
- });
- this.emitter.on("checkEnd", () => {
- if (this.outgoing.length > 0) {
- this.triggerOutgoingHandlers();
- return;
- }
- if (this.isStreamEnd && this.executingOutgoingHandlers === 0) {
- if (this.unresolvedLength > 0 && this.unresolvedLength < this.bufferSize) {
- const buffer = this.shiftBufferFromUnresolvedDataArray();
- this.outgoingHandler(() => buffer.getReadableStream(), buffer.size, this.offset)
- .then(resolve)
- .catch(reject);
- }
- else if (this.unresolvedLength >= this.bufferSize) {
- return;
- }
- else {
- resolve();
- }
- }
- });
- });
- }
- /**
- * Insert a new data into unresolved array.
- *
- * @param data -
- */
- appendUnresolvedData(data) {
- this.unresolvedDataArray.push(data);
- this.unresolvedLength += data.length;
- }
- /**
- * Try to shift a buffer with size in blockSize. The buffer returned may be less
- * than blockSize when data in unresolvedDataArray is less than bufferSize.
- *
- */
- shiftBufferFromUnresolvedDataArray(buffer) {
- if (!buffer) {
- buffer = new PooledBuffer(this.bufferSize, this.unresolvedDataArray, this.unresolvedLength);
- }
- else {
- buffer.fill(this.unresolvedDataArray, this.unresolvedLength);
- }
- this.unresolvedLength -= buffer.size;
- return buffer;
- }
- /**
- * Resolve data in unresolvedDataArray. For every buffer with size in blockSize
- * shifted, it will try to get (or allocate a buffer) from incoming, and fill it,
- * then push it into outgoing to be handled by outgoing handler.
- *
- * Return false when available buffers in incoming are not enough, else true.
- *
- * @returns Return false when buffers in incoming are not enough, else true.
- */
- resolveData() {
- while (this.unresolvedLength >= this.bufferSize) {
- let buffer;
- if (this.incoming.length > 0) {
- buffer = this.incoming.shift();
- this.shiftBufferFromUnresolvedDataArray(buffer);
- }
- else {
- if (this.numBuffers < this.maxBuffers) {
- buffer = this.shiftBufferFromUnresolvedDataArray();
- this.numBuffers++;
- }
- else {
- // No available buffer, wait for buffer returned
- return false;
- }
- }
- this.outgoing.push(buffer);
- this.triggerOutgoingHandlers();
- }
- return true;
- }
- /**
- * Try to trigger a outgoing handler for every buffer in outgoing. Stop when
- * concurrency reaches.
- */
- async triggerOutgoingHandlers() {
- let buffer;
- do {
- if (this.executingOutgoingHandlers >= this.concurrency) {
- return;
- }
- buffer = this.outgoing.shift();
- if (buffer) {
- this.triggerOutgoingHandler(buffer);
- }
- } while (buffer);
- }
- /**
- * Trigger a outgoing handler for a buffer shifted from outgoing.
- *
- * @param buffer -
- */
- async triggerOutgoingHandler(buffer) {
- const bufferLength = buffer.size;
- this.executingOutgoingHandlers++;
- this.offset += bufferLength;
- try {
- await this.outgoingHandler(() => buffer.getReadableStream(), bufferLength, this.offset - bufferLength);
- }
- catch (err) {
- this.emitter.emit("error", err);
- return;
- }
- this.executingOutgoingHandlers--;
- this.reuseBuffer(buffer);
- this.emitter.emit("checkEnd");
- }
- /**
- * Return buffer used by outgoing handler into incoming.
- *
- * @param buffer -
- */
- reuseBuffer(buffer) {
- this.incoming.push(buffer);
- if (!this.isError && this.resolveData() && !this.isStreamEnd) {
- this.readable.resume();
- }
- }
-}
-//# sourceMappingURL=BufferScheduler.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/cache.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-let _defaultHttpClient;
-function cache_getCachedDefaultHttpClient() {
- if (!_defaultHttpClient) {
- _defaultHttpClient = esm_defaultHttpClient_createDefaultHttpClient();
- }
- return _defaultHttpClient;
-}
-//# sourceMappingURL=cache.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/policies/RequestPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-/**
- * The base class from which all request policies derive.
- */
-class BaseRequestPolicy {
- _nextPolicy;
- _options;
- /**
- * The main method to implement that manipulates a request/response.
- */
- constructor(
- /**
- * The next policy in the pipeline. Each policy is responsible for executing the next one if the request is to continue through the pipeline.
- */
- _nextPolicy,
- /**
- * The options that can be passed to a given request policy.
- */
- _options) {
- this._nextPolicy = _nextPolicy;
- this._options = _options;
- }
- /**
- * Get whether or not a log with the provided log level should be logged.
- * @param logLevel - The log level of the log that will be logged.
- * @returns Whether or not a log with the provided log level should be logged.
- */
- shouldLog(logLevel) {
- return this._options.shouldLog(logLevel);
- }
- /**
- * Attempt to log the provided message to the provided logger. If no logger was provided or if
- * the log level does not meat the logger's threshold, then nothing will be logged.
- * @param logLevel - The log level of this log.
- * @param message - The message of this log.
- */
- log(logLevel, message) {
- this._options.log(logLevel, message);
- }
-}
-//# sourceMappingURL=RequestPolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/utils/constants.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-const utils_constants_SDK_VERSION = "1.0.0";
-const constants_URLConstants = {
- Parameters: {
- FORCE_BROWSER_NO_CACHE: "_",
- SIGNATURE: "sig",
- SNAPSHOT: "snapshot",
- VERSIONID: "versionid",
- TIMEOUT: "timeout",
- },
-};
-const constants_HeaderConstants = {
- AUTHORIZATION: "Authorization",
- AUTHORIZATION_SCHEME: "Bearer",
- CONTENT_ENCODING: "Content-Encoding",
- CONTENT_ID: "Content-ID",
- CONTENT_LANGUAGE: "Content-Language",
- CONTENT_LENGTH: "Content-Length",
- CONTENT_MD5: "Content-Md5",
- CONTENT_TRANSFER_ENCODING: "Content-Transfer-Encoding",
- CONTENT_TYPE: "Content-Type",
- COOKIE: "Cookie",
- DATE: "date",
- IF_MATCH: "if-match",
- IF_MODIFIED_SINCE: "if-modified-since",
- IF_NONE_MATCH: "if-none-match",
- IF_UNMODIFIED_SINCE: "if-unmodified-since",
- PREFIX_FOR_STORAGE: "x-ms-",
- RANGE: "Range",
- USER_AGENT: "User-Agent",
- X_MS_CLIENT_REQUEST_ID: "x-ms-client-request-id",
- X_MS_COPY_SOURCE: "x-ms-copy-source",
- X_MS_DATE: "x-ms-date",
- X_MS_ERROR_CODE: "x-ms-error-code",
- X_MS_VERSION: "x-ms-version",
- X_MS_CopySourceErrorCode: "x-ms-copy-source-error-code",
-};
-const constants_DevelopmentConnectionString = (/* unused pure expression or super */ null && (`DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;`));
-/// List of ports used for path style addressing.
-/// Path style addressing means that storage account is put in URI's Path segment in instead of in host.
-const constants_PathStylePorts = (/* unused pure expression or super */ null && ([
- "10000",
- "10001",
- "10002",
- "10003",
- "10004",
- "10100",
- "10101",
- "10102",
- "10103",
- "10104",
- "11000",
- "11001",
- "11002",
- "11003",
- "11004",
- "11100",
- "11101",
- "11102",
- "11103",
- "11104",
-]));
-//# sourceMappingURL=constants.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/utils/utils.common.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-
-/**
- * Reserved URL characters must be properly escaped for Storage services like Blob or File.
- *
- * ## URL encode and escape strategy for JS SDKs
- *
- * When customers pass a URL string into XxxClient classes constructor, the URL string may already be URL encoded or not.
- * But before sending to Azure Storage server, the URL must be encoded. However, it's hard for a SDK to guess whether the URL
- * string has been encoded or not. We have 2 potential strategies, and chose strategy two for the XxxClient constructors.
- *
- * ### Strategy One: Assume the customer URL string is not encoded, and always encode URL string in SDK.
- *
- * This is what legacy V2 SDK does, simple and works for most of the cases.
- * - When customer URL string is "http://account.blob.core.windows.net/con/b:",
- * SDK will encode it to "http://account.blob.core.windows.net/con/b%3A" and send to server. A blob named "b:" will be created.
- * - When customer URL string is "http://account.blob.core.windows.net/con/b%3A",
- * SDK will encode it to "http://account.blob.core.windows.net/con/b%253A" and send to server. A blob named "b%3A" will be created.
- *
- * But this strategy will make it not possible to create a blob with "?" in it's name. Because when customer URL string is
- * "http://account.blob.core.windows.net/con/blob?name", the "?name" will be treated as URL paramter instead of blob name.
- * If customer URL string is "http://account.blob.core.windows.net/con/blob%3Fname", a blob named "blob%3Fname" will be created.
- * V2 SDK doesn't have this issue because it doesn't allow customer pass in a full URL, it accepts a separate blob name and encodeURIComponent for it.
- * We cannot accept a SDK cannot create a blob name with "?". So we implement strategy two:
- *
- * ### Strategy Two: SDK doesn't assume the URL has been encoded or not. It will just escape the special characters.
- *
- * This is what V10 Blob Go SDK does. It accepts a URL type in Go, and call url.EscapedPath() to escape the special chars unescaped.
- * - When customer URL string is "http://account.blob.core.windows.net/con/b:",
- * SDK will escape ":" like "http://account.blob.core.windows.net/con/b%3A" and send to server. A blob named "b:" will be created.
- * - When customer URL string is "http://account.blob.core.windows.net/con/b%3A",
- * There is no special characters, so send "http://account.blob.core.windows.net/con/b%3A" to server. A blob named "b:" will be created.
- * - When customer URL string is "http://account.blob.core.windows.net/con/b%253A",
- * There is no special characters, so send "http://account.blob.core.windows.net/con/b%253A" to server. A blob named "b%3A" will be created.
- *
- * This strategy gives us flexibility to create with any special characters. But "%" will be treated as a special characters, if the URL string
- * is not encoded, there shouldn't a "%" in the URL string, otherwise the URL is not a valid URL.
- * If customer needs to create a blob with "%" in it's blob name, use "%25" instead of "%". Just like above 3rd sample.
- * And following URL strings are invalid:
- * - "http://account.blob.core.windows.net/con/b%"
- * - "http://account.blob.core.windows.net/con/b%2"
- * - "http://account.blob.core.windows.net/con/b%G"
- *
- * Another special character is "?", use "%2F" to represent a blob name with "?" in a URL string.
- *
- * ### Strategy for containerName, blobName or other specific XXXName parameters in methods such as `containerClient.getBlobClient(blobName)`
- *
- * We will apply strategy one, and call encodeURIComponent for these parameters like blobName. Because what customers passes in is a plain name instead of a URL.
- *
- * @see https://learn.microsoft.com/rest/api/storageservices/naming-and-referencing-containers--blobs--and-metadata
- * @see https://learn.microsoft.com/rest/api/storageservices/naming-and-referencing-shares--directories--files--and-metadata
- *
- * @param url -
- */
-function escapeURLPath(url) {
- const urlParsed = new URL(url);
- let path = urlParsed.pathname;
- path = path || "/";
- path = utils_common_escape(path);
- urlParsed.pathname = path;
- return urlParsed.toString();
-}
-function getProxyUriFromDevConnString(connectionString) {
- // Development Connection String
- // https://learn.microsoft.com/azure/storage/common/storage-configure-connection-string#connect-to-the-emulator-account-using-the-well-known-account-name-and-key
- let proxyUri = "";
- if (connectionString.search("DevelopmentStorageProxyUri=") !== -1) {
- // CONNECTION_STRING=UseDevelopmentStorage=true;DevelopmentStorageProxyUri=http://myProxyUri
- const matchCredentials = connectionString.split(";");
- for (const element of matchCredentials) {
- if (element.trim().startsWith("DevelopmentStorageProxyUri=")) {
- proxyUri = element.trim().match("DevelopmentStorageProxyUri=(.*)")[1];
- }
- }
- }
- return proxyUri;
-}
-function getValueInConnString(connectionString, argument) {
- const elements = connectionString.split(";");
- for (const element of elements) {
- if (element.trim().startsWith(argument)) {
- return element.trim().match(argument + "=(.*)")[1];
- }
- }
- return "";
-}
-/**
- * Extracts the parts of an Azure Storage account connection string.
- *
- * @param connectionString - Connection string.
- * @returns String key value pairs of the storage account's url and credentials.
- */
-function extractConnectionStringParts(connectionString) {
- let proxyUri = "";
- if (connectionString.startsWith("UseDevelopmentStorage=true")) {
- // Development connection string
- proxyUri = getProxyUriFromDevConnString(connectionString);
- connectionString = DevelopmentConnectionString;
- }
- // Matching BlobEndpoint in the Account connection string
- let blobEndpoint = getValueInConnString(connectionString, "BlobEndpoint");
- // Slicing off '/' at the end if exists
- // (The methods that use `extractConnectionStringParts` expect the url to not have `/` at the end)
- blobEndpoint = blobEndpoint.endsWith("/") ? blobEndpoint.slice(0, -1) : blobEndpoint;
- if (connectionString.search("DefaultEndpointsProtocol=") !== -1 &&
- connectionString.search("AccountKey=") !== -1) {
- // Account connection string
- let defaultEndpointsProtocol = "";
- let accountName = "";
- let accountKey = Buffer.from("accountKey", "base64");
- let endpointSuffix = "";
- // Get account name and key
- accountName = getValueInConnString(connectionString, "AccountName");
- accountKey = Buffer.from(getValueInConnString(connectionString, "AccountKey"), "base64");
- if (!blobEndpoint) {
- // BlobEndpoint is not present in the Account connection string
- // Can be obtained from `${defaultEndpointsProtocol}://${accountName}.blob.${endpointSuffix}`
- defaultEndpointsProtocol = getValueInConnString(connectionString, "DefaultEndpointsProtocol");
- const protocol = defaultEndpointsProtocol.toLowerCase();
- if (protocol !== "https" && protocol !== "http") {
- throw new Error("Invalid DefaultEndpointsProtocol in the provided Connection String. Expecting 'https' or 'http'");
- }
- endpointSuffix = getValueInConnString(connectionString, "EndpointSuffix");
- if (!endpointSuffix) {
- throw new Error("Invalid EndpointSuffix in the provided Connection String");
- }
- blobEndpoint = `${defaultEndpointsProtocol}://${accountName}.blob.${endpointSuffix}`;
- }
- if (!accountName) {
- throw new Error("Invalid AccountName in the provided Connection String");
- }
- else if (accountKey.length === 0) {
- throw new Error("Invalid AccountKey in the provided Connection String");
- }
- return {
- kind: "AccountConnString",
- url: blobEndpoint,
- accountName,
- accountKey,
- proxyUri,
- };
- }
- else {
- // SAS connection string
- let accountSas = getValueInConnString(connectionString, "SharedAccessSignature");
- let accountName = getValueInConnString(connectionString, "AccountName");
- // if accountName is empty, try to read it from BlobEndpoint
- if (!accountName) {
- accountName = getAccountNameFromUrl(blobEndpoint);
- }
- if (!blobEndpoint) {
- throw new Error("Invalid BlobEndpoint in the provided SAS Connection String");
- }
- else if (!accountSas) {
- throw new Error("Invalid SharedAccessSignature in the provided SAS Connection String");
- }
- // client constructors assume accountSas does *not* start with ?
- if (accountSas.startsWith("?")) {
- accountSas = accountSas.substring(1);
- }
- return { kind: "SASConnString", url: blobEndpoint, accountName, accountSas };
- }
-}
-/**
- * Internal escape method implemented Strategy Two mentioned in escapeURL() description.
- *
- * @param text -
- */
-function utils_common_escape(text) {
- return encodeURIComponent(text)
- .replace(/%2F/g, "/") // Don't escape for "/"
- .replace(/'/g, "%27") // Escape for "'"
- .replace(/\+/g, "%20")
- .replace(/%25/g, "%"); // Revert encoded "%"
-}
-/**
- * Append a string to URL path. Will remove duplicated "/" in front of the string
- * when URL path ends with a "/".
- *
- * @param url - Source URL string
- * @param name - String to be appended to URL
- * @returns An updated URL string
- */
-function appendToURLPath(url, name) {
- const urlParsed = new URL(url);
- let path = urlParsed.pathname;
- path = path ? (path.endsWith("/") ? `${path}${name}` : `${path}/${name}`) : name;
- urlParsed.pathname = path;
- return urlParsed.toString();
-}
-/**
- * Set URL parameter name and value. If name exists in URL parameters, old value
- * will be replaced by name key. If not provide value, the parameter will be deleted.
- *
- * @param url - Source URL string
- * @param name - Parameter name
- * @param value - Parameter value
- * @returns An updated URL string
- */
-function setURLParameter(url, name, value) {
- const urlParsed = new URL(url);
- const encodedName = encodeURIComponent(name);
- const encodedValue = value ? encodeURIComponent(value) : undefined;
- // mutating searchParams will change the encoding, so we have to do this ourselves
- const searchString = urlParsed.search === "" ? "?" : urlParsed.search;
- const searchPieces = [];
- for (const pair of searchString.slice(1).split("&")) {
- if (pair) {
- const [key] = pair.split("=", 2);
- if (key !== encodedName) {
- searchPieces.push(pair);
- }
- }
- }
- if (encodedValue) {
- searchPieces.push(`${encodedName}=${encodedValue}`);
- }
- urlParsed.search = searchPieces.length ? `?${searchPieces.join("&")}` : "";
- return urlParsed.toString();
-}
-/**
- * Get URL parameter by name.
- *
- * @param url -
- * @param name -
- */
-function getURLParameter(url, name) {
- const urlParsed = new URL(url);
- return urlParsed.searchParams.get(name) ?? undefined;
-}
-/**
- * Set URL host.
- *
- * @param url - Source URL string
- * @param host - New host string
- * @returns An updated URL string
- */
-function setURLHost(url, host) {
- const urlParsed = new URL(url);
- urlParsed.hostname = host;
- return urlParsed.toString();
-}
-/**
- * Get URL path from an URL string.
- *
- * @param url - Source URL string
- */
-function getURLPath(url) {
- try {
- const urlParsed = new URL(url);
- return urlParsed.pathname;
- }
- catch (e) {
- return undefined;
- }
-}
-/**
- * Get URL scheme from an URL string.
- *
- * @param url - Source URL string
- */
-function getURLScheme(url) {
- try {
- const urlParsed = new URL(url);
- return urlParsed.protocol.endsWith(":") ? urlParsed.protocol.slice(0, -1) : urlParsed.protocol;
- }
- catch (e) {
- return undefined;
- }
-}
-/**
- * Get URL path and query from an URL string.
- *
- * @param url - Source URL string
- */
-function getURLPathAndQuery(url) {
- const urlParsed = new URL(url);
- const pathString = urlParsed.pathname;
- if (!pathString) {
- throw new RangeError("Invalid url without valid path.");
- }
- let queryString = urlParsed.search || "";
- queryString = queryString.trim();
- if (queryString !== "") {
- queryString = queryString.startsWith("?") ? queryString : `?${queryString}`; // Ensure query string start with '?'
- }
- return `${pathString}${queryString}`;
-}
-/**
- * Get URL query key value pairs from an URL string.
- *
- * @param url -
- */
-function getURLQueries(url) {
- let queryString = new URL(url).search;
- if (!queryString) {
- return {};
- }
- queryString = queryString.trim();
- queryString = queryString.startsWith("?") ? queryString.substring(1) : queryString;
- let querySubStrings = queryString.split("&");
- querySubStrings = querySubStrings.filter((value) => {
- const indexOfEqual = value.indexOf("=");
- const lastIndexOfEqual = value.lastIndexOf("=");
- return (indexOfEqual > 0 && indexOfEqual === lastIndexOfEqual && lastIndexOfEqual < value.length - 1);
- });
- const queries = {};
- for (const querySubString of querySubStrings) {
- const splitResults = querySubString.split("=");
- const key = splitResults[0];
- const value = splitResults[1];
- queries[key] = value;
- }
- return queries;
-}
-/**
- * Append a string to URL query.
- *
- * @param url - Source URL string.
- * @param queryParts - String to be appended to the URL query.
- * @returns An updated URL string.
- */
-function appendToURLQuery(url, queryParts) {
- const urlParsed = new URL(url);
- let query = urlParsed.search;
- if (query) {
- query += "&" + queryParts;
- }
- else {
- query = queryParts;
- }
- urlParsed.search = query;
- return urlParsed.toString();
-}
-/**
- * Rounds a date off to seconds.
- *
- * @param date -
- * @param withMilliseconds - If true, YYYY-MM-DDThh:mm:ss.fffffffZ will be returned;
- * If false, YYYY-MM-DDThh:mm:ssZ will be returned.
- * @returns Date string in ISO8061 format, with or without 7 milliseconds component
- */
-function truncatedISO8061Date(date, withMilliseconds = true) {
- // Date.toISOString() will return like "2018-10-29T06:34:36.139Z"
- const dateString = date.toISOString();
- return withMilliseconds
- ? dateString.substring(0, dateString.length - 1) + "0000" + "Z"
- : dateString.substring(0, dateString.length - 5) + "Z";
-}
-/**
- * Base64 encode.
- *
- * @param content -
- */
-function base64encode(content) {
- return !isNodeLike ? btoa(content) : Buffer.from(content).toString("base64");
-}
-/**
- * Base64 decode.
- *
- * @param encodedString -
- */
-function base64decode(encodedString) {
- return !isNodeLike ? atob(encodedString) : Buffer.from(encodedString, "base64").toString();
-}
-/**
- * Generate a 64 bytes base64 block ID string.
- *
- * @param blockIndex -
- */
-function generateBlockID(blockIDPrefix, blockIndex) {
- // To generate a 64 bytes base64 string, source string should be 48
- const maxSourceStringLength = 48;
- // A blob can have a maximum of 100,000 uncommitted blocks at any given time
- const maxBlockIndexLength = 6;
- const maxAllowedBlockIDPrefixLength = maxSourceStringLength - maxBlockIndexLength;
- if (blockIDPrefix.length > maxAllowedBlockIDPrefixLength) {
- blockIDPrefix = blockIDPrefix.slice(0, maxAllowedBlockIDPrefixLength);
- }
- const res = blockIDPrefix +
- padStart(blockIndex.toString(), maxSourceStringLength - blockIDPrefix.length, "0");
- return base64encode(res);
-}
-/**
- * Delay specified time interval.
- *
- * @param timeInMs -
- * @param aborter -
- * @param abortError -
- */
-async function utils_common_delay(timeInMs, aborter, abortError) {
- return new Promise((resolve, reject) => {
- /* eslint-disable-next-line prefer-const */
- let timeout;
- const abortHandler = () => {
- if (timeout !== undefined) {
- clearTimeout(timeout);
- }
- reject(abortError);
- };
- const resolveHandler = () => {
- if (aborter !== undefined) {
- aborter.removeEventListener("abort", abortHandler);
- }
- resolve();
- };
- timeout = setTimeout(resolveHandler, timeInMs);
- if (aborter !== undefined) {
- aborter.addEventListener("abort", abortHandler);
- }
- });
-}
-/**
- * String.prototype.padStart()
- *
- * @param currentString -
- * @param targetLength -
- * @param padString -
- */
-function padStart(currentString, targetLength, padString = " ") {
- // @ts-expect-error: TS doesn't know this code needs to run downlevel sometimes
- if (String.prototype.padStart) {
- return currentString.padStart(targetLength, padString);
- }
- padString = padString || " ";
- if (currentString.length > targetLength) {
- return currentString;
- }
- else {
- targetLength = targetLength - currentString.length;
- if (targetLength > padString.length) {
- padString += padString.repeat(targetLength / padString.length);
- }
- return padString.slice(0, targetLength) + currentString;
- }
-}
-function sanitizeURL(url) {
- let safeURL = url;
- if (getURLParameter(safeURL, URLConstants.Parameters.SIGNATURE)) {
- safeURL = setURLParameter(safeURL, URLConstants.Parameters.SIGNATURE, "*****");
- }
- return safeURL;
-}
-function sanitizeHeaders(originalHeader) {
- const headers = createHttpHeaders();
- for (const [name, value] of originalHeader) {
- if (name.toLowerCase() === HeaderConstants.AUTHORIZATION.toLowerCase()) {
- headers.set(name, "*****");
- }
- else if (name.toLowerCase() === HeaderConstants.X_MS_COPY_SOURCE) {
- headers.set(name, sanitizeURL(value));
- }
- else {
- headers.set(name, value);
- }
- }
- return headers;
-}
-/**
- * If two strings are equal when compared case insensitive.
- *
- * @param str1 -
- * @param str2 -
- */
-function iEqual(str1, str2) {
- return str1.toLocaleLowerCase() === str2.toLocaleLowerCase();
-}
-/**
- * Extracts account name from the url
- * @param url - url to extract the account name from
- * @returns with the account name
- */
-function getAccountNameFromUrl(url) {
- const parsedUrl = new URL(url);
- let accountName;
- try {
- if (parsedUrl.hostname.split(".")[1] === "blob") {
- // `${defaultEndpointsProtocol}://${accountName}.blob.${endpointSuffix}`;
- accountName = parsedUrl.hostname.split(".")[0];
- }
- else if (isIpEndpointStyle(parsedUrl)) {
- // IPv4/IPv6 address hosts... Example - http://192.0.0.10:10001/devstoreaccount1/
- // Single word domain without a [dot] in the endpoint... Example - http://localhost:10001/devstoreaccount1/
- // .getPath() -> /devstoreaccount1/
- accountName = parsedUrl.pathname.split("/")[1];
- }
- else {
- // Custom domain case: "https://customdomain.com/containername/blob".
- accountName = "";
- }
- return accountName;
- }
- catch (error) {
- throw new Error("Unable to extract accountName with provided information.");
- }
-}
-function isIpEndpointStyle(parsedUrl) {
- const host = parsedUrl.host;
- // Case 1: Ipv6, use a broad regex to find out candidates whose host contains two ':'.
- // Case 2: localhost(:port) or host.docker.internal, use broad regex to match port part.
- // Case 3: Ipv4, use broad regex which just check if host contains Ipv4.
- // For valid host please refer to https://man7.org/linux/man-pages/man7/hostname.7.html.
- return (/^.*:.*:.*$|^(localhost|host.docker.internal)(:[0-9]+)?$|^(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])(\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])){3}(:[0-9]+)?$/.test(host) ||
- (Boolean(parsedUrl.port) && PathStylePorts.includes(parsedUrl.port)));
-}
-/**
- * Attach a TokenCredential to an object.
- *
- * @param thing -
- * @param credential -
- */
-function attachCredential(thing, credential) {
- thing.credential = credential;
- return thing;
-}
-function httpAuthorizationToString(httpAuthorization) {
- return httpAuthorization ? httpAuthorization.scheme + " " + httpAuthorization.value : undefined;
-}
-/**
- * Escape the blobName but keep path separator ('/').
- */
-function EscapePath(blobName) {
- const split = blobName.split("/");
- for (let i = 0; i < split.length; i++) {
- split[i] = encodeURIComponent(split[i]);
- }
- return split.join("/");
-}
-/**
- * A typesafe helper for ensuring that a given response object has
- * the original _response attached.
- * @param response - A response object from calling a client operation
- * @returns The same object, but with known _response property
- */
-function assertResponse(response) {
- if (`_response` in response) {
- return response;
- }
- throw new TypeError(`Unexpected response object ${response}`);
-}
-//# sourceMappingURL=utils.common.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/policies/StorageBrowserPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-
-
-/**
- * StorageBrowserPolicy will handle differences between Node.js and browser runtime, including:
- *
- * 1. Browsers cache GET/HEAD requests by adding conditional headers such as 'IF_MODIFIED_SINCE'.
- * StorageBrowserPolicy is a policy used to add a timestamp query to GET/HEAD request URL
- * thus avoid the browser cache.
- *
- * 2. Remove cookie header for security
- *
- * 3. Remove content-length header to avoid browsers warning
- */
-class StorageBrowserPolicy extends BaseRequestPolicy {
- /**
- * Creates an instance of StorageBrowserPolicy.
- * @param nextPolicy -
- * @param options -
- */
- // The base class has a protected constructor. Adding a public one to enable constructing of this class.
- /* eslint-disable-next-line @typescript-eslint/no-useless-constructor*/
- constructor(nextPolicy, options) {
- super(nextPolicy, options);
- }
- /**
- * Sends out request.
- *
- * @param request -
- */
- async sendRequest(request) {
- if (esm_isNodeLike) {
- return this._nextPolicy.sendRequest(request);
- }
- if (request.method.toUpperCase() === "GET" || request.method.toUpperCase() === "HEAD") {
- request.url = setURLParameter(request.url, constants_URLConstants.Parameters.FORCE_BROWSER_NO_CACHE, new Date().getTime().toString());
- }
- request.headers.remove(constants_HeaderConstants.COOKIE);
- // According to XHR standards, content-length should be fully controlled by browsers
- request.headers.remove(constants_HeaderConstants.CONTENT_LENGTH);
- return this._nextPolicy.sendRequest(request);
- }
-}
-//# sourceMappingURL=StorageBrowserPolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/StorageBrowserPolicyFactory.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-/**
- * StorageBrowserPolicyFactory is a factory class helping generating StorageBrowserPolicy objects.
- */
-class StorageBrowserPolicyFactory {
- /**
- * Creates a StorageBrowserPolicyFactory object.
- *
- * @param nextPolicy -
- * @param options -
- */
- create(nextPolicy, options) {
- return new StorageBrowserPolicy(nextPolicy, options);
- }
-}
-//# sourceMappingURL=StorageBrowserPolicyFactory.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/policies/CredentialPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-/**
- * Credential policy used to sign HTTP(S) requests before sending. This is an
- * abstract class.
- */
-class CredentialPolicy extends BaseRequestPolicy {
- /**
- * Sends out request.
- *
- * @param request -
- */
- sendRequest(request) {
- return this._nextPolicy.sendRequest(this.signRequest(request));
- }
- /**
- * Child classes must implement this method with request signing. This method
- * will be executed in {@link sendRequest}.
- *
- * @param request -
- */
- signRequest(request) {
- // Child classes must override this method with request signing. This method
- // will be executed in sendRequest().
- return request;
- }
-}
-//# sourceMappingURL=CredentialPolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/policies/AnonymousCredentialPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-/**
- * AnonymousCredentialPolicy is used with HTTP(S) requests that read public resources
- * or for use with Shared Access Signatures (SAS).
- */
-class AnonymousCredentialPolicy extends CredentialPolicy {
- /**
- * Creates an instance of AnonymousCredentialPolicy.
- * @param nextPolicy -
- * @param options -
- */
- // The base class has a protected constructor. Adding a public one to enable constructing of this class.
- /* eslint-disable-next-line @typescript-eslint/no-useless-constructor*/
- constructor(nextPolicy, options) {
- super(nextPolicy, options);
- }
-}
-//# sourceMappingURL=AnonymousCredentialPolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/credentials/Credential.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-/**
- * Credential is an abstract class for Azure Storage HTTP requests signing. This
- * class will host an credentialPolicyCreator factory which generates CredentialPolicy.
- */
-class Credential {
- /**
- * Creates a RequestPolicy object.
- *
- * @param _nextPolicy -
- * @param _options -
- */
- create(_nextPolicy, _options) {
- throw new Error("Method should be implemented in children classes.");
- }
-}
-//# sourceMappingURL=Credential.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/credentials/AnonymousCredential.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-/**
- * AnonymousCredential provides a credentialPolicyCreator member used to create
- * AnonymousCredentialPolicy objects. AnonymousCredentialPolicy is used with
- * HTTP(S) requests that read public resources or for use with Shared Access
- * Signatures (SAS).
- */
-class AnonymousCredential extends Credential {
- /**
- * Creates an {@link AnonymousCredentialPolicy} object.
- *
- * @param nextPolicy -
- * @param options -
- */
- create(nextPolicy, options) {
- return new AnonymousCredentialPolicy(nextPolicy, options);
- }
-}
-//# sourceMappingURL=AnonymousCredential.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/utils/SharedKeyComparator.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-/*
- * We need to imitate .Net culture-aware sorting, which is used in storage service.
- * Below tables contain sort-keys for en-US culture.
- */
-const table_lv0 = new Uint32Array([
- 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
- 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x71c, 0x0, 0x71f, 0x721,
- 0x723, 0x725, 0x0, 0x0, 0x0, 0x72d, 0x803, 0x0, 0x0, 0x733, 0x0, 0xd03, 0xd1a, 0xd1c, 0xd1e,
- 0xd20, 0xd22, 0xd24, 0xd26, 0xd28, 0xd2a, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xe02, 0xe09, 0xe0a,
- 0xe1a, 0xe21, 0xe23, 0xe25, 0xe2c, 0xe32, 0xe35, 0xe36, 0xe48, 0xe51, 0xe70, 0xe7c, 0xe7e, 0xe89,
- 0xe8a, 0xe91, 0xe99, 0xe9f, 0xea2, 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0x0, 0x0, 0x0, 0x0,
- 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
- 0x0, 0x8012, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8212, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
- 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
- 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
- 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
- 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
-]);
-function compareHeader(lhs, rhs) {
- if (isLessThan(lhs, rhs))
- return -1;
- return 1;
-}
-function isLessThan(lhs, rhs) {
- const tables = [table_lv0, table_lv2, table_lv4];
- let curr_level = 0;
- let i = 0;
- let j = 0;
- while (curr_level < tables.length) {
- if (curr_level === tables.length - 1 && i !== j) {
- return i > j;
- }
- const weight1 = i < lhs.length ? tables[curr_level][lhs[i].charCodeAt(0)] : 0x1;
- const weight2 = j < rhs.length ? tables[curr_level][rhs[j].charCodeAt(0)] : 0x1;
- if (weight1 === 0x1 && weight2 === 0x1) {
- i = 0;
- j = 0;
- ++curr_level;
- }
- else if (weight1 === weight2) {
- ++i;
- ++j;
- }
- else if (weight1 === 0) {
- ++i;
- }
- else if (weight2 === 0) {
- ++j;
- }
- else {
- return weight1 < weight2;
- }
- }
- return false;
-}
-//# sourceMappingURL=SharedKeyComparator.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/policies/StorageSharedKeyCredentialPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-
-
-/**
- * StorageSharedKeyCredentialPolicy is a policy used to sign HTTP request with a shared key.
- */
-class StorageSharedKeyCredentialPolicy extends CredentialPolicy {
- /**
- * Reference to StorageSharedKeyCredential which generates StorageSharedKeyCredentialPolicy
- */
- factory;
- /**
- * Creates an instance of StorageSharedKeyCredentialPolicy.
- * @param nextPolicy -
- * @param options -
- * @param factory -
- */
- constructor(nextPolicy, options, factory) {
- super(nextPolicy, options);
- this.factory = factory;
- }
- /**
- * Signs request.
- *
- * @param request -
- */
- signRequest(request) {
- request.headers.set(constants_HeaderConstants.X_MS_DATE, new Date().toUTCString());
- if (request.body &&
- (typeof request.body === "string" || request.body !== undefined) &&
- request.body.length > 0) {
- request.headers.set(constants_HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(request.body));
- }
- const stringToSign = [
- request.method.toUpperCase(),
- this.getHeaderValueToSign(request, constants_HeaderConstants.CONTENT_LANGUAGE),
- this.getHeaderValueToSign(request, constants_HeaderConstants.CONTENT_ENCODING),
- this.getHeaderValueToSign(request, constants_HeaderConstants.CONTENT_LENGTH),
- this.getHeaderValueToSign(request, constants_HeaderConstants.CONTENT_MD5),
- this.getHeaderValueToSign(request, constants_HeaderConstants.CONTENT_TYPE),
- this.getHeaderValueToSign(request, constants_HeaderConstants.DATE),
- this.getHeaderValueToSign(request, constants_HeaderConstants.IF_MODIFIED_SINCE),
- this.getHeaderValueToSign(request, constants_HeaderConstants.IF_MATCH),
- this.getHeaderValueToSign(request, constants_HeaderConstants.IF_NONE_MATCH),
- this.getHeaderValueToSign(request, constants_HeaderConstants.IF_UNMODIFIED_SINCE),
- this.getHeaderValueToSign(request, constants_HeaderConstants.RANGE),
- ].join("\n") +
- "\n" +
- this.getCanonicalizedHeadersString(request) +
- this.getCanonicalizedResourceString(request);
- const signature = this.factory.computeHMACSHA256(stringToSign);
- request.headers.set(constants_HeaderConstants.AUTHORIZATION, `SharedKey ${this.factory.accountName}:${signature}`);
- // console.log(`[URL]:${request.url}`);
- // console.log(`[HEADERS]:${request.headers.toString()}`);
- // console.log(`[STRING TO SIGN]:${JSON.stringify(stringToSign)}`);
- // console.log(`[KEY]: ${request.headers.get(HeaderConstants.AUTHORIZATION)}`);
- return request;
- }
- /**
- * Retrieve header value according to shared key sign rules.
- * @see https://learn.microsoft.com/rest/api/storageservices/authenticate-with-shared-key
- *
- * @param request -
- * @param headerName -
- */
- getHeaderValueToSign(request, headerName) {
- const value = request.headers.get(headerName);
- if (!value) {
- return "";
- }
- // When using version 2015-02-21 or later, if Content-Length is zero, then
- // set the Content-Length part of the StringToSign to an empty string.
- // https://learn.microsoft.com/rest/api/storageservices/authenticate-with-shared-key
- if (headerName === constants_HeaderConstants.CONTENT_LENGTH && value === "0") {
- return "";
- }
- return value;
- }
- /**
- * To construct the CanonicalizedHeaders portion of the signature string, follow these steps:
- * 1. Retrieve all headers for the resource that begin with x-ms-, including the x-ms-date header.
- * 2. Convert each HTTP header name to lowercase.
- * 3. Sort the headers lexicographically by header name, in ascending order.
- * Each header may appear only once in the string.
- * 4. Replace any linear whitespace in the header value with a single space.
- * 5. Trim any whitespace around the colon in the header.
- * 6. Finally, append a new-line character to each canonicalized header in the resulting list.
- * Construct the CanonicalizedHeaders string by concatenating all headers in this list into a single string.
- *
- * @param request -
- */
- getCanonicalizedHeadersString(request) {
- let headersArray = request.headers.headersArray().filter((value) => {
- return value.name.toLowerCase().startsWith(constants_HeaderConstants.PREFIX_FOR_STORAGE);
- });
- headersArray.sort((a, b) => {
- return compareHeader(a.name.toLowerCase(), b.name.toLowerCase());
- });
- // Remove duplicate headers
- headersArray = headersArray.filter((value, index, array) => {
- if (index > 0 && value.name.toLowerCase() === array[index - 1].name.toLowerCase()) {
- return false;
- }
- return true;
- });
- let canonicalizedHeadersStringToSign = "";
- headersArray.forEach((header) => {
- canonicalizedHeadersStringToSign += `${header.name
- .toLowerCase()
- .trimRight()}:${header.value.trimLeft()}\n`;
- });
- return canonicalizedHeadersStringToSign;
- }
- /**
- * Retrieves the webResource canonicalized resource string.
- *
- * @param request -
- */
- getCanonicalizedResourceString(request) {
- const path = getURLPath(request.url) || "/";
- let canonicalizedResourceString = "";
- canonicalizedResourceString += `/${this.factory.accountName}${path}`;
- const queries = getURLQueries(request.url);
- const lowercaseQueries = {};
- if (queries) {
- const queryKeys = [];
- for (const key in queries) {
- if (Object.prototype.hasOwnProperty.call(queries, key)) {
- const lowercaseKey = key.toLowerCase();
- lowercaseQueries[lowercaseKey] = queries[key];
- queryKeys.push(lowercaseKey);
- }
- }
- queryKeys.sort();
- for (const key of queryKeys) {
- canonicalizedResourceString += `\n${key}:${decodeURIComponent(lowercaseQueries[key])}`;
- }
- }
- return canonicalizedResourceString;
- }
-}
-//# sourceMappingURL=StorageSharedKeyCredentialPolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/credentials/StorageSharedKeyCredential.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-
-/**
- * ONLY AVAILABLE IN NODE.JS RUNTIME.
- *
- * StorageSharedKeyCredential for account key authorization of Azure Storage service.
- */
-class StorageSharedKeyCredential extends Credential {
- /**
- * Azure Storage account name; readonly.
- */
- accountName;
- /**
- * Azure Storage account key; readonly.
- */
- accountKey;
- /**
- * Creates an instance of StorageSharedKeyCredential.
- * @param accountName -
- * @param accountKey -
- */
- constructor(accountName, accountKey) {
- super();
- this.accountName = accountName;
- this.accountKey = Buffer.from(accountKey, "base64");
- }
- /**
- * Creates a StorageSharedKeyCredentialPolicy object.
- *
- * @param nextPolicy -
- * @param options -
- */
- create(nextPolicy, options) {
- return new StorageSharedKeyCredentialPolicy(nextPolicy, options, this);
- }
- /**
- * Generates a hash signature for an HTTP request or for a SAS.
- *
- * @param stringToSign -
- */
- computeHMACSHA256(stringToSign) {
- return (0,external_node_crypto_.createHmac)("sha256", this.accountKey).update(stringToSign, "utf8").digest("base64");
- }
-}
-//# sourceMappingURL=StorageSharedKeyCredential.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/node_modules/@azure/abort-controller/dist/esm/AbortError.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-/**
- * This error is thrown when an asynchronous operation has been aborted.
- * Check for this error by testing the `name` that the name property of the
- * error matches `"AbortError"`.
- *
- * @example
- * ```ts
- * const controller = new AbortController();
- * controller.abort();
- * try {
- * doAsyncWork(controller.signal)
- * } catch (e) {
- * if (e.name === 'AbortError') {
- * // handle abort error here.
- * }
- * }
- * ```
- */
-class esm_AbortError_AbortError extends Error {
- constructor(message) {
- super(message);
- this.name = "AbortError";
- }
-}
-//# sourceMappingURL=AbortError.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/node_modules/@azure/abort-controller/dist/esm/index.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-
-//# sourceMappingURL=index.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/log.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-/**
- * The `@azure/logger` configuration for this package.
- */
-const storage_common_dist_esm_log_logger = esm_createClientLogger("storage-common");
-//# sourceMappingURL=log.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/policies/StorageRetryPolicyType.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-/**
- * RetryPolicy types.
- */
-var StorageRetryPolicyType;
-(function (StorageRetryPolicyType) {
- /**
- * Exponential retry. Retry time delay grows exponentially.
- */
- StorageRetryPolicyType[StorageRetryPolicyType["EXPONENTIAL"] = 0] = "EXPONENTIAL";
- /**
- * Linear retry. Retry time delay grows linearly.
- */
- StorageRetryPolicyType[StorageRetryPolicyType["FIXED"] = 1] = "FIXED";
-})(StorageRetryPolicyType || (StorageRetryPolicyType = {}));
-//# sourceMappingURL=StorageRetryPolicyType.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/policies/StorageRetryPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-
-
-
-
-/**
- * A factory method used to generated a RetryPolicy factory.
- *
- * @param retryOptions -
- */
-function NewRetryPolicyFactory(retryOptions) {
- return {
- create: (nextPolicy, options) => {
- return new StorageRetryPolicy(nextPolicy, options, retryOptions);
- },
- };
-}
-// Default values of StorageRetryOptions
-const DEFAULT_RETRY_OPTIONS = {
- maxRetryDelayInMs: 120 * 1000,
- maxTries: 4,
- retryDelayInMs: 4 * 1000,
- retryPolicyType: StorageRetryPolicyType.EXPONENTIAL,
- secondaryHost: "",
- tryTimeoutInMs: undefined, // Use server side default timeout strategy
-};
-const RETRY_ABORT_ERROR = new esm_AbortError_AbortError("The operation was aborted.");
-/**
- * Retry policy with exponential retry and linear retry implemented.
- */
-class StorageRetryPolicy extends BaseRequestPolicy {
- /**
- * RetryOptions.
- */
- retryOptions;
- /**
- * Creates an instance of RetryPolicy.
- *
- * @param nextPolicy -
- * @param options -
- * @param retryOptions -
- */
- constructor(nextPolicy, options, retryOptions = DEFAULT_RETRY_OPTIONS) {
- super(nextPolicy, options);
- // Initialize retry options
- this.retryOptions = {
- retryPolicyType: retryOptions.retryPolicyType
- ? retryOptions.retryPolicyType
- : DEFAULT_RETRY_OPTIONS.retryPolicyType,
- maxTries: retryOptions.maxTries && retryOptions.maxTries >= 1
- ? Math.floor(retryOptions.maxTries)
- : DEFAULT_RETRY_OPTIONS.maxTries,
- tryTimeoutInMs: retryOptions.tryTimeoutInMs && retryOptions.tryTimeoutInMs >= 0
- ? retryOptions.tryTimeoutInMs
- : DEFAULT_RETRY_OPTIONS.tryTimeoutInMs,
- retryDelayInMs: retryOptions.retryDelayInMs && retryOptions.retryDelayInMs >= 0
- ? Math.min(retryOptions.retryDelayInMs, retryOptions.maxRetryDelayInMs
- ? retryOptions.maxRetryDelayInMs
- : DEFAULT_RETRY_OPTIONS.maxRetryDelayInMs)
- : DEFAULT_RETRY_OPTIONS.retryDelayInMs,
- maxRetryDelayInMs: retryOptions.maxRetryDelayInMs && retryOptions.maxRetryDelayInMs >= 0
- ? retryOptions.maxRetryDelayInMs
- : DEFAULT_RETRY_OPTIONS.maxRetryDelayInMs,
- secondaryHost: retryOptions.secondaryHost
- ? retryOptions.secondaryHost
- : DEFAULT_RETRY_OPTIONS.secondaryHost,
- };
- }
- /**
- * Sends request.
- *
- * @param request -
- */
- async sendRequest(request) {
- return this.attemptSendRequest(request, false, 1);
- }
- /**
- * Decide and perform next retry. Won't mutate request parameter.
- *
- * @param request -
- * @param secondaryHas404 - If attempt was against the secondary & it returned a StatusNotFound (404), then
- * the resource was not found. This may be due to replication delay. So, in this
- * case, we'll never try the secondary again for this operation.
- * @param attempt - How many retries has been attempted to performed, starting from 1, which includes
- * the attempt will be performed by this method call.
- */
- async attemptSendRequest(request, secondaryHas404, attempt) {
- const newRequest = request.clone();
- const isPrimaryRetry = secondaryHas404 ||
- !this.retryOptions.secondaryHost ||
- !(request.method === "GET" || request.method === "HEAD" || request.method === "OPTIONS") ||
- attempt % 2 === 1;
- if (!isPrimaryRetry) {
- newRequest.url = setURLHost(newRequest.url, this.retryOptions.secondaryHost);
- }
- // Set the server-side timeout query parameter "timeout=[seconds]"
- if (this.retryOptions.tryTimeoutInMs) {
- newRequest.url = setURLParameter(newRequest.url, constants_URLConstants.Parameters.TIMEOUT, Math.floor(this.retryOptions.tryTimeoutInMs / 1000).toString());
- }
- let response;
- try {
- storage_common_dist_esm_log_logger.info(`RetryPolicy: =====> Try=${attempt} ${isPrimaryRetry ? "Primary" : "Secondary"}`);
- response = await this._nextPolicy.sendRequest(newRequest);
- if (!this.shouldRetry(isPrimaryRetry, attempt, response)) {
- return response;
- }
- secondaryHas404 = secondaryHas404 || (!isPrimaryRetry && response.status === 404);
- }
- catch (err) {
- storage_common_dist_esm_log_logger.error(`RetryPolicy: Caught error, message: ${err.message}, code: ${err.code}`);
- if (!this.shouldRetry(isPrimaryRetry, attempt, response, err)) {
- throw err;
- }
- }
- await this.delay(isPrimaryRetry, attempt, request.abortSignal);
- return this.attemptSendRequest(request, secondaryHas404, ++attempt);
- }
- /**
- * Decide whether to retry according to last HTTP response and retry counters.
- *
- * @param isPrimaryRetry -
- * @param attempt -
- * @param response -
- * @param err -
- */
- shouldRetry(isPrimaryRetry, attempt, response, err) {
- if (attempt >= this.retryOptions.maxTries) {
- storage_common_dist_esm_log_logger.info(`RetryPolicy: Attempt(s) ${attempt} >= maxTries ${this.retryOptions
- .maxTries}, no further try.`);
- return false;
- }
- // Handle network failures, you may need to customize the list when you implement
- // your own http client
- const retriableErrors = [
- "ETIMEDOUT",
- "ESOCKETTIMEDOUT",
- "ECONNREFUSED",
- "ECONNRESET",
- "ENOENT",
- "ENOTFOUND",
- "TIMEOUT",
- "EPIPE",
- "REQUEST_SEND_ERROR", // For default xhr based http client provided in ms-rest-js
- ];
- if (err) {
- for (const retriableError of retriableErrors) {
- if (err.name.toUpperCase().includes(retriableError) ||
- err.message.toUpperCase().includes(retriableError) ||
- (err.code && err.code.toString().toUpperCase() === retriableError)) {
- storage_common_dist_esm_log_logger.info(`RetryPolicy: Network error ${retriableError} found, will retry.`);
- return true;
- }
- }
- }
- // If attempt was against the secondary & it returned a StatusNotFound (404), then
- // the resource was not found. This may be due to replication delay. So, in this
- // case, we'll never try the secondary again for this operation.
- if (response || err) {
- const statusCode = response ? response.status : err ? err.statusCode : 0;
- if (!isPrimaryRetry && statusCode === 404) {
- storage_common_dist_esm_log_logger.info(`RetryPolicy: Secondary access with 404, will retry.`);
- return true;
- }
- // Server internal error or server timeout
- if (statusCode === 503 || statusCode === 500) {
- storage_common_dist_esm_log_logger.info(`RetryPolicy: Will retry for status code ${statusCode}.`);
- return true;
- }
- }
- if (response) {
- // Retry select Copy Source Error Codes.
- if (response?.status >= 400) {
- const copySourceError = response.headers.get(constants_HeaderConstants.X_MS_CopySourceErrorCode);
- if (copySourceError !== undefined) {
- switch (copySourceError) {
- case "InternalError":
- case "OperationTimedOut":
- case "ServerBusy":
- return true;
- }
- }
- }
- }
- if (err?.code === "PARSE_ERROR" && err?.message.startsWith(`Error "Error: Unclosed root tag`)) {
- storage_common_dist_esm_log_logger.info("RetryPolicy: Incomplete XML response likely due to service timeout, will retry.");
- return true;
- }
- return false;
- }
- /**
- * Delay a calculated time between retries.
- *
- * @param isPrimaryRetry -
- * @param attempt -
- * @param abortSignal -
- */
- async delay(isPrimaryRetry, attempt, abortSignal) {
- let delayTimeInMs = 0;
- if (isPrimaryRetry) {
- switch (this.retryOptions.retryPolicyType) {
- case StorageRetryPolicyType.EXPONENTIAL:
- delayTimeInMs = Math.min((Math.pow(2, attempt - 1) - 1) * this.retryOptions.retryDelayInMs, this.retryOptions.maxRetryDelayInMs);
- break;
- case StorageRetryPolicyType.FIXED:
- delayTimeInMs = this.retryOptions.retryDelayInMs;
- break;
- }
- }
- else {
- delayTimeInMs = Math.random() * 1000;
- }
- storage_common_dist_esm_log_logger.info(`RetryPolicy: Delay for ${delayTimeInMs}ms`);
- return utils_common_delay(delayTimeInMs, abortSignal, RETRY_ABORT_ERROR);
- }
-}
-//# sourceMappingURL=StorageRetryPolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/StorageRetryPolicyFactory.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-
-/**
- * StorageRetryPolicyFactory is a factory class helping generating {@link StorageRetryPolicy} objects.
- */
-class StorageRetryPolicyFactory {
- retryOptions;
- /**
- * Creates an instance of StorageRetryPolicyFactory.
- * @param retryOptions -
- */
- constructor(retryOptions) {
- this.retryOptions = retryOptions;
- }
- /**
- * Creates a StorageRetryPolicy object.
- *
- * @param nextPolicy -
- * @param options -
- */
- create(nextPolicy, options) {
- return new StorageRetryPolicy(nextPolicy, options, this.retryOptions);
- }
-}
-//# sourceMappingURL=StorageRetryPolicyFactory.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/policies/StorageBrowserPolicyV2.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-
-/**
- * The programmatic identifier of the StorageBrowserPolicy.
- */
-const storageBrowserPolicyName = "storageBrowserPolicy";
-/**
- * storageBrowserPolicy is a policy used to prevent browsers from caching requests
- * and to remove cookies and explicit content-length headers.
- */
-function storageBrowserPolicy() {
- return {
- name: storageBrowserPolicyName,
- async sendRequest(request, next) {
- if (esm_isNodeLike) {
- return next(request);
- }
- if (request.method === "GET" || request.method === "HEAD") {
- request.url = setURLParameter(request.url, constants_URLConstants.Parameters.FORCE_BROWSER_NO_CACHE, new Date().getTime().toString());
- }
- request.headers.delete(constants_HeaderConstants.COOKIE);
- // According to XHR standards, content-length should be fully controlled by browsers
- request.headers.delete(constants_HeaderConstants.CONTENT_LENGTH);
- return next(request);
- },
- };
-}
-//# sourceMappingURL=StorageBrowserPolicyV2.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/policies/StorageCorrectContentLengthPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-/**
- * The programmatic identifier of the storageCorrectContentLengthPolicy.
- */
-const storageCorrectContentLengthPolicyName = "StorageCorrectContentLengthPolicy";
-/**
- * storageCorrectContentLengthPolicy to correctly set Content-Length header with request body length.
- */
-function storageCorrectContentLengthPolicy() {
- function correctContentLength(request) {
- if (request.body &&
- (typeof request.body === "string" || Buffer.isBuffer(request.body)) &&
- request.body.length > 0) {
- request.headers.set(constants_HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(request.body));
- }
- }
- return {
- name: storageCorrectContentLengthPolicyName,
- async sendRequest(request, next) {
- correctContentLength(request);
- return next(request);
- },
- };
-}
-//# sourceMappingURL=StorageCorrectContentLengthPolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/policies/StorageRetryPolicyV2.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-
-
-
-
-
-/**
- * Name of the {@link storageRetryPolicy}
- */
-const storageRetryPolicyName = "storageRetryPolicy";
-// Default values of StorageRetryOptions
-const StorageRetryPolicyV2_DEFAULT_RETRY_OPTIONS = {
- maxRetryDelayInMs: 120 * 1000,
- maxTries: 4,
- retryDelayInMs: 4 * 1000,
- retryPolicyType: StorageRetryPolicyType.EXPONENTIAL,
- secondaryHost: "",
- tryTimeoutInMs: undefined, // Use server side default timeout strategy
-};
-const retriableErrors = [
- "ETIMEDOUT",
- "ESOCKETTIMEDOUT",
- "ECONNREFUSED",
- "ECONNRESET",
- "ENOENT",
- "ENOTFOUND",
- "TIMEOUT",
- "EPIPE",
- "REQUEST_SEND_ERROR",
-];
-const StorageRetryPolicyV2_RETRY_ABORT_ERROR = new esm_AbortError_AbortError("The operation was aborted.");
-/**
- * Retry policy with exponential retry and linear retry implemented.
- */
-function storageRetryPolicy(options = {}) {
- const retryPolicyType = options.retryPolicyType ?? StorageRetryPolicyV2_DEFAULT_RETRY_OPTIONS.retryPolicyType;
- const maxTries = options.maxTries ?? StorageRetryPolicyV2_DEFAULT_RETRY_OPTIONS.maxTries;
- const retryDelayInMs = options.retryDelayInMs ?? StorageRetryPolicyV2_DEFAULT_RETRY_OPTIONS.retryDelayInMs;
- const maxRetryDelayInMs = options.maxRetryDelayInMs ?? StorageRetryPolicyV2_DEFAULT_RETRY_OPTIONS.maxRetryDelayInMs;
- const secondaryHost = options.secondaryHost ?? StorageRetryPolicyV2_DEFAULT_RETRY_OPTIONS.secondaryHost;
- const tryTimeoutInMs = options.tryTimeoutInMs ?? StorageRetryPolicyV2_DEFAULT_RETRY_OPTIONS.tryTimeoutInMs;
- function shouldRetry({ isPrimaryRetry, attempt, response, error, }) {
- if (attempt >= maxTries) {
- storage_common_dist_esm_log_logger.info(`RetryPolicy: Attempt(s) ${attempt} >= maxTries ${maxTries}, no further try.`);
- return false;
- }
- if (error) {
- for (const retriableError of retriableErrors) {
- if (error.name.toUpperCase().includes(retriableError) ||
- error.message.toUpperCase().includes(retriableError) ||
- (error.code && error.code.toString().toUpperCase() === retriableError)) {
- storage_common_dist_esm_log_logger.info(`RetryPolicy: Network error ${retriableError} found, will retry.`);
- return true;
- }
- }
- if (error?.code === "PARSE_ERROR" &&
- error?.message.startsWith(`Error "Error: Unclosed root tag`)) {
- storage_common_dist_esm_log_logger.info("RetryPolicy: Incomplete XML response likely due to service timeout, will retry.");
- return true;
- }
- }
- // If attempt was against the secondary & it returned a StatusNotFound (404), then
- // the resource was not found. This may be due to replication delay. So, in this
- // case, we'll never try the secondary again for this operation.
- if (response || error) {
- const statusCode = response?.status ?? error?.statusCode ?? 0;
- if (!isPrimaryRetry && statusCode === 404) {
- storage_common_dist_esm_log_logger.info(`RetryPolicy: Secondary access with 404, will retry.`);
- return true;
- }
- // Server internal error or server timeout
- if (statusCode === 503 || statusCode === 500) {
- storage_common_dist_esm_log_logger.info(`RetryPolicy: Will retry for status code ${statusCode}.`);
- return true;
- }
- }
- if (response) {
- // Retry select Copy Source Error Codes.
- if (response?.status >= 400) {
- const copySourceError = response.headers.get(constants_HeaderConstants.X_MS_CopySourceErrorCode);
- if (copySourceError !== undefined) {
- switch (copySourceError) {
- case "InternalError":
- case "OperationTimedOut":
- case "ServerBusy":
- return true;
- }
- }
- }
- }
- return false;
- }
- function calculateDelay(isPrimaryRetry, attempt) {
- let delayTimeInMs = 0;
- if (isPrimaryRetry) {
- switch (retryPolicyType) {
- case StorageRetryPolicyType.EXPONENTIAL:
- delayTimeInMs = Math.min((Math.pow(2, attempt - 1) - 1) * retryDelayInMs, maxRetryDelayInMs);
- break;
- case StorageRetryPolicyType.FIXED:
- delayTimeInMs = retryDelayInMs;
- break;
- }
- }
- else {
- delayTimeInMs = Math.random() * 1000;
- }
- storage_common_dist_esm_log_logger.info(`RetryPolicy: Delay for ${delayTimeInMs}ms`);
- return delayTimeInMs;
- }
- return {
- name: storageRetryPolicyName,
- async sendRequest(request, next) {
- // Set the server-side timeout query parameter "timeout=[seconds]"
- if (tryTimeoutInMs) {
- request.url = setURLParameter(request.url, constants_URLConstants.Parameters.TIMEOUT, String(Math.floor(tryTimeoutInMs / 1000)));
- }
- const primaryUrl = request.url;
- const secondaryUrl = secondaryHost ? setURLHost(request.url, secondaryHost) : undefined;
- let secondaryHas404 = false;
- let attempt = 1;
- let retryAgain = true;
- let response;
- let error;
- while (retryAgain) {
- const isPrimaryRetry = secondaryHas404 ||
- !secondaryUrl ||
- !["GET", "HEAD", "OPTIONS"].includes(request.method) ||
- attempt % 2 === 1;
- request.url = isPrimaryRetry ? primaryUrl : secondaryUrl;
- response = undefined;
- error = undefined;
- try {
- storage_common_dist_esm_log_logger.info(`RetryPolicy: =====> Try=${attempt} ${isPrimaryRetry ? "Primary" : "Secondary"}`);
- response = await next(request);
- secondaryHas404 = secondaryHas404 || (!isPrimaryRetry && response.status === 404);
- }
- catch (e) {
- if (esm_restError_isRestError(e)) {
- storage_common_dist_esm_log_logger.error(`RetryPolicy: Caught error, message: ${e.message}, code: ${e.code}`);
- error = e;
- }
- else {
- storage_common_dist_esm_log_logger.error(`RetryPolicy: Caught error, message: ${getErrorMessage(e)}`);
- throw e;
- }
- }
- retryAgain = shouldRetry({ isPrimaryRetry, attempt, response, error });
- if (retryAgain) {
- await utils_common_delay(calculateDelay(isPrimaryRetry, attempt), request.abortSignal, StorageRetryPolicyV2_RETRY_ABORT_ERROR);
- }
- attempt++;
- }
- if (response) {
- return response;
- }
- throw error ?? new esm_restError_RestError("RetryPolicy failed without known error.");
- },
- };
-}
-//# sourceMappingURL=StorageRetryPolicyV2.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/policies/StorageSharedKeyCredentialPolicyV2.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-
-
-/**
- * The programmatic identifier of the storageSharedKeyCredentialPolicy.
- */
-const storageSharedKeyCredentialPolicyName = "storageSharedKeyCredentialPolicy";
-/**
- * storageSharedKeyCredentialPolicy handles signing requests using storage account keys.
- */
-function storageSharedKeyCredentialPolicy(options) {
- function signRequest(request) {
- request.headers.set(constants_HeaderConstants.X_MS_DATE, new Date().toUTCString());
- if (request.body &&
- (typeof request.body === "string" || Buffer.isBuffer(request.body)) &&
- request.body.length > 0) {
- request.headers.set(constants_HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(request.body));
- }
- const stringToSign = [
- request.method.toUpperCase(),
- getHeaderValueToSign(request, constants_HeaderConstants.CONTENT_LANGUAGE),
- getHeaderValueToSign(request, constants_HeaderConstants.CONTENT_ENCODING),
- getHeaderValueToSign(request, constants_HeaderConstants.CONTENT_LENGTH),
- getHeaderValueToSign(request, constants_HeaderConstants.CONTENT_MD5),
- getHeaderValueToSign(request, constants_HeaderConstants.CONTENT_TYPE),
- getHeaderValueToSign(request, constants_HeaderConstants.DATE),
- getHeaderValueToSign(request, constants_HeaderConstants.IF_MODIFIED_SINCE),
- getHeaderValueToSign(request, constants_HeaderConstants.IF_MATCH),
- getHeaderValueToSign(request, constants_HeaderConstants.IF_NONE_MATCH),
- getHeaderValueToSign(request, constants_HeaderConstants.IF_UNMODIFIED_SINCE),
- getHeaderValueToSign(request, constants_HeaderConstants.RANGE),
- ].join("\n") +
- "\n" +
- getCanonicalizedHeadersString(request) +
- getCanonicalizedResourceString(request);
- const signature = (0,external_node_crypto_.createHmac)("sha256", options.accountKey)
- .update(stringToSign, "utf8")
- .digest("base64");
- request.headers.set(constants_HeaderConstants.AUTHORIZATION, `SharedKey ${options.accountName}:${signature}`);
- // console.log(`[URL]:${request.url}`);
- // console.log(`[HEADERS]:${request.headers.toString()}`);
- // console.log(`[STRING TO SIGN]:${JSON.stringify(stringToSign)}`);
- // console.log(`[KEY]: ${request.headers.get(HeaderConstants.AUTHORIZATION)}`);
- }
- /**
- * Retrieve header value according to shared key sign rules.
- * @see https://learn.microsoft.com/rest/api/storageservices/authenticate-with-shared-key
- */
- function getHeaderValueToSign(request, headerName) {
- const value = request.headers.get(headerName);
- if (!value) {
- return "";
- }
- // When using version 2015-02-21 or later, if Content-Length is zero, then
- // set the Content-Length part of the StringToSign to an empty string.
- // https://learn.microsoft.com/rest/api/storageservices/authenticate-with-shared-key
- if (headerName === constants_HeaderConstants.CONTENT_LENGTH && value === "0") {
- return "";
- }
- return value;
- }
- /**
- * To construct the CanonicalizedHeaders portion of the signature string, follow these steps:
- * 1. Retrieve all headers for the resource that begin with x-ms-, including the x-ms-date header.
- * 2. Convert each HTTP header name to lowercase.
- * 3. Sort the headers lexicographically by header name, in ascending order.
- * Each header may appear only once in the string.
- * 4. Replace any linear whitespace in the header value with a single space.
- * 5. Trim any whitespace around the colon in the header.
- * 6. Finally, append a new-line character to each canonicalized header in the resulting list.
- * Construct the CanonicalizedHeaders string by concatenating all headers in this list into a single string.
- *
- */
- function getCanonicalizedHeadersString(request) {
- let headersArray = [];
- for (const [name, value] of request.headers) {
- if (name.toLowerCase().startsWith(constants_HeaderConstants.PREFIX_FOR_STORAGE)) {
- headersArray.push({ name, value });
- }
- }
- headersArray.sort((a, b) => {
- return compareHeader(a.name.toLowerCase(), b.name.toLowerCase());
- });
- // Remove duplicate headers
- headersArray = headersArray.filter((value, index, array) => {
- if (index > 0 && value.name.toLowerCase() === array[index - 1].name.toLowerCase()) {
- return false;
- }
- return true;
- });
- let canonicalizedHeadersStringToSign = "";
- headersArray.forEach((header) => {
- canonicalizedHeadersStringToSign += `${header.name
- .toLowerCase()
- .trimRight()}:${header.value.trimLeft()}\n`;
- });
- return canonicalizedHeadersStringToSign;
- }
- function getCanonicalizedResourceString(request) {
- const path = getURLPath(request.url) || "/";
- let canonicalizedResourceString = "";
- canonicalizedResourceString += `/${options.accountName}${path}`;
- const queries = getURLQueries(request.url);
- const lowercaseQueries = {};
- if (queries) {
- const queryKeys = [];
- for (const key in queries) {
- if (Object.prototype.hasOwnProperty.call(queries, key)) {
- const lowercaseKey = key.toLowerCase();
- lowercaseQueries[lowercaseKey] = queries[key];
- queryKeys.push(lowercaseKey);
- }
- }
- queryKeys.sort();
- for (const key of queryKeys) {
- canonicalizedResourceString += `\n${key}:${decodeURIComponent(lowercaseQueries[key])}`;
- }
- }
- return canonicalizedResourceString;
- }
- return {
- name: storageSharedKeyCredentialPolicyName,
- async sendRequest(request, next) {
- signRequest(request);
- return next(request);
- },
- };
-}
-//# sourceMappingURL=StorageSharedKeyCredentialPolicyV2.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/policies/StorageRequestFailureDetailsParserPolicy.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-/**
- * The programmatic identifier of the StorageRequestFailureDetailsParserPolicy.
- */
-const storageRequestFailureDetailsParserPolicyName = "storageRequestFailureDetailsParserPolicy";
-/**
- * StorageRequestFailureDetailsParserPolicy
- */
-function storageRequestFailureDetailsParserPolicy() {
- return {
- name: storageRequestFailureDetailsParserPolicyName,
- async sendRequest(request, next) {
- try {
- const response = await next(request);
- return response;
- }
- catch (err) {
- if (typeof err === "object" &&
- err !== null &&
- err.response &&
- err.response.parsedBody) {
- if (err.response.parsedBody.code === "InvalidHeaderValue" &&
- err.response.parsedBody.HeaderName === "x-ms-version") {
- err.message =
- "The provided service version is not enabled on this storage account. Please see https://learn.microsoft.com/rest/api/storageservices/versioning-for-the-azure-storage-services for additional information.\n";
- }
- }
- throw err;
- }
- },
- };
-}
-//# sourceMappingURL=StorageRequestFailureDetailsParserPolicy.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/credentials/UserDelegationKeyCredential.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-/**
- * ONLY AVAILABLE IN NODE.JS RUNTIME.
- *
- * UserDelegationKeyCredential is only used for generation of user delegation SAS.
- * @see https://learn.microsoft.com/rest/api/storageservices/create-user-delegation-sas
- */
-class UserDelegationKeyCredential {
- /**
- * Azure Storage account name; readonly.
- */
- accountName;
- /**
- * Azure Storage user delegation key; readonly.
- */
- userDelegationKey;
- /**
- * Key value in Buffer type.
- */
- key;
- /**
- * Creates an instance of UserDelegationKeyCredential.
- * @param accountName -
- * @param userDelegationKey -
- */
- constructor(accountName, userDelegationKey) {
- this.accountName = accountName;
- this.userDelegationKey = userDelegationKey;
- this.key = Buffer.from(userDelegationKey.value, "base64");
- }
- /**
- * Generates a hash signature for an HTTP request or for a SAS.
- *
- * @param stringToSign -
- */
- computeHMACSHA256(stringToSign) {
- // console.log(`stringToSign: ${JSON.stringify(stringToSign)}`);
- return (0,external_node_crypto_.createHmac)("sha256", this.key).update(stringToSign, "utf8").digest("base64");
- }
-}
-//# sourceMappingURL=UserDelegationKeyCredential.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/storage-common/dist/esm/index.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-//# sourceMappingURL=index.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/storage-blob/dist/esm/utils/constants.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-const esm_utils_constants_SDK_VERSION = "12.30.0";
-const SERVICE_VERSION = "2026-02-06";
-const BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES = 256 * 1024 * 1024; // 256MB
-const BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES = 4000 * 1024 * 1024; // 4000MB
-const BLOCK_BLOB_MAX_BLOCKS = 50000;
-const DEFAULT_BLOCK_BUFFER_SIZE_BYTES = 8 * 1024 * 1024; // 8MB
-const DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES = 4 * 1024 * 1024; // 4MB
-const DEFAULT_MAX_DOWNLOAD_RETRY_REQUESTS = 5;
-const REQUEST_TIMEOUT = 100 * 1000; // In ms
-/**
- * The OAuth scope to use with Azure Storage.
- */
-const StorageOAuthScopes = "https://storage.azure.com/.default";
-const utils_constants_URLConstants = {
- Parameters: {
- FORCE_BROWSER_NO_CACHE: "_",
- SIGNATURE: "sig",
- SNAPSHOT: "snapshot",
- VERSIONID: "versionid",
- TIMEOUT: "timeout",
- },
-};
-const HTTPURLConnection = {
- HTTP_ACCEPTED: 202,
- HTTP_CONFLICT: 409,
- HTTP_NOT_FOUND: 404,
- HTTP_PRECON_FAILED: 412,
- HTTP_RANGE_NOT_SATISFIABLE: 416,
-};
-const utils_constants_HeaderConstants = {
- AUTHORIZATION: "Authorization",
- AUTHORIZATION_SCHEME: "Bearer",
- CONTENT_ENCODING: "Content-Encoding",
- CONTENT_ID: "Content-ID",
- CONTENT_LANGUAGE: "Content-Language",
- CONTENT_LENGTH: "Content-Length",
- CONTENT_MD5: "Content-Md5",
- CONTENT_TRANSFER_ENCODING: "Content-Transfer-Encoding",
- CONTENT_TYPE: "Content-Type",
- COOKIE: "Cookie",
- DATE: "date",
- IF_MATCH: "if-match",
- IF_MODIFIED_SINCE: "if-modified-since",
- IF_NONE_MATCH: "if-none-match",
- IF_UNMODIFIED_SINCE: "if-unmodified-since",
- PREFIX_FOR_STORAGE: "x-ms-",
- RANGE: "Range",
- USER_AGENT: "User-Agent",
- X_MS_CLIENT_REQUEST_ID: "x-ms-client-request-id",
- X_MS_COPY_SOURCE: "x-ms-copy-source",
- X_MS_DATE: "x-ms-date",
- X_MS_ERROR_CODE: "x-ms-error-code",
- X_MS_VERSION: "x-ms-version",
- X_MS_CopySourceErrorCode: "x-ms-copy-source-error-code",
-};
-const ETagNone = "";
-const ETagAny = "*";
-const SIZE_1_MB = 1 * 1024 * 1024;
-const BATCH_MAX_REQUEST = 256;
-const BATCH_MAX_PAYLOAD_IN_BYTES = 4 * SIZE_1_MB;
-const HTTP_LINE_ENDING = "\r\n";
-const HTTP_VERSION_1_1 = "HTTP/1.1";
-const EncryptionAlgorithmAES25 = "AES256";
-const utils_constants_DevelopmentConnectionString = `DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;`;
-const StorageBlobLoggingAllowedHeaderNames = [
- "Access-Control-Allow-Origin",
- "Cache-Control",
- "Content-Length",
- "Content-Type",
- "Date",
- "Request-Id",
- "traceparent",
- "Transfer-Encoding",
- "User-Agent",
- "x-ms-client-request-id",
- "x-ms-date",
- "x-ms-error-code",
- "x-ms-request-id",
- "x-ms-return-client-request-id",
- "x-ms-version",
- "Accept-Ranges",
- "Content-Disposition",
- "Content-Encoding",
- "Content-Language",
- "Content-MD5",
- "Content-Range",
- "ETag",
- "Last-Modified",
- "Server",
- "Vary",
- "x-ms-content-crc64",
- "x-ms-copy-action",
- "x-ms-copy-completion-time",
- "x-ms-copy-id",
- "x-ms-copy-progress",
- "x-ms-copy-status",
- "x-ms-has-immutability-policy",
- "x-ms-has-legal-hold",
- "x-ms-lease-state",
- "x-ms-lease-status",
- "x-ms-range",
- "x-ms-request-server-encrypted",
- "x-ms-server-encrypted",
- "x-ms-snapshot",
- "x-ms-source-range",
- "If-Match",
- "If-Modified-Since",
- "If-None-Match",
- "If-Unmodified-Since",
- "x-ms-access-tier",
- "x-ms-access-tier-change-time",
- "x-ms-access-tier-inferred",
- "x-ms-account-kind",
- "x-ms-archive-status",
- "x-ms-blob-append-offset",
- "x-ms-blob-cache-control",
- "x-ms-blob-committed-block-count",
- "x-ms-blob-condition-appendpos",
- "x-ms-blob-condition-maxsize",
- "x-ms-blob-content-disposition",
- "x-ms-blob-content-encoding",
- "x-ms-blob-content-language",
- "x-ms-blob-content-length",
- "x-ms-blob-content-md5",
- "x-ms-blob-content-type",
- "x-ms-blob-public-access",
- "x-ms-blob-sequence-number",
- "x-ms-blob-type",
- "x-ms-copy-destination-snapshot",
- "x-ms-creation-time",
- "x-ms-default-encryption-scope",
- "x-ms-delete-snapshots",
- "x-ms-delete-type-permanent",
- "x-ms-deny-encryption-scope-override",
- "x-ms-encryption-algorithm",
- "x-ms-if-sequence-number-eq",
- "x-ms-if-sequence-number-le",
- "x-ms-if-sequence-number-lt",
- "x-ms-incremental-copy",
- "x-ms-lease-action",
- "x-ms-lease-break-period",
- "x-ms-lease-duration",
- "x-ms-lease-id",
- "x-ms-lease-time",
- "x-ms-page-write",
- "x-ms-proposed-lease-id",
- "x-ms-range-get-content-md5",
- "x-ms-rehydrate-priority",
- "x-ms-sequence-number-action",
- "x-ms-sku-name",
- "x-ms-source-content-md5",
- "x-ms-source-if-match",
- "x-ms-source-if-modified-since",
- "x-ms-source-if-none-match",
- "x-ms-source-if-unmodified-since",
- "x-ms-tag-count",
- "x-ms-encryption-key-sha256",
- "x-ms-copy-source-error-code",
- "x-ms-copy-source-status-code",
- "x-ms-if-tags",
- "x-ms-source-if-tags",
-];
-const StorageBlobLoggingAllowedQueryParameters = [
- "comp",
- "maxresults",
- "rscc",
- "rscd",
- "rsce",
- "rscl",
- "rsct",
- "se",
- "si",
- "sip",
- "sp",
- "spr",
- "sr",
- "srt",
- "ss",
- "st",
- "sv",
- "include",
- "marker",
- "prefix",
- "copyid",
- "restype",
- "blockid",
- "blocklisttype",
- "delimiter",
- "prevsnapshot",
- "ske",
- "skoid",
- "sks",
- "skt",
- "sktid",
- "skv",
- "snapshot",
-];
-const BlobUsesCustomerSpecifiedEncryptionMsg = "BlobUsesCustomerSpecifiedEncryption";
-const BlobDoesNotUseCustomerSpecifiedEncryption = "BlobDoesNotUseCustomerSpecifiedEncryption";
-/// List of ports used for path style addressing.
-/// Path style addressing means that storage account is put in URI's Path segment in instead of in host.
-const utils_constants_PathStylePorts = [
- "10000",
- "10001",
- "10002",
- "10003",
- "10004",
- "10100",
- "10101",
- "10102",
- "10103",
- "10104",
- "11000",
- "11001",
- "11002",
- "11003",
- "11004",
- "11100",
- "11101",
- "11102",
- "11103",
- "11104",
-];
-//# sourceMappingURL=constants.js.map
-;// CONCATENATED MODULE: ./node_modules/@azure/storage-blob/dist/esm/Pipeline.js
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-
-
-
-
-
-
-
-
-// Export following interfaces and types for customers who want to implement their
-// own RequestPolicy or HTTPClient
-
-/**
- * A helper to decide if a given argument satisfies the Pipeline contract
- * @param pipeline - An argument that may be a Pipeline
- * @returns true when the argument satisfies the Pipeline contract
- */
-function isPipelineLike(pipeline) {
- if (!pipeline || typeof pipeline !== "object") {
- return false;
- }
- const castPipeline = pipeline;
- return (Array.isArray(castPipeline.factories) &&
- typeof castPipeline.options === "object" &&
- typeof castPipeline.toServiceClientOptions === "function");
-}
-/**
- * A Pipeline class containing HTTP request policies.
- * You can create a default Pipeline by calling {@link newPipeline}.
- * Or you can create a Pipeline with your own policies by the constructor of Pipeline.
- *
- * Refer to {@link newPipeline} and provided policies before implementing your
- * customized Pipeline.
- */
-class Pipeline {
- /**
- * A list of chained request policy factories.
- */
- factories;
- /**
- * Configures pipeline logger and HTTP client.
- */
- options;
- /**
- * Creates an instance of Pipeline. Customize HTTPClient by implementing IHttpClient interface.
- *
- * @param factories -
- * @param options -
- */
- constructor(factories, options = {}) {
- this.factories = factories;
- this.options = options;
- }
- /**
- * Transfer Pipeline object to ServiceClientOptions object which is required by
- * ServiceClient constructor.
- *
- * @returns The ServiceClientOptions object from this Pipeline.
- */
- toServiceClientOptions() {
- return {
- httpClient: this.options.httpClient,
- requestPolicyFactories: this.factories,
- };
- }
-}
-/**
- * Creates a new Pipeline object with Credential provided.
- *
- * @param credential - Such as AnonymousCredential, StorageSharedKeyCredential or any credential from the `@azure/identity` package to authenticate requests to the service. You can also provide an object that implements the TokenCredential interface. If not specified, AnonymousCredential is used.
- * @param pipelineOptions - Optional. Options.
- * @returns A new Pipeline object.
- */
-function newPipeline(credential, pipelineOptions = {}) {
- if (!credential) {
- credential = new AnonymousCredential();
- }
- const pipeline = new Pipeline([], pipelineOptions);
- pipeline._credential = credential;
- return pipeline;
-}
-function processDownlevelPipeline(pipeline) {
- const knownFactoryFunctions = [
- isAnonymousCredential,
- isStorageSharedKeyCredential,
- isCoreHttpBearerTokenFactory,
- isStorageBrowserPolicyFactory,
- isStorageRetryPolicyFactory,
- isStorageTelemetryPolicyFactory,
- isCoreHttpPolicyFactory,
- ];
- if (pipeline.factories.length) {
- const novelFactories = pipeline.factories.filter((factory) => {
- return !knownFactoryFunctions.some((knownFactory) => knownFactory(factory));
- });
- if (novelFactories.length) {
- const hasInjector = novelFactories.some((factory) => isInjectorPolicyFactory(factory));
- // if there are any left over, wrap in a requestPolicyFactoryPolicy
- return {
- wrappedPolicies: createRequestPolicyFactoryPolicy(novelFactories),
- afterRetry: hasInjector,
- };
- }
- }
- return undefined;
-}
-function getCoreClientOptions(pipeline) {
- const { httpClient: v1Client, ...restOptions } = pipeline.options;
- let httpClient = pipeline._coreHttpClient;
- if (!httpClient) {
- httpClient = v1Client ? convertHttpClient(v1Client) : cache_getCachedDefaultHttpClient();
- pipeline._coreHttpClient = httpClient;
- }
- let corePipeline = pipeline._corePipeline;
- if (!corePipeline) {
- const packageDetails = `azsdk-js-azure-storage-blob/${esm_utils_constants_SDK_VERSION}`;
- const userAgentPrefix = restOptions.userAgentOptions && restOptions.userAgentOptions.userAgentPrefix
- ? `${restOptions.userAgentOptions.userAgentPrefix} ${packageDetails}`
- : `${packageDetails}`;
- corePipeline = createClientPipeline({
- ...restOptions,
- loggingOptions: {
- additionalAllowedHeaderNames: StorageBlobLoggingAllowedHeaderNames,
- additionalAllowedQueryParameters: StorageBlobLoggingAllowedQueryParameters,
- logger: storage_blob_dist_esm_log_logger.info,
- },
- userAgentOptions: {
- userAgentPrefix,
- },
- serializationOptions: {
- stringifyXML: stringifyXML,
- serializerOptions: {
- xml: {
- // Use customized XML char key of "#" so we can deserialize metadata
- // with "_" key
- xmlCharKey: "#",
- },
- },
- },
- deserializationOptions: {
- parseXML: parseXML,
- serializerOptions: {
- xml: {
- // Use customized XML char key of "#" so we can deserialize metadata
- // with "_" key
- xmlCharKey: "#",
- },
- },
- },
- });
- corePipeline.removePolicy({ phase: "Retry" });
- corePipeline.removePolicy({ name: decompressResponsePolicy_decompressResponsePolicyName });
- corePipeline.addPolicy(storageCorrectContentLengthPolicy());
- corePipeline.addPolicy(storageRetryPolicy(restOptions.retryOptions), { phase: "Retry" });
- corePipeline.addPolicy(storageRequestFailureDetailsParserPolicy());
- corePipeline.addPolicy(storageBrowserPolicy());
- const downlevelResults = processDownlevelPipeline(pipeline);
- if (downlevelResults) {
- corePipeline.addPolicy(downlevelResults.wrappedPolicies, downlevelResults.afterRetry ? { afterPhase: "Retry" } : undefined);
- }
- const credential = getCredentialFromPipeline(pipeline);
- if (isTokenCredential(credential)) {
- corePipeline.addPolicy(bearerTokenAuthenticationPolicy({
- credential,
- scopes: restOptions.audience ?? StorageOAuthScopes,
- challengeCallbacks: { authorizeRequestOnChallenge: authorizeRequestOnTenantChallenge },
- }), { phase: "Sign" });
- }
- else if (credential instanceof StorageSharedKeyCredential) {
- corePipeline.addPolicy(storageSharedKeyCredentialPolicy({
- accountName: credential.accountName,
- accountKey: credential.accountKey,
- }), { phase: "Sign" });
- }
- pipeline._corePipeline = corePipeline;
- }
- return {
- ...restOptions,
- allowInsecureConnection: true,
- httpClient,
- pipeline: corePipeline,
- };
-}
-function getCredentialFromPipeline(pipeline) {
- // see if we squirreled one away on the type itself
- if (pipeline._credential) {
- return pipeline._credential;
- }
- // if it came from another package, loop over the factories and look for one like before
- let credential = new AnonymousCredential();
- for (const factory of pipeline.factories) {
- if (isTokenCredential(factory.credential)) {
- // Only works if the factory has been attached a "credential" property.
- // We do that in newPipeline() when using TokenCredential.
- credential = factory.credential;
- }
- else if (isStorageSharedKeyCredential(factory)) {
- return factory;
- }
- }
- return credential;
-}
-function isStorageSharedKeyCredential(factory) {
- if (factory instanceof StorageSharedKeyCredential) {
- return true;
- }
- return factory.constructor.name === "StorageSharedKeyCredential";
-}
-function isAnonymousCredential(factory) {
- if (factory instanceof AnonymousCredential) {
- return true;
- }
- return factory.constructor.name === "AnonymousCredential";
-}
-function isCoreHttpBearerTokenFactory(factory) {
- return isTokenCredential(factory.credential);
-}
-function isStorageBrowserPolicyFactory(factory) {
- if (factory instanceof StorageBrowserPolicyFactory) {
- return true;
- }
- return factory.constructor.name === "StorageBrowserPolicyFactory";
-}
-function isStorageRetryPolicyFactory(factory) {
- if (factory instanceof StorageRetryPolicyFactory) {
- return true;
- }
- return factory.constructor.name === "StorageRetryPolicyFactory";
-}
-function isStorageTelemetryPolicyFactory(factory) {
- return factory.constructor.name === "TelemetryPolicyFactory";
-}
-function isInjectorPolicyFactory(factory) {
- return factory.constructor.name === "InjectorPolicyFactory";
-}
-function isCoreHttpPolicyFactory(factory) {
- const knownPolicies = [
- "GenerateClientRequestIdPolicy",
- "TracingPolicy",
- "LogPolicy",
- "ProxyPolicy",
- "DisableResponseDecompressionPolicy",
- "KeepAlivePolicy",
- "DeserializationPolicy",
- ];
- const mockHttpClient = {
- sendRequest: async (request) => {
- return {
- request,
- headers: request.headers.clone(),
- status: 500,
- };
- },
- };
- const mockRequestPolicyOptions = {
- log(_logLevel, _message) {
- /* do nothing */
- },
- shouldLog(_logLevel) {
- return false;
- },
- };
- const policyInstance = factory.create(mockHttpClient, mockRequestPolicyOptions);
- const policyName = policyInstance.constructor.name;
- // bundlers sometimes add a custom suffix to the class name to make it unique
- return knownPolicies.some((knownPolicyName) => {
- return policyName.startsWith(knownPolicyName);
- });
+function isCoreHttpPolicyFactory(factory) {
+ const knownPolicies = [
+ "GenerateClientRequestIdPolicy",
+ "TracingPolicy",
+ "LogPolicy",
+ "ProxyPolicy",
+ "DisableResponseDecompressionPolicy",
+ "KeepAlivePolicy",
+ "DeserializationPolicy",
+ ];
+ const mockHttpClient = {
+ sendRequest: async (request) => {
+ return {
+ request,
+ headers: request.headers.clone(),
+ status: 500,
+ };
+ },
+ };
+ const mockRequestPolicyOptions = {
+ log(_logLevel, _message) {
+ /* do nothing */
+ },
+ shouldLog(_logLevel) {
+ return false;
+ },
+ };
+ const policyInstance = factory.create(mockHttpClient, mockRequestPolicyOptions);
+ const policyName = policyInstance.constructor.name;
+ // bundlers sometimes add a custom suffix to the class name to make it unique
+ return knownPolicies.some((knownPolicyName) => {
+ return policyName.startsWith(knownPolicyName);
+ });
}
//# sourceMappingURL=Pipeline.js.map
;// CONCATENATED MODULE: ./node_modules/@azure/storage-blob/dist/esm/generated/src/models/index.js
@@ -115000,7 +87962,7 @@ class Clients_BlobClient extends StorageClient_StorageClient {
options.conditions = options.conditions || {};
ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps);
return tracingClient.withSpan("BlobClient-download", options, async (updatedOptions) => {
- const res = utils_common_assertResponse(await this.blobContext.download({
+ const res = utils_common_assertResponse((await this.blobContext.download({
abortSignal: options.abortSignal,
leaseAccessConditions: options.conditions,
modifiedAccessConditions: {
@@ -115016,7 +87978,7 @@ class Clients_BlobClient extends StorageClient_StorageClient {
snapshot: options.snapshot,
cpkInfo: options.customerProvidedKey,
tracingOptions: updatedOptions.tracingOptions,
- }));
+ })));
const wrappedRes = {
...res,
_response: res._response, // _response is made non-enumerable
@@ -116338,7 +89300,7 @@ class BlockBlobClient extends Clients_BlobClient {
throw new Error("This operation currently is only supported in Node.js.");
}
return tracingClient.withSpan("BlockBlobClient-query", options, async (updatedOptions) => {
- const response = utils_common_assertResponse(await this._blobContext.query({
+ const response = utils_common_assertResponse((await this._blobContext.query({
abortSignal: options.abortSignal,
queryRequest: {
queryType: "SQL",
@@ -116353,7 +89315,7 @@ class BlockBlobClient extends Clients_BlobClient {
},
cpkInfo: options.customerProvidedKey,
tracingOptions: updatedOptions.tracingOptions,
- }));
+ })));
return new BlobQueryResponse(response, {
abortSignal: options.abortSignal,
onProgress: options.onProgress,
@@ -118249,9 +91211,9 @@ class BlobBatchClient {
return tracingClient.withSpan("BlobBatchClient-submitBatch", options, async (updatedOptions) => {
const batchRequestBody = batchRequest.getHttpRequestBody();
// ServiceSubmitBatchResponseModel and ContainerSubmitBatchResponse are compatible for now.
- const rawBatchResponse = utils_common_assertResponse(await this.serviceOrContainerContext.submitBatch(utf8ByteLength(batchRequestBody), batchRequest.getMultiPartContentType(), batchRequestBody, {
+ const rawBatchResponse = utils_common_assertResponse((await this.serviceOrContainerContext.submitBatch(utf8ByteLength(batchRequestBody), batchRequest.getMultiPartContentType(), batchRequestBody, {
...updatedOptions,
- }));
+ })));
// Parse the sub responses result, if logic reaches here(i.e. the batch request succeeded with status code 202).
const batchResponseParser = new BatchResponseParser(rawBatchResponse, batchRequest.getSubRequests());
const responseSummary = await batchResponseParser.parseBatchResponse();
@@ -120831,7 +93793,7 @@ NetworkError.isNetworkErrorCode = (code) => {
};
class UsageError extends Error {
constructor() {
- const message = `Cache storage quota has been hit. Unable to upload any new cache entries. Usage is recalculated every 6-12 hours.\nMore info on storage limits: https://docs.github.com/en/billing/managing-billing-for-github-actions/about-billing-for-github-actions#calculating-minute-and-storage-spending`;
+ const message = `Cache storage quota has been hit. Unable to upload any new cache entries.\nMore info on storage limits: https://docs.github.com/en/billing/managing-billing-for-github-actions/about-billing-for-github-actions#calculating-minute-and-storage-spending`;
super(message);
this.name = 'UsageError';
}
@@ -123423,8 +96385,6 @@ class Context {
//# sourceMappingURL=context.js.map
// EXTERNAL MODULE: ./node_modules/@actions/github/node_modules/@actions/http-client/lib/index.js
var lib = __nccwpck_require__(9659);
-// EXTERNAL MODULE: ./node_modules/@actions/github/node_modules/undici/index.js
-var node_modules_undici = __nccwpck_require__(9231);
;// CONCATENATED MODULE: ./node_modules/@actions/github/lib/internal/utils.js
var utils_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
@@ -123457,13 +96417,26 @@ function getProxyAgentDispatcher(destinationUrl) {
function getProxyFetch(destinationUrl) {
const httpDispatcher = getProxyAgentDispatcher(destinationUrl);
const proxyFetch = (url, opts) => utils_awaiter(this, void 0, void 0, function* () {
- return (0,node_modules_undici.fetch)(url, Object.assign(Object.assign({}, opts), { dispatcher: httpDispatcher }));
+ return (0,undici.fetch)(url, Object.assign(Object.assign({}, opts), { dispatcher: httpDispatcher }));
});
return proxyFetch;
}
function getApiBaseUrl() {
return process.env['GITHUB_API_URL'] || 'https://api.github.com';
}
+function getUserAgentWithOrchestrationId(baseUserAgent) {
+ var _a;
+ const orchId = (_a = process.env['ACTIONS_ORCHESTRATION_ID']) === null || _a === void 0 ? void 0 : _a.trim();
+ if (orchId) {
+ const sanitizedId = orchId.replace(/[^a-z0-9_.-]/gi, '_');
+ const tag = `actions_orchestration_id/${sanitizedId}`;
+ if (baseUserAgent === null || baseUserAgent === void 0 ? void 0 : baseUserAgent.includes(tag))
+ return baseUserAgent;
+ const ua = baseUserAgent ? `${baseUserAgent} ` : '';
+ return `${ua}${tag}`;
+ }
+ return baseUserAgent;
+}
//# sourceMappingURL=utils.js.map
;// CONCATENATED MODULE: ./node_modules/universal-user-agent/index.js
function getUserAgent() {
@@ -126820,635 +99793,4027 @@ const Endpoints = {
{},
{ renamed: ["users", "listPublicSshKeysForAuthenticatedUser"] }
],
- listPublicSshKeysForAuthenticatedUser: ["GET /user/keys"],
- listSocialAccountsForAuthenticatedUser: ["GET /user/social_accounts"],
- listSocialAccountsForUser: ["GET /users/{username}/social_accounts"],
- listSshSigningKeysForAuthenticatedUser: ["GET /user/ssh_signing_keys"],
- listSshSigningKeysForUser: ["GET /users/{username}/ssh_signing_keys"],
- setPrimaryEmailVisibilityForAuthenticated: [
- "PATCH /user/email/visibility",
- {},
- { renamed: ["users", "setPrimaryEmailVisibilityForAuthenticatedUser"] }
+ listPublicSshKeysForAuthenticatedUser: ["GET /user/keys"],
+ listSocialAccountsForAuthenticatedUser: ["GET /user/social_accounts"],
+ listSocialAccountsForUser: ["GET /users/{username}/social_accounts"],
+ listSshSigningKeysForAuthenticatedUser: ["GET /user/ssh_signing_keys"],
+ listSshSigningKeysForUser: ["GET /users/{username}/ssh_signing_keys"],
+ setPrimaryEmailVisibilityForAuthenticated: [
+ "PATCH /user/email/visibility",
+ {},
+ { renamed: ["users", "setPrimaryEmailVisibilityForAuthenticatedUser"] }
+ ],
+ setPrimaryEmailVisibilityForAuthenticatedUser: [
+ "PATCH /user/email/visibility"
+ ],
+ unblock: ["DELETE /user/blocks/{username}"],
+ unfollow: ["DELETE /user/following/{username}"],
+ updateAuthenticated: ["PATCH /user"]
+ }
+};
+var endpoints_default = Endpoints;
+
+//# sourceMappingURL=endpoints.js.map
+
+;// CONCATENATED MODULE: ./node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/endpoints-to-methods.js
+
+const endpointMethodsMap = /* @__PURE__ */ new Map();
+for (const [scope, endpoints] of Object.entries(endpoints_default)) {
+ for (const [methodName, endpoint] of Object.entries(endpoints)) {
+ const [route, defaults, decorations] = endpoint;
+ const [method, url] = route.split(/ /);
+ const endpointDefaults = Object.assign(
+ {
+ method,
+ url
+ },
+ defaults
+ );
+ if (!endpointMethodsMap.has(scope)) {
+ endpointMethodsMap.set(scope, /* @__PURE__ */ new Map());
+ }
+ endpointMethodsMap.get(scope).set(methodName, {
+ scope,
+ methodName,
+ endpointDefaults,
+ decorations
+ });
+ }
+}
+const handler = {
+ has({ scope }, methodName) {
+ return endpointMethodsMap.get(scope).has(methodName);
+ },
+ getOwnPropertyDescriptor(target, methodName) {
+ return {
+ value: this.get(target, methodName),
+ // ensures method is in the cache
+ configurable: true,
+ writable: true,
+ enumerable: true
+ };
+ },
+ defineProperty(target, methodName, descriptor) {
+ Object.defineProperty(target.cache, methodName, descriptor);
+ return true;
+ },
+ deleteProperty(target, methodName) {
+ delete target.cache[methodName];
+ return true;
+ },
+ ownKeys({ scope }) {
+ return [...endpointMethodsMap.get(scope).keys()];
+ },
+ set(target, methodName, value) {
+ return target.cache[methodName] = value;
+ },
+ get({ octokit, scope, cache }, methodName) {
+ if (cache[methodName]) {
+ return cache[methodName];
+ }
+ const method = endpointMethodsMap.get(scope).get(methodName);
+ if (!method) {
+ return void 0;
+ }
+ const { endpointDefaults, decorations } = method;
+ if (decorations) {
+ cache[methodName] = decorate(
+ octokit,
+ scope,
+ methodName,
+ endpointDefaults,
+ decorations
+ );
+ } else {
+ cache[methodName] = octokit.request.defaults(endpointDefaults);
+ }
+ return cache[methodName];
+ }
+};
+function endpointsToMethods(octokit) {
+ const newMethods = {};
+ for (const scope of endpointMethodsMap.keys()) {
+ newMethods[scope] = new Proxy({ octokit, scope, cache: {} }, handler);
+ }
+ return newMethods;
+}
+function decorate(octokit, scope, methodName, defaults, decorations) {
+ const requestWithDefaults = octokit.request.defaults(defaults);
+ function withDecorations(...args) {
+ let options = requestWithDefaults.endpoint.merge(...args);
+ if (decorations.mapToData) {
+ options = Object.assign({}, options, {
+ data: options[decorations.mapToData],
+ [decorations.mapToData]: void 0
+ });
+ return requestWithDefaults(options);
+ }
+ if (decorations.renamed) {
+ const [newScope, newMethodName] = decorations.renamed;
+ octokit.log.warn(
+ `octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()`
+ );
+ }
+ if (decorations.deprecated) {
+ octokit.log.warn(decorations.deprecated);
+ }
+ if (decorations.renamedParameters) {
+ const options2 = requestWithDefaults.endpoint.merge(...args);
+ for (const [name, alias] of Object.entries(
+ decorations.renamedParameters
+ )) {
+ if (name in options2) {
+ octokit.log.warn(
+ `"${name}" parameter is deprecated for "octokit.${scope}.${methodName}()". Use "${alias}" instead`
+ );
+ if (!(alias in options2)) {
+ options2[alias] = options2[name];
+ }
+ delete options2[name];
+ }
+ }
+ return requestWithDefaults(options2);
+ }
+ return requestWithDefaults(...args);
+ }
+ return Object.assign(withDecorations, requestWithDefaults);
+}
+
+//# sourceMappingURL=endpoints-to-methods.js.map
+
+;// CONCATENATED MODULE: ./node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/index.js
+
+
+function restEndpointMethods(octokit) {
+ const api = endpointsToMethods(octokit);
+ return {
+ rest: api
+ };
+}
+restEndpointMethods.VERSION = dist_src_version_VERSION;
+function legacyRestEndpointMethods(octokit) {
+ const api = endpointsToMethods(octokit);
+ return {
+ ...api,
+ rest: api
+ };
+}
+legacyRestEndpointMethods.VERSION = dist_src_version_VERSION;
+
+//# sourceMappingURL=index.js.map
+
+;// CONCATENATED MODULE: ./node_modules/@octokit/plugin-paginate-rest/dist-bundle/index.js
+// pkg/dist-src/version.js
+var plugin_paginate_rest_dist_bundle_VERSION = "0.0.0-development";
+
+// pkg/dist-src/normalize-paginated-list-response.js
+function normalizePaginatedListResponse(response) {
+ if (!response.data) {
+ return {
+ ...response,
+ data: []
+ };
+ }
+ const responseNeedsNormalization = ("total_count" in response.data || "total_commits" in response.data) && !("url" in response.data);
+ if (!responseNeedsNormalization) return response;
+ const incompleteResults = response.data.incomplete_results;
+ const repositorySelection = response.data.repository_selection;
+ const totalCount = response.data.total_count;
+ const totalCommits = response.data.total_commits;
+ delete response.data.incomplete_results;
+ delete response.data.repository_selection;
+ delete response.data.total_count;
+ delete response.data.total_commits;
+ const namespaceKey = Object.keys(response.data)[0];
+ const data = response.data[namespaceKey];
+ response.data = data;
+ if (typeof incompleteResults !== "undefined") {
+ response.data.incomplete_results = incompleteResults;
+ }
+ if (typeof repositorySelection !== "undefined") {
+ response.data.repository_selection = repositorySelection;
+ }
+ response.data.total_count = totalCount;
+ response.data.total_commits = totalCommits;
+ return response;
+}
+
+// pkg/dist-src/iterator.js
+function iterator(octokit, route, parameters) {
+ const options = typeof route === "function" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters);
+ const requestMethod = typeof route === "function" ? route : octokit.request;
+ const method = options.method;
+ const headers = options.headers;
+ let url = options.url;
+ return {
+ [Symbol.asyncIterator]: () => ({
+ async next() {
+ if (!url) return { done: true };
+ try {
+ const response = await requestMethod({ method, url, headers });
+ const normalizedResponse = normalizePaginatedListResponse(response);
+ url = ((normalizedResponse.headers.link || "").match(
+ /<([^<>]+)>;\s*rel="next"/
+ ) || [])[1];
+ if (!url && "total_commits" in normalizedResponse.data) {
+ const parsedUrl = new URL(normalizedResponse.url);
+ const params = parsedUrl.searchParams;
+ const page = parseInt(params.get("page") || "1", 10);
+ const per_page = parseInt(params.get("per_page") || "250", 10);
+ if (page * per_page < normalizedResponse.data.total_commits) {
+ params.set("page", String(page + 1));
+ url = parsedUrl.toString();
+ }
+ }
+ return { value: normalizedResponse };
+ } catch (error) {
+ if (error.status !== 409) throw error;
+ url = "";
+ return {
+ value: {
+ status: 200,
+ headers: {},
+ data: []
+ }
+ };
+ }
+ }
+ })
+ };
+}
+
+// pkg/dist-src/paginate.js
+function paginate(octokit, route, parameters, mapFn) {
+ if (typeof parameters === "function") {
+ mapFn = parameters;
+ parameters = void 0;
+ }
+ return gather(
+ octokit,
+ [],
+ iterator(octokit, route, parameters)[Symbol.asyncIterator](),
+ mapFn
+ );
+}
+function gather(octokit, results, iterator2, mapFn) {
+ return iterator2.next().then((result) => {
+ if (result.done) {
+ return results;
+ }
+ let earlyExit = false;
+ function done() {
+ earlyExit = true;
+ }
+ results = results.concat(
+ mapFn ? mapFn(result.value, done) : result.value.data
+ );
+ if (earlyExit) {
+ return results;
+ }
+ return gather(octokit, results, iterator2, mapFn);
+ });
+}
+
+// pkg/dist-src/compose-paginate.js
+var composePaginateRest = Object.assign(paginate, {
+ iterator
+});
+
+// pkg/dist-src/generated/paginating-endpoints.js
+var paginatingEndpoints = (/* unused pure expression or super */ null && ([
+ "GET /advisories",
+ "GET /app/hook/deliveries",
+ "GET /app/installation-requests",
+ "GET /app/installations",
+ "GET /assignments/{assignment_id}/accepted_assignments",
+ "GET /classrooms",
+ "GET /classrooms/{classroom_id}/assignments",
+ "GET /enterprises/{enterprise}/code-security/configurations",
+ "GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}/repositories",
+ "GET /enterprises/{enterprise}/dependabot/alerts",
+ "GET /enterprises/{enterprise}/teams",
+ "GET /enterprises/{enterprise}/teams/{enterprise-team}/memberships",
+ "GET /enterprises/{enterprise}/teams/{enterprise-team}/organizations",
+ "GET /events",
+ "GET /gists",
+ "GET /gists/public",
+ "GET /gists/starred",
+ "GET /gists/{gist_id}/comments",
+ "GET /gists/{gist_id}/commits",
+ "GET /gists/{gist_id}/forks",
+ "GET /installation/repositories",
+ "GET /issues",
+ "GET /licenses",
+ "GET /marketplace_listing/plans",
+ "GET /marketplace_listing/plans/{plan_id}/accounts",
+ "GET /marketplace_listing/stubbed/plans",
+ "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts",
+ "GET /networks/{owner}/{repo}/events",
+ "GET /notifications",
+ "GET /organizations",
+ "GET /organizations/{org}/dependabot/repository-access",
+ "GET /orgs/{org}/actions/cache/usage-by-repository",
+ "GET /orgs/{org}/actions/hosted-runners",
+ "GET /orgs/{org}/actions/permissions/repositories",
+ "GET /orgs/{org}/actions/permissions/self-hosted-runners/repositories",
+ "GET /orgs/{org}/actions/runner-groups",
+ "GET /orgs/{org}/actions/runner-groups/{runner_group_id}/hosted-runners",
+ "GET /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories",
+ "GET /orgs/{org}/actions/runner-groups/{runner_group_id}/runners",
+ "GET /orgs/{org}/actions/runners",
+ "GET /orgs/{org}/actions/secrets",
+ "GET /orgs/{org}/actions/secrets/{secret_name}/repositories",
+ "GET /orgs/{org}/actions/variables",
+ "GET /orgs/{org}/actions/variables/{name}/repositories",
+ "GET /orgs/{org}/attestations/repositories",
+ "GET /orgs/{org}/attestations/{subject_digest}",
+ "GET /orgs/{org}/blocks",
+ "GET /orgs/{org}/campaigns",
+ "GET /orgs/{org}/code-scanning/alerts",
+ "GET /orgs/{org}/code-security/configurations",
+ "GET /orgs/{org}/code-security/configurations/{configuration_id}/repositories",
+ "GET /orgs/{org}/codespaces",
+ "GET /orgs/{org}/codespaces/secrets",
+ "GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories",
+ "GET /orgs/{org}/copilot/billing/seats",
+ "GET /orgs/{org}/copilot/metrics",
+ "GET /orgs/{org}/dependabot/alerts",
+ "GET /orgs/{org}/dependabot/secrets",
+ "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories",
+ "GET /orgs/{org}/events",
+ "GET /orgs/{org}/failed_invitations",
+ "GET /orgs/{org}/hooks",
+ "GET /orgs/{org}/hooks/{hook_id}/deliveries",
+ "GET /orgs/{org}/insights/api/route-stats/{actor_type}/{actor_id}",
+ "GET /orgs/{org}/insights/api/subject-stats",
+ "GET /orgs/{org}/insights/api/user-stats/{user_id}",
+ "GET /orgs/{org}/installations",
+ "GET /orgs/{org}/invitations",
+ "GET /orgs/{org}/invitations/{invitation_id}/teams",
+ "GET /orgs/{org}/issues",
+ "GET /orgs/{org}/members",
+ "GET /orgs/{org}/members/{username}/codespaces",
+ "GET /orgs/{org}/migrations",
+ "GET /orgs/{org}/migrations/{migration_id}/repositories",
+ "GET /orgs/{org}/organization-roles/{role_id}/teams",
+ "GET /orgs/{org}/organization-roles/{role_id}/users",
+ "GET /orgs/{org}/outside_collaborators",
+ "GET /orgs/{org}/packages",
+ "GET /orgs/{org}/packages/{package_type}/{package_name}/versions",
+ "GET /orgs/{org}/personal-access-token-requests",
+ "GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories",
+ "GET /orgs/{org}/personal-access-tokens",
+ "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories",
+ "GET /orgs/{org}/private-registries",
+ "GET /orgs/{org}/projects",
+ "GET /orgs/{org}/projectsV2",
+ "GET /orgs/{org}/projectsV2/{project_number}/fields",
+ "GET /orgs/{org}/projectsV2/{project_number}/items",
+ "GET /orgs/{org}/properties/values",
+ "GET /orgs/{org}/public_members",
+ "GET /orgs/{org}/repos",
+ "GET /orgs/{org}/rulesets",
+ "GET /orgs/{org}/rulesets/rule-suites",
+ "GET /orgs/{org}/rulesets/{ruleset_id}/history",
+ "GET /orgs/{org}/secret-scanning/alerts",
+ "GET /orgs/{org}/security-advisories",
+ "GET /orgs/{org}/settings/immutable-releases/repositories",
+ "GET /orgs/{org}/settings/network-configurations",
+ "GET /orgs/{org}/team/{team_slug}/copilot/metrics",
+ "GET /orgs/{org}/teams",
+ "GET /orgs/{org}/teams/{team_slug}/discussions",
+ "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments",
+ "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions",
+ "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions",
+ "GET /orgs/{org}/teams/{team_slug}/invitations",
+ "GET /orgs/{org}/teams/{team_slug}/members",
+ "GET /orgs/{org}/teams/{team_slug}/projects",
+ "GET /orgs/{org}/teams/{team_slug}/repos",
+ "GET /orgs/{org}/teams/{team_slug}/teams",
+ "GET /projects/{project_id}/collaborators",
+ "GET /repos/{owner}/{repo}/actions/artifacts",
+ "GET /repos/{owner}/{repo}/actions/caches",
+ "GET /repos/{owner}/{repo}/actions/organization-secrets",
+ "GET /repos/{owner}/{repo}/actions/organization-variables",
+ "GET /repos/{owner}/{repo}/actions/runners",
+ "GET /repos/{owner}/{repo}/actions/runs",
+ "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts",
+ "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs",
+ "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs",
+ "GET /repos/{owner}/{repo}/actions/secrets",
+ "GET /repos/{owner}/{repo}/actions/variables",
+ "GET /repos/{owner}/{repo}/actions/workflows",
+ "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs",
+ "GET /repos/{owner}/{repo}/activity",
+ "GET /repos/{owner}/{repo}/assignees",
+ "GET /repos/{owner}/{repo}/attestations/{subject_digest}",
+ "GET /repos/{owner}/{repo}/branches",
+ "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations",
+ "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs",
+ "GET /repos/{owner}/{repo}/code-scanning/alerts",
+ "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances",
+ "GET /repos/{owner}/{repo}/code-scanning/analyses",
+ "GET /repos/{owner}/{repo}/codespaces",
+ "GET /repos/{owner}/{repo}/codespaces/devcontainers",
+ "GET /repos/{owner}/{repo}/codespaces/secrets",
+ "GET /repos/{owner}/{repo}/collaborators",
+ "GET /repos/{owner}/{repo}/comments",
+ "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions",
+ "GET /repos/{owner}/{repo}/commits",
+ "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments",
+ "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls",
+ "GET /repos/{owner}/{repo}/commits/{ref}/check-runs",
+ "GET /repos/{owner}/{repo}/commits/{ref}/check-suites",
+ "GET /repos/{owner}/{repo}/commits/{ref}/status",
+ "GET /repos/{owner}/{repo}/commits/{ref}/statuses",
+ "GET /repos/{owner}/{repo}/compare/{basehead}",
+ "GET /repos/{owner}/{repo}/compare/{base}...{head}",
+ "GET /repos/{owner}/{repo}/contributors",
+ "GET /repos/{owner}/{repo}/dependabot/alerts",
+ "GET /repos/{owner}/{repo}/dependabot/secrets",
+ "GET /repos/{owner}/{repo}/deployments",
+ "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses",
+ "GET /repos/{owner}/{repo}/environments",
+ "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies",
+ "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps",
+ "GET /repos/{owner}/{repo}/environments/{environment_name}/secrets",
+ "GET /repos/{owner}/{repo}/environments/{environment_name}/variables",
+ "GET /repos/{owner}/{repo}/events",
+ "GET /repos/{owner}/{repo}/forks",
+ "GET /repos/{owner}/{repo}/hooks",
+ "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries",
+ "GET /repos/{owner}/{repo}/invitations",
+ "GET /repos/{owner}/{repo}/issues",
+ "GET /repos/{owner}/{repo}/issues/comments",
+ "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions",
+ "GET /repos/{owner}/{repo}/issues/events",
+ "GET /repos/{owner}/{repo}/issues/{issue_number}/comments",
+ "GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by",
+ "GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocking",
+ "GET /repos/{owner}/{repo}/issues/{issue_number}/events",
+ "GET /repos/{owner}/{repo}/issues/{issue_number}/labels",
+ "GET /repos/{owner}/{repo}/issues/{issue_number}/reactions",
+ "GET /repos/{owner}/{repo}/issues/{issue_number}/sub_issues",
+ "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline",
+ "GET /repos/{owner}/{repo}/keys",
+ "GET /repos/{owner}/{repo}/labels",
+ "GET /repos/{owner}/{repo}/milestones",
+ "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels",
+ "GET /repos/{owner}/{repo}/notifications",
+ "GET /repos/{owner}/{repo}/pages/builds",
+ "GET /repos/{owner}/{repo}/projects",
+ "GET /repos/{owner}/{repo}/pulls",
+ "GET /repos/{owner}/{repo}/pulls/comments",
+ "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions",
+ "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments",
+ "GET /repos/{owner}/{repo}/pulls/{pull_number}/commits",
+ "GET /repos/{owner}/{repo}/pulls/{pull_number}/files",
+ "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews",
+ "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments",
+ "GET /repos/{owner}/{repo}/releases",
+ "GET /repos/{owner}/{repo}/releases/{release_id}/assets",
+ "GET /repos/{owner}/{repo}/releases/{release_id}/reactions",
+ "GET /repos/{owner}/{repo}/rules/branches/{branch}",
+ "GET /repos/{owner}/{repo}/rulesets",
+ "GET /repos/{owner}/{repo}/rulesets/rule-suites",
+ "GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history",
+ "GET /repos/{owner}/{repo}/secret-scanning/alerts",
+ "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations",
+ "GET /repos/{owner}/{repo}/security-advisories",
+ "GET /repos/{owner}/{repo}/stargazers",
+ "GET /repos/{owner}/{repo}/subscribers",
+ "GET /repos/{owner}/{repo}/tags",
+ "GET /repos/{owner}/{repo}/teams",
+ "GET /repos/{owner}/{repo}/topics",
+ "GET /repositories",
+ "GET /search/code",
+ "GET /search/commits",
+ "GET /search/issues",
+ "GET /search/labels",
+ "GET /search/repositories",
+ "GET /search/topics",
+ "GET /search/users",
+ "GET /teams/{team_id}/discussions",
+ "GET /teams/{team_id}/discussions/{discussion_number}/comments",
+ "GET /teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions",
+ "GET /teams/{team_id}/discussions/{discussion_number}/reactions",
+ "GET /teams/{team_id}/invitations",
+ "GET /teams/{team_id}/members",
+ "GET /teams/{team_id}/projects",
+ "GET /teams/{team_id}/repos",
+ "GET /teams/{team_id}/teams",
+ "GET /user/blocks",
+ "GET /user/codespaces",
+ "GET /user/codespaces/secrets",
+ "GET /user/emails",
+ "GET /user/followers",
+ "GET /user/following",
+ "GET /user/gpg_keys",
+ "GET /user/installations",
+ "GET /user/installations/{installation_id}/repositories",
+ "GET /user/issues",
+ "GET /user/keys",
+ "GET /user/marketplace_purchases",
+ "GET /user/marketplace_purchases/stubbed",
+ "GET /user/memberships/orgs",
+ "GET /user/migrations",
+ "GET /user/migrations/{migration_id}/repositories",
+ "GET /user/orgs",
+ "GET /user/packages",
+ "GET /user/packages/{package_type}/{package_name}/versions",
+ "GET /user/public_emails",
+ "GET /user/repos",
+ "GET /user/repository_invitations",
+ "GET /user/social_accounts",
+ "GET /user/ssh_signing_keys",
+ "GET /user/starred",
+ "GET /user/subscriptions",
+ "GET /user/teams",
+ "GET /users",
+ "GET /users/{username}/attestations/{subject_digest}",
+ "GET /users/{username}/events",
+ "GET /users/{username}/events/orgs/{org}",
+ "GET /users/{username}/events/public",
+ "GET /users/{username}/followers",
+ "GET /users/{username}/following",
+ "GET /users/{username}/gists",
+ "GET /users/{username}/gpg_keys",
+ "GET /users/{username}/keys",
+ "GET /users/{username}/orgs",
+ "GET /users/{username}/packages",
+ "GET /users/{username}/projects",
+ "GET /users/{username}/projectsV2",
+ "GET /users/{username}/projectsV2/{project_number}/fields",
+ "GET /users/{username}/projectsV2/{project_number}/items",
+ "GET /users/{username}/received_events",
+ "GET /users/{username}/received_events/public",
+ "GET /users/{username}/repos",
+ "GET /users/{username}/social_accounts",
+ "GET /users/{username}/ssh_signing_keys",
+ "GET /users/{username}/starred",
+ "GET /users/{username}/subscriptions"
+]));
+
+// pkg/dist-src/paginating-endpoints.js
+function isPaginatingEndpoint(arg) {
+ if (typeof arg === "string") {
+ return paginatingEndpoints.includes(arg);
+ } else {
+ return false;
+ }
+}
+
+// pkg/dist-src/index.js
+function paginateRest(octokit) {
+ return {
+ paginate: Object.assign(paginate.bind(null, octokit), {
+ iterator: iterator.bind(null, octokit)
+ })
+ };
+}
+paginateRest.VERSION = plugin_paginate_rest_dist_bundle_VERSION;
+
+
+;// CONCATENATED MODULE: ./node_modules/@actions/github/lib/utils.js
+
+
+// octokit + plugins
+
+
+
+const utils_context = new Context();
+const baseUrl = getApiBaseUrl();
+const defaults = {
+ baseUrl,
+ request: {
+ agent: getProxyAgent(baseUrl),
+ fetch: getProxyFetch(baseUrl)
+ }
+};
+const GitHub = Octokit.plugin(restEndpointMethods, paginateRest).defaults(defaults);
+
+/**
+ * Convience function to correctly format Octokit Options to pass into the constructor.
+ *
+ * @param token the repo PAT or GITHUB_TOKEN
+ * @param options other options to set
+ */
+function getOctokitOptions(token, options) {
+ const opts = Object.assign({}, options || {}); // Shallow clone - don't mutate the object provided by the caller
+ // Auth
+ const auth = getAuthString(token, opts);
+ if (auth) {
+ opts.auth = auth;
+ }
+ // Orchestration ID
+ const userAgent = getUserAgentWithOrchestrationId(opts.userAgent);
+ if (userAgent) {
+ opts.userAgent = userAgent;
+ }
+ return opts;
+}
+//# sourceMappingURL=utils.js.map
+;// CONCATENATED MODULE: ./node_modules/@actions/github/lib/github.js
+
+
+const github_context = new Context();
+/**
+ * Returns a hydrated octokit ready to use for GitHub Actions
+ *
+ * @param token the repo PAT or GITHUB_TOKEN
+ * @param options other options to set
+ */
+function getOctokit(token, options, ...additionalPlugins) {
+ const GitHubWithPlugins = GitHub.plugin(...additionalPlugins);
+ return new GitHubWithPlugins(getOctokitOptions(token, options));
+}
+//# sourceMappingURL=github.js.map
+;// CONCATENATED MODULE: ./node_modules/@actions/glob/lib/internal-glob-options-helper.js
+
+/**
+ * Returns a copy with defaults filled in.
+ */
+function internal_glob_options_helper_getOptions(copy) {
+ const result = {
+ followSymbolicLinks: true,
+ implicitDescendants: true,
+ matchDirectories: true,
+ omitBrokenSymbolicLinks: true,
+ excludeHiddenFiles: false
+ };
+ if (copy) {
+ if (typeof copy.followSymbolicLinks === 'boolean') {
+ result.followSymbolicLinks = copy.followSymbolicLinks;
+ core_debug(`followSymbolicLinks '${result.followSymbolicLinks}'`);
+ }
+ if (typeof copy.implicitDescendants === 'boolean') {
+ result.implicitDescendants = copy.implicitDescendants;
+ core_debug(`implicitDescendants '${result.implicitDescendants}'`);
+ }
+ if (typeof copy.matchDirectories === 'boolean') {
+ result.matchDirectories = copy.matchDirectories;
+ core_debug(`matchDirectories '${result.matchDirectories}'`);
+ }
+ if (typeof copy.omitBrokenSymbolicLinks === 'boolean') {
+ result.omitBrokenSymbolicLinks = copy.omitBrokenSymbolicLinks;
+ core_debug(`omitBrokenSymbolicLinks '${result.omitBrokenSymbolicLinks}'`);
+ }
+ if (typeof copy.excludeHiddenFiles === 'boolean') {
+ result.excludeHiddenFiles = copy.excludeHiddenFiles;
+ core_debug(`excludeHiddenFiles '${result.excludeHiddenFiles}'`);
+ }
+ }
+ return result;
+}
+//# sourceMappingURL=internal-glob-options-helper.js.map
+;// CONCATENATED MODULE: ./node_modules/@actions/glob/lib/internal-path-helper.js
+
+
+const lib_internal_path_helper_IS_WINDOWS = process.platform === 'win32';
+/**
+ * Similar to path.dirname except normalizes the path separators and slightly better handling for Windows UNC paths.
+ *
+ * For example, on Linux/macOS:
+ * - `/ => /`
+ * - `/hello => /`
+ *
+ * For example, on Windows:
+ * - `C:\ => C:\`
+ * - `C:\hello => C:\`
+ * - `C: => C:`
+ * - `C:hello => C:`
+ * - `\ => \`
+ * - `\hello => \`
+ * - `\\hello => \\hello`
+ * - `\\hello\world => \\hello\world`
+ */
+function internal_path_helper_dirname(p) {
+ // Normalize slashes and trim unnecessary trailing slash
+ p = internal_path_helper_safeTrimTrailingSeparator(p);
+ // Windows UNC root, e.g. \\hello or \\hello\world
+ if (lib_internal_path_helper_IS_WINDOWS && /^\\\\[^\\]+(\\[^\\]+)?$/.test(p)) {
+ return p;
+ }
+ // Get dirname
+ let result = external_path_.dirname(p);
+ // Trim trailing slash for Windows UNC root, e.g. \\hello\world\
+ if (lib_internal_path_helper_IS_WINDOWS && /^\\\\[^\\]+\\[^\\]+\\$/.test(result)) {
+ result = internal_path_helper_safeTrimTrailingSeparator(result);
+ }
+ return result;
+}
+/**
+ * Roots the path if not already rooted. On Windows, relative roots like `\`
+ * or `C:` are expanded based on the current working directory.
+ */
+function internal_path_helper_ensureAbsoluteRoot(root, itemPath) {
+ external_assert_(root, `ensureAbsoluteRoot parameter 'root' must not be empty`);
+ external_assert_(itemPath, `ensureAbsoluteRoot parameter 'itemPath' must not be empty`);
+ // Already rooted
+ if (internal_path_helper_hasAbsoluteRoot(itemPath)) {
+ return itemPath;
+ }
+ // Windows
+ if (lib_internal_path_helper_IS_WINDOWS) {
+ // Check for itemPath like C: or C:foo
+ if (itemPath.match(/^[A-Z]:[^\\/]|^[A-Z]:$/i)) {
+ let cwd = process.cwd();
+ external_assert_(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`);
+ // Drive letter matches cwd? Expand to cwd
+ if (itemPath[0].toUpperCase() === cwd[0].toUpperCase()) {
+ // Drive only, e.g. C:
+ if (itemPath.length === 2) {
+ // Preserve specified drive letter case (upper or lower)
+ return `${itemPath[0]}:\\${cwd.substr(3)}`;
+ }
+ // Drive + path, e.g. C:foo
+ else {
+ if (!cwd.endsWith('\\')) {
+ cwd += '\\';
+ }
+ // Preserve specified drive letter case (upper or lower)
+ return `${itemPath[0]}:\\${cwd.substr(3)}${itemPath.substr(2)}`;
+ }
+ }
+ // Different drive
+ else {
+ return `${itemPath[0]}:\\${itemPath.substr(2)}`;
+ }
+ }
+ // Check for itemPath like \ or \foo
+ else if (lib_internal_path_helper_normalizeSeparators(itemPath).match(/^\\$|^\\[^\\]/)) {
+ const cwd = process.cwd();
+ external_assert_(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`);
+ return `${cwd[0]}:\\${itemPath.substr(1)}`;
+ }
+ }
+ external_assert_(internal_path_helper_hasAbsoluteRoot(root), `ensureAbsoluteRoot parameter 'root' must have an absolute root`);
+ // Otherwise ensure root ends with a separator
+ if (root.endsWith('/') || (lib_internal_path_helper_IS_WINDOWS && root.endsWith('\\'))) {
+ // Intentionally empty
+ }
+ else {
+ // Append separator
+ root += external_path_.sep;
+ }
+ return root + itemPath;
+}
+/**
+ * On Linux/macOS, true if path starts with `/`. On Windows, true for paths like:
+ * `\\hello\share` and `C:\hello` (and using alternate separator).
+ */
+function internal_path_helper_hasAbsoluteRoot(itemPath) {
+ external_assert_(itemPath, `hasAbsoluteRoot parameter 'itemPath' must not be empty`);
+ // Normalize separators
+ itemPath = lib_internal_path_helper_normalizeSeparators(itemPath);
+ // Windows
+ if (lib_internal_path_helper_IS_WINDOWS) {
+ // E.g. \\hello\share or C:\hello
+ return itemPath.startsWith('\\\\') || /^[A-Z]:\\/i.test(itemPath);
+ }
+ // E.g. /hello
+ return itemPath.startsWith('/');
+}
+/**
+ * On Linux/macOS, true if path starts with `/`. On Windows, true for paths like:
+ * `\`, `\hello`, `\\hello\share`, `C:`, and `C:\hello` (and using alternate separator).
+ */
+function internal_path_helper_hasRoot(itemPath) {
+ external_assert_(itemPath, `isRooted parameter 'itemPath' must not be empty`);
+ // Normalize separators
+ itemPath = lib_internal_path_helper_normalizeSeparators(itemPath);
+ // Windows
+ if (lib_internal_path_helper_IS_WINDOWS) {
+ // E.g. \ or \hello or \\hello
+ // E.g. C: or C:\hello
+ return itemPath.startsWith('\\') || /^[A-Z]:/i.test(itemPath);
+ }
+ // E.g. /hello
+ return itemPath.startsWith('/');
+}
+/**
+ * Removes redundant slashes and converts `/` to `\` on Windows
+ */
+function lib_internal_path_helper_normalizeSeparators(p) {
+ p = p || '';
+ // Windows
+ if (lib_internal_path_helper_IS_WINDOWS) {
+ // Convert slashes on Windows
+ p = p.replace(/\//g, '\\');
+ // Remove redundant slashes
+ const isUnc = /^\\\\+[^\\]/.test(p); // e.g. \\hello
+ return (isUnc ? '\\' : '') + p.replace(/\\\\+/g, '\\'); // preserve leading \\ for UNC
+ }
+ // Remove redundant slashes
+ return p.replace(/\/\/+/g, '/');
+}
+/**
+ * Normalizes the path separators and trims the trailing separator (when safe).
+ * For example, `/foo/ => /foo` but `/ => /`
+ */
+function internal_path_helper_safeTrimTrailingSeparator(p) {
+ // Short-circuit if empty
+ if (!p) {
+ return '';
+ }
+ // Normalize separators
+ p = lib_internal_path_helper_normalizeSeparators(p);
+ // No trailing slash
+ if (!p.endsWith(external_path_.sep)) {
+ return p;
+ }
+ // Check '/' on Linux/macOS and '\' on Windows
+ if (p === external_path_.sep) {
+ return p;
+ }
+ // On Windows check if drive root. E.g. C:\
+ if (lib_internal_path_helper_IS_WINDOWS && /^[A-Z]:\\$/i.test(p)) {
+ return p;
+ }
+ // Otherwise trim trailing slash
+ return p.substr(0, p.length - 1);
+}
+//# sourceMappingURL=internal-path-helper.js.map
+;// CONCATENATED MODULE: ./node_modules/@actions/glob/lib/internal-match-kind.js
+/**
+ * Indicates whether a pattern matches a path
+ */
+var lib_internal_match_kind_MatchKind;
+(function (MatchKind) {
+ /** Not matched */
+ MatchKind[MatchKind["None"] = 0] = "None";
+ /** Matched if the path is a directory */
+ MatchKind[MatchKind["Directory"] = 1] = "Directory";
+ /** Matched if the path is a regular file */
+ MatchKind[MatchKind["File"] = 2] = "File";
+ /** Matched */
+ MatchKind[MatchKind["All"] = 3] = "All";
+})(lib_internal_match_kind_MatchKind || (lib_internal_match_kind_MatchKind = {}));
+//# sourceMappingURL=internal-match-kind.js.map
+;// CONCATENATED MODULE: ./node_modules/@actions/glob/lib/internal-pattern-helper.js
+
+
+const lib_internal_pattern_helper_IS_WINDOWS = process.platform === 'win32';
+/**
+ * Given an array of patterns, returns an array of paths to search.
+ * Duplicates and paths under other included paths are filtered out.
+ */
+function internal_pattern_helper_getSearchPaths(patterns) {
+ // Ignore negate patterns
+ patterns = patterns.filter(x => !x.negate);
+ // Create a map of all search paths
+ const searchPathMap = {};
+ for (const pattern of patterns) {
+ const key = lib_internal_pattern_helper_IS_WINDOWS
+ ? pattern.searchPath.toUpperCase()
+ : pattern.searchPath;
+ searchPathMap[key] = 'candidate';
+ }
+ const result = [];
+ for (const pattern of patterns) {
+ // Check if already included
+ const key = lib_internal_pattern_helper_IS_WINDOWS
+ ? pattern.searchPath.toUpperCase()
+ : pattern.searchPath;
+ if (searchPathMap[key] === 'included') {
+ continue;
+ }
+ // Check for an ancestor search path
+ let foundAncestor = false;
+ let tempKey = key;
+ let parent = internal_path_helper_dirname(tempKey);
+ while (parent !== tempKey) {
+ if (searchPathMap[parent]) {
+ foundAncestor = true;
+ break;
+ }
+ tempKey = parent;
+ parent = internal_path_helper_dirname(tempKey);
+ }
+ // Include the search pattern in the result
+ if (!foundAncestor) {
+ result.push(pattern.searchPath);
+ searchPathMap[key] = 'included';
+ }
+ }
+ return result;
+}
+/**
+ * Matches the patterns against the path
+ */
+function internal_pattern_helper_match(patterns, itemPath) {
+ let result = lib_internal_match_kind_MatchKind.None;
+ for (const pattern of patterns) {
+ if (pattern.negate) {
+ result &= ~pattern.match(itemPath);
+ }
+ else {
+ result |= pattern.match(itemPath);
+ }
+ }
+ return result;
+}
+/**
+ * Checks whether to descend further into the directory
+ */
+function internal_pattern_helper_partialMatch(patterns, itemPath) {
+ return patterns.some(x => !x.negate && x.partialMatch(itemPath));
+}
+//# sourceMappingURL=internal-pattern-helper.js.map
+;// CONCATENATED MODULE: ./node_modules/@actions/glob/node_modules/balanced-match/dist/esm/index.js
+const balanced = (a, b, str) => {
+ const ma = a instanceof RegExp ? maybeMatch(a, str) : a;
+ const mb = b instanceof RegExp ? maybeMatch(b, str) : b;
+ const r = ma !== null && mb != null && esm_range(ma, mb, str);
+ return (r && {
+ start: r[0],
+ end: r[1],
+ pre: str.slice(0, r[0]),
+ body: str.slice(r[0] + ma.length, r[1]),
+ post: str.slice(r[1] + mb.length),
+ });
+};
+const maybeMatch = (reg, str) => {
+ const m = str.match(reg);
+ return m ? m[0] : null;
+};
+const esm_range = (a, b, str) => {
+ let begs, beg, left, right = undefined, result;
+ let ai = str.indexOf(a);
+ let bi = str.indexOf(b, ai + 1);
+ let i = ai;
+ if (ai >= 0 && bi > 0) {
+ if (a === b) {
+ return [ai, bi];
+ }
+ begs = [];
+ left = str.length;
+ while (i >= 0 && !result) {
+ if (i === ai) {
+ begs.push(i);
+ ai = str.indexOf(a, i + 1);
+ }
+ else if (begs.length === 1) {
+ const r = begs.pop();
+ if (r !== undefined)
+ result = [r, bi];
+ }
+ else {
+ beg = begs.pop();
+ if (beg !== undefined && beg < left) {
+ left = beg;
+ right = bi;
+ }
+ bi = str.indexOf(b, i + 1);
+ }
+ i = ai < bi && ai >= 0 ? ai : bi;
+ }
+ if (begs.length && right !== undefined) {
+ result = [left, right];
+ }
+ }
+ return result;
+};
+//# sourceMappingURL=index.js.map
+;// CONCATENATED MODULE: ./node_modules/@actions/glob/node_modules/brace-expansion/dist/esm/index.js
+
+const escSlash = '\0SLASH' + Math.random() + '\0';
+const escOpen = '\0OPEN' + Math.random() + '\0';
+const escClose = '\0CLOSE' + Math.random() + '\0';
+const escComma = '\0COMMA' + Math.random() + '\0';
+const escPeriod = '\0PERIOD' + Math.random() + '\0';
+const escSlashPattern = new RegExp(escSlash, 'g');
+const escOpenPattern = new RegExp(escOpen, 'g');
+const escClosePattern = new RegExp(escClose, 'g');
+const escCommaPattern = new RegExp(escComma, 'g');
+const escPeriodPattern = new RegExp(escPeriod, 'g');
+const slashPattern = /\\\\/g;
+const openPattern = /\\{/g;
+const closePattern = /\\}/g;
+const commaPattern = /\\,/g;
+const periodPattern = /\\\./g;
+const EXPANSION_MAX = 100_000;
+function numeric(str) {
+ return !isNaN(str) ? parseInt(str, 10) : str.charCodeAt(0);
+}
+function escapeBraces(str) {
+ return str
+ .replace(slashPattern, escSlash)
+ .replace(openPattern, escOpen)
+ .replace(closePattern, escClose)
+ .replace(commaPattern, escComma)
+ .replace(periodPattern, escPeriod);
+}
+function unescapeBraces(str) {
+ return str
+ .replace(escSlashPattern, '\\')
+ .replace(escOpenPattern, '{')
+ .replace(escClosePattern, '}')
+ .replace(escCommaPattern, ',')
+ .replace(escPeriodPattern, '.');
+}
+/**
+ * Basically just str.split(","), but handling cases
+ * where we have nested braced sections, which should be
+ * treated as individual members, like {a,{b,c},d}
+ */
+function parseCommaParts(str) {
+ if (!str) {
+ return [''];
+ }
+ const parts = [];
+ const m = balanced('{', '}', str);
+ if (!m) {
+ return str.split(',');
+ }
+ const { pre, body, post } = m;
+ const p = pre.split(',');
+ p[p.length - 1] += '{' + body + '}';
+ const postParts = parseCommaParts(post);
+ if (post.length) {
+ ;
+ p[p.length - 1] += postParts.shift();
+ p.push.apply(p, postParts);
+ }
+ parts.push.apply(parts, p);
+ return parts;
+}
+function esm_expand(str, options = {}) {
+ if (!str) {
+ return [];
+ }
+ const { max = EXPANSION_MAX } = options;
+ // I don't know why Bash 4.3 does this, but it does.
+ // Anything starting with {} will have the first two bytes preserved
+ // but *only* at the top level, so {},a}b will not expand to anything,
+ // but a{},b}c will be expanded to [a}c,abc].
+ // One could argue that this is a bug in Bash, but since the goal of
+ // this module is to match Bash's rules, we escape a leading {}
+ if (str.slice(0, 2) === '{}') {
+ str = '\\{\\}' + str.slice(2);
+ }
+ return expand_(escapeBraces(str), max, true).map(unescapeBraces);
+}
+function embrace(str) {
+ return '{' + str + '}';
+}
+function isPadded(el) {
+ return /^-?0\d/.test(el);
+}
+function lte(i, y) {
+ return i <= y;
+}
+function gte(i, y) {
+ return i >= y;
+}
+function expand_(str, max, isTop) {
+ /** @type {string[]} */
+ const expansions = [];
+ const m = balanced('{', '}', str);
+ if (!m)
+ return [str];
+ // no need to expand pre, since it is guaranteed to be free of brace-sets
+ const pre = m.pre;
+ const post = m.post.length ? expand_(m.post, max, false) : [''];
+ if (/\$$/.test(m.pre)) {
+ for (let k = 0; k < post.length && k < max; k++) {
+ const expansion = pre + '{' + m.body + '}' + post[k];
+ expansions.push(expansion);
+ }
+ }
+ else {
+ const isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
+ const isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
+ const isSequence = isNumericSequence || isAlphaSequence;
+ const isOptions = m.body.indexOf(',') >= 0;
+ if (!isSequence && !isOptions) {
+ // {a},b}
+ if (m.post.match(/,(?!,).*\}/)) {
+ str = m.pre + '{' + m.body + escClose + m.post;
+ return expand_(str, max, true);
+ }
+ return [str];
+ }
+ let n;
+ if (isSequence) {
+ n = m.body.split(/\.\./);
+ }
+ else {
+ n = parseCommaParts(m.body);
+ if (n.length === 1 && n[0] !== undefined) {
+ // x{{a,b}}y ==> x{a}y x{b}y
+ n = expand_(n[0], max, false).map(embrace);
+ //XXX is this necessary? Can't seem to hit it in tests.
+ /* c8 ignore start */
+ if (n.length === 1) {
+ return post.map(p => m.pre + n[0] + p);
+ }
+ /* c8 ignore stop */
+ }
+ }
+ // at this point, n is the parts, and we know it's not a comma set
+ // with a single entry.
+ let N;
+ if (isSequence && n[0] !== undefined && n[1] !== undefined) {
+ const x = numeric(n[0]);
+ const y = numeric(n[1]);
+ const width = Math.max(n[0].length, n[1].length);
+ let incr = n.length === 3 && n[2] !== undefined ?
+ Math.max(Math.abs(numeric(n[2])), 1)
+ : 1;
+ let test = lte;
+ const reverse = y < x;
+ if (reverse) {
+ incr *= -1;
+ test = gte;
+ }
+ const pad = n.some(isPadded);
+ N = [];
+ for (let i = x; test(i, y) && N.length < max; i += incr) {
+ let c;
+ if (isAlphaSequence) {
+ c = String.fromCharCode(i);
+ if (c === '\\') {
+ c = '';
+ }
+ }
+ else {
+ c = String(i);
+ if (pad) {
+ const need = width - c.length;
+ if (need > 0) {
+ const z = new Array(need + 1).join('0');
+ if (i < 0) {
+ c = '-' + z + c.slice(1);
+ }
+ else {
+ c = z + c;
+ }
+ }
+ }
+ }
+ N.push(c);
+ }
+ }
+ else {
+ N = [];
+ for (let j = 0; j < n.length; j++) {
+ N.push.apply(N, expand_(n[j], max, false));
+ }
+ }
+ for (let j = 0; j < N.length; j++) {
+ for (let k = 0; k < post.length && expansions.length < max; k++) {
+ const expansion = pre + N[j] + post[k];
+ if (!isTop || isSequence || expansion) {
+ expansions.push(expansion);
+ }
+ }
+ }
+ }
+ return expansions;
+}
+//# sourceMappingURL=index.js.map
+;// CONCATENATED MODULE: ./node_modules/@actions/glob/node_modules/minimatch/dist/esm/assert-valid-pattern.js
+const MAX_PATTERN_LENGTH = 1024 * 64;
+const assertValidPattern = (pattern) => {
+ if (typeof pattern !== 'string') {
+ throw new TypeError('invalid pattern');
+ }
+ if (pattern.length > MAX_PATTERN_LENGTH) {
+ throw new TypeError('pattern is too long');
+ }
+};
+//# sourceMappingURL=assert-valid-pattern.js.map
+;// CONCATENATED MODULE: ./node_modules/@actions/glob/node_modules/minimatch/dist/esm/brace-expressions.js
+// translate the various posix character classes into unicode properties
+// this works across all unicode locales
+// { : [, /u flag required, negated]
+const posixClasses = {
+ '[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}', true],
+ '[:alpha:]': ['\\p{L}\\p{Nl}', true],
+ '[:ascii:]': ['\\x' + '00-\\x' + '7f', false],
+ '[:blank:]': ['\\p{Zs}\\t', true],
+ '[:cntrl:]': ['\\p{Cc}', true],
+ '[:digit:]': ['\\p{Nd}', true],
+ '[:graph:]': ['\\p{Z}\\p{C}', true, true],
+ '[:lower:]': ['\\p{Ll}', true],
+ '[:print:]': ['\\p{C}', true],
+ '[:punct:]': ['\\p{P}', true],
+ '[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f', true],
+ '[:upper:]': ['\\p{Lu}', true],
+ '[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}', true],
+ '[:xdigit:]': ['A-Fa-f0-9', false],
+};
+// only need to escape a few things inside of brace expressions
+// escapes: [ \ ] -
+const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&');
+// escape all regexp magic characters
+const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
+// everything has already been escaped, we just have to join
+const rangesToString = (ranges) => ranges.join('');
+// takes a glob string at a posix brace expression, and returns
+// an equivalent regular expression source, and boolean indicating
+// whether the /u flag needs to be applied, and the number of chars
+// consumed to parse the character class.
+// This also removes out of order ranges, and returns ($.) if the
+// entire class just no good.
+const parseClass = (glob, position) => {
+ const pos = position;
+ /* c8 ignore start */
+ if (glob.charAt(pos) !== '[') {
+ throw new Error('not in a brace expression');
+ }
+ /* c8 ignore stop */
+ const ranges = [];
+ const negs = [];
+ let i = pos + 1;
+ let sawStart = false;
+ let uflag = false;
+ let escaping = false;
+ let negate = false;
+ let endPos = pos;
+ let rangeStart = '';
+ WHILE: while (i < glob.length) {
+ const c = glob.charAt(i);
+ if ((c === '!' || c === '^') && i === pos + 1) {
+ negate = true;
+ i++;
+ continue;
+ }
+ if (c === ']' && sawStart && !escaping) {
+ endPos = i + 1;
+ break;
+ }
+ sawStart = true;
+ if (c === '\\') {
+ if (!escaping) {
+ escaping = true;
+ i++;
+ continue;
+ }
+ // escaped \ char, fall through and treat like normal char
+ }
+ if (c === '[' && !escaping) {
+ // either a posix class, a collation equivalent, or just a [
+ for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
+ if (glob.startsWith(cls, i)) {
+ // invalid, [a-[] is fine, but not [a-[:alpha]]
+ if (rangeStart) {
+ return ['$.', false, glob.length - pos, true];
+ }
+ i += cls.length;
+ if (neg)
+ negs.push(unip);
+ else
+ ranges.push(unip);
+ uflag = uflag || u;
+ continue WHILE;
+ }
+ }
+ }
+ // now it's just a normal character, effectively
+ escaping = false;
+ if (rangeStart) {
+ // throw this range away if it's not valid, but others
+ // can still match.
+ if (c > rangeStart) {
+ ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c));
+ }
+ else if (c === rangeStart) {
+ ranges.push(braceEscape(c));
+ }
+ rangeStart = '';
+ i++;
+ continue;
+ }
+ // now might be the start of a range.
+ // can be either c-d or c-] or c] or c] at this point
+ if (glob.startsWith('-]', i + 1)) {
+ ranges.push(braceEscape(c + '-'));
+ i += 2;
+ continue;
+ }
+ if (glob.startsWith('-', i + 1)) {
+ rangeStart = c;
+ i += 2;
+ continue;
+ }
+ // not the start of a range, just a single character
+ ranges.push(braceEscape(c));
+ i++;
+ }
+ if (endPos < i) {
+ // didn't see the end of the class, not a valid class,
+ // but might still be valid as a literal match.
+ return ['', false, 0, false];
+ }
+ // if we got no ranges and no negates, then we have a range that
+ // cannot possibly match anything, and that poisons the whole glob
+ if (!ranges.length && !negs.length) {
+ return ['$.', false, glob.length - pos, true];
+ }
+ // if we got one positive range, and it's a single character, then that's
+ // not actually a magic pattern, it's just that one literal character.
+ // we should not treat that as "magic", we should just return the literal
+ // character. [_] is a perfectly valid way to escape glob magic chars.
+ if (negs.length === 0 &&
+ ranges.length === 1 &&
+ /^\\?.$/.test(ranges[0]) &&
+ !negate) {
+ const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
+ return [regexpEscape(r), false, endPos - pos, false];
+ }
+ const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']';
+ const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']';
+ const comb = ranges.length && negs.length ? '(' + sranges + '|' + snegs + ')'
+ : ranges.length ? sranges
+ : snegs;
+ return [comb, uflag, endPos - pos, true];
+};
+//# sourceMappingURL=brace-expressions.js.map
+;// CONCATENATED MODULE: ./node_modules/@actions/glob/node_modules/minimatch/dist/esm/unescape.js
+/**
+ * Un-escape a string that has been escaped with {@link escape}.
+ *
+ * If the {@link MinimatchOptions.windowsPathsNoEscape} option is used, then
+ * square-bracket escapes are removed, but not backslash escapes.
+ *
+ * For example, it will turn the string `'[*]'` into `*`, but it will not
+ * turn `'\\*'` into `'*'`, because `\` is a path separator in
+ * `windowsPathsNoEscape` mode.
+ *
+ * When `windowsPathsNoEscape` is not set, then both square-bracket escapes and
+ * backslash escapes are removed.
+ *
+ * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
+ * or unescaped.
+ *
+ * When `magicalBraces` is not set, escapes of braces (`{` and `}`) will not be
+ * unescaped.
+ */
+const unescape_unescape = (s, { windowsPathsNoEscape = false, magicalBraces = true, } = {}) => {
+ if (magicalBraces) {
+ return windowsPathsNoEscape ?
+ s.replace(/\[([^/\\])\]/g, '$1')
+ : s
+ .replace(/((?!\\).|^)\[([^/\\])\]/g, '$1$2')
+ .replace(/\\([^/])/g, '$1');
+ }
+ return windowsPathsNoEscape ?
+ s.replace(/\[([^/\\{}])\]/g, '$1')
+ : s
+ .replace(/((?!\\).|^)\[([^/\\{}])\]/g, '$1$2')
+ .replace(/\\([^/{}])/g, '$1');
+};
+//# sourceMappingURL=unescape.js.map
+;// CONCATENATED MODULE: ./node_modules/@actions/glob/node_modules/minimatch/dist/esm/ast.js
+// parse a single path portion
+var _a;
+
+
+const types = new Set(['!', '?', '+', '*', '@']);
+const isExtglobType = (c) => types.has(c);
+const isExtglobAST = (c) => isExtglobType(c.type);
+// Map of which extglob types can adopt the children of a nested extglob
+//
+// anything but ! can adopt a matching type:
+// +(a|+(b|c)|d) => +(a|b|c|d)
+// *(a|*(b|c)|d) => *(a|b|c|d)
+// @(a|@(b|c)|d) => @(a|b|c|d)
+// ?(a|?(b|c)|d) => ?(a|b|c|d)
+//
+// * can adopt anything, because 0 or repetition is allowed
+// *(a|?(b|c)|d) => *(a|b|c|d)
+// *(a|+(b|c)|d) => *(a|b|c|d)
+// *(a|@(b|c)|d) => *(a|b|c|d)
+//
+// + can adopt @, because 1 or repetition is allowed
+// +(a|@(b|c)|d) => +(a|b|c|d)
+//
+// + and @ CANNOT adopt *, because 0 would be allowed
+// +(a|*(b|c)|d) => would match "", on *(b|c)
+// @(a|*(b|c)|d) => would match "", on *(b|c)
+//
+// + and @ CANNOT adopt ?, because 0 would be allowed
+// +(a|?(b|c)|d) => would match "", on ?(b|c)
+// @(a|?(b|c)|d) => would match "", on ?(b|c)
+//
+// ? can adopt @, because 0 or 1 is allowed
+// ?(a|@(b|c)|d) => ?(a|b|c|d)
+//
+// ? and @ CANNOT adopt * or +, because >1 would be allowed
+// ?(a|*(b|c)|d) => would match bbb on *(b|c)
+// @(a|*(b|c)|d) => would match bbb on *(b|c)
+// ?(a|+(b|c)|d) => would match bbb on +(b|c)
+// @(a|+(b|c)|d) => would match bbb on +(b|c)
+//
+// ! CANNOT adopt ! (nothing else can either)
+// !(a|!(b|c)|d) => !(a|b|c|d) would fail to match on b (not not b|c)
+//
+// ! can adopt @
+// !(a|@(b|c)|d) => !(a|b|c|d)
+//
+// ! CANNOT adopt *
+// !(a|*(b|c)|d) => !(a|b|c|d) would match on bbb, not allowed
+//
+// ! CANNOT adopt +
+// !(a|+(b|c)|d) => !(a|b|c|d) would match on bbb, not allowed
+//
+// ! CANNOT adopt ?
+// x!(a|?(b|c)|d) => x!(a|b|c|d) would fail to match "x"
+const adoptionMap = new Map([
+ ['!', ['@']],
+ ['?', ['?', '@']],
+ ['@', ['@']],
+ ['*', ['*', '+', '?', '@']],
+ ['+', ['+', '@']],
+]);
+// nested extglobs that can be adopted in, but with the addition of
+// a blank '' element.
+const adoptionWithSpaceMap = new Map([
+ ['!', ['?']],
+ ['@', ['?']],
+ ['+', ['?', '*']],
+]);
+// union of the previous two maps
+const adoptionAnyMap = new Map([
+ ['!', ['?', '@']],
+ ['?', ['?', '@']],
+ ['@', ['?', '@']],
+ ['*', ['*', '+', '?', '@']],
+ ['+', ['+', '@', '?', '*']],
+]);
+// Extglobs that can take over their parent if they are the only child
+// the key is parent, value maps child to resulting extglob parent type
+// '@' is omitted because it's a special case. An `@` extglob with a single
+// member can always be usurped by that subpattern.
+const usurpMap = new Map([
+ ['!', new Map([['!', '@']])],
+ [
+ '?',
+ new Map([
+ ['*', '*'],
+ ['+', '*'],
+ ]),
+ ],
+ [
+ '@',
+ new Map([
+ ['!', '!'],
+ ['?', '?'],
+ ['@', '@'],
+ ['*', '*'],
+ ['+', '+'],
+ ]),
],
- setPrimaryEmailVisibilityForAuthenticatedUser: [
- "PATCH /user/email/visibility"
+ [
+ '+',
+ new Map([
+ ['?', '*'],
+ ['*', '*'],
+ ]),
],
- unblock: ["DELETE /user/blocks/{username}"],
- unfollow: ["DELETE /user/following/{username}"],
- updateAuthenticated: ["PATCH /user"]
- }
+]);
+// Patterns that get prepended to bind to the start of either the
+// entire string, or just a single path portion, to prevent dots
+// and/or traversal patterns, when needed.
+// Exts don't need the ^ or / bit, because the root binds that already.
+const startNoTraversal = '(?!(?:^|/)\\.\\.?(?:$|/))';
+const startNoDot = '(?!\\.)';
+// characters that indicate a start of pattern needs the "no dots" bit,
+// because a dot *might* be matched. ( is not in the list, because in
+// the case of a child extglob, it will handle the prevention itself.
+const addPatternStart = new Set(['[', '.']);
+// cases where traversal is A-OK, no dot prevention needed
+const justDots = new Set(['..', '.']);
+const reSpecials = new Set('().*{}+?[]^$\\!');
+const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
+// any single thing other than /
+const qmark = '[^/]';
+// * => any number of characters
+const star = qmark + '*?';
+// use + when we need to ensure that *something* matches, because the * is
+// the only thing in the path portion.
+const starNoEmpty = qmark + '+?';
+// remove the \ chars that we added if we end up doing a nonmagic compare
+// const deslash = (s: string) => s.replace(/\\(.)/g, '$1')
+let ID = 0;
+class AST {
+ type;
+ #root;
+ #hasMagic;
+ #uflag = false;
+ #parts = [];
+ #parent;
+ #parentIndex;
+ #negs;
+ #filledNegs = false;
+ #options;
+ #toString;
+ // set to true if it's an extglob with no children
+ // (which really means one child of '')
+ #emptyExt = false;
+ id = ++ID;
+ get depth() {
+ return (this.#parent?.depth ?? -1) + 1;
+ }
+ [Symbol.for('nodejs.util.inspect.custom')]() {
+ return {
+ '@@type': 'AST',
+ id: this.id,
+ type: this.type,
+ root: this.#root.id,
+ parent: this.#parent?.id,
+ depth: this.depth,
+ partsLength: this.#parts.length,
+ parts: this.#parts,
+ };
+ }
+ constructor(type, parent, options = {}) {
+ this.type = type;
+ // extglobs are inherently magical
+ if (type)
+ this.#hasMagic = true;
+ this.#parent = parent;
+ this.#root = this.#parent ? this.#parent.#root : this;
+ this.#options = this.#root === this ? options : this.#root.#options;
+ this.#negs = this.#root === this ? [] : this.#root.#negs;
+ if (type === '!' && !this.#root.#filledNegs)
+ this.#negs.push(this);
+ this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;
+ }
+ get hasMagic() {
+ /* c8 ignore start */
+ if (this.#hasMagic !== undefined)
+ return this.#hasMagic;
+ /* c8 ignore stop */
+ for (const p of this.#parts) {
+ if (typeof p === 'string')
+ continue;
+ if (p.type || p.hasMagic)
+ return (this.#hasMagic = true);
+ }
+ // note: will be undefined until we generate the regexp src and find out
+ return this.#hasMagic;
+ }
+ // reconstructs the pattern
+ toString() {
+ return (this.#toString !== undefined ? this.#toString
+ : !this.type ?
+ (this.#toString = this.#parts.map(p => String(p)).join(''))
+ : (this.#toString =
+ this.type +
+ '(' +
+ this.#parts.map(p => String(p)).join('|') +
+ ')'));
+ }
+ #fillNegs() {
+ /* c8 ignore start */
+ if (this !== this.#root)
+ throw new Error('should only call on root');
+ if (this.#filledNegs)
+ return this;
+ /* c8 ignore stop */
+ // call toString() once to fill this out
+ this.toString();
+ this.#filledNegs = true;
+ let n;
+ while ((n = this.#negs.pop())) {
+ if (n.type !== '!')
+ continue;
+ // walk up the tree, appending everthing that comes AFTER parentIndex
+ let p = n;
+ let pp = p.#parent;
+ while (pp) {
+ for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {
+ for (const part of n.#parts) {
+ /* c8 ignore start */
+ if (typeof part === 'string') {
+ throw new Error('string part in extglob AST??');
+ }
+ /* c8 ignore stop */
+ part.copyIn(pp.#parts[i]);
+ }
+ }
+ p = pp;
+ pp = p.#parent;
+ }
+ }
+ return this;
+ }
+ push(...parts) {
+ for (const p of parts) {
+ if (p === '')
+ continue;
+ /* c8 ignore start */
+ if (typeof p !== 'string' &&
+ !(p instanceof _a && p.#parent === this)) {
+ throw new Error('invalid part: ' + p);
+ }
+ /* c8 ignore stop */
+ this.#parts.push(p);
+ }
+ }
+ toJSON() {
+ const ret = this.type === null ?
+ this.#parts
+ .slice()
+ .map(p => (typeof p === 'string' ? p : p.toJSON()))
+ : [this.type, ...this.#parts.map(p => p.toJSON())];
+ if (this.isStart() && !this.type)
+ ret.unshift([]);
+ if (this.isEnd() &&
+ (this === this.#root ||
+ (this.#root.#filledNegs && this.#parent?.type === '!'))) {
+ ret.push({});
+ }
+ return ret;
+ }
+ isStart() {
+ if (this.#root === this)
+ return true;
+ // if (this.type) return !!this.#parent?.isStart()
+ if (!this.#parent?.isStart())
+ return false;
+ if (this.#parentIndex === 0)
+ return true;
+ // if everything AHEAD of this is a negation, then it's still the "start"
+ const p = this.#parent;
+ for (let i = 0; i < this.#parentIndex; i++) {
+ const pp = p.#parts[i];
+ if (!(pp instanceof _a && pp.type === '!')) {
+ return false;
+ }
+ }
+ return true;
+ }
+ isEnd() {
+ if (this.#root === this)
+ return true;
+ if (this.#parent?.type === '!')
+ return true;
+ if (!this.#parent?.isEnd())
+ return false;
+ if (!this.type)
+ return this.#parent?.isEnd();
+ // if not root, it'll always have a parent
+ /* c8 ignore start */
+ const pl = this.#parent ? this.#parent.#parts.length : 0;
+ /* c8 ignore stop */
+ return this.#parentIndex === pl - 1;
+ }
+ copyIn(part) {
+ if (typeof part === 'string')
+ this.push(part);
+ else
+ this.push(part.clone(this));
+ }
+ clone(parent) {
+ const c = new _a(this.type, parent);
+ for (const p of this.#parts) {
+ c.copyIn(p);
+ }
+ return c;
+ }
+ static #parseAST(str, ast, pos, opt, extDepth) {
+ const maxDepth = opt.maxExtglobRecursion ?? 2;
+ let escaping = false;
+ let inBrace = false;
+ let braceStart = -1;
+ let braceNeg = false;
+ if (ast.type === null) {
+ // outside of a extglob, append until we find a start
+ let i = pos;
+ let acc = '';
+ while (i < str.length) {
+ const c = str.charAt(i++);
+ // still accumulate escapes at this point, but we do ignore
+ // starts that are escaped
+ if (escaping || c === '\\') {
+ escaping = !escaping;
+ acc += c;
+ continue;
+ }
+ if (inBrace) {
+ if (i === braceStart + 1) {
+ if (c === '^' || c === '!') {
+ braceNeg = true;
+ }
+ }
+ else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
+ inBrace = false;
+ }
+ acc += c;
+ continue;
+ }
+ else if (c === '[') {
+ inBrace = true;
+ braceStart = i;
+ braceNeg = false;
+ acc += c;
+ continue;
+ }
+ // we don't have to check for adoption here, because that's
+ // done at the other recursion point.
+ const doRecurse = !opt.noext &&
+ isExtglobType(c) &&
+ str.charAt(i) === '(' &&
+ extDepth <= maxDepth;
+ if (doRecurse) {
+ ast.push(acc);
+ acc = '';
+ const ext = new _a(c, ast);
+ i = _a.#parseAST(str, ext, i, opt, extDepth + 1);
+ ast.push(ext);
+ continue;
+ }
+ acc += c;
+ }
+ ast.push(acc);
+ return i;
+ }
+ // some kind of extglob, pos is at the (
+ // find the next | or )
+ let i = pos + 1;
+ let part = new _a(null, ast);
+ const parts = [];
+ let acc = '';
+ while (i < str.length) {
+ const c = str.charAt(i++);
+ // still accumulate escapes at this point, but we do ignore
+ // starts that are escaped
+ if (escaping || c === '\\') {
+ escaping = !escaping;
+ acc += c;
+ continue;
+ }
+ if (inBrace) {
+ if (i === braceStart + 1) {
+ if (c === '^' || c === '!') {
+ braceNeg = true;
+ }
+ }
+ else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
+ inBrace = false;
+ }
+ acc += c;
+ continue;
+ }
+ else if (c === '[') {
+ inBrace = true;
+ braceStart = i;
+ braceNeg = false;
+ acc += c;
+ continue;
+ }
+ const doRecurse = !opt.noext &&
+ isExtglobType(c) &&
+ str.charAt(i) === '(' &&
+ /* c8 ignore start - the maxDepth is sufficient here */
+ (extDepth <= maxDepth || (ast && ast.#canAdoptType(c)));
+ /* c8 ignore stop */
+ if (doRecurse) {
+ const depthAdd = ast && ast.#canAdoptType(c) ? 0 : 1;
+ part.push(acc);
+ acc = '';
+ const ext = new _a(c, part);
+ part.push(ext);
+ i = _a.#parseAST(str, ext, i, opt, extDepth + depthAdd);
+ continue;
+ }
+ if (c === '|') {
+ part.push(acc);
+ acc = '';
+ parts.push(part);
+ part = new _a(null, ast);
+ continue;
+ }
+ if (c === ')') {
+ if (acc === '' && ast.#parts.length === 0) {
+ ast.#emptyExt = true;
+ }
+ part.push(acc);
+ acc = '';
+ ast.push(...parts, part);
+ return i;
+ }
+ acc += c;
+ }
+ // unfinished extglob
+ // if we got here, it was a malformed extglob! not an extglob, but
+ // maybe something else in there.
+ ast.type = null;
+ ast.#hasMagic = undefined;
+ ast.#parts = [str.substring(pos - 1)];
+ return i;
+ }
+ #canAdoptWithSpace(child) {
+ return this.#canAdopt(child, adoptionWithSpaceMap);
+ }
+ #canAdopt(child, map = adoptionMap) {
+ if (!child ||
+ typeof child !== 'object' ||
+ child.type !== null ||
+ child.#parts.length !== 1 ||
+ this.type === null) {
+ return false;
+ }
+ const gc = child.#parts[0];
+ if (!gc || typeof gc !== 'object' || gc.type === null) {
+ return false;
+ }
+ return this.#canAdoptType(gc.type, map);
+ }
+ #canAdoptType(c, map = adoptionAnyMap) {
+ return !!map.get(this.type)?.includes(c);
+ }
+ #adoptWithSpace(child, index) {
+ const gc = child.#parts[0];
+ const blank = new _a(null, gc, this.options);
+ blank.#parts.push('');
+ gc.push(blank);
+ this.#adopt(child, index);
+ }
+ #adopt(child, index) {
+ const gc = child.#parts[0];
+ this.#parts.splice(index, 1, ...gc.#parts);
+ for (const p of gc.#parts) {
+ if (typeof p === 'object')
+ p.#parent = this;
+ }
+ this.#toString = undefined;
+ }
+ #canUsurpType(c) {
+ const m = usurpMap.get(this.type);
+ return !!m?.has(c);
+ }
+ #canUsurp(child) {
+ if (!child ||
+ typeof child !== 'object' ||
+ child.type !== null ||
+ child.#parts.length !== 1 ||
+ this.type === null ||
+ this.#parts.length !== 1) {
+ return false;
+ }
+ const gc = child.#parts[0];
+ if (!gc || typeof gc !== 'object' || gc.type === null) {
+ return false;
+ }
+ return this.#canUsurpType(gc.type);
+ }
+ #usurp(child) {
+ const m = usurpMap.get(this.type);
+ const gc = child.#parts[0];
+ const nt = m?.get(gc.type);
+ /* c8 ignore start - impossible */
+ if (!nt)
+ return false;
+ /* c8 ignore stop */
+ this.#parts = gc.#parts;
+ for (const p of this.#parts) {
+ if (typeof p === 'object') {
+ p.#parent = this;
+ }
+ }
+ this.type = nt;
+ this.#toString = undefined;
+ this.#emptyExt = false;
+ }
+ static fromGlob(pattern, options = {}) {
+ const ast = new _a(null, undefined, options);
+ _a.#parseAST(pattern, ast, 0, options, 0);
+ return ast;
+ }
+ // returns the regular expression if there's magic, or the unescaped
+ // string if not.
+ toMMPattern() {
+ // should only be called on root
+ /* c8 ignore start */
+ if (this !== this.#root)
+ return this.#root.toMMPattern();
+ /* c8 ignore stop */
+ const glob = this.toString();
+ const [re, body, hasMagic, uflag] = this.toRegExpSource();
+ // if we're in nocase mode, and not nocaseMagicOnly, then we do
+ // still need a regular expression if we have to case-insensitively
+ // match capital/lowercase characters.
+ const anyMagic = hasMagic ||
+ this.#hasMagic ||
+ (this.#options.nocase &&
+ !this.#options.nocaseMagicOnly &&
+ glob.toUpperCase() !== glob.toLowerCase());
+ if (!anyMagic) {
+ return body;
+ }
+ const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '');
+ return Object.assign(new RegExp(`^${re}$`, flags), {
+ _src: re,
+ _glob: glob,
+ });
+ }
+ get options() {
+ return this.#options;
+ }
+ // returns the string match, the regexp source, whether there's magic
+ // in the regexp (so a regular expression is required) and whether or
+ // not the uflag is needed for the regular expression (for posix classes)
+ // TODO: instead of injecting the start/end at this point, just return
+ // the BODY of the regexp, along with the start/end portions suitable
+ // for binding the start/end in either a joined full-path makeRe context
+ // (where we bind to (^|/), or a standalone matchPart context (where
+ // we bind to ^, and not /). Otherwise slashes get duped!
+ //
+ // In part-matching mode, the start is:
+ // - if not isStart: nothing
+ // - if traversal possible, but not allowed: ^(?!\.\.?$)
+ // - if dots allowed or not possible: ^
+ // - if dots possible and not allowed: ^(?!\.)
+ // end is:
+ // - if not isEnd(): nothing
+ // - else: $
+ //
+ // In full-path matching mode, we put the slash at the START of the
+ // pattern, so start is:
+ // - if first pattern: same as part-matching mode
+ // - if not isStart(): nothing
+ // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
+ // - if dots allowed or not possible: /
+ // - if dots possible and not allowed: /(?!\.)
+ // end is:
+ // - if last pattern, same as part-matching mode
+ // - else nothing
+ //
+ // Always put the (?:$|/) on negated tails, though, because that has to be
+ // there to bind the end of the negated pattern portion, and it's easier to
+ // just stick it in now rather than try to inject it later in the middle of
+ // the pattern.
+ //
+ // We can just always return the same end, and leave it up to the caller
+ // to know whether it's going to be used joined or in parts.
+ // And, if the start is adjusted slightly, can do the same there:
+ // - if not isStart: nothing
+ // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
+ // - if dots allowed or not possible: (?:/|^)
+ // - if dots possible and not allowed: (?:/|^)(?!\.)
+ //
+ // But it's better to have a simpler binding without a conditional, for
+ // performance, so probably better to return both start options.
+ //
+ // Then the caller just ignores the end if it's not the first pattern,
+ // and the start always gets applied.
+ //
+ // But that's always going to be $ if it's the ending pattern, or nothing,
+ // so the caller can just attach $ at the end of the pattern when building.
+ //
+ // So the todo is:
+ // - better detect what kind of start is needed
+ // - return both flavors of starting pattern
+ // - attach $ at the end of the pattern when creating the actual RegExp
+ //
+ // Ah, but wait, no, that all only applies to the root when the first pattern
+ // is not an extglob. If the first pattern IS an extglob, then we need all
+ // that dot prevention biz to live in the extglob portions, because eg
+ // +(*|.x*) can match .xy but not .yx.
+ //
+ // So, return the two flavors if it's #root and the first child is not an
+ // AST, otherwise leave it to the child AST to handle it, and there,
+ // use the (?:^|/) style of start binding.
+ //
+ // Even simplified further:
+ // - Since the start for a join is eg /(?!\.) and the start for a part
+ // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
+ // or start or whatever) and prepend ^ or / at the Regexp construction.
+ toRegExpSource(allowDot) {
+ const dot = allowDot ?? !!this.#options.dot;
+ if (this.#root === this) {
+ this.#flatten();
+ this.#fillNegs();
+ }
+ if (!isExtglobAST(this)) {
+ const noEmpty = this.isStart() &&
+ this.isEnd() &&
+ !this.#parts.some(s => typeof s !== 'string');
+ const src = this.#parts
+ .map(p => {
+ const [re, _, hasMagic, uflag] = typeof p === 'string' ?
+ _a.#parseGlob(p, this.#hasMagic, noEmpty)
+ : p.toRegExpSource(allowDot);
+ this.#hasMagic = this.#hasMagic || hasMagic;
+ this.#uflag = this.#uflag || uflag;
+ return re;
+ })
+ .join('');
+ let start = '';
+ if (this.isStart()) {
+ if (typeof this.#parts[0] === 'string') {
+ // this is the string that will match the start of the pattern,
+ // so we need to protect against dots and such.
+ // '.' and '..' cannot match unless the pattern is that exactly,
+ // even if it starts with . or dot:true is set.
+ const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);
+ if (!dotTravAllowed) {
+ const aps = addPatternStart;
+ // check if we have a possibility of matching . or ..,
+ // and prevent that.
+ const needNoTrav =
+ // dots are allowed, and the pattern starts with [ or .
+ (dot && aps.has(src.charAt(0))) ||
+ // the pattern starts with \., and then [ or .
+ (src.startsWith('\\.') && aps.has(src.charAt(2))) ||
+ // the pattern starts with \.\., and then [ or .
+ (src.startsWith('\\.\\.') && aps.has(src.charAt(4)));
+ // no need to prevent dots if it can't match a dot, or if a
+ // sub-pattern will be preventing it anyway.
+ const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));
+ start =
+ needNoTrav ? startNoTraversal
+ : needNoDot ? startNoDot
+ : '';
+ }
+ }
+ }
+ // append the "end of path portion" pattern to negation tails
+ let end = '';
+ if (this.isEnd() &&
+ this.#root.#filledNegs &&
+ this.#parent?.type === '!') {
+ end = '(?:$|\\/)';
+ }
+ const final = start + src + end;
+ return [
+ final,
+ unescape_unescape(src),
+ (this.#hasMagic = !!this.#hasMagic),
+ this.#uflag,
+ ];
+ }
+ // We need to calculate the body *twice* if it's a repeat pattern
+ // at the start, once in nodot mode, then again in dot mode, so a
+ // pattern like *(?) can match 'x.y'
+ const repeated = this.type === '*' || this.type === '+';
+ // some kind of extglob
+ const start = this.type === '!' ? '(?:(?!(?:' : '(?:';
+ let body = this.#partsToRegExp(dot);
+ if (this.isStart() && this.isEnd() && !body && this.type !== '!') {
+ // invalid extglob, has to at least be *something* present, if it's
+ // the entire path portion.
+ const s = this.toString();
+ const me = this;
+ me.#parts = [s];
+ me.type = null;
+ me.#hasMagic = undefined;
+ return [s, unescape_unescape(this.toString()), false, false];
+ }
+ let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot ?
+ ''
+ : this.#partsToRegExp(true);
+ if (bodyDotAllowed === body) {
+ bodyDotAllowed = '';
+ }
+ if (bodyDotAllowed) {
+ body = `(?:${body})(?:${bodyDotAllowed})*?`;
+ }
+ // an empty !() is exactly equivalent to a starNoEmpty
+ let final = '';
+ if (this.type === '!' && this.#emptyExt) {
+ final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty;
+ }
+ else {
+ const close = this.type === '!' ?
+ // !() must match something,but !(x) can match ''
+ '))' +
+ (this.isStart() && !dot && !allowDot ? startNoDot : '') +
+ star +
+ ')'
+ : this.type === '@' ? ')'
+ : this.type === '?' ? ')?'
+ : this.type === '+' && bodyDotAllowed ? ')'
+ : this.type === '*' && bodyDotAllowed ? `)?`
+ : `)${this.type}`;
+ final = start + body + close;
+ }
+ return [
+ final,
+ unescape_unescape(body),
+ (this.#hasMagic = !!this.#hasMagic),
+ this.#uflag,
+ ];
+ }
+ #flatten() {
+ if (!isExtglobAST(this)) {
+ for (const p of this.#parts) {
+ if (typeof p === 'object') {
+ p.#flatten();
+ }
+ }
+ }
+ else {
+ // do up to 10 passes to flatten as much as possible
+ let iterations = 0;
+ let done = false;
+ do {
+ done = true;
+ for (let i = 0; i < this.#parts.length; i++) {
+ const c = this.#parts[i];
+ if (typeof c === 'object') {
+ c.#flatten();
+ if (this.#canAdopt(c)) {
+ done = false;
+ this.#adopt(c, i);
+ }
+ else if (this.#canAdoptWithSpace(c)) {
+ done = false;
+ this.#adoptWithSpace(c, i);
+ }
+ else if (this.#canUsurp(c)) {
+ done = false;
+ this.#usurp(c);
+ }
+ }
+ }
+ } while (!done && ++iterations < 10);
+ }
+ this.#toString = undefined;
+ }
+ #partsToRegExp(dot) {
+ return this.#parts
+ .map(p => {
+ // extglob ASTs should only contain parent ASTs
+ /* c8 ignore start */
+ if (typeof p === 'string') {
+ throw new Error('string type in extglob ast??');
+ }
+ /* c8 ignore stop */
+ // can ignore hasMagic, because extglobs are already always magic
+ const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot);
+ this.#uflag = this.#uflag || uflag;
+ return re;
+ })
+ .filter(p => !(this.isStart() && this.isEnd()) || !!p)
+ .join('|');
+ }
+ static #parseGlob(glob, hasMagic, noEmpty = false) {
+ let escaping = false;
+ let re = '';
+ let uflag = false;
+ // multiple stars that aren't globstars coalesce into one *
+ let inStar = false;
+ for (let i = 0; i < glob.length; i++) {
+ const c = glob.charAt(i);
+ if (escaping) {
+ escaping = false;
+ re += (reSpecials.has(c) ? '\\' : '') + c;
+ continue;
+ }
+ if (c === '*') {
+ if (inStar)
+ continue;
+ inStar = true;
+ re += noEmpty && /^[*]+$/.test(glob) ? starNoEmpty : star;
+ hasMagic = true;
+ continue;
+ }
+ else {
+ inStar = false;
+ }
+ if (c === '\\') {
+ if (i === glob.length - 1) {
+ re += '\\\\';
+ }
+ else {
+ escaping = true;
+ }
+ continue;
+ }
+ if (c === '[') {
+ const [src, needUflag, consumed, magic] = parseClass(glob, i);
+ if (consumed) {
+ re += src;
+ uflag = uflag || needUflag;
+ i += consumed - 1;
+ hasMagic = hasMagic || magic;
+ continue;
+ }
+ }
+ if (c === '?') {
+ re += qmark;
+ hasMagic = true;
+ continue;
+ }
+ re += regExpEscape(c);
+ }
+ return [re, unescape_unescape(glob), !!hasMagic, uflag];
+ }
+}
+_a = AST;
+//# sourceMappingURL=ast.js.map
+;// CONCATENATED MODULE: ./node_modules/@actions/glob/node_modules/minimatch/dist/esm/escape.js
+/**
+ * Escape all magic characters in a glob pattern.
+ *
+ * If the {@link MinimatchOptions.windowsPathsNoEscape}
+ * option is used, then characters are escaped by wrapping in `[]`, because
+ * a magic character wrapped in a character class can only be satisfied by
+ * that exact character. In this mode, `\` is _not_ escaped, because it is
+ * not interpreted as a magic character, but instead as a path separator.
+ *
+ * If the {@link MinimatchOptions.magicalBraces} option is used,
+ * then braces (`{` and `}`) will be escaped.
+ */
+const escape_escape = (s, { windowsPathsNoEscape = false, magicalBraces = false, } = {}) => {
+ // don't need to escape +@! because we escape the parens
+ // that make those magic, and escaping ! as [!] isn't valid,
+ // because [!]] is a valid glob class meaning not ']'.
+ if (magicalBraces) {
+ return windowsPathsNoEscape ?
+ s.replace(/[?*()[\]{}]/g, '[$&]')
+ : s.replace(/[?*()[\]\\{}]/g, '\\$&');
+ }
+ return windowsPathsNoEscape ?
+ s.replace(/[?*()[\]]/g, '[$&]')
+ : s.replace(/[?*()[\]\\]/g, '\\$&');
};
-var endpoints_default = Endpoints;
+//# sourceMappingURL=escape.js.map
+;// CONCATENATED MODULE: ./node_modules/@actions/glob/node_modules/minimatch/dist/esm/index.js
+
+
+
+
+
+const esm_minimatch = (p, pattern, options = {}) => {
+ assertValidPattern(pattern);
+ // shortcut: comments match nothing.
+ if (!options.nocomment && pattern.charAt(0) === '#') {
+ return false;
+ }
+ return new esm_Minimatch(pattern, options).match(p);
+};
+// Optimized checking for the most common glob patterns.
+const starDotExtRE = /^\*+([^+@!?*[(]*)$/;
+const starDotExtTest = (ext) => (f) => !f.startsWith('.') && f.endsWith(ext);
+const starDotExtTestDot = (ext) => (f) => f.endsWith(ext);
+const starDotExtTestNocase = (ext) => {
+ ext = ext.toLowerCase();
+ return (f) => !f.startsWith('.') && f.toLowerCase().endsWith(ext);
+};
+const starDotExtTestNocaseDot = (ext) => {
+ ext = ext.toLowerCase();
+ return (f) => f.toLowerCase().endsWith(ext);
+};
+const starDotStarRE = /^\*+\.\*+$/;
+const starDotStarTest = (f) => !f.startsWith('.') && f.includes('.');
+const starDotStarTestDot = (f) => f !== '.' && f !== '..' && f.includes('.');
+const dotStarRE = /^\.\*+$/;
+const dotStarTest = (f) => f !== '.' && f !== '..' && f.startsWith('.');
+const starRE = /^\*+$/;
+const starTest = (f) => f.length !== 0 && !f.startsWith('.');
+const starTestDot = (f) => f.length !== 0 && f !== '.' && f !== '..';
+const qmarksRE = /^\?+([^+@!?*[(]*)?$/;
+const qmarksTestNocase = ([$0, ext = '']) => {
+ const noext = qmarksTestNoExt([$0]);
+ if (!ext)
+ return noext;
+ ext = ext.toLowerCase();
+ return (f) => noext(f) && f.toLowerCase().endsWith(ext);
+};
+const qmarksTestNocaseDot = ([$0, ext = '']) => {
+ const noext = qmarksTestNoExtDot([$0]);
+ if (!ext)
+ return noext;
+ ext = ext.toLowerCase();
+ return (f) => noext(f) && f.toLowerCase().endsWith(ext);
+};
+const qmarksTestDot = ([$0, ext = '']) => {
+ const noext = qmarksTestNoExtDot([$0]);
+ return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
+};
+const qmarksTest = ([$0, ext = '']) => {
+ const noext = qmarksTestNoExt([$0]);
+ return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
+};
+const qmarksTestNoExt = ([$0]) => {
+ const len = $0.length;
+ return (f) => f.length === len && !f.startsWith('.');
+};
+const qmarksTestNoExtDot = ([$0]) => {
+ const len = $0.length;
+ return (f) => f.length === len && f !== '.' && f !== '..';
+};
+/* c8 ignore start */
+const defaultPlatform = (typeof process === 'object' && process ?
+ (typeof process.env === 'object' &&
+ process.env &&
+ process.env.__MINIMATCH_TESTING_PLATFORM__) ||
+ process.platform
+ : 'posix');
+const esm_path = {
+ win32: { sep: '\\' },
+ posix: { sep: '/' },
+};
+/* c8 ignore stop */
+const esm_sep = defaultPlatform === 'win32' ? esm_path.win32.sep : esm_path.posix.sep;
+esm_minimatch.sep = esm_sep;
+const GLOBSTAR = Symbol('globstar **');
+esm_minimatch.GLOBSTAR = GLOBSTAR;
+// any single thing other than /
+// don't need to escape / when using new RegExp()
+const esm_qmark = '[^/]';
+// * => any number of characters
+const esm_star = esm_qmark + '*?';
+// ** when dots are allowed. Anything goes, except .. and .
+// not (^ or / followed by one or two dots followed by $ or /),
+// followed by anything, any number of times.
+const twoStarDot = '(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?';
+// not a ^ or / followed by a dot,
+// followed by anything, any number of times.
+const twoStarNoDot = '(?:(?!(?:\\/|^)\\.).)*?';
+const filter = (pattern, options = {}) => (p) => esm_minimatch(p, pattern, options);
+esm_minimatch.filter = filter;
+const ext = (a, b = {}) => Object.assign({}, a, b);
+const esm_defaults = (def) => {
+ if (!def || typeof def !== 'object' || !Object.keys(def).length) {
+ return esm_minimatch;
+ }
+ const orig = esm_minimatch;
+ const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));
+ return Object.assign(m, {
+ Minimatch: class Minimatch extends orig.Minimatch {
+ constructor(pattern, options = {}) {
+ super(pattern, ext(def, options));
+ }
+ static defaults(options) {
+ return orig.defaults(ext(def, options)).Minimatch;
+ }
+ },
+ AST: class AST extends orig.AST {
+ /* c8 ignore start */
+ constructor(type, parent, options = {}) {
+ super(type, parent, ext(def, options));
+ }
+ /* c8 ignore stop */
+ static fromGlob(pattern, options = {}) {
+ return orig.AST.fromGlob(pattern, ext(def, options));
+ }
+ },
+ unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),
+ escape: (s, options = {}) => orig.escape(s, ext(def, options)),
+ filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
+ defaults: (options) => orig.defaults(ext(def, options)),
+ makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
+ braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
+ match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
+ sep: orig.sep,
+ GLOBSTAR: GLOBSTAR,
+ });
+};
+esm_minimatch.defaults = esm_defaults;
+// Brace expansion:
+// a{b,c}d -> abd acd
+// a{b,}c -> abc ac
+// a{0..3}d -> a0d a1d a2d a3d
+// a{b,c{d,e}f}g -> abg acdfg acefg
+// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
+//
+// Invalid sets are not expanded.
+// a{2..}b -> a{2..}b
+// a{b}c -> a{b}c
+const braceExpand = (pattern, options = {}) => {
+ assertValidPattern(pattern);
+ // Thanks to Yeting Li