Update test framework: fix run_tests.py to support all test files, add auto-import-check for test files

This commit is contained in:
qiaoxinjiu
2026-05-09 15:11:30 +08:00
parent eb053a347f
commit eaba8328da
21739 changed files with 2236758 additions and 719 deletions

66
node_modules/formdata-node/@type/Blob.d.ts generated vendored Normal file
View File

@@ -0,0 +1,66 @@
/*! Based on fetch-blob. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> & David Frank */
import { ReadableStream } from "web-streams-polyfill";
/**
* Reflects minimal valid Blob for BlobParts.
*/
export interface BlobLike {
type: string;
size: number;
slice(start?: number, end?: number, contentType?: string): BlobLike;
arrayBuffer(): Promise<ArrayBuffer>;
[Symbol.toStringTag]: string;
}
export declare type BlobParts = unknown[] | Iterable<unknown>;
export interface BlobPropertyBag {
/**
* The [`MIME type`](https://developer.mozilla.org/en-US/docs/Glossary/MIME_type) of the data that will be stored into the blob.
* The default value is the empty string, (`""`).
*/
type?: string;
}
/**
* The **Blob** object represents a blob, which is a file-like object of immutable, raw data;
* they can be read as text or binary data, or converted into a ReadableStream
* so its methods can be used for processing the data.
*/
export declare class Blob {
#private;
static [Symbol.hasInstance](value: unknown): value is Blob;
/**
* Returns a new [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) object.
* The content of the blob consists of the concatenation of the values given in the parameter array.
*
* @param blobParts An `Array` strings, or [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), [`ArrayBufferView`](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView), [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) objects, or a mix of any of such objects, that will be put inside the [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob).
* @param options An optional object of type `BlobPropertyBag`.
*/
constructor(blobParts?: BlobParts, options?: BlobPropertyBag);
/**
* Returns the [`MIME type`](https://developer.mozilla.org/en-US/docs/Glossary/MIME_type) of the [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File).
*/
get type(): string;
/**
* Returns the size of the [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File) in bytes.
*/
get size(): number;
/**
* Creates and returns a new [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) object which contains data from a subset of the blob on which it's called.
*
* @param start An index into the Blob indicating the first byte to include in the new Blob. If you specify a negative value, it's treated as an offset from the end of the Blob toward the beginning. For example, -10 would be the 10th from last byte in the Blob. The default value is 0. If you specify a value for start that is larger than the size of the source Blob, the returned Blob has size 0 and contains no data.
* @param end An index into the Blob indicating the first byte that will *not* be included in the new Blob (i.e. the byte exactly at this index is not included). If you specify a negative value, it's treated as an offset from the end of the Blob toward the beginning. For example, -10 would be the 10th from last byte in the Blob. The default value is size.
* @param contentType The content type to assign to the new Blob; this will be the value of its type property. The default value is an empty string.
*/
slice(start?: number, end?: number, contentType?: string): Blob;
/**
* Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with a string containing the contents of the blob, interpreted as UTF-8.
*/
text(): Promise<string>;
/**
* Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with the contents of the blob as binary data contained in an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer).
*/
arrayBuffer(): Promise<ArrayBuffer>;
/**
* Returns a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) which upon reading returns the data contained within the [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob).
*/
stream(): ReadableStream<Uint8Array>;
get [Symbol.toStringTag](): string;
}

2
node_modules/formdata-node/@type/BlobPart.d.ts generated vendored Normal file
View File

@@ -0,0 +1,2 @@
import type { Blob, BlobLike } from "./Blob";
export declare type BlobPart = BlobLike | Blob | Uint8Array;

53
node_modules/formdata-node/@type/File.d.ts generated vendored Normal file
View File

@@ -0,0 +1,53 @@
import { Blob, BlobParts as FileBits, BlobPropertyBag } from "./Blob";
export interface FileLike {
/**
* Name of the file referenced by the File object.
*/
readonly name: string;
/**
* Size of the file parts in bytes
*/
readonly size: number;
/**
* Returns the media type ([`MIME`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types)) of the file represented by a `File` object.
*/
readonly type: string;
/**
* The last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date.
*/
readonly lastModified: number;
[Symbol.toStringTag]: string;
/**
* Returns a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) which upon reading returns the data contained within the [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File).
*/
stream(): AsyncIterable<Uint8Array>;
}
export interface FilePropertyBag extends BlobPropertyBag {
/**
* The last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date.
*/
lastModified?: number;
}
/**
* @deprecated Use FilePropertyBag instead.
*/
export declare type FileOptions = FilePropertyBag;
/**
* The **File** interface provides information about files and allows JavaScript to access their content.
*/
export declare class File extends Blob implements FileLike {
#private;
static [Symbol.hasInstance](value: unknown): value is File;
/**
* Creates a new File instance.
*
* @param fileBits An `Array` strings, or [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), [`ArrayBufferView`](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView), [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) objects, or a mix of any of such objects, that will be put inside the [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File).
* @param name The name of the file.
* @param options An options object containing optional attributes for the file.
*/
constructor(fileBits: FileBits, name: string, options?: FilePropertyBag);
get name(): string;
get lastModified(): number;
get webkitRelativePath(): string;
get [Symbol.toStringTag](): string;
}

105
node_modules/formdata-node/@type/FormData.d.ts generated vendored Normal file
View File

@@ -0,0 +1,105 @@
/// <reference types="node" />
import { inspect } from "util";
import { File } from "./File";
/**
* A `string` or `File` that represents a single value from a set of `FormData` key-value pairs.
*/
export declare type FormDataEntryValue = string | File;
/**
* Constructor entries for FormData
*/
export declare type FormDataConstructorEntries = Array<{
name: string;
value: unknown;
fileName?: string;
}>;
/**
* Provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using fetch().
*
* Note that this object is not a part of Node.js, so you might need to check if an HTTP client of your choice support spec-compliant FormData.
* However, if your HTTP client does not support FormData, you can use [`form-data-encoder`](https://npmjs.com/package/form-data-encoder) package to handle "multipart/form-data" encoding.
*/
export declare class FormData {
#private;
static [Symbol.hasInstance](value: unknown): value is FormData;
constructor(entries?: FormDataConstructorEntries);
/**
* Appends a new value onto an existing key inside a FormData object,
* or adds the key if it does not already exist.
*
* The difference between `set()` and `append()` is that if the specified key already exists, `set()` will overwrite all existing values with the new one, whereas `append()` will append the new value onto the end of the existing set of values.
*
* @param name The name of the field whose data is contained in `value`.
* @param value The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob)
or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string.
* @param fileName The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename.
*/
append(name: string, value: unknown, fileName?: string): void;
/**
* Set a new value for an existing key inside FormData,
* or add the new field if it does not already exist.
*
* @param name The name of the field whose data is contained in `value`.
* @param value The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob)
or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string.
* @param fileName The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename.
*
*/
set(name: string, value: unknown, fileName?: string): void;
/**
* Returns the first value associated with a given key from within a `FormData` object.
* If you expect multiple values and want all of them, use the `getAll()` method instead.
*
* @param {string} name A name of the value you want to retrieve.
*
* @returns A `FormDataEntryValue` containing the value. If the key doesn't exist, the method returns null.
*/
get(name: string): FormDataEntryValue | null;
/**
* Returns all the values associated with a given key from within a `FormData` object.
*
* @param {string} name A name of the value you want to retrieve.
*
* @returns An array of `FormDataEntryValue` whose key matches the value passed in the `name` parameter. If the key doesn't exist, the method returns an empty list.
*/
getAll(name: string): FormDataEntryValue[];
/**
* Returns a boolean stating whether a `FormData` object contains a certain key.
*
* @param name A string representing the name of the key you want to test for.
*
* @return A boolean value.
*/
has(name: string): boolean;
/**
* Deletes a key and its value(s) from a `FormData` object.
*
* @param name The name of the key you want to delete.
*/
delete(name: string): void;
/**
* Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all keys contained in this `FormData` object.
* Each key is a `string`.
*/
keys(): Generator<string>;
/**
* Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through the `FormData` key/value pairs.
* The key of each pair is a string; the value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue).
*/
entries(): Generator<[string, FormDataEntryValue]>;
/**
* Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all values contained in this object `FormData` object.
* Each value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue).
*/
values(): Generator<FormDataEntryValue>;
/**
* An alias for FormData#entries()
*/
[Symbol.iterator](): Generator<[string, FormDataEntryValue], any, unknown>;
/**
* Executes given callback function for each field of the FormData instance
*/
forEach(callback: (value: FormDataEntryValue, key: string, form: FormData) => void, thisArg?: unknown): void;
get [Symbol.toStringTag](): string;
[inspect.custom](): string;
}

9
node_modules/formdata-node/@type/blobHelpers.d.ts generated vendored Normal file
View File

@@ -0,0 +1,9 @@
/*! Based on fetch-blob. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> & David Frank */
import type { BlobPart } from "./BlobPart";
/**
* Creates an iterator allowing to go through blob parts and consume their content
*
* @param parts blob parts from Blob class
*/
export declare function consumeBlobParts(parts: BlobPart[], clone?: boolean): AsyncGenerator<Uint8Array, void>;
export declare function sliceBlob(blobParts: BlobPart[], blobSize: number, start?: number, end?: number): Generator<BlobPart, void>;

10
node_modules/formdata-node/@type/browser.d.ts generated vendored Normal file
View File

@@ -0,0 +1,10 @@
export declare const FormData: {
new (form?: HTMLFormElement | undefined): FormData;
prototype: FormData;
}, Blob: {
new (blobParts?: BlobPart[] | undefined, options?: BlobPropertyBag | undefined): Blob;
prototype: Blob;
}, File: {
new (fileBits: BlobPart[], fileName: string, options?: FilePropertyBag | undefined): File;
prototype: File;
};

View File

@@ -0,0 +1 @@
export declare const deprecateConstructorEntries: () => void;

55
node_modules/formdata-node/@type/fileFromPath.d.ts generated vendored Normal file
View File

@@ -0,0 +1,55 @@
import { File, FilePropertyBag } from "./File";
export * from "./isFile";
export declare type FileFromPathOptions = Omit<FilePropertyBag, "lastModified">;
/**
* Creates a `File` referencing the one on a disk by given path. Synchronous version of the `fileFromPath`
*
* @param path Path to a file
* @param filename Optional name of the file. Will be passed as the second argument in `File` constructor. If not presented, the name will be taken from the file's path.
* @param options Additional `File` options, except for `lastModified`.
*
* @example
*
* ```js
* import {FormData, File} from "formdata-node"
* import {fileFromPathSync} from "formdata-node/file-from-path"
*
* const form = new FormData()
*
* const file = fileFromPathSync("/path/to/some/file.txt")
*
* form.set("file", file)
*
* form.get("file") // -> Your `File` object
* ```
*/
export declare function fileFromPathSync(path: string): File;
export declare function fileFromPathSync(path: string, filename?: string): File;
export declare function fileFromPathSync(path: string, options?: FileFromPathOptions): File;
export declare function fileFromPathSync(path: string, filename?: string, options?: FileFromPathOptions): File;
/**
* Creates a `File` referencing the one on a disk by given path.
*
* @param path Path to a file
* @param filename Optional name of the file. Will be passed as the second argument in `File` constructor. If not presented, the name will be taken from the file's path.
* @param options Additional `File` options, except for `lastModified`.
*
* @example
*
* ```js
* import {FormData, File} from "formdata-node"
* import {fileFromPath} from "formdata-node/file-from-path"
*
* const form = new FormData()
*
* const file = await fileFromPath("/path/to/some/file.txt")
*
* form.set("file", file)
*
* form.get("file") // -> Your `File` object
* ```
*/
export declare function fileFromPath(path: string): Promise<File>;
export declare function fileFromPath(path: string, filename?: string): Promise<File>;
export declare function fileFromPath(path: string, options?: FileFromPathOptions): Promise<File>;
export declare function fileFromPath(path: string, filename?: string, options?: FileFromPathOptions): Promise<File>;

3
node_modules/formdata-node/@type/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,3 @@
export * from "./FormData";
export * from "./Blob";
export * from "./File";

2
node_modules/formdata-node/@type/isBlob.d.ts generated vendored Normal file
View File

@@ -0,0 +1,2 @@
import { Blob } from "./Blob";
export declare const isBlob: (value: unknown) => value is Blob;

7
node_modules/formdata-node/@type/isFile.d.ts generated vendored Normal file
View File

@@ -0,0 +1,7 @@
import { File } from "./File";
/**
* Checks if given value is a File, Blob or file-look-a-like object.
*
* @param value A value to test
*/
export declare const isFile: (value: unknown) => value is File;

1
node_modules/formdata-node/@type/isFunction.d.ts generated vendored Normal file
View File

@@ -0,0 +1 @@
export declare const isFunction: (value: unknown) => value is Function;

2
node_modules/formdata-node/@type/isPlainObject.d.ts generated vendored Normal file
View File

@@ -0,0 +1,2 @@
declare function isPlainObject(value: unknown): value is object;
export default isPlainObject;

122
node_modules/formdata-node/lib/cjs/Blob.js generated vendored Normal file
View File

