Update checked-in dependencies

This commit is contained in:
github-actions[bot] 2025-01-27 17:21:38 +00:00
parent 7fdbca3ba3
commit 357e0ceaa9
360 changed files with 25673 additions and 917 deletions

191
node_modules/@open-draft/deferred-promise/README.md generated vendored Normal file
View file

@ -0,0 +1,191 @@
# Deferred Promise
The `DeferredPromise` class is a Promise-compatible abstraction that defers resolving/rejecting promises to another closure. This class is primarily useful when one part of your system establishes as promise but another part of your system fulfills it.
> This class is conceptually inspired by the [`createDeferredPromise()`](https://github.com/nodejs/node/blob/696fd4b14fc34cc2d01497a3abd9bb441b89be50/lib/internal/util.js#L468-L477) internal utility in Node.js. Unlike the Node.js implementation, however, `DeferredProimse` _extends_ a native `Promise`, allowing the consumer to handle deferred promises like regular promises (no `.promise` instance nesting).
## Getting started
```sh
npm install @open-draft/deferred-promise
```
## Documentation
- [**`createDeferredExecutor()`**](#createdeferredexecutor)
- [`DeferredExecutor.state`](#deferredexecutorstate)
- [`DeferredExecutor.resolve()`](#deferredexecutorresolve)
- [`DeferredExecutor.reject()`](#deferredexecutorreject)
- [`DeferredExecutor.rejectionReason`](#deferredexecutorrejectionreason)
- [**Class: `DeferredPromise`**](#class-deferredpromise)
- [`new DeferredPromise()`](#new-defferedpromise)
- [`deferredPromise.state`](#deferredpromisestate)
- [`deferredPromise.resolve()`](#deferredpromiseresolve)
- [`deferredPromise.reject()`](#deferredpromisereject)
- [`deferredPromise.rejectionReason`](#deferredpromiserejectionreason)
---
## `createDeferredExecutor()`
Creates a Promise executor function that delegates its resolution to the current scope.
```js
import { createDeferredExecutor } from '@open-draft/deferred-promise'
const executor = createDeferredExecutor()
const promise = new Promise(executor)
executor.resolve('hello')
// executor.reject(new Error('Reason'))
```
Deferred executor allows you to control any promise remotely and doesn't affect the Promise instance in any way. Similar to the [`DeferredPromise`](#class-deferredpromise) instance, the deferred executor exposes additional promise properties like `state`, `rejectionReason`, `resolve`, and `reject`. In fact, the `DeferredPromise` class is implemented on top of the deferred executor.
```js
const executor = createDeferredExecutor()
const promise = new Promise(executor)
executor.reject('reason')
nextTick(() => {
console.log(executor.rejectionReason) // "reason"
})
```
### `DeferredExecutor.state`
- `<"pending" | "fulfilled" | "rejected">` **Default:** `"pending"`
```js
const executor = createDeferredExecutor()
const promise = new Promise(executor)
console.log(executor.state) // "pending"
```
Calling [`resolve()`](#deferredexecutorresolve) and [`reject()`](#deferredexecutorreject) methods of the executor transitions the state to "fulfilled" and "rejected" respectively.
### `DeferredExecutor.resolve()`
Resolves the promise with a given value.
```js
const executor = createDeferredExecutor()
const promise = new Promise(executor)
console.log(executor.state) // "pending"
executor.resolve()
// The promise state is still "pending"
// because promises are settled in the next microtask.
console.log(executor.state) // "pending"
nextTick(() => {
// In the next microtask, the promise's state is resolved.
console.log(executor.state) // "fulfilled"
})
```
### `DeferredExecutor.reject()`
Rejects the promise with a given reason.
```js
const executor = createDeferredExecutor()
const promise = new Promise(executor)
executor.reject(new Error('Failed to fetch'))
nextTick(() => {
console.log(executor.state) // "rejected"
console.log(executor.rejectionReason) // Error("Failed to fetch")
})
```
You can access the rejection reason of the promise at any time by the [`rejectionReason`](#deferredexecutorrejectionreason) property of the deferred executor.
### `DeferredExecutor.rejectionReason`
Returns the reason of the promise rejection. If no reason has been provided to the `reject()` call, `undefined` is returned instead.
```js
const executor = createDeferredExecutor()
const promise = new Promise(executor)
promise.reject(new Error('Internal Server Error'))
nextTick(() => {
console.log(promise.rejectionReason) // Error("Internal Server Error")
})
```
---
## Class: `DeferredPromise`
### `new DefferedPromise()`
Creates a new instance of a deferred promise.
```js
import { DeferredPromise } from '@open-draft/deferred-promise'
const promise = new DeferredPromise()
```
A deferred promise is a Promise-compatible class that constructs a regular Promise instance under the hood, controlling it via the [deferred executor](#createdeferredexecutor).
A deferred promise is fully compatible with the regular Promise, both type- and runtime-wise, e.g. a deferred promise can be chained and awaited normally.
```js
const promise = new DefferredPromise()
.then((value) => value.toUpperCase())
.then((value) => value.substring(0, 2))
.catch((error) => console.error(error))
await promise
```
Unlike the regular Promise, however, a deferred promise doesn't accept the `executor` function as the constructor argument. Instead, the resolution of the deferred promise is deferred to the current scope (thus the name).
```js
function getPort() {
// Notice that you don't provide any executor function
// when constructing a deferred promise.
const portPromise = new DeferredPromise()
port.on('open', (port) => {
// Resolve the deferred promise whenever necessary.
portPromise.resolve(port)
})
// Return the deferred promise immediately.
return portPromise
}
```
Use the [`resolve()`](#deferredpromiseresolve) and [`reject()`](#deferredpromisereject) methods of the deferred promise instance to resolve and reject that promise respectively.
### `deferredPromise.state`
See [`DeferredExecutor.state`](#deferredexecutorstate)
### `deferredPromise.resolve()`
See [`DeferredExecutor.resolve()`](#deferredexecutorresolve)
### `deferredPromise.reject()`
See [`DeferredExecutor.reject()`](#deferredexecutorreject)
### `deferredPromise.rejectionReason`
See [`DeferredExecutor.rejectionReason`](#deferredexecutorrejectionreason)
---
## Mentions
- [Jonas Kuske](https://github.com/jonaskuske) for the phenomenal work around improving Promise-compliance.

View file

@ -0,0 +1,27 @@
declare type PromiseState = 'pending' | 'fulfilled' | 'rejected';
declare type Executor<Value> = ConstructorParameters<typeof Promise<Value>>[0];
declare type ResolveFunction<Value> = Parameters<Executor<Value>>[0];
declare type RejectFunction<Reason> = Parameters<Executor<Reason>>[1];
declare type DeferredPromiseExecutor<Input = never, Output = Input> = {
(resolve?: ResolveFunction<Input>, reject?: RejectFunction<any>): void;
resolve: ResolveFunction<Input>;
reject: RejectFunction<any>;
result?: Output;
state: PromiseState;
rejectionReason?: unknown;
};
declare function createDeferredExecutor<Input = never, Output = Input>(): DeferredPromiseExecutor<Input, Output>;
declare class DeferredPromise<Input, Output = Input> extends Promise<Input> {
#private;
resolve: ResolveFunction<Output>;
reject: RejectFunction<Output>;
constructor(executor?: Executor<Input> | null);
get state(): PromiseState;
get rejectionReason(): unknown;
then<ThenResult = Input, CatchResult = never>(onFulfilled?: (value: Input) => ThenResult | PromiseLike<ThenResult>, onRejected?: (reason: any) => CatchResult | PromiseLike<CatchResult>): DeferredPromise<ThenResult | CatchResult, Output>;
catch<CatchResult = never>(onRejected?: (reason: any) => CatchResult | PromiseLike<CatchResult>): DeferredPromise<Input | CatchResult, Output>;
finally(onfinally?: () => void | Promise<any>): DeferredPromise<Input, Output>;
}
export { DeferredPromise, DeferredPromiseExecutor, Executor, PromiseState, RejectFunction, ResolveFunction, createDeferredExecutor };

View file

@ -0,0 +1,27 @@
declare type PromiseState = 'pending' | 'fulfilled' | 'rejected';
declare type Executor<Value> = ConstructorParameters<typeof Promise<Value>>[0];
declare type ResolveFunction<Value> = Parameters<Executor<Value>>[0];
declare type RejectFunction<Reason> = Parameters<Executor<Reason>>[1];
declare type DeferredPromiseExecutor<Input = never, Output = Input> = {
(resolve?: ResolveFunction<Input>, reject?: RejectFunction<any>): void;
resolve: ResolveFunction<Input>;
reject: RejectFunction<any>;
result?: Output;
state: PromiseState;
rejectionReason?: unknown;
};
declare function createDeferredExecutor<Input = never, Output = Input>(): DeferredPromiseExecutor<Input, Output>;
declare class DeferredPromise<Input, Output = Input> extends Promise<Input> {
#private;
resolve: ResolveFunction<Output>;
reject: RejectFunction<Output>;
constructor(executor?: Executor<Input> | null);
get state(): PromiseState;
get rejectionReason(): unknown;
then<ThenResult = Input, CatchResult = never>(onFulfilled?: (value: Input) => ThenResult | PromiseLike<ThenResult>, onRejected?: (reason: any) => CatchResult | PromiseLike<CatchResult>): DeferredPromise<ThenResult | CatchResult, Output>;
catch<CatchResult = never>(onRejected?: (reason: any) => CatchResult | PromiseLike<CatchResult>): DeferredPromise<Input | CatchResult, Output>;
finally(onfinally?: () => void | Promise<any>): DeferredPromise<Input, Output>;
}
export { DeferredPromise, DeferredPromiseExecutor, Executor, PromiseState, RejectFunction, ResolveFunction, createDeferredExecutor };

View file

@ -0,0 +1,99 @@
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);
// src/index.ts
var src_exports = {};
__export(src_exports, {
DeferredPromise: () => DeferredPromise,
createDeferredExecutor: () => createDeferredExecutor
});
module.exports = __toCommonJS(src_exports);
// src/createDeferredExecutor.ts
function createDeferredExecutor() {
const executor = (resolve, reject) => {
executor.state = "pending";
executor.resolve = (data) => {
if (executor.state !== "pending") {
return;
}
executor.result = data;
const onFulfilled = (value) => {
executor.state = "fulfilled";
return value;
};
return resolve(
data instanceof Promise ? data : Promise.resolve(data).then(onFulfilled)
);
};
executor.reject = (reason) => {
if (executor.state !== "pending") {
return;
}
queueMicrotask(() => {
executor.state = "rejected";
});
return reject(executor.rejectionReason = reason);
};
};
return executor;
}
// src/DeferredPromise.ts
var DeferredPromise = class extends Promise {
#executor;
resolve;
reject;
constructor(executor = null) {
const deferredExecutor = createDeferredExecutor();
super((originalResolve, originalReject) => {
deferredExecutor(originalResolve, originalReject);
executor?.(deferredExecutor.resolve, deferredExecutor.reject);
});
this.#executor = deferredExecutor;
this.resolve = this.#executor.resolve;
this.reject = this.#executor.reject;
}
get state() {
return this.#executor.state;
}
get rejectionReason() {
return this.#executor.rejectionReason;
}
then(onFulfilled, onRejected) {
return this.#decorate(super.then(onFulfilled, onRejected));
}
catch(onRejected) {
return this.#decorate(super.catch(onRejected));
}
finally(onfinally) {
return this.#decorate(super.finally(onfinally));
}
#decorate(promise) {
return Object.defineProperties(promise, {
resolve: { configurable: true, value: this.resolve },
reject: { configurable: true, value: this.reject }
});
}
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
DeferredPromise,
createDeferredExecutor
});
//# sourceMappingURL=index.js.map

View file

@ -0,0 +1 @@
{"version":3,"sources":["../src/index.ts","../src/createDeferredExecutor.ts","../src/DeferredPromise.ts"],"sourcesContent":["export * from './createDeferredExecutor'\nexport * from './DeferredPromise'\n","export type PromiseState = 'pending' | 'fulfilled' | 'rejected'\n\nexport type Executor<Value> = ConstructorParameters<typeof Promise<Value>>[0]\nexport type ResolveFunction<Value> = Parameters<Executor<Value>>[0]\nexport type RejectFunction<Reason> = Parameters<Executor<Reason>>[1]\n\nexport type DeferredPromiseExecutor<Input = never, Output = Input> = {\n (resolve?: ResolveFunction<Input>, reject?: RejectFunction<any>): void\n\n resolve: ResolveFunction<Input>\n reject: RejectFunction<any>\n result?: Output\n state: PromiseState\n rejectionReason?: unknown\n}\nexport function createDeferredExecutor<\n Input = never,\n Output = Input\n>(): DeferredPromiseExecutor<Input, Output> {\n const executor = <DeferredPromiseExecutor<Input, Output>>((\n resolve,\n reject\n ) => {\n executor.state = 'pending'\n\n executor.resolve = (data) => {\n if (executor.state !== 'pending') {\n return\n }\n\n executor.result = data as Output\n\n const onFulfilled = <Value>(value: Value) => {\n executor.state = 'fulfilled'\n return value\n }\n\n return resolve(\n data instanceof Promise ? data : Promise.resolve(data).then(onFulfilled)\n )\n }\n\n executor.reject = (reason) => {\n if (executor.state !== 'pending') {\n return\n }\n\n queueMicrotask(() => {\n executor.state = 'rejected'\n })\n\n return reject((executor.rejectionReason = reason))\n }\n })\n\n return executor\n}\n","import {\n type Executor,\n type RejectFunction,\n type ResolveFunction,\n type DeferredPromiseExecutor,\n createDeferredExecutor,\n} from './createDeferredExecutor'\n\nexport class DeferredPromise<Input, Output = Input> extends Promise<Input> {\n #executor: DeferredPromiseExecutor\n\n public resolve: ResolveFunction<Output>\n public reject: RejectFunction<Output>\n\n constructor(executor: Executor<Input> | null = null) {\n const deferredExecutor = createDeferredExecutor()\n super((originalResolve, originalReject) => {\n deferredExecutor(originalResolve, originalReject)\n executor?.(deferredExecutor.resolve, deferredExecutor.reject)\n })\n\n this.#executor = deferredExecutor\n this.resolve = this.#executor.resolve\n this.reject = this.#executor.reject\n }\n\n public get state() {\n return this.#executor.state\n }\n\n public get rejectionReason() {\n return this.#executor.rejectionReason\n }\n\n public then<ThenResult = Input, CatchResult = never>(\n onFulfilled?: (value: Input) => ThenResult | PromiseLike<ThenResult>,\n onRejected?: (reason: any) => CatchResult | PromiseLike<CatchResult>\n ) {\n return this.#decorate(super.then(onFulfilled, onRejected))\n }\n\n public catch<CatchResult = never>(\n onRejected?: (reason: any) => CatchResult | PromiseLike<CatchResult>\n ) {\n return this.#decorate(super.catch(onRejected))\n }\n\n public finally(onfinally?: () => void | Promise<any>) {\n return this.#decorate(super.finally(onfinally))\n }\n\n #decorate<ChildInput>(\n promise: Promise<ChildInput>\n ): DeferredPromise<ChildInput, Output> {\n return Object.defineProperties(promise, {\n resolve: { configurable: true, value: this.resolve },\n reject: { configurable: true, value: this.reject },\n }) as DeferredPromise<ChildInput, Output>\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACeO,SAAS,yBAG4B;AAC1C,QAAM,WAAoD,CACxD,SACA,WACG;AACH,aAAS,QAAQ;AAEjB,aAAS,UAAU,CAAC,SAAS;AAC3B,UAAI,SAAS,UAAU,WAAW;AAChC;AAAA,MACF;AAEA,eAAS,SAAS;AAElB,YAAM,cAAc,CAAQ,UAAiB;AAC3C,iBAAS,QAAQ;AACjB,eAAO;AAAA,MACT;AAEA,aAAO;AAAA,QACL,gBAAgB,UAAU,OAAO,QAAQ,QAAQ,IAAI,EAAE,KAAK,WAAW;AAAA,MACzE;AAAA,IACF;AAEA,aAAS,SAAS,CAAC,WAAW;AAC5B,UAAI,SAAS,UAAU,WAAW;AAChC;AAAA,MACF;AAEA,qBAAe,MAAM;AACnB,iBAAS,QAAQ;AAAA,MACnB,CAAC;AAED,aAAO,OAAQ,SAAS,kBAAkB,MAAO;AAAA,IACnD;AAAA,EACF;AAEA,SAAO;AACT;;;AChDO,IAAM,kBAAN,cAAqD,QAAe;AAAA,EACzE;AAAA,EAEO;AAAA,EACA;AAAA,EAEP,YAAY,WAAmC,MAAM;AACnD,UAAM,mBAAmB,uBAAuB;AAChD,UAAM,CAAC,iBAAiB,mBAAmB;AACzC,uBAAiB,iBAAiB,cAAc;AAChD,iBAAW,iBAAiB,SAAS,iBAAiB,MAAM;AAAA,IAC9D,CAAC;AAED,SAAK,YAAY;AACjB,SAAK,UAAU,KAAK,UAAU;AAC9B,SAAK,SAAS,KAAK,UAAU;AAAA,EAC/B;AAAA,EAEA,IAAW,QAAQ;AACjB,WAAO,KAAK,UAAU;AAAA,EACxB;AAAA,EAEA,IAAW,kBAAkB;AAC3B,WAAO,KAAK,UAAU;AAAA,EACxB;AAAA,EAEO,KACL,aACA,YACA;AACA,WAAO,KAAK,UAAU,MAAM,KAAK,aAAa,UAAU,CAAC;AAAA,EAC3D;AAAA,EAEO,MACL,YACA;AACA,WAAO,KAAK,UAAU,MAAM,MAAM,UAAU,CAAC;AAAA,EAC/C;AAAA,EAEO,QAAQ,WAAuC;AACpD,WAAO,KAAK,UAAU,MAAM,QAAQ,SAAS,CAAC;AAAA,EAChD;AAAA,EAEA,UACE,SACqC;AACrC,WAAO,OAAO,iBAAiB,SAAS;AAAA,MACtC,SAAS,EAAE,cAAc,MAAM,OAAO,KAAK,QAAQ;AAAA,MACnD,QAAQ,EAAE,cAAc,MAAM,OAAO,KAAK,OAAO;AAAA,IACnD,CAAC;AAAA,EACH;AACF;","names":[]}

View file

@ -0,0 +1,72 @@
// src/createDeferredExecutor.ts
function createDeferredExecutor() {
const executor = (resolve, reject) => {
executor.state = "pending";
executor.resolve = (data) => {
if (executor.state !== "pending") {
return;
}
executor.result = data;
const onFulfilled = (value) => {
executor.state = "fulfilled";
return value;
};
return resolve(
data instanceof Promise ? data : Promise.resolve(data).then(onFulfilled)
);
};
executor.reject = (reason) => {
if (executor.state !== "pending") {
return;
}
queueMicrotask(() => {
executor.state = "rejected";
});
return reject(executor.rejectionReason = reason);
};
};
return executor;
}
// src/DeferredPromise.ts
var DeferredPromise = class extends Promise {
#executor;
resolve;
reject;
constructor(executor = null) {
const deferredExecutor = createDeferredExecutor();
super((originalResolve, originalReject) => {
deferredExecutor(originalResolve, originalReject);
executor?.(deferredExecutor.resolve, deferredExecutor.reject);
});
this.#executor = deferredExecutor;
this.resolve = this.#executor.resolve;
this.reject = this.#executor.reject;
}
get state() {
return this.#executor.state;
}
get rejectionReason() {
return this.#executor.rejectionReason;
}
then(onFulfilled, onRejected) {
return this.#decorate(super.then(onFulfilled, onRejected));
}
catch(onRejected) {
return this.#decorate(super.catch(onRejected));
}
finally(onfinally) {
return this.#decorate(super.finally(onfinally));
}
#decorate(promise) {
return Object.defineProperties(promise, {
resolve: { configurable: true, value: this.resolve },
reject: { configurable: true, value: this.reject }
});
}
};
export {
DeferredPromise,
createDeferredExecutor
};
//# sourceMappingURL=index.mjs.map

View file

@ -0,0 +1 @@
{"version":3,"sources":["../src/createDeferredExecutor.ts","../src/DeferredPromise.ts"],"sourcesContent":["export type PromiseState = 'pending' | 'fulfilled' | 'rejected'\n\nexport type Executor<Value> = ConstructorParameters<typeof Promise<Value>>[0]\nexport type ResolveFunction<Value> = Parameters<Executor<Value>>[0]\nexport type RejectFunction<Reason> = Parameters<Executor<Reason>>[1]\n\nexport type DeferredPromiseExecutor<Input = never, Output = Input> = {\n (resolve?: ResolveFunction<Input>, reject?: RejectFunction<any>): void\n\n resolve: ResolveFunction<Input>\n reject: RejectFunction<any>\n result?: Output\n state: PromiseState\n rejectionReason?: unknown\n}\nexport function createDeferredExecutor<\n Input = never,\n Output = Input\n>(): DeferredPromiseExecutor<Input, Output> {\n const executor = <DeferredPromiseExecutor<Input, Output>>((\n resolve,\n reject\n ) => {\n executor.state = 'pending'\n\n executor.resolve = (data) => {\n if (executor.state !== 'pending') {\n return\n }\n\n executor.result = data as Output\n\n const onFulfilled = <Value>(value: Value) => {\n executor.state = 'fulfilled'\n return value\n }\n\n return resolve(\n data instanceof Promise ? data : Promise.resolve(data).then(onFulfilled)\n )\n }\n\n executor.reject = (reason) => {\n if (executor.state !== 'pending') {\n return\n }\n\n queueMicrotask(() => {\n executor.state = 'rejected'\n })\n\n return reject((executor.rejectionReason = reason))\n }\n })\n\n return executor\n}\n","import {\n type Executor,\n type RejectFunction,\n type ResolveFunction,\n type DeferredPromiseExecutor,\n createDeferredExecutor,\n} from './createDeferredExecutor'\n\nexport class DeferredPromise<Input, Output = Input> extends Promise<Input> {\n #executor: DeferredPromiseExecutor\n\n public resolve: ResolveFunction<Output>\n public reject: RejectFunction<Output>\n\n constructor(executor: Executor<Input> | null = null) {\n const deferredExecutor = createDeferredExecutor()\n super((originalResolve, originalReject) => {\n deferredExecutor(originalResolve, originalReject)\n executor?.(deferredExecutor.resolve, deferredExecutor.reject)\n })\n\n this.#executor = deferredExecutor\n this.resolve = this.#executor.resolve\n this.reject = this.#executor.reject\n }\n\n public get state() {\n return this.#executor.state\n }\n\n public get rejectionReason() {\n return this.#executor.rejectionReason\n }\n\n public then<ThenResult = Input, CatchResult = never>(\n onFulfilled?: (value: Input) => ThenResult | PromiseLike<ThenResult>,\n onRejected?: (reason: any) => CatchResult | PromiseLike<CatchResult>\n ) {\n return this.#decorate(super.then(onFulfilled, onRejected))\n }\n\n public catch<CatchResult = never>(\n onRejected?: (reason: any) => CatchResult | PromiseLike<CatchResult>\n ) {\n return this.#decorate(super.catch(onRejected))\n }\n\n public finally(onfinally?: () => void | Promise<any>) {\n return this.#decorate(super.finally(onfinally))\n }\n\n #decorate<ChildInput>(\n promise: Promise<ChildInput>\n ): DeferredPromise<ChildInput, Output> {\n return Object.defineProperties(promise, {\n resolve: { configurable: true, value: this.resolve },\n reject: { configurable: true, value: this.reject },\n }) as DeferredPromise<ChildInput, Output>\n }\n}\n"],"mappings":";AAeO,SAAS,yBAG4B;AAC1C,QAAM,WAAoD,CACxD,SACA,WACG;AACH,aAAS,QAAQ;AAEjB,aAAS,UAAU,CAAC,SAAS;AAC3B,UAAI,SAAS,UAAU,WAAW;AAChC;AAAA,MACF;AAEA,eAAS,SAAS;AAElB,YAAM,cAAc,CAAQ,UAAiB;AAC3C,iBAAS,QAAQ;AACjB,eAAO;AAAA,MACT;AAEA,aAAO;AAAA,QACL,gBAAgB,UAAU,OAAO,QAAQ,QAAQ,IAAI,EAAE,KAAK,WAAW;AAAA,MACzE;AAAA,IACF;AAEA,aAAS,SAAS,CAAC,WAAW;AAC5B,UAAI,SAAS,UAAU,WAAW;AAChC;AAAA,MACF;AAEA,qBAAe,MAAM;AACnB,iBAAS,QAAQ;AAAA,MACnB,CAAC;AAED,aAAO,OAAQ,SAAS,kBAAkB,MAAO;AAAA,IACnD;AAAA,EACF;AAEA,SAAO;AACT;;;AChDO,IAAM,kBAAN,cAAqD,QAAe;AAAA,EACzE;AAAA,EAEO;AAAA,EACA;AAAA,EAEP,YAAY,WAAmC,MAAM;AACnD,UAAM,mBAAmB,uBAAuB;AAChD,UAAM,CAAC,iBAAiB,mBAAmB;AACzC,uBAAiB,iBAAiB,cAAc;AAChD,iBAAW,iBAAiB,SAAS,iBAAiB,MAAM;AAAA,IAC9D,CAAC;AAED,SAAK,YAAY;AACjB,SAAK,UAAU,KAAK,UAAU;AAC9B,SAAK,SAAS,KAAK,UAAU;AAAA,EAC/B;AAAA,EAEA,IAAW,QAAQ;AACjB,WAAO,KAAK,UAAU;AAAA,EACxB;AAAA,EAEA,IAAW,kBAAkB;AAC3B,WAAO,KAAK,UAAU;AAAA,EACxB;AAAA,EAEO,KACL,aACA,YACA;AACA,WAAO,KAAK,UAAU,MAAM,KAAK,aAAa,UAAU,CAAC;AAAA,EAC3D;AAAA,EAEO,MACL,YACA;AACA,WAAO,KAAK,UAAU,MAAM,MAAM,UAAU,CAAC;AAAA,EAC/C;AAAA,EAEO,QAAQ,WAAuC;AACpD,WAAO,KAAK,UAAU,MAAM,QAAQ,SAAS,CAAC;AAAA,EAChD;AAAA,EAEA,UACE,SACqC;AACrC,WAAO,OAAO,iBAAiB,SAAS;AAAA,MACtC,SAAS,EAAE,cAAc,MAAM,OAAO,KAAK,QAAQ;AAAA,MACnD,QAAQ,EAAE,cAAc,MAAM,OAAO,KAAK,OAAO;AAAA,IACnD,CAAC;AAAA,EACH;AACF;","names":[]}

49
node_modules/@open-draft/deferred-promise/package.json generated vendored Normal file
View file

@ -0,0 +1,49 @@
{
"name": "@open-draft/deferred-promise",
"version": "2.2.0",
"description": "A Promise-compatible abstraction that defers resolving/rejecting promises to another closure.",
"main": "./build/index.js",
"types": "./build/index.d.ts",
"module": "./build/index.mjs",
"exports": {
".": {
"types": "./build/index.d.ts",
"require": "./build/index.js",
"default": "./build/index.mjs"
}
},
"scripts": {
"test": "jest",
"test:compliance": "export NODE_OPTIONS=--loader=tsx || set NODE_OPTIONS=--loader=tsx&& npx -y promises-aplus-tests ./test/aplus-tests-adapter.ts",
"prebuild": "rimraf ./build",
"build": "tsup",
"release": "release publish"
},
"files": [
"./build"
],
"keywords": [
"promise",
"defer",
"deferred",
"resolve",
"reject",
"executor"
],
"author": "Artem Zakharchenko",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/open-draft/deferred-promise"
},
"devDependencies": {
"@ossjs/release": "^0.7.2",
"@types/jest": "^29.0.1",
"jest": "^29.0.3",
"rimraf": "^3.0.2",
"ts-jest": "^29.0.0",
"tsup": "^7.2.0",
"tsx": "^3.12.1",
"typescript": "^4.8.3"
}
}

9
node_modules/@open-draft/logger/LICENSE generated vendored Normal file
View file

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

225
node_modules/@open-draft/logger/README.md generated vendored Normal file
View file

@ -0,0 +1,225 @@
# Logger
Environment-agnostic, ESM-friendly logger for simple needs.
## Why does this exist?
I've been using `debug` for quite some time but wanted to migrate my projects to better ESM support. Alas, `debug` doesn't ship as ESM so I went and wrote this little logger just for my needs. You will likely see it printing useful data in Mock Service Worker and beyond.
## Installation
```sh
npm install @open-draft/logger
```
## Usage
This package has the same API for both browser and Node.js and can run in those environments out of the box.
```js
// app.js
import { Logger } from '@open-draft/logger'
const logger = new Logger('parser')
logger.info('starting parsing...')
logger.warning('found legacy document format')
logger.success('parsed 120 documents!')
```
Logging is disabled by default. To enable logging, provide the `DEBUG` environment variable:
```sh
DEBUG=1 node ./app.js
```
> You can also use `true` instead of `1`. You can also use a specific logger's name to enable [logger filtering](#logger-filtering).
## API
- Class: `Logger`
- [`new Logger(name)`](#new-loggername)
- [`logger.debug(message, ...positionals)`](#loggerdebugmessage-positionals)
- [`logger.info(message, ...positionals)`](#loggerinfomessage-positionals)
- [`logger.success(message, ...positionals)`](#loggersuccessmessage-positionals)
- [`logger.warning(message, ...positionals)`](#loggerwarningmessage-positionals)
- [`logger.error(message, ...positionals)`](#loggererrormessage-positionals)
- [`logger.extend(name)`](#loggerextendprefix)
- [`logger.only(callback)`](#loggeronlycallback)
### `new Logger(name)`
- `name` `string` the name of the logger.
Creates a new instance of the logger. Each message printed by the logger will be prefixed with the given `name`. You can have multiple loggers with different names for different areas of your system.
```js
const logger = new Logger('parser')
```
> You can nest loggers via [`logger.extend()`](#loggerextendprefix).
### `logger.debug(message, ...positionals)`
- `message` `string`
- `positionals` `unknown[]`
Prints a debug message.
```js
logger.debug('no duplicates found, skipping...')
```
```
12:34:56:789 [parser] no duplicates found, skipping...
```
### `logger.info(message, ...positionals)`
- `message` `string`
- `positionals` `unknown[]`
Prints an info message.
```js
logger.info('new parse request')
```
```
12:34:56:789 [parser] new parse request
```
### `logger.success(message, ...positionals)`
- `message` `string`
- `positionals` `unknown[]`
Prints a success message.
```js
logger.success('prased 123 documents!')
```
```
12:34:56:789 ✔ [parser] prased 123 documents!
```
### `logger.warning(message, ...positionals)`
- `message` `string`
- `positionals` `unknown[]`
Prints a warning. In Node.js, prints it to `process.stderr`.
```js
logger.warning('found legacy document format')
```
```
12:34:56:789 ⚠ [parser] found legacy document format
```
### `logger.error(message, ...positionals)`
- `message` `string`
- `positionals` `unknown[]`
Prints an error. In Node.js, prints it to `process.stderr`.
```js
logger.error('failed to parse document')
```
```
12:34:56:789 ✖ [parser] failed to parse document
```
### `logger.extend(prefix)`
- `prefix` `string` Additional prefix to append to the logger's name.
Creates a new logger out of the current one.
```js
const logger = new Logger('parser')
function parseRequest(request) {
const requestLogger = logger.extend(`${request.method} ${request.url}`)
requestLogger.info('start parsing...')
}
```
```
12:34:56:789 [parser] [GET https://example.com] start parsing...
```
### `logger.only(callback)`
Executes a given callback only when the logging is activated. Useful for computing additional information for logs.
```js
logger.only(() => {
const documentSize = getSizeBytes(document)
logger.debug(`document size: ${documentSize}`)
})
```
> You can nest `logger.*` methods in the callback to `logger.only()`.
## Log levels
You can specify the log levels to print using the `LOG_LEVEL` environment variable.
There are the following log levels:
- `debug`
- `info`
- `success`
- `warning`
- `error`
> Providing no log level will print all the messages.
Here's an example of how to print only warnings:
```js
// app.js
import { Logger } from '@open-draft/logger'
const logger = new Logger('parser')
logger.info('some info')
logger.warning('some warning')
logger.error('some error')
```
```js
LOG_LEVEL=warning node ./app.js
```
```
12:34:56:789 ⚠ [parser] some warning
```
## Logger filtering
You can only print a specific logger by providing its name as the `DEBUG` environment variable.
```js
// app.js
import { Logger } from '@open-draft/logger'
const appLogger = new Logger('app')
const parserLogger = new Logger('parser')
appLogger.info('starting app...')
parserLogger.info('creating a new parser...')
```
```sh
DEBUG=app node ./app.js
```
```
12:34:56:789 [app] starting app...
```

83
node_modules/@open-draft/logger/lib/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,83 @@
type ColorFunction = (text: string) => void;
declare function yellow(text: string): string;
declare function blue(text: string): string;
declare function gray(text: string): string;
declare function red(text: string): string;
declare function green(text: string): string;
type colors_ColorFunction = ColorFunction;
declare const colors_blue: typeof blue;
declare const colors_gray: typeof gray;
declare const colors_green: typeof green;
declare const colors_red: typeof red;
declare const colors_yellow: typeof yellow;
declare namespace colors {
export {
colors_ColorFunction as ColorFunction,
colors_blue as blue,
colors_gray as gray,
colors_green as green,
colors_red as red,
colors_yellow as yellow,
};
}
type LogLevel = 'debug' | 'info' | 'success' | 'warning' | 'error';
type LogColors = keyof typeof colors;
interface LogEntry {
timestamp: Date;
level: LogLevel;
message: any;
}
declare class Logger {
private readonly name;
private prefix;
constructor(name: string);
extend(domain: string): Logger;
/**
* Print a debug message.
* @example
* logger.debug('no duplicates found, creating a document...')
*/
debug(message: any, ...positionals: Array<unknown>): void;
/**
* Print an info message.
* @example
* logger.info('start parsing...')
*/
info(message: any, ...positionals: Array<unknown>): (message: any, ...positionals: Array<unknown>) => void;
/**
* Print a success message.
* @example
* logger.success('successfully created document')
*/
success(message: any, ...positionals: Array<unknown>): void;
/**
* Print a warning.
* @example
* logger.warning('found legacy document format')
*/
warning(message: any, ...positionals: Array<unknown>): void;
/**
* Print an error message.
* @example
* logger.error('something went wrong')
*/
error(message: any, ...positionals: Array<unknown>): void;
/**
* Execute the given callback only when the logging is enabled.
* This is skipped in its entirety and has no runtime cost otherwise.
* This executes regardless of the log level.
* @example
* logger.only(() => {
* logger.info('additional info')
* })
*/
only(callback: () => void): void;
private createEntry;
private logEntry;
private formatTimestamp;
private getWriter;
}
export { LogColors, LogEntry, LogLevel, Logger };

295
node_modules/@open-draft/logger/lib/index.js generated vendored Normal file
View file

@ -0,0 +1,295 @@
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);
// src/index.ts
var src_exports = {};
__export(src_exports, {
Logger: () => Logger
});
module.exports = __toCommonJS(src_exports);
var import_is_node_process = require("is-node-process");
var import_outvariant = require("outvariant");
// src/colors.ts
var colors_exports = {};
__export(colors_exports, {
blue: () => blue,
gray: () => gray,
green: () => green,
red: () => red,
yellow: () => yellow
});
function yellow(text) {
return `\x1B[33m${text}\x1B[0m`;
}
function blue(text) {
return `\x1B[34m${text}\x1B[0m`;
}
function gray(text) {
return `\x1B[90m${text}\x1B[0m`;
}
function red(text) {
return `\x1B[31m${text}\x1B[0m`;
}
function green(text) {
return `\x1B[32m${text}\x1B[0m`;
}
// src/index.ts
var IS_NODE = (0, import_is_node_process.isNodeProcess)();
var Logger = class {
constructor(name) {
this.name = name;
this.prefix = `[${this.name}]`;
const LOGGER_NAME = getVariable("DEBUG");
const LOGGER_LEVEL = getVariable("LOG_LEVEL");
const isLoggingEnabled = LOGGER_NAME === "1" || LOGGER_NAME === "true" || typeof LOGGER_NAME !== "undefined" && this.name.startsWith(LOGGER_NAME);
if (isLoggingEnabled) {
this.debug = isDefinedAndNotEquals(LOGGER_LEVEL, "debug") ? noop : this.debug;
this.info = isDefinedAndNotEquals(LOGGER_LEVEL, "info") ? noop : this.info;
this.success = isDefinedAndNotEquals(LOGGER_LEVEL, "success") ? noop : this.success;
this.warning = isDefinedAndNotEquals(LOGGER_LEVEL, "warning") ? noop : this.warning;
this.error = isDefinedAndNotEquals(LOGGER_LEVEL, "error") ? noop : this.error;
} else {
this.info = noop;
this.success = noop;
this.warning = noop;
this.error = noop;
this.only = noop;
}
}
prefix;
extend(domain) {
return new Logger(`${this.name}:${domain}`);
}
/**
* Print a debug message.
* @example
* logger.debug('no duplicates found, creating a document...')
*/
debug(message, ...positionals) {
this.logEntry({
level: "debug",
message: gray(message),
positionals,
prefix: this.prefix,
colors: {
prefix: "gray"
}
});
}
/**
* Print an info message.
* @example
* logger.info('start parsing...')
*/
info(message, ...positionals) {
this.logEntry({
level: "info",
message,
positionals,
prefix: this.prefix,
colors: {
prefix: "blue"
}
});
const performance2 = new PerformanceEntry();
return (message2, ...positionals2) => {
performance2.measure();
this.logEntry({
level: "info",
message: `${message2} ${gray(`${performance2.deltaTime}ms`)}`,
positionals: positionals2,
prefix: this.prefix,
colors: {
prefix: "blue"
}
});
};
}
/**
* Print a success message.
* @example
* logger.success('successfully created document')
*/
success(message, ...positionals) {
this.logEntry({
level: "info",
message,
positionals,
prefix: `\u2714 ${this.prefix}`,
colors: {
timestamp: "green",
prefix: "green"
}
});
}
/**
* Print a warning.
* @example
* logger.warning('found legacy document format')
*/
warning(message, ...positionals) {
this.logEntry({
level: "warning",
message,
positionals,
prefix: `\u26A0 ${this.prefix}`,
colors: {
timestamp: "yellow",
prefix: "yellow"
}
});
}
/**
* Print an error message.
* @example
* logger.error('something went wrong')
*/
error(message, ...positionals) {
this.logEntry({
level: "error",
message,
positionals,
prefix: `\u2716 ${this.prefix}`,
colors: {
timestamp: "red",
prefix: "red"
}
});
}
/**
* Execute the given callback only when the logging is enabled.
* This is skipped in its entirety and has no runtime cost otherwise.
* This executes regardless of the log level.
* @example
* logger.only(() => {
* logger.info('additional info')
* })
*/
only(callback) {
callback();
}
createEntry(level, message) {
return {
timestamp: /* @__PURE__ */ new Date(),
level,
message
};
}
logEntry(args) {
const {
level,
message,
prefix,
colors: customColors,
positionals = []
} = args;
const entry = this.createEntry(level, message);
const timestampColor = customColors?.timestamp || "gray";
const prefixColor = customColors?.prefix || "gray";
const colorize = {
timestamp: colors_exports[timestampColor],
prefix: colors_exports[prefixColor]
};
const write = this.getWriter(level);
write(
[colorize.timestamp(this.formatTimestamp(entry.timestamp))].concat(prefix != null ? colorize.prefix(prefix) : []).concat(serializeInput(message)).join(" "),
...positionals.map(serializeInput)
);
}
formatTimestamp(timestamp) {
return `${timestamp.toLocaleTimeString(
"en-GB"
)}:${timestamp.getMilliseconds()}`;
}
getWriter(level) {
switch (level) {
case "debug":
case "success":
case "info": {
return log;
}
case "warning": {
return warn;
}
case "error": {
return error;
}
}
}
};
var PerformanceEntry = class {
startTime;
endTime;
deltaTime;
constructor() {
this.startTime = performance.now();
}
measure() {
this.endTime = performance.now();
const deltaTime = this.endTime - this.startTime;
this.deltaTime = deltaTime.toFixed(2);
}
};
var noop = () => void 0;
function log(message, ...positionals) {
if (IS_NODE) {
process.stdout.write((0, import_outvariant.format)(message, ...positionals) + "\n");
return;
}
console.log(message, ...positionals);
}
function warn(message, ...positionals) {
if (IS_NODE) {
process.stderr.write((0, import_outvariant.format)(message, ...positionals) + "\n");
return;
}
console.warn(message, ...positionals);
}
function error(message, ...positionals) {
if (IS_NODE) {
process.stderr.write((0, import_outvariant.format)(message, ...positionals) + "\n");
return;
}
console.error(message, ...positionals);
}
function getVariable(variableName) {
if (IS_NODE) {
return process.env[variableName];
}
return globalThis[variableName]?.toString();
}
function isDefinedAndNotEquals(value, expected) {
return value !== void 0 && value !== expected;
}
function serializeInput(message) {
if (typeof message === "undefined") {
return "undefined";
}
if (message === null) {
return "null";
}
if (typeof message === "string") {
return message;
}
if (typeof message === "object") {
return JSON.stringify(message);
}
return message.toString();
}

281
node_modules/@open-draft/logger/lib/index.mjs generated vendored Normal file
View file

@ -0,0 +1,281 @@
var __defProp = Object.defineProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
// src/index.ts
import { isNodeProcess } from "is-node-process";
import { format } from "outvariant";
// src/colors.ts
var colors_exports = {};
__export(colors_exports, {
blue: () => blue,
gray: () => gray,
green: () => green,
red: () => red,
yellow: () => yellow
});
function yellow(text) {
return `\x1B[33m${text}\x1B[0m`;
}
function blue(text) {
return `\x1B[34m${text}\x1B[0m`;
}
function gray(text) {
return `\x1B[90m${text}\x1B[0m`;
}
function red(text) {
return `\x1B[31m${text}\x1B[0m`;
}
function green(text) {
return `\x1B[32m${text}\x1B[0m`;
}
// src/index.ts
var IS_NODE = isNodeProcess();
var Logger = class {
constructor(name) {
this.name = name;
this.prefix = `[${this.name}]`;
const LOGGER_NAME = getVariable("DEBUG");
const LOGGER_LEVEL = getVariable("LOG_LEVEL");
const isLoggingEnabled = LOGGER_NAME === "1" || LOGGER_NAME === "true" || typeof LOGGER_NAME !== "undefined" && this.name.startsWith(LOGGER_NAME);
if (isLoggingEnabled) {
this.debug = isDefinedAndNotEquals(LOGGER_LEVEL, "debug") ? noop : this.debug;
this.info = isDefinedAndNotEquals(LOGGER_LEVEL, "info") ? noop : this.info;
this.success = isDefinedAndNotEquals(LOGGER_LEVEL, "success") ? noop : this.success;
this.warning = isDefinedAndNotEquals(LOGGER_LEVEL, "warning") ? noop : this.warning;
this.error = isDefinedAndNotEquals(LOGGER_LEVEL, "error") ? noop : this.error;
} else {
this.info = noop;
this.success = noop;
this.warning = noop;
this.error = noop;
this.only = noop;
}
}
prefix;
extend(domain) {
return new Logger(`${this.name}:${domain}`);
}
/**
* Print a debug message.
* @example
* logger.debug('no duplicates found, creating a document...')
*/
debug(message, ...positionals) {
this.logEntry({
level: "debug",
message: gray(message),
positionals,
prefix: this.prefix,
colors: {
prefix: "gray"
}
});
}
/**
* Print an info message.
* @example
* logger.info('start parsing...')
*/
info(message, ...positionals) {
this.logEntry({
level: "info",
message,
positionals,
prefix: this.prefix,
colors: {
prefix: "blue"
}
});
const performance2 = new PerformanceEntry();
return (message2, ...positionals2) => {
performance2.measure();
this.logEntry({
level: "info",
message: `${message2} ${gray(`${performance2.deltaTime}ms`)}`,
positionals: positionals2,
prefix: this.prefix,
colors: {
prefix: "blue"
}
});
};
}
/**
* Print a success message.
* @example
* logger.success('successfully created document')
*/
success(message, ...positionals) {
this.logEntry({
level: "info",
message,
positionals,
prefix: `\u2714 ${this.prefix}`,
colors: {
timestamp: "green",
prefix: "green"
}
});
}
/**
* Print a warning.
* @example
* logger.warning('found legacy document format')
*/
warning(message, ...positionals) {
this.logEntry({
level: "warning",
message,
positionals,
prefix: `\u26A0 ${this.prefix}`,
colors: {
timestamp: "yellow",
prefix: "yellow"
}
});
}
/**
* Print an error message.
* @example
* logger.error('something went wrong')
*/
error(message, ...positionals) {
this.logEntry({
level: "error",
message,
positionals,
prefix: `\u2716 ${this.prefix}`,
colors: {
timestamp: "red",
prefix: "red"
}
});
}
/**
* Execute the given callback only when the logging is enabled.
* This is skipped in its entirety and has no runtime cost otherwise.
* This executes regardless of the log level.
* @example
* logger.only(() => {
* logger.info('additional info')
* })
*/
only(callback) {
callback();
}
createEntry(level, message) {
return {
timestamp: /* @__PURE__ */ new Date(),
level,
message
};
}
logEntry(args) {
const {
level,
message,
prefix,
colors: customColors,
positionals = []
} = args;
const entry = this.createEntry(level, message);
const timestampColor = customColors?.timestamp || "gray";
const prefixColor = customColors?.prefix || "gray";
const colorize = {
timestamp: colors_exports[timestampColor],
prefix: colors_exports[prefixColor]
};
const write = this.getWriter(level);
write(
[colorize.timestamp(this.formatTimestamp(entry.timestamp))].concat(prefix != null ? colorize.prefix(prefix) : []).concat(serializeInput(message)).join(" "),
...positionals.map(serializeInput)
);
}
formatTimestamp(timestamp) {
return `${timestamp.toLocaleTimeString(
"en-GB"
)}:${timestamp.getMilliseconds()}`;
}
getWriter(level) {
switch (level) {
case "debug":
case "success":
case "info": {
return log;
}
case "warning": {
return warn;
}
case "error": {
return error;
}
}
}
};
var PerformanceEntry = class {
startTime;
endTime;
deltaTime;
constructor() {
this.startTime = performance.now();
}
measure() {
this.endTime = performance.now();
const deltaTime = this.endTime - this.startTime;
this.deltaTime = deltaTime.toFixed(2);
}
};
var noop = () => void 0;
function log(message, ...positionals) {
if (IS_NODE) {
process.stdout.write(format(message, ...positionals) + "\n");
return;
}
console.log(message, ...positionals);
}
function warn(message, ...positionals) {
if (IS_NODE) {
process.stderr.write(format(message, ...positionals) + "\n");
return;
}
console.warn(message, ...positionals);
}
function error(message, ...positionals) {
if (IS_NODE) {
process.stderr.write(format(message, ...positionals) + "\n");
return;
}
console.error(message, ...positionals);
}
function getVariable(variableName) {
if (IS_NODE) {
return process.env[variableName];
}
return globalThis[variableName]?.toString();
}
function isDefinedAndNotEquals(value, expected) {
return value !== void 0 && value !== expected;
}
function serializeInput(message) {
if (typeof message === "undefined") {
return "undefined";
}
if (message === null) {
return "null";
}
if (typeof message === "string") {
return message;
}
if (typeof message === "object") {
return JSON.stringify(message);
}
return message.toString();
}
export {
Logger
};

56
node_modules/@open-draft/logger/package.json generated vendored Normal file
View file

@ -0,0 +1,56 @@
{
"name": "@open-draft/logger",
"version": "0.3.0",
"description": "Environment-agnostic, ESM-friendly logger for simple needs.",
"main": "./lib/index.js",
"module": "./lib/index.mjs",
"types": "./lib/index.d.ts",
"exports": {
".": {
"types": "./lib/index.d.ts",
"require": "./lib/index.js",
"import": "./lib/index.mjs",
"default": "./lib/index.js"
},
"./package.json": "./package.json"
},
"keywords": [
"log",
"logger",
"logging",
"universal",
"tiny"
],
"files": [
"lib",
"LICENSE",
"README.md"
],
"author": "Artem Zakharchenko",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/open-draft/logger"
},
"devDependencies": {
"@ossjs/release": "^0.5.1",
"@playwright/test": "^1.32.3",
"@types/node": "^18.15.11",
"playwright": "^1.32.3",
"tsup": "^6.7.0",
"typescript": "^5.0.3",
"vitest": "^0.29.8",
"webpack-http-server": "^0.5.0"
},
"dependencies": {
"is-node-process": "^1.2.0",
"outvariant": "^1.4.0"
},
"scripts": {
"build": "tsup",
"test": "pnpm test:node && pnpm test:browser",
"test:node": "vitest run",
"test:browser": "playwright test",
"release": "release publish"
}
}

21
node_modules/@open-draft/until/LICENSE generated vendored Normal file
View file

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

150
node_modules/@open-draft/until/README.md generated vendored Normal file
View file

@ -0,0 +1,150 @@
[![Latest release](https://img.shields.io/npm/v/@open-draft/until.svg)](https://www.npmjs.com/package/@open-draft/until)
# `until`
Gracefully handle a Promise using `async`/`await`.
## Why?
With the addition of `async`/`await` keywords in ECMAScript 2017 the handling of Promises became much easier. However, one must keep in mind that the `await` keyword provides no standard error handling API. Consider this usage:
```js
function getUser(id) {
const data = await fetchUser(id)
// Work with "data"...
}
```
In case `fetchUser()` throws an error, the entire `getUser()` function's scope will terminate. Because of this, it's recommended to implement error handling using `try`/`catch` block wrapping `await` expressions:
```js
function getUser(id)
let data = null
try {
data = await asyncAction()
} catch (error) {
console.error(error)
}
// Work with "data"...
}
```
While this is a semantically valid approach, constructing `try`/`catch` around each awaited operation may be tedious and get overlooked at times. Such error handling also introduces separate closures for execution and error scenarios of an asynchronous operation.
This library encapsulates the `try`/`catch` error handling in a utility function that does not create a separate closure and exposes a NodeJS-friendly API to work with errors and resolved data.
## Getting started
### Install
```bash
npm install @open-draft/until
```
### Usage
```js
import { until } from '@open-draft/until'
async function(id) {
const { error, data } = await until(() => fetchUser(id))
if (error) {
return handleError(error)
}
return data
}
```
### Usage with TypeScript
```ts
import { until } from '@open-draft/until'
interface User {
firstName: string
age: number
}
interface UserFetchError {
type: 'FORBIDDEN' | 'NOT_FOUND'
message?: string
}
async function(id: string) {
const { error, data } = await until<UserFetchError, User>(() => fetchUser(id))
if (error) {
handleError(error.type, error.message)
}
return data.firstName
}
```
## Frequently asked questions
### Why does `until` accept a function and not a `Promise` directly?
This has been intentionally introduced to await a single logical unit as opposed to a single `Promise`.
```js
// Notice how a single "until" invocation can handle
// a rather complex piece of logic. This way any rejections
// or exceptions happening within the given function
// can be handled via the same "error".
const { error, data } = until(async () => {
const user = await fetchUser()
const nextUser = normalizeUser(user)
const transaction = await saveModel('user', user)
invariant(transaction.status === 'OK', 'Saving user failed')
return transaction.result
})
if (error) {
// Handle any exceptions happened within the function.
}
```
### Why does `until` return an object and not an array?
The `until` function used to return an array of shape `[error, data]` prior to `2.0.0`. That has been changed, however, to get proper type-safety using discriminated union type.
Compare these two examples:
```ts
const [error, data] = await until(() => action())
if (error) {
return null
}
// Data still has ambiguous "DataType | null" type here
// even after you've checked and handled the "error" above.
console.log(data)
```
```ts
const result = await until(() => action())
// At this point, "data" is ambiguous "DataType | null"
// which is correct, as you haven't checked nor handled the "error".
if (result.error) {
return null
}
// Data is strict "DataType" since you've handled the "error" above.
console.log(result.data)
```
> It's crucial to keep the entire result of the `Promise` in a single variable and not destructure it. TypeScript will always keep the type of `error` and `data` as it was upon destructuring, ignoring any type guards you may perform later on.
## Special thanks
- [giuseppegurgone](https://twitter.com/giuseppegurgone) for the discussion about the original `until` API.

15
node_modules/@open-draft/until/lib/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,15 @@
type AsyncTuple<ErrorType extends any = Error, DataType extends any = unknown> = {
error: ErrorType;
data: null;
} | {
error: null;
data: DataType;
};
/**
* Gracefully handles a given Promise factory.
* @example
* const { error, data } = await until(() => asyncAction())
*/
declare const until: <ErrorType extends unknown = Error, DataType extends unknown = unknown>(promise: () => Promise<DataType>) => Promise<AsyncTuple<ErrorType, DataType>>;
export { until };

41
node_modules/@open-draft/until/lib/index.js generated vendored Normal file
View file

@ -0,0 +1,41 @@
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);
// src/index.ts
var src_exports = {};
__export(src_exports, {
until: () => until
});
module.exports = __toCommonJS(src_exports);
// src/until.ts
var until = async (promise) => {
try {
const data = await promise().catch((error) => {
throw error;
});
return { error: null, data };
} catch (error) {
return { error, data: null };
}
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
until
});
//# sourceMappingURL=index.js.map

1
node_modules/@open-draft/until/lib/index.js.map generated vendored Normal file
View file

@ -0,0 +1 @@
{"version":3,"sources":["../src/index.ts","../src/until.ts"],"sourcesContent":["export { until } from './until'","export type AsyncTuple<\n ErrorType extends any = Error,\n DataType extends any = unknown,\n> =\n | {\n error: ErrorType\n data: null\n }\n | { error: null; data: DataType }\n\n/**\n * Gracefully handles a given Promise factory.\n * @example\n * const { error, data } = await until(() => asyncAction())\n */\nexport const until = async <\n ErrorType extends any = Error,\n DataType extends any = unknown,\n>(\n promise: () => Promise<DataType>,\n): Promise<AsyncTuple<ErrorType, DataType>> => {\n try {\n const data = await promise().catch((error) => {\n throw error\n })\n return { error: null, data }\n } catch (error) {\n return { error, data: null }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACeO,IAAM,QAAQ,OAInB,YAC6C;AAC7C,MAAI;AACF,UAAM,OAAO,MAAM,QAAQ,EAAE,MAAM,CAAC,UAAU;AAC5C,YAAM;AAAA,IACR,CAAC;AACD,WAAO,EAAE,OAAO,MAAM,KAAK;AAAA,EAC7B,SAAS,OAAP;AACA,WAAO,EAAE,OAAO,MAAM,KAAK;AAAA,EAC7B;AACF;","names":[]}

15
node_modules/@open-draft/until/lib/index.mjs generated vendored Normal file
View file

@ -0,0 +1,15 @@
// src/until.ts
var until = async (promise) => {
try {
const data = await promise().catch((error) => {
throw error;
});
return { error: null, data };
} catch (error) {
return { error, data: null };
}
};
export {
until
};
//# sourceMappingURL=index.mjs.map

1
node_modules/@open-draft/until/lib/index.mjs.map generated vendored Normal file
View file

@ -0,0 +1 @@
{"version":3,"sources":["../src/until.ts"],"sourcesContent":["export type AsyncTuple<\n ErrorType extends any = Error,\n DataType extends any = unknown,\n> =\n | {\n error: ErrorType\n data: null\n }\n | { error: null; data: DataType }\n\n/**\n * Gracefully handles a given Promise factory.\n * @example\n * const { error, data } = await until(() => asyncAction())\n */\nexport const until = async <\n ErrorType extends any = Error,\n DataType extends any = unknown,\n>(\n promise: () => Promise<DataType>,\n): Promise<AsyncTuple<ErrorType, DataType>> => {\n try {\n const data = await promise().catch((error) => {\n throw error\n })\n return { error: null, data }\n } catch (error) {\n return { error, data: null }\n }\n}\n"],"mappings":";AAeO,IAAM,QAAQ,OAInB,YAC6C;AAC7C,MAAI;AACF,UAAM,OAAO,MAAM,QAAQ,EAAE,MAAM,CAAC,UAAU;AAC5C,YAAM;AAAA,IACR,CAAC;AACD,WAAO,EAAE,OAAO,MAAM,KAAK;AAAA,EAC7B,SAAS,OAAP;AACA,WAAO,EAAE,OAAO,MAAM,KAAK;AAAA,EAC7B;AACF;","names":[]}

37
node_modules/@open-draft/until/package.json generated vendored Normal file
View file

@ -0,0 +1,37 @@
{
"name": "@open-draft/until",
"version": "2.1.0",
"description": "Gracefully handle a Promise using async/await.",
"main": "./lib/index.js",
"module": "./lib/index.mjs",
"types": "./lib/index.d.ts",
"exports": {
".": {
"types": "./lib/index.d.ts",
"require": "./lib/index.js",
"import": "./lib/index.mjs",
"default": "./lib/index.mjs"
}
},
"repository": "open-draft/until",
"author": "Artem Zakharchenko <kettanaito@gmail.com>",
"license": "MIT",
"files": [
"README.md",
"lib"
],
"devDependencies": {
"@ossjs/release": "^0.5.1",
"@types/jest": "^26.0.22",
"jest": "^26.6.3",
"ts-jest": "^26.5.4",
"tsup": "^6.2.3",
"typescript": "^4.2.4"
},
"scripts": {
"start": "tsc -w",
"test": "jest",
"build": "tsup",
"release": "release publish"
}
}