@@ -0,0 +1,122 @@
"use strict";
/*! Based on fetch-blob. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> & David Frank */
var __classPrivateFieldGet = (this && this.__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);
};
var __classPrivateFieldSet = (this && this.__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;
};
var _Blob_parts, _Blob_type, _Blob_size;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Blob = void 0;
const web_streams_polyfill_1 = require("web-streams-polyfill");
const isFunction_1 = require("./isFunction");
const blobHelpers_1 = require("./blobHelpers");
class Blob {
constructor(blobParts = [], options = {}) {
_Blob_parts.set(this, []);
_Blob_type.set(this, "");
_Blob_size.set(this, 0);
options !== null && options !== void 0 ? options : (options = {});
if (typeof blobParts !== "object" || blobParts === null) {
throw new TypeError("Failed to construct 'Blob': "
+ "The provided value cannot be converted to a sequence.");
}
if (!(0, isFunction_1.isFunction)(blobParts[Symbol.iterator])) {
throw new TypeError("Failed to construct 'Blob': "
+ "The object must have a callable @@iterator property.");
}
if (typeof options !== "object" && !(0, isFunction_1.isFunction)(options)) {
throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.");
}
const encoder = new TextEncoder();
for (const raw of blobParts) {
let part;
if (ArrayBuffer.isView(raw)) {
part = new Uint8Array(raw.buffer.slice(raw.byteOffset, raw.byteOffset + raw.byteLength));
}
else if (raw instanceof ArrayBuffer) {
part = new Uint8Array(raw.slice(0));
}
else if (raw instanceof Blob) {
part = raw;
}
else {
part = encoder.encode(String(raw));
}
__classPrivateFieldSet(this, _Blob_size, __classPrivateFieldGet(this, _Blob_size, "f") + (ArrayBuffer.isView(part) ? part.byteLength : part.size), "f");
__classPrivateFieldGet(this, _Blob_parts, "f").push(part);
}
const type = options.type === undefined ? "" : String(options.type);
__classPrivateFieldSet(this, _Blob_type, /^[\x20-\x7E]*$/.test(type) ? type : "", "f");
}
static [(_Blob_parts = new WeakMap(), _Blob_type = new WeakMap(), _Blob_size = new WeakMap(), Symbol.hasInstance)](value) {
return Boolean(value
&& typeof value === "object"
&& (0, isFunction_1.isFunction)(value.constructor)
&& ((0, isFunction_1.isFunction)(value.stream)
|| (0, isFunction_1.isFunction)(value.arrayBuffer))
&& /^(Blob|File)$/.test(value[Symbol.toStringTag]));
}
get type() {
return __classPrivateFieldGet(this, _Blob_type, "f");
}
get size() {
return __classPrivateFieldGet(this, _Blob_size, "f");
}
slice(start, end, contentType) {
return new Blob((0, blobHelpers_1.sliceBlob)(__classPrivateFieldGet(this, _Blob_parts, "f"), this.size, start, end), {
type: contentType
});
}
async text() {
const decoder = new TextDecoder();
let result = "";
for await (const chunk of (0, blobHelpers_1.consumeBlobParts)(__classPrivateFieldGet(this, _Blob_parts, "f"))) {
result += decoder.decode(chunk, { stream: true });
}
result += decoder.decode();
return result;
}
async arrayBuffer() {
const view = new Uint8Array(this.size);
let offset = 0;
for await (const chunk of (0, blobHelpers_1.consumeBlobParts)(__classPrivateFieldGet(this, _Blob_parts, "f"))) {
view.set(chunk, offset);
offset += chunk.length;
}
return view.buffer;
}
stream() {
const iterator = (0, blobHelpers_1.consumeBlobParts)(__classPrivateFieldGet(this, _Blob_parts, "f"), true);
return new web_streams_polyfill_1.ReadableStream({
async pull(controller) {
const { value, done } = await iterator.next();
if (done) {
return queueMicrotask(() => controller.close());
}
controller.enqueue(value);
},
async cancel() {
await iterator.return();
}
});
}
get [Symbol.toStringTag]() {
return "Blob";
}
}
exports.Blob = Blob;
Object.defineProperties(Blob.prototype, {
type: { enumerable: true },
size: { enumerable: true },
slice: { enumerable: true },
stream: { enumerable: true },
text: { enumerable: true },
arrayBuffer: { enumerable: true }
});

2
node_modules/formdata-node/lib/cjs/BlobPart.js generated vendored Normal file
View File

@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

52
node_modules/formdata-node/lib/cjs/File.js generated vendored Normal file
View File

@@ -0,0 +1,52 @@
"use strict";
var __classPrivateFieldSet = (this && this.__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;
};
var __classPrivateFieldGet = (this && this.__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);
};
var _File_name, _File_lastModified;
Object.defineProperty(exports, "__esModule", { value: true });
exports.File = void 0;
const Blob_1 = require("./Blob");
class File extends Blob_1.Blob {
constructor(fileBits, name, options = {}) {
super(fileBits, options);
_File_name.set(this, void 0);
_File_lastModified.set(this, 0);
if (arguments.length < 2) {
throw new TypeError("Failed to construct 'File': 2 arguments required, "
+ `but only ${arguments.length} present.`);
}
__classPrivateFieldSet(this, _File_name, String(name), "f");
const lastModified = options.lastModified === undefined
? Date.now()
: Number(options.lastModified);
if (!Number.isNaN(lastModified)) {
__classPrivateFieldSet(this, _File_lastModified, lastModified, "f");
}
}
static [(_File_name = new WeakMap(), _File_lastModified = new WeakMap(), Symbol.hasInstance)](value) {
return value instanceof Blob_1.Blob
&& value[Symbol.toStringTag] === "File"
&& typeof value.name === "string";
}
get name() {
return __classPrivateFieldGet(this, _File_name, "f");
}
get lastModified() {
return __classPrivateFieldGet(this, _File_lastModified, "f");
}
get webkitRelativePath() {
return "";
}
get [Symbol.toStringTag]() {
return "File";
}
}
exports.File = File;

148
node_modules/formdata-node/lib/cjs/FormData.js generated vendored Normal file
View File

@@ -0,0 +1,148 @@
"use strict";
var __classPrivateFieldGet = (this && this.__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);
};
var _FormData_instances, _FormData_entries, _FormData_setEntry;
Object.defineProperty(exports, "__esModule", { value: true });
exports.FormData = void 0;
const util_1 = require("util");
const File_1 = require("./File");
const isFile_1 = require("./isFile");
const isBlob_1 = require("./isBlob");
const isFunction_1 = require("./isFunction");
const deprecateConstructorEntries_1 = require("./deprecateConstructorEntries");
class FormData {
constructor(entries) {
_FormData_instances.add(this);
_FormData_entries.set(this, new Map());
if (entries) {
(0, deprecateConstructorEntries_1.deprecateConstructorEntries)();
entries.forEach(({ name, value, fileName }) => this.append(name, value, fileName));
}
}
static [(_FormData_entries = new WeakMap(), _FormData_instances = new WeakSet(), Symbol.hasInstance)](value) {
return Boolean(value
&& (0, isFunction_1.isFunction)(value.constructor)
&& value[Symbol.toStringTag] === "FormData"
&& (0, isFunction_1.isFunction)(value.append)
&& (0, isFunction_1.isFunction)(value.set)
&& (0, isFunction_1.isFunction)(value.get)
&& (0, isFunction_1.isFunction)(value.getAll)
&& (0, isFunction_1.isFunction)(value.has)
&& (0, isFunction_1.isFunction)(value.delete)
&& (0, isFunction_1.isFunction)(value.entries)
&& (0, isFunction_1.isFunction)(value.values)
&& (0, isFunction_1.isFunction)(value.keys)
&& (0, isFunction_1.isFunction)(value[Symbol.iterator])
&& (0, isFunction_1.isFunction)(value.forEach));
}
append(name, value, fileName) {
__classPrivateFieldGet(this, _FormData_instances, "m", _FormData_setEntry).call(this, {
name,
fileName,
append: true,
rawValue: value,
argsLength: arguments.length
});
}
set(name, value, fileName) {
__classPrivateFieldGet(this, _FormData_instances, "m", _FormData_setEntry).call(this, {
name,
fileName,
append: false,
rawValue: value,
argsLength: arguments.length
});
}
get(name) {
const field = __classPrivateFieldGet(this, _FormData_entries, "f").get(String(name));
if (!field) {
return null;
}
return field[0];
}
getAll(name) {
const field = __classPrivateFieldGet(this, _FormData_entries, "f").get(String(name));
if (!field) {
return [];
}
return field.slice();
}
has(name) {
return __classPrivateFieldGet(this, _FormData_entries, "f").has(String(name));
}
delete(name) {
__classPrivateFieldGet(this, _FormData_entries, "f").delete(String(name));
}
*keys() {
for (const key of __classPrivateFieldGet(this, _FormData_entries, "f").keys()) {
yield key;
}
}
*entries() {
for (const name of this.keys()) {
const values = this.getAll(name);
for (const value of values) {
yield [name, value];
}
}
}
*values() {
for (const [, value] of this) {
yield value;
}
}
[(_FormData_setEntry = function _FormData_setEntry({ name, rawValue, append, fileName, argsLength }) {
const methodName = append ? "append" : "set";
if (argsLength < 2) {
throw new TypeError(`Failed to execute '${methodName}' on 'FormData': `
+ `2 arguments required, but only ${argsLength} present.`);
}
name = String(name);
let value;
if ((0, isFile_1.isFile)(rawValue)) {
value = fileName === undefined
? rawValue
: new File_1.File([rawValue], fileName, {
type: rawValue.type,
lastModified: rawValue.lastModified
});
}
else if ((0, isBlob_1.isBlob)(rawValue)) {
value = new File_1.File([rawValue], fileName === undefined ? "blob" : fileName, {
type: rawValue.type
});
}
else if (fileName) {
throw new TypeError(`Failed to execute '${methodName}' on 'FormData': `
+ "parameter 2 is not of type 'Blob'.");
}
else {
value = String(rawValue);
}
const values = __classPrivateFieldGet(this, _FormData_entries, "f").get(name);
if (!values) {
return void __classPrivateFieldGet(this, _FormData_entries, "f").set(name, [value]);
}
if (!append) {
return void __classPrivateFieldGet(this, _FormData_entries, "f").set(name, [value]);
}
values.push(value);
}, Symbol.iterator)]() {
return this.entries();
}
forEach(callback, thisArg) {
for (const [name, value] of this) {
callback.call(thisArg, value, name, this);
}
}
get [Symbol.toStringTag]() {
return "FormData";
}
[util_1.inspect.custom]() {
return this[Symbol.toStringTag];
}
}
exports.FormData = FormData;

80
node_modules/formdata-node/lib/cjs/blobHelpers.js generated vendored Normal file
View File

@@ -0,0 +1,80 @@
"use strict";
/*! Based on fetch-blob. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> & David Frank */
Object.defineProperty(exports, "__esModule", { value: true });
exports.sliceBlob = exports.consumeBlobParts = void 0;
const isFunction_1 = require("./isFunction");
const CHUNK_SIZE = 65536;
async function* clonePart(part) {
const end = part.byteOffset + part.byteLength;
let position = part.byteOffset;
while (position !== end) {
const size = Math.min(end - position, CHUNK_SIZE);
const chunk = part.buffer.slice(position, position + size);
position += chunk.byteLength;
yield new Uint8Array(chunk);
}
}
async function* consumeNodeBlob(blob) {
let position = 0;
while (position !== blob.size) {
const chunk = blob.slice(position, Math.min(blob.size, position + CHUNK_SIZE));
const buffer = await chunk.arrayBuffer();
position += buffer.byteLength;
yield new Uint8Array(buffer);
}
}
async function* consumeBlobParts(parts, clone = false) {
for (const part of parts) {
if (ArrayBuffer.isView(part)) {
if (clone) {
yield* clonePart(part);
}
else {
yield part;
}
}
else if ((0, isFunction_1.isFunction)(part.stream)) {
yield* part.stream();
}
else {
yield* consumeNodeBlob(part);
}
}
}
exports.consumeBlobParts = consumeBlobParts;
function* sliceBlob(blobParts, blobSize, start = 0, end) {
end !== null && end !== void 0 ? end : (end = blobSize);
let relativeStart = start < 0
? Math.max(blobSize + start, 0)
: Math.min(start, blobSize);
let relativeEnd = end < 0
? Math.max(blobSize + end, 0)
: Math.min(end, blobSize);
const span = Math.max(relativeEnd - relativeStart, 0);
let added = 0;
for (const part of blobParts) {
if (added >= span) {
break;
}
const partSize = ArrayBuffer.isView(part) ? part.byteLength : part.size;
if (relativeStart && partSize <= relativeStart) {
relativeStart -= partSize;
relativeEnd -= partSize;
}
else {
let chunk;
if (ArrayBuffer.isView(part)) {
chunk = part.subarray(relativeStart, Math.min(partSize, relativeEnd));
added += chunk.byteLength;
}
else {
chunk = part.slice(relativeStart, Math.min(partSize, relativeEnd));
added += chunk.size;
}
relativeEnd -= partSize;
relativeStart = 0;
yield chunk;
}
}
}
exports.sliceBlob = sliceBlob;

13
node_modules/formdata-node/lib/cjs/browser.js generated vendored Normal file
View File

@@ -0,0 +1,13 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.File = exports.Blob = exports.FormData = void 0;
const globalObject = (function () {
if (typeof globalThis !== "undefined") {
return globalThis;
}
if (typeof self !== "undefined") {
return self;
}
return window;
}());
exports.FormData = globalObject.FormData, exports.Blob = globalObject.Blob, exports.File = globalObject.File;

View File

@@ -0,0 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.deprecateConstructorEntries = void 0;
const util_1 = require("util");
exports.deprecateConstructorEntries = (0, util_1.deprecate)(() => { }, "Constructor \"entries\" argument is not spec-compliant "
+ "and will be removed in next major release.");

97
node_modules/formdata-node/lib/cjs/fileFromPath.js generated vendored Normal file
View File

@@ -0,0 +1,97 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
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);
};
var __classPrivateFieldSet = (this && this.__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;
};
var __classPrivateFieldGet = (this && this.__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);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
var _FileFromPath_path, _FileFromPath_start;
Object.defineProperty(exports, "__esModule", { value: true });
exports.fileFromPath = exports.fileFromPathSync = void 0;
const fs_1 = require("fs");
const path_1 = require("path");
const node_domexception_1 = __importDefault(require("node-domexception"));
const File_1 = require("./File");
const isPlainObject_1 = __importDefault(require("./isPlainObject"));
__exportStar(require("./isFile"), exports);
const MESSAGE = "The requested file could not be read, "
+ "typically due to permission problems that have occurred after a reference "
+ "to a file was acquired.";
class FileFromPath {
constructor(input) {
_FileFromPath_path.set(this, void 0);
_FileFromPath_start.set(this, void 0);
__classPrivateFieldSet(this, _FileFromPath_path, input.path, "f");
__classPrivateFieldSet(this, _FileFromPath_start, input.start || 0, "f");
this.name = (0, path_1.basename)(__classPrivateFieldGet(this, _FileFromPath_path, "f"));
this.size = input.size;
this.lastModified = input.lastModified;
}
slice(start, end) {
return new FileFromPath({
path: __classPrivateFieldGet(this, _FileFromPath_path, "f"),
lastModified: this.lastModified,
size: end - start,
start
});
}
async *stream() {
const { mtimeMs } = await fs_1.promises.stat(__classPrivateFieldGet(this, _FileFromPath_path, "f"));
if (mtimeMs > this.lastModified) {
throw new node_domexception_1.default(MESSAGE, "NotReadableError");
}
if (this.size) {
yield* (0, fs_1.createReadStream)(__classPrivateFieldGet(this, _FileFromPath_path, "f"), {
start: __classPrivateFieldGet(this, _FileFromPath_start, "f"),
end: __classPrivateFieldGet(this, _FileFromPath_start, "f") + this.size - 1
});
}
}
get [(_FileFromPath_path = new WeakMap(), _FileFromPath_start = new WeakMap(), Symbol.toStringTag)]() {
return "File";
}
}
function createFileFromPath(path, { mtimeMs, size }, filenameOrOptions, options = {}) {
let filename;
if ((0, isPlainObject_1.default)(filenameOrOptions)) {
[options, filename] = [filenameOrOptions, undefined];
}
else {
filename = filenameOrOptions;
}
const file = new FileFromPath({ path, size, lastModified: mtimeMs });
if (!filename) {
filename = file.name;
}
return new File_1.File([file], filename, {
...options, lastModified: file.lastModified
});
}
function fileFromPathSync(path, filenameOrOptions, options = {}) {
const stats = (0, fs_1.statSync)(path);
return createFileFromPath(path, stats, filenameOrOptions, options);
}
exports.fileFromPathSync = fileFromPathSync;
async function fileFromPath(path, filenameOrOptions, options) {
const stats = await fs_1.promises.stat(path);
return createFileFromPath(path, stats, filenameOrOptions, options);
}
exports.fileFromPath = fileFromPath;

15
node_modules/formdata-node/lib/cjs/index.js generated vendored Normal file
View File

@@ -0,0 +1,15 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
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 });
__exportStar(require("./FormData"), exports);
__exportStar(require("./Blob"), exports);
__exportStar(require("./File"), exports);

6
node_modules/formdata-node/lib/cjs/isBlob.js generated vendored Normal file
View File

@@ -0,0 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isBlob = void 0;
const Blob_1 = require("./Blob");
const isBlob = (value) => value instanceof Blob_1.Blob;
exports.isBlob = isBlob;

6
node_modules/formdata-node/lib/cjs/isFile.js generated vendored Normal file
View File

@@ -0,0 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isFile = void 0;
const File_1 = require("./File");
const isFile = (value) => value instanceof File_1.File;
exports.isFile = isFile;

5
node_modules/formdata-node/lib/cjs/isFunction.js generated vendored Normal file
View File

@@ -0,0 +1,5 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isFunction = void 0;
const isFunction = (value) => (typeof value === "function");
exports.isFunction = isFunction;

15
node_modules/formdata-node/lib/cjs/isPlainObject.js generated vendored Normal file
View File

@@ -0,0 +1,15 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const getType = (value) => (Object.prototype.toString.call(value).slice(8, -1).toLowerCase());
function isPlainObject(value) {
if (getType(value) !== "object") {
return false;
}
const pp = Object.getPrototypeOf(value);
if (pp === null || pp === undefined) {
return true;
}
const Ctor = pp.constructor && pp.constructor.toString();
return Ctor === Object.toString();
}
exports.default = isPlainObject;

3
node_modules/formdata-node/lib/cjs/package.json generated vendored Normal file
View File

@@ -0,0 +1,3 @@
{
"type": "commonjs"
}

118
node_modules/formdata-node/lib/esm/Blob.js generated vendored Normal file
View File

@@ -0,0 +1,118 @@
/*! Based on fetch-blob. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> & David Frank */
var __classPrivateFieldGet = (this && this.__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);
};
var __classPrivateFieldSet = (this && this.__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;
};
var _Blob_parts, _Blob_type, _Blob_size;
import { ReadableStream } from "web-streams-polyfill";
import { isFunction } from "./isFunction.js";
import { consumeBlobParts, sliceBlob } from "./blobHelpers.js";
export class Blob {
constructor(blobParts = [], options = {}) {
_Blob_parts.set(this, []);
_Blob_type.set(this, "");
_Blob_size.set(this, 0);
options !== null && options !== void 0 ? options : (options = {});
if (typeof blobParts !== "object" || blobParts === null) {
throw new TypeError("Failed to construct 'Blob': "
+ "The provided value cannot be converted to a sequence.");
}
if (!isFunction(blobParts[Symbol.iterator])) {
throw new TypeError("Failed to construct 'Blob': "
+ "The object must have a callable @@iterator property.");
}
if (typeof options !== "object" && !isFunction(options)) {
throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.");
}
const encoder = new TextEncoder();
for (const raw of blobParts) {
let part;
if (ArrayBuffer.isView(raw)) {
part = new Uint8Array(raw.buffer.slice(raw.byteOffset, raw.byteOffset + raw.byteLength));
}
else if (raw instanceof ArrayBuffer) {
part = new Uint8Array(raw.slice(0));
}
else if (raw instanceof Blob) {
part = raw;
}
else {
part = encoder.encode(String(raw));
}
__classPrivateFieldSet(this, _Blob_size, __classPrivateFieldGet(this, _Blob_size, "f") + (ArrayBuffer.isView(part) ? part.byteLength : part.size), "f");
__classPrivateFieldGet(this, _Blob_parts, "f").push(part);
}
const type = options.type === undefined ? "" : String(options.type);
__classPrivateFieldSet(this, _Blob_type, /^[\x20-\x7E]*$/.test(type) ? type : "", "f");
}
static [(_Blob_parts = new WeakMap(), _Blob_type = new WeakMap(), _Blob_size = new WeakMap(), Symbol.hasInstance)](value) {
return Boolean(value
&& typeof value === "object"
&& isFunction(value.constructor)
&& (isFunction(value.stream)
|| isFunction(value.arrayBuffer))
&& /^(Blob|File)$/.test(value[Symbol.toStringTag]));
}
get type() {
return __classPrivateFieldGet(this, _Blob_type, "f");
}
get size() {
return __classPrivateFieldGet(this, _Blob_size, "f");
}
slice(start, end, contentType) {
return new Blob(sliceBlob(__classPrivateFieldGet(this, _Blob_parts, "f"), this.size, start, end), {
type: contentType
});
}
async text() {
const decoder = new TextDecoder();
let result = "";
for await (const chunk of consumeBlobParts(__classPrivateFieldGet(this, _Blob_parts, "f"))) {
result += decoder.decode(chunk, { stream: true });
}
result += decoder.decode();
return result;
}
async arrayBuffer() {
const view = new Uint8Array(this.size);
let offset = 0;
for await (const chunk of consumeBlobParts(__classPrivateFieldGet(this, _Blob_parts, "f"))) {
view.set(chunk, offset);
offset += chunk.length;
}
return view.buffer;
}
stream() {
const iterator = consumeBlobParts(__classPrivateFieldGet(this, _Blob_parts, "f"), true);
return new ReadableStream({
async pull(controller) {
const { value, done } = await iterator.next();
if (done) {
return queueMicrotask(() => controller.close());
}
controller.enqueue(value);
},
async cancel() {
await iterator.return();
}
});
}
get [Symbol.toStringTag]() {
return "Blob";
}
}
Object.defineProperties(Blob.prototype, {
type: { enumerable: true },
size: { enumerable: true },
slice: { enumerable: true },
stream: { enumerable: true },
text: { enumerable: true },
arrayBuffer: { enumerable: true }
});

1
node_modules/formdata-node/lib/esm/BlobPart.js generated vendored Normal file
View File

@@ -0,0 +1 @@
export {};

48
node_modules/formdata-node/lib/esm/File.js generated vendored Normal file
View File

@@ -0,0 +1,48 @@
var __classPrivateFieldSet = (this && this.__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;
};
var __classPrivateFieldGet = (this && this.__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);
};
var _File_name, _File_lastModified;
import { Blob } from "./Blob.js";
export class File extends Blob {
constructor(fileBits, name, options = {}) {
super(fileBits, options);
_File_name.set(this, void 0);
_File_lastModified.set(this, 0);
if (arguments.length < 2) {
throw new TypeError("Failed to construct 'File': 2 arguments required, "
+ `but only ${arguments.length} present.`);
}
__classPrivateFieldSet(this, _File_name, String(name), "f");
const lastModified = options.lastModified === undefined
? Date.now()
: Number(options.lastModified);
if (!Number.isNaN(lastModified)) {
__classPrivateFieldSet(this, _File_lastModified, lastModified, "f");
}
}
static [(_File_name = new WeakMap(), _File_lastModified = new WeakMap(), Symbol.hasInstance)](value) {
return value instanceof Blob
&& value[Symbol.toStringTag] === "File"
&& typeof value.name === "string";
}
get name() {
return __classPrivateFieldGet(this, _File_name, "f");
}
get lastModified() {
return __classPrivateFieldGet(this, _File_lastModified, "f");
}
get webkitRelativePath() {
return "";
}
get [Symbol.toStringTag]() {
return "File";
}
}

144
node_modules/formdata-node/lib/esm/FormData.js generated vendored Normal file
View File

@@ -0,0 +1,144 @@
var __classPrivateFieldGet = (this && this.__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);
};
var _FormData_instances, _FormData_entries, _FormData_setEntry;
import { inspect } from "util";
import { File } from "./File.js";
import { isFile } from "./isFile.js";
import { isBlob } from "./isBlob.js";
import { isFunction } from "./isFunction.js";
import { deprecateConstructorEntries } from "./deprecateConstructorEntries.js";
export class FormData {
constructor(entries) {
_FormData_instances.add(this);
_FormData_entries.set(this, new Map());
if (entries) {
deprecateConstructorEntries();
entries.forEach(({ name, value, fileName }) => this.append(name, value, fileName));
}
}
static [(_FormData_entries = new WeakMap(), _FormData_instances = new WeakSet(), Symbol.hasInstance)](value) {
return Boolean(value
&& isFunction(value.constructor)
&& value[Symbol.toStringTag] === "FormData"
&& isFunction(value.append)
&& isFunction(value.set)
&& isFunction(value.get)
&& isFunction(value.getAll)
&& isFunction(value.has)
&& isFunction(value.delete)
&& isFunction(value.entries)
&& isFunction(value.values)
&& isFunction(value.keys)
&& isFunction(value[Symbol.iterator])
&& isFunction(value.forEach));
}
append(name, value, fileName) {
__classPrivateFieldGet(this, _FormData_instances, "m", _FormData_setEntry).call(this, {
name,
fileName,
append: true,
rawValue: value,
argsLength: arguments.length
});
}
set(name, value, fileName) {
__classPrivateFieldGet(this, _FormData_instances, "m", _FormData_setEntry).call(this, {
name,
fileName,
append: false,
rawValue: value,
argsLength: arguments.length
});
}
get(name) {
const field = __classPrivateFieldGet(this, _FormData_entries, "f").get(String(name));
if (!field) {
return null;
}
return field[0];
}
getAll(name) {
const field = __classPrivateFieldGet(this, _FormData_entries, "f").get(String(name));
if (!field) {
return [];
}
return field.slice();
}
has(name) {
return __classPrivateFieldGet(this, _FormData_entries, "f").has(String(name));
}
delete(name) {
__classPrivateFieldGet(this, _FormData_entries, "f").delete(String(name));
}
*keys() {
for (const key of __classPrivateFieldGet(this, _FormData_entries, "f").keys()) {
yield key;
}
}
*entries() {
for (const name of this.keys()) {
const values = this.getAll(name);
for (const value of values) {
yield [name, value];
}
}
}
*values() {
for (const [, value] of this) {
yield value;
}
}
[(_FormData_setEntry = function _FormData_setEntry({ name, rawValue, append, fileName, argsLength }) {
const methodName = append ? "append" : "set";
if (argsLength < 2) {
throw new TypeError(`Failed to execute '${methodName}' on 'FormData': `
+ `2 arguments required, but only ${argsLength} present.`);
}
name = String(name);
let value;
if (isFile(rawValue)) {
value = fileName === undefined
? rawValue
: new File([rawValue], fileName, {
type: rawValue.type,
lastModified: rawValue.lastModified
});
}
else if (isBlob(rawValue)) {
value = new File([rawValue], fileName === undefined ? "blob" : fileName, {
type: rawValue.type
});
}
else if (fileName) {
throw new TypeError(`Failed to execute '${methodName}' on 'FormData': `
+ "parameter 2 is not of type 'Blob'.");
}
else {
value = String(rawValue);
}
const values = __classPrivateFieldGet(this, _FormData_entries, "f").get(name);
if (!values) {
return void __classPrivateFieldGet(this, _FormData_entries, "f").set(name, [value]);
}
if (!append) {
return void __classPrivateFieldGet(this, _FormData_entries, "f").set(name, [value]);
}
values.push(value);
}, Symbol.iterator)]() {
return this.entries();
}
forEach(callback, thisArg) {
for (const [name, value] of this) {
callback.call(thisArg, value, name, this);
}
}
get [Symbol.toStringTag]() {
return "FormData";
}
[inspect.custom]() {
return this[Symbol.toStringTag];
}
}

75
node_modules/formdata-node/lib/esm/blobHelpers.js generated vendored Normal file
View File

@@ -0,0 +1,75 @@
/*! Based on fetch-blob. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> & David Frank */
import { isFunction } from "./isFunction.js";
const CHUNK_SIZE = 65536;
async function* clonePart(part) {
const end = part.byteOffset + part.byteLength;
let position = part.byteOffset;
while (position !== end) {
const size = Math.min(end - position, CHUNK_SIZE);
const chunk = part.buffer.slice(position, position + size);
position += chunk.byteLength;
yield new Uint8Array(chunk);
}
}
async function* consumeNodeBlob(blob) {
let position = 0;
while (position !== blob.size) {
const chunk = blob.slice(position, Math.min(blob.size, position + CHUNK_SIZE));
const buffer = await chunk.arrayBuffer();
position += buffer.byteLength;
yield new Uint8Array(buffer);
}
}
export async function* consumeBlobParts(parts, clone = false) {
for (const part of parts) {
if (ArrayBuffer.isView(part)) {
if (clone) {
yield* clonePart(part);
}
else {
yield part;
}
}
else if (isFunction(part.stream)) {
yield* part.stream();
}
else {
yield* consumeNodeBlob(part);
}
}
}
export function* sliceBlob(blobParts, blobSize, start = 0, end) {
end !== null && end !== void 0 ? end : (end = blobSize);
let relativeStart = start < 0
? Math.max(blobSize + start, 0)
: Math.min(start, blobSize);
let relativeEnd = end < 0
? Math.max(blobSize + end, 0)
: Math.min(end, blobSize);
const span = Math.max(relativeEnd - relativeStart, 0);
let added = 0;
for (const part of blobParts) {
if (added >= span) {
break;
}
const partSize = ArrayBuffer.isView(part) ? part.byteLength : part.size;
if (relativeStart && partSize <= relativeStart) {
relativeStart -= partSize;
relativeEnd -= partSize;
}
else {
let chunk;
if (ArrayBuffer.isView(part)) {
chunk = part.subarray(relativeStart, Math.min(partSize, relativeEnd));
added += chunk.byteLength;
}
else {
chunk = part.slice(relativeStart, Math.min(partSize, relativeEnd));
added += chunk.size;
}
relativeEnd -= partSize;
relativeStart = 0;
yield chunk;
}
}
}

10
node_modules/formdata-node/lib/esm/browser.js generated vendored Normal file
View File

@@ -0,0 +1,10 @@
const globalObject = (function () {
if (typeof globalThis !== "undefined") {
return globalThis;
}
if (typeof self !== "undefined") {
return self;
}
return window;
}());
export const { FormData, Blob, File } = globalObject;

View File

@@ -0,0 +1,3 @@
import { deprecate } from "util";
export const deprecateConstructorEntries = deprecate(() => { }, "Constructor \"entries\" argument is not spec-compliant "
+ "and will be removed in next major release.");

79
node_modules/formdata-node/lib/esm/fileFromPath.js generated vendored Normal file
View File

@@ -0,0 +1,79 @@
var __classPrivateFieldSet = (this && this.__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;
};
var __classPrivateFieldGet = (this && this.__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);
};
var _FileFromPath_path, _FileFromPath_start;
import { statSync, createReadStream, promises as fs } from "fs";
import { basename } from "path";
import DOMException from "node-domexception";
import { File } from "./File.js";
import isPlainObject from "./isPlainObject.js";
export * from "./isFile.js";
const MESSAGE = "The requested file could not be read, "
+ "typically due to permission problems that have occurred after a reference "
+ "to a file was acquired.";
class FileFromPath {
constructor(input) {
_FileFromPath_path.set(this, void 0);
_FileFromPath_start.set(this, void 0);
__classPrivateFieldSet(this, _FileFromPath_path, input.path, "f");
__classPrivateFieldSet(this, _FileFromPath_start, input.start || 0, "f");
this.name = basename(__classPrivateFieldGet(this, _FileFromPath_path, "f"));
this.size = input.size;
this.lastModified = input.lastModified;
}
slice(start, end) {
return new FileFromPath({
path: __classPrivateFieldGet(this, _FileFromPath_path, "f"),
lastModified: this.lastModified,
size: end - start,
start
});
}
async *stream() {
const { mtimeMs } = await fs.stat(__classPrivateFieldGet(this, _FileFromPath_path, "f"));
if (mtimeMs > this.lastModified) {
throw new DOMException(MESSAGE, "NotReadableError");
}
if (this.size) {
yield* createReadStream(__classPrivateFieldGet(this, _FileFromPath_path, "f"), {
start: __classPrivateFieldGet(this, _FileFromPath_start, "f"),
end: __classPrivateFieldGet(this, _FileFromPath_start, "f") + this.size - 1
});
}
}
get [(_FileFromPath_path = new WeakMap(), _FileFromPath_start = new WeakMap(), Symbol.toStringTag)]() {
return "File";
}
}
function createFileFromPath(path, { mtimeMs, size }, filenameOrOptions, options = {}) {
let filename;
if (isPlainObject(filenameOrOptions)) {
[options, filename] = [filenameOrOptions, undefined];
}
else {
filename = filenameOrOptions;
}
const file = new FileFromPath({ path, size, lastModified: mtimeMs });
if (!filename) {
filename = file.name;
}
return new File([file], filename, {
...options, lastModified: file.lastModified
});
}
export function fileFromPathSync(path, filenameOrOptions, options = {}) {
const stats = statSync(path);
return createFileFromPath(path, stats, filenameOrOptions, options);
}
export async function fileFromPath(path, filenameOrOptions, options) {
const stats = await fs.stat(path);
return createFileFromPath(path, stats, filenameOrOptions, options);
}

3
node_modules/formdata-node/lib/esm/index.js generated vendored Normal file
View File

@@ -0,0 +1,3 @@
export * from "./FormData.js";
export * from "./Blob.js";
export * from "./File.js";

2
node_modules/formdata-node/lib/esm/isBlob.js generated vendored Normal file
View File

@@ -0,0 +1,2 @@
import { Blob } from "./Blob.js";
export const isBlob = (value) => value instanceof Blob;

2
node_modules/formdata-node/lib/esm/isFile.js generated vendored Normal file
View File

@@ -0,0 +1,2 @@
import { File } from "./File.js";
export const isFile = (value) => value instanceof File;

1
node_modules/formdata-node/lib/esm/isFunction.js generated vendored Normal file
View File

@@ -0,0 +1 @@
export const isFunction = (value) => (typeof value === "function");

13
node_modules/formdata-node/lib/esm/isPlainObject.js generated vendored Normal file
View File

@@ -0,0 +1,13 @@
const getType = (value) => (Object.prototype.toString.call(value).slice(8, -1).toLowerCase());
function isPlainObject(value) {
if (getType(value) !== "object") {
return false;
}
const pp = Object.getPrototypeOf(value);
if (pp === null || pp === undefined) {
return true;
}
const Ctor = pp.constructor && pp.constructor.toString();
return Ctor === Object.toString();
}
export default isPlainObject;

3
node_modules/formdata-node/lib/esm/package.json generated vendored Normal file
View File

@@ -0,0 +1,3 @@
{
"type": "module"
}

View File

@@ -0,0 +1,5 @@
declare class DOMException {
constructor(message: string, name: string)
}
export default DOMException

21
node_modules/formdata-node/license generated vendored Normal file
View File

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

View File

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

View File

@@ -0,0 +1,135 @@
# web-streams-polyfill
Web Streams, based on the WHATWG spec reference implementation.
[![build status](https://api.travis-ci.com/MattiasBuelens/web-streams-polyfill.svg?branch=master)](https://travis-ci.com/MattiasBuelens/web-streams-polyfill)
[![npm version](https://img.shields.io/npm/v/web-streams-polyfill.svg)](https://www.npmjs.com/package/web-streams-polyfill)
[![license](https://img.shields.io/npm/l/web-streams-polyfill.svg)](https://github.com/MattiasBuelens/web-streams-polyfill/blob/master/LICENSE)
[![Join the chat at https://gitter.im/web-streams-polyfill/Lobby](https://badges.gitter.im/web-streams-polyfill/Lobby.svg)](https://gitter.im/web-streams-polyfill/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
## Links
- [Official spec][spec]
- [Reference implementation][ref-impl]
## Usage
This library comes in multiple variants:
* `web-streams-polyfill`: a [ponyfill] that provides the stream implementations
without replacing any globals, targeting ES2015+ environments.
* ✅ Node 6+ through `import` or `require()`
* ✅ Modern web browsers through `import`/`export` or `<script type="module">`
* ✅ Web apps for modern browsers using a bundler (like webpack or Rollup)
* `web-streams-polyfill/es5`: a ponyfill targeting ES5+ environments.
* ✅ Legacy Node through `require()`
* ✅ Legacy web browsers through [AMD][amd]
* ✅ Web apps for legacy browsers using a bundler (like webpack or Rollup)
* `web-streams-polyfill/polyfill`: a polyfill that replaces the native stream implementations,
targeting ES2015+ environments.
* ✅ Modern web browsers through regular `<script>`
* `web-streams-polyfill/polyfill/es5`: a polyfill targeting ES5+ environments.
* ✅ Legacy web browsers through regular `<script>`
Each variant also includes TypeScript type definitions, compatible with the DOM type definitions for streams included in TypeScript.
In version 4, the list of variants was reworked to have more modern defaults and to reduce the download size of the package.
See the [migration guide][migrating] for more information.
Usage as a polyfill:
```html
<!-- option 1: hosted by unpkg CDN -->
<script src="https://unpkg.com/web-streams-polyfill/dist/polyfill.js"></script>
<!-- option 2: self hosted -->
<script src="/path/to/web-streams-polyfill/dist/polyfill.js"></script>
<script>
var readable = new ReadableStream();
</script>
```
Usage as a Node module:
```js
var streams = require("web-streams-polyfill");
var readable = new streams.ReadableStream();
```
Usage as a ponyfill from within a ES2015 module:
```js
import { ReadableStream } from "web-streams-polyfill";
const readable = new ReadableStream();
```
Usage as a polyfill from within an ES2015 module:
```js
import "web-streams-polyfill/polyfill";
const readable = new ReadableStream();
```
## Compatibility
The default and `polyfill` variants work in any ES2015-compatible environment.
The `es5` and `polyfill/es5` variants work in any ES5-compatible environment that has a global `Promise`.
If you need to support older browsers or Node versions that do not have a native `Promise` implementation
(check the [support table][promise-support]), you must first include a `Promise` polyfill
(e.g. [promise-polyfill][promise-polyfill]).
[Async iterable support for `ReadableStream`][rs-asynciterator] is available in all variants, but requires an ES2018-compatible environment or a polyfill for `Symbol.asyncIterator`.
[`WritableStreamDefaultController.signal`][ws-controller-signal] is available in all variants, but requires a global `AbortController` constructor. If necessary, consider using a polyfill such as [abortcontroller-polyfill].
## Compliance
The polyfill implements [version `e9355ce` (18 Apr 2022)][spec-snapshot] of the streams specification.
The polyfill is tested against the same [web platform tests][wpt] that are used by browsers to test their native implementations.
It aims to pass all tests, although it allows some exceptions for practical reasons:
* The default (ES2015) variant passes all of the tests, except for:
* The ["bad buffers and views" tests for readable byte streams][wpt-bad-buffers].
These tests require the implementation to synchronously transfer the contents of an `ArrayBuffer`, which is not yet possible from JavaScript (although there is a [proposal][proposal-arraybuffer-transfer] to make it possible).
The reference implementation "cheats" on these tests [by making a copy instead][ref-impl-transferarraybuffer], but that is unacceptable for the polyfill's performance ([#3][issue-3]).
* The [test for the prototype of `ReadableStream`'s async iterator][wpt-async-iterator-prototype].
Retrieving the correct `%AsyncIteratorPrototype%` requires using an async generator (`async function* () {}`), which is invalid syntax before ES2018.
Instead, the polyfill [creates its own version][stub-async-iterator-prototype] which is functionally equivalent to the real prototype.
* The tests [with patched globals][wpt-rs-patched-global] and [with `Object.prototype.then`][wpt-then-interception].
These tests are meant for browsers to ensure user-land modifications cannot affect the internal logic of `pipeTo()` and `tee()`.
However, it's not reasonable or desirable for a user-land polyfill to try and isolate itself completely from using the global `Object`.
* Certain `pipeTo()` tests that require synchronous inspection of the stream's state ([1][wpt-pipe-sync-state-1], [2][wpt-pipe-sync-state-2]).
Because the polyfill uses the public `getReader()` and `getWriter()` API to implement `pipeTo()`, it can only *asynchronously* observe if and when a stream becomes closed or errored.
Therefore, when the readable and the writable end become errored *at the exact same time*, it's difficult for the polyfill to observe these state changes in exactly the same order.
* The ES5 variant passes the same tests as the ES2015 variant, except for various tests about specific characteristics of the constructors, properties and methods.
These test failures do not affect the run-time behavior of the polyfill.
For example:
* The `name` property of down-leveled constructors is incorrect.
* The `length` property of down-leveled constructors and methods with optional arguments is incorrect.
* Not all properties and methods are correctly marked as non-enumerable.
* Down-leveled class methods are not correctly marked as non-constructable.
The type definitions are compatible with the built-in stream types of TypeScript 3.3 and higher.
## Contributors
Thanks to these people for their work on [the original polyfill][creatorrr-polyfill]:
- Diwank Singh Tomer ([creatorrr](https://github.com/creatorrr))
- Anders Riutta ([ariutta](https://github.com/ariutta))
[spec]: https://streams.spec.whatwg.org
[ref-impl]: https://github.com/whatwg/streams
[ponyfill]: https://github.com/sindresorhus/ponyfill
[amd]: https://requirejs.org/docs/whyamd.html
[migrating]: https://github.com/MattiasBuelens/web-streams-polyfill/blob/v4.0.0-beta.3/MIGRATING.md
[promise-support]: https://kangax.github.io/compat-table/es6/#test-Promise
[promise-polyfill]: https://www.npmjs.com/package/promise-polyfill
[rs-asynciterator]: https://streams.spec.whatwg.org/#rs-asynciterator
[ws-controller-signal]: https://streams.spec.whatwg.org/#ws-default-controller-signal
[abortcontroller-polyfill]: https://www.npmjs.com/package/abortcontroller-polyfill
[spec-snapshot]: https://streams.spec.whatwg.org/commit-snapshots/e9355ce79925947e8eb496563d599c329769d315/
[wpt]: https://github.com/web-platform-tests/wpt/tree/6a46d9cb8d20c510a620141c721b81b460a4ee55/streams
[wpt-bad-buffers]: https://github.com/web-platform-tests/wpt/blob/6a46d9cb8d20c510a620141c721b81b460a4ee55/streams/readable-byte-streams/bad-buffers-and-views.any.js
[proposal-arraybuffer-transfer]: https://github.com/domenic/proposal-arraybuffer-transfer
[ref-impl-transferarraybuffer]: https://github.com/whatwg/streams/blob/e9355ce79925947e8eb496563d599c329769d315/reference-implementation/lib/abstract-ops/ecmascript.js#L16
[issue-3]: https://github.com/MattiasBuelens/web-streams-polyfill/issues/3
[wpt-async-iterator-prototype]: https://github.com/web-platform-tests/wpt/blob/6a46d9cb8d20c510a620141c721b81b460a4ee55/streams/readable-streams/async-iterator.any.js#L24
[stub-async-iterator-prototype]: https://github.com/MattiasBuelens/web-streams-polyfill/blob/v4.0.0-beta.3/src/lib/readable-stream/async-iterator.ts#L126-L134
[wpt-rs-patched-global]: https://github.com/web-platform-tests/wpt/blob/887350c2f46def5b01c4dd1f8d2eee35dfb9c5bb/streams/readable-streams/patched-global.any.js
[wpt-then-interception]: https://github.com/web-platform-tests/wpt/blob/cf33f00596af295ee0f207c88e23b5f8b0791307/streams/piping/then-interception.any.js
[wpt-pipe-sync-state-1]: https://github.com/web-platform-tests/wpt/blob/e1e713c842e54ea0a9410ddc988b63d0e1d31973/streams/piping/multiple-propagation.any.js#L30-L53
[wpt-pipe-sync-state-2]: https://github.com/web-platform-tests/wpt/blob/e1e713c842e54ea0a9410ddc988b63d0e1d31973/streams/piping/multiple-propagation.any.js#L114-L138
[creatorrr-polyfill]: https://github.com/creatorrr/web-streams-polyfill

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,6 @@
{
"name": "web-streams-polyfill",
"main": "../dist/ponyfill.es5.js",
"module": "../dist/ponyfill.es5.mjs",
"types": "../types/ponyfill.d.ts"
}

View File

@@ -0,0 +1,101 @@
{
"name": "web-streams-polyfill",
"version": "4.0.0-beta.3",
"description": "Web Streams, based on the WHATWG spec reference implementation",
"main": "dist/ponyfill.js",
"module": "dist/ponyfill.mjs",
"types": "types/ponyfill.d.ts",
"exports": {
".": {
"types": "./types/ponyfill.d.ts",
"import": "./dist/ponyfill.mjs",
"require": "./dist/ponyfill.js"
},
"./es5": {
"types": "./types/ponyfill.d.ts",
"import": "./dist/ponyfill.es5.mjs",
"require": "./dist/ponyfill.es5.js"
},
"./polyfill": {
"types": "./types/polyfill.d.ts",
"default": "./dist/polyfill.js"
},
"./polyfill/es5": {
"types": "./types/polyfill.d.ts",
"default": "./dist/polyfill.es5.js"
},
"./dist/*": "./dist/*",
"./types/*": "./types/*",
"./package": "./package.json",
"./package.json": "./package.json"
},
"scripts": {
"test": "npm run test:types && npm run test:unit && npm run test:wpt && npm run test:bundler",
"test:wpt": "npm run test:wpt:node && npm run test:wpt:chromium && npm run test:wpt:firefox",
"test:wpt:node": "node --expose_gc ./test/wpt/node/run.js",
"test:wpt:chromium": "node ./test/wpt/browser/run.js --browser chromium",
"test:wpt:firefox": "node ./test/wpt/browser/run.js --browser firefox",
"test:bundler": "npm run test:bundler:rollup && npm run test:bundler:webpack",
"test:bundler:rollup": "cd test/rollup && npm ci && npm test",
"test:bundler:webpack": "cd test/webpack && npm ci && npm test",
"test:types": "tsc -p ./test/types/tsconfig.json",
"test:unit": "node --experimental-import-meta-resolve ./node_modules/jasmine/bin/jasmine.js --config=test/unit/jasmine.json",
"lint": "eslint \"src/**/*.ts\"",
"build": "npm run build:bundle && npm run build:types",
"build:bundle": "rollup -c",
"build:types": "tsc --project . --emitDeclarationOnly --declarationDir ./lib && api-extractor run",
"accept:types": "tsc --project . --emitDeclarationOnly --declarationDir ./lib && api-extractor run --local",
"prepare": "npm run build"
},
"files": [
"dist",
"es5",
"polyfill",
"types"
],
"engines": {
"node": ">= 14"
},
"repository": {
"type": "git",
"url": "git+https://github.com/MattiasBuelens/web-streams-polyfill.git"
},
"keywords": [
"streams",
"whatwg",
"polyfill"
],
"author": "Mattias Buelens <mattias@buelens.com>",
"contributors": [
"Diwank Singh <diwank.singh@gmail.com>"
],
"license": "MIT",
"bugs": {
"url": "https://github.com/MattiasBuelens/web-streams-polyfill/issues"
},
"homepage": "https://github.com/MattiasBuelens/web-streams-polyfill#readme",
"devDependencies": {
"@microsoft/api-extractor": "^7.21.2",
"@rollup/plugin-inject": "^4.0.4",
"@rollup/plugin-replace": "^4.0.0",
"@rollup/plugin-strip": "^2.1.0",
"@rollup/plugin-typescript": "^8.3.1",
"@types/jasmine": "^4.0.2",
"@types/node": "^14.18.12",
"@typescript-eslint/eslint-plugin": "^5.19.0",
"@typescript-eslint/parser": "^5.19.0",
"@ungap/promise-all-settled": "^1.1.2",
"abort-controller": "^3.0.0",
"eslint": "^8.13.0",
"jasmine": "^4.0.2",
"micromatch": "^4.0.5",
"minimist": "^1.2.6",
"playwright": "^1.20.2",
"recursive-readdir": "^2.2.2",
"rollup": "^2.70.1",
"rollup-plugin-terser": "^7.0.2",
"tslib": "^2.3.1",
"typescript": "^4.7.0-beta",
"wpt-runner": "^4.1.0"
}
}

View File

@@ -0,0 +1,5 @@
{
"name": "web-streams-polyfill",
"main": "../../dist/polyfill.es5.js",
"types": "../../types/polyfill.d.ts"
}

View File

@@ -0,0 +1,5 @@
{
"name": "web-streams-polyfill",
"main": "../dist/polyfill.js",
"types": "../types/polyfill.d.ts"
}

View File

@@ -0,0 +1,62 @@
/// <reference lib="dom" />
/// <reference lib="es2018.asynciterable" />
import type {
ReadableStreamAsyncIterator,
ReadableStreamBYOBReader,
ReadableStreamBYOBReadResult,
ReadableStreamIteratorOptions
} from './ponyfill';
export type {
ReadableStreamAsyncIterator,
ReadableStreamBYOBReader,
ReadableStreamBYOBReadResult,
ReadableStreamIteratorOptions
};
declare global {
interface ReadableStream<R = any> {
/**
* Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.
*
* This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,
* i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading.
* The returned BYOB reader provides the ability to directly read individual chunks from the stream via its
* {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise
* control over allocation.
*/
getReader({ mode }: {
mode: 'byob';
}): ReadableStreamBYOBReader;
/**
* Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.
* While the stream is locked, no other reader can be acquired until this one is released.
*
* This functionality is especially useful for creating abstractions that desire the ability to consume a stream
* in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours
* or cancel the stream, which would interfere with your abstraction.
*/
getReader(): ReadableStreamDefaultReader<R>;
/**
* Asynchronously iterates over the chunks in the stream's internal queue.
*
* Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.
* The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method
* is called, e.g. by breaking out of the loop.
*
* By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also
* cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing
* `true` for the `preventCancel` option.
*/
values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator<R>;
/**
* {@inheritDoc ReadableStream.values}
*/
[Symbol.asyncIterator]: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator<R>;
}
}

View File

@@ -0,0 +1,775 @@
/// <reference lib="es2018.asynciterable" />
/**
* A signal object that allows you to communicate with a request and abort it if required
* via its associated `AbortController` object.
*
* @remarks
* This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.
* It is redefined here, so it can be polyfilled without a DOM, for example with
* {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.
*
* @public
*/
export declare interface AbortSignal {
/**
* Whether the request is aborted.
*/
readonly aborted: boolean;
/**
* The abort reason.
*/
readonly reason?: any;
/**
* Add an event listener to be triggered when this signal becomes aborted.
*/
addEventListener(type: 'abort', listener: () => void): void;
/**
* Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.
*/
removeEventListener(type: 'abort', listener: () => void): void;
}
/**
* A queuing strategy that counts the number of bytes in each chunk.
*
* @public
*/
export declare class ByteLengthQueuingStrategy implements QueuingStrategy<ArrayBufferView> {
constructor(options: QueuingStrategyInit);
/**
* Returns the high water mark provided to the constructor.
*/
get highWaterMark(): number;
/**
* Measures the size of `chunk` by returning the value of its `byteLength` property.
*/
get size(): (chunk: ArrayBufferView) => number;
}
/**
* A queuing strategy that counts the number of chunks.
*
* @public
*/
export declare class CountQueuingStrategy implements QueuingStrategy<any> {
constructor(options: QueuingStrategyInit);
/**
* Returns the high water mark provided to the constructor.
*/
get highWaterMark(): number;
/**
* Measures the size of `chunk` by always returning 1.
* This ensures that the total queue size is a count of the number of chunks in the queue.
*/
get size(): (chunk: any) => 1;
}
/**
* A queuing strategy.
*
* @public
*/
export declare interface QueuingStrategy<T = any> {
/**
* A non-negative number indicating the high water mark of the stream using this queuing strategy.
*/
highWaterMark?: number;
/**
* A function that computes and returns the finite non-negative size of the given chunk value.
*/
size?: QueuingStrategySizeCallback<T>;
}
/**
* @public
*/
export declare interface QueuingStrategyInit {
/**
* {@inheritDoc QueuingStrategy.highWaterMark}
*/
highWaterMark: number;
}
/**
* {@inheritDoc QueuingStrategy.size}
* @public
*/
export declare type QueuingStrategySizeCallback<T = any> = (chunk: T) => number;
/**
* Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.
*
* @public
*/
export declare class ReadableByteStreamController {
private constructor();
/**
* Returns the current BYOB pull request, or `null` if there isn't one.
*/
get byobRequest(): ReadableStreamBYOBRequest | null;
/**
* Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is
* over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.
*/
get desiredSize(): number | null;
/**
* Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from
* the stream, but once those are read, the stream will become closed.
*/
close(): void;
/**
* Enqueues the given chunk chunk in the controlled readable stream.
* The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.
*/
enqueue(chunk: ArrayBufferView): void;
/**
* Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.
*/
error(e?: any): void;
}
/**
* A readable stream represents a source of data, from which you can read.
*
* @public
*/
export declare class ReadableStream<R = any> {
constructor(underlyingSource: UnderlyingByteSource, strategy?: {
highWaterMark?: number;
size?: undefined;
});
constructor(underlyingSource?: UnderlyingSource<R>, strategy?: QueuingStrategy<R>);
/**
* Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.
*/
get locked(): boolean;
/**
* Cancels the stream, signaling a loss of interest in the stream by a consumer.
*
* The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}
* method, which might or might not use it.
*/
cancel(reason?: any): Promise<void>;
/**
* Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.
*
* This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,
* i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading.
* The returned BYOB reader provides the ability to directly read individual chunks from the stream via its
* {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise
* control over allocation.
*/
getReader({ mode }: {
mode: 'byob';
}): ReadableStreamBYOBReader;
/**
* Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.
* While the stream is locked, no other reader can be acquired until this one is released.
*
* This functionality is especially useful for creating abstractions that desire the ability to consume a stream
* in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours
* or cancel the stream, which would interfere with your abstraction.
*/
getReader(): ReadableStreamDefaultReader<R>;
/**
* Provides a convenient, chainable way of piping this readable stream through a transform stream
* (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream
* into the writable side of the supplied pair, and returns the readable side for further use.
*
* Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.
*/
pipeThrough<RS extends ReadableStream>(transform: {
readable: RS;
writable: WritableStream<R>;
}, options?: StreamPipeOptions): RS;
/**
* Pipes this readable stream to a given writable stream. The way in which the piping process behaves under
* various error conditions can be customized with a number of passed options. It returns a promise that fulfills
* when the piping process completes successfully, or rejects if any errors were encountered.
*
* Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.
*/
pipeTo(destination: WritableStream<R>, options?: StreamPipeOptions): Promise<void>;
/**
* Tees this readable stream, returning a two-element array containing the two resulting branches as
* new {@link ReadableStream} instances.
*
* Teeing a stream will lock it, preventing any other consumer from acquiring a reader.
* To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be
* propagated to the stream's underlying source.
*
* Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,
* this could allow interference between the two branches.
*/
tee(): [ReadableStream<R>, ReadableStream<R>];
/**
* Asynchronously iterates over the chunks in the stream's internal queue.
*
* Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.
* The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method
* is called, e.g. by breaking out of the loop.
*
* By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also
* cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing
* `true` for the `preventCancel` option.
*/
values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator<R>;
/**
* {@inheritDoc ReadableStream.values}
*/
[Symbol.asyncIterator]: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator<R>;
}
/**
* An async iterator returned by {@link ReadableStream.values}.
*
* @public
*/
export declare interface ReadableStreamAsyncIterator<R> extends AsyncIterator<R> {
next(): Promise<IteratorResult<R, undefined>>;
return(value?: any): Promise<IteratorResult<any>>;
}
/**
* A BYOB reader vended by a {@link ReadableStream}.
*
* @public
*/
export declare class ReadableStreamBYOBReader {
constructor(stream: ReadableStream<Uint8Array>);
/**
* Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or
* the reader's lock is released before the stream finishes closing.
*/
get closed(): Promise<undefined>;
/**
* If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.
*/
cancel(reason?: any): Promise<void>;
/**
* Attempts to reads bytes into view, and returns a promise resolved with the result.
*
* If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.
*/
read<T extends ArrayBufferView>(view: T): Promise<ReadableStreamBYOBReadResult<T>>;
/**
* Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.
* If the associated stream is errored when the lock is released, the reader will appear errored in the same way
* from now on; otherwise, the reader will appear closed.
*
* A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by
* the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to
* do so will throw a `TypeError` and leave the reader locked to the stream.
*/
releaseLock(): void;
}
/**
* A result returned by {@link ReadableStreamBYOBReader.read}.
*
* @public
*/
export declare type ReadableStreamBYOBReadResult<T extends ArrayBufferView> = {
done: false;
value: T;
} | {
done: true;
value: T | undefined;
};
/**
* A pull-into request in a {@link ReadableByteStreamController}.
*
* @public
*/
export declare class ReadableStreamBYOBRequest {
private constructor();
/**
* Returns the view for writing in to, or `null` if the BYOB request has already been responded to.
*/
get view(): ArrayBufferView | null;
/**
* Indicates to the associated readable byte stream that `bytesWritten` bytes were written into
* {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.
*
* After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer
* modifiable.
*/
respond(bytesWritten: number): void;
/**
* Indicates to the associated readable byte stream that instead of writing into
* {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,
* which will be given to the consumer of the readable byte stream.
*
* After this method is called, `view` will be transferred and no longer modifiable.
*/
respondWithNewView(view: ArrayBufferView): void;
}
/**
* Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.
*
* @public
*/
export declare class ReadableStreamDefaultController<R> {
private constructor();
/**
* Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is
* over-full. An underlying source ought to use this information to determine when and how to apply backpressure.
*/
get desiredSize(): number | null;
/**
* Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from
* the stream, but once those are read, the stream will become closed.
*/
close(): void;
/**
* Enqueues the given chunk `chunk` in the controlled readable stream.
*/
enqueue(chunk: R): void;
/**
* Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.
*/
error(e?: any): void;
}
/**
* A default reader vended by a {@link ReadableStream}.
*
* @public
*/
export declare class ReadableStreamDefaultReader<R = any> {
constructor(stream: ReadableStream<R>);
/**
* Returns a promise that will be fulfilled when the stream becomes closed,
* or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.
*/
get closed(): Promise<undefined>;
/**
* If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.
*/
cancel(reason?: any): Promise<void>;
/**
* Returns a promise that allows access to the next chunk from the stream's internal queue, if available.
*
* If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.
*/
read(): Promise<ReadableStreamDefaultReadResult<R>>;
/**
* Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.
* If the associated stream is errored when the lock is released, the reader will appear errored in the same way
* from now on; otherwise, the reader will appear closed.
*
* A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by
* the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to
* do so will throw a `TypeError` and leave the reader locked to the stream.
*/
releaseLock(): void;
}
/**
* A result returned by {@link ReadableStreamDefaultReader.read}.
*
* @public
*/
export declare type ReadableStreamDefaultReadResult<T> = {
done: false;
value: T;
} | {
done: true;
value?: undefined;
};
/**
* Options for {@link ReadableStream.values | async iterating} a stream.
*
* @public
*/
export declare interface ReadableStreamIteratorOptions {
preventCancel?: boolean;
}
/**
* A pair of a {@link ReadableStream | readable stream} and {@link WritableStream | writable stream} that can be passed
* to {@link ReadableStream.pipeThrough}.
*
* @public
*/
export declare interface ReadableWritablePair<R, W> {
readable: ReadableStream<R>;
writable: WritableStream<W>;
}
/**
* Options for {@link ReadableStream.pipeTo | piping} a stream.
*
* @public
*/
export declare interface StreamPipeOptions {
/**
* If set to true, {@link ReadableStream.pipeTo} will not abort the writable stream if the readable stream errors.
*/
preventAbort?: boolean;
/**
* If set to true, {@link ReadableStream.pipeTo} will not cancel the readable stream if the writable stream closes
* or errors.
*/
preventCancel?: boolean;
/**
* If set to true, {@link ReadableStream.pipeTo} will not close the writable stream if the readable stream closes.
*/
preventClose?: boolean;
/**
* Can be set to an {@link AbortSignal} to allow aborting an ongoing pipe operation via the corresponding
* `AbortController`. In this case, the source readable stream will be canceled, and the destination writable stream
* aborted, unless the respective options `preventCancel` or `preventAbort` are set.
*/
signal?: AbortSignal;
}
/**
* A transformer for constructing a {@link TransformStream}.
*
* @public
*/
export declare interface Transformer<I = any, O = any> {
/**
* A function that is called immediately during creation of the {@link TransformStream}.
*/
start?: TransformerStartCallback<O>;
/**
* A function called when a new chunk originally written to the writable side is ready to be transformed.
*/
transform?: TransformerTransformCallback<I, O>;
/**
* A function called after all chunks written to the writable side have been transformed by successfully passing
* through {@link Transformer.transform | transform()}, and the writable side is about to be closed.
*/
flush?: TransformerFlushCallback<O>;
readableType?: undefined;
writableType?: undefined;
}
/** @public */
export declare type TransformerFlushCallback<O> = (controller: TransformStreamDefaultController<O>) => void | PromiseLike<void>;
/** @public */
export declare type TransformerStartCallback<O> = (controller: TransformStreamDefaultController<O>) => void | PromiseLike<void>;
/** @public */
export declare type TransformerTransformCallback<I, O> = (chunk: I, controller: TransformStreamDefaultController<O>) => void | PromiseLike<void>;
/**
* A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},
* known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.
* In a manner specific to the transform stream in question, writes to the writable side result in new data being
* made available for reading from the readable side.
*
* @public
*/
export declare class TransformStream<I = any, O = any> {
constructor(transformer?: Transformer<I, O>, writableStrategy?: QueuingStrategy<I>, readableStrategy?: QueuingStrategy<O>);
/**
* The readable side of the transform stream.
*/
get readable(): ReadableStream<O>;
/**
* The writable side of the transform stream.
*/
get writable(): WritableStream<I>;
}
/**
* Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.
*
* @public
*/
export declare class TransformStreamDefaultController<O> {
private constructor();
/**
* Returns the desired size to fill the readable sides internal queue. It can be negative, if the queue is over-full.
*/
get desiredSize(): number | null;
/**
* Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.
*/
enqueue(chunk: O): void;
/**
* Errors both the readable side and the writable side of the controlled transform stream, making all future
* interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.
*/
error(reason?: any): void;
/**
* Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the
* transformer only needs to consume a portion of the chunks written to the writable side.
*/
terminate(): void;
}
/**
* An underlying byte source for constructing a {@link ReadableStream}.
*
* @public
*/
export declare interface UnderlyingByteSource {
/**
* {@inheritDoc UnderlyingSource.start}
*/
start?: UnderlyingByteSourceStartCallback;
/**
* {@inheritDoc UnderlyingSource.pull}
*/
pull?: UnderlyingByteSourcePullCallback;
/**
* {@inheritDoc UnderlyingSource.cancel}
*/
cancel?: UnderlyingSourceCancelCallback;
/**
* Can be set to "bytes" to signal that the constructed {@link ReadableStream} is a readable byte stream.
* This ensures that the resulting {@link ReadableStream} will successfully be able to vend BYOB readers via its
* {@link ReadableStream.(getReader:1) | getReader()} method.
* It also affects the controller argument passed to the {@link UnderlyingByteSource.start | start()}
* and {@link UnderlyingByteSource.pull | pull()} methods.
*/
type: 'bytes';
/**
* Can be set to a positive integer to cause the implementation to automatically allocate buffers for the
* underlying source code to write into. In this case, when a consumer is using a default reader, the stream
* implementation will automatically allocate an ArrayBuffer of the given size, so that
* {@link ReadableByteStreamController.byobRequest | controller.byobRequest} is always present,
* as if the consumer was using a BYOB reader.
*/
autoAllocateChunkSize?: number;
}
/** @public */
export declare type UnderlyingByteSourcePullCallback = (controller: ReadableByteStreamController) => void | PromiseLike<void>;
/** @public */
export declare type UnderlyingByteSourceStartCallback = (controller: ReadableByteStreamController) => void | PromiseLike<void>;
/**
* An underlying sink for constructing a {@link WritableStream}.
*
* @public
*/
export declare interface UnderlyingSink<W = any> {
/**
* A function that is called immediately during creation of the {@link WritableStream}.
*/
start?: UnderlyingSinkStartCallback;
/**
* A function that is called when a new chunk of data is ready to be written to the underlying sink. The stream
* implementation guarantees that this function will be called only after previous writes have succeeded, and never
* before {@link UnderlyingSink.start | start()} has succeeded or after {@link UnderlyingSink.close | close()} or
* {@link UnderlyingSink.abort | abort()} have been called.
*
* This function is used to actually send the data to the resource presented by the underlying sink, for example by
* calling a lower-level API.
*/
write?: UnderlyingSinkWriteCallback<W>;
/**
* A function that is called after the producer signals, via
* {@link WritableStreamDefaultWriter.close | writer.close()}, that they are done writing chunks to the stream, and
* subsequently all queued-up writes have successfully completed.
*
* This function can perform any actions necessary to finalize or flush writes to the underlying sink, and release
* access to any held resources.
*/
close?: UnderlyingSinkCloseCallback;
/**
* A function that is called after the producer signals, via {@link WritableStream.abort | stream.abort()} or
* {@link WritableStreamDefaultWriter.abort | writer.abort()}, that they wish to abort the stream. It takes as its
* argument the same value as was passed to those methods by the producer.
*
* Writable streams can additionally be aborted under certain conditions during piping; see the definition of the
* {@link ReadableStream.pipeTo | pipeTo()} method for more details.
*
* This function can clean up any held resources, much like {@link UnderlyingSink.close | close()}, but perhaps with
* some custom handling.
*/
abort?: UnderlyingSinkAbortCallback;
type?: undefined;
}
/** @public */
export declare type UnderlyingSinkAbortCallback = (reason: any) => void | PromiseLike<void>;
/** @public */
export declare type UnderlyingSinkCloseCallback = () => void | PromiseLike<void>;
/** @public */
export declare type UnderlyingSinkStartCallback = (controller: WritableStreamDefaultController) => void | PromiseLike<void>;
/** @public */
export declare type UnderlyingSinkWriteCallback<W> = (chunk: W, controller: WritableStreamDefaultController) => void | PromiseLike<void>;
/**
* An underlying source for constructing a {@link ReadableStream}.
*
* @public
*/
export declare interface UnderlyingSource<R = any> {
/**
* A function that is called immediately during creation of the {@link ReadableStream}.
*/
start?: UnderlyingSourceStartCallback<R>;
/**
* A function that is called whenever the streams internal queue of chunks becomes not full,
* i.e. whenever the queues desired size becomes positive. Generally, it will be called repeatedly
* until the queue reaches its high water mark (i.e. until the desired size becomes non-positive).
*/
pull?: UnderlyingSourcePullCallback<R>;
/**
* A function that is called whenever the consumer cancels the stream, via
* {@link ReadableStream.cancel | stream.cancel()},
* {@link ReadableStreamDefaultReader.cancel | defaultReader.cancel()}, or
* {@link ReadableStreamBYOBReader.cancel | byobReader.cancel()}.
* It takes as its argument the same value as was passed to those methods by the consumer.
*/
cancel?: UnderlyingSourceCancelCallback;
type?: undefined;
}
/** @public */
export declare type UnderlyingSourceCancelCallback = (reason: any) => void | PromiseLike<void>;
/** @public */
export declare type UnderlyingSourcePullCallback<R> = (controller: ReadableStreamDefaultController<R>) => void | PromiseLike<void>;
/** @public */
export declare type UnderlyingSourceStartCallback<R> = (controller: ReadableStreamDefaultController<R>) => void | PromiseLike<void>;
/**
* A writable stream represents a destination for data, into which you can write.
*
* @public
*/
export declare class WritableStream<W = any> {
constructor(underlyingSink?: UnderlyingSink<W>, strategy?: QueuingStrategy<W>);
/**
* Returns whether or not the writable stream is locked to a writer.
*/
get locked(): boolean;
/**
* Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be
* immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort
* mechanism of the underlying sink.
*
* The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled
* that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel
* the stream) if the stream is currently locked.
*/
abort(reason?: any): Promise<void>;
/**
* Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its
* close behavior. During this time any further attempts to write will fail (without erroring the stream).
*
* The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream
* successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with
* a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.
*/
close(): Promise<undefined>;
/**
* Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream
* is locked, no other writer can be acquired until this one is released.
*
* This functionality is especially useful for creating abstractions that desire the ability to write to a stream
* without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at
* the same time, which would cause the resulting written data to be unpredictable and probably useless.
*/
getWriter(): WritableStreamDefaultWriter<W>;
}
/**
* Allows control of a {@link WritableStream | writable stream}'s state and internal queue.
*
* @public
*/
export declare class WritableStreamDefaultController<W = any> {
private constructor();
/**
* The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.
*
* @deprecated
* This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.
* Use {@link WritableStreamDefaultController.signal}'s `reason` instead.
*/
get abortReason(): any;
/**
* An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.
*/
get signal(): AbortSignal;
/**
* Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.
*
* This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying
* sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the
* normal lifecycle of interactions with the underlying sink.
*/
error(e?: any): void;
}
/**
* A default writer vended by a {@link WritableStream}.
*
* @public
*/
export declare class WritableStreamDefaultWriter<W = any> {
constructor(stream: WritableStream<W>);
/**
* Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or
* the writers lock is released before the stream finishes closing.
*/
get closed(): Promise<undefined>;
/**
* Returns the desired size to fill the streams internal queue. It can be negative, if the queue is over-full.
* A producer can use this information to determine the right amount of data to write.
*
* It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort
* queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when
* the writers lock is released.
*/
get desiredSize(): number | null;
/**
* Returns a promise that will be fulfilled when the desired size to fill the streams internal queue transitions
* from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips
* back to zero or below, the getter will return a new promise that stays pending until the next transition.
*
* If the stream becomes errored or aborted, or the writers lock is released, the returned promise will become
* rejected.
*/
get ready(): Promise<undefined>;
/**
* If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.
*/
abort(reason?: any): Promise<void>;
/**
* If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.
*/
close(): Promise<void>;
/**
* Releases the writers lock on the corresponding stream. After the lock is released, the writer is no longer active.
* If the associated stream is errored when the lock is released, the writer will appear errored in the same way from
* now on; otherwise, the writer will appear closed.
*
* Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the
* promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).
* Its not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents
* other producers from writing in an interleaved manner.
*/
releaseLock(): void;
/**
* Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,
* and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return
* a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes
* errored before the writing process is initiated.
*
* Note that what "success" means is up to the underlying sink; it might indicate simply that the chunk has been
* accepted, and not necessarily that it is safely saved to its ultimate destination.
*/
write(chunk: W): Promise<void>;
}
export { }

View File

@@ -0,0 +1,11 @@
// This file is read by tools that parse documentation comments conforming to the TSDoc standard.
// It should be published with your NPM package. It should not be tracked by Git.
{
"tsdocVersion": "0.12",
"toolPackages": [
{
"packageName": "@microsoft/api-extractor",
"packageVersion": "7.21.2"
}
]
}

94
node_modules/formdata-node/package.json generated vendored Normal file
View File

@@ -0,0 +1,94 @@
{
"name": "formdata-node",
"version": "4.4.1",
"description": "Spec-compliant FormData implementation for Node.js",
"repository": "octet-stream/form-data",
"sideEffects": false,
"keywords": [
"form-data",
"node",
"form",
"upload",
"files-upload",
"ponyfill"
],
"author": "Nick K. <io@octetstream.me>",
"license": "MIT",
"main": "./lib/cjs/index.js",
"module": "./lib/esm/browser.js",
"browser": "./lib/cjs/browser.js",
"exports": {
"./package.json": "./package.json",
".": {
"node": {
"types": "./@type/index.d.ts",
"import": "./lib/esm/index.js",
"require": "./lib/cjs/index.js"
},
"browser": {
"types": "./@type/browser.d.ts",
"import": "./lib/esm/browser.js",
"require": "./lib/cjs/browser.js"
},
"default": "./lib/esm/index.js"
},
"./file-from-path": {
"types": "./@type/fileFromPath.d.ts",
"import": "./lib/esm/fileFromPath.js",
"require": "./lib/cjs/fileFromPath.js"
}
},
"types": "./@type/index.d.ts",
"typesVersions": {
"*": {
"file-from-path": [
"@type/fileFromPath.d.ts"
]
}
},
"engines": {
"node": ">= 12.20"
},
"scripts": {
"eslint": "eslint lib/**/*.ts",
"staged": "lint-staged",
"coverage": "c8 npm test",
"report:html": "c8 -r=html npm test",
"ci": "c8 npm test && c8 report --reporter=json",
"build:esm": "ttsc --project tsconfig.esm.json",
"build:cjs": "ttsc --project tsconfig.cjs.json",
"build:types": "ttsc --project tsconfig.d.ts.json",
"build": "npm run build:esm && npm run build:cjs && npm run build:types",
"test": "ava --fail-fast",
"cleanup": "npx rimraf @type \"lib/**/*.js\"",
"prepare": "npm run cleanup && npm run build",
"husky": "husky install"
},
"devDependencies": {
"@octetstream/eslint-config": "5.0.0",
"@types/node": "17.0.19",
"@types/sinon": "10.0.11",
"@typescript-eslint/eslint-plugin": "4.32.0",
"@typescript-eslint/parser": "4.32.0",
"@zoltu/typescript-transformer-append-js-extension": "1.0.1",
"ava": "4.0.1",
"c8": "7.12.0",
"eslint": "7.32.0",
"eslint-config-airbnb-typescript": "12.3.1",
"eslint-import-resolver-typescript": "2.5.0",
"eslint-plugin-ava": "12.0.0",
"eslint-plugin-jsx-a11y": "6.4.1",
"eslint-plugin-react": "7.26.1",
"husky": "7.0.4",
"lint-staged": "12.3.4",
"rimraf": "^3.0.2",
"sinon": "13.0.1",
"ts-node": "10.5.0",
"ttypescript": "1.5.13",
"typescript": "4.5.5"
},
"dependencies": {
"node-domexception": "1.0.0",
"web-streams-polyfill": "4.0.0-beta.3"
}
}

444
node_modules/formdata-node/readme.md generated vendored Normal file
View File

@@ -0,0 +1,444 @@
# FormData
Spec-compliant [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) implementation for Node.js
[![Code Coverage](https://codecov.io/github/octet-stream/form-data/coverage.svg?branch=master)](https://codecov.io/github/octet-stream/form-data?branch=master)
[![CI](https://github.com/octet-stream/form-data/workflows/CI/badge.svg)](https://github.com/octet-stream/form-data/actions/workflows/ci.yml)
[![ESLint](https://github.com/octet-stream/form-data/workflows/ESLint/badge.svg)](https://github.com/octet-stream/form-data/actions/workflows/eslint.yml)
## Highlights
1. Spec-compliant: implements every method of the [`FormData interface`](https://developer.mozilla.org/en-US/docs/Web/API/FormData).
2. Supports Blobs and Files sourced from anywhere: you can use builtin [`fileFromPath`](#filefrompathpath-filename-options---promisefile) and [`fileFromPathSync`](#filefrompathsyncpath-filename-options---file) helpers to create a File from FS, or you can implement your `BlobDataItem` object to use a different source of data.
3. Supports both ESM and CJS targets. See [`ESM/CJS support`](#esmcjs-support) section for details.
4. Written on TypeScript and ships with TS typings.
5. Isomorphic, but only re-exports native FormData object for browsers. If you need a polyfill for browsers, use [`formdata-polyfill`](https://github.com/jimmywarting/FormData)
6. It's a [`ponyfill`](https://ponyfill.com/)! Which means, no effect has been caused on `globalThis` or native `FormData` implementation.
## Installation
You can install this package with npm:
```
npm install formdata-node
```
Or yarn:
```
yarn add formdata-node
```
Or pnpm
```
pnpm add formdata-node
```
## ESM/CJS support
This package is targeting ESM and CJS for backwards compatibility reasons and smoothen transition period while you convert your projects to ESM only. Note that CJS support will be removed as [Node.js v12 will reach its EOL](https://github.com/nodejs/release#release-schedule). This change will be released as major version update, so you won't miss it.
## Usage
1. Let's take a look at minimal example with [got](https://github.com/sindresorhus/got):
```js
import {FormData} from "formdata-node"
// I assume Got >= 12.x is used for this example
import got from "got"
const form = new FormData()
form.set("greeting", "Hello, World!")
const data = await got.post("https://httpbin.org/post", {body: form}).json()
console.log(data.form.greeting) // => Hello, World!
```
2. If your HTTP client does not support spec-compliant FormData, you can use [`form-data-encoder`](https://github.com/octet-stream/form-data-encoder) to encode entries:
```js
import {Readable} from "stream"
import {FormDataEncoder} from "form-data-encoder"
import {FormData} from "formdata-node"
// Note that `node-fetch` >= 3.x have builtin support for spec-compliant FormData, sou you'll only need the `form-data-encoder` if you use `node-fetch` <= 2.x.
import fetch from "node-fetch"
const form = new FormData()
form.set("field", "Some value")
const encoder = new FormDataEncoder(form)
const options = {
method: "post",
headers: encoder.headers,
body: Readable.from(encoder)
}
await fetch("https://httpbin.org/post", options)
```
3. Sending files over form-data:
```js
import {FormData, File} from "formdata-node" // You can use `File` from fetch-blob >= 3.x
import fetch from "node-fetch"
const form = new FormData()
const file = new File(["My hovercraft is full of eels"], "file.txt")
form.set("file", file)
await fetch("https://httpbin.org/post", {method: "post", body: form})
```
4. Blobs as field's values allowed too:
```js
import {FormData, Blob} from "formdata-node" // You can use `Blob` from fetch-blob
const form = new FormData()
const blob = new Blob(["Some content"], {type: "text/plain"})
form.set("blob", blob)
// Will always be returned as `File`
let file = form.get("blob")
// The created file has "blob" as the name by default
console.log(file.name) // -> blob
// To change that, you need to set filename argument manually
form.set("file", blob, "some-file.txt")
file = form.get("file")
console.log(file.name) // -> some-file.txt
```
5. You can also append files using `fileFromPath` or `fileFromPathSync` helpers. It does the same thing as [`fetch-blob/from`](https://github.com/node-fetch/fetch-blob#blob-part-backed-up-by-filesystem), but returns a `File` instead of `Blob`:
```js
import {fileFromPath} from "formdata-node/file-from-path"
import {FormData} from "formdata-node"
import fetch from "node-fetch"
const form = new FormData()
form.set("file", await fileFromPath("/path/to/a/file"))
await fetch("https://httpbin.org/post", {method: "post", body: form})
```
6. You can still use files sourced from any stream, but unlike in v2 you'll need some extra work to achieve that:
```js
import {Readable} from "stream"
import {FormData} from "formdata-node"
class BlobFromStream {
#stream
constructor(stream, size) {
this.#stream = stream
this.size = size
}
stream() {
return this.#stream
}
get [Symbol.toStringTag]() {
return "Blob"
}
}
const content = Buffer.from("Stream content")
const stream = new Readable({
read() {
this.push(content)
this.push(null)
}
})
const form = new FormData()
form.set("stream", new BlobFromStream(stream, content.length), "file.txt")
await fetch("https://httpbin.org/post", {method: "post", body: form})
```
7. Note that if you don't know the length of that stream, you'll also need to handle form-data encoding manually or use [`form-data-encoder`](https://github.com/octet-stream/form-data-encoder) package. This is necessary to control which headers will be sent with your HTTP request:
```js
import {Readable} from "stream"
import {Encoder} from "form-data-encoder"
import {FormData} from "formdata-node"
const form = new FormData()
// You can use file-shaped or blob-shaped objects as FormData value instead of creating separate class
form.set("stream", {
type: "text/plain",
name: "file.txt",
[Symbol.toStringTag]: "File",
stream() {
return getStreamFromSomewhere()
}
})
const encoder = new Encoder(form)
const options = {
method: "post",
headers: {
"content-type": encoder.contentType
},
body: Readable.from(encoder)
}
await fetch("https://httpbin.org/post", {method: "post", body: form})
```
## Comparison
| | formdata-node | formdata-polyfill | undici FormData | form-data |
| ---------------- | ------------- | ----------------- | --------------- | -------------------- |
| .append() | ✔️ | ✔️ | ✔️ | ✔️<sup>1</sup> |
| .set() | ✔️ | ✔️ | ✔️ | ❌ |
| .get() | ✔️ | ✔️ | ✔️ | ❌ |
| .getAll() | ✔️ | ✔️ | ✔️ | ❌ |
| .forEach() | ✔️ | ✔️ | ✔️ | ❌ |
| .keys() | ✔️ | ✔️ | ✔️ | ❌ |
| .values() | ✔️ | ✔️ | ✔️ | ❌ |
| .entries() | ✔️ | ✔️ | ✔️ | ❌ |
| Symbol.iterator | ✔️ | ✔️ | ✔️ | ❌ |
| CommonJS | ✔️ | ❌ | ✔️ | ✔️ |
| ESM | ✔️ | ✔️ | ✔️<sup>2</sup> | ✔️<sup>2</sup> |
| Blob | ✔️<sup>3</sup> | ✔️<sup>4</sup> | ✔️<sup>3</sup> | ❌ |
| Browser polyfill | ❌ | ✔️ | ✔️ | ❌ |
| Builtin encoder | ❌ | ✔️ | ✔️<sup>5</sup> | ✔️ |
<sup>1</sup> Does not support Blob and File in entry value, but allows streams and Buffer (which is not spec-compiant, however).
<sup>2</sup> Can be imported in ESM, because Node.js support for CJS modules in ESM context, but it does not have ESM entry point.
<sup>3</sup> Have builtin implementations of Blob and/or File, allows native Blob and File as entry value.
<sup>4</sup> Support Blob and File via fetch-blob package, allows native Blob and File as entry value.
<sup>5</sup> Have `multipart/form-data` encoder as part of their `fetch` implementation.
✔️ - For FormData methods, indicates that the method is present and spec-compliant. For features, shows its presence.
❌ - Indicates that method or feature is not implemented.
## API
### `class FormData`
##### `constructor([entries]) -> {FormData}`
Creates a new FormData instance
- **{array}** [entries = null] an optional FormData initial entries.
Each initial field should be passed as a collection of the objects
with "name", "value" and "filename" props.
See the [FormData#append()](#appendname-value-filename---void) for more info about the available format.
#### Instance methods
##### `set(name, value[, filename]) -> {void}`
Set a new value for an existing key inside **FormData**,
or add the new field if it does not already exist.
- **{string}** name The name of the field whose data is contained in `value`.
- **{unknown}** value The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob)
or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string.
- **{string}** [filename = undefined] The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename.
##### `append(name, value[, filename]) -> {void}`
Appends a new value onto an existing key inside a FormData object,
or adds the key if it does not already exist.
The difference between `set()` and `append()` is that if the specified key already exists, `set()` will overwrite all existing values with the new one, whereas `append()` will append the new value onto the end of the existing set of values.
- **{string}** name The name of the field whose data is contained in `value`.
- **{unknown}** value The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob)
or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string.
- **{string}** [filename = undefined] The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename.
##### `get(name) -> {FormDataValue}`
Returns the first value associated with a given key from within a `FormData` object.
If you expect multiple values and want all of them, use the `getAll()` method instead.
- **{string}** name A name of the value you want to retrieve.
##### `getAll(name) -> {Array<FormDataValue>}`
Returns all the values associated with a given key from within a `FormData` object.
- **{string}** name A name of the value you want to retrieve.
##### `has(name) -> {boolean}`
Returns a boolean stating whether a `FormData` object contains a certain key.
- **{string}** A string representing the name of the key you want to test for.
##### `delete(name) -> {void}`
Deletes a key and its value(s) from a `FormData` object.
- **{string}** name The name of the key you want to delete.
##### `forEach(callback[, thisArg]) -> {void}`
Executes a given **callback** for each field of the FormData instance
- **{function}** callback Function to execute for each element, taking three arguments:
+ **{FormDataValue}** value A value(s) of the current field.
+ **{string}** name Name of the current field.
+ **{FormData}** form The FormData instance that **forEach** is being applied to
- **{unknown}** [thisArg = null] Value to use as **this** context when executing the given **callback**
##### `keys() -> {Generator<string>}`
Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all keys contained in this `FormData` object.
Each key is a `string`.
##### `values() -> {Generator<FormDataValue>}`
Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all values contained in this object `FormData` object.
Each value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue).
##### `entries() -> {Generator<[string, FormDataValue]>}`
Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through key/value pairs contained in this `FormData` object.
The key of each pair is a string; the value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue).
##### `[Symbol.iterator]() -> {Generator<[string, FormDataValue]>}`
An alias for [`FormData#entries()`](#entries---iterator)
### `class Blob`
The `Blob` object represents a blob, which is a file-like object of immutable, raw data;
they can be read as text or binary data, or converted into a ReadableStream
so its methods can be used for processing the data.
##### `constructor(blobParts[, options]) -> {Blob}`
Creates a new `Blob` instance. The `Blob` constructor accepts following arguments:
- **{(ArrayBufferLike | ArrayBufferView | File | Blob | string)[]}** blobParts An `Array` strings, or [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), [`ArrayBufferView`](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView), [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) objects, or a mix of any of such objects, that will be put inside the [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob);
- **{object}** [options = {}] - An options object containing optional attributes for the file. Available options are as follows;
- **{string}** [options.type = ""] - Returns the media type ([`MIME`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types)) of the blob represented by a `Blob` object.
#### Instance properties
##### `type -> {string}`
Returns the [`MIME type`](https://developer.mozilla.org/en-US/docs/Glossary/MIME_type) of the [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File).
##### `size -> {number}`
Returns the size of the [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File) in bytes.
#### Instance methods
##### `slice([start, end, contentType]) -> {Blob}`
Creates and returns a new [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) object which contains data from a subset of the blob on which it's called.
- **{number}** [start = 0] An index into the `Blob` indicating the first byte to include in the new `Blob`. If you specify a negative value, it's treated as an offset from the end of the `Blob` toward the beginning. For example, -10 would be the 10th from last byte in the `Blob`. The default value is 0. If you specify a value for start that is larger than the size of the source `Blob`, the returned `Blob` has size 0 and contains no data.
- **{number}** [end = `blob`.size] An index into the `Blob` indicating the first byte that will *not* be included in the new `Blob` (i.e. the byte exactly at this index is not included). If you specify a negative value, it's treated as an offset from the end of the `Blob` toward the beginning. For example, -10 would be the 10th from last byte in the `Blob`. The default value is size.
- **{string}** [contentType = ""] The content type to assign to the new ``Blob``; this will be the value of its type property. The default value is an empty string.
##### `stream() -> {ReadableStream<Uint8Array>}`
Returns a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) which upon reading returns the data contained within the [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob).
##### `arrayBuffer() -> {Promise<ArrayBuffer>}`
Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with the contents of the blob as binary data contained in an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer).
##### `text() -> {Promise<string>}`
Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with a string containing the contents of the blob, interpreted as UTF-8.
### `class File extends Blob`
The `File` class provides information about files. The `File` class inherits `Blob`.
##### `constructor(fileBits, filename[, options]) -> {File}`
Creates a new `File` instance. The `File` constructor accepts following arguments:
- **{(ArrayBufferLike | ArrayBufferView | File | Blob | string)[]}** fileBits An `Array` strings, or [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), [`ArrayBufferView`](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView), [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) objects, or a mix of any of such objects, that will be put inside the [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File);
- **{string}** filename Representing the file name.
- **{object}** [options = {}] - An options object containing optional attributes for the file. Available options are as follows;
- **{number}** [options.lastModified = Date.now()] provides the last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date;
- **{string}** [options.type = ""] - Returns the media type ([`MIME`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types)) of the file represented by a `File` object.
### `fileFromPath(path[, filename, options]) -> {Promise<File>}`
Available from `formdata-node/file-from-path` subpath.
Creates a `File` referencing the one on a disk by given path.
- **{string}** path - Path to a file
- **{string}** [filename] - Optional name of the file. Will be passed as the second argument in `File` constructor. If not presented, the name will be taken from the file's path.
- **{object}** [options = {}] - Additional `File` options, except for `lastModified`.
- **{string}** [options.type = ""] - Returns the media type ([`MIME`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types)) of the file represented by a `File` object.
### `fileFromPathSync(path[, filename, options]) -> {File}`
Available from `formdata-node/file-from-path` subpath.
Creates a `File` referencing the one on a disk by given path. Synchronous version of the `fileFromPath`.
- **{string}** path - Path to a file
- **{string}** [filename] - Optional name of the file. Will be passed as the second argument in `File` constructor. If not presented, the name will be taken from the file's path.
- **{object}** [options = {}] - Additional `File` options, except for `lastModified`.
- **{string}** [options.type = ""] - Returns the media type ([`MIME`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types)) of the file represented by a `File` object.
### `isFile(value) -> {boolean}`
Available from `formdata-node/file-from-path` subpath.
Checks if given value is a File, Blob or file-look-a-like object.
- **{unknown}** value - A value to test
### Husky installation
This package is using `husky` to perform git hooks on developer's machine, so your changes might be verified before you push them to `GitHub`. If you want to install these hooks, run `npm run husky` command.
## Related links
- [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) documentation on MDN
- [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File) documentation on MDN
- [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) documentation on MDN
- [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue) documentation on MDN.
- [`formdata-polyfill`](https://github.com/jimmywarting/FormData) HTML5 `FormData` for Browsers & NodeJS.
- [`node-fetch`](https://github.com/node-fetch/node-fetch) a light-weight module that brings the Fetch API to Node.js
- [`fetch-blob`](https://github.com/node-fetch/fetch-blob) a Blob implementation on node.js, originally from `node-fetch`.
- [`form-data-encoder`](https://github.com/octet-stream/form-data-encoder) spec-compliant `multipart/form-data` encoder implementation.
- [`then-busboy`](https://github.com/octet-stream/then-busboy) a promise-based wrapper around Busboy. Process multipart/form-data content and returns it as a single object. Will be helpful to handle your data on the server-side applications.
- [`@octetstream/object-to-form-data`](https://github.com/octet-stream/object-to-form-data) converts JavaScript object to FormData.